lang
stringclasses 2
values | license
stringclasses 13
values | stderr
stringlengths 0
343
| commit
stringlengths 40
40
| returncode
int64 0
128
| repos
stringlengths 6
87.7k
| new_contents
stringlengths 0
6.23M
| new_file
stringlengths 3
311
| old_contents
stringlengths 0
6.23M
| message
stringlengths 6
9.1k
| old_file
stringlengths 3
311
| subject
stringlengths 0
4k
| git_diff
stringlengths 0
6.31M
|
---|---|---|---|---|---|---|---|---|---|---|---|---|
Java | mpl-2.0 | 4d3881759cdb4afdc898ebef2ad8faf8cd905812 | 0 | jentfoo/ambushGUI,threadly/ambushGUI | package org.threadly.load;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import org.threadly.load.ExecutableScript.ExecutionItem;
import org.threadly.load.ExecutableScript.ExecutionItem.ChildItems;
import org.threadly.load.gui.Node;
/**
* <p>Class which builds a graph of {@link Node}'s based off a script produced by a
* {@link ScriptFactory}. This builds a script and then traverses the executable items to produce
* a graph of {@link Node} objects.</p>
*
* @author jent - Mike Jensen
*/
public class ScriptGraphBuilder extends AbstractScriptFactoryInitializer {
/**
* Builds a graph from an array of arguments. It is expected that the first argument is the
* {@link ScriptFactory} class. The following arguments should be parameters for that factory
* in the form of key=value.
*
* @param args Arguments to construct {@link ScriptFactory} with
* @return The head node for the graph provided from the script
*/
public static Node buildGraph(String[] args) {
return new ScriptGraphBuilder(args).makeGraph();
}
/**
* Makes a {@link Node} graph from the list of provided steps. It is expected that these
* initial steps are ran sequentially between each other, but it can handle steps which fork
* out into parallel channels.
*
* @param childItems Collection of sequential steps to start graph production from
* @return Head node of a graph which matches the steps execution
*/
public static Node makeGraph(ChildItems childItems) {
Node head = new Node("start");
Node current = head;
for (ExecutionItem step : childItems) {
current = expandNode(current, step, new AtomicInteger());
}
head.cleanGraph();
return head;
}
private static Node expandNode(Node previousNode, ExecutionItem item, AtomicInteger chainLength) {
ChildItems childItems = item.getChildItems();
if (! childItems.hasChildren()) {
Node result = new Node(item.toString());
previousNode.addChildNode(result);
chainLength.incrementAndGet();
return result;
} else {
int maxLength = -1;
List<Node> childNodes = new LinkedList<Node>();
Node longestNode = previousNode;
Iterator<ExecutionItem> it = childItems.iterator();
if (! childItems.itemsRunSequential()) {
Node branchPoint = new Node();
previousNode.addChildNode(branchPoint);
previousNode = branchPoint;
}
while (it.hasNext()) {
ExecutionItem childItem = it.next();
AtomicInteger length = new AtomicInteger();
Node endNode = expandNode(previousNode, childItem, length);
if (childItems.itemsRunSequential()) {
previousNode = endNode;
}
if (length.get() >= maxLength) {
maxLength = length.get();
longestNode = endNode;
}
childNodes.add(endNode);
}
if (childItems.itemsRunSequential() || maxLength < 1) {
return longestNode;
} else {
Node joinPoint = new Node();
for (Node n : childNodes) {
n.addChildNode(joinPoint);
}
return joinPoint;
}
}
}
protected ScriptGraphBuilder(String[] args) {
super(args);
}
protected Node makeGraph() {
return ScriptGraphBuilder.makeGraph(script.startExecutionItem.getChildItems());
}
}
| src/main/java/org/threadly/load/ScriptGraphBuilder.java | package org.threadly.load;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import org.threadly.load.ExecutableScript.ExecutionItem;
import org.threadly.load.ExecutableScript.ExecutionItem.ChildItems;
import org.threadly.load.gui.Node;
/**
* <p>Class which builds a graph of {@link Node}'s based off a script produced by a
* {@link ScriptFactory}. This builds a script and then traverses the executable items to produce
* a graph of {@link Node} objects.</p>
*
* @author jent - Mike Jensen
*/
public class ScriptGraphBuilder extends AbstractScriptFactoryInitializer {
/**
* Builds a graph from an array of arguments. It is expected that the first argument is the
* {@link ScriptFactory} class. The following arguments should be parameters for that factory
* in the form of key=value.
*
* @param args Arguments to construct {@link ScriptFactory} with
* @return The head node for the graph provided from the script
*/
public static Node buildGraph(String[] args) {
return new ScriptGraphBuilder(args).makeGraph();
}
/**
* Makes a {@link Node} graph from the list of provided steps. It is expected that these
* initial steps are ran sequentially between each other, but it can handle steps which fork
* out into parallel channels.
*
* @param steps Collection of sequential steps to start graph production from
* @return Head node of a graph which matches the steps execution
*/
public static Node makeGraph(ExecutionItem[] steps) {
Node head = new Node("start");
Node current = head;
for (ExecutionItem step : steps) {
current = expandNode(current, step, new AtomicInteger());
}
head.cleanGraph();
return head;
}
private static Node expandNode(Node previousNode, ExecutionItem item, AtomicInteger chainLength) {
ChildItems childItems = item.getChildItems();
if (! childItems.hasChildren()) {
Node result = new Node(item.toString());
previousNode.addChildNode(result);
chainLength.incrementAndGet();
return result;
} else {
int maxLength = -1;
List<Node> childNodes = new LinkedList<Node>();
Node longestNode = previousNode;
Iterator<ExecutionItem> it = childItems.iterator();
if (! childItems.itemsRunSequential()) {
Node branchPoint = new Node();
previousNode.addChildNode(branchPoint);
previousNode = branchPoint;
}
while (it.hasNext()) {
ExecutionItem childItem = it.next();
AtomicInteger length = new AtomicInteger();
Node endNode = expandNode(previousNode, childItem, length);
if (childItems.itemsRunSequential()) {
previousNode = endNode;
}
if (length.get() >= maxLength) {
maxLength = length.get();
longestNode = endNode;
}
childNodes.add(endNode);
}
if (childItems.itemsRunSequential() || maxLength < 1) {
return longestNode;
} else {
Node joinPoint = new Node();
for (Node n : childNodes) {
n.addChildNode(joinPoint);
}
return joinPoint;
}
}
}
protected ScriptGraphBuilder(String[] args) {
super(args);
}
protected Node makeGraph() {
return ScriptGraphBuilder.makeGraph(script.steps);
}
}
| Updated for latest ambush changes (build fix)
| src/main/java/org/threadly/load/ScriptGraphBuilder.java | Updated for latest ambush changes (build fix) | <ide><path>rc/main/java/org/threadly/load/ScriptGraphBuilder.java
<ide> * initial steps are ran sequentially between each other, but it can handle steps which fork
<ide> * out into parallel channels.
<ide> *
<del> * @param steps Collection of sequential steps to start graph production from
<add> * @param childItems Collection of sequential steps to start graph production from
<ide> * @return Head node of a graph which matches the steps execution
<ide> */
<del> public static Node makeGraph(ExecutionItem[] steps) {
<add> public static Node makeGraph(ChildItems childItems) {
<ide> Node head = new Node("start");
<ide> Node current = head;
<del> for (ExecutionItem step : steps) {
<add> for (ExecutionItem step : childItems) {
<ide> current = expandNode(current, step, new AtomicInteger());
<ide> }
<ide>
<ide> }
<ide>
<ide> protected Node makeGraph() {
<del> return ScriptGraphBuilder.makeGraph(script.steps);
<add> return ScriptGraphBuilder.makeGraph(script.startExecutionItem.getChildItems());
<ide> }
<ide> } |
|
Java | apache-2.0 | c45068590874dee15b68b5066bdc9fda87167a8f | 0 | sqs/avro-keyvalue | package com.blendlabsinc.avrokeyvalue;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Map;
import org.apache.avro.AvroTypeException;
import org.apache.avro.Schema;
import org.apache.avro.Schema.Type;
import org.apache.avro.generic.GenericDatumReader;
import org.apache.avro.generic.GenericDatumWriter;
import org.apache.avro.io.DatumWriter;
import org.apache.avro.io.Encoder;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
import org.apache.avro.io.EncoderFactory;
/**
* Unit test for Avro map encoding.
*/
public class MapEncodingTest extends TestCase {
/**
* Create the test case
*
* @param testName name of the test case
*/
public MapEncodingTest(String testName) {
super( testName );
}
/**
* @return the suite of tests being tested
*/
public static Test suite() {
return new TestSuite(MapEncodingTest.class);
}
/**
* Helpers
*/
private Map<String, String> write(Schema schema, Object datum) throws IOException {
DatumWriter<Object> writer = new GenericDatumWriter<Object>(schema);
Map<String, String> out = new java.util.HashMap();
KeyValueEncoder encoder = new KeyValueEncoder(schema, out);
writer.write(datum, encoder);
return out;
}
/**
* Test cases
*/
public void testMap() throws IOException {
Schema schema = Schema.parse("{\"type\": \"map\", \"values\": \"string\"}");
Map<String, String> expected = new java.util.HashMap();
expected.put("a", "aa");
expected.put("b", "bb");
assertEquals(expected, write(schema, expected));
}
public void testEmptyMap() throws IOException {
Schema schema = Schema.parse("{\"type\": \"map\", \"values\": \"string\"}");
Map<String, String> expected = new java.util.HashMap();
assertEquals(expected, write(schema, expected));
}
public void testMapWithEmptyKey() throws IOException {
Schema schema = Schema.parse("{\"type\": \"map\", \"values\": \"string\"}");
Map<String, String> expected = new java.util.HashMap();
expected.put("", "a");
assertEquals(expected, write(schema, expected));
}
public void testNestedMap() throws IOException {
Schema schema = Schema.parse("{\"type\": \"map\", \"values\": {\"type\": \"map\", \"values\": \"string\"}}");
Map<String, Map<String, String>> nestedMap = new java.util.HashMap();
Map<String, String> mapA = new java.util.HashMap(); mapA.put("aa", "aaa");
Map<String, String> mapB = new java.util.HashMap(); mapB.put("bb", "bbb");
nestedMap.put("a", mapA);
nestedMap.put("b", mapB);
Map<String, String> expected = new java.util.HashMap();
expected.put("a|aa", "aaa");
expected.put("b|bb", "bbb");
assertEquals(expected, write(schema, nestedMap));
}
}
| src/test/java/com/blendlabsinc/avrokeyvalue/MapEncodingTest.java | package com.blendlabsinc.avrokeyvalue;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import org.apache.avro.AvroTypeException;
import org.apache.avro.Schema;
import org.apache.avro.Schema.Type;
import org.apache.avro.generic.GenericDatumReader;
import org.apache.avro.generic.GenericDatumWriter;
import org.apache.avro.io.DatumWriter;
import org.apache.avro.io.Encoder;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
import org.apache.avro.io.EncoderFactory;
/**
* Unit test for Avro map encoding.
*/
public class MapEncodingTest extends TestCase {
/**
* Create the test case
*
* @param testName name of the test case
*/
public MapEncodingTest(String testName) {
super( testName );
}
/**
* @return the suite of tests being tested
*/
public static Test suite() {
return new TestSuite(MapEncodingTest.class);
}
/**
* Helpers
*/
private java.util.Map<String, String> write(Schema schema, Object datum) throws IOException {
DatumWriter<Object> writer = new GenericDatumWriter<Object>(schema);
java.util.Map<String, String> out = new java.util.HashMap();
KeyValueEncoder encoder = new KeyValueEncoder(schema, out);
writer.write(datum, encoder);
return out;
}
/**
* Test cases
*/
public void testMap() throws IOException {
Schema schema = Schema.parse("{\"type\": \"map\", \"values\": \"string\"}");
java.util.Map<String, String> expected = new java.util.HashMap();
expected.put("a", "aa");
expected.put("b", "bb");
assertEquals(expected, write(schema, expected));
}
public void testEmptyMap() throws IOException {
Schema schema = Schema.parse("{\"type\": \"map\", \"values\": \"string\"}");
java.util.Map<String, String> expected = new java.util.HashMap();
assertEquals(expected, write(schema, expected));
}
public void testMapWithEmptyKey() throws IOException {
Schema schema = Schema.parse("{\"type\": \"map\", \"values\": \"string\"}");
java.util.Map<String, String> expected = new java.util.HashMap();
expected.put("", "a");
assertEquals(expected, write(schema, expected));
}
public void testNestedMap() throws IOException {
Schema schema = Schema.parse("{\"type\": \"map\", \"values\": {\"type\": \"map\", \"values\": \"string\"}}");
java.util.Map<String, java.util.Map<String, String>> nestedMap = new java.util.HashMap();
java.util.Map<String, String> mapA = new java.util.HashMap(); mapA.put("aa", "aaa");
java.util.Map<String, String> mapB = new java.util.HashMap(); mapB.put("bb", "bbb");
nestedMap.put("a", mapA);
nestedMap.put("b", mapB);
java.util.Map<String, String> expected = new java.util.HashMap();
expected.put("a|aa", "aaa");
expected.put("b|bb", "bbb");
assertEquals(expected, write(schema, nestedMap));
}
}
| import java.util.Map
| src/test/java/com/blendlabsinc/avrokeyvalue/MapEncodingTest.java | import java.util.Map | <ide><path>rc/test/java/com/blendlabsinc/avrokeyvalue/MapEncodingTest.java
<ide> import java.io.ByteArrayOutputStream;
<ide> import java.io.IOException;
<ide> import java.io.OutputStream;
<add>import java.util.Map;
<ide>
<ide> import org.apache.avro.AvroTypeException;
<ide> import org.apache.avro.Schema;
<ide> * Helpers
<ide> */
<ide>
<del> private java.util.Map<String, String> write(Schema schema, Object datum) throws IOException {
<add> private Map<String, String> write(Schema schema, Object datum) throws IOException {
<ide> DatumWriter<Object> writer = new GenericDatumWriter<Object>(schema);
<del> java.util.Map<String, String> out = new java.util.HashMap();
<add> Map<String, String> out = new java.util.HashMap();
<ide> KeyValueEncoder encoder = new KeyValueEncoder(schema, out);
<ide> writer.write(datum, encoder);
<ide> return out;
<ide>
<ide> public void testMap() throws IOException {
<ide> Schema schema = Schema.parse("{\"type\": \"map\", \"values\": \"string\"}");
<del> java.util.Map<String, String> expected = new java.util.HashMap();
<add> Map<String, String> expected = new java.util.HashMap();
<ide> expected.put("a", "aa");
<ide> expected.put("b", "bb");
<ide> assertEquals(expected, write(schema, expected));
<ide>
<ide> public void testEmptyMap() throws IOException {
<ide> Schema schema = Schema.parse("{\"type\": \"map\", \"values\": \"string\"}");
<del> java.util.Map<String, String> expected = new java.util.HashMap();
<add> Map<String, String> expected = new java.util.HashMap();
<ide> assertEquals(expected, write(schema, expected));
<ide> }
<ide>
<ide> public void testMapWithEmptyKey() throws IOException {
<ide> Schema schema = Schema.parse("{\"type\": \"map\", \"values\": \"string\"}");
<del> java.util.Map<String, String> expected = new java.util.HashMap();
<add> Map<String, String> expected = new java.util.HashMap();
<ide> expected.put("", "a");
<ide> assertEquals(expected, write(schema, expected));
<ide> }
<ide>
<ide> public void testNestedMap() throws IOException {
<ide> Schema schema = Schema.parse("{\"type\": \"map\", \"values\": {\"type\": \"map\", \"values\": \"string\"}}");
<del> java.util.Map<String, java.util.Map<String, String>> nestedMap = new java.util.HashMap();
<del> java.util.Map<String, String> mapA = new java.util.HashMap(); mapA.put("aa", "aaa");
<del> java.util.Map<String, String> mapB = new java.util.HashMap(); mapB.put("bb", "bbb");
<add> Map<String, Map<String, String>> nestedMap = new java.util.HashMap();
<add> Map<String, String> mapA = new java.util.HashMap(); mapA.put("aa", "aaa");
<add> Map<String, String> mapB = new java.util.HashMap(); mapB.put("bb", "bbb");
<ide> nestedMap.put("a", mapA);
<ide> nestedMap.put("b", mapB);
<ide>
<del> java.util.Map<String, String> expected = new java.util.HashMap();
<add> Map<String, String> expected = new java.util.HashMap();
<ide> expected.put("a|aa", "aaa");
<ide> expected.put("b|bb", "bbb");
<ide> |
|
Java | lgpl-2.1 | 8621d9a1b719f9c9737fb04ab6c5ea53e873ee14 | 0 | ethaneldridge/vassal,ethaneldridge/vassal,ethaneldridge/vassal | /*
*
* Copyright (c) 2004-2012 by Rodney Kinney, Brent Easton
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License (LGPL) as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this library; if not, copies are available
* at http://www.opensource.org.
*/
package VASSAL.counters;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Frame;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.Shape;
import java.awt.event.ActionEvent;
import java.io.File;
import java.io.IOException;
import java.io.Writer;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Objects;
import java.util.Random;
import javax.swing.Action;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.KeyStroke;
import javax.swing.ListSelectionModel;
import javax.swing.SwingUtilities;
import VASSAL.build.BadDataReport;
import VASSAL.build.GameModule;
import VASSAL.build.module.Chatter;
import VASSAL.build.module.Map;
import VASSAL.build.module.PlayerRoster;
import VASSAL.build.module.map.DeckGlobalKeyCommand;
import VASSAL.build.module.map.DrawPile;
import VASSAL.build.module.map.StackMetrics;
import VASSAL.build.module.properties.MutableProperty;
import VASSAL.build.module.properties.PropertySource;
import VASSAL.command.AddPiece;
import VASSAL.command.ChangeTracker;
import VASSAL.command.Command;
import VASSAL.command.CommandEncoder;
import VASSAL.command.NullCommand;
import VASSAL.configure.ColorConfigurer;
import VASSAL.configure.PropertyExpression;
import VASSAL.i18n.Localization;
import VASSAL.i18n.Resources;
import VASSAL.tools.ErrorDialog;
import VASSAL.tools.FormattedString;
import VASSAL.tools.NamedKeyStroke;
import VASSAL.tools.NamedKeyStrokeListener;
import VASSAL.tools.ReadErrorDialog;
import VASSAL.tools.ScrollPane;
import VASSAL.tools.SequenceEncoder;
import VASSAL.tools.WriteErrorDialog;
import VASSAL.tools.filechooser.FileChooser;
import VASSAL.tools.ProblemDialog;
/**
* A collection of pieces that behaves like a deck, i.e.: Doesn't move.
* Can't be expanded. Can be shuffled. Can be turned face-up and face-down.
*/
public class Deck extends Stack implements PlayerRoster.SideChangeListener {
public static final String ID = "deck;"; //$NON-NLS-1$
public static final String ALWAYS = "Always"; // NON-NLS
public static final String NEVER = "Never"; // NON-NLS
public static final String USE_MENU = "Via right-click Menu"; // NON-NLS
public static final String NO_USER = "nobody"; // Dummy user ID for turning // NON-NLS
protected static final StackMetrics deckStackMetrics = new StackMetrics(false, 2, 2, 2, 2);
// cards face down
protected boolean drawOutline = true;
protected Color outlineColor = Color.black;
protected Dimension size = new Dimension(40, 40);
protected boolean shuffle = true;
protected String faceDownOption = ALWAYS;
protected String shuffleOption = ALWAYS;
protected String shuffleCommand = "";
protected boolean allowMultipleDraw = false;
protected boolean allowSelectDraw = false;
protected boolean reversible = false;
protected String reshuffleCommand = ""; //$NON-NLS-1$
protected String reshuffleTarget;
protected String reshuffleMsgFormat;
protected NamedKeyStrokeListener reshuffleListener;
protected NamedKeyStroke reshuffleKey;
protected String reverseMsgFormat;
protected String reverseCommand;
protected NamedKeyStroke reverseKey;
protected NamedKeyStrokeListener reverseListener;
protected String shuffleMsgFormat;
protected NamedKeyStrokeListener shuffleListener;
protected NamedKeyStroke shuffleKey;
protected String faceDownMsgFormat;
protected boolean drawFaceUp;
protected boolean persistable;
protected FormattedString selectDisplayProperty = new FormattedString("$" + BasicPiece.BASIC_NAME + "$");
protected String selectSortProperty = "";
protected MutableProperty.Impl countProperty =
new MutableProperty.Impl("", this);
protected List<MutableProperty.Impl> expressionProperties = new ArrayList<>();
protected String deckName;
protected String localizedDeckName;
protected boolean faceDown;
protected int dragCount = 0;
protected int maxStack = 10;
protected CountExpression[] countExpressions = new CountExpression[0];
protected boolean expressionCounting = false;
protected List<GamePiece> nextDraw = null;
protected KeyCommand[] commands;
protected List<DeckGlobalKeyCommand> globalCommands = new ArrayList<>();
protected boolean hotkeyOnEmpty;
protected NamedKeyStroke emptyKey;
protected boolean restrictOption;
protected PropertyExpression restrictExpression = new PropertyExpression();
protected PropertySource propertySource;
/**
* Special {@link CommandEncoder} to handle loading/saving Decks from files.
*/
protected CommandEncoder commandEncoder = new CommandEncoder() {
/**
* Deserializes a Deck loaded from a file, turning it into a LoadDeckCommand.
* @param command String contents of deck
* @return {@link LoadDeckCommand} to put the specified contents in the deck
*/
@Override
public Command decode(String command) {
if (!command.startsWith(LoadDeckCommand.PREFIX)) {
return null;
}
return new LoadDeckCommand(Deck.this);
}
/**
* Serializes a LoadDeckCommand
* @param c LoadDeckCommand
* @return string form of command
*/
@Override
public String encode(Command c) {
if (!(c instanceof LoadDeckCommand)) {
return null;
}
return LoadDeckCommand.PREFIX;
}
};
private final GameModule gameModule;
/**
* Not for internal use, but required for initial build of module
*
* @deprecated use {@link #Deck(GameModule)}
*/
@Deprecated
public Deck() {
this(GameModule.getGameModule());
}
/**
* @deprecated use {@link #Deck(GameModule, String)}
*/
@Deprecated(since = "2020-08-06", forRemoval = true)
public Deck(String type) {
this(GameModule.getGameModule(), type);
ProblemDialog.showDeprecated("2020-08-06");
}
/**
* @deprecated use {@link #Deck(GameModule, String, PropertySource)}
*/
@Deprecated(since = "2020-08-06", forRemoval = true)
public Deck(String type, PropertySource source) {
this(GameModule.getGameModule(), type, source);
ProblemDialog.showDeprecated("2020-08-06");
}
/**
* Create an empty deck
* @param gameModule The game module
*/
public Deck(GameModule gameModule) {
this(gameModule, ID);
}
/**
* Creates an empty deck using specified type information
* @param gameModule The game module
* @param type Type information for the deck (the configuration information that does not change during the game)
*/
public Deck(GameModule gameModule, String type) {
this.gameModule = gameModule;
mySetType(type);
}
/**
* Creates an empty deck using specified type information
* @param gameModule The game module
* @param type Type information for the deck (the configuration information that does not change during the game)
* @param source PropertySource
*/
public Deck(GameModule gameModule, String type, PropertySource source) {
this(gameModule, type);
propertySource = source;
}
/**
* Sets the Deck's property source
* @param source PropertySource
*/
public void setPropertySource(PropertySource source) {
propertySource = source;
if (globalCommands != null) {
for (final DeckGlobalKeyCommand globalCommand : globalCommands) {
globalCommand.setPropertySource(propertySource);
}
}
}
/**
* Listener for when the local player changes side. Updates all of our counts of expressions of pieces configured to be counted.
* @param oldSide local player's old side
* @param newSide local player's new side
*/
@Override
public void sideChanged(String oldSide, String newSide) {
updateCountsAll();
}
/**
* Adds a Deck Global Key Command (DGKC).
* @param globalCommand The command to add
*/
public void addGlobalKeyCommand(DeckGlobalKeyCommand globalCommand) {
globalCommands.add(globalCommand);
}
/**
* Removes a Deck Global Key Command (DGKC).
* @param globalCommand The command to remove
*/
public void removeGlobalKeyCommand(DeckGlobalKeyCommand globalCommand) {
globalCommands.remove(globalCommand);
}
/**
* @return A list of Deck Global Key Commands for this deck, serialized by their encoder.
*/
protected String[] getGlobalCommands() {
final String[] commands = new String[globalCommands.size()];
for (int i = 0; i < globalCommands.size(); i++) {
commands[i] = globalCommands.get(i).encode();
}
return commands;
}
/**
* Sets the list of Deck Global Key Commands for this deck
* @param commands The list of commands to set (in serialized string form)
*/
protected void setGlobalCommands(String[] commands) {
globalCommands = new ArrayList<>(commands.length);
for (final String command : commands) {
globalCommands.add(new DeckGlobalKeyCommand(command, propertySource));
}
}
/**
* Update map-level count properties for all "expressions" of pieces that are configured
* to be counted. These are held in the String[] countExpressions.
*/
private void updateCountsAll() {
if (!doesExpressionCounting() || getMap() == null) {
return;
}
//Clear out all of the registered count expressions
for (int index = 0; index < countExpressions.length; index++) {
expressionProperties.get(index).setPropertyValue("0"); //$NON-NLS-1$
}
//Increase all of the pieces with expressions specified in this deck
asList().stream()
.filter(Objects::nonNull)
.forEach(p -> updateCounts(p, true));
}
/**
* Update map-level count property for a piece located at index
* @param index Index (within the Deck, counting from the top) of the piece whose count to update
*/
private void updateCounts(int index) {
if (!doesExpressionCounting()) {
return;
}
if (index >= 0 && index < getPieceCount()) {
final GamePiece p = getPieceAt(index);
if (p == null) {
//can't figure out the piece, do a full update
updateCountsAll();
}
else {
updateCounts(p, false);
}
}
else {
//can't figure out the piece, do a full update
updateCountsAll();
}
}
/**
* Update map-level count property for a piece
* @param p Game piece to update counts for
* @param increase if true, increase the count; if false, decrease.
*/
private void updateCounts(GamePiece p, boolean increase) {
if (!doesExpressionCounting() || getMap() == null) {
return;
}
//test all the expressions for this deck
for (int index = 0; index < countExpressions.length; index++) {
final MutableProperty.Impl prop = expressionProperties.get(index);
final FormattedString formatted =
new FormattedString(countExpressions[index].getExpression());
final PieceFilter f = PropertiesPieceFilter.parse(formatted.getText());
if (f.accept(p)) {
final String mapProperty = prop.getPropertyValue();
if (mapProperty != null) {
int newValue = Integer.decode(mapProperty);
if (increase) {
newValue++;
}
else {
newValue--;
}
prop.setPropertyValue(String.valueOf(newValue));
}
}
}
}
/**
* Set the <deckName>_numPieces property in the containing Map
*/
protected void fireNumCardsProperty() {
countProperty.setPropertyValue(String.valueOf(pieceCount));
}
/**
* Inserts a piece into a specific position into the Deck (counting down from the top)
* @param p Piece to insert
* @param index "How many cards down into the Deck" to put it.
*/
@Override
protected void insertPieceAt(GamePiece p, int index) {
super.insertPieceAt(p, index);
updateCounts(p, true);
fireNumCardsProperty();
}
/**
* Removes a piece from a specific location in the deck
* @param index Piece to remove, counting down from the top
*/
@Override
protected void removePieceAt(int index) {
final int startCount = pieceCount;
updateCounts(index);
super.removePieceAt(index);
fireNumCardsProperty();
if (hotkeyOnEmpty && emptyKey != null && startCount > 0 && pieceCount == 0) {
gameModule.fireKeyStroke(emptyKey);
}
}
/**
* Removes all pieces from the Deck.
*/
@Override
public void removeAll() {
super.removeAll();
updateCountsAll();
fireNumCardsProperty();
}
/**
* Sets the Map this Deck appears on
* @param map Map to assign Deck to
*/
@Override
public void setMap(Map map) {
if (map != getMap()) {
countProperty.removeFromContainer();
if (map != null) countProperty.addTo(map);
for (final MutableProperty.Impl prop : expressionProperties) {
prop.removeFromContainer();
if (map != null) prop.addTo(map);
}
}
super.setMap(map);
updateCountsAll();
fireNumCardsProperty();
}
public void addListeners() {
if (shuffleListener == null) {
shuffleListener = new NamedKeyStrokeListener(e -> {
gameModule.sendAndLog(shuffle());
repaintMap();
});
gameModule.addKeyStrokeListener(shuffleListener);
shuffleListener.setKeyStroke(getShuffleKey());
}
if (reshuffleListener == null) {
reshuffleListener = new NamedKeyStrokeListener(e -> {
gameModule.sendAndLog(sendToDeck());
repaintMap();
});
gameModule.addKeyStrokeListener(reshuffleListener);
reshuffleListener.setKeyStroke(getReshuffleKey());
}
if (reverseListener == null) {
reverseListener = new NamedKeyStrokeListener(e -> {
gameModule.sendAndLog(reverse());
repaintMap();
});
gameModule.addKeyStrokeListener(reverseListener);
reverseListener.setKeyStroke(getReverseKey());
}
gameModule.addSideChangeListenerToPlayerRoster(this);
}
public void removeListeners() {
if (shuffleListener != null) {
gameModule.removeKeyStrokeListener(shuffleListener);
shuffleListener = null;
}
if (reshuffleListener != null) {
gameModule.removeKeyStrokeListener(reshuffleListener);
reshuffleListener = null;
}
if (reverseListener != null) {
gameModule.removeKeyStrokeListener(reverseListener);
reverseListener = null;
}
gameModule.removeSideChangeListenerFromPlayerRoster(this);
}
/** Sets the information for this Deck. See {@link Decorator#myGetType}
* @param type a serialized configuration string to
* set the "type information" of this Deck, which is
* information that doesn't change during the course of
* a single game (e.g. Image Files, Context Menu strings,
* etc, rules about when deck is shuffled, whether it is
* face-up or face down, etc).
*/
protected void mySetType(String type) {
final SequenceEncoder.Decoder st = new SequenceEncoder.Decoder(type, ';');
st.nextToken();
drawOutline = st.nextBoolean(true);
outlineColor = ColorConfigurer.stringToColor(st.nextToken("0,0,0")); //$NON-NLS-1$
size.setSize(st.nextInt(40), st.nextInt(40));
faceDownOption = st.nextToken("Always"); //$NON-NLS-1$
shuffleOption = st.nextToken("Always"); //$NON-NLS-1$
allowMultipleDraw = st.nextBoolean(true);
allowSelectDraw = st.nextBoolean(true);
reversible = st.nextBoolean(true);
reshuffleCommand = st.nextToken(""); //$NON-NLS-1$
reshuffleTarget = st.nextToken(""); //$NON-NLS-1$
reshuffleMsgFormat = st.nextToken(""); //$NON-NLS-1$
setDeckName(st.nextToken(Resources.getString("Deck.deck")));
shuffleMsgFormat = st.nextToken(""); //$NON-NLS-1$
reverseMsgFormat = st.nextToken(""); //$NON-NLS-1$
faceDownMsgFormat = st.nextToken(""); //$NON-NLS-1$
drawFaceUp = st.nextBoolean(false);
persistable = st.nextBoolean(false);
shuffleKey = st.nextNamedKeyStroke(null);
reshuffleKey = st.nextNamedKeyStroke(null);
maxStack = st.nextInt(10);
setCountExpressions(st.nextStringArray(0));
expressionCounting = st.nextBoolean(false);
setGlobalCommands(st.nextStringArray(0));
hotkeyOnEmpty = st.nextBoolean(false);
emptyKey = st.nextNamedKeyStroke(null);
selectDisplayProperty.setFormat(st.nextToken("$" + BasicPiece.BASIC_NAME + "$"));
selectSortProperty = st.nextToken("");
restrictOption = st.nextBoolean(false);
restrictExpression.setExpression(st.nextToken(""));
shuffleCommand = st.nextToken(Resources.getString("Deck.shuffle"));
reverseCommand = st.nextToken(Resources.getString("Deck.reverse"));
reverseKey = st.nextNamedKeyStroke(null);
final DrawPile myPile = DrawPile.findDrawPile(getDeckName());
// If a New game/Load Game is starting, set this Deck into the matching DrawPile
// If a Load Continuation is starting, ignore this Deck and let the DrawPile continue with the existing Deck.
// Combined fix for bugs 4507, 10249 & 13461
if (myPile != null && ! GameModule.getGameModule().getGameState().isGameStarted()) {
myPile.setDeck(this);
}
}
public String getFaceDownOption() {
return faceDownOption;
}
/**
* @return true if cards are turned face up when drawn from this deck
*/
public boolean isDrawFaceUp() {
return drawFaceUp;
}
public void setDrawFaceUp(boolean drawFaceUp) {
this.drawFaceUp = drawFaceUp;
}
public void setFaceDownOption(String faceDownOption) {
this.faceDownOption = faceDownOption;
faceDown = !faceDownOption.equals(NEVER);
}
public Dimension getSize() {
return size;
}
public void setSize(Dimension size) {
this.size.setSize(size);
}
public String getShuffleOption() {
return shuffleOption;
}
public void setShuffleOption(String shuffleOption) {
this.shuffleOption = shuffleOption;
}
public boolean isShuffle() {
return shuffle;
}
public int getMaxStack() {
return maxStack;
}
@Override
public int getMaximumVisiblePieceCount() {
return Math.min(pieceCount, maxStack);
}
public String[] getCountExpressions() {
final String[] fullstrings = new String[countExpressions.length];
for (int index = 0; index < countExpressions.length; index++) {
fullstrings[index] = countExpressions[index].getFullString();
}
return fullstrings;
}
public boolean doesExpressionCounting() {
return expressionCounting;
}
public String getFaceDownMsgFormat() {
return faceDownMsgFormat;
}
public void setFaceDownMsgFormat(String faceDownMsgFormat) {
this.faceDownMsgFormat = faceDownMsgFormat;
}
public String getReverseMsgFormat() {
return reverseMsgFormat;
}
public void setReverseMsgFormat(String reverseMsgFormat) {
this.reverseMsgFormat = reverseMsgFormat;
}
public String getReverseCommand() {
return reverseCommand;
}
public void setReverseCommand(String s) {
reverseCommand = s;
}
public NamedKeyStroke getReverseKey() {
return reverseKey;
}
public void setReverseKey(NamedKeyStroke reverseKey) {
this.reverseKey = reverseKey;
}
public String getShuffleMsgFormat() {
return shuffleMsgFormat;
}
public void setShuffleMsgFormat(String shuffleMsgFormat) {
this.shuffleMsgFormat = shuffleMsgFormat;
}
public NamedKeyStroke getShuffleKey() {
return shuffleKey;
}
public void setShuffleKey(NamedKeyStroke shuffleKey) {
this.shuffleKey = shuffleKey;
}
public String getShuffleCommand() {
return shuffleCommand;
}
public void setShuffleCommand(String s) {
shuffleCommand = s;
}
public void setShuffle(boolean shuffle) {
this.shuffle = shuffle;
}
public boolean isAllowMultipleDraw() {
return allowMultipleDraw;
}
public void setAllowMultipleDraw(boolean allowMultipleDraw) {
this.allowMultipleDraw = allowMultipleDraw;
}
public boolean isAllowSelectDraw() {
return allowSelectDraw;
}
public void setMaxStack(int maxStack) {
this.maxStack = maxStack;
}
public void setCountExpressions(String[] countExpressionsString) {
final CountExpression[] c = new CountExpression[countExpressionsString.length];
int goodExpressionCount = 0;
for (int index = 0; index < countExpressionsString.length; index++) {
final CountExpression n = new CountExpression(countExpressionsString[index]);
if (n.getName() != null) {
c[index] = n;
goodExpressionCount++;
}
}
this.countExpressions = Arrays.copyOf(c, goodExpressionCount);
while (countExpressions.length > expressionProperties.size()) {
expressionProperties.add(new MutableProperty.Impl("", this));
}
for (int i = 0; i < countExpressions.length; i++) {
expressionProperties.get(i).setPropertyName(
deckName + "_" + countExpressions[i].getName());
}
}
public void setExpressionCounting(boolean expressionCounting) {
this.expressionCounting = expressionCounting;
}
public void setAllowSelectDraw(boolean allowSelectDraw) {
this.allowSelectDraw = allowSelectDraw;
}
public boolean isReversible() {
return reversible;
}
public void setReversible(boolean reversible) {
this.reversible = reversible;
}
public void setDeckName(String n) {
if (Localization.getInstance().isTranslationInProgress()) {
localizedDeckName = n;
}
else {
deckName = n;
}
countProperty.setPropertyName(deckName + "_numPieces"); // NON-NLS
for (int i = 0; i < countExpressions.length; ++i) {
expressionProperties.get(i).setPropertyName(
deckName + "_" + countExpressions[i].getName());
}
}
public String getDeckName() {
return deckName;
}
public String getLocalizedDeckName() {
return localizedDeckName == null ? deckName : localizedDeckName;
}
/**
* @return The popup menu text for the command that sends the entire deck to another deck
*/
public String getReshuffleCommand() {
return reshuffleCommand;
}
public void setReshuffleCommand(String reshuffleCommand) {
this.reshuffleCommand = reshuffleCommand;
}
public NamedKeyStroke getReshuffleKey() {
return reshuffleKey;
}
public void setReshuffleKey(NamedKeyStroke reshuffleKey) {
this.reshuffleKey = reshuffleKey;
}
/**
* The name of the {@link VASSAL.build.module.map.DrawPile} to which the
* contents of this deck will be sent when the reshuffle command is selected
*/
public String getReshuffleTarget() {
return reshuffleTarget;
}
public void setReshuffleTarget(String reshuffleTarget) {
this.reshuffleTarget = reshuffleTarget;
}
/**
* @return The message to send to the chat window when the deck is reshuffled to another deck
*/
public String getReshuffleMsgFormat() {
return reshuffleMsgFormat;
}
public void setReshuffleMsgFormat(String reshuffleMsgFormat) {
this.reshuffleMsgFormat = reshuffleMsgFormat;
}
public boolean isHotkeyOnEmpty() {
return hotkeyOnEmpty;
}
public void setHotkeyOnEmpty(boolean b) {
hotkeyOnEmpty = b;
}
@Deprecated(since = "2020-08-06", forRemoval = true)
public KeyStroke getEmptyKey() {
ProblemDialog.showDeprecated("2020-08-06");
return emptyKey.getKeyStroke();
}
public NamedKeyStroke getNamedEmptyKey() {
return emptyKey;
}
@Deprecated(since = "2020-08-06", forRemoval = true)
public void setEmptyKey(KeyStroke k) {
ProblemDialog.showDeprecated("2020-08-06");
emptyKey = NamedKeyStroke.of(k);
}
public void setEmptyKey(NamedKeyStroke k) {
emptyKey = k;
}
public void setRestrictOption(boolean restrictOption) {
this.restrictOption = restrictOption;
}
public boolean isRestrictOption() {
return restrictOption;
}
public void setRestrictExpression(PropertyExpression restrictExpression) {
this.restrictExpression = restrictExpression;
}
public PropertyExpression getRestrictExpression() {
return restrictExpression;
}
/**
* Does the specified GamePiece meet the rules to be contained
* in this Deck.
*/
public boolean mayContain(GamePiece piece) {
if (! restrictOption || restrictExpression.isNull()) {
return true;
}
else {
return restrictExpression.accept(piece);
}
}
@Override
public String getType() {
final SequenceEncoder se = new SequenceEncoder(';');
se.append(drawOutline)
.append(ColorConfigurer.colorToString(outlineColor))
.append(String.valueOf(size.width))
.append(String.valueOf(size.height))
.append(faceDownOption)
.append(shuffleOption)
.append(String.valueOf(allowMultipleDraw))
.append(String.valueOf(allowSelectDraw))
.append(String.valueOf(reversible))
.append(reshuffleCommand)
.append(reshuffleTarget)
.append(reshuffleMsgFormat)
.append(deckName)
.append(shuffleMsgFormat)
.append(reverseMsgFormat)
.append(faceDownMsgFormat)
.append(drawFaceUp)
.append(persistable)
.append(shuffleKey)
.append(reshuffleKey)
.append(String.valueOf(maxStack))
.append(getCountExpressions())
.append(expressionCounting)
.append(getGlobalCommands())
.append(hotkeyOnEmpty)
.append(emptyKey)
.append(selectDisplayProperty.getFormat())
.append(selectSortProperty)
.append(restrictOption)
.append(restrictExpression)
.append(shuffleCommand)
.append(reverseCommand)
.append(reverseKey);
return ID + se.getValue();
}
/** Shuffle the contents of the Deck */
public Command shuffle() {
final GamePiece[] a = new GamePiece[pieceCount];
System.arraycopy(contents, 0, a, 0, pieceCount);
final List<GamePiece> l = Arrays.asList(a);
DragBuffer.getBuffer().clear();
Collections.shuffle(l, gameModule.getRNG());
return setContents(l).append(reportCommand(shuffleMsgFormat, Resources.getString("Deck.shuffle"))); //$NON-NLS-1$
}
/**
* Return a list if pieces in the Deck in Dealable order.
* If this is an Always shuffle Deck, then shuffle the list of pieces, otherwise just
* reverse the list order so that we deal from the top.
*
* @return List of pieces in Dealable order
*/
public List<GamePiece> getOrderedPieces() {
final List<GamePiece> pieces = asList();
if (ALWAYS.equals(shuffleOption)) {
Collections.shuffle(pieces, GameModule.getGameModule().getRNG());
}
else {
Collections.reverse(pieces);
}
return pieces;
}
/**
* Return an iterator of pieces to be drawn from the Deck. Normally, a random
* piece will be drawn, but if the Deck supports it, the user may have
* specified a particular set of pieces or a fixed number of pieces to select
* with the next draw.
*/
public PieceIterator drawCards() {
final Iterator<GamePiece> it;
if (nextDraw != null) {
it = nextDraw.iterator();
}
else if (getPieceCount() == 0) {
it = Collections.emptyIterator();
}
else {
int count = Math.max(dragCount, Math.min(1, getPieceCount()));
final ArrayList<GamePiece> pieces = new ArrayList<>();
if (ALWAYS.equals(shuffleOption)) {
// Instead of shuffling the entire deck, just pick <b>count</b> random elements
final ArrayList<Integer> indices = new ArrayList<>();
for (int i = 0; i < getPieceCount(); ++i) {
indices.add(i);
}
final Random rng = gameModule.getRNG();
while (count-- > 0 && !indices.isEmpty()) {
final int i = rng.nextInt(indices.size());
final int index = indices.get(i);
indices.remove(i);
final GamePiece p = getPieceAt(index);
pieces.add(p);
}
}
else {
final Iterator<GamePiece> i = getPiecesReverseIterator();
while (count-- > 0 && i.hasNext()) pieces.add(i.next());
}
it = pieces.iterator();
}
dragCount = 0;
nextDraw = null;
return new PieceIterator(it) {
@Override
public GamePiece nextPiece() {
final GamePiece p = super.nextPiece();
/*
* Bug 12951 results in Cards going back into a Deck via Undo in an inconsistent state.
* This statement is the culprit. As far as I can tell, it is not needed as Deck.pieceRemoved()
* sets OBSCURED_BY if drawing a facedown card from a face down Deck which is the only case
* where this would be needed.
* Bug 13433
* HOWEVER, the nextPiece() iterator is used to select cards to test against property match expressions
* which historically assume that this has already been done. To maintain legacy support, we need to record
* the original OBSCURED_BY, change it, then the consumers of nextPiece() must change it back.
* Note use of scratch-pad props map in BasicPiece, no need to use persistent properties.
*/
p.setProperty(Properties.OBSCURED_BY_PRE_DRAW, p.getProperty(Properties.OBSCURED_BY));
if (faceDown) {
p.setProperty(Properties.OBSCURED_BY, NO_USER);
}
return p;
}
};
}
/** Set the contents of this Deck to a Collection of GamePieces */
protected Command setContents(Collection<GamePiece> c) {
final ChangeTracker track = new ChangeTracker(this);
removeAll();
for (final GamePiece child : c) {
insertChild(child, pieceCount);
}
return track.getChangeCommand();
}
/**
* Set the contents of this Deck to an Iterator of GamePieces
* @deprecated Use {@link #setContents(Collection)} instead.
*/
@Deprecated(since = "2020-08-06", forRemoval = true)
protected Command setContents(Iterator<GamePiece> it) {
ProblemDialog.showDeprecated("2020-08-06");
final ChangeTracker track = new ChangeTracker(this);
removeAll();
while (it.hasNext()) {
final GamePiece child = it.next();
insertChild(child, pieceCount);
}
return track.getChangeCommand();
}
@Override
public String getState() {
final SequenceEncoder se = new SequenceEncoder(';');
se.append(getMap() == null ? "null" : getMap().getIdentifier()).append(getPosition().x).append(getPosition().y); //$NON-NLS-1$
se.append(faceDown);
final SequenceEncoder se2 = new SequenceEncoder(',');
asList().forEach(gamePiece -> se2.append(gamePiece.getId()));
if (se2.getValue() != null) {
se.append(se2.getValue());
}
return se.getValue();
}
@Override
public void setState(String state) {
final SequenceEncoder.Decoder st = new SequenceEncoder.Decoder(state, ';');
final String mapId = st.nextToken();
setPosition(new Point(st.nextInt(0), st.nextInt(0)));
Map m = null;
if (!"null".equals(mapId)) { //$NON-NLS-1$
m = Map.getMapById(mapId);
if (m == null) {
ErrorDialog.dataWarning(new BadDataReport("No such map", mapId, null)); // NON-NLS
}
}
if (m != getMap()) {
if (m != null) {
m.addPiece(this);
}
else {
setMap(null);
}
}
faceDown = "true".equals(st.nextToken()); //$NON-NLS-1$
final ArrayList<GamePiece> l = new ArrayList<>();
if (st.hasMoreTokens()) {
final SequenceEncoder.Decoder st2 =
new SequenceEncoder.Decoder(st.nextToken(), ',');
while (st2.hasMoreTokens()) {
final GamePiece p = gameModule.getGameState()
.getPieceForId(st2.nextToken());
if (p != null) {
l.add(p);
}
}
}
setContents(l);
commands = null; // Force rebuild of popup menu
}
public Command setContentsFaceDown(boolean value) {
final ChangeTracker t = new ChangeTracker(this);
final Command c = new NullCommand();
faceDown = value;
return t.getChangeCommand().append(c).append(reportCommand(faceDownMsgFormat, value ? Resources.getString("Deck.face_down") : Resources.getString("Deck.face_up"))); //$NON-NLS-1$ //$NON-NLS-2$
}
/** Reverse the order of the contents of the Deck */
public Command reverse() {
final ArrayList<GamePiece> list = new ArrayList<>();
for (final Iterator<GamePiece> i = getPiecesReverseIterator(); i.hasNext(); ) {
list.add(i.next());
}
return setContents(list).append(reportCommand(
reverseMsgFormat, Resources.getString("Deck.reverse"))); //$NON-NLS-1$
}
public boolean isDrawOutline() {
return drawOutline;
}
public void setOutlineColor(Color outlineColor) {
this.outlineColor = outlineColor;
}
public void setDrawOutline(boolean drawOutline) {
this.drawOutline = drawOutline;
}
public Color getOutlineColor() {
return outlineColor;
}
public boolean isFaceDown() {
return faceDown;
}
@Override
public Command pieceAdded(GamePiece p) {
return null;
}
@Override
public Command pieceRemoved(GamePiece p) {
final ChangeTracker tracker = new ChangeTracker(p);
p.setProperty(Properties.OBSCURED_TO_OTHERS, isFaceDown() && !isDrawFaceUp());
return tracker.getChangeCommand();
}
public void setFaceDown(boolean faceDown) {
this.faceDown = faceDown;
}
@Override
public void draw(java.awt.Graphics g, int x, int y, Component obs, double zoom) {
final int count = Math.min(getPieceCount(), maxStack);
final GamePiece top = (nextDraw != null && !nextDraw.isEmpty()) ?
nextDraw.get(0) : topPiece();
if (top != null) {
final Object owner = top.getProperty(Properties.OBSCURED_BY);
top.setProperty(Properties.OBSCURED_BY, faceDown ? NO_USER : null);
final Color blankColor = getBlankColor();
final Rectangle r = top.getShape().getBounds();
r.setLocation(x + (int) (zoom * (r.x)), y + (int) (zoom * (r.y)));
r.setSize((int) (zoom * r.width), (int) (zoom * r.height));
for (int i = 0; i < count - 1; ++i) {
if (blankColor != null) {
g.setColor(blankColor);
g.fillRect(r.x + (int) (zoom * 2 * i), r.y - (int) (zoom * 2 * i), r.width, r.height);
g.setColor(Color.black);
g.drawRect(r.x + (int) (zoom * 2 * i), r.y - (int) (zoom * 2 * i), r.width, r.height);
}
else if (faceDown) {
top.draw(g, x + (int) (zoom * 2 * i), y - (int) (zoom * 2 * i), obs, zoom);
}
else {
getPieceAt(count - i - 1).draw(g, x + (int) (zoom * 2 * i), y - (int) (zoom * 2 * i), obs, zoom);
}
}
top.draw(g, x + (int) (zoom * 2 * (count - 1)), y - (int) (zoom * 2 * (count - 1)), obs, zoom);
top.setProperty(Properties.OBSCURED_BY, owner);
}
else {
if (drawOutline) {
final Rectangle r = boundingBox();
r.setLocation(x + (int) (zoom * r.x), y + (int) (zoom * r.y));
r.setSize((int) (zoom * r.width), (int) (zoom * r.height));
g.setColor(outlineColor);
g.drawRect(r.x, r.y, r.width, r.height);
}
}
}
/**
* The color used to draw boxes representing cards underneath the top one. If
* null, then draw each card normally for face-up decks, and duplicate the top
* card for face-down decks
*/
protected Color getBlankColor() {
Color c = Color.white;
if (getMap() != null) {
c = getMap().getStackMetrics().getBlankColor();
}
return c;
}
@Override
public StackMetrics getStackMetrics() {
return deckStackMetrics;
}
@Override
public Rectangle boundingBox() {
final GamePiece top = topPiece();
final Dimension d = top == null ? size : top.getShape().getBounds().getSize();
final Rectangle r = new Rectangle(new Point(), d);
r.translate(-r.width / 2, -r.height / 2);
final int n = getMaximumVisiblePieceCount();
for (int i = 0; i < n; ++i) {
r.y -= 2;
r.height += 2;
r.width += 2;
}
return r;
}
@Override
public Shape getShape() {
return boundingBox();
}
@Override
public Object getProperty(Object key) {
Object value = null;
if (Properties.NO_STACK.equals(key)) {
value = Boolean.TRUE;
}
else if (Properties.KEY_COMMANDS.equals(key)) {
value = getKeyCommands();
}
return value;
}
protected KeyCommand[] getKeyCommands() {
if (commands == null) {
final ArrayList<KeyCommand> l = new ArrayList<>();
KeyCommand c;
if (USE_MENU.equals(shuffleOption)) {
c = new KeyCommand(shuffleCommand, getShuffleKey(), this) {
private static final long serialVersionUID = 1L;
@Override
public void actionPerformed(ActionEvent e) {
gameModule.sendAndLog(shuffle());
repaintMap();
}
};
l.add(c);
}
if (reshuffleCommand.length() > 0) {
c = new KeyCommand(reshuffleCommand, getReshuffleKey(), this) {
private static final long serialVersionUID = 1L;
@Override
public void actionPerformed(ActionEvent evt) {
gameModule.sendAndLog(sendToDeck());
repaintMap();
}
};
l.add(c);
}
if (USE_MENU.equals(faceDownOption)) {
final KeyCommand faceDownAction = new KeyCommand(faceDown ? Resources.getString("Deck.face_up") : Resources.getString("Deck.face_down"), NamedKeyStroke.NULL_KEYSTROKE, this) { //$NON-NLS-1$ //$NON-NLS-2$
private static final long serialVersionUID = 1L;
@Override
public void actionPerformed(ActionEvent e) {
final Command c = setContentsFaceDown(!faceDown);
gameModule.sendAndLog(c);
repaintMap();
}
};
l.add(faceDownAction);
}
if (reversible) {
c = new KeyCommand(reverseCommand, NamedKeyStroke.NULL_KEYSTROKE, this) { //$NON-NLS-1$
private static final long serialVersionUID = 1L;
@Override
public void actionPerformed(ActionEvent e) {
final Command c = reverse();
gameModule.sendAndLog(c);
repaintMap();
}
};
l.add(c);
}
if (allowMultipleDraw) {
c = new KeyCommand(Resources.getString("Deck.draw_multiple"), NamedKeyStroke.NULL_KEYSTROKE, this) { //$NON-NLS-1$
private static final long serialVersionUID = 1L;
@Override
public void actionPerformed(ActionEvent e) {
promptForDragCount();
}
};
l.add(c);
}
if (allowSelectDraw) {
c = new KeyCommand(Resources.getString("Deck.draw_specific"), NamedKeyStroke.NULL_KEYSTROKE, this) { //$NON-NLS-1$
private static final long serialVersionUID = 1L;
@Override
public void actionPerformed(ActionEvent e) {
promptForNextDraw();
repaintMap();
}
};
l.add(c);
}
if (persistable) {
c = new KeyCommand(Resources.getString(Resources.SAVE), NamedKeyStroke.NULL_KEYSTROKE, this) {
private static final long serialVersionUID = 1L;
@Override
public void actionPerformed(ActionEvent e) {
gameModule.sendAndLog(saveDeck());
repaintMap();
}
};
l.add(c);
c = new KeyCommand(Resources.getString(Resources.LOAD), NamedKeyStroke.NULL_KEYSTROKE, this) {
private static final long serialVersionUID = 1L;
@Override
public void actionPerformed(ActionEvent e) {
gameModule.sendAndLog(loadDeck());
repaintMap();
}
};
l.add(c);
}
for (final DeckGlobalKeyCommand cmd : globalCommands) {
l.add(cmd.getKeyCommand(this));
}
commands = l.toArray(new KeyCommand[0]);
}
for (final KeyCommand command : commands) {
if (Resources.getString("Deck.face_up").equals(command.getValue(Action.NAME)) && !faceDown) { //$NON-NLS-1$
command.putValue(Action.NAME, Resources.getString("Deck.face_down")); //$NON-NLS-1$
}
else if (Resources.getString("Deck.face_down").equals(command.getValue(Action.NAME)) && faceDown) { //$NON-NLS-1$
command.putValue(Action.NAME, Resources.getString("Deck.face_up")); //$NON-NLS-1$
}
}
return commands;
}
/*
* Format command report as per module designers setup.
*/
protected Command reportCommand(String format, String commandName) {
Command c = null;
final FormattedString reportFormat = new FormattedString(format);
reportFormat.setProperty(DrawPile.DECK_NAME, getLocalizedDeckName());
reportFormat.setProperty(DrawPile.COMMAND_NAME, commandName);
final String rep = reportFormat.getLocalizedText();
if (rep.length() > 0) {
c = new Chatter.DisplayText(gameModule.getChatter(), "* " + rep); //$NON-NLS-1$
c.execute();
}
return c;
}
public void promptForDragCount() {
while (true) {
final String s = JOptionPane.showInputDialog(GameModule.getGameModule().getPlayerWindow(),
Resources.getString("Deck.enter_the_number")); //$NON-NLS-1$
if (s != null) {
try {
dragCount = Integer.parseInt(s);
dragCount = Math.min(dragCount, getPieceCount());
if (dragCount >= 0) break;
}
catch (NumberFormatException ex) {
// Ignore if user doesn't enter a number
}
}
else {
break;
}
}
}
protected void promptForNextDraw() {
final JDialog d = new JDialog((Frame) SwingUtilities.getAncestorOfClass(Frame.class, map.getView()), true);
d.setTitle(Resources.getString("Deck.draw")); //$NON-NLS-1$
d.setLayout(new BoxLayout(d.getContentPane(), BoxLayout.Y_AXIS));
class AvailablePiece implements Comparable<AvailablePiece> {
private final GamePiece piece;
public AvailablePiece(GamePiece piece) {
this.piece = piece;
}
@Override
public int compareTo(AvailablePiece other) {
if (other == null) return 1;
final String otherProperty =
(String) other.piece.getProperty(selectSortProperty);
if (otherProperty == null) return 1;
final String myProperty =
(String) piece.getProperty(selectSortProperty);
if (myProperty == null) return -1;
return -otherProperty.compareTo(myProperty);
}
@Override
public String toString() {
return selectDisplayProperty.getText(piece);
}
@Override
public boolean equals(Object o) {
if (! (o instanceof AvailablePiece)) return false;
return ((AvailablePiece)o).piece.equals(piece);
}
}
final AvailablePiece[] pieces = new AvailablePiece[getPieceCount()];
for (int i = 0; i < pieces.length; ++i) {
pieces[pieces.length - i - 1] = new AvailablePiece(getPieceAt(i));
}
if (selectSortProperty != null && selectSortProperty.length() > 0) {
Arrays.sort(pieces);
}
final JList<AvailablePiece> list = new JList<>(pieces);
list.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
d.add(new ScrollPane(list));
d.add(new JLabel(Resources.getString("Deck.select_cards"))); //$NON-NLS-1$
d.add(new JLabel(Resources.getString("Deck.then_click"))); //$NON-NLS-1$
final Box box = Box.createHorizontalBox();
JButton b = new JButton(Resources.getString(Resources.OK));
b.addActionListener(e -> {
final int[] selection = list.getSelectedIndices();
if (selection.length > 0) {
nextDraw = new ArrayList<>();
for (final int value : selection) {
nextDraw.add(pieces[value].piece);
}
}
else {
nextDraw = null;
}
d.dispose();
});
box.add(b);
b = new JButton(Resources.getString(Resources.CANCEL));
b.addActionListener(e -> d.dispose());
box.add(b);
d.add(box);
d.pack();
d.setLocationRelativeTo(d.getOwner());
d.setVisible(true);
}
/**
* Combine the contents of this Deck with the contents of the deck specified
* by {@link #reshuffleTarget}
*/
public Command sendToDeck() {
Command c = null;
nextDraw = null;
final DrawPile target = DrawPile.findDrawPile(reshuffleTarget);
if (target != null) {
if (reshuffleMsgFormat.length() > 0) {
c = reportCommand(reshuffleMsgFormat, reshuffleCommand);
if (c == null) {
c = new NullCommand();
}
}
else {
c = new NullCommand();
}
// move cards to deck
final int cnt = getPieceCount() - 1;
for (int i = cnt; i >= 0; i--) {
c.append(target.addToContents(getPieceAt(i)));
}
}
return c;
}
@Override
public boolean isExpanded() {
return false;
}
/** Return true if this deck can be saved to and loaded from a file on disk */
public boolean isPersistable() {
return persistable;
}
public void setPersistable(boolean persistable) {
this.persistable = persistable;
}
private File getSaveFileName() {
final FileChooser fc = gameModule.getFileChooser();
final File sf = fc.getSelectedFile();
if (sf != null) {
String name = sf.getPath();
final int index = name.lastIndexOf('.');
if (index > 0) {
name = name.substring(0, index) + ".sav"; //$NON-NLS-1$
fc.setSelectedFile(new File(name));
}
}
if (fc.showSaveDialog(map.getView()) != FileChooser.APPROVE_OPTION)
return null;
File outputFile = fc.getSelectedFile();
if (outputFile != null &&
outputFile.exists() &&
shouldConfirmOverwrite() &&
JOptionPane.NO_OPTION ==
JOptionPane.showConfirmDialog(gameModule.getPlayerWindow(),
Resources.getString("Deck.overwrite", outputFile.getName()), Resources.getString("Deck.file_exists"), //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
JOptionPane.YES_NO_OPTION)) {
outputFile = null;
}
return outputFile;
}
private boolean shouldConfirmOverwrite() {
return System.getProperty("os.name").trim().equalsIgnoreCase("linux"); //$NON-NLS-1$ //$NON-NLS-2$
}
private Command saveDeck() {
final Command c = new NullCommand();
gameModule.warn(Resources.getString("Deck.saving_deck")); //$NON-NLS-1$
final File saveFile = getSaveFileName();
try {
if (saveFile != null) {
saveDeck(saveFile);
gameModule.warn(Resources.getString("Deck.deck_saved")); //$NON-NLS-1$
}
else {
gameModule.warn(Resources.getString("Deck.save_canceled")); //$NON-NLS-1$
}
}
catch (IOException e) {
WriteErrorDialog.error(e, saveFile);
}
return c;
}
public void saveDeck(File f) throws IOException {
Command comm = new LoadDeckCommand(null);
for (final GamePiece p : asList()) {
p.setMap(null);
comm = comm.append(new AddPiece(p));
}
try (Writer w = Files.newBufferedWriter(f.toPath(), StandardCharsets.UTF_8)) {
gameModule.addCommandEncoder(commandEncoder);
w.write(gameModule.encode(comm));
gameModule.removeCommandEncoder(commandEncoder);
}
}
private File getLoadFileName() {
final FileChooser fc = gameModule.getFileChooser();
fc.selectDotSavFile();
if (fc.showOpenDialog(map.getView()) != FileChooser.APPROVE_OPTION)
return null;
return fc.getSelectedFile();
}
private Command loadDeck() {
Command c = new NullCommand();
gameModule.warn(Resources.getString("Deck.loading_deck")); //$NON-NLS-1$
final File loadFile = getLoadFileName();
try {
if (loadFile != null) {
c = loadDeck(loadFile);
gameModule.warn(Resources.getString("Deck.deck_loaded")); //$NON-NLS-1$
}
else {
gameModule.warn(Resources.getString("Deck.load_canceled")); //$NON-NLS-1$
}
}
catch (IOException e) {
ReadErrorDialog.error(e, loadFile);
}
return c;
}
public Command loadDeck(File f) throws IOException {
final String ds = Files.readString(f.toPath(), StandardCharsets.UTF_8);
gameModule.addCommandEncoder(commandEncoder);
Command c = gameModule.decode(ds);
gameModule.removeCommandEncoder(commandEncoder);
if (c instanceof LoadDeckCommand) {
/*
* A LoadDeckCommand doesn't specify the deck to be changed (since the
* saved deck can be loaded into any deck) so the Command we send to other
* players is a ChangePiece command for this deck, which we need to place
* after the AddPiece commands for the contents
*/
final ChangeTracker t = new ChangeTracker(this);
c.execute();
final Command[] sub = c.getSubCommands();
c = new NullCommand();
for (final Command command : sub) {
c.append(command);
}
c.append(t.getChangeCommand());
updateCountsAll();
}
else {
gameModule.warn(Resources.getString("Deck.not_a_saved_deck", f.getName())); //$NON-NLS-1$
c = null;
}
return c;
}
/**
* Command to set the contents of this deck from a saved file. The contents
* are saved with whatever id's the pieces have in the game when the deck was
* saved, but new copies are created when the deck is re-loaded.
*
* @author rkinney
*
*/
protected static class LoadDeckCommand extends Command {
public static final String PREFIX = "DECK\t"; //$NON-NLS-1$
private final Deck target;
public LoadDeckCommand(Deck target) {
this.target = target;
}
@Override
protected void executeCommand() {
target.removeAll();
final Command[] sub = getSubCommands();
for (final Command command : sub) {
if (command instanceof AddPiece) {
final GamePiece p = ((AddPiece) command).getTarget();
// We set the id to null so that the piece will get a new id
// when the AddPiece command executes
p.setId(null);
target.add(p);
}
}
}
public String getTargetId() {
return target == null ? "" : target.getId(); //$NON-NLS-1$
}
@Override
protected Command myUndoCommand() {
return null;
}
}
/**
* An object that parses expression strings from the config window
*/
public static class CountExpression {
private String fullstring;
private String name;
private String expression;
public CountExpression(String expressionString) {
final String[] split = expressionString.split("\\s*:\\s*", 2); //$NON-NLS-1$
if (split.length == 2) {
name = split[0];
expression = split[1];
fullstring = expressionString;
}
}
public String getName() {
return name;
}
public String getExpression() {
return expression;
}
public String getFullString() {
return fullstring;
}
}
/**
* Return the number of cards to be returned by next call to
* {@link #drawCards()}.
*/
public int getDragCount() {
return dragCount;
}
/**
* Set the number of cards to be returned by next call to
* {@link #drawCards()}.
*
* @param dragCount number of cards to be returned
*/
public void setDragCount(int dragCount) {
this.dragCount = dragCount;
}
public void setSelectDisplayProperty(String promptDisplayProperty) {
this.selectDisplayProperty.setFormat(promptDisplayProperty);
}
public void setSelectSortProperty(String promptSortProperty) {
this.selectSortProperty = promptSortProperty;
}
public String getSelectDisplayProperty() {
return selectDisplayProperty.getFormat();
}
public String getSelectSortProperty() {
return selectSortProperty;
}
protected void repaintMap() {
if (map != null) {
map.repaint();
}
}
}
| vassal-app/src/main/java/VASSAL/counters/Deck.java | /*
*
* Copyright (c) 2004-2012 by Rodney Kinney, Brent Easton
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License (LGPL) as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this library; if not, copies are available
* at http://www.opensource.org.
*/
package VASSAL.counters;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Frame;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.Shape;
import java.awt.event.ActionEvent;
import java.io.File;
import java.io.IOException;
import java.io.Writer;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Objects;
import java.util.Random;
import javax.swing.Action;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.KeyStroke;
import javax.swing.ListSelectionModel;
import javax.swing.SwingUtilities;
import VASSAL.build.BadDataReport;
import VASSAL.build.GameModule;
import VASSAL.build.module.Chatter;
import VASSAL.build.module.Map;
import VASSAL.build.module.PlayerRoster;
import VASSAL.build.module.map.DeckGlobalKeyCommand;
import VASSAL.build.module.map.DrawPile;
import VASSAL.build.module.map.StackMetrics;
import VASSAL.build.module.properties.MutableProperty;
import VASSAL.build.module.properties.PropertySource;
import VASSAL.command.AddPiece;
import VASSAL.command.ChangeTracker;
import VASSAL.command.Command;
import VASSAL.command.CommandEncoder;
import VASSAL.command.NullCommand;
import VASSAL.configure.ColorConfigurer;
import VASSAL.configure.PropertyExpression;
import VASSAL.i18n.Localization;
import VASSAL.i18n.Resources;
import VASSAL.tools.ErrorDialog;
import VASSAL.tools.FormattedString;
import VASSAL.tools.NamedKeyStroke;
import VASSAL.tools.NamedKeyStrokeListener;
import VASSAL.tools.ReadErrorDialog;
import VASSAL.tools.ScrollPane;
import VASSAL.tools.SequenceEncoder;
import VASSAL.tools.WriteErrorDialog;
import VASSAL.tools.filechooser.FileChooser;
import VASSAL.tools.ProblemDialog;
/**
* A collection of pieces that behaves like a deck, i.e.: Doesn't move.
* Can't be expanded. Can be shuffled. Can be turned face-up and face-down.
*/
public class Deck extends Stack implements PlayerRoster.SideChangeListener {
public static final String ID = "deck;"; //$NON-NLS-1$
public static final String ALWAYS = "Always"; // NON-NLS
public static final String NEVER = "Never"; // NON-NLS
public static final String USE_MENU = "Via right-click Menu"; // NON-NLS
public static final String NO_USER = "nobody"; // Dummy user ID for turning // NON-NLS
protected static final StackMetrics deckStackMetrics = new StackMetrics(false, 2, 2, 2, 2);
// cards face down
protected boolean drawOutline = true;
protected Color outlineColor = Color.black;
protected Dimension size = new Dimension(40, 40);
protected boolean shuffle = true;
protected String faceDownOption = ALWAYS;
protected String shuffleOption = ALWAYS;
protected String shuffleCommand = "";
protected boolean allowMultipleDraw = false;
protected boolean allowSelectDraw = false;
protected boolean reversible = false;
protected String reshuffleCommand = ""; //$NON-NLS-1$
protected String reshuffleTarget;
protected String reshuffleMsgFormat;
protected NamedKeyStrokeListener reshuffleListener;
protected NamedKeyStroke reshuffleKey;
protected String reverseMsgFormat;
protected String reverseCommand;
protected NamedKeyStroke reverseKey;
protected NamedKeyStrokeListener reverseListener;
protected String shuffleMsgFormat;
protected NamedKeyStrokeListener shuffleListener;
protected NamedKeyStroke shuffleKey;
protected String faceDownMsgFormat;
protected boolean drawFaceUp;
protected boolean persistable;
protected FormattedString selectDisplayProperty = new FormattedString("$" + BasicPiece.BASIC_NAME + "$");
protected String selectSortProperty = "";
protected MutableProperty.Impl countProperty =
new MutableProperty.Impl("", this);
protected List<MutableProperty.Impl> expressionProperties = new ArrayList<>();
protected String deckName;
protected String localizedDeckName;
protected boolean faceDown;
protected int dragCount = 0;
protected int maxStack = 10;
protected CountExpression[] countExpressions = new CountExpression[0];
protected boolean expressionCounting = false;
protected List<GamePiece> nextDraw = null;
protected KeyCommand[] commands;
protected List<DeckGlobalKeyCommand> globalCommands = new ArrayList<>();
protected boolean hotkeyOnEmpty;
protected NamedKeyStroke emptyKey;
protected boolean restrictOption;
protected PropertyExpression restrictExpression = new PropertyExpression();
protected PropertySource propertySource;
/**
* Special {@link CommandEncoder} to handle loading/saving Decks from files.
*/
protected CommandEncoder commandEncoder = new CommandEncoder() {
/**
* Deserializes a Deck loaded from a file, turning it into a LoadDeckCommand.
* @param command String contents of deck
* @return {@link LoadDeckCommand} to put the specified contents in the deck
*/
@Override
public Command decode(String command) {
if (!command.startsWith(LoadDeckCommand.PREFIX)) {
return null;
}
return new LoadDeckCommand(Deck.this);
}
/**
* Serializes a LoadDeckCommand
* @param c LoadDeckCommand
* @return string form of command
*/
@Override
public String encode(Command c) {
if (!(c instanceof LoadDeckCommand)) {
return null;
}
return LoadDeckCommand.PREFIX;
}
};
private final GameModule gameModule;
/**
* Not for internal use, but required for initial build of module
*
* @deprecated use {@link #Deck(GameModule)}
*/
@Deprecated
public Deck() {
this(GameModule.getGameModule());
}
/**
* @deprecated use {@link #Deck(GameModule, String)}
*/
@Deprecated(since = "2020-08-06", forRemoval = true)
public Deck(String type) {
this(GameModule.getGameModule(), type);
ProblemDialog.showDeprecated("2020-08-06");
}
/**
* @deprecated use {@link #Deck(GameModule, String, PropertySource)}
*/
@Deprecated(since = "2020-08-06", forRemoval = true)
public Deck(String type, PropertySource source) {
this(GameModule.getGameModule(), type, source);
ProblemDialog.showDeprecated("2020-08-06");
}
/**
* Create an empty deck
* @param gameModule The game module
*/
public Deck(GameModule gameModule) {
this(gameModule, ID);
}
/**
* Creates an empty deck using specified type information
* @param gameModule The game module
* @param type Type information for the deck (the configuration information that does not change during the game)
*/
public Deck(GameModule gameModule, String type) {
this.gameModule = gameModule;
mySetType(type);
}
/**
* Creates an empty deck using specified type information
* @param gameModule The game module
* @param type Type information for the deck (the configuration information that does not change during the game)
* @param source PropertySource
*/
public Deck(GameModule gameModule, String type, PropertySource source) {
this(gameModule, type);
propertySource = source;
}
/**
* Sets the Deck's property source
* @param source PropertySource
*/
public void setPropertySource(PropertySource source) {
propertySource = source;
if (globalCommands != null) {
for (final DeckGlobalKeyCommand globalCommand : globalCommands) {
globalCommand.setPropertySource(propertySource);
}
}
}
/**
* Listener for when the local player changes side. Updates all of our counts of expressions of pieces configured to be counted.
* @param oldSide local player's old side
* @param newSide local player's new side
*/
@Override
public void sideChanged(String oldSide, String newSide) {
updateCountsAll();
}
/**
* Adds a Deck Global Key Command (DGKC).
* @param globalCommand The command to add
*/
public void addGlobalKeyCommand(DeckGlobalKeyCommand globalCommand) {
globalCommands.add(globalCommand);
}
/**
* Removes a Deck Global Key Command (DGKC).
* @param globalCommand The command to remove
*/
public void removeGlobalKeyCommand(DeckGlobalKeyCommand globalCommand) {
globalCommands.remove(globalCommand);
}
/**
* @return A list of Deck Global Key Commands for this deck, serialized by their encoder.
*/
protected String[] getGlobalCommands() {
final String[] commands = new String[globalCommands.size()];
for (int i = 0; i < globalCommands.size(); i++) {
commands[i] = globalCommands.get(i).encode();
}
return commands;
}
/**
* Sets the list of Deck Global Key Commands for this deck
* @param commands The list of commands to set (in serialized string form)
*/
protected void setGlobalCommands(String[] commands) {
globalCommands = new ArrayList<>(commands.length);
for (final String command : commands) {
globalCommands.add(new DeckGlobalKeyCommand(command, propertySource));
}
}
/**
* Update map-level count properties for all "expressions" of pieces that are configured
* to be counted. These are held in the String[] countExpressions.
*/
private void updateCountsAll() {
if (!doesExpressionCounting() || getMap() == null) {
return;
}
//Clear out all of the registered count expressions
for (int index = 0; index < countExpressions.length; index++) {
expressionProperties.get(index).setPropertyValue("0"); //$NON-NLS-1$
}
//Increase all of the pieces with expressions specified in this deck
asList().stream()
.filter(Objects::nonNull)
.forEach(p -> updateCounts(p, true));
}
/**
* Update map-level count property for a piece located at index
* @param index Index (within the Deck, counting from the top) of the piece whose count to update
*/
private void updateCounts(int index) {
if (!doesExpressionCounting()) {
return;
}
if (index >= 0 && index < getPieceCount()) {
final GamePiece p = getPieceAt(index);
if (p == null) {
//can't figure out the piece, do a full update
updateCountsAll();
}
else {
updateCounts(p, false);
}
}
else {
//can't figure out the piece, do a full update
updateCountsAll();
}
}
/**
* Update map-level count property for a piece
* @param p Game piece to update counts for
* @param increase if true, increase the count; if false, decrease.
*/
private void updateCounts(GamePiece p, boolean increase) {
if (!doesExpressionCounting() || getMap() == null) {
return;
}
//test all the expressions for this deck
for (int index = 0; index < countExpressions.length; index++) {
final MutableProperty.Impl prop = expressionProperties.get(index);
final FormattedString formatted =
new FormattedString(countExpressions[index].getExpression());
final PieceFilter f = PropertiesPieceFilter.parse(formatted.getText());
if (f.accept(p)) {
final String mapProperty = prop.getPropertyValue();
if (mapProperty != null) {
int newValue = Integer.decode(mapProperty);
if (increase) {
newValue++;
}
else {
newValue--;
}
prop.setPropertyValue(String.valueOf(newValue));
}
}
}
}
/**
* Set the <deckName>_numPieces property in the containing Map
*/
protected void fireNumCardsProperty() {
countProperty.setPropertyValue(String.valueOf(pieceCount));
}
/**
* Inserts a piece into a specific position into the Deck (counting down from the top)
* @param p Piece to insert
* @param index "How many cards down into the Deck" to put it.
*/
@Override
protected void insertPieceAt(GamePiece p, int index) {
super.insertPieceAt(p, index);
updateCounts(p, true);
fireNumCardsProperty();
}
/**
* Removes a piece from a specific location in the deck
* @param index Piece to remove, counting down from the top
*/
@Override
protected void removePieceAt(int index) {
final int startCount = pieceCount;
updateCounts(index);
super.removePieceAt(index);
fireNumCardsProperty();
if (hotkeyOnEmpty && emptyKey != null && startCount > 0 && pieceCount == 0) {
gameModule.fireKeyStroke(emptyKey);
}
}
/**
* Removes all pieces from the Deck.
*/
@Override
public void removeAll() {
super.removeAll();
updateCountsAll();
fireNumCardsProperty();
}
/**
* Sets the Map this Deck appears on
* @param map Map to assign Deck to
*/
@Override
public void setMap(Map map) {
if (map != getMap()) {
countProperty.removeFromContainer();
if (map != null) countProperty.addTo(map);
for (final MutableProperty.Impl prop : expressionProperties) {
prop.removeFromContainer();
if (map != null) prop.addTo(map);
}
}
super.setMap(map);
updateCountsAll();
fireNumCardsProperty();
}
public void addListeners() {
if (shuffleListener == null) {
shuffleListener = new NamedKeyStrokeListener(e -> {
gameModule.sendAndLog(shuffle());
repaintMap();
});
gameModule.addKeyStrokeListener(shuffleListener);
shuffleListener.setKeyStroke(getShuffleKey());
}
if (reshuffleListener == null) {
reshuffleListener = new NamedKeyStrokeListener(e -> {
gameModule.sendAndLog(sendToDeck());
repaintMap();
});
gameModule.addKeyStrokeListener(reshuffleListener);
reshuffleListener.setKeyStroke(getReshuffleKey());
}
if (reverseListener == null) {
reverseListener = new NamedKeyStrokeListener(e -> {
gameModule.sendAndLog(reverse());
repaintMap();
});
gameModule.addKeyStrokeListener(reverseListener);
reverseListener.setKeyStroke(getReverseKey());
}
gameModule.addSideChangeListenerToPlayerRoster(this);
}
public void removeListeners() {
if (shuffleListener != null) {
gameModule.removeKeyStrokeListener(shuffleListener);
shuffleListener = null;
}
if (reshuffleListener != null) {
gameModule.removeKeyStrokeListener(reshuffleListener);
reshuffleListener = null;
}
if (reverseListener != null) {
gameModule.removeKeyStrokeListener(reverseListener);
reverseListener = null;
}
gameModule.removeSideChangeListenerFromPlayerRoster(this);
}
/** Sets the information for this Deck. See {@link Decorator#myGetType}
* @param type a serialized configuration string to
* set the "type information" of this Deck, which is
* information that doesn't change during the course of
* a single game (e.g. Image Files, Context Menu strings,
* etc, rules about when deck is shuffled, whether it is
* face-up or face down, etc).
*/
protected void mySetType(String type) {
final SequenceEncoder.Decoder st = new SequenceEncoder.Decoder(type, ';');
st.nextToken();
drawOutline = st.nextBoolean(true);
outlineColor = ColorConfigurer.stringToColor(st.nextToken("0,0,0")); //$NON-NLS-1$
size.setSize(st.nextInt(40), st.nextInt(40));
faceDownOption = st.nextToken("Always"); //$NON-NLS-1$
shuffleOption = st.nextToken("Always"); //$NON-NLS-1$
allowMultipleDraw = st.nextBoolean(true);
allowSelectDraw = st.nextBoolean(true);
reversible = st.nextBoolean(true);
reshuffleCommand = st.nextToken(""); //$NON-NLS-1$
reshuffleTarget = st.nextToken(""); //$NON-NLS-1$
reshuffleMsgFormat = st.nextToken(""); //$NON-NLS-1$
setDeckName(st.nextToken(Resources.getString("Deck.deck")));
shuffleMsgFormat = st.nextToken(""); //$NON-NLS-1$
reverseMsgFormat = st.nextToken(""); //$NON-NLS-1$
faceDownMsgFormat = st.nextToken(""); //$NON-NLS-1$
drawFaceUp = st.nextBoolean(false);
persistable = st.nextBoolean(false);
shuffleKey = st.nextNamedKeyStroke(null);
reshuffleKey = st.nextNamedKeyStroke(null);
maxStack = st.nextInt(10);
setCountExpressions(st.nextStringArray(0));
expressionCounting = st.nextBoolean(false);
setGlobalCommands(st.nextStringArray(0));
hotkeyOnEmpty = st.nextBoolean(false);
emptyKey = st.nextNamedKeyStroke(null);
selectDisplayProperty.setFormat(st.nextToken("$" + BasicPiece.BASIC_NAME + "$"));
selectSortProperty = st.nextToken("");
restrictOption = st.nextBoolean(false);
restrictExpression.setExpression(st.nextToken(""));
shuffleCommand = st.nextToken(Resources.getString("Deck.shuffle"));
reverseCommand = st.nextToken(Resources.getString("Deck.reverse"));
reverseKey = st.nextNamedKeyStroke(null);
final DrawPile myPile = DrawPile.findDrawPile(getDeckName());
// If a New game/Load Game is starting, set this Deck into the matching DrawPile
// If a Load Continuation is starting, ignore this Deck and let the DrawPile continue with the existing Deck.
// Combined fix for bugs 4507, 10249 & 13461
if (myPile != null && ! GameModule.getGameModule().getGameState().isGameStarted()) {
myPile.setDeck(this);
}
}
public String getFaceDownOption() {
return faceDownOption;
}
/**
* @return true if cards are turned face up when drawn from this deck
*/
public boolean isDrawFaceUp() {
return drawFaceUp;
}
public void setDrawFaceUp(boolean drawFaceUp) {
this.drawFaceUp = drawFaceUp;
}
public void setFaceDownOption(String faceDownOption) {
this.faceDownOption = faceDownOption;
faceDown = !faceDownOption.equals(NEVER);
}
public Dimension getSize() {
return size;
}
public void setSize(Dimension size) {
this.size.setSize(size);
}
public String getShuffleOption() {
return shuffleOption;
}
public void setShuffleOption(String shuffleOption) {
this.shuffleOption = shuffleOption;
}
public boolean isShuffle() {
return shuffle;
}
public int getMaxStack() {
return maxStack;
}
@Override
public int getMaximumVisiblePieceCount() {
return Math.min(pieceCount, maxStack);
}
public String[] getCountExpressions() {
final String[] fullstrings = new String[countExpressions.length];
for (int index = 0; index < countExpressions.length; index++) {
fullstrings[index] = countExpressions[index].getFullString();
}
return fullstrings;
}
public boolean doesExpressionCounting() {
return expressionCounting;
}
public String getFaceDownMsgFormat() {
return faceDownMsgFormat;
}
public void setFaceDownMsgFormat(String faceDownMsgFormat) {
this.faceDownMsgFormat = faceDownMsgFormat;
}
public String getReverseMsgFormat() {
return reverseMsgFormat;
}
public void setReverseMsgFormat(String reverseMsgFormat) {
this.reverseMsgFormat = reverseMsgFormat;
}
public String getReverseCommand() {
return reverseCommand;
}
public void setReverseCommand(String s) {
reverseCommand = s;
}
public NamedKeyStroke getReverseKey() {
return reverseKey;
}
public void setReverseKey(NamedKeyStroke reverseKey) {
this.reverseKey = reverseKey;
}
public String getShuffleMsgFormat() {
return shuffleMsgFormat;
}
public void setShuffleMsgFormat(String shuffleMsgFormat) {
this.shuffleMsgFormat = shuffleMsgFormat;
}
public NamedKeyStroke getShuffleKey() {
return shuffleKey;
}
public void setShuffleKey(NamedKeyStroke shuffleKey) {
this.shuffleKey = shuffleKey;
}
public String getShuffleCommand() {
return shuffleCommand;
}
public void setShuffleCommand(String s) {
shuffleCommand = s;
}
public void setShuffle(boolean shuffle) {
this.shuffle = shuffle;
}
public boolean isAllowMultipleDraw() {
return allowMultipleDraw;
}
public void setAllowMultipleDraw(boolean allowMultipleDraw) {
this.allowMultipleDraw = allowMultipleDraw;
}
public boolean isAllowSelectDraw() {
return allowSelectDraw;
}
public void setMaxStack(int maxStack) {
this.maxStack = maxStack;
}
public void setCountExpressions(String[] countExpressionsString) {
final CountExpression[] c = new CountExpression[countExpressionsString.length];
int goodExpressionCount = 0;
for (int index = 0; index < countExpressionsString.length; index++) {
final CountExpression n = new CountExpression(countExpressionsString[index]);
if (n.getName() != null) {
c[index] = n;
goodExpressionCount++;
}
}
this.countExpressions = Arrays.copyOf(c, goodExpressionCount);
while (countExpressions.length > expressionProperties.size()) {
expressionProperties.add(new MutableProperty.Impl("", this));
}
for (int i = 0; i < countExpressions.length; i++) {
expressionProperties.get(i).setPropertyName(
deckName + "_" + countExpressions[i].getName());
}
}
public void setExpressionCounting(boolean expressionCounting) {
this.expressionCounting = expressionCounting;
}
public void setAllowSelectDraw(boolean allowSelectDraw) {
this.allowSelectDraw = allowSelectDraw;
}
public boolean isReversible() {
return reversible;
}
public void setReversible(boolean reversible) {
this.reversible = reversible;
}
public void setDeckName(String n) {
if (Localization.getInstance().isTranslationInProgress()) {
localizedDeckName = n;
}
else {
deckName = n;
}
countProperty.setPropertyName(deckName + "_numPieces"); // NON-NLS
for (int i = 0; i < countExpressions.length; ++i) {
expressionProperties.get(i).setPropertyName(
deckName + "_" + countExpressions[i].getName());
}
}
public String getDeckName() {
return deckName;
}
public String getLocalizedDeckName() {
return localizedDeckName == null ? deckName : localizedDeckName;
}
/**
* @return The popup menu text for the command that sends the entire deck to another deck
*/
public String getReshuffleCommand() {
return reshuffleCommand;
}
public void setReshuffleCommand(String reshuffleCommand) {
this.reshuffleCommand = reshuffleCommand;
}
public NamedKeyStroke getReshuffleKey() {
return reshuffleKey;
}
public void setReshuffleKey(NamedKeyStroke reshuffleKey) {
this.reshuffleKey = reshuffleKey;
}
/**
* The name of the {@link VASSAL.build.module.map.DrawPile} to which the
* contents of this deck will be sent when the reshuffle command is selected
*/
public String getReshuffleTarget() {
return reshuffleTarget;
}
public void setReshuffleTarget(String reshuffleTarget) {
this.reshuffleTarget = reshuffleTarget;
}
/**
* @return The message to send to the chat window when the deck is reshuffled to another deck
*/
public String getReshuffleMsgFormat() {
return reshuffleMsgFormat;
}
public void setReshuffleMsgFormat(String reshuffleMsgFormat) {
this.reshuffleMsgFormat = reshuffleMsgFormat;
}
public boolean isHotkeyOnEmpty() {
return hotkeyOnEmpty;
}
public void setHotkeyOnEmpty(boolean b) {
hotkeyOnEmpty = b;
}
@Deprecated(since = "2020-08-06", forRemoval = true)
public KeyStroke getEmptyKey() {
ProblemDialog.showDeprecated("2020-08-06");
return emptyKey.getKeyStroke();
}
public NamedKeyStroke getNamedEmptyKey() {
return emptyKey;
}
@Deprecated(since = "2020-08-06", forRemoval = true)
public void setEmptyKey(KeyStroke k) {
ProblemDialog.showDeprecated("2020-08-06");
emptyKey = NamedKeyStroke.of(k);
}
public void setEmptyKey(NamedKeyStroke k) {
emptyKey = k;
}
public void setRestrictOption(boolean restrictOption) {
this.restrictOption = restrictOption;
}
public boolean isRestrictOption() {
return restrictOption;
}
public void setRestrictExpression(PropertyExpression restrictExpression) {
this.restrictExpression = restrictExpression;
}
public PropertyExpression getRestrictExpression() {
return restrictExpression;
}
/**
* Does the specified GamePiece meet the rules to be contained
* in this Deck.
*/
public boolean mayContain(GamePiece piece) {
if (! restrictOption || restrictExpression.isNull()) {
return true;
}
else {
return restrictExpression.accept(piece);
}
}
@Override
public String getType() {
final SequenceEncoder se = new SequenceEncoder(';');
se.append(drawOutline)
.append(ColorConfigurer.colorToString(outlineColor))
.append(String.valueOf(size.width))
.append(String.valueOf(size.height))
.append(faceDownOption)
.append(shuffleOption)
.append(String.valueOf(allowMultipleDraw))
.append(String.valueOf(allowSelectDraw))
.append(String.valueOf(reversible))
.append(reshuffleCommand)
.append(reshuffleTarget)
.append(reshuffleMsgFormat)
.append(deckName)
.append(shuffleMsgFormat)
.append(reverseMsgFormat)
.append(faceDownMsgFormat)
.append(drawFaceUp)
.append(persistable)
.append(shuffleKey)
.append(reshuffleKey)
.append(String.valueOf(maxStack))
.append(getCountExpressions())
.append(expressionCounting)
.append(getGlobalCommands())
.append(hotkeyOnEmpty)
.append(emptyKey)
.append(selectDisplayProperty.getFormat())
.append(selectSortProperty)
.append(restrictOption)
.append(restrictExpression)
.append(shuffleCommand)
.append(reverseCommand)
.append(reverseKey);
return ID + se.getValue();
}
/** Shuffle the contents of the Deck */
public Command shuffle() {
final GamePiece[] a = new GamePiece[pieceCount];
System.arraycopy(contents, 0, a, 0, pieceCount);
final List<GamePiece> l = Arrays.asList(a);
DragBuffer.getBuffer().clear();
Collections.shuffle(l, gameModule.getRNG());
return setContents(l).append(reportCommand(shuffleMsgFormat, Resources.getString("Deck.shuffle"))); //$NON-NLS-1$
}
/**
* Return a list if pieces in the Deck in Dealable order.
* If this is an Always shuffle Deck, then shuffle the list of pieces, otherwise just
* reverse the list order so that we deal from the top.
*
* @return List of pieces in Dealable order
*/
public List<GamePiece> getOrderedPieces() {
final List<GamePiece> pieces = asList();
if (!ALWAYS.equals(shuffleOption)) {
Collections.shuffle(pieces, GameModule.getGameModule().getRNG());
}
else {
Collections.reverse(pieces);
}
return pieces;
}
/**
* Return an iterator of pieces to be drawn from the Deck. Normally, a random
* piece will be drawn, but if the Deck supports it, the user may have
* specified a particular set of pieces or a fixed number of pieces to select
* with the next draw.
*/
public PieceIterator drawCards() {
final Iterator<GamePiece> it;
if (nextDraw != null) {
it = nextDraw.iterator();
}
else if (getPieceCount() == 0) {
it = Collections.emptyIterator();
}
else {
int count = Math.max(dragCount, Math.min(1, getPieceCount()));
final ArrayList<GamePiece> pieces = new ArrayList<>();
if (ALWAYS.equals(shuffleOption)) {
// Instead of shuffling the entire deck, just pick <b>count</b> random elements
final ArrayList<Integer> indices = new ArrayList<>();
for (int i = 0; i < getPieceCount(); ++i) {
indices.add(i);
}
final Random rng = gameModule.getRNG();
while (count-- > 0 && !indices.isEmpty()) {
final int i = rng.nextInt(indices.size());
final int index = indices.get(i);
indices.remove(i);
final GamePiece p = getPieceAt(index);
pieces.add(p);
}
}
else {
final Iterator<GamePiece> i = getPiecesReverseIterator();
while (count-- > 0 && i.hasNext()) pieces.add(i.next());
}
it = pieces.iterator();
}
dragCount = 0;
nextDraw = null;
return new PieceIterator(it) {
@Override
public GamePiece nextPiece() {
final GamePiece p = super.nextPiece();
/*
* Bug 12951 results in Cards going back into a Deck via Undo in an inconsistent state.
* This statement is the culprit. As far as I can tell, it is not needed as Deck.pieceRemoved()
* sets OBSCURED_BY if drawing a facedown card from a face down Deck which is the only case
* where this would be needed.
* Bug 13433
* HOWEVER, the nextPiece() iterator is used to select cards to test against property match expressions
* which historically assume that this has already been done. To maintain legacy support, we need to record
* the original OBSCURED_BY, change it, then the consumers of nextPiece() must change it back.
* Note use of scratch-pad props map in BasicPiece, no need to use persistent properties.
*/
p.setProperty(Properties.OBSCURED_BY_PRE_DRAW, p.getProperty(Properties.OBSCURED_BY));
if (faceDown) {
p.setProperty(Properties.OBSCURED_BY, NO_USER);
}
return p;
}
};
}
/** Set the contents of this Deck to a Collection of GamePieces */
protected Command setContents(Collection<GamePiece> c) {
final ChangeTracker track = new ChangeTracker(this);
removeAll();
for (final GamePiece child : c) {
insertChild(child, pieceCount);
}
return track.getChangeCommand();
}
/**
* Set the contents of this Deck to an Iterator of GamePieces
* @deprecated Use {@link #setContents(Collection)} instead.
*/
@Deprecated(since = "2020-08-06", forRemoval = true)
protected Command setContents(Iterator<GamePiece> it) {
ProblemDialog.showDeprecated("2020-08-06");
final ChangeTracker track = new ChangeTracker(this);
removeAll();
while (it.hasNext()) {
final GamePiece child = it.next();
insertChild(child, pieceCount);
}
return track.getChangeCommand();
}
@Override
public String getState() {
final SequenceEncoder se = new SequenceEncoder(';');
se.append(getMap() == null ? "null" : getMap().getIdentifier()).append(getPosition().x).append(getPosition().y); //$NON-NLS-1$
se.append(faceDown);
final SequenceEncoder se2 = new SequenceEncoder(',');
asList().forEach(gamePiece -> se2.append(gamePiece.getId()));
if (se2.getValue() != null) {
se.append(se2.getValue());
}
return se.getValue();
}
@Override
public void setState(String state) {
final SequenceEncoder.Decoder st = new SequenceEncoder.Decoder(state, ';');
final String mapId = st.nextToken();
setPosition(new Point(st.nextInt(0), st.nextInt(0)));
Map m = null;
if (!"null".equals(mapId)) { //$NON-NLS-1$
m = Map.getMapById(mapId);
if (m == null) {
ErrorDialog.dataWarning(new BadDataReport("No such map", mapId, null)); // NON-NLS
}
}
if (m != getMap()) {
if (m != null) {
m.addPiece(this);
}
else {
setMap(null);
}
}
faceDown = "true".equals(st.nextToken()); //$NON-NLS-1$
final ArrayList<GamePiece> l = new ArrayList<>();
if (st.hasMoreTokens()) {
final SequenceEncoder.Decoder st2 =
new SequenceEncoder.Decoder(st.nextToken(), ',');
while (st2.hasMoreTokens()) {
final GamePiece p = gameModule.getGameState()
.getPieceForId(st2.nextToken());
if (p != null) {
l.add(p);
}
}
}
setContents(l);
commands = null; // Force rebuild of popup menu
}
public Command setContentsFaceDown(boolean value) {
final ChangeTracker t = new ChangeTracker(this);
final Command c = new NullCommand();
faceDown = value;
return t.getChangeCommand().append(c).append(reportCommand(faceDownMsgFormat, value ? Resources.getString("Deck.face_down") : Resources.getString("Deck.face_up"))); //$NON-NLS-1$ //$NON-NLS-2$
}
/** Reverse the order of the contents of the Deck */
public Command reverse() {
final ArrayList<GamePiece> list = new ArrayList<>();
for (final Iterator<GamePiece> i = getPiecesReverseIterator(); i.hasNext(); ) {
list.add(i.next());
}
return setContents(list).append(reportCommand(
reverseMsgFormat, Resources.getString("Deck.reverse"))); //$NON-NLS-1$
}
public boolean isDrawOutline() {
return drawOutline;
}
public void setOutlineColor(Color outlineColor) {
this.outlineColor = outlineColor;
}
public void setDrawOutline(boolean drawOutline) {
this.drawOutline = drawOutline;
}
public Color getOutlineColor() {
return outlineColor;
}
public boolean isFaceDown() {
return faceDown;
}
@Override
public Command pieceAdded(GamePiece p) {
return null;
}
@Override
public Command pieceRemoved(GamePiece p) {
final ChangeTracker tracker = new ChangeTracker(p);
p.setProperty(Properties.OBSCURED_TO_OTHERS, isFaceDown() && !isDrawFaceUp());
return tracker.getChangeCommand();
}
public void setFaceDown(boolean faceDown) {
this.faceDown = faceDown;
}
@Override
public void draw(java.awt.Graphics g, int x, int y, Component obs, double zoom) {
final int count = Math.min(getPieceCount(), maxStack);
final GamePiece top = (nextDraw != null && !nextDraw.isEmpty()) ?
nextDraw.get(0) : topPiece();
if (top != null) {
final Object owner = top.getProperty(Properties.OBSCURED_BY);
top.setProperty(Properties.OBSCURED_BY, faceDown ? NO_USER : null);
final Color blankColor = getBlankColor();
final Rectangle r = top.getShape().getBounds();
r.setLocation(x + (int) (zoom * (r.x)), y + (int) (zoom * (r.y)));
r.setSize((int) (zoom * r.width), (int) (zoom * r.height));
for (int i = 0; i < count - 1; ++i) {
if (blankColor != null) {
g.setColor(blankColor);
g.fillRect(r.x + (int) (zoom * 2 * i), r.y - (int) (zoom * 2 * i), r.width, r.height);
g.setColor(Color.black);
g.drawRect(r.x + (int) (zoom * 2 * i), r.y - (int) (zoom * 2 * i), r.width, r.height);
}
else if (faceDown) {
top.draw(g, x + (int) (zoom * 2 * i), y - (int) (zoom * 2 * i), obs, zoom);
}
else {
getPieceAt(count - i - 1).draw(g, x + (int) (zoom * 2 * i), y - (int) (zoom * 2 * i), obs, zoom);
}
}
top.draw(g, x + (int) (zoom * 2 * (count - 1)), y - (int) (zoom * 2 * (count - 1)), obs, zoom);
top.setProperty(Properties.OBSCURED_BY, owner);
}
else {
if (drawOutline) {
final Rectangle r = boundingBox();
r.setLocation(x + (int) (zoom * r.x), y + (int) (zoom * r.y));
r.setSize((int) (zoom * r.width), (int) (zoom * r.height));
g.setColor(outlineColor);
g.drawRect(r.x, r.y, r.width, r.height);
}
}
}
/**
* The color used to draw boxes representing cards underneath the top one. If
* null, then draw each card normally for face-up decks, and duplicate the top
* card for face-down decks
*/
protected Color getBlankColor() {
Color c = Color.white;
if (getMap() != null) {
c = getMap().getStackMetrics().getBlankColor();
}
return c;
}
@Override
public StackMetrics getStackMetrics() {
return deckStackMetrics;
}
@Override
public Rectangle boundingBox() {
final GamePiece top = topPiece();
final Dimension d = top == null ? size : top.getShape().getBounds().getSize();
final Rectangle r = new Rectangle(new Point(), d);
r.translate(-r.width / 2, -r.height / 2);
final int n = getMaximumVisiblePieceCount();
for (int i = 0; i < n; ++i) {
r.y -= 2;
r.height += 2;
r.width += 2;
}
return r;
}
@Override
public Shape getShape() {
return boundingBox();
}
@Override
public Object getProperty(Object key) {
Object value = null;
if (Properties.NO_STACK.equals(key)) {
value = Boolean.TRUE;
}
else if (Properties.KEY_COMMANDS.equals(key)) {
value = getKeyCommands();
}
return value;
}
protected KeyCommand[] getKeyCommands() {
if (commands == null) {
final ArrayList<KeyCommand> l = new ArrayList<>();
KeyCommand c;
if (USE_MENU.equals(shuffleOption)) {
c = new KeyCommand(shuffleCommand, getShuffleKey(), this) {
private static final long serialVersionUID = 1L;
@Override
public void actionPerformed(ActionEvent e) {
gameModule.sendAndLog(shuffle());
repaintMap();
}
};
l.add(c);
}
if (reshuffleCommand.length() > 0) {
c = new KeyCommand(reshuffleCommand, getReshuffleKey(), this) {
private static final long serialVersionUID = 1L;
@Override
public void actionPerformed(ActionEvent evt) {
gameModule.sendAndLog(sendToDeck());
repaintMap();
}
};
l.add(c);
}
if (USE_MENU.equals(faceDownOption)) {
final KeyCommand faceDownAction = new KeyCommand(faceDown ? Resources.getString("Deck.face_up") : Resources.getString("Deck.face_down"), NamedKeyStroke.NULL_KEYSTROKE, this) { //$NON-NLS-1$ //$NON-NLS-2$
private static final long serialVersionUID = 1L;
@Override
public void actionPerformed(ActionEvent e) {
final Command c = setContentsFaceDown(!faceDown);
gameModule.sendAndLog(c);
repaintMap();
}
};
l.add(faceDownAction);
}
if (reversible) {
c = new KeyCommand(reverseCommand, NamedKeyStroke.NULL_KEYSTROKE, this) { //$NON-NLS-1$
private static final long serialVersionUID = 1L;
@Override
public void actionPerformed(ActionEvent e) {
final Command c = reverse();
gameModule.sendAndLog(c);
repaintMap();
}
};
l.add(c);
}
if (allowMultipleDraw) {
c = new KeyCommand(Resources.getString("Deck.draw_multiple"), NamedKeyStroke.NULL_KEYSTROKE, this) { //$NON-NLS-1$
private static final long serialVersionUID = 1L;
@Override
public void actionPerformed(ActionEvent e) {
promptForDragCount();
}
};
l.add(c);
}
if (allowSelectDraw) {
c = new KeyCommand(Resources.getString("Deck.draw_specific"), NamedKeyStroke.NULL_KEYSTROKE, this) { //$NON-NLS-1$
private static final long serialVersionUID = 1L;
@Override
public void actionPerformed(ActionEvent e) {
promptForNextDraw();
repaintMap();
}
};
l.add(c);
}
if (persistable) {
c = new KeyCommand(Resources.getString(Resources.SAVE), NamedKeyStroke.NULL_KEYSTROKE, this) {
private static final long serialVersionUID = 1L;
@Override
public void actionPerformed(ActionEvent e) {
gameModule.sendAndLog(saveDeck());
repaintMap();
}
};
l.add(c);
c = new KeyCommand(Resources.getString(Resources.LOAD), NamedKeyStroke.NULL_KEYSTROKE, this) {
private static final long serialVersionUID = 1L;
@Override
public void actionPerformed(ActionEvent e) {
gameModule.sendAndLog(loadDeck());
repaintMap();
}
};
l.add(c);
}
for (final DeckGlobalKeyCommand cmd : globalCommands) {
l.add(cmd.getKeyCommand(this));
}
commands = l.toArray(new KeyCommand[0]);
}
for (final KeyCommand command : commands) {
if (Resources.getString("Deck.face_up").equals(command.getValue(Action.NAME)) && !faceDown) { //$NON-NLS-1$
command.putValue(Action.NAME, Resources.getString("Deck.face_down")); //$NON-NLS-1$
}
else if (Resources.getString("Deck.face_down").equals(command.getValue(Action.NAME)) && faceDown) { //$NON-NLS-1$
command.putValue(Action.NAME, Resources.getString("Deck.face_up")); //$NON-NLS-1$
}
}
return commands;
}
/*
* Format command report as per module designers setup.
*/
protected Command reportCommand(String format, String commandName) {
Command c = null;
final FormattedString reportFormat = new FormattedString(format);
reportFormat.setProperty(DrawPile.DECK_NAME, getLocalizedDeckName());
reportFormat.setProperty(DrawPile.COMMAND_NAME, commandName);
final String rep = reportFormat.getLocalizedText();
if (rep.length() > 0) {
c = new Chatter.DisplayText(gameModule.getChatter(), "* " + rep); //$NON-NLS-1$
c.execute();
}
return c;
}
public void promptForDragCount() {
while (true) {
final String s = JOptionPane.showInputDialog(GameModule.getGameModule().getPlayerWindow(),
Resources.getString("Deck.enter_the_number")); //$NON-NLS-1$
if (s != null) {
try {
dragCount = Integer.parseInt(s);
dragCount = Math.min(dragCount, getPieceCount());
if (dragCount >= 0) break;
}
catch (NumberFormatException ex) {
// Ignore if user doesn't enter a number
}
}
else {
break;
}
}
}
protected void promptForNextDraw() {
final JDialog d = new JDialog((Frame) SwingUtilities.getAncestorOfClass(Frame.class, map.getView()), true);
d.setTitle(Resources.getString("Deck.draw")); //$NON-NLS-1$
d.setLayout(new BoxLayout(d.getContentPane(), BoxLayout.Y_AXIS));
class AvailablePiece implements Comparable<AvailablePiece> {
private final GamePiece piece;
public AvailablePiece(GamePiece piece) {
this.piece = piece;
}
@Override
public int compareTo(AvailablePiece other) {
if (other == null) return 1;
final String otherProperty =
(String) other.piece.getProperty(selectSortProperty);
if (otherProperty == null) return 1;
final String myProperty =
(String) piece.getProperty(selectSortProperty);
if (myProperty == null) return -1;
return -otherProperty.compareTo(myProperty);
}
@Override
public String toString() {
return selectDisplayProperty.getText(piece);
}
@Override
public boolean equals(Object o) {
if (! (o instanceof AvailablePiece)) return false;
return ((AvailablePiece)o).piece.equals(piece);
}
}
final AvailablePiece[] pieces = new AvailablePiece[getPieceCount()];
for (int i = 0; i < pieces.length; ++i) {
pieces[pieces.length - i - 1] = new AvailablePiece(getPieceAt(i));
}
if (selectSortProperty != null && selectSortProperty.length() > 0) {
Arrays.sort(pieces);
}
final JList<AvailablePiece> list = new JList<>(pieces);
list.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
d.add(new ScrollPane(list));
d.add(new JLabel(Resources.getString("Deck.select_cards"))); //$NON-NLS-1$
d.add(new JLabel(Resources.getString("Deck.then_click"))); //$NON-NLS-1$
final Box box = Box.createHorizontalBox();
JButton b = new JButton(Resources.getString(Resources.OK));
b.addActionListener(e -> {
final int[] selection = list.getSelectedIndices();
if (selection.length > 0) {
nextDraw = new ArrayList<>();
for (final int value : selection) {
nextDraw.add(pieces[value].piece);
}
}
else {
nextDraw = null;
}
d.dispose();
});
box.add(b);
b = new JButton(Resources.getString(Resources.CANCEL));
b.addActionListener(e -> d.dispose());
box.add(b);
d.add(box);
d.pack();
d.setLocationRelativeTo(d.getOwner());
d.setVisible(true);
}
/**
* Combine the contents of this Deck with the contents of the deck specified
* by {@link #reshuffleTarget}
*/
public Command sendToDeck() {
Command c = null;
nextDraw = null;
final DrawPile target = DrawPile.findDrawPile(reshuffleTarget);
if (target != null) {
if (reshuffleMsgFormat.length() > 0) {
c = reportCommand(reshuffleMsgFormat, reshuffleCommand);
if (c == null) {
c = new NullCommand();
}
}
else {
c = new NullCommand();
}
// move cards to deck
final int cnt = getPieceCount() - 1;
for (int i = cnt; i >= 0; i--) {
c.append(target.addToContents(getPieceAt(i)));
}
}
return c;
}
@Override
public boolean isExpanded() {
return false;
}
/** Return true if this deck can be saved to and loaded from a file on disk */
public boolean isPersistable() {
return persistable;
}
public void setPersistable(boolean persistable) {
this.persistable = persistable;
}
private File getSaveFileName() {
final FileChooser fc = gameModule.getFileChooser();
final File sf = fc.getSelectedFile();
if (sf != null) {
String name = sf.getPath();
final int index = name.lastIndexOf('.');
if (index > 0) {
name = name.substring(0, index) + ".sav"; //$NON-NLS-1$
fc.setSelectedFile(new File(name));
}
}
if (fc.showSaveDialog(map.getView()) != FileChooser.APPROVE_OPTION)
return null;
File outputFile = fc.getSelectedFile();
if (outputFile != null &&
outputFile.exists() &&
shouldConfirmOverwrite() &&
JOptionPane.NO_OPTION ==
JOptionPane.showConfirmDialog(gameModule.getPlayerWindow(),
Resources.getString("Deck.overwrite", outputFile.getName()), Resources.getString("Deck.file_exists"), //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
JOptionPane.YES_NO_OPTION)) {
outputFile = null;
}
return outputFile;
}
private boolean shouldConfirmOverwrite() {
return System.getProperty("os.name").trim().equalsIgnoreCase("linux"); //$NON-NLS-1$ //$NON-NLS-2$
}
private Command saveDeck() {
final Command c = new NullCommand();
gameModule.warn(Resources.getString("Deck.saving_deck")); //$NON-NLS-1$
final File saveFile = getSaveFileName();
try {
if (saveFile != null) {
saveDeck(saveFile);
gameModule.warn(Resources.getString("Deck.deck_saved")); //$NON-NLS-1$
}
else {
gameModule.warn(Resources.getString("Deck.save_canceled")); //$NON-NLS-1$
}
}
catch (IOException e) {
WriteErrorDialog.error(e, saveFile);
}
return c;
}
public void saveDeck(File f) throws IOException {
Command comm = new LoadDeckCommand(null);
for (final GamePiece p : asList()) {
p.setMap(null);
comm = comm.append(new AddPiece(p));
}
try (Writer w = Files.newBufferedWriter(f.toPath(), StandardCharsets.UTF_8)) {
gameModule.addCommandEncoder(commandEncoder);
w.write(gameModule.encode(comm));
gameModule.removeCommandEncoder(commandEncoder);
}
}
private File getLoadFileName() {
final FileChooser fc = gameModule.getFileChooser();
fc.selectDotSavFile();
if (fc.showOpenDialog(map.getView()) != FileChooser.APPROVE_OPTION)
return null;
return fc.getSelectedFile();
}
private Command loadDeck() {
Command c = new NullCommand();
gameModule.warn(Resources.getString("Deck.loading_deck")); //$NON-NLS-1$
final File loadFile = getLoadFileName();
try {
if (loadFile != null) {
c = loadDeck(loadFile);
gameModule.warn(Resources.getString("Deck.deck_loaded")); //$NON-NLS-1$
}
else {
gameModule.warn(Resources.getString("Deck.load_canceled")); //$NON-NLS-1$
}
}
catch (IOException e) {
ReadErrorDialog.error(e, loadFile);
}
return c;
}
public Command loadDeck(File f) throws IOException {
final String ds = Files.readString(f.toPath(), StandardCharsets.UTF_8);
gameModule.addCommandEncoder(commandEncoder);
Command c = gameModule.decode(ds);
gameModule.removeCommandEncoder(commandEncoder);
if (c instanceof LoadDeckCommand) {
/*
* A LoadDeckCommand doesn't specify the deck to be changed (since the
* saved deck can be loaded into any deck) so the Command we send to other
* players is a ChangePiece command for this deck, which we need to place
* after the AddPiece commands for the contents
*/
final ChangeTracker t = new ChangeTracker(this);
c.execute();
final Command[] sub = c.getSubCommands();
c = new NullCommand();
for (final Command command : sub) {
c.append(command);
}
c.append(t.getChangeCommand());
updateCountsAll();
}
else {
gameModule.warn(Resources.getString("Deck.not_a_saved_deck", f.getName())); //$NON-NLS-1$
c = null;
}
return c;
}
/**
* Command to set the contents of this deck from a saved file. The contents
* are saved with whatever id's the pieces have in the game when the deck was
* saved, but new copies are created when the deck is re-loaded.
*
* @author rkinney
*
*/
protected static class LoadDeckCommand extends Command {
public static final String PREFIX = "DECK\t"; //$NON-NLS-1$
private final Deck target;
public LoadDeckCommand(Deck target) {
this.target = target;
}
@Override
protected void executeCommand() {
target.removeAll();
final Command[] sub = getSubCommands();
for (final Command command : sub) {
if (command instanceof AddPiece) {
final GamePiece p = ((AddPiece) command).getTarget();
// We set the id to null so that the piece will get a new id
// when the AddPiece command executes
p.setId(null);
target.add(p);
}
}
}
public String getTargetId() {
return target == null ? "" : target.getId(); //$NON-NLS-1$
}
@Override
protected Command myUndoCommand() {
return null;
}
}
/**
* An object that parses expression strings from the config window
*/
public static class CountExpression {
private String fullstring;
private String name;
private String expression;
public CountExpression(String expressionString) {
final String[] split = expressionString.split("\\s*:\\s*", 2); //$NON-NLS-1$
if (split.length == 2) {
name = split[0];
expression = split[1];
fullstring = expressionString;
}
}
public String getName() {
return name;
}
public String getExpression() {
return expression;
}
public String getFullString() {
return fullstring;
}
}
/**
* Return the number of cards to be returned by next call to
* {@link #drawCards()}.
*/
public int getDragCount() {
return dragCount;
}
/**
* Set the number of cards to be returned by next call to
* {@link #drawCards()}.
*
* @param dragCount number of cards to be returned
*/
public void setDragCount(int dragCount) {
this.dragCount = dragCount;
}
public void setSelectDisplayProperty(String promptDisplayProperty) {
this.selectDisplayProperty.setFormat(promptDisplayProperty);
}
public void setSelectSortProperty(String promptSortProperty) {
this.selectSortProperty = promptSortProperty;
}
public String getSelectDisplayProperty() {
return selectDisplayProperty.getFormat();
}
public String getSelectSortProperty() {
return selectSortProperty;
}
protected void repaintMap() {
if (map != null) {
map.repaint();
}
}
}
| 14290 - Shuffle correctly
| vassal-app/src/main/java/VASSAL/counters/Deck.java | 14290 - Shuffle correctly | <ide><path>assal-app/src/main/java/VASSAL/counters/Deck.java
<ide> */
<ide> public List<GamePiece> getOrderedPieces() {
<ide> final List<GamePiece> pieces = asList();
<del> if (!ALWAYS.equals(shuffleOption)) {
<add> if (ALWAYS.equals(shuffleOption)) {
<ide> Collections.shuffle(pieces, GameModule.getGameModule().getRNG());
<ide> }
<ide> else { |
|
Java | bsd-2-clause | b1aaf616b0283a538bfd487a329e1bf15e8ce709 | 0 | dungkhmt/cblsvr,dungkhmt/cblsvr,dungkhmt/cblsvr,dungkhmt/cblsvr,dungkhmt/cblsvr | package localsearch.domainspecific.vehiclerouting.apps.sharedaride;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.logging.FileHandler;
import java.util.logging.Formatter;
import java.util.logging.Handler;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.logging.SimpleFormatter;
import localsearch.domainspecific.vehiclerouting.apps.sharedaride.Search.ALNSwithSA;
import localsearch.domainspecific.vehiclerouting.vrp.Constants;
import localsearch.domainspecific.vehiclerouting.vrp.ConstraintSystemVR;
import localsearch.domainspecific.vehiclerouting.vrp.IFunctionVR;
import localsearch.domainspecific.vehiclerouting.vrp.VRManager;
import localsearch.domainspecific.vehiclerouting.vrp.VarRoutesVR;
import localsearch.domainspecific.vehiclerouting.vrp.constraints.timewindows.CEarliestArrivalTimeVR;
import localsearch.domainspecific.vehiclerouting.vrp.entities.ArcWeightsManager;
import localsearch.domainspecific.vehiclerouting.vrp.entities.LexMultiValues;
import localsearch.domainspecific.vehiclerouting.vrp.entities.Point;
import localsearch.domainspecific.vehiclerouting.vrp.functions.AccumulatedEdgeWeightsOnPathVR;
import localsearch.domainspecific.vehiclerouting.vrp.functions.TotalCostVR;
import localsearch.domainspecific.vehiclerouting.vrp.invariants.AccumulatedWeightEdgesVR;
import localsearch.domainspecific.vehiclerouting.vrp.invariants.EarliestArrivalTimeVR;
public class ShareARide{
public static final Logger LOGGER = Logger.getLogger("Logger");
public static int PEOPLE =1 ;
public static int GOOD = 0;
int scale = 100000;
ArrayList<Point> points;
public static ArrayList<Point> pickupPoints;
public static ArrayList<Point> deliveryPoints;
ArrayList<Integer> type;
ArrayList<Point> startPoints;
ArrayList<Point> stopPoints;
public static ArrayList<Point> rejectPoints;
public static ArrayList<Point> rejectPickupGoods;
public static ArrayList<Point> rejectPickupPeoples;
public static HashMap<Point, Integer> earliestAllowedArrivalTime;
public static HashMap<Point, Integer> serviceDuration;
public static HashMap<Point, Integer> lastestAllowedArrivalTime;
public static HashMap<Point,Point> pickup2DeliveryOfGood;
public static HashMap<Point,Point> pickup2DeliveryOfPeople;
public static HashMap<Point, Point> pickup2Delivery;
public static HashMap<Point,Point> delivery2Pickup;
public int nVehicle;
public static int nRequest;
public static double MAX_DISTANCE;
HashMap<Point, Double> scoreReq;
Point badPick;
HashMap<Integer, ArrayList<Point>> bestS;
ArcWeightsManager awm;
VRManager mgr;
VarRoutesVR XR;
ConstraintSystemVR S;
public IFunctionVR objective;
public CEarliestArrivalTimeVR ceat;
LexMultiValues valueSolution;
EarliestArrivalTimeVR eat;
CEarliestArrivalTimeVR cEarliest;
AccumulatedWeightEdgesVR accDisInvr;
HashMap<Point, IFunctionVR> accDisF;
int cntTimeRestart;
int cntInteration;
public ShareARide(Info info){
this.nVehicle = info.nbVehicle;
this.nRequest = info.nRequest;
points = new ArrayList<Point>();
earliestAllowedArrivalTime = new HashMap<Point, Integer>();
serviceDuration = new HashMap<Point, Integer>();
lastestAllowedArrivalTime = new HashMap<Point, Integer>();
scoreReq = new HashMap<Point, Double>();
pickupPoints = new ArrayList<Point>();
deliveryPoints = new ArrayList<Point>();
startPoints = new ArrayList<Point>();
stopPoints = new ArrayList<Point>();
type = new ArrayList<>();
rejectPoints = new ArrayList<Point>();
rejectPickupGoods = new ArrayList<Point>();
rejectPickupPeoples = new ArrayList<Point>();
bestS = new HashMap<Integer, ArrayList<Point>>();
for(int i=1; i <= info.nbVehicle; ++i)
{
int startPointId = i+info.nRequest*2;
Point sp = new Point(startPointId,info.p[startPointId].getX(),info.p[startPointId].getY());
int stopPointId = i+info.nRequest*2+info.nbVehicle;
Point tp = new Point(stopPointId,info.p[stopPointId].getX(),info.p[stopPointId].getY());
points.add(sp);
points.add(tp);
startPoints.add(sp);
stopPoints.add(tp);
earliestAllowedArrivalTime.put(sp,(int)( info.earliest[startPointId]));
serviceDuration.put(sp, (int)(info.serviceTime[startPointId]));
lastestAllowedArrivalTime.put(sp,(int)( info.lastest[startPointId]));
earliestAllowedArrivalTime.put(tp,(int)( info.earliest[stopPointId]));
serviceDuration.put(tp, (int)(info.serviceTime[stopPointId]));
lastestAllowedArrivalTime.put(tp,(int)( info.lastest[stopPointId]));
}
for(int i=0;i<info.nRequest; ++i)
{
Point pickup = new Point(i*2+1,info.p[i*2+1].getX(),info.p[i*2+1].getY());
Point delivery = new Point(2*i+2,info.p[2*i+2].getX(),info.p[2*i+2].getY());
points.add(pickup);
points.add(delivery);
pickupPoints.add(pickup);
deliveryPoints.add(delivery);
earliestAllowedArrivalTime.put(pickup,(int)( info.earliest[2*i+1]));
serviceDuration.put(pickup, (int)(info.serviceTime[2*i+1]));
lastestAllowedArrivalTime.put(pickup,(int)( info.lastest[2*i+1]));
earliestAllowedArrivalTime.put(delivery,(int)( info.earliest[2*i+2]));
serviceDuration.put(delivery, (int)(info.serviceTime[2*i+2]));
lastestAllowedArrivalTime.put(delivery,(int)( info.lastest[2*i+2]));
type.add(info.type[i*2+1]);
scoreReq.put(pickup, 0.0);
}
awm = new ArcWeightsManager(points);
double max_dist = Double.MIN_VALUE;
for(Point px: points){
for(Point py: points){
double tmp_cost = info.cost[px.getID()][py.getID()];
awm.setWeight(px, py, tmp_cost*3600/70000);
max_dist = tmp_cost > max_dist ? tmp_cost : max_dist;
}
}
MAX_DISTANCE = max_dist;
}
public void stateModel() {
pickup2DeliveryOfGood = new HashMap<Point, Point>();
pickup2DeliveryOfPeople = new HashMap<Point, Point>();
pickup2Delivery = new HashMap<Point, Point>();
delivery2Pickup = new HashMap<Point, Point>();
for(int i=0; i < nRequest; ++i)
{
Point pickup = pickupPoints.get(i);
Point delivery = deliveryPoints.get(i);
pickup2Delivery.put(pickup, delivery);
delivery2Pickup.put(delivery, pickup);
if(type.get(i)==PEOPLE)
{
pickup2DeliveryOfPeople.put(pickup, delivery);
}
else{
pickup2DeliveryOfGood.put(pickup, delivery);
}
}
mgr = new VRManager();
XR = new VarRoutesVR(mgr);
S = new ConstraintSystemVR(mgr);
for(int i=0;i<nVehicle;++i)
XR.addRoute(startPoints.get(i), stopPoints.get(i));
for(int i=0;i<nRequest; ++i)
{
Point pickup = pickupPoints.get(i);
Point delivery = deliveryPoints.get(i);
XR.addClientPoint(pickup);
XR.addClientPoint(delivery);
}
//IConstraintVR goodC = new CPickupDeliveryOfGoodVR(XR, pickup2DeliveryOfGood);
//IConstraintVR peopleC = new CPickupDeliveryOfPeopleVR(XR, pickup2DeliveryOfPeople);
//S.post(goodC);
//S.post(peopleC);
//time windows
eat = new EarliestArrivalTimeVR(XR,awm,earliestAllowedArrivalTime,serviceDuration);
cEarliest = new CEarliestArrivalTimeVR(eat, lastestAllowedArrivalTime);
// new accumulated distance
accDisInvr = new AccumulatedWeightEdgesVR(XR, awm);
//function mapping a point to F calculate distance when route exchanged
accDisF = new HashMap<Point, IFunctionVR>();
for(Point p: XR.getAllPoints()){
IFunctionVR f =new AccumulatedEdgeWeightsOnPathVR(accDisInvr, p);
accDisF.put(p, f);
}
S.post(cEarliest);
objective = new TotalCostVR(XR,awm);
valueSolution = new LexMultiValues();
valueSolution.add(S.violations());
valueSolution.add(objective.getValue());
mgr.close();
}
public void greedyInitSolution(){
for(int i = 0; i < pickupPoints.size(); i++){
Point pickup = pickupPoints.get(i);
if(XR.route(pickup) != Constants.NULL_POINT)
continue;
Point delivery = deliveryPoints.get(i);
//add the request to route
Point pre_pick = null;
Point pre_delivery = null;
double best_objective = Double.MAX_VALUE;
boolean isPeople = pickup2DeliveryOfPeople.containsKey(pickup);
for(int r = 1; r <= XR.getNbRoutes(); r++){
for(Point p = XR.getStartingPointOfRoute(r); p!= XR.getTerminatingPointOfRoute(r); p = XR.next(p)){
if(pickup2DeliveryOfPeople.containsKey(p) || S.evaluateAddOnePoint(pickup, p) > 0)
continue;
if(isPeople){
//check constraint
if(S.evaluateAddTwoPoints(pickup, p, delivery, p) == 0){
//cost improve
double cost = objective.evaluateAddTwoPoints(pickup, p, delivery, p);
if( cost < best_objective){
best_objective = cost;
pre_pick = p;
pre_delivery = p;
}
}
}
//point is good
else{
for(Point q = p; q != XR.getTerminatingPointOfRoute(r); q = XR.next(q)){
if(pickup2DeliveryOfPeople.containsKey(q) || S.evaluateAddOnePoint(delivery, q) > 0)
continue;
if(S.evaluateAddTwoPoints(pickup, p, delivery, q) == 0){
double cost = objective.evaluateAddTwoPoints(pickup, p, delivery, q);
if(cost < best_objective){
best_objective = cost;
pre_pick = p;
pre_delivery = q;
}
}
}
}
}
}
if((pre_pick == null || pre_delivery == null) && !rejectPoints.contains(pickup)){
rejectPoints.add(pickup);
rejectPoints.add(delivery);
if(isPeople){
rejectPickupPeoples.add(pickup);
}else{
rejectPickupGoods.add(pickup);
}
//rejectPickup.add(pickup);
//rejectDelivery.add(delivery);
//System.out.println("reject request: " + i + "reject size = " + rejectPickup.size());
}
else if(pre_pick != null && pre_delivery != null){
mgr.performAddTwoPoints(pickup, pre_pick, delivery, pre_delivery);
}
}
}
public void InitSolutionByInsertGoodFirst(){
/*
* Insert good first
* find best route and best position in route to insert
*/
LOGGER.log(Level.INFO,"Insert good to route");
Iterator<Map.Entry<Point, Point>> it = pickup2DeliveryOfGood.entrySet().iterator();
while(it.hasNext()){
Map.Entry<Point,Point> requestOfGood = it.next();
Point pickup = requestOfGood.getKey();
Point delivery = requestOfGood.getValue();
Point pre_pick = null;
Point pre_delivery = null;
double best_objective = Double.MAX_VALUE;
for(int r = 1; r <= XR.getNbRoutes(); r++){
for(Point p = XR.getStartingPointOfRoute(r); p!= XR.getTerminatingPointOfRoute(r); p = XR.next(p)){
if(S.evaluateAddOnePoint(pickup, p) > 0)
continue;
for(Point q = p; q != XR.getTerminatingPointOfRoute(r); q = XR.next(q)){
if(S.evaluateAddOnePoint(delivery, q) > 0)
continue;
if(S.evaluateAddTwoPoints(pickup, p, delivery, q) == 0){
double cost = objective.evaluateAddTwoPoints(pickup, p, delivery, q);
if(cost < best_objective){
best_objective = cost;
pre_pick = p;
pre_delivery = q;
}
}
}
}
}
if(pre_pick == null || pre_delivery == null){
rejectPoints.add(pickup);
rejectPoints.add(delivery);
rejectPickupGoods.add(pickup);
//System.out.println("reject request: " + i + "reject size = " + rejectPickup.size());
}
else if(pre_pick != null && pre_delivery != null){
mgr.performAddTwoPoints(pickup, pre_pick, delivery, pre_delivery);
}
}
/*
* Insert people
* find best route and best position in route to insert
*/
LOGGER.log(Level.INFO,"Insert people to route");
Iterator<Map.Entry<Point, Point>> it2 = pickup2DeliveryOfPeople.entrySet().iterator();
while(it2.hasNext()){
Map.Entry<Point,Point> requestOfPeople = it2.next();
Point pickup = requestOfPeople.getKey();
Point delivery = requestOfPeople.getValue();
Point pre_pick = null;
Point pre_delivery = null;
double best_objective = Double.MAX_VALUE;
for(int r = 1; r <= XR.getNbRoutes(); r++){
for(Point p = XR.getStartingPointOfRoute(r); p!= XR.getTerminatingPointOfRoute(r); p = XR.next(p)){
if(S.evaluateAddOnePoint(pickup, p) > 0)
continue;
if(S.evaluateAddTwoPoints(pickup, p, delivery, p) == 0){
//cost improve
double cost = objective.evaluateAddTwoPoints(pickup, p, delivery, p);
if( cost < best_objective){
best_objective = cost;
pre_pick = p;
pre_delivery = p;
}
}
}
}
if(pre_pick == null || pre_delivery == null){
rejectPoints.add(pickup);
rejectPoints.add(delivery);
rejectPickupPeoples.add(pickup);
//System.out.println("reject request: " + i + "reject size = " + rejectPickup.size());
}
else if(pre_pick != null && pre_delivery != null){
mgr.performAddTwoPoints(pickup, pre_pick, delivery, pre_delivery);
}
}
}
public void firstPossibleInit(){
for(int i = 0; i < pickupPoints.size(); i++){
Point pickup = pickupPoints.get(i);
if(XR.route(pickup) != Constants.NULL_POINT)
continue;
Point delivery = deliveryPoints.get(i);
//add the request to route
boolean isPeople = pickup2DeliveryOfPeople.containsKey(pickup);
boolean finded = false;
for(int r = 1; r <= XR.getNbRoutes(); r++){
if(finded)
break;
for(Point p = XR.getStartingPointOfRoute(r); p!= XR.getTerminatingPointOfRoute(r); p = XR.next(p)){
if(pickup2DeliveryOfPeople.containsKey(p) || S.evaluateAddOnePoint(pickup, p) > 0)
continue;
if(finded)
break;
if(isPeople){
//check constraint
if(S.evaluateAddTwoPoints(pickup, p, delivery, p) == 0){
//cost improve
mgr.performAddTwoPoints(pickup, p, delivery, p);
finded = true;
}
}
//point is good
else{
for(Point q = p; q != XR.getTerminatingPointOfRoute(r); q = XR.next(q)){
if(pickup2DeliveryOfPeople.containsKey(q) || S.evaluateAddOnePoint(delivery, q) > 0)
continue;
if(S.evaluateAddTwoPoints(pickup, p, delivery, q) == 0){
mgr.performAddTwoPoints(pickup, p, delivery, p);
finded = true;
break;
}
}
}
}
}
if(!finded){
rejectPoints.add(pickup);
rejectPoints.add(delivery);
if(isPeople){
rejectPickupPeoples.add(pickup);
}else{
rejectPickupGoods.add(pickup);
}
//rejectPickup.add(pickup);
//rejectDelivery.add(delivery);
//System.out.println("reject request: " + i + "reject size = " + rejectPickup.size());
}
}
}
public SolutionShareARide search(int maxIter, int timeLimit){
ALNSwithSA alns = new ALNSwithSA(mgr, objective, S, eat, awm);
return alns.search(maxIter, timeLimit);
}
public static void main(String []args){
String inData = "data/SARP-offline/n12335r100_1.txt";
int timeLimit = 36000000;
int nIter = 10000;
Handler fileHandler;
Formatter simpleFormater;
try {
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss");
Date date = new Date();
//System.out.println(dateFormat.format(date));
fileHandler = new FileHandler("data/output/SARP-offline/anhtu/n12335r100_1/"+dateFormat.format(date)+"greedyInit_13Removal_14Insertion.txt");
simpleFormater = new SimpleFormatter();
LOGGER.addHandler(fileHandler);
fileHandler.setFormatter(simpleFormater);
String description = "\n\n\t RUN WITH 13 REMOVAL AND 14 INSERTION (3,1,-5,1) \n\n";
LOGGER.log(Level.INFO, description);
LOGGER.log(Level.INFO, "Read data");
Info info = new Info(inData);
ShareARide sar = new ShareARide(info);
LOGGER.log(Level.INFO, "Read data done --> Create model");
sar.stateModel();
LOGGER.log(Level.INFO, "Create model done --> Init solution");
//sar.InitSolutionByInsertGoodFirst();
sar.greedyInitSolution();
LOGGER.log(Level.INFO,"Init solution done. At start search number of reject points = "+rejectPoints.size()/2+" violations = "+sar.S.violations()+" cost = "+sar.objective.getValue());
SolutionShareARide best_solution = sar.search(nIter, timeLimit);
LOGGER.log(Level.INFO,"Search done. At end search number of reject points = "+best_solution.get_rejectPoints().size()/2+" cost = "+best_solution.get_cost());
fileHandler.close();
} catch (SecurityException | IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
| src/localsearch/domainspecific/vehiclerouting/apps/sharedaride/ShareARide.java | package localsearch.domainspecific.vehiclerouting.apps.sharedaride;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.logging.FileHandler;
import java.util.logging.Formatter;
import java.util.logging.Handler;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.logging.SimpleFormatter;
import localsearch.domainspecific.vehiclerouting.apps.sharedaride.Search.ALNSwithSA;
import localsearch.domainspecific.vehiclerouting.vrp.Constants;
import localsearch.domainspecific.vehiclerouting.vrp.ConstraintSystemVR;
import localsearch.domainspecific.vehiclerouting.vrp.IFunctionVR;
import localsearch.domainspecific.vehiclerouting.vrp.VRManager;
import localsearch.domainspecific.vehiclerouting.vrp.VarRoutesVR;
import localsearch.domainspecific.vehiclerouting.vrp.constraints.timewindows.CEarliestArrivalTimeVR;
import localsearch.domainspecific.vehiclerouting.vrp.entities.ArcWeightsManager;
import localsearch.domainspecific.vehiclerouting.vrp.entities.LexMultiValues;
import localsearch.domainspecific.vehiclerouting.vrp.entities.Point;
import localsearch.domainspecific.vehiclerouting.vrp.functions.AccumulatedEdgeWeightsOnPathVR;
import localsearch.domainspecific.vehiclerouting.vrp.functions.TotalCostVR;
import localsearch.domainspecific.vehiclerouting.vrp.invariants.AccumulatedWeightEdgesVR;
import localsearch.domainspecific.vehiclerouting.vrp.invariants.EarliestArrivalTimeVR;
public class ShareARide{
public static final Logger LOGGER = Logger.getLogger("Logger");
public static int PEOPLE =1 ;
public static int GOOD = 0;
int scale = 100000;
ArrayList<Point> points;
public static ArrayList<Point> pickupPoints;
public static ArrayList<Point> deliveryPoints;
ArrayList<Integer> type;
ArrayList<Point> startPoints;
ArrayList<Point> stopPoints;
public static ArrayList<Point> rejectPoints;
public static ArrayList<Point> rejectPickupGoods;
public static ArrayList<Point> rejectPickupPeoples;
public static HashMap<Point, Integer> earliestAllowedArrivalTime;
public static HashMap<Point, Integer> serviceDuration;
public static HashMap<Point, Integer> lastestAllowedArrivalTime;
public static HashMap<Point,Point> pickup2DeliveryOfGood;
public static HashMap<Point,Point> pickup2DeliveryOfPeople;
public static HashMap<Point, Point> pickup2Delivery;
public static HashMap<Point,Point> delivery2Pickup;
public int nVehicle;
public static int nRequest;
public static double MAX_DISTANCE;
HashMap<Point, Double> scoreReq;
Point badPick;
HashMap<Integer, ArrayList<Point>> bestS;
ArcWeightsManager awm;
VRManager mgr;
VarRoutesVR XR;
ConstraintSystemVR S;
public IFunctionVR objective;
public CEarliestArrivalTimeVR ceat;
LexMultiValues valueSolution;
EarliestArrivalTimeVR eat;
CEarliestArrivalTimeVR cEarliest;
AccumulatedWeightEdgesVR accDisInvr;
HashMap<Point, IFunctionVR> accDisF;
int cntTimeRestart;
int cntInteration;
public ShareARide(Info info){
this.nVehicle = info.nbVehicle;
this.nRequest = info.nRequest;
points = new ArrayList<Point>();
earliestAllowedArrivalTime = new HashMap<Point, Integer>();
serviceDuration = new HashMap<Point, Integer>();
lastestAllowedArrivalTime = new HashMap<Point, Integer>();
scoreReq = new HashMap<Point, Double>();
pickupPoints = new ArrayList<Point>();
deliveryPoints = new ArrayList<Point>();
startPoints = new ArrayList<Point>();
stopPoints = new ArrayList<Point>();
type = new ArrayList<>();
rejectPoints = new ArrayList<Point>();
rejectPickupGoods = new ArrayList<Point>();
rejectPickupPeoples = new ArrayList<Point>();
bestS = new HashMap<Integer, ArrayList<Point>>();
for(int i=1; i <= info.nbVehicle; ++i)
{
int startPointId = i+info.nRequest*2;
Point sp = new Point(startPointId,info.p[startPointId].getX(),info.p[startPointId].getY());
int stopPointId = i+info.nRequest*2+info.nbVehicle;
Point tp = new Point(stopPointId,info.p[stopPointId].getX(),info.p[stopPointId].getY());
points.add(sp);
points.add(tp);
startPoints.add(sp);
stopPoints.add(tp);
earliestAllowedArrivalTime.put(sp,(int)( info.earliest[startPointId]));
serviceDuration.put(sp, (int)(info.serviceTime[startPointId]));
lastestAllowedArrivalTime.put(sp,(int)( info.lastest[startPointId]));
earliestAllowedArrivalTime.put(tp,(int)( info.earliest[stopPointId]));
serviceDuration.put(tp, (int)(info.serviceTime[stopPointId]));
lastestAllowedArrivalTime.put(tp,(int)( info.lastest[stopPointId]));
}
for(int i=0;i<info.nRequest; ++i)
{
Point pickup = new Point(i*2+1,info.p[i*2+1].getX(),info.p[i*2+1].getY());
Point delivery = new Point(2*i+2,info.p[2*i+2].getX(),info.p[2*i+2].getY());
points.add(pickup);
points.add(delivery);
pickupPoints.add(pickup);
deliveryPoints.add(delivery);
earliestAllowedArrivalTime.put(pickup,(int)( info.earliest[2*i+1]));
serviceDuration.put(pickup, (int)(info.serviceTime[2*i+1]));
lastestAllowedArrivalTime.put(pickup,(int)( info.lastest[2*i+1]));
earliestAllowedArrivalTime.put(delivery,(int)( info.earliest[2*i+2]));
serviceDuration.put(delivery, (int)(info.serviceTime[2*i+2]));
lastestAllowedArrivalTime.put(delivery,(int)( info.lastest[2*i+2]));
type.add(info.type[i*2+1]);
scoreReq.put(pickup, 0.0);
}
awm = new ArcWeightsManager(points);
double max_dist = Double.MIN_VALUE;
for(Point px: points){
for(Point py: points){
double tmp_cost = info.cost[px.getID()][py.getID()];
awm.setWeight(px, py, tmp_cost*3600/70000);
max_dist = tmp_cost > max_dist ? tmp_cost : max_dist;
}
}
MAX_DISTANCE = max_dist;
}
public void stateModel() {
pickup2DeliveryOfGood = new HashMap<Point, Point>();
pickup2DeliveryOfPeople = new HashMap<Point, Point>();
pickup2Delivery = new HashMap<Point, Point>();
delivery2Pickup = new HashMap<Point, Point>();
for(int i=0; i < nRequest; ++i)
{
Point pickup = pickupPoints.get(i);
Point delivery = deliveryPoints.get(i);
pickup2Delivery.put(pickup, delivery);
delivery2Pickup.put(delivery, pickup);
if(type.get(i)==PEOPLE)
{
pickup2DeliveryOfPeople.put(pickup, delivery);
}
else{
pickup2DeliveryOfGood.put(pickup, delivery);
}
}
mgr = new VRManager();
XR = new VarRoutesVR(mgr);
S = new ConstraintSystemVR(mgr);
for(int i=0;i<nVehicle;++i)
XR.addRoute(startPoints.get(i), stopPoints.get(i));
for(int i=0;i<nRequest; ++i)
{
Point pickup = pickupPoints.get(i);
Point delivery = deliveryPoints.get(i);
XR.addClientPoint(pickup);
XR.addClientPoint(delivery);
}
//IConstraintVR goodC = new CPickupDeliveryOfGoodVR(XR, pickup2DeliveryOfGood);
//IConstraintVR peopleC = new CPickupDeliveryOfPeopleVR(XR, pickup2DeliveryOfPeople);
//S.post(goodC);
//S.post(peopleC);
//time windows
eat = new EarliestArrivalTimeVR(XR,awm,earliestAllowedArrivalTime,serviceDuration);
cEarliest = new CEarliestArrivalTimeVR(eat, lastestAllowedArrivalTime);
// new accumulated distance
accDisInvr = new AccumulatedWeightEdgesVR(XR, awm);
//function mapping a point to F calculate distance when route exchanged
accDisF = new HashMap<Point, IFunctionVR>();
for(Point p: XR.getAllPoints()){
IFunctionVR f =new AccumulatedEdgeWeightsOnPathVR(accDisInvr, p);
accDisF.put(p, f);
}
S.post(cEarliest);
objective = new TotalCostVR(XR,awm);
valueSolution = new LexMultiValues();
valueSolution.add(S.violations());
valueSolution.add(objective.getValue());
mgr.close();
}
public void greedyInitSolution(){
for(int i = 0; i < pickupPoints.size(); i++){
Point pickup = pickupPoints.get(i);
if(XR.route(pickup) != Constants.NULL_POINT)
continue;
Point delivery = deliveryPoints.get(i);
//add the request to route
Point pre_pick = null;
Point pre_delivery = null;
double best_objective = Double.MAX_VALUE;
boolean isPeople = pickup2DeliveryOfPeople.containsKey(pickup);
for(int r = 1; r <= XR.getNbRoutes(); r++){
for(Point p = XR.getStartingPointOfRoute(r); p!= XR.getTerminatingPointOfRoute(r); p = XR.next(p)){
if(pickup2DeliveryOfPeople.containsKey(p) || S.evaluateAddOnePoint(pickup, p) > 0)
continue;
if(isPeople){
//check constraint
if(S.evaluateAddTwoPoints(pickup, p, delivery, p) == 0){
//cost improve
double cost = objective.evaluateAddTwoPoints(pickup, p, delivery, p);
if( cost < best_objective){
best_objective = cost;
pre_pick = p;
pre_delivery = p;
}
}
}
//point is good
else{
for(Point q = p; q != XR.getTerminatingPointOfRoute(r); q = XR.next(q)){
if(pickup2DeliveryOfPeople.containsKey(q) || S.evaluateAddOnePoint(delivery, q) > 0)
continue;
if(S.evaluateAddTwoPoints(pickup, p, delivery, q) == 0){
double cost = objective.evaluateAddTwoPoints(pickup, p, delivery, q);
if(cost < best_objective){
best_objective = cost;
pre_pick = p;
pre_delivery = q;
}
}
}
}
}
}
if((pre_pick == null || pre_delivery == null) && !rejectPoints.contains(pickup)){
rejectPoints.add(pickup);
rejectPoints.add(delivery);
if(isPeople){
rejectPickupPeoples.add(pickup);
}else{
rejectPickupGoods.add(pickup);
}
//rejectPickup.add(pickup);
//rejectDelivery.add(delivery);
//System.out.println("reject request: " + i + "reject size = " + rejectPickup.size());
}
else if(pre_pick != null && pre_delivery != null){
mgr.performAddTwoPoints(pickup, pre_pick, delivery, pre_delivery);
}
}
}
public void InitSolutionByInsertGoodFirst(){
/*
* Insert good first
* find best route and best position in route to insert
*/
LOGGER.log(Level.INFO,"Insert good to route");
Iterator<Map.Entry<Point, Point>> it = pickup2DeliveryOfGood.entrySet().iterator();
while(it.hasNext()){
Map.Entry<Point,Point> requestOfGood = it.next();
Point pickup = requestOfGood.getKey();
Point delivery = requestOfGood.getValue();
Point pre_pick = null;
Point pre_delivery = null;
double best_objective = Double.MAX_VALUE;
for(int r = 1; r <= XR.getNbRoutes(); r++){
for(Point p = XR.getStartingPointOfRoute(r); p!= XR.getTerminatingPointOfRoute(r); p = XR.next(p)){
if(S.evaluateAddOnePoint(pickup, p) > 0)
continue;
for(Point q = p; q != XR.getTerminatingPointOfRoute(r); q = XR.next(q)){
if(S.evaluateAddOnePoint(delivery, q) > 0)
continue;
if(S.evaluateAddTwoPoints(pickup, p, delivery, q) == 0){
double cost = objective.evaluateAddTwoPoints(pickup, p, delivery, q);
if(cost < best_objective){
best_objective = cost;
pre_pick = p;
pre_delivery = q;
}
}
}
}
}
if(pre_pick == null || pre_delivery == null){
rejectPoints.add(pickup);
rejectPoints.add(delivery);
rejectPickupGoods.add(pickup);
//System.out.println("reject request: " + i + "reject size = " + rejectPickup.size());
}
else if(pre_pick != null && pre_delivery != null){
mgr.performAddTwoPoints(pickup, pre_pick, delivery, pre_delivery);
}
}
/*
* Insert people
* find best route and best position in route to insert
*/
LOGGER.log(Level.INFO,"Insert people to route");
Iterator<Map.Entry<Point, Point>> it2 = pickup2DeliveryOfPeople.entrySet().iterator();
while(it2.hasNext()){
Map.Entry<Point,Point> requestOfPeople = it2.next();
Point pickup = requestOfPeople.getKey();
Point delivery = requestOfPeople.getValue();
Point pre_pick = null;
Point pre_delivery = null;
double best_objective = Double.MAX_VALUE;
for(int r = 1; r <= XR.getNbRoutes(); r++){
for(Point p = XR.getStartingPointOfRoute(r); p!= XR.getTerminatingPointOfRoute(r); p = XR.next(p)){
if(S.evaluateAddOnePoint(pickup, p) > 0)
continue;
if(S.evaluateAddTwoPoints(pickup, p, delivery, p) == 0){
//cost improve
double cost = objective.evaluateAddTwoPoints(pickup, p, delivery, p);
if( cost < best_objective){
best_objective = cost;
pre_pick = p;
pre_delivery = p;
}
}
}
}
if(pre_pick == null || pre_delivery == null){
rejectPoints.add(pickup);
rejectPoints.add(delivery);
rejectPickupPeoples.add(pickup);
//System.out.println("reject request: " + i + "reject size = " + rejectPickup.size());
}
else if(pre_pick != null && pre_delivery != null){
mgr.performAddTwoPoints(pickup, pre_pick, delivery, pre_delivery);
}
}
}
public SolutionShareARide search(int maxIter, int timeLimit){
ALNSwithSA alns = new ALNSwithSA(mgr, objective, S, eat, awm);
return alns.search(maxIter, timeLimit);
}
public static void main(String []args){
String inData = "data/SARP-offline/n12335r100_1.txt";
int timeLimit = 36000000;
int nIter = 10000;
Handler fileHandler;
Formatter simpleFormater;
try {
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss");
Date date = new Date();
//System.out.println(dateFormat.format(date));
fileHandler = new FileHandler("data/output/SARP-offline/anhtu/n12335r100_1/"+dateFormat.format(date)+"greedyInit_13Removal_14Insertion.txt");
simpleFormater = new SimpleFormatter();
LOGGER.addHandler(fileHandler);
fileHandler.setFormatter(simpleFormater);
String description = "\n\n\t RUN WITH 13 REMOVAL AND 14 INSERTION (3,1,-5,1) \n\n";
LOGGER.log(Level.INFO, description);
LOGGER.log(Level.INFO, "Read data");
Info info = new Info(inData);
ShareARide sar = new ShareARide(info);
LOGGER.log(Level.INFO, "Read data done --> Create model");
sar.stateModel();
LOGGER.log(Level.INFO, "Create model done --> Init solution");
//sar.InitSolutionByInsertGoodFirst();
sar.greedyInitSolution();
LOGGER.log(Level.INFO,"Init solution done. At start search number of reject points = "+rejectPoints.size()/2+" violations = "+sar.S.violations()+" cost = "+sar.objective.getValue());
SolutionShareARide best_solution = sar.search(nIter, timeLimit);
LOGGER.log(Level.INFO,"Search done. At end search number of reject points = "+best_solution.get_rejectPoints().size()/2+" cost = "+best_solution.get_cost());
fileHandler.close();
} catch (SecurityException | IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
| [anhtu][add first possible init]
| src/localsearch/domainspecific/vehiclerouting/apps/sharedaride/ShareARide.java | [anhtu][add first possible init] | <ide><path>rc/localsearch/domainspecific/vehiclerouting/apps/sharedaride/ShareARide.java
<ide> }
<ide> }
<ide>
<add> public void firstPossibleInit(){
<add>
<add> for(int i = 0; i < pickupPoints.size(); i++){
<add> Point pickup = pickupPoints.get(i);
<add> if(XR.route(pickup) != Constants.NULL_POINT)
<add> continue;
<add> Point delivery = deliveryPoints.get(i);
<add> //add the request to route
<add>
<add> boolean isPeople = pickup2DeliveryOfPeople.containsKey(pickup);
<add> boolean finded = false;
<add>
<add> for(int r = 1; r <= XR.getNbRoutes(); r++){
<add> if(finded)
<add> break;
<add>
<add> for(Point p = XR.getStartingPointOfRoute(r); p!= XR.getTerminatingPointOfRoute(r); p = XR.next(p)){
<add> if(pickup2DeliveryOfPeople.containsKey(p) || S.evaluateAddOnePoint(pickup, p) > 0)
<add> continue;
<add>
<add> if(finded)
<add> break;
<add>
<add> if(isPeople){
<add> //check constraint
<add> if(S.evaluateAddTwoPoints(pickup, p, delivery, p) == 0){
<add> //cost improve
<add> mgr.performAddTwoPoints(pickup, p, delivery, p);
<add> finded = true;
<add> }
<add> }
<add> //point is good
<add> else{
<add> for(Point q = p; q != XR.getTerminatingPointOfRoute(r); q = XR.next(q)){
<add> if(pickup2DeliveryOfPeople.containsKey(q) || S.evaluateAddOnePoint(delivery, q) > 0)
<add> continue;
<add> if(S.evaluateAddTwoPoints(pickup, p, delivery, q) == 0){
<add> mgr.performAddTwoPoints(pickup, p, delivery, p);
<add> finded = true;
<add> break;
<add> }
<add> }
<add> }
<add> }
<add> }
<add>
<add> if(!finded){
<add> rejectPoints.add(pickup);
<add> rejectPoints.add(delivery);
<add>
<add> if(isPeople){
<add> rejectPickupPeoples.add(pickup);
<add> }else{
<add> rejectPickupGoods.add(pickup);
<add> }
<add> //rejectPickup.add(pickup);
<add> //rejectDelivery.add(delivery);
<add> //System.out.println("reject request: " + i + "reject size = " + rejectPickup.size());
<add> }
<add> }
<add> }
<add>
<ide> public SolutionShareARide search(int maxIter, int timeLimit){
<ide> ALNSwithSA alns = new ALNSwithSA(mgr, objective, S, eat, awm);
<ide> return alns.search(maxIter, timeLimit); |
|
Java | apache-2.0 | 894f5da0e50c1f649e8d4a2458f9edc37fa3bf43 | 0 | wso2/devstudio-tooling-esb,prabushi/devstudio-tooling-esb,prabushi/devstudio-tooling-esb,prabushi/devstudio-tooling-esb,prabushi/devstudio-tooling-esb,wso2/devstudio-tooling-esb,wso2/devstudio-tooling-esb,wso2/devstudio-tooling-esb | /**
* Generated with Acceleo
*/
package org.wso2.developerstudio.eclipse.gmf.esb.parts.impl;
// Start of user code for imports
import org.eclipse.emf.common.util.Enumerator;
import org.eclipse.emf.edit.ui.provider.AdapterFactoryLabelProvider;
import org.eclipse.emf.eef.runtime.EEFRuntimePlugin;
import org.eclipse.emf.eef.runtime.api.component.IPropertiesEditionComponent;
import org.eclipse.emf.eef.runtime.api.notify.IPropertiesEditionEvent;
import org.eclipse.emf.eef.runtime.api.parts.ISWTPropertiesEditionPart;
import org.eclipse.emf.eef.runtime.impl.notify.PropertiesEditionEvent;
import org.eclipse.emf.eef.runtime.impl.parts.CompositePropertiesEditionPart;
import org.eclipse.emf.eef.runtime.ui.parts.PartComposer;
import org.eclipse.emf.eef.runtime.ui.parts.sequence.BindingCompositionSequence;
import org.eclipse.emf.eef.runtime.ui.parts.sequence.CompositionSequence;
import org.eclipse.emf.eef.runtime.ui.parts.sequence.CompositionStep;
import org.eclipse.emf.eef.runtime.ui.utils.EditingUtils;
import org.eclipse.emf.eef.runtime.ui.widgets.EMFComboViewer;
import org.eclipse.emf.eef.runtime.ui.widgets.FormUtils;
import org.eclipse.emf.eef.runtime.ui.widgets.SWTUtils;
import org.eclipse.jface.viewers.ArrayContentProvider;
import org.eclipse.jface.viewers.ISelectionChangedListener;
import org.eclipse.jface.viewers.SelectionChangedEvent;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.FocusAdapter;
import org.eclipse.swt.events.FocusEvent;
import org.eclipse.swt.events.KeyAdapter;
import org.eclipse.swt.events.KeyEvent;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.events.MouseListener;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Group;
import org.eclipse.swt.widgets.Text;
import org.eclipse.ui.forms.widgets.FormToolkit;
import org.wso2.developerstudio.eclipse.gmf.esb.NamespacedProperty;
import org.wso2.developerstudio.eclipse.gmf.esb.PayloadFactoryArgumentType;
import org.wso2.developerstudio.eclipse.gmf.esb.impl.EsbFactoryImpl;
import org.wso2.developerstudio.eclipse.gmf.esb.parts.EsbViewsRepository;
import org.wso2.developerstudio.eclipse.gmf.esb.parts.PayloadFactoryArgumentPropertiesEditionPart;
import org.wso2.developerstudio.eclipse.gmf.esb.parts.forms.HeaderMediatorPropertiesEditionPartForm;
import org.wso2.developerstudio.eclipse.gmf.esb.parts.forms.PayloadFactoryArgumentPropertiesEditionPartForm;
import org.wso2.developerstudio.eclipse.gmf.esb.presentation.EEFNameSpacedPropertyEditorDialog;
import org.wso2.developerstudio.eclipse.gmf.esb.presentation.EEFPropertyViewUtil;
import org.wso2.developerstudio.eclipse.gmf.esb.providers.EsbMessages;
// End of user code
/**
*
*
*/
public class PayloadFactoryArgumentPropertiesEditionPartImpl extends CompositePropertiesEditionPart implements ISWTPropertiesEditionPart, PayloadFactoryArgumentPropertiesEditionPart {
protected EMFComboViewer argumentType;
protected Text argumentValue;
// Start of user code for argumentExpression widgets declarations
protected NamespacedProperty argumentExpression;
protected Text argumentExpressionText;
protected Group propertiesGroup;
protected Control[] argumentExpressionElements;
protected Control[] argumentTypeElements;
protected Control[] argumentValueElements;
protected Control[] evaluatorElements;
protected Control[] literalElements;
// End of user code
protected EMFComboViewer evaluator;
protected Button literal;
/**
* Default constructor
* @param editionComponent the {@link IPropertiesEditionComponent} that manage this part
*
*/
public PayloadFactoryArgumentPropertiesEditionPartImpl(IPropertiesEditionComponent editionComponent) {
super(editionComponent);
}
/**
* {@inheritDoc}
*
* @see org.eclipse.emf.eef.runtime.api.parts.ISWTPropertiesEditionPart#
* createFigure(org.eclipse.swt.widgets.Composite)
*
*/
public Composite createFigure(final Composite parent) {
view = new Composite(parent, SWT.NONE);
GridLayout layout = new GridLayout();
layout.numColumns = 3;
view.setLayout(layout);
createControls(view);
return view;
}
/**
* {@inheritDoc}
*
* @see org.eclipse.emf.eef.runtime.api.parts.ISWTPropertiesEditionPart#
* createControls(org.eclipse.swt.widgets.Composite)
*
*/
public void createControls(Composite view) {
CompositionSequence payloadFactoryArgumentStep = new BindingCompositionSequence(propertiesEditionComponent);
CompositionStep propertiesStep = payloadFactoryArgumentStep.addStep(EsbViewsRepository.PayloadFactoryArgument.Properties.class);
propertiesStep.addStep(EsbViewsRepository.PayloadFactoryArgument.Properties.argumentType);
propertiesStep.addStep(EsbViewsRepository.PayloadFactoryArgument.Properties.argumentValue);
propertiesStep.addStep(EsbViewsRepository.PayloadFactoryArgument.Properties.argumentExpression);
propertiesStep.addStep(EsbViewsRepository.PayloadFactoryArgument.Properties.evaluator);
propertiesStep.addStep(EsbViewsRepository.PayloadFactoryArgument.Properties.literal);
composer = new PartComposer(payloadFactoryArgumentStep) {
@Override
public Composite addToPart(Composite parent, Object key) {
if (key == EsbViewsRepository.PayloadFactoryArgument.Properties.class) {
return createPropertiesGroup(parent);
}
if (key == EsbViewsRepository.PayloadFactoryArgument.Properties.argumentType) {
return createArgumentTypeEMFComboViewer(parent);
}
if (key == EsbViewsRepository.PayloadFactoryArgument.Properties.argumentValue) {
return createArgumentValueText(parent);
}
// Start of user code for argumentExpression addToPart creation
if (key == EsbViewsRepository.PayloadFactoryArgument.Properties.argumentExpression) {
return createArgumentExpression(parent);
}
// End of user code
if (key == EsbViewsRepository.PayloadFactoryArgument.Properties.evaluator) {
return createEvaluatorEMFComboViewer(parent);
}
if (key == EsbViewsRepository.PayloadFactoryArgument.Properties.literal) {
return createLiteralCheckbox(parent);
}
return parent;
}
};
composer.compose(view);
}
/**
*
*/
protected Composite createPropertiesGroup(Composite parent) {
propertiesGroup = new Group(parent, SWT.NONE);
propertiesGroup.setText(EsbMessages.PayloadFactoryArgumentPropertiesEditionPart_PropertiesGroupLabel);
GridData propertiesGroupData = new GridData(GridData.FILL_HORIZONTAL);
propertiesGroupData.horizontalSpan = 3;
propertiesGroup.setLayoutData(propertiesGroupData);
GridLayout propertiesGroupLayout = new GridLayout();
propertiesGroupLayout.numColumns = 3;
propertiesGroup.setLayout(propertiesGroupLayout);
return propertiesGroup;
}
/**
* @generated NOT
*/
protected Composite createArgumentTypeEMFComboViewer(Composite parent) {
Control argumentTypeLabel = createDescription(parent, EsbViewsRepository.PayloadFactoryArgument.Properties.argumentType, EsbMessages.PayloadFactoryArgumentPropertiesEditionPart_ArgumentTypeLabel);
argumentType = new EMFComboViewer(parent, SWT.SCROLL_LOCK);
argumentType.setContentProvider(new ArrayContentProvider());
argumentType.setLabelProvider(new AdapterFactoryLabelProvider(EEFRuntimePlugin.getDefault().getAdapterFactory()));
GridData argumentTypeData = new GridData(GridData.FILL_HORIZONTAL);
argumentType.getCombo().setLayoutData(argumentTypeData);
argumentType.addSelectionChangedListener(new ISelectionChangedListener() {
/**
* {@inheritDoc}
*
* @see org.eclipse.jface.viewers.ISelectionChangedListener#selectionChanged(org.eclipse.jface.viewers.SelectionChangedEvent)
*
*/
public void selectionChanged(SelectionChangedEvent event) {
if (propertiesEditionComponent != null) {
propertiesEditionComponent.firePropertiesChanged(new PropertiesEditionEvent(PayloadFactoryArgumentPropertiesEditionPartImpl.this,
EsbViewsRepository.PayloadFactoryArgument.Properties.argumentType, PropertiesEditionEvent.COMMIT, PropertiesEditionEvent.SET, null, getArgumentType()));
}
validate();
}
});
argumentType.setID(EsbViewsRepository.PayloadFactoryArgument.Properties.argumentType);
Control argumentTypeHelp = SWTUtils.createHelpButton(parent, propertiesEditionComponent.getHelpContent(EsbViewsRepository.PayloadFactoryArgument.Properties.argumentType, EsbViewsRepository.SWT_KIND), null); //$NON-NLS-1$
// Start of user code for createArgumentTypeEMFComboViewer
argumentTypeElements = new Control[] {argumentTypeLabel, argumentType.getCombo(), argumentTypeHelp};
// End of user code
return parent;
}
/**
* @generated NOT
*/
protected Composite createArgumentValueText(Composite parent) {
Control argumentValueLabel = createDescription(parent, EsbViewsRepository.PayloadFactoryArgument.Properties.argumentValue, EsbMessages.PayloadFactoryArgumentPropertiesEditionPart_ArgumentValueLabel);
argumentValue = SWTUtils.createScrollableText(parent, SWT.BORDER);
GridData argumentValueData = new GridData(GridData.FILL_HORIZONTAL);
argumentValue.setLayoutData(argumentValueData);
argumentValue.addFocusListener(new FocusAdapter() {
/**
* {@inheritDoc}
*
* @see org.eclipse.swt.events.FocusAdapter#focusLost(org.eclipse.swt.events.FocusEvent)
*
*/
@Override
@SuppressWarnings("synthetic-access")
public void focusLost(FocusEvent e) {
if (propertiesEditionComponent != null)
propertiesEditionComponent.firePropertiesChanged(new PropertiesEditionEvent(PayloadFactoryArgumentPropertiesEditionPartImpl.this, EsbViewsRepository.PayloadFactoryArgument.Properties.argumentValue, PropertiesEditionEvent.COMMIT, PropertiesEditionEvent.SET, null, argumentValue.getText()));
}
});
argumentValue.addKeyListener(new KeyAdapter() {
/**
* {@inheritDoc}
*
* @see org.eclipse.swt.events.KeyAdapter#keyPressed(org.eclipse.swt.events.KeyEvent)
*
*/
@Override
@SuppressWarnings("synthetic-access")
public void keyReleased(KeyEvent e) {
if (propertiesEditionComponent != null) {
propertiesEditionComponent.firePropertiesChanged(new PropertiesEditionEvent(PayloadFactoryArgumentPropertiesEditionPartImpl.this, EsbViewsRepository.PayloadFactoryArgument.Properties.argumentValue, PropertiesEditionEvent.COMMIT, PropertiesEditionEvent.SET, null, argumentValue.getText()));
}
}
});
EditingUtils.setID(argumentValue, EsbViewsRepository.PayloadFactoryArgument.Properties.argumentValue);
EditingUtils.setEEFtype(argumentValue, "eef::Text"); //$NON-NLS-1$
Control argumentValueHelp = SWTUtils.createHelpButton(parent, propertiesEditionComponent.getHelpContent(EsbViewsRepository.PayloadFactoryArgument.Properties.argumentValue, EsbViewsRepository.SWT_KIND), null); //$NON-NLS-1$
// Start of user code for createArgumentValueText
argumentValueElements = new Control[] {argumentValueLabel, argumentValue, argumentValueHelp};
// End of user code
return parent;
}
/**
* @generated NOT
*/
protected Composite createEvaluatorEMFComboViewer(Composite parent) {
Control evaluatorLabel = createDescription(parent, EsbViewsRepository.PayloadFactoryArgument.Properties.evaluator, EsbMessages.PayloadFactoryArgumentPropertiesEditionPart_EvaluatorLabel);
evaluator = new EMFComboViewer(parent, SWT.SCROLL_LOCK);
evaluator.setContentProvider(new ArrayContentProvider());
evaluator.setLabelProvider(new AdapterFactoryLabelProvider(EEFRuntimePlugin.getDefault().getAdapterFactory()));
GridData evaluatorData = new GridData(GridData.FILL_HORIZONTAL);
evaluator.getCombo().setLayoutData(evaluatorData);
evaluator.addSelectionChangedListener(new ISelectionChangedListener() {
/**
* {@inheritDoc}
*
* @see org.eclipse.jface.viewers.ISelectionChangedListener#selectionChanged(org.eclipse.jface.viewers.SelectionChangedEvent)
*
*/
public void selectionChanged(SelectionChangedEvent event) {
if (propertiesEditionComponent != null)
propertiesEditionComponent.firePropertiesChanged(new PropertiesEditionEvent(PayloadFactoryArgumentPropertiesEditionPartImpl.this, EsbViewsRepository.PayloadFactoryArgument.Properties.evaluator, PropertiesEditionEvent.COMMIT, PropertiesEditionEvent.SET, null, getEvaluator()));
}
});
evaluator.setID(EsbViewsRepository.PayloadFactoryArgument.Properties.evaluator);
Control evaluatorHelp = SWTUtils.createHelpButton(parent, propertiesEditionComponent.getHelpContent(EsbViewsRepository.PayloadFactoryArgument.Properties.evaluator, EsbViewsRepository.SWT_KIND), null); //$NON-NLS-1$
// Start of user code for createEvaluatorEMFComboViewer
evaluatorElements = new Control[] {evaluatorLabel, evaluator.getCombo(), evaluatorHelp};
// End of user code
return parent;
}
/**
* @generated NOT
*/
protected Composite createLiteralCheckbox(Composite parent) {
literal = new Button(parent, SWT.CHECK);
literal.setText(getDescription(EsbViewsRepository.PayloadFactoryArgument.Properties.literal, EsbMessages.PayloadFactoryArgumentPropertiesEditionPart_LiteralLabel));
literal.addSelectionListener(new SelectionAdapter() {
/**
* {@inheritDoc}
*
* @see org.eclipse.swt.events.SelectionAdapter#widgetSelected(org.eclipse.swt.events.SelectionEvent)
*
*/
public void widgetSelected(SelectionEvent e) {
if (propertiesEditionComponent != null)
propertiesEditionComponent.firePropertiesChanged(new PropertiesEditionEvent(PayloadFactoryArgumentPropertiesEditionPartImpl.this, EsbViewsRepository.PayloadFactoryArgument.Properties.literal, PropertiesEditionEvent.COMMIT, PropertiesEditionEvent.SET, null, new Boolean(literal.getSelection())));
}
});
GridData literalData = new GridData(GridData.FILL_HORIZONTAL);
literalData.horizontalSpan = 2;
literal.setLayoutData(literalData);
EditingUtils.setID(literal, EsbViewsRepository.PayloadFactoryArgument.Properties.literal);
EditingUtils.setEEFtype(literal, "eef::Checkbox"); //$NON-NLS-1$
Control literalHelp = SWTUtils.createHelpButton(parent, propertiesEditionComponent.getHelpContent(EsbViewsRepository.PayloadFactoryArgument.Properties.literal, EsbViewsRepository.SWT_KIND), null); //$NON-NLS-1$
// Start of user code for createLiteralCheckbox
literalElements = new Control[] {literal, literalHelp};
// End of user code
return parent;
}
/**
* {@inheritDoc}
*
* @see org.eclipse.emf.eef.runtime.api.notify.IPropertiesEditionListener#firePropertiesChanged(org.eclipse.emf.eef.runtime.api.notify.IPropertiesEditionEvent)
*
*/
public void firePropertiesChanged(IPropertiesEditionEvent event) {
// Start of user code for tab synchronization
// End of user code
}
/**
* {@inheritDoc}
*
* @see org.wso2.developerstudio.eclipse.gmf.esb.parts.PayloadFactoryArgumentPropertiesEditionPart#getArgumentType()
*
*/
public Enumerator getArgumentType() {
Enumerator selection = (Enumerator) ((StructuredSelection) argumentType.getSelection()).getFirstElement();
return selection;
}
/**
* {@inheritDoc}
*
* @see org.wso2.developerstudio.eclipse.gmf.esb.parts.PayloadFactoryArgumentPropertiesEditionPart#initArgumentType(Object input, Enumerator current)
*/
public void initArgumentType(Object input, Enumerator current) {
argumentType.setInput(input);
argumentType.modelUpdating(new StructuredSelection(current));
boolean eefElementEditorReadOnlyState = isReadOnly(EsbViewsRepository.PayloadFactoryArgument.Properties.argumentType);
if (eefElementEditorReadOnlyState && argumentType.isEnabled()) {
argumentType.setEnabled(false);
argumentType.setToolTipText(EsbMessages.PayloadFactoryArgument_ReadOnly);
} else if (!eefElementEditorReadOnlyState && !argumentType.isEnabled()) {
argumentType.setEnabled(true);
}
}
/**
* {@inheritDoc}
*
* @see org.wso2.developerstudio.eclipse.gmf.esb.parts.PayloadFactoryArgumentPropertiesEditionPart#setArgumentType(Enumerator newValue)
*
*/
public void setArgumentType(Enumerator newValue) {
argumentType.modelUpdating(new StructuredSelection(newValue));
boolean eefElementEditorReadOnlyState = isReadOnly(EsbViewsRepository.PayloadFactoryArgument.Properties.argumentType);
if (eefElementEditorReadOnlyState && argumentType.isEnabled()) {
argumentType.setEnabled(false);
argumentType.setToolTipText(EsbMessages.PayloadFactoryArgument_ReadOnly);
} else if (!eefElementEditorReadOnlyState && !argumentType.isEnabled()) {
argumentType.setEnabled(true);
}
}
/**
* {@inheritDoc}
*
* @see org.wso2.developerstudio.eclipse.gmf.esb.parts.PayloadFactoryArgumentPropertiesEditionPart#getArgumentValue()
*
*/
public String getArgumentValue() {
return argumentValue.getText();
}
/**
* {@inheritDoc}
*
* @see org.wso2.developerstudio.eclipse.gmf.esb.parts.PayloadFactoryArgumentPropertiesEditionPart#setArgumentValue(String newValue)
*
*/
public void setArgumentValue(String newValue) {
if (newValue != null) {
argumentValue.setText(newValue);
} else {
argumentValue.setText(""); //$NON-NLS-1$
}
boolean eefElementEditorReadOnlyState = isReadOnly(EsbViewsRepository.PayloadFactoryArgument.Properties.argumentValue);
if (eefElementEditorReadOnlyState && argumentValue.isEnabled()) {
argumentValue.setEnabled(false);
argumentValue.setToolTipText(EsbMessages.PayloadFactoryArgument_ReadOnly);
} else if (!eefElementEditorReadOnlyState && !argumentValue.isEnabled()) {
argumentValue.setEnabled(true);
}
}
/**
* {@inheritDoc}
*
* @see org.wso2.developerstudio.eclipse.gmf.esb.parts.PayloadFactoryArgumentPropertiesEditionPart#getEvaluator()
*
*/
public Enumerator getEvaluator() {
Enumerator selection = (Enumerator) ((StructuredSelection) evaluator.getSelection()).getFirstElement();
return selection;
}
/**
* {@inheritDoc}
*
* @see org.wso2.developerstudio.eclipse.gmf.esb.parts.PayloadFactoryArgumentPropertiesEditionPart#initEvaluator(Object input, Enumerator current)
*/
public void initEvaluator(Object input, Enumerator current) {
evaluator.setInput(input);
evaluator.modelUpdating(new StructuredSelection(current));
boolean eefElementEditorReadOnlyState = isReadOnly(EsbViewsRepository.PayloadFactoryArgument.Properties.evaluator);
if (eefElementEditorReadOnlyState && evaluator.isEnabled()) {
evaluator.setEnabled(false);
evaluator.setToolTipText(EsbMessages.PayloadFactoryArgument_ReadOnly);
} else if (!eefElementEditorReadOnlyState && !evaluator.isEnabled()) {
evaluator.setEnabled(true);
}
}
/**
* {@inheritDoc}
*
* @see org.wso2.developerstudio.eclipse.gmf.esb.parts.PayloadFactoryArgumentPropertiesEditionPart#setEvaluator(Enumerator newValue)
*
*/
public void setEvaluator(Enumerator newValue) {
evaluator.modelUpdating(new StructuredSelection(newValue));
boolean eefElementEditorReadOnlyState = isReadOnly(EsbViewsRepository.PayloadFactoryArgument.Properties.evaluator);
if (eefElementEditorReadOnlyState && evaluator.isEnabled()) {
evaluator.setEnabled(false);
evaluator.setToolTipText(EsbMessages.PayloadFactoryArgument_ReadOnly);
} else if (!eefElementEditorReadOnlyState && !evaluator.isEnabled()) {
evaluator.setEnabled(true);
}
}
/**
* {@inheritDoc}
*
* @see org.wso2.developerstudio.eclipse.gmf.esb.parts.PayloadFactoryArgumentPropertiesEditionPart#getLiteral()
*
*/
public Boolean getLiteral() {
return Boolean.valueOf(literal.getSelection());
}
/**
* {@inheritDoc}
*
* @see org.wso2.developerstudio.eclipse.gmf.esb.parts.PayloadFactoryArgumentPropertiesEditionPart#setLiteral(Boolean newValue)
*
*/
public void setLiteral(Boolean newValue) {
if (newValue != null) {
literal.setSelection(newValue.booleanValue());
} else {
literal.setSelection(false);
}
boolean eefElementEditorReadOnlyState = isReadOnly(EsbViewsRepository.PayloadFactoryArgument.Properties.literal);
if (eefElementEditorReadOnlyState && literal.isEnabled()) {
literal.setEnabled(false);
literal.setToolTipText(EsbMessages.PayloadFactoryArgument_ReadOnly);
} else if (!eefElementEditorReadOnlyState && !literal.isEnabled()) {
literal.setEnabled(true);
}
}
// Start of user code for argumentExpression specific getters and setters implementation
@Override
public void setArgumentExpression(NamespacedProperty namespacedProperty) {
if (namespacedProperty != null) {
argumentExpression = namespacedProperty;
argumentExpressionText.setText(namespacedProperty.getPropertyValue());
}
}
@Override
public NamespacedProperty getArgumentExpression() {
return argumentExpression;
}
// End of user code
/**
* {@inheritDoc}
*
* @see org.eclipse.emf.eef.runtime.api.parts.IPropertiesEditionPart#getTitle()
*
*/
public String getTitle() {
return EsbMessages.PayloadFactoryArgument_Part_Title;
}
// Start of user code additional methods
public void validate() {
EEFPropertyViewUtil eu = new EEFPropertyViewUtil(view);
eu.clearElements(new Composite[] {propertiesGroup});
eu.showEntry(argumentTypeElements, false);
if (getArgumentType().getName().equals(PayloadFactoryArgumentType.VALUE.getName())) {
eu.showEntry(argumentValueElements, false);
} else if (getArgumentType().getName().equals(PayloadFactoryArgumentType.EXPRESSION.getName())) {
eu.showEntry(argumentExpressionElements, false);
eu.showEntry(evaluatorElements, false);
}
eu.showEntry(literalElements, false);
view.layout(true, true);
}
protected Composite createArgumentExpression(final Composite parent) {
Control argumentExpressionLabel = createDescription(parent, EsbViewsRepository.PayloadFactoryArgument.Properties.argumentExpression, EsbMessages.PayloadFactoryArgumentPropertiesEditionPart_ArgumentExpressionLabel);
if (argumentExpression == null) {
argumentExpression = EsbFactoryImpl.eINSTANCE.createNamespacedProperty();
}
argumentExpressionText = SWTUtils.createScrollableText(parent, SWT.BORDER | SWT.READ_ONLY);
GridData valueData = new GridData(GridData.FILL_HORIZONTAL);
argumentExpressionText.setLayoutData(valueData);
argumentExpressionText.addMouseListener(new MouseListener() {
@Override
public void mouseUp(MouseEvent e) {
// TODO Auto-generated method stub
}
@Override
public void mouseDown(MouseEvent e) {
EEFNameSpacedPropertyEditorDialog nspd = new EEFNameSpacedPropertyEditorDialog(parent.getShell(), SWT.NULL, argumentExpression);
nspd.open();
argumentExpressionText.setText(argumentExpression.getPropertyValue());
propertiesEditionComponent.firePropertiesChanged(new PropertiesEditionEvent(PayloadFactoryArgumentPropertiesEditionPartImpl.this,
EsbViewsRepository.PayloadFactoryArgument.Properties.argumentExpression, PropertiesEditionEvent.COMMIT, PropertiesEditionEvent.SET, null, getArgumentExpression()));
}
@Override
public void mouseDoubleClick(MouseEvent e) {
// TODO Auto-generated method stub
}
});
EditingUtils.setID(argumentExpressionText, EsbViewsRepository.PayloadFactoryArgument.Properties.argumentExpression);
EditingUtils.setEEFtype(argumentExpressionText, "eef::Text");
Control argumentExpressionHelp = SWTUtils.createHelpButton(parent, propertiesEditionComponent.getHelpContent(EsbViewsRepository.PayloadFactoryArgument.Properties.argumentExpression, EsbViewsRepository.SWT_KIND), null);
argumentExpressionElements = new Control[] {argumentExpressionLabel, argumentExpressionText, argumentExpressionHelp};
return parent;
}
@Override
public void refresh() {
super.refresh();
validate();
}
// End of user code
}
| plugins/org.wso2.developerstudio.eclipse.gmf.esb.edit/src-gen/org/wso2/developerstudio/eclipse/gmf/esb/parts/impl/PayloadFactoryArgumentPropertiesEditionPartImpl.java | /**
* Generated with Acceleo
*/
package org.wso2.developerstudio.eclipse.gmf.esb.parts.impl;
// Start of user code for imports
import org.eclipse.emf.common.util.Enumerator;
import org.eclipse.emf.edit.ui.provider.AdapterFactoryLabelProvider;
import org.eclipse.emf.eef.runtime.EEFRuntimePlugin;
import org.eclipse.emf.eef.runtime.api.component.IPropertiesEditionComponent;
import org.eclipse.emf.eef.runtime.api.notify.IPropertiesEditionEvent;
import org.eclipse.emf.eef.runtime.api.parts.ISWTPropertiesEditionPart;
import org.eclipse.emf.eef.runtime.impl.notify.PropertiesEditionEvent;
import org.eclipse.emf.eef.runtime.impl.parts.CompositePropertiesEditionPart;
import org.eclipse.emf.eef.runtime.ui.parts.PartComposer;
import org.eclipse.emf.eef.runtime.ui.parts.sequence.BindingCompositionSequence;
import org.eclipse.emf.eef.runtime.ui.parts.sequence.CompositionSequence;
import org.eclipse.emf.eef.runtime.ui.parts.sequence.CompositionStep;
import org.eclipse.emf.eef.runtime.ui.utils.EditingUtils;
import org.eclipse.emf.eef.runtime.ui.widgets.EMFComboViewer;
import org.eclipse.emf.eef.runtime.ui.widgets.FormUtils;
import org.eclipse.emf.eef.runtime.ui.widgets.SWTUtils;
import org.eclipse.jface.viewers.ArrayContentProvider;
import org.eclipse.jface.viewers.ISelectionChangedListener;
import org.eclipse.jface.viewers.SelectionChangedEvent;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.FocusAdapter;
import org.eclipse.swt.events.FocusEvent;
import org.eclipse.swt.events.KeyAdapter;
import org.eclipse.swt.events.KeyEvent;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.events.MouseListener;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Group;
import org.eclipse.swt.widgets.Text;
import org.eclipse.ui.forms.widgets.FormToolkit;
import org.wso2.developerstudio.eclipse.gmf.esb.NamespacedProperty;
import org.wso2.developerstudio.eclipse.gmf.esb.PayloadFactoryArgumentType;
import org.wso2.developerstudio.eclipse.gmf.esb.impl.EsbFactoryImpl;
import org.wso2.developerstudio.eclipse.gmf.esb.parts.EsbViewsRepository;
import org.wso2.developerstudio.eclipse.gmf.esb.parts.PayloadFactoryArgumentPropertiesEditionPart;
import org.wso2.developerstudio.eclipse.gmf.esb.parts.forms.HeaderMediatorPropertiesEditionPartForm;
import org.wso2.developerstudio.eclipse.gmf.esb.parts.forms.PayloadFactoryArgumentPropertiesEditionPartForm;
import org.wso2.developerstudio.eclipse.gmf.esb.presentation.EEFNameSpacedPropertyEditorDialog;
import org.wso2.developerstudio.eclipse.gmf.esb.presentation.EEFPropertyViewUtil;
import org.wso2.developerstudio.eclipse.gmf.esb.providers.EsbMessages;
// End of user code
/**
*
*
*/
public class PayloadFactoryArgumentPropertiesEditionPartImpl extends CompositePropertiesEditionPart implements ISWTPropertiesEditionPart, PayloadFactoryArgumentPropertiesEditionPart {
protected EMFComboViewer argumentType;
protected Text argumentValue;
// Start of user code for argumentExpression widgets declarations
protected NamespacedProperty argumentExpression;
protected Text argumentExpressionText;
protected Group propertiesGroup;
protected Control[] argumentExpressionElements;
protected Control[] argumentTypeElements;
protected Control[] argumentValueElements;
protected Control[] evaluatorElements;
protected Control[] literalElements;
// End of user code
protected EMFComboViewer evaluator;
protected Button literal;
/**
* Default constructor
* @param editionComponent the {@link IPropertiesEditionComponent} that manage this part
*
*/
public PayloadFactoryArgumentPropertiesEditionPartImpl(IPropertiesEditionComponent editionComponent) {
super(editionComponent);
}
/**
* {@inheritDoc}
*
* @see org.eclipse.emf.eef.runtime.api.parts.ISWTPropertiesEditionPart#
* createFigure(org.eclipse.swt.widgets.Composite)
*
*/
public Composite createFigure(final Composite parent) {
view = new Composite(parent, SWT.NONE);
GridLayout layout = new GridLayout();
layout.numColumns = 3;
view.setLayout(layout);
createControls(view);
return view;
}
/**
* {@inheritDoc}
*
* @see org.eclipse.emf.eef.runtime.api.parts.ISWTPropertiesEditionPart#
* createControls(org.eclipse.swt.widgets.Composite)
*
*/
public void createControls(Composite view) {
CompositionSequence payloadFactoryArgumentStep = new BindingCompositionSequence(propertiesEditionComponent);
CompositionStep propertiesStep = payloadFactoryArgumentStep.addStep(EsbViewsRepository.PayloadFactoryArgument.Properties.class);
propertiesStep.addStep(EsbViewsRepository.PayloadFactoryArgument.Properties.argumentType);
propertiesStep.addStep(EsbViewsRepository.PayloadFactoryArgument.Properties.argumentValue);
propertiesStep.addStep(EsbViewsRepository.PayloadFactoryArgument.Properties.argumentExpression);
propertiesStep.addStep(EsbViewsRepository.PayloadFactoryArgument.Properties.evaluator);
propertiesStep.addStep(EsbViewsRepository.PayloadFactoryArgument.Properties.literal);
composer = new PartComposer(payloadFactoryArgumentStep) {
@Override
public Composite addToPart(Composite parent, Object key) {
if (key == EsbViewsRepository.PayloadFactoryArgument.Properties.class) {
return createPropertiesGroup(parent);
}
if (key == EsbViewsRepository.PayloadFactoryArgument.Properties.argumentType) {
return createArgumentTypeEMFComboViewer(parent);
}
if (key == EsbViewsRepository.PayloadFactoryArgument.Properties.argumentValue) {
return createArgumentValueText(parent);
}
// Start of user code for argumentExpression addToPart creation
if (key == EsbViewsRepository.PayloadFactoryArgument.Properties.argumentExpression) {
return createArgumentExpression(parent);
}
// End of user code
if (key == EsbViewsRepository.PayloadFactoryArgument.Properties.evaluator) {
return createEvaluatorEMFComboViewer(parent);
}
if (key == EsbViewsRepository.PayloadFactoryArgument.Properties.literal) {
return createLiteralCheckbox(parent);
}
return parent;
}
};
composer.compose(view);
}
/**
*
*/
protected Composite createPropertiesGroup(Composite parent) {
propertiesGroup = new Group(parent, SWT.NONE);
propertiesGroup.setText(EsbMessages.PayloadFactoryArgumentPropertiesEditionPart_PropertiesGroupLabel);
GridData propertiesGroupData = new GridData(GridData.FILL_HORIZONTAL);
propertiesGroupData.horizontalSpan = 3;
propertiesGroup.setLayoutData(propertiesGroupData);
GridLayout propertiesGroupLayout = new GridLayout();
propertiesGroupLayout.numColumns = 3;
propertiesGroup.setLayout(propertiesGroupLayout);
return propertiesGroup;
}
/**
* @generated NOT
*/
protected Composite createArgumentTypeEMFComboViewer(Composite parent) {
Control argumentTypeLabel = createDescription(parent, EsbViewsRepository.PayloadFactoryArgument.Properties.argumentType, EsbMessages.PayloadFactoryArgumentPropertiesEditionPart_ArgumentTypeLabel);
argumentType = new EMFComboViewer(parent, SWT.SCROLL_LOCK);
argumentType.setContentProvider(new ArrayContentProvider());
argumentType.setLabelProvider(new AdapterFactoryLabelProvider(EEFRuntimePlugin.getDefault().getAdapterFactory()));
GridData argumentTypeData = new GridData(GridData.FILL_HORIZONTAL);
argumentType.getCombo().setLayoutData(argumentTypeData);
argumentType.addSelectionChangedListener(new ISelectionChangedListener() {
/**
* {@inheritDoc}
*
* @see org.eclipse.jface.viewers.ISelectionChangedListener#selectionChanged(org.eclipse.jface.viewers.SelectionChangedEvent)
*
*/
public void selectionChanged(SelectionChangedEvent event) {
if (propertiesEditionComponent != null) {
propertiesEditionComponent.firePropertiesChanged(new PropertiesEditionEvent(PayloadFactoryArgumentPropertiesEditionPartImpl.this,
EsbViewsRepository.PayloadFactoryArgument.Properties.argumentType, PropertiesEditionEvent.COMMIT, PropertiesEditionEvent.SET, null, getArgumentType()));
}
validate();
}
});
argumentType.setID(EsbViewsRepository.PayloadFactoryArgument.Properties.argumentType);
Control argumentTypeHelp = SWTUtils.createHelpButton(parent, propertiesEditionComponent.getHelpContent(EsbViewsRepository.PayloadFactoryArgument.Properties.argumentType, EsbViewsRepository.SWT_KIND), null); //$NON-NLS-1$
// Start of user code for createArgumentTypeEMFComboViewer
argumentTypeElements = new Control[] {argumentTypeLabel, argumentType.getCombo(), argumentTypeHelp};
// End of user code
return parent;
}
/**
* @generated NOT
*/
protected Composite createArgumentValueText(Composite parent) {
Control argumentValueLabel = createDescription(parent, EsbViewsRepository.PayloadFactoryArgument.Properties.argumentValue, EsbMessages.PayloadFactoryArgumentPropertiesEditionPart_ArgumentValueLabel);
argumentValue = SWTUtils.createScrollableText(parent, SWT.BORDER);
GridData argumentValueData = new GridData(GridData.FILL_HORIZONTAL);
argumentValue.setLayoutData(argumentValueData);
argumentValue.addFocusListener(new FocusAdapter() {
/**
* {@inheritDoc}
*
* @see org.eclipse.swt.events.FocusAdapter#focusLost(org.eclipse.swt.events.FocusEvent)
*
*/
@Override
@SuppressWarnings("synthetic-access")
public void focusLost(FocusEvent e) {
if (propertiesEditionComponent != null)
propertiesEditionComponent.firePropertiesChanged(new PropertiesEditionEvent(PayloadFactoryArgumentPropertiesEditionPartImpl.this, EsbViewsRepository.PayloadFactoryArgument.Properties.argumentValue, PropertiesEditionEvent.COMMIT, PropertiesEditionEvent.SET, null, argumentValue.getText()));
}
});
argumentValue.addKeyListener(new KeyAdapter() {
/**
* {@inheritDoc}
*
* @see org.eclipse.swt.events.KeyAdapter#keyPressed(org.eclipse.swt.events.KeyEvent)
*
*/
@Override
@SuppressWarnings("synthetic-access")
public void keyReleased(KeyEvent e) {
if (!EEFPropertyViewUtil.isReservedKeyCombination(e)) {
if (propertiesEditionComponent != null) {
propertiesEditionComponent.firePropertiesChanged(new PropertiesEditionEvent(PayloadFactoryArgumentPropertiesEditionPartImpl.this, EsbViewsRepository.PayloadFactoryArgument.Properties.argumentValue, PropertiesEditionEvent.COMMIT, PropertiesEditionEvent.SET, null, argumentValue.getText()));
}
}
}
});
EditingUtils.setID(argumentValue, EsbViewsRepository.PayloadFactoryArgument.Properties.argumentValue);
EditingUtils.setEEFtype(argumentValue, "eef::Text"); //$NON-NLS-1$
Control argumentValueHelp = SWTUtils.createHelpButton(parent, propertiesEditionComponent.getHelpContent(EsbViewsRepository.PayloadFactoryArgument.Properties.argumentValue, EsbViewsRepository.SWT_KIND), null); //$NON-NLS-1$
// Start of user code for createArgumentValueText
argumentValueElements = new Control[] {argumentValueLabel, argumentValue, argumentValueHelp};
// End of user code
return parent;
}
/**
* @generated NOT
*/
protected Composite createEvaluatorEMFComboViewer(Composite parent) {
Control evaluatorLabel = createDescription(parent, EsbViewsRepository.PayloadFactoryArgument.Properties.evaluator, EsbMessages.PayloadFactoryArgumentPropertiesEditionPart_EvaluatorLabel);
evaluator = new EMFComboViewer(parent, SWT.SCROLL_LOCK);
evaluator.setContentProvider(new ArrayContentProvider());
evaluator.setLabelProvider(new AdapterFactoryLabelProvider(EEFRuntimePlugin.getDefault().getAdapterFactory()));
GridData evaluatorData = new GridData(GridData.FILL_HORIZONTAL);
evaluator.getCombo().setLayoutData(evaluatorData);
evaluator.addSelectionChangedListener(new ISelectionChangedListener() {
/**
* {@inheritDoc}
*
* @see org.eclipse.jface.viewers.ISelectionChangedListener#selectionChanged(org.eclipse.jface.viewers.SelectionChangedEvent)
*
*/
public void selectionChanged(SelectionChangedEvent event) {
if (propertiesEditionComponent != null)
propertiesEditionComponent.firePropertiesChanged(new PropertiesEditionEvent(PayloadFactoryArgumentPropertiesEditionPartImpl.this, EsbViewsRepository.PayloadFactoryArgument.Properties.evaluator, PropertiesEditionEvent.COMMIT, PropertiesEditionEvent.SET, null, getEvaluator()));
}
});
evaluator.setID(EsbViewsRepository.PayloadFactoryArgument.Properties.evaluator);
Control evaluatorHelp = SWTUtils.createHelpButton(parent, propertiesEditionComponent.getHelpContent(EsbViewsRepository.PayloadFactoryArgument.Properties.evaluator, EsbViewsRepository.SWT_KIND), null); //$NON-NLS-1$
// Start of user code for createEvaluatorEMFComboViewer
evaluatorElements = new Control[] {evaluatorLabel, evaluator.getCombo(), evaluatorHelp};
// End of user code
return parent;
}
/**
* @generated NOT
*/
protected Composite createLiteralCheckbox(Composite parent) {
literal = new Button(parent, SWT.CHECK);
literal.setText(getDescription(EsbViewsRepository.PayloadFactoryArgument.Properties.literal, EsbMessages.PayloadFactoryArgumentPropertiesEditionPart_LiteralLabel));
literal.addSelectionListener(new SelectionAdapter() {
/**
* {@inheritDoc}
*
* @see org.eclipse.swt.events.SelectionAdapter#widgetSelected(org.eclipse.swt.events.SelectionEvent)
*
*/
public void widgetSelected(SelectionEvent e) {
if (propertiesEditionComponent != null)
propertiesEditionComponent.firePropertiesChanged(new PropertiesEditionEvent(PayloadFactoryArgumentPropertiesEditionPartImpl.this, EsbViewsRepository.PayloadFactoryArgument.Properties.literal, PropertiesEditionEvent.COMMIT, PropertiesEditionEvent.SET, null, new Boolean(literal.getSelection())));
}
});
GridData literalData = new GridData(GridData.FILL_HORIZONTAL);
literalData.horizontalSpan = 2;
literal.setLayoutData(literalData);
EditingUtils.setID(literal, EsbViewsRepository.PayloadFactoryArgument.Properties.literal);
EditingUtils.setEEFtype(literal, "eef::Checkbox"); //$NON-NLS-1$
Control literalHelp = SWTUtils.createHelpButton(parent, propertiesEditionComponent.getHelpContent(EsbViewsRepository.PayloadFactoryArgument.Properties.literal, EsbViewsRepository.SWT_KIND), null); //$NON-NLS-1$
// Start of user code for createLiteralCheckbox
literalElements = new Control[] {literal, literalHelp};
// End of user code
return parent;
}
/**
* {@inheritDoc}
*
* @see org.eclipse.emf.eef.runtime.api.notify.IPropertiesEditionListener#firePropertiesChanged(org.eclipse.emf.eef.runtime.api.notify.IPropertiesEditionEvent)
*
*/
public void firePropertiesChanged(IPropertiesEditionEvent event) {
// Start of user code for tab synchronization
// End of user code
}
/**
* {@inheritDoc}
*
* @see org.wso2.developerstudio.eclipse.gmf.esb.parts.PayloadFactoryArgumentPropertiesEditionPart#getArgumentType()
*
*/
public Enumerator getArgumentType() {
Enumerator selection = (Enumerator) ((StructuredSelection) argumentType.getSelection()).getFirstElement();
return selection;
}
/**
* {@inheritDoc}
*
* @see org.wso2.developerstudio.eclipse.gmf.esb.parts.PayloadFactoryArgumentPropertiesEditionPart#initArgumentType(Object input, Enumerator current)
*/
public void initArgumentType(Object input, Enumerator current) {
argumentType.setInput(input);
argumentType.modelUpdating(new StructuredSelection(current));
boolean eefElementEditorReadOnlyState = isReadOnly(EsbViewsRepository.PayloadFactoryArgument.Properties.argumentType);
if (eefElementEditorReadOnlyState && argumentType.isEnabled()) {
argumentType.setEnabled(false);
argumentType.setToolTipText(EsbMessages.PayloadFactoryArgument_ReadOnly);
} else if (!eefElementEditorReadOnlyState && !argumentType.isEnabled()) {
argumentType.setEnabled(true);
}
}
/**
* {@inheritDoc}
*
* @see org.wso2.developerstudio.eclipse.gmf.esb.parts.PayloadFactoryArgumentPropertiesEditionPart#setArgumentType(Enumerator newValue)
*
*/
public void setArgumentType(Enumerator newValue) {
argumentType.modelUpdating(new StructuredSelection(newValue));
boolean eefElementEditorReadOnlyState = isReadOnly(EsbViewsRepository.PayloadFactoryArgument.Properties.argumentType);
if (eefElementEditorReadOnlyState && argumentType.isEnabled()) {
argumentType.setEnabled(false);
argumentType.setToolTipText(EsbMessages.PayloadFactoryArgument_ReadOnly);
} else if (!eefElementEditorReadOnlyState && !argumentType.isEnabled()) {
argumentType.setEnabled(true);
}
}
/**
* {@inheritDoc}
*
* @see org.wso2.developerstudio.eclipse.gmf.esb.parts.PayloadFactoryArgumentPropertiesEditionPart#getArgumentValue()
*
*/
public String getArgumentValue() {
return argumentValue.getText();
}
/**
* {@inheritDoc}
*
* @see org.wso2.developerstudio.eclipse.gmf.esb.parts.PayloadFactoryArgumentPropertiesEditionPart#setArgumentValue(String newValue)
*
*/
public void setArgumentValue(String newValue) {
if (newValue != null) {
argumentValue.setText(newValue);
} else {
argumentValue.setText(""); //$NON-NLS-1$
}
boolean eefElementEditorReadOnlyState = isReadOnly(EsbViewsRepository.PayloadFactoryArgument.Properties.argumentValue);
if (eefElementEditorReadOnlyState && argumentValue.isEnabled()) {
argumentValue.setEnabled(false);
argumentValue.setToolTipText(EsbMessages.PayloadFactoryArgument_ReadOnly);
} else if (!eefElementEditorReadOnlyState && !argumentValue.isEnabled()) {
argumentValue.setEnabled(true);
}
}
/**
* {@inheritDoc}
*
* @see org.wso2.developerstudio.eclipse.gmf.esb.parts.PayloadFactoryArgumentPropertiesEditionPart#getEvaluator()
*
*/
public Enumerator getEvaluator() {
Enumerator selection = (Enumerator) ((StructuredSelection) evaluator.getSelection()).getFirstElement();
return selection;
}
/**
* {@inheritDoc}
*
* @see org.wso2.developerstudio.eclipse.gmf.esb.parts.PayloadFactoryArgumentPropertiesEditionPart#initEvaluator(Object input, Enumerator current)
*/
public void initEvaluator(Object input, Enumerator current) {
evaluator.setInput(input);
evaluator.modelUpdating(new StructuredSelection(current));
boolean eefElementEditorReadOnlyState = isReadOnly(EsbViewsRepository.PayloadFactoryArgument.Properties.evaluator);
if (eefElementEditorReadOnlyState && evaluator.isEnabled()) {
evaluator.setEnabled(false);
evaluator.setToolTipText(EsbMessages.PayloadFactoryArgument_ReadOnly);
} else if (!eefElementEditorReadOnlyState && !evaluator.isEnabled()) {
evaluator.setEnabled(true);
}
}
/**
* {@inheritDoc}
*
* @see org.wso2.developerstudio.eclipse.gmf.esb.parts.PayloadFactoryArgumentPropertiesEditionPart#setEvaluator(Enumerator newValue)
*
*/
public void setEvaluator(Enumerator newValue) {
evaluator.modelUpdating(new StructuredSelection(newValue));
boolean eefElementEditorReadOnlyState = isReadOnly(EsbViewsRepository.PayloadFactoryArgument.Properties.evaluator);
if (eefElementEditorReadOnlyState && evaluator.isEnabled()) {
evaluator.setEnabled(false);
evaluator.setToolTipText(EsbMessages.PayloadFactoryArgument_ReadOnly);
} else if (!eefElementEditorReadOnlyState && !evaluator.isEnabled()) {
evaluator.setEnabled(true);
}
}
/**
* {@inheritDoc}
*
* @see org.wso2.developerstudio.eclipse.gmf.esb.parts.PayloadFactoryArgumentPropertiesEditionPart#getLiteral()
*
*/
public Boolean getLiteral() {
return Boolean.valueOf(literal.getSelection());
}
/**
* {@inheritDoc}
*
* @see org.wso2.developerstudio.eclipse.gmf.esb.parts.PayloadFactoryArgumentPropertiesEditionPart#setLiteral(Boolean newValue)
*
*/
public void setLiteral(Boolean newValue) {
if (newValue != null) {
literal.setSelection(newValue.booleanValue());
} else {
literal.setSelection(false);
}
boolean eefElementEditorReadOnlyState = isReadOnly(EsbViewsRepository.PayloadFactoryArgument.Properties.literal);
if (eefElementEditorReadOnlyState && literal.isEnabled()) {
literal.setEnabled(false);
literal.setToolTipText(EsbMessages.PayloadFactoryArgument_ReadOnly);
} else if (!eefElementEditorReadOnlyState && !literal.isEnabled()) {
literal.setEnabled(true);
}
}
// Start of user code for argumentExpression specific getters and setters implementation
@Override
public void setArgumentExpression(NamespacedProperty namespacedProperty) {
if (namespacedProperty != null) {
argumentExpression = namespacedProperty;
argumentExpressionText.setText(namespacedProperty.getPropertyValue());
}
}
@Override
public NamespacedProperty getArgumentExpression() {
return argumentExpression;
}
// End of user code
/**
* {@inheritDoc}
*
* @see org.eclipse.emf.eef.runtime.api.parts.IPropertiesEditionPart#getTitle()
*
*/
public String getTitle() {
return EsbMessages.PayloadFactoryArgument_Part_Title;
}
// Start of user code additional methods
public void validate() {
EEFPropertyViewUtil eu = new EEFPropertyViewUtil(view);
eu.clearElements(new Composite[] {propertiesGroup});
eu.showEntry(argumentTypeElements, false);
if (getArgumentType().getName().equals(PayloadFactoryArgumentType.VALUE.getName())) {
eu.showEntry(argumentValueElements, false);
} else if (getArgumentType().getName().equals(PayloadFactoryArgumentType.EXPRESSION.getName())) {
eu.showEntry(argumentExpressionElements, false);
eu.showEntry(evaluatorElements, false);
}
eu.showEntry(literalElements, false);
view.layout(true, true);
}
protected Composite createArgumentExpression(final Composite parent) {
Control argumentExpressionLabel = createDescription(parent, EsbViewsRepository.PayloadFactoryArgument.Properties.argumentExpression, EsbMessages.PayloadFactoryArgumentPropertiesEditionPart_ArgumentExpressionLabel);
if (argumentExpression == null) {
argumentExpression = EsbFactoryImpl.eINSTANCE.createNamespacedProperty();
}
argumentExpressionText = SWTUtils.createScrollableText(parent, SWT.BORDER | SWT.READ_ONLY);
GridData valueData = new GridData(GridData.FILL_HORIZONTAL);
argumentExpressionText.setLayoutData(valueData);
argumentExpressionText.addMouseListener(new MouseListener() {
@Override
public void mouseUp(MouseEvent e) {
// TODO Auto-generated method stub
}
@Override
public void mouseDown(MouseEvent e) {
EEFNameSpacedPropertyEditorDialog nspd = new EEFNameSpacedPropertyEditorDialog(parent.getShell(), SWT.NULL, argumentExpression);
nspd.open();
argumentExpressionText.setText(argumentExpression.getPropertyValue());
propertiesEditionComponent.firePropertiesChanged(new PropertiesEditionEvent(PayloadFactoryArgumentPropertiesEditionPartImpl.this,
EsbViewsRepository.PayloadFactoryArgument.Properties.argumentExpression, PropertiesEditionEvent.COMMIT, PropertiesEditionEvent.SET, null, getArgumentExpression()));
}
@Override
public void mouseDoubleClick(MouseEvent e) {
// TODO Auto-generated method stub
}
});
EditingUtils.setID(argumentExpressionText, EsbViewsRepository.PayloadFactoryArgument.Properties.argumentExpression);
EditingUtils.setEEFtype(argumentExpressionText, "eef::Text");
Control argumentExpressionHelp = SWTUtils.createHelpButton(parent, propertiesEditionComponent.getHelpContent(EsbViewsRepository.PayloadFactoryArgument.Properties.argumentExpression, EsbViewsRepository.SWT_KIND), null);
argumentExpressionElements = new Control[] {argumentExpressionLabel, argumentExpressionText, argumentExpressionHelp};
return parent;
}
@Override
public void refresh() {
super.refresh();
validate();
}
// End of user code
}
| fix copy paste issue
| plugins/org.wso2.developerstudio.eclipse.gmf.esb.edit/src-gen/org/wso2/developerstudio/eclipse/gmf/esb/parts/impl/PayloadFactoryArgumentPropertiesEditionPartImpl.java | fix copy paste issue | <ide><path>lugins/org.wso2.developerstudio.eclipse.gmf.esb.edit/src-gen/org/wso2/developerstudio/eclipse/gmf/esb/parts/impl/PayloadFactoryArgumentPropertiesEditionPartImpl.java
<ide> @Override
<ide> @SuppressWarnings("synthetic-access")
<ide> public void keyReleased(KeyEvent e) {
<del> if (!EEFPropertyViewUtil.isReservedKeyCombination(e)) {
<del> if (propertiesEditionComponent != null) {
<del> propertiesEditionComponent.firePropertiesChanged(new PropertiesEditionEvent(PayloadFactoryArgumentPropertiesEditionPartImpl.this, EsbViewsRepository.PayloadFactoryArgument.Properties.argumentValue, PropertiesEditionEvent.COMMIT, PropertiesEditionEvent.SET, null, argumentValue.getText()));
<del> }
<del> }
<add>
<add> if (propertiesEditionComponent != null) {
<add> propertiesEditionComponent.firePropertiesChanged(new PropertiesEditionEvent(PayloadFactoryArgumentPropertiesEditionPartImpl.this, EsbViewsRepository.PayloadFactoryArgument.Properties.argumentValue, PropertiesEditionEvent.COMMIT, PropertiesEditionEvent.SET, null, argumentValue.getText()));
<add> }
<add>
<ide> }
<ide>
<ide> }); |
|
Java | apache-2.0 | 47d9d253f741f08f9fd3072136c1b535a91bd92a | 0 | marubinotto/Piggydb,marubinotto/Piggydb,vincentschut/Piggydb,marubinotto/Piggydb,vincentschut/Piggydb,vincentschut/Piggydb,vincentschut/Piggydb,marubinotto/Piggydb | package marubinotto.piggydb.ui.page.partial;
import static org.apache.commons.lang.StringUtils.trimToNull;
import marubinotto.util.message.CodedException;
import marubinotto.util.procedure.Procedure;
public class UpdateFragment extends AbstractSubmitFragmentForm {
@Override
protected void setModels() throws Exception {
super.setModels();
if (this.fragment == null) {
throw new CodedException("no-such-fragment", String.valueOf(this.id));
}
this.fragment.setTitleByUser(trimToNull(this.title), getUser());
this.fragment.setContentByUser(this.content, getUser());
this.fragment.validateTagRole(getUser(), getDomain().getTagRepository());
getDomain().getTransaction().execute(new Procedure() {
public Object execute(Object input) throws Exception {
getDomain().getFragmentRepository().update(getFragment(), !isMinorEdit());
return null;
}
});
}
}
| src/main/java/marubinotto/piggydb/ui/page/partial/UpdateFragment.java | package marubinotto.piggydb.ui.page.partial;
import static org.apache.commons.lang.StringUtils.trimToNull;
import marubinotto.util.message.CodedException;
import marubinotto.util.procedure.Procedure;
public class UpdateFragment extends AbstractSingleFragment {
public String title;
public String content;
public String minorEdit;
private boolean isMinorEdit() {
return this.minorEdit != null;
}
@Override
protected void setModels() throws Exception {
super.setModels();
if (this.fragment == null) {
throw new CodedException("no-such-fragment", String.valueOf(this.id));
}
this.fragment.setTitleByUser(trimToNull(this.title), getUser());
this.fragment.setContentByUser(this.content, getUser());
this.fragment.validateTagRole(getUser(), getDomain().getTagRepository());
getDomain().getTransaction().execute(new Procedure() {
public Object execute(Object input) throws Exception {
getDomain().getFragmentRepository().update(getFragment(), !isMinorEdit());
return null;
}
});
}
}
| #refactoring: changed the base class of marubinotto.piggydb.ui.page.partial.UpdateFragment to AbstractSubmitFragmentForm | src/main/java/marubinotto/piggydb/ui/page/partial/UpdateFragment.java | #refactoring: changed the base class of marubinotto.piggydb.ui.page.partial.UpdateFragment to AbstractSubmitFragmentForm | <ide><path>rc/main/java/marubinotto/piggydb/ui/page/partial/UpdateFragment.java
<ide> import marubinotto.util.message.CodedException;
<ide> import marubinotto.util.procedure.Procedure;
<ide>
<del>public class UpdateFragment extends AbstractSingleFragment {
<del>
<del> public String title;
<del> public String content;
<del> public String minorEdit;
<del>
<del> private boolean isMinorEdit() {
<del> return this.minorEdit != null;
<del> }
<add>public class UpdateFragment extends AbstractSubmitFragmentForm {
<ide>
<ide> @Override
<ide> protected void setModels() throws Exception { |
|
JavaScript | bsd-2-clause | a2bfb6d631504f4ef406ac11ded32f2aab0caf22 | 0 | routexl/carmen,landsurveyorsunited/carmen | var _ = require('underscore');
var iconv = new require('iconv').Iconv('UTF-8', 'ASCII//TRANSLIT//IGNORE');
var crypto = require('crypto');
var Parent = require('mbtiles');
module.exports = MBTiles;
require('util').inherits(MBTiles, Parent);
function MBTiles(uri, callback) {
return Parent.call(this, uri, function(err, source) {
source.emit('open', err);
callback(err, source);
});
};
// Implements carmen#getFeature method.
MBTiles.prototype.getFeature = function(id, callback) {
this._db.get('SELECT key_name AS id, key_json AS data FROM keymap WHERE key_name = ?', id, function(err, row) {
if (err) return callback(err);
try { return callback(null, JSON.parse(row.data)); }
catch(err) { return callback(err); }
});
};
// Implements carmen#putFeature method.
MBTiles.prototype.putFeature = function(id, data, callback) {
this.write('keymap', id, {
key_name: id,
key_json: JSON.stringify(data)
}, callback);
};
// Implements carmen#getCarmen method.
MBTiles.prototype.getCarmen = function(type, shard, callback) {
return this._db.get('SELECT data FROM carmen_' + type + ' WHERE shard = ?', shard, function(err, row) {
callback(err, row ? row.data : null);
});
};
// Implements carmen#putCarmen method.
MBTiles.prototype.putCarmen = function(type, shard, data, callback) {
this.write('carmen_' + type, shard, { shard: shard, data: data }, callback);
};
// Implements carmen#indexable method.
MBTiles.prototype.indexable = function(pointer, callback) {
pointer = pointer || {};
pointer.limit = pointer.limit || 10000;
pointer.offset = pointer.offset || 0;
pointer.nogrids = 'nogrids' in pointer ? pointer.nogrids : false;
// Converts MBTiles native TMS coords to ZXY.
function tms2zxy(zxys) {
return zxys.split(',').map(function(tms) {
var zxy = tms.split('/').map(function(v) { return parseInt(v,10) });
zxy[2] = (1 << zxy[0]) - 1 - zxy[2];
return zxy.join('/');
});
};
// If 'carmen' option is passed in initial pointer, retrieve indexables from
// carmen table. This option can be used to access the previously indexed
// documents from an MBTiles database without having to know what search
// field was used in the past (see comment below).
if (pointer.table === 'carmen') return this._db.all("SELECT c.id, c.text, c.zxy, k.key_json FROM carmen c JOIN keymap k ON c.id = k.key_name LIMIT ? OFFSET ?", pointer.limit, pointer.offset, function(err, rows) {
if (err) return callback(err);
var docs = rows.map(function(row) {
var doc = {};
doc.id = row.id;
doc.doc = JSON.parse(row.key_json);
doc.text = row.text;
if (row.zxy) doc.zxy = tms2zxy(row.zxy);
return doc;
});
pointer.offset += pointer.limit;
return callback(null, docs, pointer);
}.bind(this));
// By default the keymap table contains all indexable documents.
this.getInfo(function(err, info) {
if (err) return callback(err);
if (pointer.nogrids) {
var sql = "SELECT key_name, key_json FROM keymap LIMIT ? OFFSET ?;";
var args = [pointer.limit, pointer.offset];
} else {
var sql = "SELECT k.key_name, k.key_json, GROUP_CONCAT(zoom_level||'/'||tile_column ||'/'||tile_row,',') AS zxy FROM keymap k JOIN grid_key g ON k.key_name = g.key_name JOIN map m ON g.grid_id = m.grid_id WHERE m.zoom_level=? GROUP BY k.key_name LIMIT ? OFFSET ?;"
var args = [info.maxzoom, pointer.limit, pointer.offset];
}
this._db.all(sql, args, function(err, rows) {
if (err) return callback(err);
var docs = rows.map(function(row) {
var doc = {};
doc.id = row.key_name;
doc.doc = JSON.parse(row.key_json);
// @TODO the doc field name for searching probably (?) belongs
// in `metadata` and should be un-hardcoded in the future.
doc.text = doc.doc.search || doc.doc.name || '';
if (row.zxy) doc.zxy = tms2zxy(row.zxy);
return doc;
});
pointer.offset += pointer.limit;
return callback(null, docs, pointer);
}.bind(this));
}.bind(this));
};
// Adds carmen schema to startWriting.
MBTiles.prototype.startWriting = _(MBTiles.prototype.startWriting).wrap(function(parent, callback) {
parent.call(this, function(err) {
if (err) return callback(err);
var sql = '\
CREATE INDEX IF NOT EXISTS map_grid_id ON map (grid_id);\
CREATE TABLE IF NOT EXISTS carmen_docs(shard INTEGER PRIMARY KEY, data BLOB);\
CREATE TABLE IF NOT EXISTS carmen_freq(shard INTEGER PRIMARY KEY, data BLOB);\
CREATE TABLE IF NOT EXISTS carmen_term(shard INTEGER PRIMARY KEY, data BLOB);\
CREATE TABLE IF NOT EXISTS carmen_grid(shard INTEGER PRIMARY KEY, data BLOB);';
this._db.exec(sql, function(err) {
if (err) {
return callback(err);
} else {
return callback();
}
});
}.bind(this));
});
| api-mbtiles.js | var _ = require('underscore');
var iconv = new require('iconv').Iconv('UTF-8', 'ASCII//TRANSLIT//IGNORE');
var crypto = require('crypto');
var Parent = require('mbtiles');
module.exports = MBTiles;
require('util').inherits(MBTiles, Parent);
function MBTiles(uri, callback) {
return Parent.call(this, uri, function(err, source) {
source.emit('open', err);
callback(err, source);
});
};
// Implements carmen#getFeature method.
MBTiles.prototype.getFeature = function(id, callback) {
this._db.get('SELECT key_name AS id, key_json AS data FROM keymap WHERE key_name = ?', id, function(err, row) {
if (err) return callback(err);
try { return callback(null, JSON.parse(row.data)); }
catch(err) { return callback(err); }
});
};
// Implements carmen#putFeature method.
MBTiles.prototype.putFeature = function(id, data, callback) {
this.write('keymap', id, {
key_name: id,
key_json: JSON.stringify(data)
}, callback);
};
// Implements carmen#getCarmen method.
MBTiles.prototype.getCarmen = function(type, shard, callback) {
return this._db.get('SELECT data FROM carmen_' + type + ' WHERE shard = ?', shard, function(err, row) {
callback(err, row ? row.data : null);
});
};
// Implements carmen#putCarmen method.
MBTiles.prototype.putCarmen = function(type, shard, data, callback) {
this.write('carmen_' + type, shard, { shard: shard, data: data }, callback);
};
// Implements carmen#indexable method.
MBTiles.prototype.indexable = function(pointer, callback) {
pointer = pointer || {};
pointer.limit = pointer.limit || 10000;
pointer.offset = pointer.offset || 0;
pointer.nogrids = 'nogrids' in pointer ? pointer.nogrids : false;
// If 'carmen' option is passed in initial pointer, retrieve indexables from
// carmen table. This option can be used to access the previously indexed
// documents from an MBTiles database without having to know what search
// field was used in the past (see comment below).
if (pointer.table === 'carmen') return this._db.all("SELECT c.id, c.text, c.zxy, k.key_json FROM carmen c JOIN keymap k ON c.id = k.key_name LIMIT ? OFFSET ?", pointer.limit, pointer.offset, function(err, rows) {
if (err) return callback(err);
var docs = rows.map(function(row) {
var doc = {};
doc.id = row.id;
doc.doc = JSON.parse(row.key_json);
doc.text = row.text;
doc.zxy = row.zxy.split(',');
return doc;
});
pointer.offset += pointer.limit;
return callback(null, docs, pointer);
}.bind(this));
// By default the keymap table contains all indexable documents.
this.getInfo(function(err, info) {
if (err) return callback(err);
if (pointer.nogrids) {
var sql = "SELECT key_name, key_json FROM keymap LIMIT ? OFFSET ?;";
var args = [pointer.limit, pointer.offset];
} else {
var sql = "SELECT k.key_name, k.key_json, GROUP_CONCAT(zoom_level||'/'||tile_column ||'/'||tile_row,',') AS zxy FROM keymap k JOIN grid_key g ON k.key_name = g.key_name JOIN map m ON g.grid_id = m.grid_id WHERE m.zoom_level=? GROUP BY k.key_name LIMIT ? OFFSET ?;"
var args = [info.maxzoom, pointer.limit, pointer.offset];
}
this._db.all(sql, args, function(err, rows) {
if (err) return callback(err);
var docs = rows.map(function(row) {
var doc = {};
doc.id = row.key_name;
doc.doc = JSON.parse(row.key_json);
// @TODO the doc field name for searching probably (?) belongs
// in `metadata` and should be un-hardcoded in the future.
doc.text = doc.doc.search || doc.doc.name || '';
if (row.zxy) doc.zxy = row.zxy.split(',');
return doc;
});
pointer.offset += pointer.limit;
return callback(null, docs, pointer);
}.bind(this));
}.bind(this));
};
// Adds carmen schema to startWriting.
MBTiles.prototype.startWriting = _(MBTiles.prototype.startWriting).wrap(function(parent, callback) {
parent.call(this, function(err) {
if (err) return callback(err);
var sql = '\
CREATE INDEX IF NOT EXISTS map_grid_id ON map (grid_id);\
CREATE TABLE IF NOT EXISTS carmen_docs(shard INTEGER PRIMARY KEY, data BLOB);\
CREATE TABLE IF NOT EXISTS carmen_freq(shard INTEGER PRIMARY KEY, data BLOB);\
CREATE TABLE IF NOT EXISTS carmen_term(shard INTEGER PRIMARY KEY, data BLOB);\
CREATE TABLE IF NOT EXISTS carmen_grid(shard INTEGER PRIMARY KEY, data BLOB);';
this._db.exec(sql, function(err) {
if (err) {
return callback(err);
} else {
return callback();
}
});
}.bind(this));
});
| Operate on ZXY scheme.
| api-mbtiles.js | Operate on ZXY scheme. | <ide><path>pi-mbtiles.js
<ide> pointer.offset = pointer.offset || 0;
<ide> pointer.nogrids = 'nogrids' in pointer ? pointer.nogrids : false;
<ide>
<add> // Converts MBTiles native TMS coords to ZXY.
<add> function tms2zxy(zxys) {
<add> return zxys.split(',').map(function(tms) {
<add> var zxy = tms.split('/').map(function(v) { return parseInt(v,10) });
<add> zxy[2] = (1 << zxy[0]) - 1 - zxy[2];
<add> return zxy.join('/');
<add> });
<add> };
<add>
<ide> // If 'carmen' option is passed in initial pointer, retrieve indexables from
<ide> // carmen table. This option can be used to access the previously indexed
<ide> // documents from an MBTiles database without having to know what search
<ide> doc.id = row.id;
<ide> doc.doc = JSON.parse(row.key_json);
<ide> doc.text = row.text;
<del> doc.zxy = row.zxy.split(',');
<add> if (row.zxy) doc.zxy = tms2zxy(row.zxy);
<ide> return doc;
<ide> });
<ide> pointer.offset += pointer.limit;
<ide> // @TODO the doc field name for searching probably (?) belongs
<ide> // in `metadata` and should be un-hardcoded in the future.
<ide> doc.text = doc.doc.search || doc.doc.name || '';
<del> if (row.zxy) doc.zxy = row.zxy.split(',');
<add> if (row.zxy) doc.zxy = tms2zxy(row.zxy);
<ide> return doc;
<ide> });
<ide> pointer.offset += pointer.limit; |
|
Java | apache-2.0 | 89eb7bc3a671a7309cda4434244a8aaa93906eb0 | 0 | gabby2212/gs-collections,goldmansachs/gs-collections,mix-juice001/gs-collections,Pelumi/gs-collections,motlin/gs-collections,xingguang2013/gs-collections | /*
* Copyright 2011 Goldman Sachs.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.gs.collections.api;
import java.util.Collection;
import java.util.Comparator;
import java.util.NoSuchElementException;
import com.gs.collections.api.bag.MutableBag;
import com.gs.collections.api.block.function.Function;
import com.gs.collections.api.block.function.Function0;
import com.gs.collections.api.block.function.Function2;
import com.gs.collections.api.block.function.primitive.BooleanFunction;
import com.gs.collections.api.block.function.primitive.ByteFunction;
import com.gs.collections.api.block.function.primitive.CharFunction;
import com.gs.collections.api.block.function.primitive.DoubleFunction;
import com.gs.collections.api.block.function.primitive.DoubleObjectToDoubleFunction;
import com.gs.collections.api.block.function.primitive.FloatFunction;
import com.gs.collections.api.block.function.primitive.FloatObjectToFloatFunction;
import com.gs.collections.api.block.function.primitive.IntFunction;
import com.gs.collections.api.block.function.primitive.IntObjectToIntFunction;
import com.gs.collections.api.block.function.primitive.LongFunction;
import com.gs.collections.api.block.function.primitive.LongObjectToLongFunction;
import com.gs.collections.api.block.function.primitive.ShortFunction;
import com.gs.collections.api.block.predicate.Predicate;
import com.gs.collections.api.block.predicate.Predicate2;
import com.gs.collections.api.block.procedure.Procedure2;
import com.gs.collections.api.list.MutableList;
import com.gs.collections.api.map.MapIterable;
import com.gs.collections.api.map.MutableMap;
import com.gs.collections.api.map.sorted.MutableSortedMap;
import com.gs.collections.api.multimap.Multimap;
import com.gs.collections.api.multimap.MutableMultimap;
import com.gs.collections.api.partition.PartitionIterable;
import com.gs.collections.api.set.MutableSet;
import com.gs.collections.api.set.sorted.MutableSortedSet;
import com.gs.collections.api.tuple.Pair;
/**
* RichIterable is an interface which extends the InternalIterable interface with several internal iterator methods, from
* the Smalltalk Collection protocol. These include select, reject, detect, collect, injectInto, anySatisfy,
* allSatisfy. The API also includes converter methods to convert a RichIterable to a List (toList), to a sorted
* List (toSortedList), to a Set (toSet), and to a Map (toMap).
*
* @since 1.0
*/
public interface
RichIterable<T>
extends InternalIterable<T>
{
/**
* Returns the number of items in this iterable.
*
* @since 1.0
*/
int size();
/**
* Returns true if this iterable has zero items.
*
* @since 1.0
*/
boolean isEmpty();
/**
* The English equivalent of !this.isEmpty()
*
* @since 1.0
*/
boolean notEmpty();
/**
* Returns the first element of an iterable. In the case of a List it is the element at the first index. In the
* case of any other Collection, it is the first element that would be returned during an iteration. If the
* iterable is empty, null is returned. If null is a valid element of the container, then a developer would need to
* check to see if the iterable is empty to validate that a null result was not due to the container being empty.
* <p/>
* The order of Sets are not guaranteed (except for TreeSets and other Ordered Set implementations), so if you use
* this method, the first element could be any element from the Set.
*
* @since 1.0
*/
T getFirst();
/**
* Returns the last element of an iterable. In the case of a List it is the element at the last index. In the case
* of any other Collection, it is the last element that would be returned during an iteration. If the iterable is
* empty, null is returned. If null is a valid element of the container, then a developer would need to check to
* see if the iterable is empty to validate that a null result was not due to the container being empty.
* <p/>
* The order of Sets are not guaranteed (except for TreeSets and other Ordered Set implementations), so if you use
* this method, the last element could be any element from the Set.
*
* @since 1.0
*/
T getLast();
/**
* Returns true if the iterable has an element which responds true to element.equals(object).
*
* @since 1.0
*/
boolean contains(Object object);
/**
* Returns true if all elements in source are contained in this collection.
*
* @since 1.0
*/
boolean containsAllIterable(Iterable<?> source);
/**
* Returns true if all elements in source are contained in this collection.
*
* @see Collection#containsAll(Collection)
* @since 1.0
*/
boolean containsAll(Collection<?> source);
/**
* Returns true if all elements in the specified var arg array are contained in this collection.
*
* @since 1.0
*/
boolean containsAllArguments(Object... elements);
/**
* Returns all elements of the source collection that return true when evaluating the predicate. This method is also
* commonly called filter.
* <p/>
* <pre>e.g.
* return people.<b>select</b>(new Predicate<Person>()
* {
* public boolean accept(Person person)
* {
* return person.getAddress().getCity().equals("Metuchen");
* }
* });
* </pre>
*
* @since 1.0
*/
RichIterable<T> select(Predicate<? super T> predicate);
/**
* Same as the select method with one parameter but uses the specified target collection for the results.
* <p/>
* <pre>e.g.
* return people.select(new Predicate<Person>()
* {
* public boolean accept(Person person)
* {
* return person.person.getLastName().equals("Smith");
* }
* }, Lists.mutable.of());
* </pre>
* <p/>
* <pre>e.g.
* return collection.select(Predicates.attributeEqual("lastName", "Smith"), new ArrayList());
* </pre>
*
* @param predicate a {@link Predicate} to use as the select criteria
* @param target the Collection to append to for all elements in this {@code RichIterable} that meet select criteria {@code predicate}
* @return {@code target}, which contains appended elements as a result of the select criteria
* @see #select(Predicate)
* @since 1.0
*/
<R extends Collection<T>> R select(Predicate<? super T> predicate, R target);
/**
* Similar to {@link #select(Predicate, Collection)}, except with an evaluation parameter for the second generic argument in {@link Predicate2}.
*
* @param predicate a {@link Predicate2} to use as the select criteria
* @param parameter a parameter to pass in for evaluation of the second argument {@code P} in {@code predicate}
* @see #select(Predicate)
* @see #select(Predicate, Collection)
* @since 5.0
*/
<P> RichIterable<T> selectWith(Predicate2<? super T, ? super P> predicate, P parameter);
/**
* Similar to {@link #select(Predicate, Collection)}, except with an evaluation parameter for the second generic argument in {@link Predicate2}.
*
* @param predicate a {@link Predicate2} to use as the select criteria
* @param parameter a parameter to pass in for evaluation of the second argument {@code P} in {@code predicate}
* @param targetCollection the Collection to append to for all elements in this {@code RichIterable} that meet select criteria {@code predicate}
* @return {@code targetCollection}, which contains appended elements as a result of the select criteria
* @see #select(Predicate)
* @see #select(Predicate, Collection)
* @since 1.0
*/
<P, R extends Collection<T>> R selectWith(
Predicate2<? super T, ? super P> predicate,
P parameter,
R targetCollection);
/**
* Returns all elements of the source collection that return false when evaluating of the predicate. This method is also
* sometimes called filterNot and is the equivalent of calling iterable.select(Predicates.not(predicate)).
* <p/>
* <pre>e.g.
* return people.reject(new Predicate<Person>()
* {
* public boolean accept(Person person)
* {
* return person.person.getLastName().equals("Smith");
* }
* });
* </pre>
* <p/>
* <pre>e.g.
* return people.reject(Predicates.attributeEqual("lastName", "Smith"));
* </pre>
*
* @param predicate a {@link Predicate} to use as the reject criteria
* @return a RichIterable that contains elements that cause {@link Predicate#accept(Object)} method to evaluate to false
* @since 1.0
*/
RichIterable<T> reject(Predicate<? super T> predicate);
/**
* Same as the reject method with one parameter but uses the specified target collection for the results.
* <p/>
* <pre>e.g.
* return people.reject(new Predicate<Person>()
* {
* public boolean accept(Person person)
* {
* return person.person.getLastName().equals("Smith");
* }
* }, Lists.mutable.of());
* </pre>
*
* @param predicate a {@link Predicate} to use as the reject criteria
* @param target the Collection to append to for all elements in this {@code RichIterable} that cause {@code Predicate#accept(Object)} method to evaluate to false
* @return {@code target}, which contains appended elements as a result of the reject criteria
* @since 1.0
*/
<R extends Collection<T>> R reject(Predicate<? super T> predicate, R target);
/**
* Similar to {@link #reject(Predicate, Collection)}, except with an evaluation parameter for the second generic argument in {@link Predicate2}.
* <p/>
* E.g. return a {@link Collection} of Person elements where the person has a height <b>greater than</b> 100cm
* <pre>
* return people.reject(new Predicate2<Person, Integer>()
* {
* public boolean accept(Person p, Integer i)
* {
* return p.getHeightInCm() < i.intValue();
* }
* }, Integer.valueOf(100), FastList.<Person>newList());
* </pre>
*
* @param predicate a {@link Predicate2} to use as the reject criteria
* @param parameter a parameter to pass in for evaluation of the second argument {@code P} in {@code predicate}
* @param targetCollection the Collection to append to for all elements in this {@code RichIterable} that cause {@code Predicate#accept(Object)} method to evaluate to false
* @return {@code targetCollection}, which contains appended elements as a result of the reject criteria
* @see #reject(Predicate)
* @see #reject(Predicate, Collection)
* @since 1.0
*/
<P, R extends Collection<T>> R rejectWith(
Predicate2<? super T, ? super P> predicate,
P parameter,
R targetCollection);
/**
* Filters a collection into a PartitionedIterable based on the evaluation of the predicate.
* <p/>
* <pre>e.g.
* return people.<b>partition</b>(new Predicate<Person>()
* {
* public boolean accept(Person person)
* {
* return person.getAddress().getState().getName().equals("New York");
* }
* });
* </pre>
*
* @since 1.0.
*/
PartitionIterable<T> partition(Predicate<? super T> predicate);
/**
* Returns all elements of the source collection that are instances of the Class {@code clazz}.
*
* @since 2.0
*/
<S> RichIterable<S> selectInstancesOf(Class<S> clazz);
/**
* Returns a new collection with the results of applying the specified function on each element of the source
* collection. This method is also commonly called transform or map.
* <p/>
* <pre>e.g.
* return people.collect(new Function<Person, String>()
* {
* public String valueOf(Person person)
* {
* return person.getFirstName() + " " + person.getLastName();
* }
* });
* </pre>
*
* @since 1.0
*/
<V> RichIterable<V> collect(Function<? super T, ? extends V> function);
/**
* Returns a new primitive {@code boolean} iterable with the results of applying the specified function on each element
* of the source collection. This method is also commonly called transform or map.
* <p/>
* <pre>e.g.
* return people.collectBoolean(new BooleanFunction<Person>()
* {
* public boolean booleanValueOf(Person person)
* {
* return person.hasDrivingLicense();
* }
* });
* </pre>
*
* @since 4.0
*/
BooleanIterable collectBoolean(BooleanFunction<? super T> booleanFunction);
/**
* Returns a new primitive {@code byte} iterable with the results of applying the specified function on each element
* of the source collection. This method is also commonly called transform or map.
* <p/>
* <pre>e.g.
* return people.collectByte(new ByteFunction<Person>()
* {
* public byte byteValueOf(Person person)
* {
* return person.getCode();
* }
* });
* </pre>
*
* @since 4.0
*/
ByteIterable collectByte(ByteFunction<? super T> byteFunction);
/**
* Returns a new primitive {@code char} iterable with the results of applying the specified function on each element
* of the source collection. This method is also commonly called transform or map.
* <p/>
* <pre>e.g.
* return people.collectChar(new CharFunction<Person>()
* {
* public char charValueOf(Person person)
* {
* return person.getMiddleInitial();
* }
* });
* </pre>
*
* @since 4.0
*/
CharIterable collectChar(CharFunction<? super T> charFunction);
/**
* Returns a new primitive {@code double} iterable with the results of applying the specified function on each element
* of the source collection. This method is also commonly called transform or map.
* <p/>
* <pre>e.g.
* return people.collectDouble(new DoubleFunction<Person>()
* {
* public double doubleValueOf(Person person)
* {
* return person.getMilesFromNorthPole();
* }
* });
* </pre>
*
* @since 4.0
*/
DoubleIterable collectDouble(DoubleFunction<? super T> doubleFunction);
/**
* Returns a new primitive {@code float} iterable with the results of applying the specified function on each element
* of the source collection. This method is also commonly called transform or map.
* <p/>
* <pre>e.g.
* return people.collectFloat(new FloatFunction<Person>()
* {
* public float floatValueOf(Person person)
* {
* return person.getHeightInInches();
* }
* });
* </pre>
*
* @since 4.0
*/
FloatIterable collectFloat(FloatFunction<? super T> floatFunction);
/**
* Returns a new primitive {@code int} iterable with the results of applying the specified function on each element
* of the source collection. This method is also commonly called transform or map.
* <p/>
* <pre>e.g.
* return people.collectInt(new IntFunction<Person>()
* {
* public int intValueOf(Person person)
* {
* return person.getAge();
* }
* });
* </pre>
*
* @since 4.0
*/
IntIterable collectInt(IntFunction<? super T> intFunction);
/**
* Returns a new primitive {@code long} iterable with the results of applying the specified function on each element
* of the source collection. This method is also commonly called transform or map.
* <p/>
* <pre>e.g.
* return people.collectLong(new LongFunction<Person>()
* {
* public long longValueOf(Person person)
* {
* return person.getGuid();
* }
* });
* </pre>
*
* @since 4.0
*/
LongIterable collectLong(LongFunction<? super T> longFunction);
/**
* Returns a new primitive {@code short} iterable with the results of applying the specified function on each element
* of the source collection. This method is also commonly called transform or map.
* <p/>
* <pre>e.g.
* return people.collectShort(new ShortFunction<Person>()
* {
* public short shortValueOf(Person person)
* {
* return person.getNumberOfJunkMailItemsReceivedPerMonth();
* }
* });
* </pre>
*
* @since 4.0
*/
ShortIterable collectShort(ShortFunction<? super T> shortFunction);
/**
* Same as {@link #collect(Function)}, except that the results are gathered into the specified {@code target}
* collection.
* <p/>
* <pre>e.g.
* return people.collect(new Function<Person, String>()
* {
* public String valueOf(Person person)
* {
* return person.getFirstName() + " " + person.getLastName();
* }
* }, Lists.mutable.of());
* </pre>
*
* @param function a {@link Function} to use as the collect transformation function
* @param target the Collection to append to for all elements in this {@code RichIterable} that meet select criteria {@code function}
* @return {@code target}, which contains appended elements as a result of the collect transformation
* @see #collect(Function)
* @since 1.0
*/
<V, R extends Collection<V>> R collect(Function<? super T, ? extends V> function, R target);
/**
* Same as collectWith but with a targetCollection parameter to gather the results.
* <p/>
* <pre>e.g.
* Function2<Integer, Integer, Integer> addParameterFunction =
* new Function2<Integer, Integer, Integer>()
* {
* public Integer value(final Integer each, final Integer parameter)
* {
* return each + parameter;
* }
* };
* FastList.newListWith(1, 2, 3).collectWith(addParameterFunction, Integer.valueOf(1), UnifiedSet.newSet());
* </pre>
*
* @param function a {@link Function2} to use as the collect transformation function
* @param parameter a parameter to pass in for evaluation of the second argument {@code P} in {@code function}
* @param targetCollection the Collection to append to for all elements in this {@code RichIterable} that meet select criteria {@code function}
* @return {@code targetCollection}, which contains appended elements as a result of the collect transformation
* @since 1.0
*/
<P, V, R extends Collection<V>> R collectWith(
Function2<? super T, ? super P, ? extends V> function,
P parameter,
R targetCollection);
/**
* Returns a new collection with the results of applying the specified function on each element of the source
* collection, but only for those elements which return true upon evaluation of the predicate. This is the
* the optimized equivalent of calling iterable.select(predicate).collect(function).
* <p/>
* <pre>e.g.
* Lists.mutable.of().with(1, 2, 3).collectIf(Predicates.notNull(), Functions.getToString())
* </pre>
*
* @since 1.0
*/
<V> RichIterable<V> collectIf(Predicate<? super T> predicate, Function<? super T, ? extends V> function);
/**
* Same as the collectIf method with two parameters but uses the specified target collection for the results.
*
* @param predicate a {@link Predicate} to use as the select criteria
* @param function a {@link Function} to use as the collect transformation function
* @param target the Collection to append to for all elements in this {@code RichIterable} that meet the collect criteria {@code predicate}
* @return {@code targetCollection}, which contains appended elements as a result of the collect criteria and transformation
* @see #collectIf(Predicate, Function)
* @since 1.0
*/
<V, R extends Collection<V>> R collectIf(
Predicate<? super T> predicate,
Function<? super T, ? extends V> function,
R target);
/**
* {@code flatCollect} is a special case of {@link #collect(Function)}. With {@code collect}, when the {@link Function} returns
* a collection, the result is a collection of collections. {@code flatCollect} outputs a single "flattened" collection
* instead. This method is commonly called flatMap.
* <p/>
* Consider the following example where we have a {@code Person} class, and each {@code Person} has a list of {@code Address} objects. Take the following {@link Function}:
* <pre>
* Function<Person, List<Address>> addressFunction = new Function<Person, List<Address>>() {
* public List<Address> valueOf(Person person) {
* return person.getAddresses();
* }
* };
* MutableList<Person> people = ...;
* </pre>
* Using {@code collect} returns a collection of collections of addresses.
* <pre>
* MutableList<List<Address>> addresses = people.collect(addressFunction);
* </pre>
* Using {@code flatCollect} returns a single flattened list of addresses.
* <pre>
* MutableList<Address> addresses = people.flatCollect(addressFunction);
* </pre>
*
* @param function The {@link Function} to apply
* @return a new flattened collection produced by applying the given {@code function}
* @since 1.0
*/
<V> RichIterable<V> flatCollect(Function<? super T, ? extends Iterable<V>> function);
/**
* Same as flatCollect, only the results are collected into the target collection.
*
* @param function The {@link Function} to apply
* @param target The collection into which results should be added.
* @return {@code target}, which will contain a flattened collection of results produced by applying the given {@code function}
* @see #flatCollect(Function)
*/
<V, R extends Collection<V>> R flatCollect(Function<? super T, ? extends Iterable<V>> function, R target);
/**
* Returns the first element of the iterable for which the predicate evaluates to true or null in the case where no
* element returns true. This method is commonly called find.
* <p/>
* <pre>e.g.
* return people.detect(new Predicate<Person>()
* {
* public boolean value(Person person)
* {
* return person.getFirstName().equals("John") && person.getLastName().equals("Smith");
* }
* });
* </pre>
*
* @since 1.0
*/
T detect(Predicate<? super T> predicate);
/**
* Returns the first element of the iterable for which the predicate evaluates to true. If no element matches
* the predicate, then returns the value of applying the specified function.
*
* @since 1.0
*/
T detectIfNone(Predicate<? super T> predicate, Function0<? extends T> function);
/**
* Return the total number of elements that answer true to the specified predicate.
* <p/>
* <pre>e.g.
* return people.<b>count</b>(new Predicate<Person>()
* {
* public boolean value(Person person)
* {
* return person.getAddress().getState().getName().equals("New York");
* }
* });
* </pre>
*
* @since 1.0
*/
int count(Predicate<? super T> predicate);
/**
* Returns true if the predicate evaluates to true for any element of the iterable. Returns
* false if the iterable is empty, or if no element returned true when evaluating the predicate.
*
* @since 1.0
*/
boolean anySatisfy(Predicate<? super T> predicate);
/**
* Returns true if the predicate evaluates to true for every element of the iterable or if the iterable is empty.
* Otherwise, returns false.
*
* @since 1.0
*/
boolean allSatisfy(Predicate<? super T> predicate);
/**
* Returns true if the predicate evaluates to false for every element of the iterable or if the iterable is empty.
* Otherwise, returns false.
*
* @since 3.0
*/
boolean noneSatisfy(Predicate<? super T> predicate);
/**
* Returns the final result of evaluating function using each element of the iterable and the previous evaluation
* result as the parameters. The injected value is used for the first parameter of the first evaluation, and the current
* item in the iterable is used as the second parameter. This method is commonly called fold or sometimes reduce.
*
* @since 1.0
*/
<IV> IV injectInto(IV injectedValue, Function2<? super IV, ? super T, ? extends IV> function);
/**
* Returns the final int result of evaluating function using each element of the iterable and the previous evaluation
* result as the parameters. The injected value is used for the first parameter of the first evaluation, and the current
* item in the iterable is used as the second parameter.
*
* @since 1.0
*/
int injectInto(int injectedValue, IntObjectToIntFunction<? super T> function);
/**
* Returns the final long result of evaluating function using each element of the iterable and the previous evaluation
* result as the parameters. The injected value is used for the first parameter of the first evaluation, and the current
* item in the iterable is used as the second parameter.
*
* @since 1.0
*/
long injectInto(long injectedValue, LongObjectToLongFunction<? super T> function);
/**
* Returns the final float result of evaluating function using each element of the iterable and the previous evaluation
* result as the parameters. The injected value is used for the first parameter of the first evaluation, and the current
* item in the iterable is used as the second parameter.
*
* @since 2.0
*/
float injectInto(float injectedValue, FloatObjectToFloatFunction<? super T> function);
/**
* Returns the final double result of evaluating function using each element of the iterable and the previous evaluation
* result as the parameters. The injected value is used for the first parameter of the first evaluation, and the current
* item in the iterable is used as the second parameter.
*
* @since 1.0
*/
double injectInto(double injectedValue, DoubleObjectToDoubleFunction<? super T> function);
/**
* Converts the collection to a MutableList implementation.
*
* @since 1.0
*/
MutableList<T> toList();
/**
* Converts the collection to a MutableList implementation and sorts it using the natural order of the elements.
*
* @since 1.0
*/
MutableList<T> toSortedList();
/**
* Converts the collection to a MutableList implementation and sorts it using the specified comparator.
*
* @since 1.0
*/
MutableList<T> toSortedList(Comparator<? super T> comparator);
/**
* Converts the collection to a MutableList implementation and sorts it based on the natural order of the
* attribute returned by {@code function}.
*
* @since 1.0
*/
<V extends Comparable<? super V>> MutableList<T> toSortedListBy(Function<? super T, ? extends V> function);
/**
* Converts the collection to a MutableSet implementation.
*
* @since 1.0
*/
MutableSet<T> toSet();
/**
* Converts the collection to a MutableSortedSet implementation and sorts it using the natural order of the
* elements.
*
* @since 1.0
*/
MutableSortedSet<T> toSortedSet();
/**
* Converts the collection to a MutableSortedSet implementation and sorts it using the specified comparator.
*
* @since 1.0
*/
MutableSortedSet<T> toSortedSet(Comparator<? super T> comparator);
/**
* Converts the collection to a MutableSortedSet implementation and sorts it based on the natural order of the
* attribute returned by {@code function}.
*
* @since 1.0
*/
<V extends Comparable<? super V>> MutableSortedSet<T> toSortedSetBy(Function<? super T, ? extends V> function);
/**
* Converts the collection to the default MutableBag implementation.
*
* @since 1.0
*/
MutableBag<T> toBag();
/**
* Converts the collection to a MutableMap implementation using the specified key and value functions.
*
* @since 1.0
*/
<NK, NV> MutableMap<NK, NV> toMap(
Function<? super T, ? extends NK> keyFunction,
Function<? super T, ? extends NV> valueFunction);
/**
* Converts the collection to a MutableSortedMap implementation using the specified key and value functions
* sorted by the key elements' natural ordering.
*
* @since 1.0
*/
<NK, NV> MutableSortedMap<NK, NV> toSortedMap(
Function<? super T, ? extends NK> keyFunction,
Function<? super T, ? extends NV> valueFunction);
/**
* Converts the collection to a MutableSortedMap implementation using the specified key and value functions
* sorted by the given comparator.
*
* @since 1.0
*/
<NK, NV> MutableSortedMap<NK, NV> toSortedMap(
Comparator<? super NK> comparator,
Function<? super T, ? extends NK> keyFunction,
Function<? super T, ? extends NV> valueFunction);
/**
* Returns a lazy (deferred) iterable, most likely implemented by calling LazyIterate.adapt(this).
*
* @since 1.0.
*/
LazyIterable<T> asLazy();
/**
* Converts this iterable to an array.
*
* @see Collection#toArray()
* @since 1.0
*/
Object[] toArray();
/**
* Converts this iterable to an array using the specified target array, assuming the target array is as long
* or longer than the iterable.
*
* @see Collection#toArray(Object[])
* @since 1.0
*/
<T> T[] toArray(T[] target);
/**
* Returns the minimum element out of this container based on the comparator.
*
* @throws NoSuchElementException if the RichIterable is empty
* @since 1.0
*/
T min(Comparator<? super T> comparator);
/**
* Returns the maximum element out of this container based on the comparator.
*
* @throws NoSuchElementException if the RichIterable is empty
* @since 1.0
*/
T max(Comparator<? super T> comparator);
/**
* Returns the minimum element out of this container based on the natural order.
*
* @throws ClassCastException if the elements are not {@link Comparable}
* @throws NoSuchElementException if the RichIterable is empty
* @since 1.0
*/
T min();
/**
* Returns the maximum element out of this container based on the natural order.
*
* @throws ClassCastException if the elements are not {@link Comparable}
* @throws NoSuchElementException if the RichIterable is empty
* @since 1.0
*/
T max();
/**
* Returns the minimum elements out of this container based on the natural order of the attribute returned by Function.
*
* @throws NoSuchElementException if the RichIterable is empty
* @since 1.0
*/
<V extends Comparable<? super V>> T minBy(Function<? super T, ? extends V> function);
/**
* Returns the maximum elements out of this container based on the natural order of the attribute returned by Function.
*
* @throws NoSuchElementException if the RichIterable is empty
* @since 1.0
*/
<V extends Comparable<? super V>> T maxBy(Function<? super T, ? extends V> function);
/**
* Returns the final long result of evaluating function for each element of the iterable and adding the results
* together.
*
* @since 2.0
*/
long sumOfInt(IntFunction<? super T> function);
/**
* Returns the final double result of evaluating function for each element of the iterable and adding the results
* together.
*
* @since 2.0
*/
double sumOfFloat(FloatFunction<? super T> function);
/**
* Returns the final long result of evaluating function for each element of the iterable and adding the results
* together.
*
* @since 2.0
*/
long sumOfLong(LongFunction<? super T> function);
/**
* Returns the final double result of evaluating function for each element of the iterable and adding the results
* together.
*
* @since 2.0
*/
double sumOfDouble(DoubleFunction<? super T> function);
/**
* Returns a string representation of this collection by delegating to {@link #makeString(String)} and defaulting
* the separator parameter to the characters <tt>", "</tt> (comma and space).
*
* @return a string representation of this collection.
* @since 1.0
*/
String makeString();
/**
* Returns a string representation of this collection by delegating to {@link #makeString(String, String, String)}
* and defaulting the start and end parameters to <tt>""</tt> (the empty String).
*
* @return a string representation of this collection.
* @since 1.0
*/
String makeString(String separator);
/**
* Returns a string representation of this collection. The string representation consists of a list of the
* collection's elements in the order they are returned by its iterator, enclosed in the start and end strings.
* Adjacent elements are separated by the separator string. Elements are converted to strings as by
* <tt>String.valueOf(Object)</tt>.
*
* @return a string representation of this collection.
* @since 1.0
*/
String makeString(String start, String separator, String end);
/**
* Prints a string representation of this collection onto the given {@code Appendable}. Prints the string returned
* by {@link #makeString()}.
*
* @since 1.0
*/
void appendString(Appendable appendable);
/**
* Prints a string representation of this collection onto the given {@code Appendable}. Prints the string returned
* by {@link #makeString(String)}.
*
* @since 1.0
*/
void appendString(Appendable appendable, String separator);
/**
* Prints a string representation of this collection onto the given {@code Appendable}. Prints the string returned
* by {@link #makeString(String, String, String)}.
*
* @since 1.0
*/
void appendString(Appendable appendable, String start, String separator, String end);
/**
* For each element of the iterable, the function is evaluated and the results of these evaluations are collected
* into a new multimap, where the transformed value is the key and the original values are added to the same (or similar)
* species of collection as the source iterable.
* <p/>
* <pre>e.g.
* return people.groupBy(new Function<Person, String>()
* {
* public String value(Person person)
* {
* return person.getFirstName() + " " + person.getLastName();
* }
* });
* </pre>
*
* @since 1.0
*/
<V> Multimap<V, T> groupBy(Function<? super T, ? extends V> function);
/**
* Same as {@link #groupBy(Function)}, except that the results are gathered into the specified {@code target}
* multimap.
* <p/>
* <pre>e.g.
* return people.groupBy(new Function<Person, String>()
* {
* public String value(Person person)
* {
* return person.getFirstName() + " " + person.getLastName();
* }
* }, new FastListMultimap<String, Person>());
* </pre>
*
* @since 1.0
*/
<V, R extends MutableMultimap<V, T>> R groupBy(Function<? super T, ? extends V> function, R target);
/**
* Similar to {@link #groupBy(Function)}, except the result of evaluating function will return a collection of keys
* for each value.
*
* @since 1.0
*/
<V> Multimap<V, T> groupByEach(Function<? super T, ? extends Iterable<V>> function);
/**
* Same as {@link #groupByEach(Function)}, except that the results are gathered into the specified {@code target}
* multimap.
*
* @since 1.0
*/
<V, R extends MutableMultimap<V, T>> R groupByEach(
Function<? super T, ? extends Iterable<V>> function,
R target);
/**
* Returns a string representation of this RichIterable. The string representation consists of a list of the
* RichIterable's elements in the order they are returned by its iterator, enclosed in square brackets
* (<tt>"[]"</tt>). Adjacent elements are separated by the characters <tt>", "</tt> (comma and space). Elements
* are converted to strings as by {@link String#valueOf(Object)}.
*
* @return a string representation of this RichIterable
* @since 1.0
*/
@Override
String toString();
/**
* Returns a {@code RichIterable} formed from this {@code RichIterable} and another {@code RichIterable} by
* combining corresponding elements in pairs. If one of the two {@code RichIterable}s is longer than the other, its
* remaining elements are ignored.
*
* @param that The {@code RichIterable} providing the second half of each result pair
* @param <S> the type of the second half of the returned pairs
* @return A new {@code RichIterable} containing pairs consisting of corresponding elements of this {@code
* RichIterable} and that. The length of the returned {@code RichIterable} is the minimum of the lengths of
* this {@code RichIterable} and that.
* @since 1.0
*/
<S> RichIterable<Pair<T, S>> zip(Iterable<S> that);
/**
* Same as {@link #zip(Iterable)} but uses {@code target} for output.
*
* @since 1.0
*/
<S, R extends Collection<Pair<T, S>>> R zip(Iterable<S> that, R target);
/**
* Zips this {@code RichIterable} with its indices.
*
* @return A new {@code RichIterable} containing pairs consisting of all elements of this {@code RichIterable}
* paired with their index. Indices start at 0.
* @see #zip(Iterable)
* @since 1.0
*/
RichIterable<Pair<T, Integer>> zipWithIndex();
/**
* Same as {@link #zipWithIndex()} but uses {@code target} for output.
*
* @since 1.0
*/
<R extends Collection<Pair<T, Integer>>> R zipWithIndex(R target);
/**
* Partitions elements in fixed size chunks.
*
* @param size the number of elements per chunk
* @return A {@code RichIterable} containing {@code RichIterable}s of size {@code size}, except the last will be
* truncated if the elements don't divide evenly.
* @since 1.0
*/
RichIterable<RichIterable<T>> chunk(int size);
/**
* Applies an aggregate procedure over the iterable grouping results into a Map based on the specific groupBy function.
* Aggregate results are required to be mutable as they will be changed in place by the procedure. A second function
* specifies the initial "zero" aggregate value to work with (i.e. new AtomicInteger(0)).
*
* @since 3.0
*/
<K, V> MapIterable<K, V> aggregateInPlaceBy(Function<? super T, ? extends K> groupBy, Function0<? extends V> zeroValueFactory, Procedure2<? super V, ? super T> mutatingAggregator);
/**
* Applies an aggregate function over the iterable grouping results into a map based on the specific groupBy function.
* Aggregate results are allowed to be immutable as they will be replaced in place in the map. A second function
* specifies the initial "zero" aggregate value to work with (i.e. new Integer(0)).
*
* @since 3.0
*/
<K, V> MapIterable<K, V> aggregateBy(Function<? super T, ? extends K> groupBy, Function0<? extends V> zeroValueFactory, Function2<? super V, ? super T, ? extends V> nonMutatingAggregator);
}
| collections-api/src/main/java/com/gs/collections/api/RichIterable.java | /*
* Copyright 2011 Goldman Sachs.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.gs.collections.api;
import java.util.Collection;
import java.util.Comparator;
import java.util.NoSuchElementException;
import com.gs.collections.api.bag.MutableBag;
import com.gs.collections.api.block.function.Function;
import com.gs.collections.api.block.function.Function0;
import com.gs.collections.api.block.function.Function2;
import com.gs.collections.api.block.function.primitive.BooleanFunction;
import com.gs.collections.api.block.function.primitive.ByteFunction;
import com.gs.collections.api.block.function.primitive.CharFunction;
import com.gs.collections.api.block.function.primitive.DoubleFunction;
import com.gs.collections.api.block.function.primitive.DoubleObjectToDoubleFunction;
import com.gs.collections.api.block.function.primitive.FloatFunction;
import com.gs.collections.api.block.function.primitive.FloatObjectToFloatFunction;
import com.gs.collections.api.block.function.primitive.IntFunction;
import com.gs.collections.api.block.function.primitive.IntObjectToIntFunction;
import com.gs.collections.api.block.function.primitive.LongFunction;
import com.gs.collections.api.block.function.primitive.LongObjectToLongFunction;
import com.gs.collections.api.block.function.primitive.ShortFunction;
import com.gs.collections.api.block.predicate.Predicate;
import com.gs.collections.api.block.predicate.Predicate2;
import com.gs.collections.api.block.procedure.Procedure2;
import com.gs.collections.api.list.MutableList;
import com.gs.collections.api.map.MapIterable;
import com.gs.collections.api.map.MutableMap;
import com.gs.collections.api.map.sorted.MutableSortedMap;
import com.gs.collections.api.multimap.Multimap;
import com.gs.collections.api.multimap.MutableMultimap;
import com.gs.collections.api.partition.PartitionIterable;
import com.gs.collections.api.set.MutableSet;
import com.gs.collections.api.set.sorted.MutableSortedSet;
import com.gs.collections.api.tuple.Pair;
/**
* RichIterable is an interface which extends the InternalIterable interface with several internal iterator methods, from
* the Smalltalk Collection protocol. These include select, reject, detect, collect, injectInto, anySatisfy,
* allSatisfy. The API also includes converter methods to convert a RichIterable to a List (toList), to a sorted
* List (toSortedList), to a Set (toSet), and to a Map (toMap).
*
* @since 1.0
*/
public interface
RichIterable<T>
extends InternalIterable<T>
{
/**
* Returns the number of items in this iterable.
*
* @since 1.0
*/
int size();
/**
* Returns true if this iterable has zero items.
*
* @since 1.0
*/
boolean isEmpty();
/**
* The English equivalent of !this.isEmpty()
*
* @since 1.0
*/
boolean notEmpty();
/**
* Returns the first element of an iterable. In the case of a List it is the element at the first index. In the
* case of any other Collection, it is the first element that would be returned during an iteration. If the
* iterable is empty, null is returned. If null is a valid element of the container, then a developer would need to
* check to see if the iterable is empty to validate that a null result was not due to the container being empty.
* <p/>
* The order of Sets are not guaranteed (except for TreeSets and other Ordered Set implementations), so if you use
* this method, the first element could be any element from the Set.
*
* @since 1.0
*/
T getFirst();
/**
* Returns the last element of an iterable. In the case of a List it is the element at the last index. In the case
* of any other Collection, it is the last element that would be returned during an iteration. If the iterable is
* empty, null is returned. If null is a valid element of the container, then a developer would need to check to
* see if the iterable is empty to validate that a null result was not due to the container being empty.
* <p/>
* The order of Sets are not guaranteed (except for TreeSets and other Ordered Set implementations), so if you use
* this method, the last element could be any element from the Set.
*
* @since 1.0
*/
T getLast();
/**
* Returns true if the iterable has an element which responds true to element.equals(object).
*
* @since 1.0
*/
boolean contains(Object object);
/**
* Returns true if all elements in source are contained in this collection.
*
* @since 1.0
*/
boolean containsAllIterable(Iterable<?> source);
/**
* Returns true if all elements in source are contained in this collection.
*
* @see Collection#containsAll(Collection)
* @since 1.0
*/
boolean containsAll(Collection<?> source);
/**
* Returns true if all elements in the specified var arg array are contained in this collection.
*
* @since 1.0
*/
boolean containsAllArguments(Object... elements);
/**
* Returns all elements of the source collection that return true when evaluating the predicate. This method is also
* commonly called filter.
* <p/>
* <pre>e.g.
* return people.<b>select</b>(new Predicate<Person>()
* {
* public boolean accept(Person person)
* {
* return person.getAddress().getCity().equals("Metuchen");
* }
* });
* </pre>
*
* @since 1.0
*/
RichIterable<T> select(Predicate<? super T> predicate);
/**
* Same as the select method with one parameter but uses the specified target collection for the results.
* <p/>
* <pre>e.g.
* return people.select(new Predicate<Person>()
* {
* public boolean accept(Person person)
* {
* return person.person.getLastName().equals("Smith");
* }
* }, Lists.mutable.of());
* </pre>
* <p/>
* <pre>e.g.
* return collection.select(Predicates.attributeEqual("lastName", "Smith"), new ArrayList());
* </pre>
*
* @param predicate a {@link Predicate} to use as the select criteria
* @param target the Collection to append to for all elements in this {@code RichIterable} that meet select criteria {@code predicate}
* @return {@code target}, which contains appended elements as a result of the select criteria
* @see #select(Predicate)
* @since 1.0
*/
<R extends Collection<T>> R select(Predicate<? super T> predicate, R target);
/**
* Similar to {@link #select(Predicate, Collection)}, except with an evaluation parameter for the second generic argument in {@link Predicate2}.
*
* @param predicate a {@link Predicate2} to use as the select criteria
* @param parameter a parameter to pass in for evaluation of the second argument {@code P} in {@code predicate}
* @see #select(Predicate)
* @see #select(Predicate, Collection)
* @since 5.0
*/
<P> RichIterable<T> selectWith(Predicate2<? super T, ? super P> predicate, P parameter);
/**
* Similar to {@link #select(Predicate, Collection)}, except with an evaluation parameter for the second generic argument in {@link Predicate2}.
*
* @param predicate a {@link Predicate2} to use as the select criteria
* @param parameter a parameter to pass in for evaluation of the second argument {@code P} in {@code predicate}
* @param targetCollection the Collection to append to for all elements in this {@code RichIterable} that meet select criteria {@code predicate}
* @return {@code targetCollection}, which contains appended elements as a result of the select criteria
* @see #select(Predicate)
* @see #select(Predicate, Collection)
* @since 1.0
*/
<P, R extends Collection<T>> R selectWith(
Predicate2<? super T, ? super P> predicate,
P parameter,
R targetCollection);
/**
* Returns all elements of the source collection that return false when evaluating of the predicate. This method is also
* sometimes called filterNot and is the equivalent of calling iterable.select(Predicates.not(predicate)).
* <p/>
* <pre>e.g.
* return people.reject(new Predicate<Person>()
* {
* public boolean accept(Person person)
* {
* return person.person.getLastName().equals("Smith");
* }
* });
* </pre>
* <p/>
* <pre>e.g.
* return people.reject(Predicates.attributeEqual("lastName", "Smith"));
* </pre>
*
* @param predicate a {@link Predicate} to use as the reject criteria
* @return a RichIterable that contains elements that cause {@link Predicate#accept(Object)} method to evaluate to false
* @since 1.0
*/
RichIterable<T> reject(Predicate<? super T> predicate);
/**
* Same as the reject method with one parameter but uses the specified target collection for the results.
* <p/>
* <pre>e.g.
* return people.reject(new Predicate<Person>()
* {
* public boolean accept(Person person)
* {
* return person.person.getLastName().equals("Smith");
* }
* }, Lists.mutable.of());
* </pre>
*
* @param predicate a {@link Predicate} to use as the reject criteria
* @param target the Collection to append to for all elements in this {@code RichIterable} that cause {@code Predicate#accept(Object)} method to evaluate to false
* @return {@code target}, which contains appended elements as a result of the reject criteria
* @since 1.0
*/
<R extends Collection<T>> R reject(Predicate<? super T> predicate, R target);
/**
* Similar to {@link #reject(Predicate, Collection)}, except with an evaluation parameter for the second generic argument in {@link Predicate2}.
* <p/>
* E.g. return a {@link Collection} of Person elements where the person has a height <b>greater than</b> 100cm
* <pre>
* return people.reject(new Predicate2<Person, Integer>()
* {
* public boolean accept(Person p, Integer i)
* {
* return p.getHeightInCm() < i.intValue();
* }
* }, Integer.valueOf(100), FastList.<Person>newList());
* </pre>
*
* @param predicate a {@link Predicate2} to use as the reject criteria
* @param parameter a parameter to pass in for evaluation of the second argument {@code P} in {@code predicate}
* @param targetCollection the Collection to append to for all elements in this {@code RichIterable} that cause {@code Predicate#accept(Object)} method to evaluate to false
* @return {@code targetCollection}, which contains appended elements as a result of the reject criteria
* @see #reject(Predicate)
* @see #reject(Predicate, Collection)
* @since 1.0
*/
<P, R extends Collection<T>> R rejectWith(
Predicate2<? super T, ? super P> predicate,
P parameter,
R targetCollection);
/**
* Filters a collection into a PartitionedIterable based on the evaluation of the predicate.
* <p/>
* <pre>e.g.
* return people.<b>partition</b>(new Predicate<Person>()
* {
* public boolean accept(Person person)
* {
* return person.getAddress().getState().getName().equals("New York");
* }
* });
* </pre>
*
* @since 1.0.
*/
PartitionIterable<T> partition(Predicate<? super T> predicate);
/**
* Returns all elements of the source collection that are instances of the Class {@code clazz}.
*
* @since 2.0
*/
<S> RichIterable<S> selectInstancesOf(Class<S> clazz);
/**
* Returns a new collection with the results of applying the specified function on each element of the source
* collection. This method is also commonly called transform or map.
* <p/>
* <pre>e.g.
* return people.collect(new Function<Person, String>()
* {
* public String valueOf(Person person)
* {
* return person.getFirstName() + " " + person.getLastName();
* }
* });
* </pre>
*
* @since 1.0
*/
<V> RichIterable<V> collect(Function<? super T, ? extends V> function);
/**
* Returns a new primitive {@code boolean} iterable with the results of applying the specified function on each element
* of the source collection. This method is also commonly called transform or map.
* <p/>
* <pre>e.g.
* return people.collectBoolean(new BooleanFunction<Person>()
* {
* public boolean booleanValueOf(Person person)
* {
* return person.hasDrivingLicense();
* }
* });
* </pre>
*
* @since 4.0
*/
BooleanIterable collectBoolean(BooleanFunction<? super T> booleanFunction);
/**
* Returns a new primitive {@code byte} iterable with the results of applying the specified function on each element
* of the source collection. This method is also commonly called transform or map.
* <p/>
* <pre>e.g.
* return people.collectByte(new ByteFunction<Person>()
* {
* public byte byteValueOf(Person person)
* {
* return person.getCode();
* }
* });
* </pre>
*
* @since 4.0
*/
ByteIterable collectByte(ByteFunction<? super T> byteFunction);
/**
* Returns a new primitive {@code char} iterable with the results of applying the specified function on each element
* of the source collection. This method is also commonly called transform or map.
* <p/>
* <pre>e.g.
* return people.collectChar(new CharFunction<Person>()
* {
* public char charValueOf(Person person)
* {
* return person.getMiddleInitial();
* }
* });
* </pre>
*
* @since 4.0
*/
CharIterable collectChar(CharFunction<? super T> charFunction);
/**
* Returns a new primitive {@code double} iterable with the results of applying the specified function on each element
* of the source collection. This method is also commonly called transform or map.
* <p/>
* <pre>e.g.
* return people.collectDouble(new DoubleFunction<Person>()
* {
* public double doubleValueOf(Person person)
* {
* return person.getMilesFromNorthPole();
* }
* });
* </pre>
*
* @since 4.0
*/
DoubleIterable collectDouble(DoubleFunction<? super T> doubleFunction);
/**
* Returns a new primitive {@code float} iterable with the results of applying the specified function on each element
* of the source collection. This method is also commonly called transform or map.
* <p/>
* <pre>e.g.
* return people.collectFloat(new FloatFunction<Person>()
* {
* public float floatValueOf(Person person)
* {
* return person.getHeightInInches();
* }
* });
* </pre>
*
* @since 4.0
*/
FloatIterable collectFloat(FloatFunction<? super T> floatFunction);
/**
* Returns a new primitive {@code int} iterable with the results of applying the specified function on each element
* of the source collection. This method is also commonly called transform or map.
* <p/>
* <pre>e.g.
* return people.collectInt(new IntFunction<Person>()
* {
* public int intValueOf(Person person)
* {
* return person.getAge();
* }
* });
* </pre>
*
* @since 4.0
*/
IntIterable collectInt(IntFunction<? super T> intFunction);
/**
* Returns a new primitive {@code long} iterable with the results of applying the specified function on each element
* of the source collection. This method is also commonly called transform or map.
* <p/>
* <pre>e.g.
* return people.collectLong(new LongFunction<Person>()
* {
* public long longValueOf(Person person)
* {
* return person.getGuid();
* }
* });
* </pre>
*
* @since 4.0
*/
LongIterable collectLong(LongFunction<? super T> longFunction);
/**
* Returns a new primitive {@code short} iterable with the results of applying the specified function on each element
* of the source collection. This method is also commonly called transform or map.
* <p/>
* <pre>e.g.
* return people.collectShort(new ShortFunction<Person>()
* {
* public short shortValueOf(Person person)
* {
* return person.getNumberOfJunkMailItemsReceivedPerMonth();
* }
* });
* </pre>
*
* @since 4.0
*/
ShortIterable collectShort(ShortFunction<? super T> shortFunction);
/**
* Same as {@link #collect(Function)}, except that the results are gathered into the specified {@code target}
* collection.
* <p/>
* <pre>e.g.
* return people.collect(new Function<Person, String>()
* {
* public String valueOf(Person person)
* {
* return person.getFirstName() + " " + person.getLastName();
* }
* }, Lists.mutable.of());
* </pre>
*
* @param function a {@link Function} to use as the collect transformation function
* @param target the Collection to append to for all elements in this {@code RichIterable} that meet select criteria {@code function}
* @return {@code target}, which contains appended elements as a result of the collect transformation
* @see #collect(Function)
* @since 1.0
*/
<V, R extends Collection<V>> R collect(Function<? super T, ? extends V> function, R target);
/**
* Same as collectWith but with a targetCollection parameter to gather the results.
* <p/>
* <pre>e.g.
* Function2<Integer, Integer, Integer> addParameterFunction =
* new Function2<Integer, Integer, Integer>()
* {
* public Integer value(final Integer each, final Integer parameter)
* {
* return each + parameter;
* }
* };
* FastList.newListWith(1, 2, 3).collectWith(addParameterFunction, Integer.valueOf(1), UnifiedSet.newSet());
* </pre>
*
* @param function a {@link Function2} to use as the collect transformation function
* @param parameter a parameter to pass in for evaluation of the second argument {@code P} in {@code function}
* @param targetCollection the Collection to append to for all elements in this {@code RichIterable} that meet select criteria {@code function}
* @return {@code targetCollection}, which contains appended elements as a result of the collect transformation
* @since 1.0
*/
<P, V, R extends Collection<V>> R collectWith(
Function2<? super T, ? super P, ? extends V> function,
P parameter,
R targetCollection);
/**
* Returns a new collection with the results of applying the specified function on each element of the source
* collection, but only for those elements which return true upon evaluation of the predicate. This is the
* the optimized equivalent of calling iterable.select(predicate).collect(function).
* <p/>
* <pre>e.g.
* Lists.mutable.of().with(1, 2, 3).collectIf(Predicates.notNull(), Functions.getToString())
* </pre>
*
* @since 1.0
*/
<V> RichIterable<V> collectIf(Predicate<? super T> predicate, Function<? super T, ? extends V> function);
/**
* Same as the collectIf method with two parameters but uses the specified target collection for the results.
*
* @param predicate a {@link Predicate} to use as the select criteria
* @param function a {@link Function} to use as the collect transformation function
* @param target the Collection to append to for all elements in this {@code RichIterable} that meet the collect criteria {@code predicate}
* @return {@code targetCollection}, which contains appended elements as a result of the collect criteria and transformation
* @see #collectIf(Predicate, Function)
* @since 1.0
*/
<V, R extends Collection<V>> R collectIf(
Predicate<? super T> predicate,
Function<? super T, ? extends V> function,
R target);
/**
* {@code flatCollect} is a special case of {@link #collect(Function)}. With {@code collect}, when the {@link Function} returns
* a collection, the result is a collection of collections. {@code flatCollect} outputs a single "flattened" collection
* instead. This method is commonly called flatMap.
* <p/>
* Consider the following example where we have a {@code Person} class, and each {@code Person} has a list of {@code Address} objects. Take the following {@link Function}:
* <pre>
* Function<Person, List<Address>> addressFunction = new Function<Person, List<Address>>() {
* public List<Address> valueOf(Person person) {
* return person.getAddresses();
* }
* };
* MutableList<Person> people = ...;
* </pre>
* Using {@code collect} returns a collection of collections of addresses.
* <pre>
* MutableList<List<Address>> addresses = people.collect(addressFunction);
* </pre>
* Using {@code flatCollect} returns a single flattened list of addresses.
* <pre>
* MutableList<Address> addresses = people.flatCollect(addressFunction);
* </pre>
*
* @param function The {@link Function} to apply
* @return a new flattened collection produced by applying the given {@code function}
* @since 1.0
*/
<V> RichIterable<V> flatCollect(Function<? super T, ? extends Iterable<V>> function);
/**
* Same as flatCollect, only the results are collected into the target collection.
*
* @param function The {@link Function} to apply
* @param target The collection into which results should be added.
* @return {@code target}, which will contain a flattened collection of results produced by applying the given {@code function}
* @see #flatCollect(Function)
*/
<V, R extends Collection<V>> R flatCollect(Function<? super T, ? extends Iterable<V>> function, R target);
/**
* Returns the first element of the iterable for which the predicate evaluates to true or null in the case where no
* element returns true. This method is commonly called find.
* <p/>
* <pre>e.g.
* return people.detect(new Predicate<Person>()
* {
* public boolean value(Person person)
* {
* return person.getFirstName().equals("John") && person.getLastName().equals("Smith");
* }
* });
* </pre>
*
* @since 1.0
*/
T detect(Predicate<? super T> predicate);
/**
* Returns the first element of the iterable for which the predicate evaluates to true. If no element matches
* the predicate, then returns the value of applying the specified function.
*
* @since 1.0
*/
T detectIfNone(Predicate<? super T> predicate, Function0<? extends T> function);
/**
* Return the total number of elements that answer true to the specified predicate.
* <p/>
* <pre>e.g.
* return people.<b>count</b>(new Predicate<Person>()
* {
* public boolean value(Person person)
* {
* return person.getAddress().getState().getName().equals("New York");
* }
* });
* </pre>
*
* @since 1.0
*/
int count(Predicate<? super T> predicate);
/**
* Returns true if the predicate evaluates to true for any element of the iterable. Returns
* false if the iterable is empty, or if no element returned true when evaluating the predicate.
*
* @since 1.0
*/
boolean anySatisfy(Predicate<? super T> predicate);
/**
* Returns true if the predicate evaluates to true for every element of the iterable or if the iterable is empty.
* Otherwise, returns false.
*
* @since 1.0
*/
boolean allSatisfy(Predicate<? super T> predicate);
/**
* Returns true if the predicate evaluates to false for every element of the iterable or if the iterable is empty.
* Otherwise, returns false.
*
* @since 3.0
*/
boolean noneSatisfy(Predicate<? super T> predicate);
/**
* Returns the final result of evaluating function using each element of the iterable and the previous evaluation
* result as the parameters. The injected value is used for the first parameter of the first evaluation, and the current
* item in the iterable is used as the second parameter. This method is commonly called fold or sometimes reduce.
*
* @since 1.0
*/
<IV> IV injectInto(IV injectedValue, Function2<? super IV, ? super T, ? extends IV> function);
/**
* Returns the final int result of evaluating function using each element of the iterable and the previous evaluation
* result as the parameters. The injected value is used for the first parameter of the first evaluation, and the current
* item in the iterable is used as the second parameter.
*
* @since 1.0
*/
int injectInto(int injectedValue, IntObjectToIntFunction<? super T> function);
/**
* Returns the final long result of evaluating function using each element of the iterable and the previous evaluation
* result as the parameters. The injected value is used for the first parameter of the first evaluation, and the current
* item in the iterable is used as the second parameter.
*
* @since 1.0
*/
long injectInto(long injectedValue, LongObjectToLongFunction<? super T> function);
/**
* Returns the final float result of evaluating function using each element of the iterable and the previous evaluation
* result as the parameters. The injected value is used for the first parameter of the first evaluation, and the current
* item in the iterable is used as the second parameter.
*
* @since 2.0
*/
float injectInto(float injectedValue, FloatObjectToFloatFunction<? super T> function);
/**
* Returns the final double result of evaluating function using each element of the iterable and the previous evaluation
* result as the parameters. The injected value is used for the first parameter of the first evaluation, and the current
* item in the iterable is used as the second parameter.
*
* @since 1.0
*/
double injectInto(double injectedValue, DoubleObjectToDoubleFunction<? super T> function);
/**
* Converts the collection to a MutableList implementation.
*
* @since 1.0
*/
MutableList<T> toList();
/**
* Converts the collection to a MutableList implementation and sorts it using the natural order of the elements.
*
* @since 1.0
*/
MutableList<T> toSortedList();
/**
* Converts the collection to a MutableList implementation and sorts it using the specified comparator.
*
* @since 1.0
*/
MutableList<T> toSortedList(Comparator<? super T> comparator);
/**
* Converts the collection to a MutableList implementation and sorts it based on the natural order of the
* attribute returned by {@code function}.
*
* @since 1.0
*/
<V extends Comparable<? super V>> MutableList<T> toSortedListBy(Function<? super T, ? extends V> function);
/**
* Converts the collection to a MutableSet implementation.
*
* @since 1.0
*/
MutableSet<T> toSet();
/**
* Converts the collection to a MutableSortedSet implementation and sorts it using the natural order of the
* elements.
*
* @since 1.0
*/
MutableSortedSet<T> toSortedSet();
/**
* Converts the collection to a MutableSortedSet implementation and sorts it using the specified comparator.
*
* @since 1.0
*/
MutableSortedSet<T> toSortedSet(Comparator<? super T> comparator);
/**
* Converts the collection to a MutableSortedSet implementation and sorts it based on the natural order of the
* attribute returned by {@code function}.
*
* @since 1.0
*/
<V extends Comparable<? super V>> MutableSortedSet<T> toSortedSetBy(Function<? super T, ? extends V> function);
/**
* Converts the collection to the default MutableBag implementation.
*
* @since 1.0
*/
MutableBag<T> toBag();
/**
* Converts the collection to a MutableMap implementation using the specified key and value functions.
*
* @since 1.0
*/
<NK, NV> MutableMap<NK, NV> toMap(
Function<? super T, ? extends NK> keyFunction,
Function<? super T, ? extends NV> valueFunction);
/**
* Converts the collection to a MutableSortedMap implementation using the specified key and value functions
* sorted by the key elements' natural ordering.
*
* @since 1.0
*/
<NK, NV> MutableSortedMap<NK, NV> toSortedMap(
Function<? super T, ? extends NK> keyFunction,
Function<? super T, ? extends NV> valueFunction);
/**
* Converts the collection to a MutableSortedMap implementation using the specified key and value functions
* sorted by the given comparator.
*
* @since 1.0
*/
<NK, NV> MutableSortedMap<NK, NV> toSortedMap(
Comparator<? super NK> comparator,
Function<? super T, ? extends NK> keyFunction,
Function<? super T, ? extends NV> valueFunction);
/**
* Returns a deferred iterable, most likely implemented by calling LazyIterate.defer(this).
*
* @since 1.0.
*/
LazyIterable<T> asLazy();
/**
* Converts this iterable to an array.
*
* @see Collection#toArray()
* @since 1.0
*/
Object[] toArray();
/**
* Converts this iterable to an array using the specified target array, assuming the target array is as long
* or longer than the iterable.
*
* @see Collection#toArray(Object[])
* @since 1.0
*/
<T> T[] toArray(T[] target);
/**
* Returns the minimum element out of this container based on the comparator.
*
* @throws NoSuchElementException if the RichIterable is empty
* @since 1.0
*/
T min(Comparator<? super T> comparator);
/**
* Returns the maximum element out of this container based on the comparator.
*
* @throws NoSuchElementException if the RichIterable is empty
* @since 1.0
*/
T max(Comparator<? super T> comparator);
/**
* Returns the minimum element out of this container based on the natural order.
*
* @throws ClassCastException if the elements are not {@link Comparable}
* @throws NoSuchElementException if the RichIterable is empty
* @since 1.0
*/
T min();
/**
* Returns the maximum element out of this container based on the natural order.
*
* @throws ClassCastException if the elements are not {@link Comparable}
* @throws NoSuchElementException if the RichIterable is empty
* @since 1.0
*/
T max();
/**
* Returns the minimum elements out of this container based on the natural order of the attribute returned by Function.
*
* @throws NoSuchElementException if the RichIterable is empty
* @since 1.0
*/
<V extends Comparable<? super V>> T minBy(Function<? super T, ? extends V> function);
/**
* Returns the maximum elements out of this container based on the natural order of the attribute returned by Function.
*
* @throws NoSuchElementException if the RichIterable is empty
* @since 1.0
*/
<V extends Comparable<? super V>> T maxBy(Function<? super T, ? extends V> function);
/**
* Returns the final long result of evaluating function for each element of the iterable and adding the results
* together.
*
* @since 2.0
*/
long sumOfInt(IntFunction<? super T> function);
/**
* Returns the final double result of evaluating function for each element of the iterable and adding the results
* together.
*
* @since 2.0
*/
double sumOfFloat(FloatFunction<? super T> function);
/**
* Returns the final long result of evaluating function for each element of the iterable and adding the results
* together.
*
* @since 2.0
*/
long sumOfLong(LongFunction<? super T> function);
/**
* Returns the final double result of evaluating function for each element of the iterable and adding the results
* together.
*
* @since 2.0
*/
double sumOfDouble(DoubleFunction<? super T> function);
/**
* Returns a string representation of this collection by delegating to {@link #makeString(String)} and defaulting
* the separator parameter to the characters <tt>", "</tt> (comma and space).
*
* @return a string representation of this collection.
* @since 1.0
*/
String makeString();
/**
* Returns a string representation of this collection by delegating to {@link #makeString(String, String, String)}
* and defaulting the start and end parameters to <tt>""</tt> (the empty String).
*
* @return a string representation of this collection.
* @since 1.0
*/
String makeString(String separator);
/**
* Returns a string representation of this collection. The string representation consists of a list of the
* collection's elements in the order they are returned by its iterator, enclosed in the start and end strings.
* Adjacent elements are separated by the separator string. Elements are converted to strings as by
* <tt>String.valueOf(Object)</tt>.
*
* @return a string representation of this collection.
* @since 1.0
*/
String makeString(String start, String separator, String end);
/**
* Prints a string representation of this collection onto the given {@code Appendable}. Prints the string returned
* by {@link #makeString()}.
*
* @since 1.0
*/
void appendString(Appendable appendable);
/**
* Prints a string representation of this collection onto the given {@code Appendable}. Prints the string returned
* by {@link #makeString(String)}.
*
* @since 1.0
*/
void appendString(Appendable appendable, String separator);
/**
* Prints a string representation of this collection onto the given {@code Appendable}. Prints the string returned
* by {@link #makeString(String, String, String)}.
*
* @since 1.0
*/
void appendString(Appendable appendable, String start, String separator, String end);
/**
* For each element of the iterable, the function is evaluated and the results of these evaluations are collected
* into a new multimap, where the transformed value is the key and the original values are added to the same (or similar)
* species of collection as the source iterable.
* <p/>
* <pre>e.g.
* return people.groupBy(new Function<Person, String>()
* {
* public String value(Person person)
* {
* return person.getFirstName() + " " + person.getLastName();
* }
* });
* </pre>
*
* @since 1.0
*/
<V> Multimap<V, T> groupBy(Function<? super T, ? extends V> function);
/**
* Same as {@link #groupBy(Function)}, except that the results are gathered into the specified {@code target}
* multimap.
* <p/>
* <pre>e.g.
* return people.groupBy(new Function<Person, String>()
* {
* public String value(Person person)
* {
* return person.getFirstName() + " " + person.getLastName();
* }
* }, new FastListMultimap<String, Person>());
* </pre>
*
* @since 1.0
*/
<V, R extends MutableMultimap<V, T>> R groupBy(Function<? super T, ? extends V> function, R target);
/**
* Similar to {@link #groupBy(Function)}, except the result of evaluating function will return a collection of keys
* for each value.
*
* @since 1.0
*/
<V> Multimap<V, T> groupByEach(Function<? super T, ? extends Iterable<V>> function);
/**
* Same as {@link #groupByEach(Function)}, except that the results are gathered into the specified {@code target}
* multimap.
*
* @since 1.0
*/
<V, R extends MutableMultimap<V, T>> R groupByEach(
Function<? super T, ? extends Iterable<V>> function,
R target);
/**
* Returns a string representation of this RichIterable. The string representation consists of a list of the
* RichIterable's elements in the order they are returned by its iterator, enclosed in square brackets
* (<tt>"[]"</tt>). Adjacent elements are separated by the characters <tt>", "</tt> (comma and space). Elements
* are converted to strings as by {@link String#valueOf(Object)}.
*
* @return a string representation of this RichIterable
* @since 1.0
*/
@Override
String toString();
/**
* Returns a {@code RichIterable} formed from this {@code RichIterable} and another {@code RichIterable} by
* combining corresponding elements in pairs. If one of the two {@code RichIterable}s is longer than the other, its
* remaining elements are ignored.
*
* @param that The {@code RichIterable} providing the second half of each result pair
* @param <S> the type of the second half of the returned pairs
* @return A new {@code RichIterable} containing pairs consisting of corresponding elements of this {@code
* RichIterable} and that. The length of the returned {@code RichIterable} is the minimum of the lengths of
* this {@code RichIterable} and that.
* @since 1.0
*/
<S> RichIterable<Pair<T, S>> zip(Iterable<S> that);
/**
* Same as {@link #zip(Iterable)} but uses {@code target} for output.
*
* @since 1.0
*/
<S, R extends Collection<Pair<T, S>>> R zip(Iterable<S> that, R target);
/**
* Zips this {@code RichIterable} with its indices.
*
* @return A new {@code RichIterable} containing pairs consisting of all elements of this {@code RichIterable}
* paired with their index. Indices start at 0.
* @see #zip(Iterable)
* @since 1.0
*/
RichIterable<Pair<T, Integer>> zipWithIndex();
/**
* Same as {@link #zipWithIndex()} but uses {@code target} for output.
*
* @since 1.0
*/
<R extends Collection<Pair<T, Integer>>> R zipWithIndex(R target);
/**
* Partitions elements in fixed size chunks.
*
* @param size the number of elements per chunk
* @return A {@code RichIterable} containing {@code RichIterable}s of size {@code size}, except the last will be
* truncated if the elements don't divide evenly.
* @since 1.0
*/
RichIterable<RichIterable<T>> chunk(int size);
/**
* Applies an aggregate procedure over the iterable grouping results into a Map based on the specific groupBy function.
* Aggregate results are required to be mutable as they will be changed in place by the procedure. A second function
* specifies the initial "zero" aggregate value to work with (i.e. new AtomicInteger(0)).
*
* @since 3.0
*/
<K, V> MapIterable<K, V> aggregateInPlaceBy(Function<? super T, ? extends K> groupBy, Function0<? extends V> zeroValueFactory, Procedure2<? super V, ? super T> mutatingAggregator);
/**
* Applies an aggregate function over the iterable grouping results into a map based on the specific groupBy function.
* Aggregate results are allowed to be immutable as they will be replaced in place in the map. A second function
* specifies the initial "zero" aggregate value to work with (i.e. new Integer(0)).
*
* @since 3.0
*/
<K, V> MapIterable<K, V> aggregateBy(Function<? super T, ? extends K> groupBy, Function0<? extends V> zeroValueFactory, Function2<? super V, ? super T, ? extends V> nonMutatingAggregator);
}
| [GSCOLLECT-1183] Correct the Javadoc on RichIterable.asLazy().
git-svn-id: c173b60cd131fd691c78c4467fb70aa9fb29b506@444 d5c9223b-1aff-41ac-aadd-f810b4a99ac4
| collections-api/src/main/java/com/gs/collections/api/RichIterable.java | [GSCOLLECT-1183] Correct the Javadoc on RichIterable.asLazy(). | <ide><path>ollections-api/src/main/java/com/gs/collections/api/RichIterable.java
<ide> Function<? super T, ? extends NV> valueFunction);
<ide>
<ide> /**
<del> * Returns a deferred iterable, most likely implemented by calling LazyIterate.defer(this).
<add> * Returns a lazy (deferred) iterable, most likely implemented by calling LazyIterate.adapt(this).
<ide> *
<ide> * @since 1.0.
<ide> */ |
|
Java | apache-2.0 | 118b26742fb1baf081a1e0437c76351f8c958ccf | 0 | rythmengine/rythmengine,greenlaw110/Rythm,rythmengine/rythmengine,rythmengine/rythmengine,greenlaw110/Rythm,greenlaw110/Rythm | /*
* Copyright (C) 2013-2016 The Rythm Engine project
* for LICENSE and other details see:
* https://github.com/rythmengine/rythmengine
*/
package org.rythmengine.issue;
import java.io.File;
import java.util.HashMap;
import java.util.Map;
import org.apache.commons.io.FileUtils;
import org.junit.Test;
import org.rythmengine.RythmEngine;
import org.rythmengine.TestBase;
/**
* Test for https://github.com/rythmengine/rythmengine/issues/321
* @author wf
*
*/
public class GithubIssue321Test extends TestBase {
@Test
public void testHomeTemplate() throws Exception {
// http://rythmengine.org/doc/template_guide.md#invoke_template
File tmpFile = File.createTempFile("Home", "Template");
File templateDir=tmpFile.getParentFile();
File template = new File(templateDir,"test.html");
String test="@include(\"common.html\")\n" +
"@show(\"test\")";
FileUtils.writeStringToFile(template, test);
String common="@def show(String param) {\n" +
"common @param\n" +
"}";
File commonTemplate = new File(templateDir,"common.html");
FileUtils.writeStringToFile(commonTemplate,common);
Map<String,Object> conf = new HashMap<String,Object>();
conf.put("home.template", templateDir.getAbsolutePath());
RythmEngine engine = new RythmEngine(conf);
Map<String,Object> rootMap = new HashMap<String,Object>();
String result = engine.render(template, rootMap);
if (debug)
System.out.println(result);
}
}
| src/test/java/org/rythmengine/issue/GithubIssue321Test.java | /*
* Copyright (C) 2013-2016 The Rythm Engine project
* for LICENSE and other details see:
* https://github.com/rythmengine/rythmengine
*/
package org.rythmengine.issue;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import org.apache.commons.io.FileUtils;
import org.junit.Test;
import org.rythmengine.RythmEngine;
import org.rythmengine.TestBase;
/**
* Test for https://github.com/rythmengine/rythmengine/issues/321
* @author wf
*
*/
public class GithubIssue321Test extends TestBase {
@Test
public void testHomeTemplate() throws Exception {
// http://rythmengine.org/doc/template_guide.md#invoke_template
File tmpFile = File.createTempFile("Home", "Template");
File templateDir=tmpFile.getParentFile();
File template = new File(templateDir,"test.html");
String test="@include(\"common.html\")\n" +
"@show(\"test\")";
FileUtils.writeStringToFile(template, test);
String common="@def show(String param) {\n" +
"common @param\n" +
"}";
File commonTemplate = new File(templateDir,"common.html");
FileUtils.writeStringToFile(commonTemplate,common);
Map<String,Object> conf = new HashMap<String,Object>();
conf.put("home.template", templateDir.getAbsolutePath());
RythmEngine engine = new RythmEngine(conf);
Map<String,Object> rootMap = new HashMap<String,Object>();
String result = engine.render(template, rootMap);
System.out.println(result);
}
}
| explains #321 | src/test/java/org/rythmengine/issue/GithubIssue321Test.java | explains #321 | <ide><path>rc/test/java/org/rythmengine/issue/GithubIssue321Test.java
<ide> package org.rythmengine.issue;
<ide>
<ide> import java.io.File;
<del>import java.io.IOException;
<ide> import java.util.HashMap;
<ide> import java.util.Map;
<ide>
<ide> RythmEngine engine = new RythmEngine(conf);
<ide> Map<String,Object> rootMap = new HashMap<String,Object>();
<ide> String result = engine.render(template, rootMap);
<del> System.out.println(result);
<add> if (debug)
<add> System.out.println(result);
<ide> }
<ide>
<ide> } |
|
Java | apache-2.0 | 70a0459c82f4f3ae104806b13a14b42cdbd5d169 | 0 | ubikloadpack/jmeter,ubikloadpack/jmeter,ubikloadpack/jmeter,ubikloadpack/jmeter | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.apache.jmeter.protocol.http.sampler;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLDecoder;
import java.nio.charset.Charset;
import java.security.GeneralSecurityException;
import java.security.PrivilegedActionException;
import java.security.PrivilegedExceptionAction;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.function.Predicate;
import java.util.regex.Pattern;
import javax.security.auth.Subject;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.tuple.MutableTriple;
import org.apache.http.Header;
import org.apache.http.HttpClientConnection;
import org.apache.http.HttpConnectionMetrics;
import org.apache.http.HttpEntity;
import org.apache.http.HttpException;
import org.apache.http.HttpHost;
import org.apache.http.HttpRequest;
import org.apache.http.HttpRequestInterceptor;
import org.apache.http.HttpResponse;
import org.apache.http.HttpResponseInterceptor;
import org.apache.http.NameValuePair;
import org.apache.http.StatusLine;
import org.apache.http.auth.AuthSchemeProvider;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.AuthState;
import org.apache.http.auth.Credentials;
import org.apache.http.auth.NTCredentials;
import org.apache.http.client.AuthCache;
import org.apache.http.client.AuthenticationStrategy;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.config.AuthSchemes;
import org.apache.http.client.config.CookieSpecs;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.InputStreamFactory;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpEntityEnclosingRequestBase;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpHead;
import org.apache.http.client.methods.HttpOptions;
import org.apache.http.client.methods.HttpPatch;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.client.methods.HttpTrace;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.client.protocol.ResponseContentEncoding;
import org.apache.http.config.Lookup;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.config.SocketConfig;
import org.apache.http.conn.ConnectionKeepAliveStrategy;
import org.apache.http.conn.DnsResolver;
import org.apache.http.conn.ManagedHttpClientConnection;
import org.apache.http.conn.SchemePortResolver;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.cookie.CookieSpecProvider;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.FileEntity;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.FormBodyPart;
import org.apache.http.entity.mime.FormBodyPartBuilder;
import org.apache.http.entity.mime.MIME;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.auth.BasicScheme;
import org.apache.http.impl.auth.BasicSchemeFactory;
import org.apache.http.impl.auth.DigestScheme;
import org.apache.http.impl.auth.DigestSchemeFactory;
import org.apache.http.impl.auth.KerberosScheme;
import org.apache.http.impl.auth.NTLMSchemeFactory;
import org.apache.http.impl.client.BasicAuthCache;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultClientConnectionReuseStrategy;
import org.apache.http.impl.client.DefaultConnectionKeepAliveStrategy;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.client.LaxRedirectStrategy;
import org.apache.http.impl.client.ProxyAuthenticationStrategy;
import org.apache.http.impl.client.StandardHttpRequestRetryHandler;
import org.apache.http.impl.conn.DefaultHttpClientConnectionOperator;
import org.apache.http.impl.conn.DefaultSchemePortResolver;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.impl.conn.SystemDefaultDnsResolver;
import org.apache.http.impl.cookie.IgnoreSpecProvider;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.message.BufferedHeader;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HTTP;
import org.apache.http.protocol.HttpContext;
import org.apache.http.protocol.HttpCoreContext;
import org.apache.http.protocol.HttpRequestExecutor;
import org.apache.http.util.CharArrayBuffer;
import org.apache.http.util.EntityUtils;
import org.apache.jmeter.config.Arguments;
import org.apache.jmeter.protocol.http.api.auth.DigestParameters;
import org.apache.jmeter.protocol.http.control.AuthManager;
import org.apache.jmeter.protocol.http.control.AuthManager.Mechanism;
import org.apache.jmeter.protocol.http.control.Authorization;
import org.apache.jmeter.protocol.http.control.CacheManager;
import org.apache.jmeter.protocol.http.control.CookieManager;
import org.apache.jmeter.protocol.http.control.DynamicKerberosSchemeFactory;
import org.apache.jmeter.protocol.http.control.DynamicSPNegoSchemeFactory;
import org.apache.jmeter.protocol.http.control.HeaderManager;
import org.apache.jmeter.protocol.http.sampler.hc.LaxDeflateInputStream;
import org.apache.jmeter.protocol.http.sampler.hc.LaxGZIPInputStream;
import org.apache.jmeter.protocol.http.sampler.hc.LazyLayeredConnectionSocketFactory;
import org.apache.jmeter.protocol.http.util.EncoderCache;
import org.apache.jmeter.protocol.http.util.HTTPArgument;
import org.apache.jmeter.protocol.http.util.HTTPConstants;
import org.apache.jmeter.protocol.http.util.HTTPFileArg;
import org.apache.jmeter.protocol.http.util.SlowHCPlainConnectionSocketFactory;
import org.apache.jmeter.samplers.SampleResult;
import org.apache.jmeter.services.FileServer;
import org.apache.jmeter.testelement.property.CollectionProperty;
import org.apache.jmeter.testelement.property.JMeterProperty;
import org.apache.jmeter.testelement.property.PropertyIterator;
import org.apache.jmeter.threads.JMeterContextService;
import org.apache.jmeter.threads.JMeterVariables;
import org.apache.jmeter.util.JMeterUtils;
import org.apache.jmeter.util.JsseSSLManager;
import org.apache.jmeter.util.SSLManager;
import org.apache.jorphan.util.JOrphanUtils;
import org.brotli.dec.BrotliInputStream;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* HTTP Sampler using Apache HttpClient 4.x.
*
*/
public class HTTPHC4Impl extends HTTPHCAbstractImpl {
private static final String CONTEXT_ATTRIBUTE_AUTH_MANAGER = "__jmeter.A_M__";
private static final String JMETER_VARIABLE_USER_TOKEN = "__jmeter.U_T__"; //$NON-NLS-1$
static final String CONTEXT_ATTRIBUTE_SAMPLER_RESULT = "__jmeter.S_R__"; //$NON-NLS-1$
private static final String CONTEXT_ATTRIBUTE_HTTPCLIENT_TOKEN = "__jmeter.H_T__";
private static final String CONTEXT_ATTRIBUTE_CLIENT_KEY = "__jmeter.C_K__";
private static final String CONTEXT_ATTRIBUTE_SENT_BYTES = "__jmeter.S_B__";
private static final String CONTEXT_ATTRIBUTE_METRICS = "__jmeter.M__";
private static final boolean DISABLE_DEFAULT_UA = JMeterUtils.getPropDefault("httpclient4.default_user_agent_disabled", false);
private static final boolean GZIP_RELAX_MODE = JMeterUtils.getPropDefault("httpclient4.gzip_relax_mode", false);
private static final boolean DEFLATE_RELAX_MODE = JMeterUtils.getPropDefault("httpclient4.deflate_relax_mode", false);
private static final Logger log = LoggerFactory.getLogger(HTTPHC4Impl.class);
private static final InputStreamFactory GZIP = new InputStreamFactory() {
@Override
public InputStream create(final InputStream instream) throws IOException {
return new LaxGZIPInputStream(instream, GZIP_RELAX_MODE);
}
};
private static final InputStreamFactory DEFLATE = new InputStreamFactory() {
@Override
public InputStream create(final InputStream instream) throws IOException {
return new LaxDeflateInputStream(instream, DEFLATE_RELAX_MODE);
}
};
private static final InputStreamFactory BROTLI = new InputStreamFactory() {
@Override
public InputStream create(final InputStream instream) throws IOException {
return new BrotliInputStream(instream);
}
};
private static final class PreemptiveAuthRequestInterceptor implements HttpRequestInterceptor {
@Override
public void process(HttpRequest request, HttpContext context) throws HttpException, IOException {
HttpClientContext localContext = HttpClientContext.adapt(context);
AuthManager authManager = (AuthManager) localContext.getAttribute(CONTEXT_ATTRIBUTE_AUTH_MANAGER);
if (authManager == null) {
Credentials credentials = null;
HttpClientKey key = (HttpClientKey) localContext.getAttribute(CONTEXT_ATTRIBUTE_CLIENT_KEY);
AuthScope authScope = null;
CredentialsProvider credentialsProvider = localContext.getCredentialsProvider();
if (key.hasProxy && !StringUtils.isEmpty(key.proxyUser)) {
authScope = new AuthScope(key.proxyHost, key.proxyPort);
credentials = credentialsProvider.getCredentials(authScope);
}
credentialsProvider.clear();
if (credentials != null) {
credentialsProvider.setCredentials(authScope, credentials);
}
return;
}
URI requestURI = null;
if (request instanceof HttpUriRequest) {
requestURI = ((HttpUriRequest) request).getURI();
} else {
try {
requestURI = new URI(request.getRequestLine().getUri());
} catch (final URISyntaxException ignore) { // NOSONAR
// NOOP
}
}
if(requestURI != null) {
HttpHost targetHost = (HttpHost) context.getAttribute(HttpCoreContext.HTTP_TARGET_HOST);
URL url;
if(requestURI.isAbsolute()) {
url = requestURI.toURL();
} else {
url = new URL(targetHost.getSchemeName(), targetHost.getHostName(), targetHost.getPort(),
requestURI.getPath());
}
Authorization authorization =
authManager.getAuthForURL(url);
CredentialsProvider credentialsProvider = localContext.getCredentialsProvider();
if(authorization != null) {
AuthCache authCache = localContext.getAuthCache();
if(authCache == null) {
authCache = new BasicAuthCache();
localContext.setAuthCache(authCache);
}
authManager.setupCredentials(authorization, url, localContext, credentialsProvider, LOCALHOST);
AuthState authState = (AuthState) context.getAttribute(HttpClientContext.TARGET_AUTH_STATE);
if (authState.getAuthScheme() == null) {
AuthScope authScope = new AuthScope(targetHost.getHostName(), targetHost.getPort(),
authorization.getRealm(), targetHost.getSchemeName());
Credentials creds = credentialsProvider.getCredentials(authScope);
if (creds != null) {
fillAuthCache(targetHost, authorization, authCache, authScope);
}
}
} else {
credentialsProvider.clear();
}
}
}
/**
* @param targetHost
* @param authorization
* @param authCache
* @param authScope
*/
private void fillAuthCache(HttpHost targetHost, Authorization authorization, AuthCache authCache,
AuthScope authScope) {
if(authorization.getMechanism() == Mechanism.BASIC_DIGEST || // NOSONAR
authorization.getMechanism() == Mechanism.BASIC) {
BasicScheme basicAuth = new BasicScheme();
authCache.put(targetHost, basicAuth);
} else if (authorization.getMechanism() == Mechanism.DIGEST) {
JMeterVariables vars = JMeterContextService.getContext().getVariables();
DigestParameters digestParameters = (DigestParameters)
vars.getObject(DIGEST_PARAMETERS);
if(digestParameters!=null) {
DigestScheme digestAuth = (DigestScheme) authCache.get(targetHost);
if(digestAuth == null) {
digestAuth = new DigestScheme();
}
digestAuth.overrideParamter("realm", authScope.getRealm());
digestAuth.overrideParamter("algorithm", digestParameters.getAlgorithm());
digestAuth.overrideParamter("charset", digestParameters.getCharset());
digestAuth.overrideParamter("nonce", digestParameters.getNonce());
digestAuth.overrideParamter("opaque", digestParameters.getOpaque());
digestAuth.overrideParamter("qop", digestParameters.getQop());
authCache.put(targetHost, digestAuth);
}
} else if (authorization.getMechanism() == Mechanism.KERBEROS) {
KerberosScheme kerberosScheme = new KerberosScheme();
authCache.put(targetHost, kerberosScheme);
}
}
}
private static final class JMeterDefaultHttpClientConnectionOperator extends DefaultHttpClientConnectionOperator {
public JMeterDefaultHttpClientConnectionOperator(Lookup<ConnectionSocketFactory> socketFactoryRegistry, SchemePortResolver schemePortResolver,
DnsResolver dnsResolver) {
super(socketFactoryRegistry, schemePortResolver, dnsResolver);
}
/* (non-Javadoc)
* @see org.apache.http.impl.conn.DefaultHttpClientConnectionOperator#connect(
* org.apache.http.conn.ManagedHttpClientConnection, org.apache.http.HttpHost,
* java.net.InetSocketAddress, int, org.apache.http.config.SocketConfig,
* org.apache.http.protocol.HttpContext)
*/
@Override
public void connect(ManagedHttpClientConnection conn, HttpHost host, InetSocketAddress localAddress,
int connectTimeout, SocketConfig socketConfig, HttpContext context) throws IOException {
try {
super.connect(conn, host, localAddress, connectTimeout, socketConfig, context);
} finally {
SampleResult sample =
(SampleResult)context.getAttribute(HTTPHC4Impl.CONTEXT_ATTRIBUTE_SAMPLER_RESULT);
if (sample != null) {
sample.connectEnd();
}
}
}
}
/** retry count to be used (default 0); 0 = disable retries */
private static final int RETRY_COUNT = JMeterUtils.getPropDefault("httpclient4.retrycount", 0);
/** true if it's OK to retry requests that have been sent */
private static final boolean REQUEST_SENT_RETRY_ENABLED =
JMeterUtils.getPropDefault("httpclient4.request_sent_retry_enabled", false);
/** Idle timeout to be applied to connections if no Keep-Alive header is sent by the server (default 0 = disable) */
private static final int IDLE_TIMEOUT = JMeterUtils.getPropDefault("httpclient4.idletimeout", 0);
private static final int VALIDITY_AFTER_INACTIVITY_TIMEOUT = JMeterUtils.getPropDefault("httpclient4.validate_after_inactivity", 1700);
private static final int TIME_TO_LIVE = JMeterUtils.getPropDefault("httpclient4.time_to_live", 2000);
/** Preemptive Basic Auth */
private static final boolean BASIC_AUTH_PREEMPTIVE = JMeterUtils.getPropDefault("httpclient4.auth.preemptive", true);
private static final Pattern PORT_PATTERN = Pattern.compile("\\d+"); // only used in .matches(), no need for anchors
private static final ConnectionKeepAliveStrategy IDLE_STRATEGY = new DefaultConnectionKeepAliveStrategy(){
@Override
public long getKeepAliveDuration(HttpResponse response, HttpContext context) {
long duration = super.getKeepAliveDuration(response, context);
if (duration <= 0 && IDLE_TIMEOUT > 0) {// none found by the superclass
log.debug("Setting keepalive to {}", IDLE_TIMEOUT);
return IDLE_TIMEOUT;
}
return duration; // return the super-class value
}
};
private static final String DIGEST_PARAMETERS = DigestParameters.VARIABLE_NAME;
private static final HttpRequestInterceptor PREEMPTIVE_AUTH_INTERCEPTOR = new PreemptiveAuthRequestInterceptor();
// see https://stackoverflow.com/questions/26166469/measure-bandwidth-usage-with-apache-httpcomponents-httpclient
private static final HttpRequestExecutor REQUEST_EXECUTOR = new HttpRequestExecutor() {
@Override
protected HttpResponse doSendRequest(
final HttpRequest request,
final HttpClientConnection conn,
final HttpContext context) throws IOException, HttpException {
HttpResponse response = super.doSendRequest(request, conn, context);
HttpConnectionMetrics metrics = conn.getMetrics();
long sentBytesCount = metrics.getSentBytesCount();
// We save to store sent bytes as we need to reset metrics for received bytes
context.setAttribute(CONTEXT_ATTRIBUTE_SENT_BYTES, metrics.getSentBytesCount());
context.setAttribute(CONTEXT_ATTRIBUTE_METRICS, metrics);
log.debug("Sent {} bytes", sentBytesCount);
metrics.reset();
return response;
}
};
/**
* Headers to save
*/
private static final String[] HEADERS_TO_SAVE = new String[]{
"content-length",
"content-encoding",
"content-md5"
};
/**
* Custom implementation that backups headers related to Compressed responses
* that HC core {@link ResponseContentEncoding} removes after uncompressing
* See Bug 59401
*/
private static final HttpResponseInterceptor RESPONSE_CONTENT_ENCODING = new ResponseContentEncoding(createLookupRegistry()) {
@Override
public void process(HttpResponse response, HttpContext context)
throws HttpException, IOException {
ArrayList<Header[]> headersToSave = null;
final HttpEntity entity = response.getEntity();
final HttpClientContext clientContext = HttpClientContext.adapt(context);
final RequestConfig requestConfig = clientContext.getRequestConfig();
// store the headers if necessary
if (requestConfig.isContentCompressionEnabled() && entity != null && entity.getContentLength() != 0) {
final Header ceheader = entity.getContentEncoding();
if (ceheader != null) {
headersToSave = new ArrayList<>(3);
for(String name : HEADERS_TO_SAVE) {
Header[] hdr = response.getHeaders(name); // empty if none
headersToSave.add(hdr);
}
}
}
// Now invoke original parent code
super.process(response, clientContext);
// Should this be in a finally ?
if(headersToSave != null) {
for (Header[] headers : headersToSave) {
for (Header headerToRestore : headers) {
if (response.containsHeader(headerToRestore.getName())) {
break;
}
response.addHeader(headerToRestore);
}
}
}
}
};
/**
* 1 HttpClient instance per combination of (HttpClient,HttpClientKey)
*/
private static final ThreadLocal<Map<HttpClientKey, MutableTriple<CloseableHttpClient, AuthState, PoolingHttpClientConnectionManager>>>
HTTPCLIENTS_CACHE_PER_THREAD_AND_HTTPCLIENTKEY =
InheritableThreadLocal.withInitial(() -> new HashMap<>(5));
/**
* CONNECTION_SOCKET_FACTORY changes if we want to simulate Slow connection
*/
private static final ConnectionSocketFactory CONNECTION_SOCKET_FACTORY;
private static final ViewableFileBody[] EMPTY_FILE_BODIES = new ViewableFileBody[0];
static {
log.info("HTTP request retry count = {}", RETRY_COUNT);
// Set up HTTP scheme override if necessary
if (CPS_HTTP > 0) {
log.info("Setting up HTTP SlowProtocol, cps={}", CPS_HTTP);
CONNECTION_SOCKET_FACTORY = new SlowHCPlainConnectionSocketFactory(CPS_HTTP);
} else {
CONNECTION_SOCKET_FACTORY = PlainConnectionSocketFactory.getSocketFactory();
}
}
private volatile HttpUriRequest currentRequest; // Accessed from multiple threads
protected HTTPHC4Impl(HTTPSamplerBase testElement) {
super(testElement);
}
/**
* Customize to plug Brotli
* @return {@link Lookup}
*/
private static Lookup<InputStreamFactory> createLookupRegistry() {
return
RegistryBuilder.<InputStreamFactory>create()
.register("br", BROTLI)
.register("gzip", GZIP)
.register("x-gzip", GZIP)
.register("deflate", DEFLATE).build();
}
/**
* Implementation that allows GET method to have a body
*/
public static final class HttpGetWithEntity extends HttpEntityEnclosingRequestBase {
public HttpGetWithEntity(final URI uri) {
super();
setURI(uri);
}
@Override
public String getMethod() {
return HTTPConstants.GET;
}
}
public static final class HttpDelete extends HttpEntityEnclosingRequestBase {
public HttpDelete(final URI uri) {
super();
setURI(uri);
}
@Override
public String getMethod() {
return HTTPConstants.DELETE;
}
}
@Override
protected HTTPSampleResult sample(URL url, String method,
boolean areFollowingRedirect, int frameDepth) {
if (log.isDebugEnabled()) {
log.debug("Start : sample {} method {} followingRedirect {} depth {}",
url, method, areFollowingRedirect, frameDepth);
}
JMeterVariables jMeterVariables = JMeterContextService.getContext().getVariables();
HTTPSampleResult res = createSampleResult(url, method);
CloseableHttpClient httpClient = null;
HttpRequestBase httpRequest = null;
HttpContext localContext = new BasicHttpContext();
HttpClientContext clientContext = HttpClientContext.adapt(localContext);
clientContext.setAttribute(CONTEXT_ATTRIBUTE_AUTH_MANAGER, getAuthManager());
HttpClientKey key = createHttpClientKey(url);
MutableTriple<CloseableHttpClient, AuthState, PoolingHttpClientConnectionManager> triple;
try {
httpClient = setupClient(key, jMeterVariables, clientContext);
// Cache triple for further use
Map<HttpClientKey, MutableTriple<CloseableHttpClient, AuthState, PoolingHttpClientConnectionManager>>
mapHttpClientPerHttpClientKey =
HTTPCLIENTS_CACHE_PER_THREAD_AND_HTTPCLIENTKEY.get();
triple =
mapHttpClientPerHttpClientKey.get(key);
URI uri = url.toURI();
httpRequest = createHttpRequest(uri, method, areFollowingRedirect);
setupRequest(url, httpRequest, res); // can throw IOException
} catch (Exception e) {
res.sampleStart();
res.sampleEnd();
errorResult(e, res);
return res;
}
setupClientContextBeforeSample(jMeterVariables, localContext);
res.sampleStart();
final CacheManager cacheManager = getCacheManager();
if (cacheManager != null && HTTPConstants.GET.equalsIgnoreCase(method) && cacheManager.inCache(url, httpRequest.getAllHeaders())) {
return updateSampleResultForResourceInCache(res);
}
CloseableHttpResponse httpResponse = null;
try {
currentRequest = httpRequest;
handleMethod(method, res, httpRequest, localContext);
// store the SampleResult in LocalContext to compute connect time
localContext.setAttribute(CONTEXT_ATTRIBUTE_SAMPLER_RESULT, res);
// perform the sample
httpResponse =
executeRequest(httpClient, httpRequest, localContext, url);
saveProxyAuth(triple, localContext);
if (log.isDebugEnabled()) {
log.debug("Headers in request before:{}", Arrays.asList(httpRequest.getAllHeaders()));
}
// Needs to be done after execute to pick up all the headers
final HttpRequest request = (HttpRequest) localContext.getAttribute(HttpCoreContext.HTTP_REQUEST);
if (log.isDebugEnabled()) {
log.debug("Headers in request after:{}, in localContext#request:{}",
Arrays.asList(httpRequest.getAllHeaders()),
Arrays.asList(request.getAllHeaders()));
}
extractClientContextAfterSample(jMeterVariables, localContext);
// We've finished with the request, so we can add the LocalAddress to it for display
if (localAddress != null) {
request.addHeader(HEADER_LOCAL_ADDRESS, localAddress.toString());
}
res.setRequestHeaders(getAllHeadersExceptCookie(request));
Header contentType = httpResponse.getLastHeader(HTTPConstants.HEADER_CONTENT_TYPE);
if (contentType != null){
String ct = contentType.getValue();
res.setContentType(ct);
res.setEncodingAndType(ct);
}
HttpEntity entity = httpResponse.getEntity();
if (entity != null) {
res.setResponseData(readResponse(res, entity.getContent(), entity.getContentLength()));
}
res.sampleEnd(); // Done with the sampling proper.
currentRequest = null;
// Now collect the results into the HTTPSampleResult:
StatusLine statusLine = httpResponse.getStatusLine();
int statusCode = statusLine.getStatusCode();
res.setResponseCode(Integer.toString(statusCode));
res.setResponseMessage(statusLine.getReasonPhrase());
res.setSuccessful(isSuccessCode(statusCode));
res.setResponseHeaders(getResponseHeaders(httpResponse));
if (res.isRedirect()) {
final Header headerLocation = httpResponse.getLastHeader(HTTPConstants.HEADER_LOCATION);
if (headerLocation == null) { // HTTP protocol violation, but avoids NPE
throw new IllegalArgumentException("Missing location header in redirect for " + httpRequest.getRequestLine());
}
String redirectLocation = headerLocation.getValue();
res.setRedirectLocation(redirectLocation);
}
// record some sizes to allow HTTPSampleResult.getBytes() with different options
long headerBytes =
(long)res.getResponseHeaders().length() // condensed length (without \r)
+ (long) httpResponse.getAllHeaders().length // Add \r for each header
+ 1L // Add \r for initial header
+ 2L; // final \r\n before data
HttpConnectionMetrics metrics = (HttpConnectionMetrics) localContext.getAttribute(CONTEXT_ATTRIBUTE_METRICS);
long totalBytes = metrics.getReceivedBytesCount();
res.setHeadersSize((int)headerBytes);
res.setBodySize(totalBytes - headerBytes);
res.setSentBytes((Long) localContext.getAttribute(CONTEXT_ATTRIBUTE_SENT_BYTES));
if (log.isDebugEnabled()) {
long total = res.getHeadersSize() + res.getBodySizeAsLong();
log.debug("ResponseHeadersSize={} Content-Length={} Total={}",
res.getHeadersSize(), res.getBodySizeAsLong(), total);
}
// If we redirected automatically, the URL may have changed
if (getAutoRedirects()) {
HttpUriRequest req = (HttpUriRequest) localContext.getAttribute(HttpCoreContext.HTTP_REQUEST);
HttpHost target = (HttpHost) localContext.getAttribute(HttpCoreContext.HTTP_TARGET_HOST);
URI redirectURI = req.getURI();
if (redirectURI.isAbsolute()) {
res.setURL(redirectURI.toURL());
} else {
res.setURL(new URL(new URL(target.toURI()),redirectURI.toString()));
}
}
// Store any cookies received in the cookie manager:
saveConnectionCookies(httpResponse, res.getURL(), getCookieManager());
// Save cache information
if (cacheManager != null){
cacheManager.saveDetails(httpResponse, res);
}
// Follow redirects and download page resources if appropriate:
res = resultProcessing(areFollowingRedirect, frameDepth, res);
if(!isSuccessCode(statusCode)) {
EntityUtils.consumeQuietly(httpResponse.getEntity());
}
} catch (IOException e) {
log.debug("IOException", e);
if (res.getEndTime() == 0) {
res.sampleEnd();
}
// pick up headers if failed to execute the request
if (res.getRequestHeaders() != null) {
log.debug("Overwriting request old headers: {}", res.getRequestHeaders());
}
res.setRequestHeaders(getAllHeadersExceptCookie((HttpRequest) localContext.getAttribute(HttpCoreContext.HTTP_REQUEST)));
errorResult(e, res);
return res;
} catch (RuntimeException e) {
log.debug("RuntimeException", e);
if (res.getEndTime() == 0) {
res.sampleEnd();
}
errorResult(e, res);
return res;
} finally {
JOrphanUtils.closeQuietly(httpResponse);
currentRequest = null;
JMeterContextService.getContext().getSamplerContext().remove(CONTEXT_ATTRIBUTE_HTTPCLIENT_TOKEN);
}
return res;
}
/**
* Associate Proxy state to thread
* @param triple {@link MutableTriple}
* @param localContext {@link HttpContext}
*/
private void saveProxyAuth(
MutableTriple<CloseableHttpClient, AuthState, PoolingHttpClientConnectionManager> triple,
HttpContext localContext) {
triple.setMiddle((AuthState) localContext.getAttribute(HttpClientContext.PROXY_AUTH_STATE));
}
/**
* Store in localContext Proxy auth state of triple
* @param triple {@link MutableTriple}
* @param localContext {@link HttpContext}
*/
private void setupProxyAuth(MutableTriple<CloseableHttpClient, AuthState, PoolingHttpClientConnectionManager> triple,
HttpContext localContext) {
if (triple != null) {
AuthState proxy = triple.getMiddle();
localContext.setAttribute(HttpClientContext.PROXY_AUTH_STATE, proxy);
}
}
/**
* @param uri {@link URI}
* @param method HTTP Method
* @param areFollowingRedirect Are we following redirects
* @return {@link HttpRequestBase}
*/
private HttpRequestBase createHttpRequest(URI uri, String method, boolean areFollowingRedirect) {
HttpRequestBase result;
if (method.equals(HTTPConstants.POST)) {
result = new HttpPost(uri);
} else if (method.equals(HTTPConstants.GET)) {
// Some servers fail if Content-Length is equal to 0
// so to avoid this we use HttpGet when there is no body (Content-Length will not be set)
// otherwise we use HttpGetWithEntity
if ( !areFollowingRedirect
&& ((!hasArguments() && getSendFileAsPostBody())
|| getSendParameterValuesAsPostBody()) ) {
result = new HttpGetWithEntity(uri);
} else {
result = new HttpGet(uri);
}
} else if (method.equals(HTTPConstants.PUT)) {
result = new HttpPut(uri);
} else if (method.equals(HTTPConstants.HEAD)) {
result = new HttpHead(uri);
} else if (method.equals(HTTPConstants.TRACE)) {
result = new HttpTrace(uri);
} else if (method.equals(HTTPConstants.OPTIONS)) {
result = new HttpOptions(uri);
} else if (method.equals(HTTPConstants.DELETE)) {
result = new HttpDelete(uri);
} else if (method.equals(HTTPConstants.PATCH)) {
result = new HttpPatch(uri);
} else if (HttpWebdav.isWebdavMethod(method)) {
result = new HttpWebdav(method, uri);
} else {
throw new IllegalArgumentException("Unexpected method: '"+method+"'");
}
return result;
}
/**
* Store in JMeter Variables the UserToken so that the SSL context is reused
* See <a href="https://bz.apache.org/bugzilla/show_bug.cgi?id=57804">Bug 57804</a>
* @param jMeterVariables {@link JMeterVariables}
* @param localContext {@link HttpContext}
*/
private void extractClientContextAfterSample(JMeterVariables jMeterVariables, HttpContext localContext) {
Object userToken = localContext.getAttribute(HttpClientContext.USER_TOKEN);
if(userToken != null) {
log.debug("Extracted from HttpContext user token:{} storing it as JMeter variable:{}", userToken, JMETER_VARIABLE_USER_TOKEN);
// During recording JMeterContextService.getContext().getVariables() is null
if (jMeterVariables != null) {
jMeterVariables.putObject(JMETER_VARIABLE_USER_TOKEN, userToken);
}
}
}
/**
* Configure the UserToken so that the SSL context is reused
* See <a href="https://bz.apache.org/bugzilla/show_bug.cgi?id=57804">Bug 57804</a>
* @param jMeterVariables {@link JMeterVariables}
* @param localContext {@link HttpContext}
*/
private void setupClientContextBeforeSample(JMeterVariables jMeterVariables, HttpContext localContext) {
Object userToken = null;
// During recording JMeterContextService.getContext().getVariables() is null
if(jMeterVariables != null) {
userToken = jMeterVariables.getObject(JMETER_VARIABLE_USER_TOKEN);
}
if(userToken != null) {
log.debug("Found user token:{} as JMeter variable:{}, storing it in HttpContext", userToken, JMETER_VARIABLE_USER_TOKEN);
localContext.setAttribute(HttpClientContext.USER_TOKEN, userToken);
} else {
// It would be better to create a ClientSessionManager that would compute this value
// for now it can be Thread.currentThread().getName() but must be changed when we would change
// the Thread per User model
String userId = Thread.currentThread().getName();
log.debug("Storing in HttpContext the user token: {}", userId);
localContext.setAttribute(HttpClientContext.USER_TOKEN, userId);
}
}
/**
* Setup Body of request if different from GET.
* Field HTTPSampleResult#queryString of result is modified in the 2 cases
*
* @param method
* String HTTP method
* @param result
* {@link HTTPSampleResult}
* @param httpRequest
* {@link HttpRequestBase}
* @param localContext
* {@link HttpContext}
* @throws IOException
* when posting data fails due to I/O
*/
protected void handleMethod(String method, HTTPSampleResult result,
HttpRequestBase httpRequest, HttpContext localContext) throws IOException {
// Handle the various methods
if (httpRequest instanceof HttpEntityEnclosingRequestBase) {
String entityBody = setupHttpEntityEnclosingRequestData((HttpEntityEnclosingRequestBase)httpRequest);
result.setQueryString(entityBody);
}
}
/**
* Create HTTPSampleResult filling url, method and SampleLabel.
* Monitor field is computed calling isMonitor()
* @param url URL
* @param method HTTP Method
* @return {@link HTTPSampleResult}
*/
protected HTTPSampleResult createSampleResult(URL url, String method) {
HTTPSampleResult res = new HTTPSampleResult();
configureSampleLabel(res, url);
res.setHTTPMethod(method);
res.setURL(url);
return res;
}
/**
* Execute request either as is or under PrivilegedAction
* if a Subject is available for url
* @param httpClient the {@link CloseableHttpClient} to be used to execute the httpRequest
* @param httpRequest the {@link HttpRequest} to be executed
* @param localContext th {@link HttpContext} to be used for execution
* @param url the target url (will be used to look up a possible subject for the execution)
* @return the result of the execution of the httpRequest
* @throws IOException
*/
private CloseableHttpResponse executeRequest(final CloseableHttpClient httpClient,
final HttpRequestBase httpRequest, final HttpContext localContext, final URL url)
throws IOException {
AuthManager authManager = getAuthManager();
if (authManager != null) {
Subject subject = authManager.getSubjectForUrl(url);
if (subject != null) {
try {
return Subject.doAs(subject,
(PrivilegedExceptionAction<CloseableHttpResponse>) () ->
httpClient.execute(httpRequest, localContext));
} catch (PrivilegedActionException e) {
log.error("Can't execute httpRequest with subject: {}", subject, e);
throw new IllegalArgumentException("Can't execute httpRequest with subject:" + subject, e);
}
}
}
return httpClient.execute(httpRequest, localContext);
}
/**
* Holder class for all fields that define an HttpClient instance;
* used as the key to the ThreadLocal map of HttpClient instances.
*/
private static final class HttpClientKey {
private final String target; // protocol://[user:pass@]host:[port]
private final boolean hasProxy;
private final String proxyScheme;
private final String proxyHost;
private final int proxyPort;
private final String proxyUser;
private final String proxyPass;
private final int hashCode; // Always create hash because we will always need it
/**
* @param url URL Only protocol and url authority are used (protocol://[user:pass@]host:[port])
* @param hasProxy has proxy
* @param proxyScheme scheme
* @param proxyHost proxy host
* @param proxyPort proxy port
* @param proxyUser proxy user
* @param proxyPass proxy password
*/
public HttpClientKey(URL url, boolean hasProxy, String proxyScheme, String proxyHost,
int proxyPort, String proxyUser, String proxyPass) {
// N.B. need to separate protocol from authority otherwise http://server would match https://erver (<= sic, not typo error)
// could use separate fields, but simpler to combine them
this.target = url.getProtocol()+"://"+url.getAuthority();
this.hasProxy = hasProxy;
this.proxyScheme = proxyScheme;
this.proxyHost = proxyHost;
this.proxyPort = proxyPort;
this.proxyUser = proxyUser;
this.proxyPass = proxyPass;
this.hashCode = getHash();
}
private int getHash() {
int hash = 17;
hash = hash*31 + (hasProxy ? 1 : 0);
if (hasProxy) {
hash = hash*31 + getHash(proxyScheme);
hash = hash*31 + getHash(proxyHost);
hash = hash*31 + proxyPort;
hash = hash*31 + getHash(proxyUser);
hash = hash*31 + getHash(proxyPass);
}
hash = hash*31 + target.hashCode();
return hash;
}
// Allow for null strings
private int getHash(String s) {
return s == null ? 0 : s.hashCode();
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (!(obj instanceof HttpClientKey)) {
return false;
}
HttpClientKey other = (HttpClientKey) obj;
if (this.hasProxy) { // otherwise proxy String fields may be null
if (proxyScheme == null) {
if (other.proxyScheme != null) {
return false;
}
} else if (!proxyScheme.equals(other.proxyScheme)) {
return false;
}
return
this.hasProxy == other.hasProxy &&
this.proxyPort == other.proxyPort &&
this.proxyHost.equals(other.proxyHost) &&
this.proxyUser.equals(other.proxyUser) &&
this.proxyPass.equals(other.proxyPass) &&
this.target.equals(other.target);
}
// No proxy, so don't check proxy fields
return
this.hasProxy == other.hasProxy &&
this.target.equals(other.target);
}
@Override
public int hashCode(){
return hashCode;
}
// For debugging
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(target);
if (hasProxy) {
sb.append(" via ");
sb.append(proxyUser);
sb.append('@');
sb.append(proxyScheme);
sb.append("://");
sb.append(proxyHost);
sb.append(':');
sb.append(proxyPort);
}
return sb.toString();
}
}
private CloseableHttpClient setupClient(HttpClientKey key, JMeterVariables jMeterVariables,
HttpClientContext clientContext) throws GeneralSecurityException {
Map<HttpClientKey, MutableTriple<CloseableHttpClient, AuthState, PoolingHttpClientConnectionManager>> mapHttpClientPerHttpClientKey =
HTTPCLIENTS_CACHE_PER_THREAD_AND_HTTPCLIENTKEY.get();
clientContext.setAttribute(CONTEXT_ATTRIBUTE_CLIENT_KEY, key);
CloseableHttpClient httpClient = null;
boolean concurrentDwn = this.testElement.isConcurrentDwn();
if(concurrentDwn) {
httpClient = (CloseableHttpClient) JMeterContextService.getContext().getSamplerContext().get(CONTEXT_ATTRIBUTE_HTTPCLIENT_TOKEN);
}
MutableTriple<CloseableHttpClient, AuthState, PoolingHttpClientConnectionManager> triple =
mapHttpClientPerHttpClientKey.get(key);
if (httpClient == null) {
httpClient = triple != null ? triple.getLeft() : null;
}
setupProxyAuth(triple, clientContext);
resetStateIfNeeded(triple, jMeterVariables, clientContext, mapHttpClientPerHttpClientKey);
if (httpClient == null) { // One-time init for this client
DnsResolver resolver = this.testElement.getDNSResolver();
if (resolver == null) {
resolver = SystemDefaultDnsResolver.INSTANCE;
}
Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory> create().
register("https", new LazyLayeredConnectionSocketFactory()).
register("http", CONNECTION_SOCKET_FACTORY).
build();
// Modern browsers use more connections per host than the current httpclient default (2)
// when using parallel download the httpclient and connection manager are shared by the downloads threads
// to be realistic JMeter must set an higher value to DefaultMaxPerRoute
PoolingHttpClientConnectionManager pHCCM =
new PoolingHttpClientConnectionManager(
new JMeterDefaultHttpClientConnectionOperator(registry, null, resolver),
null, TIME_TO_LIVE, TimeUnit.MILLISECONDS);
pHCCM.setValidateAfterInactivity(VALIDITY_AFTER_INACTIVITY_TIMEOUT);
if(concurrentDwn) {
try {
int maxConcurrentDownloads = Integer.parseInt(this.testElement.getConcurrentPool());
pHCCM.setDefaultMaxPerRoute(Math.max(maxConcurrentDownloads, pHCCM.getDefaultMaxPerRoute()));
} catch (NumberFormatException nfe) {
// no need to log -> will be done by the sampler
}
}
CookieSpecProvider cookieSpecProvider = new IgnoreSpecProvider();
Lookup<CookieSpecProvider> cookieSpecRegistry = RegistryBuilder.<CookieSpecProvider>create()
.register(CookieSpecs.IGNORE_COOKIES, cookieSpecProvider)
.build();
HttpClientBuilder builder = HttpClients.custom().setConnectionManager(pHCCM).
setSchemePortResolver(new DefaultSchemePortResolver()).
setDnsResolver(resolver).
setRequestExecutor(REQUEST_EXECUTOR).
setSSLSocketFactory(new LazyLayeredConnectionSocketFactory()).
setDefaultCookieSpecRegistry(cookieSpecRegistry).
setDefaultSocketConfig(SocketConfig.DEFAULT).
setRedirectStrategy(new LaxRedirectStrategy()).
setConnectionTimeToLive(TIME_TO_LIVE, TimeUnit.MILLISECONDS).
setRetryHandler(new StandardHttpRequestRetryHandler(RETRY_COUNT, REQUEST_SENT_RETRY_ENABLED)).
setConnectionReuseStrategy(DefaultClientConnectionReuseStrategy.INSTANCE).
setProxyAuthenticationStrategy(getProxyAuthStrategy());
if(DISABLE_DEFAULT_UA) {
builder.disableDefaultUserAgent();
}
Lookup<AuthSchemeProvider> authSchemeRegistry =
RegistryBuilder.<AuthSchemeProvider>create()
.register(AuthSchemes.BASIC, new BasicSchemeFactory())
.register(AuthSchemes.DIGEST, new DigestSchemeFactory())
.register(AuthSchemes.NTLM, new NTLMSchemeFactory())
.register(AuthSchemes.SPNEGO, new DynamicSPNegoSchemeFactory(
AuthManager.STRIP_PORT, AuthManager.USE_CANONICAL_HOST_NAME))
.register(AuthSchemes.KERBEROS, new DynamicKerberosSchemeFactory(
AuthManager.STRIP_PORT, AuthManager.USE_CANONICAL_HOST_NAME))
.build();
builder.setDefaultAuthSchemeRegistry(authSchemeRegistry);
if (IDLE_TIMEOUT > 0) {
builder.setKeepAliveStrategy(IDLE_STRATEGY);
}
// Set up proxy details
if (key.hasProxy) {
HttpHost proxy = new HttpHost(key.proxyHost, key.proxyPort, key.proxyScheme);
builder.setProxy(proxy);
CredentialsProvider credsProvider = new BasicCredentialsProvider();
if (!key.proxyUser.isEmpty()) {
credsProvider.setCredentials(
new AuthScope(key.proxyHost, key.proxyPort),
new NTCredentials(key.proxyUser, key.proxyPass, LOCALHOST, PROXY_DOMAIN));
}
builder.setDefaultCredentialsProvider(credsProvider);
}
builder.disableContentCompression().addInterceptorLast(RESPONSE_CONTENT_ENCODING);
if(BASIC_AUTH_PREEMPTIVE) {
builder.addInterceptorFirst(PREEMPTIVE_AUTH_INTERCEPTOR);
}
httpClient = builder.build();
if (log.isDebugEnabled()) {
log.debug("Created new HttpClient: @{} {}", System.identityHashCode(httpClient), key);
}
mapHttpClientPerHttpClientKey.put(key, MutableTriple.of(httpClient, null, pHCCM)); // save the agent for next time round
} else {
if (log.isDebugEnabled()) {
log.debug("Reusing the HttpClient: @{} {}", System.identityHashCode(httpClient),key);
}
}
if(concurrentDwn) {
JMeterContextService.getContext().getSamplerContext().put(CONTEXT_ATTRIBUTE_HTTPCLIENT_TOKEN, httpClient);
}
return httpClient;
}
protected AuthenticationStrategy getProxyAuthStrategy() {
return ProxyAuthenticationStrategy.INSTANCE;
}
private HttpClientKey createHttpClientKey(URL url) {
final String host = url.getHost();
String proxyScheme = getProxyScheme();
String proxyHost = getProxyHost();
int proxyPort = getProxyPortInt();
String proxyPass = getProxyPass();
String proxyUser = getProxyUser();
// static proxy is the globally define proxy eg command line or properties
boolean useStaticProxy = isStaticProxy(host);
// dynamic proxy is the proxy defined for this sampler
boolean useDynamicProxy = isDynamicProxy(proxyHost, proxyPort);
boolean useProxy = useStaticProxy || useDynamicProxy;
// if both dynamic and static are used, the dynamic proxy has priority over static
if(!useDynamicProxy) {
proxyScheme = PROXY_SCHEME;
proxyHost = PROXY_HOST;
proxyPort = PROXY_PORT;
proxyUser = PROXY_USER;
proxyPass = PROXY_PASS;
}
// Lookup key - must agree with all the values used to create the HttpClient.
return new HttpClientKey(url, useProxy, proxyScheme, proxyHost, proxyPort, proxyUser, proxyPass);
}
/**
* Reset SSL State. <br/>
* In order to do that we need to:
* <ul>
* <li>Call resetContext() on SSLManager</li>
* <li>Close current Idle or Expired connections that hold SSL State</li>
* <li>Remove HttpClientContext.USER_TOKEN from {@link HttpClientContext}</li>
* </ul>
* @param jMeterVariables {@link JMeterVariables}
* @param clientContext {@link HttpClientContext}
* @param mapHttpClientPerHttpClientKey Map of {@link MutableTriple} holding {@link CloseableHttpClient} and {@link PoolingHttpClientConnectionManager}
*/
private void resetStateIfNeeded(
MutableTriple<CloseableHttpClient, AuthState, PoolingHttpClientConnectionManager> triple,
JMeterVariables jMeterVariables,
HttpClientContext clientContext,
Map<HttpClientKey, MutableTriple<CloseableHttpClient, AuthState, PoolingHttpClientConnectionManager>> mapHttpClientPerHttpClientKey) {
if (resetStateOnThreadGroupIteration.get()) {
closeCurrentConnections(mapHttpClientPerHttpClientKey);
clientContext.removeAttribute(HttpClientContext.USER_TOKEN);
clientContext.removeAttribute(HttpClientContext.PROXY_AUTH_STATE);
if (triple != null) {
triple.setMiddle(null);
}
jMeterVariables.remove(JMETER_VARIABLE_USER_TOKEN);
((JsseSSLManager) SSLManager.getInstance()).resetContext();
resetStateOnThreadGroupIteration.set(false);
}
}
/**
* @param mapHttpClientPerHttpClientKey
*/
private void closeCurrentConnections(
Map<HttpClientKey, MutableTriple<CloseableHttpClient, AuthState, PoolingHttpClientConnectionManager>> mapHttpClientPerHttpClientKey) {
for (MutableTriple<CloseableHttpClient, AuthState, PoolingHttpClientConnectionManager> triple :
mapHttpClientPerHttpClientKey.values()) {
PoolingHttpClientConnectionManager poolingHttpClientConnectionManager = triple.getRight();
poolingHttpClientConnectionManager.closeExpiredConnections();
poolingHttpClientConnectionManager.closeIdleConnections(1L, TimeUnit.MICROSECONDS);
}
}
/**
* Setup following elements on httpRequest:
* <ul>
* <li>ConnRoutePNames.LOCAL_ADDRESS enabling IP-SPOOFING</li>
* <li>Socket and connection timeout</li>
* <li>Redirect handling</li>
* <li>Keep Alive header or Connection Close</li>
* <li>Calls setConnectionHeaders to setup headers</li>
* <li>Calls setConnectionCookie to setup Cookie</li>
* </ul>
*
* @param url
* {@link URL} of the request
* @param httpRequest
* http request for the request
* @param res
* sample result to set cookies on
* @throws IOException
* if hostname/ip to use could not be figured out
*/
protected void setupRequest(URL url, HttpRequestBase httpRequest, HTTPSampleResult res)
throws IOException {
RequestConfig.Builder rCB = RequestConfig.custom();
// Set up the local address if one exists
final InetAddress inetAddr = getIpSourceAddress();
if (inetAddr != null) {// Use special field ip source address (for pseudo 'ip spoofing')
rCB.setLocalAddress(inetAddr);
} else if (localAddress != null){
rCB.setLocalAddress(localAddress);
}
int rto = getResponseTimeout();
if (rto > 0){
rCB.setSocketTimeout(rto);
}
int cto = getConnectTimeout();
if (cto > 0){
rCB.setConnectTimeout(cto);
}
rCB.setRedirectsEnabled(getAutoRedirects());
rCB.setMaxRedirects(HTTPSamplerBase.MAX_REDIRECTS);
httpRequest.setConfig(rCB.build());
// a well-behaved browser is supposed to send 'Connection: close'
// with the last request to an HTTP server. Instead, most browsers
// leave it to the server to close the connection after their
// timeout period. Leave it to the JMeter user to decide.
if (getUseKeepAlive()) {
httpRequest.setHeader(HTTPConstants.HEADER_CONNECTION, HTTPConstants.KEEP_ALIVE);
} else {
httpRequest.setHeader(HTTPConstants.HEADER_CONNECTION, HTTPConstants.CONNECTION_CLOSE);
}
setConnectionHeaders(httpRequest, url, getHeaderManager(), getCacheManager());
String cookies = setConnectionCookie(httpRequest, url, getCookieManager());
if (res != null) {
if(cookies != null && !cookies.isEmpty()) {
res.setCookies(cookies);
} else {
// During recording Cookie Manager doesn't handle cookies
res.setCookies(getOnlyCookieFromHeaders(httpRequest));
}
}
}
/**
* Set any default request headers to include
*
* @param request the HttpRequest to be used
*/
protected void setDefaultRequestHeaders(HttpRequest request) {
// Method left empty here, but allows subclasses to override
}
/**
* Gets the ResponseHeaders
*
* @param response
* containing the headers
* @return string containing the headers, one per line
*/
private String getResponseHeaders(HttpResponse response) {
Header[] rh = response.getAllHeaders();
StringBuilder headerBuf = new StringBuilder(40 * (rh.length+1));
headerBuf.append(response.getStatusLine());// header[0] is not the status line...
headerBuf.append("\n"); // $NON-NLS-1$
for (Header responseHeader : rh) {
writeHeader(headerBuf, responseHeader);
}
return headerBuf.toString();
}
/**
* Write header to headerBuffer in an optimized way
* @param headerBuffer {@link StringBuilder}
* @param header {@link Header}
*/
private void writeHeader(StringBuilder headerBuffer, Header header) {
if(header instanceof BufferedHeader) {
CharArrayBuffer buffer = ((BufferedHeader)header).getBuffer();
headerBuffer.append(buffer.buffer(), 0, buffer.length()).append('\n'); // $NON-NLS-1$
}
else {
headerBuffer.append(header.getName())
.append(": ") // $NON-NLS-1$
.append(header.getValue())
.append('\n'); // $NON-NLS-1$
}
}
/**
* Extracts all the required cookies for that particular URL request and
* sets them in the <code>HttpMethod</code> passed in.
*
* @param request <code>HttpRequest</code> for the request
* @param url <code>URL</code> of the request
* @param cookieManager the <code>CookieManager</code> containing all the cookies
* @return a String containing the cookie details (for the response)
* May be null
*/
protected String setConnectionCookie(HttpRequest request, URL url, CookieManager cookieManager) {
String cookieHeader = null;
if (cookieManager != null) {
cookieHeader = cookieManager.getCookieHeaderForURL(url);
if (cookieHeader != null) {
request.setHeader(HTTPConstants.HEADER_COOKIE, cookieHeader);
}
}
return cookieHeader;
}
/**
* Extracts all the required non-cookie headers for that particular URL request and
* sets them in the <code>HttpMethod</code> passed in
*
* @param request
* <code>HttpRequest</code> which represents the request
* @param url
* <code>URL</code> of the URL request
* @param headerManager
* the <code>HeaderManager</code> containing all the cookies
* for this <code>UrlConfig</code>
* @param cacheManager the CacheManager (may be null)
*/
protected void setConnectionHeaders(HttpRequestBase request, URL url, HeaderManager headerManager, CacheManager cacheManager) {
if (headerManager != null) {
CollectionProperty headers = headerManager.getHeaders();
if (headers != null) {
for (JMeterProperty jMeterProperty : headers) {
org.apache.jmeter.protocol.http.control.Header header
= (org.apache.jmeter.protocol.http.control.Header)
jMeterProperty.getObjectValue();
String headerName = header.getName();
// Don't allow override of Content-Length
if (!HTTPConstants.HEADER_CONTENT_LENGTH.equalsIgnoreCase(headerName)) {
String headerValue = header.getValue();
if (HTTPConstants.HEADER_HOST.equalsIgnoreCase(headerName)) {
int port = getPortFromHostHeader(headerValue, url.getPort());
// remove any port specification
headerValue = headerValue.replaceFirst(":\\d+$", ""); // $NON-NLS-1$ $NON-NLS-2$
if (port != -1 && port == url.getDefaultPort()) {
port = -1; // no need to specify the port if it is the default
}
if(port == -1) {
request.addHeader(HEADER_HOST, headerValue);
} else {
request.addHeader(HEADER_HOST, headerValue+":"+port);
}
} else {
request.addHeader(headerName, headerValue);
}
}
}
}
}
if (cacheManager != null) {
cacheManager.setHeaders(url, request);
}
}
/**
* Get port from the value of the Host header, or return the given
* defaultValue
*
* @param hostHeaderValue
* value of the http Host header
* @param defaultValue
* value to be used, when no port could be extracted from
* hostHeaderValue
* @return integer representing the port for the host header
*/
private int getPortFromHostHeader(String hostHeaderValue, int defaultValue) {
String[] hostParts = hostHeaderValue.split(":");
if (hostParts.length > 1) {
String portString = hostParts[hostParts.length - 1];
if (PORT_PATTERN.matcher(portString).matches()) {
return Integer.parseInt(portString);
}
}
return defaultValue;
}
/**
* Get all the request headers except Cookie for the <code>HttpRequest</code>
*
* @param method
* <code>HttpMethod</code> which represents the request
* @return the headers as a string
*/
private String getAllHeadersExceptCookie(HttpRequest method) {
return getFromHeadersMatchingPredicate(method, ALL_EXCEPT_COOKIE);
}
/**
* Get only Cookie header for the <code>HttpRequest</code>
*
* @param method
* <code>HttpMethod</code> which represents the request
* @return the headers as a string
*/
private String getOnlyCookieFromHeaders(HttpRequest method) {
String cookieHeader= getFromHeadersMatchingPredicate(method, ONLY_COOKIE).trim();
if(!cookieHeader.isEmpty()) {
return cookieHeader.substring((HTTPConstants.HEADER_COOKIE_IN_REQUEST).length(), cookieHeader.length()).trim();
}
return "";
}
/**
* Get only cookies from request headers for the <code>HttpRequest</code>
*
* @param method
* <code>HttpMethod</code> which represents the request
* @return the headers as a string
*/
private String getFromHeadersMatchingPredicate(HttpRequest method, Predicate<String> predicate) {
if(method != null) {
// Get all the request headers
StringBuilder hdrs = new StringBuilder(150);
Header[] requestHeaders = method.getAllHeaders();
for (Header requestHeader : requestHeaders) {
// Get header if it matches predicate
if (predicate.test(requestHeader.getName())) {
writeHeader(hdrs, requestHeader);
}
}
return hdrs.toString();
}
return ""; ////$NON-NLS-1$
}
// Helper class so we can generate request data without dumping entire file contents
private static class ViewableFileBody extends FileBody {
private boolean hideFileData;
public ViewableFileBody(File file, ContentType contentType) {
super(file, contentType);
hideFileData = false;
}
@Override
public void writeTo(final OutputStream out) throws IOException {
if (hideFileData) {
out.write("<actual file content, not shown here>".getBytes());// encoding does not really matter here
} else {
super.writeTo(out);
}
}
}
/**
* @param entityEnclosingRequest {@link HttpEntityEnclosingRequestBase}
* @return String body sent if computable
* @throws IOException if sending the data fails due to I/O
*/
protected String setupHttpEntityEnclosingRequestData(HttpEntityEnclosingRequestBase entityEnclosingRequest) throws IOException {
// Buffer to hold the post body, except file content
StringBuilder postedBody = new StringBuilder(1000);
HTTPFileArg[] files = getHTTPFiles();
final String contentEncoding = getContentEncodingOrNull();
final boolean haveContentEncoding = contentEncoding != null;
// Check if we should do a multipart/form-data or an
// application/x-www-form-urlencoded post request
if(getUseMultipart()) {
// If a content encoding is specified, we use that as the
// encoding of any parameter values
Charset charset;
if(haveContentEncoding) {
charset = Charset.forName(contentEncoding);
} else {
charset = MIME.DEFAULT_CHARSET;
}
if(log.isDebugEnabled()) {
log.debug("Building multipart with:getDoBrowserCompatibleMultipart(): {}, with charset:{}, haveContentEncoding:{}",
getDoBrowserCompatibleMultipart(), charset, haveContentEncoding);
}
// Write the request to our own stream
MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
if(getDoBrowserCompatibleMultipart()) {
multipartEntityBuilder.setLaxMode();
} else {
multipartEntityBuilder.setStrictMode();
}
// Create the parts
// Add any parameters
for (JMeterProperty jMeterProperty : getArguments()) {
HTTPArgument arg = (HTTPArgument) jMeterProperty.getObjectValue();
String parameterName = arg.getName();
if (arg.isSkippable(parameterName)) {
continue;
}
StringBody stringBody = new StringBody(arg.getValue(), ContentType.create(arg.getContentType(), charset));
FormBodyPart formPart = FormBodyPartBuilder.create(
parameterName, stringBody).build();
multipartEntityBuilder.addPart(formPart);
}
// Add any files
// Cannot retrieve parts once added to the MultiPartEntity, so have to save them here.
ViewableFileBody[] fileBodies = new ViewableFileBody[files.length];
for (int i=0; i < files.length; i++) {
HTTPFileArg file = files[i];
File reservedFile = FileServer.getFileServer().getResolvedFile(file.getPath());
fileBodies[i] = new ViewableFileBody(reservedFile, ContentType.create(file.getMimeType()));
multipartEntityBuilder.addPart(file.getParamName(), fileBodies[i] );
}
HttpEntity entity = multipartEntityBuilder.build();
entityEnclosingRequest.setEntity(entity);
writeEntityToSB(postedBody, entity, fileBodies, contentEncoding);
} else { // not multipart
// Check if the header manager had a content type header
// This allows the user to specify his own content-type for a POST request
Header contentTypeHeader = entityEnclosingRequest.getFirstHeader(HTTPConstants.HEADER_CONTENT_TYPE);
boolean hasContentTypeHeader = contentTypeHeader != null && contentTypeHeader.getValue() != null && contentTypeHeader.getValue().length() > 0;
// If there are no arguments, we can send a file as the body of the request
// TODO: needs a multiple file upload scenerio
if(!hasArguments() && getSendFileAsPostBody()) {
// If getSendFileAsPostBody returned true, it's sure that file is not null
HTTPFileArg file = files[0];
if(!hasContentTypeHeader) {
// Allow the mimetype of the file to control the content type
if(file.getMimeType() != null && file.getMimeType().length() > 0) {
entityEnclosingRequest.setHeader(HTTPConstants.HEADER_CONTENT_TYPE, file.getMimeType());
}
else if(ADD_CONTENT_TYPE_TO_POST_IF_MISSING) {
entityEnclosingRequest.setHeader(HTTPConstants.HEADER_CONTENT_TYPE, HTTPConstants.APPLICATION_X_WWW_FORM_URLENCODED);
}
}
FileEntity fileRequestEntity = new FileEntity(FileServer.getFileServer().getResolvedFile(file.getPath()), (ContentType) null);
entityEnclosingRequest.setEntity(fileRequestEntity);
// We just add placeholder text for file content
postedBody.append("<actual file content, not shown here>");
} else {
// In a post request which is not multipart, we only support
// parameters, no file upload is allowed
// If none of the arguments have a name specified, we
// just send all the values as the post body
if(getSendParameterValuesAsPostBody()) {
// Allow the mimetype of the file to control the content type
// This is not obvious in GUI if you are not uploading any files,
// but just sending the content of nameless parameters
// TODO: needs a multiple file upload scenario
if(!hasContentTypeHeader) {
HTTPFileArg file = files.length > 0? files[0] : null;
if(file != null && file.getMimeType() != null && file.getMimeType().length() > 0) {
entityEnclosingRequest.setHeader(HTTPConstants.HEADER_CONTENT_TYPE, file.getMimeType());
}
else if(ADD_CONTENT_TYPE_TO_POST_IF_MISSING) {
entityEnclosingRequest.setHeader(HTTPConstants.HEADER_CONTENT_TYPE, HTTPConstants.APPLICATION_X_WWW_FORM_URLENCODED);
}
}
// Just append all the parameter values, and use that as the post body
StringBuilder postBody = new StringBuilder();
for (JMeterProperty jMeterProperty : getArguments()) {
HTTPArgument arg = (HTTPArgument) jMeterProperty.getObjectValue();
// Note: if "Encoded?" is not selected, arg.getEncodedValue is equivalent to arg.getValue
if (haveContentEncoding) {
postBody.append(arg.getEncodedValue(contentEncoding));
} else {
postBody.append(arg.getEncodedValue());
}
}
// Let StringEntity perform the encoding
StringEntity requestEntity = new StringEntity(postBody.toString(), contentEncoding);
entityEnclosingRequest.setEntity(requestEntity);
postedBody.append(postBody.toString());
} else {
// It is a normal post request, with parameter names and values
// Set the content type
if(!hasContentTypeHeader && ADD_CONTENT_TYPE_TO_POST_IF_MISSING) {
entityEnclosingRequest.setHeader(HTTPConstants.HEADER_CONTENT_TYPE, HTTPConstants.APPLICATION_X_WWW_FORM_URLENCODED);
}
String urlContentEncoding = contentEncoding;
UrlEncodedFormEntity entity = createUrlEncodedFormEntity(urlContentEncoding);
entityEnclosingRequest.setEntity(entity);
writeEntityToSB(postedBody, entity, EMPTY_FILE_BODIES, contentEncoding);
}
}
}
return postedBody.toString();
}
/**
* @param postedBody
* @param entity
* @param fileBodies Array of {@link ViewableFileBody}
* @param contentEncoding
* @throws IOException
* @throws UnsupportedEncodingException
*/
private void writeEntityToSB(final StringBuilder postedBody, final HttpEntity entity,
final ViewableFileBody[] fileBodies, final String contentEncoding)
throws IOException {
if (entity.isRepeatable()){
ByteArrayOutputStream bos = new ByteArrayOutputStream();
for(ViewableFileBody fileBody : fileBodies){
fileBody.hideFileData = true;
}
entity.writeTo(bos);
for(ViewableFileBody fileBody : fileBodies){
fileBody.hideFileData = false;
}
bos.flush();
// We get the posted bytes using the encoding used to create it
postedBody.append(bos.toString(
contentEncoding == null ? SampleResult.DEFAULT_HTTP_ENCODING
: contentEncoding));
bos.close();
} else {
postedBody.append("<Entity was not repeatable, cannot view what was sent>"); // $NON-NLS-1$
}
}
/**
* Creates the entity data to be sent.
* <p>
* If there is a file entry with a non-empty MIME type we use that to
* set the request Content-Type header, otherwise we default to whatever
* header is present from a Header Manager.
* <p>
* If the content charset {@link #getContentEncoding()} is null or empty
* we use the HC4 default provided by {@link HTTP#DEF_CONTENT_CHARSET} which is
* ISO-8859-1.
*
* @param entity to be processed, e.g. PUT or PATCH
* @return the entity content, may be empty
* @throws UnsupportedEncodingException for invalid charset name
* @throws IOException cannot really occur for ByteArrayOutputStream methods
*/
protected String sendEntityData( HttpEntityEnclosingRequestBase entity) throws IOException {
boolean hasEntityBody = false;
final HTTPFileArg[] files = getHTTPFiles();
// Allow the mimetype of the file to control the content type
// This is not obvious in GUI if you are not uploading any files,
// but just sending the content of nameless parameters
final HTTPFileArg file = files.length > 0? files[0] : null;
String contentTypeValue;
if(file != null && file.getMimeType() != null && file.getMimeType().length() > 0) {
contentTypeValue = file.getMimeType();
entity.setHeader(HEADER_CONTENT_TYPE, contentTypeValue); // we provide the MIME type here
}
// Check for local contentEncoding (charset) override; fall back to default for content body
// we do this here rather so we can use the same charset to retrieve the data
final String charset = getContentEncoding(HTTP.DEF_CONTENT_CHARSET.name());
// Only create this if we are overriding whatever default there may be
// If there are no arguments, we can send a file as the body of the request
if(!hasArguments() && getSendFileAsPostBody()) {
hasEntityBody = true;
// If getSendFileAsPostBody returned true, it's sure that file is not null
File reservedFile = FileServer.getFileServer().getResolvedFile(files[0].getPath());
FileEntity fileRequestEntity = new FileEntity(reservedFile); // no need for content-type here
entity.setEntity(fileRequestEntity);
}
// If none of the arguments have a name specified, we
// just send all the values as the entity body
else if(getSendParameterValuesAsPostBody()) {
hasEntityBody = true;
// Just append all the parameter values, and use that as the entity body
Arguments arguments = getArguments();
StringBuilder entityBodyContent = new StringBuilder(arguments.getArgumentCount()*15);
for (JMeterProperty jMeterProperty : arguments) {
HTTPArgument arg = (HTTPArgument) jMeterProperty.getObjectValue();
// Note: if "Encoded?" is not selected, arg.getEncodedValue is equivalent to arg.getValue
if (charset != null) {
entityBodyContent.append(arg.getEncodedValue(charset));
} else {
entityBodyContent.append(arg.getEncodedValue());
}
}
StringEntity requestEntity = new StringEntity(entityBodyContent.toString(), charset);
entity.setEntity(requestEntity);
} else if (hasArguments()) {
hasEntityBody = true;
entity.setEntity(createUrlEncodedFormEntity(getContentEncodingOrNull()));
}
// Check if we have any content to send for body
if(hasEntityBody) {
// If the request entity is repeatable, we can send it first to
// our own stream, so we can return it
final HttpEntity entityEntry = entity.getEntity();
// Buffer to hold the entity body
StringBuilder entityBody = new StringBuilder(65);
writeEntityToSB(entityBody, entityEntry, EMPTY_FILE_BODIES, charset);
return entityBody.toString();
}
return ""; // may be the empty string
}
/**
* Create UrlEncodedFormEntity from parameters
* @param contentEncoding Content encoding may be null or empty
* @return {@link UrlEncodedFormEntity}
* @throws UnsupportedEncodingException
*/
private UrlEncodedFormEntity createUrlEncodedFormEntity(final String contentEncoding) throws UnsupportedEncodingException {
// It is a normal request, with parameter names and values
// Add the parameters
PropertyIterator args = getArguments().iterator();
List<NameValuePair> nvps = new ArrayList<>();
String urlContentEncoding = contentEncoding;
if (urlContentEncoding == null || urlContentEncoding.length() == 0) {
// Use the default encoding for urls
urlContentEncoding = EncoderCache.URL_ARGUMENT_ENCODING;
}
while (args.hasNext()) {
HTTPArgument arg = (HTTPArgument) args.next().getObjectValue();
// The HTTPClient always urlencodes both name and value,
// so if the argument is already encoded, we have to decode
// it before adding it to the post request
String parameterName = arg.getName();
if (arg.isSkippable(parameterName)) {
continue;
}
String parameterValue = arg.getValue();
if (!arg.isAlwaysEncoded()) {
// The value is already encoded by the user
// Must decode the value now, so that when the
// httpclient encodes it, we end up with the same value
// as the user had entered.
parameterName = URLDecoder.decode(parameterName, urlContentEncoding);
parameterValue = URLDecoder.decode(parameterValue, urlContentEncoding);
}
// Add the parameter, httpclient will urlencode it
nvps.add(new BasicNameValuePair(parameterName, parameterValue));
}
return new UrlEncodedFormEntity(nvps, urlContentEncoding);
}
/**
*
* @return the value of {@link #getContentEncoding()}; forced to null if empty
*/
private String getContentEncodingOrNull() {
return getContentEncoding(null);
}
/**
* @param dflt the default to be used
* @return the value of {@link #getContentEncoding()}; default if null or empty
*/
private String getContentEncoding(String dflt) {
String ce = getContentEncoding();
if (isNullOrEmptyTrimmed(ce)) {
return dflt;
} else {
return ce;
}
}
private void saveConnectionCookies(HttpResponse method, URL u, CookieManager cookieManager) {
if (cookieManager != null) {
Header[] hdrs = method.getHeaders(HTTPConstants.HEADER_SET_COOKIE);
for (Header hdr : hdrs) {
cookieManager.addCookieFromHeader(hdr.getValue(),u);
}
}
}
@Override
protected void notifyFirstSampleAfterLoopRestart() {
log.debug("notifyFirstSampleAfterLoopRestart called "
+ "with config(httpclient.reset_state_on_thread_group_iteration={})",
RESET_STATE_ON_THREAD_GROUP_ITERATION);
resetStateOnThreadGroupIteration.set(RESET_STATE_ON_THREAD_GROUP_ITERATION);
}
@Override
protected void threadFinished() {
log.debug("Thread Finished");
closeThreadLocalConnections();
}
/**
*
*/
private void closeThreadLocalConnections() {
// Does not need to be synchronised, as all access is from same thread
Map<HttpClientKey, MutableTriple<CloseableHttpClient, AuthState, PoolingHttpClientConnectionManager>>
mapHttpClientPerHttpClientKey = HTTPCLIENTS_CACHE_PER_THREAD_AND_HTTPCLIENTKEY.get();
if (mapHttpClientPerHttpClientKey != null ) {
for (MutableTriple<CloseableHttpClient, AuthState, PoolingHttpClientConnectionManager> triple : mapHttpClientPerHttpClientKey.values() ) {
JOrphanUtils.closeQuietly(triple.getLeft());
JOrphanUtils.closeQuietly(triple.getRight());
}
mapHttpClientPerHttpClientKey.clear();
}
}
@Override
public boolean interrupt() {
HttpUriRequest request = currentRequest;
if (request != null) {
currentRequest = null; // don't try twice
try {
request.abort();
} catch (UnsupportedOperationException e) {
log.warn("Could not abort pending request", e);
}
}
return request != null;
}
}
| src/protocol/http/org/apache/jmeter/protocol/http/sampler/HTTPHC4Impl.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.apache.jmeter.protocol.http.sampler;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLDecoder;
import java.nio.charset.Charset;
import java.security.GeneralSecurityException;
import java.security.PrivilegedActionException;
import java.security.PrivilegedExceptionAction;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.function.Predicate;
import java.util.regex.Pattern;
import javax.security.auth.Subject;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.tuple.MutableTriple;
import org.apache.http.Header;
import org.apache.http.HttpClientConnection;
import org.apache.http.HttpConnectionMetrics;
import org.apache.http.HttpEntity;
import org.apache.http.HttpException;
import org.apache.http.HttpHost;
import org.apache.http.HttpRequest;
import org.apache.http.HttpRequestInterceptor;
import org.apache.http.HttpResponse;
import org.apache.http.HttpResponseInterceptor;
import org.apache.http.NameValuePair;
import org.apache.http.StatusLine;
import org.apache.http.auth.AuthSchemeProvider;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.AuthState;
import org.apache.http.auth.Credentials;
import org.apache.http.auth.NTCredentials;
import org.apache.http.client.AuthCache;
import org.apache.http.client.AuthenticationStrategy;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.config.AuthSchemes;
import org.apache.http.client.config.CookieSpecs;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.InputStreamFactory;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpEntityEnclosingRequestBase;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpHead;
import org.apache.http.client.methods.HttpOptions;
import org.apache.http.client.methods.HttpPatch;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.client.methods.HttpTrace;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.client.protocol.ResponseContentEncoding;
import org.apache.http.config.Lookup;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.config.SocketConfig;
import org.apache.http.conn.ConnectionKeepAliveStrategy;
import org.apache.http.conn.DnsResolver;
import org.apache.http.conn.ManagedHttpClientConnection;
import org.apache.http.conn.SchemePortResolver;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.cookie.CookieSpecProvider;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.FileEntity;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.FormBodyPart;
import org.apache.http.entity.mime.FormBodyPartBuilder;
import org.apache.http.entity.mime.MIME;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.auth.BasicScheme;
import org.apache.http.impl.auth.BasicSchemeFactory;
import org.apache.http.impl.auth.DigestScheme;
import org.apache.http.impl.auth.DigestSchemeFactory;
import org.apache.http.impl.auth.KerberosScheme;
import org.apache.http.impl.auth.NTLMSchemeFactory;
import org.apache.http.impl.client.BasicAuthCache;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultClientConnectionReuseStrategy;
import org.apache.http.impl.client.DefaultConnectionKeepAliveStrategy;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.client.LaxRedirectStrategy;
import org.apache.http.impl.client.ProxyAuthenticationStrategy;
import org.apache.http.impl.client.StandardHttpRequestRetryHandler;
import org.apache.http.impl.conn.DefaultHttpClientConnectionOperator;
import org.apache.http.impl.conn.DefaultSchemePortResolver;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.impl.conn.SystemDefaultDnsResolver;
import org.apache.http.impl.cookie.IgnoreSpecProvider;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.message.BufferedHeader;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HTTP;
import org.apache.http.protocol.HttpContext;
import org.apache.http.protocol.HttpCoreContext;
import org.apache.http.protocol.HttpRequestExecutor;
import org.apache.http.util.CharArrayBuffer;
import org.apache.http.util.EntityUtils;
import org.apache.jmeter.config.Arguments;
import org.apache.jmeter.protocol.http.api.auth.DigestParameters;
import org.apache.jmeter.protocol.http.control.AuthManager;
import org.apache.jmeter.protocol.http.control.AuthManager.Mechanism;
import org.apache.jmeter.protocol.http.control.Authorization;
import org.apache.jmeter.protocol.http.control.CacheManager;
import org.apache.jmeter.protocol.http.control.CookieManager;
import org.apache.jmeter.protocol.http.control.DynamicKerberosSchemeFactory;
import org.apache.jmeter.protocol.http.control.DynamicSPNegoSchemeFactory;
import org.apache.jmeter.protocol.http.control.HeaderManager;
import org.apache.jmeter.protocol.http.sampler.hc.LaxDeflateInputStream;
import org.apache.jmeter.protocol.http.sampler.hc.LaxGZIPInputStream;
import org.apache.jmeter.protocol.http.sampler.hc.LazyLayeredConnectionSocketFactory;
import org.apache.jmeter.protocol.http.util.EncoderCache;
import org.apache.jmeter.protocol.http.util.HTTPArgument;
import org.apache.jmeter.protocol.http.util.HTTPConstants;
import org.apache.jmeter.protocol.http.util.HTTPFileArg;
import org.apache.jmeter.protocol.http.util.SlowHCPlainConnectionSocketFactory;
import org.apache.jmeter.samplers.SampleResult;
import org.apache.jmeter.services.FileServer;
import org.apache.jmeter.testelement.property.CollectionProperty;
import org.apache.jmeter.testelement.property.JMeterProperty;
import org.apache.jmeter.testelement.property.PropertyIterator;
import org.apache.jmeter.threads.JMeterContextService;
import org.apache.jmeter.threads.JMeterVariables;
import org.apache.jmeter.util.JMeterUtils;
import org.apache.jmeter.util.JsseSSLManager;
import org.apache.jmeter.util.SSLManager;
import org.apache.jorphan.util.JOrphanUtils;
import org.brotli.dec.BrotliInputStream;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* HTTP Sampler using Apache HttpClient 4.x.
*
*/
public class HTTPHC4Impl extends HTTPHCAbstractImpl {
private static final String CONTEXT_ATTRIBUTE_AUTH_MANAGER = "__jmeter.A_M__";
private static final String JMETER_VARIABLE_USER_TOKEN = "__jmeter.U_T__"; //$NON-NLS-1$
static final String CONTEXT_ATTRIBUTE_SAMPLER_RESULT = "__jmeter.S_R__"; //$NON-NLS-1$
private static final String CONTEXT_ATTRIBUTE_HTTPCLIENT_TOKEN = "__jmeter.H_T__";
private static final String CONTEXT_ATTRIBUTE_CLIENT_KEY = "__jmeter.C_K__";
private static final String CONTEXT_ATTRIBUTE_SENT_BYTES = "__jmeter.S_B__";
private static final String CONTEXT_ATTRIBUTE_METRICS = "__jmeter.M__";
private static final boolean DISABLE_DEFAULT_UA = JMeterUtils.getPropDefault("httpclient4.default_user_agent_disabled", false);
private static final boolean GZIP_RELAX_MODE = JMeterUtils.getPropDefault("httpclient4.gzip_relax_mode", false);
private static final boolean DEFLATE_RELAX_MODE = JMeterUtils.getPropDefault("httpclient4.deflate_relax_mode", false);
private static final Logger log = LoggerFactory.getLogger(HTTPHC4Impl.class);
private static final InputStreamFactory GZIP = new InputStreamFactory() {
@Override
public InputStream create(final InputStream instream) throws IOException {
return new LaxGZIPInputStream(instream, GZIP_RELAX_MODE);
}
};
private static final InputStreamFactory DEFLATE = new InputStreamFactory() {
@Override
public InputStream create(final InputStream instream) throws IOException {
return new LaxDeflateInputStream(instream, DEFLATE_RELAX_MODE);
}
};
private static final InputStreamFactory BROTLI = new InputStreamFactory() {
@Override
public InputStream create(final InputStream instream) throws IOException {
return new BrotliInputStream(instream);
}
};
private static final class PreemptiveAuthRequestInterceptor implements HttpRequestInterceptor {
@Override
public void process(HttpRequest request, HttpContext context) throws HttpException, IOException {
HttpClientContext localContext = HttpClientContext.adapt(context);
AuthManager authManager = (AuthManager) localContext.getAttribute(CONTEXT_ATTRIBUTE_AUTH_MANAGER);
if (authManager == null) {
Credentials credentials = null;
HttpClientKey key = (HttpClientKey) localContext.getAttribute(CONTEXT_ATTRIBUTE_CLIENT_KEY);
AuthScope authScope = null;
CredentialsProvider credentialsProvider = localContext.getCredentialsProvider();
if (key.hasProxy && !StringUtils.isEmpty(key.proxyUser)) {
authScope = new AuthScope(key.proxyHost, key.proxyPort);
credentials = credentialsProvider.getCredentials(authScope);
}
credentialsProvider.clear();
if (credentials != null) {
credentialsProvider.setCredentials(authScope, credentials);
}
return;
}
URI requestURI = null;
if (request instanceof HttpUriRequest) {
requestURI = ((HttpUriRequest) request).getURI();
} else {
try {
requestURI = new URI(request.getRequestLine().getUri());
} catch (final URISyntaxException ignore) { // NOSONAR
// NOOP
}
}
if(requestURI != null) {
HttpHost targetHost = (HttpHost) context.getAttribute(HttpCoreContext.HTTP_TARGET_HOST);
URL url;
if(requestURI.isAbsolute()) {
url = requestURI.toURL();
} else {
url = new URL(targetHost.getSchemeName(), targetHost.getHostName(), targetHost.getPort(),
requestURI.getPath());
}
Authorization authorization =
authManager.getAuthForURL(url);
CredentialsProvider credentialsProvider = localContext.getCredentialsProvider();
if(authorization != null) {
AuthCache authCache = localContext.getAuthCache();
if(authCache == null) {
authCache = new BasicAuthCache();
localContext.setAuthCache(authCache);
}
authManager.setupCredentials(authorization, url, localContext, credentialsProvider, LOCALHOST);
AuthState authState = (AuthState) context.getAttribute(HttpClientContext.TARGET_AUTH_STATE);
if (authState.getAuthScheme() == null) {
AuthScope authScope = new AuthScope(targetHost.getHostName(), targetHost.getPort(),
authorization.getRealm(), targetHost.getSchemeName());
Credentials creds = credentialsProvider.getCredentials(authScope);
if (creds != null) {
fillAuthCache(targetHost, authorization, authCache, authScope);
}
}
} else {
credentialsProvider.clear();
}
}
}
/**
* @param targetHost
* @param authorization
* @param authCache
* @param authScope
*/
private void fillAuthCache(HttpHost targetHost, Authorization authorization, AuthCache authCache,
AuthScope authScope) {
if(authorization.getMechanism() == Mechanism.BASIC_DIGEST || // NOSONAR
authorization.getMechanism() == Mechanism.BASIC) {
BasicScheme basicAuth = new BasicScheme();
authCache.put(targetHost, basicAuth);
} else if (authorization.getMechanism() == Mechanism.DIGEST) {
JMeterVariables vars = JMeterContextService.getContext().getVariables();
DigestParameters digestParameters = (DigestParameters)
vars.getObject(DIGEST_PARAMETERS);
if(digestParameters!=null) {
DigestScheme digestAuth = (DigestScheme) authCache.get(targetHost);
if(digestAuth == null) {
digestAuth = new DigestScheme();
}
digestAuth.overrideParamter("realm", authScope.getRealm());
digestAuth.overrideParamter("algorithm", digestParameters.getAlgorithm());
digestAuth.overrideParamter("charset", digestParameters.getCharset());
digestAuth.overrideParamter("nonce", digestParameters.getNonce());
digestAuth.overrideParamter("opaque", digestParameters.getOpaque());
digestAuth.overrideParamter("qop", digestParameters.getQop());
authCache.put(targetHost, digestAuth);
}
} else if (authorization.getMechanism() == Mechanism.KERBEROS) {
KerberosScheme kerberosScheme = new KerberosScheme();
authCache.put(targetHost, kerberosScheme);
}
}
}
private static final class JMeterDefaultHttpClientConnectionOperator extends DefaultHttpClientConnectionOperator {
public JMeterDefaultHttpClientConnectionOperator(Lookup<ConnectionSocketFactory> socketFactoryRegistry, SchemePortResolver schemePortResolver,
DnsResolver dnsResolver) {
super(socketFactoryRegistry, schemePortResolver, dnsResolver);
}
/* (non-Javadoc)
* @see org.apache.http.impl.conn.DefaultHttpClientConnectionOperator#connect(
* org.apache.http.conn.ManagedHttpClientConnection, org.apache.http.HttpHost,
* java.net.InetSocketAddress, int, org.apache.http.config.SocketConfig,
* org.apache.http.protocol.HttpContext)
*/
@Override
public void connect(ManagedHttpClientConnection conn, HttpHost host, InetSocketAddress localAddress,
int connectTimeout, SocketConfig socketConfig, HttpContext context) throws IOException {
try {
super.connect(conn, host, localAddress, connectTimeout, socketConfig, context);
} finally {
SampleResult sample =
(SampleResult)context.getAttribute(HTTPHC4Impl.CONTEXT_ATTRIBUTE_SAMPLER_RESULT);
if (sample != null) {
sample.connectEnd();
}
}
}
}
/** retry count to be used (default 0); 0 = disable retries */
private static final int RETRY_COUNT = JMeterUtils.getPropDefault("httpclient4.retrycount", 0);
/** true if it's OK to retry requests that have been sent */
private static final boolean REQUEST_SENT_RETRY_ENABLED =
JMeterUtils.getPropDefault("httpclient4.request_sent_retry_enabled", false);
/** Idle timeout to be applied to connections if no Keep-Alive header is sent by the server (default 0 = disable) */
private static final int IDLE_TIMEOUT = JMeterUtils.getPropDefault("httpclient4.idletimeout", 0);
private static final int VALIDITY_AFTER_INACTIVITY_TIMEOUT = JMeterUtils.getPropDefault("httpclient4.validate_after_inactivity", 1700);
private static final int TIME_TO_LIVE = JMeterUtils.getPropDefault("httpclient4.time_to_live", 2000);
/** Preemptive Basic Auth */
private static final boolean BASIC_AUTH_PREEMPTIVE = JMeterUtils.getPropDefault("httpclient4.auth.preemptive", true);
private static final Pattern PORT_PATTERN = Pattern.compile("\\d+"); // only used in .matches(), no need for anchors
private static final ConnectionKeepAliveStrategy IDLE_STRATEGY = new DefaultConnectionKeepAliveStrategy(){
@Override
public long getKeepAliveDuration(HttpResponse response, HttpContext context) {
long duration = super.getKeepAliveDuration(response, context);
if (duration <= 0 && IDLE_TIMEOUT > 0) {// none found by the superclass
log.debug("Setting keepalive to {}", IDLE_TIMEOUT);
return IDLE_TIMEOUT;
}
return duration; // return the super-class value
}
};
private static final String DIGEST_PARAMETERS = DigestParameters.VARIABLE_NAME;
private static final HttpRequestInterceptor PREEMPTIVE_AUTH_INTERCEPTOR = new PreemptiveAuthRequestInterceptor();
// see https://stackoverflow.com/questions/26166469/measure-bandwidth-usage-with-apache-httpcomponents-httpclient
private static final HttpRequestExecutor REQUEST_EXECUTOR = new HttpRequestExecutor() {
@Override
protected HttpResponse doSendRequest(
final HttpRequest request,
final HttpClientConnection conn,
final HttpContext context) throws IOException, HttpException {
HttpResponse response = super.doSendRequest(request, conn, context);
HttpConnectionMetrics metrics = conn.getMetrics();
long sentBytesCount = metrics.getSentBytesCount();
// We save to store sent bytes as we need to reset metrics for received bytes
context.setAttribute(CONTEXT_ATTRIBUTE_SENT_BYTES, metrics.getSentBytesCount());
context.setAttribute(CONTEXT_ATTRIBUTE_METRICS, metrics);
log.debug("Sent {} bytes", sentBytesCount);
metrics.reset();
return response;
}
};
/**
* Headers to save
*/
private static final String[] HEADERS_TO_SAVE = new String[]{
"content-length",
"content-encoding",
"content-md5"
};
/**
* Custom implementation that backups headers related to Compressed responses
* that HC core {@link ResponseContentEncoding} removes after uncompressing
* See Bug 59401
*/
private static final HttpResponseInterceptor RESPONSE_CONTENT_ENCODING = new ResponseContentEncoding(createLookupRegistry()) {
@Override
public void process(HttpResponse response, HttpContext context)
throws HttpException, IOException {
ArrayList<Header[]> headersToSave = null;
final HttpEntity entity = response.getEntity();
final HttpClientContext clientContext = HttpClientContext.adapt(context);
final RequestConfig requestConfig = clientContext.getRequestConfig();
// store the headers if necessary
if (requestConfig.isContentCompressionEnabled() && entity != null && entity.getContentLength() != 0) {
final Header ceheader = entity.getContentEncoding();
if (ceheader != null) {
headersToSave = new ArrayList<>(3);
for(String name : HEADERS_TO_SAVE) {
Header[] hdr = response.getHeaders(name); // empty if none
headersToSave.add(hdr);
}
}
}
// Now invoke original parent code
super.process(response, clientContext);
// Should this be in a finally ?
if(headersToSave != null) {
for (Header[] headers : headersToSave) {
for (Header headerToRestore : headers) {
if (response.containsHeader(headerToRestore.getName())) {
break;
}
response.addHeader(headerToRestore);
}
}
}
}
};
/**
* 1 HttpClient instance per combination of (HttpClient,HttpClientKey)
*/
private static final ThreadLocal<Map<HttpClientKey, MutableTriple<CloseableHttpClient, AuthState, PoolingHttpClientConnectionManager>>>
HTTPCLIENTS_CACHE_PER_THREAD_AND_HTTPCLIENTKEY =
InheritableThreadLocal.withInitial(() -> new HashMap<>(5));
/**
* CONNECTION_SOCKET_FACTORY changes if we want to simulate Slow connection
*/
private static final ConnectionSocketFactory CONNECTION_SOCKET_FACTORY;
private static final ViewableFileBody[] EMPTY_FILE_BODIES = new ViewableFileBody[0];
static {
log.info("HTTP request retry count = {}", RETRY_COUNT);
// Set up HTTP scheme override if necessary
if (CPS_HTTP > 0) {
log.info("Setting up HTTP SlowProtocol, cps={}", CPS_HTTP);
CONNECTION_SOCKET_FACTORY = new SlowHCPlainConnectionSocketFactory(CPS_HTTP);
} else {
CONNECTION_SOCKET_FACTORY = PlainConnectionSocketFactory.getSocketFactory();
}
}
private volatile HttpUriRequest currentRequest; // Accessed from multiple threads
protected HTTPHC4Impl(HTTPSamplerBase testElement) {
super(testElement);
}
/**
* Customize to plug Brotli
* @return {@link Lookup}
*/
private static Lookup<InputStreamFactory> createLookupRegistry() {
return
RegistryBuilder.<InputStreamFactory>create()
.register("br", BROTLI)
.register("gzip", GZIP)
.register("x-gzip", GZIP)
.register("deflate", DEFLATE).build();
}
/**
* Implementation that allows GET method to have a body
*/
public static final class HttpGetWithEntity extends HttpEntityEnclosingRequestBase {
public HttpGetWithEntity(final URI uri) {
super();
setURI(uri);
}
@Override
public String getMethod() {
return HTTPConstants.GET;
}
}
public static final class HttpDelete extends HttpEntityEnclosingRequestBase {
public HttpDelete(final URI uri) {
super();
setURI(uri);
}
@Override
public String getMethod() {
return HTTPConstants.DELETE;
}
}
@Override
protected HTTPSampleResult sample(URL url, String method,
boolean areFollowingRedirect, int frameDepth) {
if (log.isDebugEnabled()) {
log.debug("Start : sample {} method {} followingRedirect {} depth {}",
url, method, areFollowingRedirect, frameDepth);
}
JMeterVariables jMeterVariables = JMeterContextService.getContext().getVariables();
HTTPSampleResult res = createSampleResult(url, method);
CloseableHttpClient httpClient = null;
HttpRequestBase httpRequest = null;
HttpContext localContext = new BasicHttpContext();
HttpClientContext clientContext = HttpClientContext.adapt(localContext);
clientContext.setAttribute(CONTEXT_ATTRIBUTE_AUTH_MANAGER, getAuthManager());
HttpClientKey key = createHttpClientKey(url);
MutableTriple<CloseableHttpClient, AuthState, PoolingHttpClientConnectionManager> triple;
try {
httpClient = setupClient(key, jMeterVariables, clientContext);
// Cache triple for further use
Map<HttpClientKey, MutableTriple<CloseableHttpClient, AuthState, PoolingHttpClientConnectionManager>>
mapHttpClientPerHttpClientKey =
HTTPCLIENTS_CACHE_PER_THREAD_AND_HTTPCLIENTKEY.get();
triple =
mapHttpClientPerHttpClientKey.get(key);
URI uri = url.toURI();
httpRequest = createHttpRequest(uri, method, areFollowingRedirect);
setupRequest(url, httpRequest, res); // can throw IOException
} catch (Exception e) {
res.sampleStart();
res.sampleEnd();
errorResult(e, res);
return res;
}
setupClientContextBeforeSample(jMeterVariables, localContext);
res.sampleStart();
final CacheManager cacheManager = getCacheManager();
if (cacheManager != null && HTTPConstants.GET.equalsIgnoreCase(method) && cacheManager.inCache(url, httpRequest.getAllHeaders())) {
return updateSampleResultForResourceInCache(res);
}
CloseableHttpResponse httpResponse = null;
try {
currentRequest = httpRequest;
handleMethod(method, res, httpRequest, localContext);
// store the SampleResult in LocalContext to compute connect time
localContext.setAttribute(CONTEXT_ATTRIBUTE_SAMPLER_RESULT, res);
// perform the sample
httpResponse =
executeRequest(httpClient, httpRequest, localContext, url);
saveProxyAuth(triple, localContext);
if (log.isDebugEnabled()) {
log.debug("Headers in request before:{}", Arrays.asList(httpRequest.getAllHeaders()));
}
// Needs to be done after execute to pick up all the headers
final HttpRequest request = (HttpRequest) localContext.getAttribute(HttpCoreContext.HTTP_REQUEST);
if (log.isDebugEnabled()) {
log.debug("Headers in request after:{}, in localContext#request:{}",
Arrays.asList(httpRequest.getAllHeaders()),
Arrays.asList(request.getAllHeaders()));
}
extractClientContextAfterSample(jMeterVariables, localContext);
// We've finished with the request, so we can add the LocalAddress to it for display
if (localAddress != null) {
request.addHeader(HEADER_LOCAL_ADDRESS, localAddress.toString());
}
res.setRequestHeaders(getAllHeadersExceptCookie(request));
Header contentType = httpResponse.getLastHeader(HTTPConstants.HEADER_CONTENT_TYPE);
if (contentType != null){
String ct = contentType.getValue();
res.setContentType(ct);
res.setEncodingAndType(ct);
}
HttpEntity entity = httpResponse.getEntity();
if (entity != null) {
res.setResponseData(readResponse(res, entity.getContent(), entity.getContentLength()));
}
res.sampleEnd(); // Done with the sampling proper.
currentRequest = null;
// Now collect the results into the HTTPSampleResult:
StatusLine statusLine = httpResponse.getStatusLine();
int statusCode = statusLine.getStatusCode();
res.setResponseCode(Integer.toString(statusCode));
res.setResponseMessage(statusLine.getReasonPhrase());
res.setSuccessful(isSuccessCode(statusCode));
res.setResponseHeaders(getResponseHeaders(httpResponse));
if (res.isRedirect()) {
final Header headerLocation = httpResponse.getLastHeader(HTTPConstants.HEADER_LOCATION);
if (headerLocation == null) { // HTTP protocol violation, but avoids NPE
throw new IllegalArgumentException("Missing location header in redirect for " + httpRequest.getRequestLine());
}
String redirectLocation = headerLocation.getValue();
res.setRedirectLocation(redirectLocation);
}
// record some sizes to allow HTTPSampleResult.getBytes() with different options
long headerBytes =
(long)res.getResponseHeaders().length() // condensed length (without \r)
+ (long) httpResponse.getAllHeaders().length // Add \r for each header
+ 1L // Add \r for initial header
+ 2L; // final \r\n before data
HttpConnectionMetrics metrics = (HttpConnectionMetrics) localContext.getAttribute(CONTEXT_ATTRIBUTE_METRICS);
long totalBytes = metrics.getReceivedBytesCount();
res.setHeadersSize((int)headerBytes);
res.setBodySize(totalBytes - headerBytes);
res.setSentBytes((Long) localContext.getAttribute(CONTEXT_ATTRIBUTE_SENT_BYTES));
if (log.isDebugEnabled()) {
long total = res.getHeadersSize() + res.getBodySizeAsLong();
log.debug("ResponseHeadersSize={} Content-Length={} Total={}",
res.getHeadersSize(), res.getBodySizeAsLong(), total);
}
// If we redirected automatically, the URL may have changed
if (getAutoRedirects()) {
HttpUriRequest req = (HttpUriRequest) localContext.getAttribute(HttpCoreContext.HTTP_REQUEST);
HttpHost target = (HttpHost) localContext.getAttribute(HttpCoreContext.HTTP_TARGET_HOST);
URI redirectURI = req.getURI();
if (redirectURI.isAbsolute()) {
res.setURL(redirectURI.toURL());
} else {
res.setURL(new URL(new URL(target.toURI()),redirectURI.toString()));
}
}
// Store any cookies received in the cookie manager:
saveConnectionCookies(httpResponse, res.getURL(), getCookieManager());
// Save cache information
if (cacheManager != null){
cacheManager.saveDetails(httpResponse, res);
}
// Follow redirects and download page resources if appropriate:
res = resultProcessing(areFollowingRedirect, frameDepth, res);
if(!isSuccessCode(statusCode)) {
EntityUtils.consumeQuietly(httpResponse.getEntity());
}
} catch (IOException e) {
log.debug("IOException", e);
if (res.getEndTime() == 0) {
res.sampleEnd();
}
// pick up headers if failed to execute the request
if (res.getRequestHeaders() != null) {
log.debug("Overwriting request old headers: {}", res.getRequestHeaders());
}
res.setRequestHeaders(getAllHeadersExceptCookie((HttpRequest) localContext.getAttribute(HttpCoreContext.HTTP_REQUEST)));
errorResult(e, res);
return res;
} catch (RuntimeException e) {
log.debug("RuntimeException", e);
if (res.getEndTime() == 0) {
res.sampleEnd();
}
errorResult(e, res);
return res;
} finally {
JOrphanUtils.closeQuietly(httpResponse);
currentRequest = null;
JMeterContextService.getContext().getSamplerContext().remove(CONTEXT_ATTRIBUTE_HTTPCLIENT_TOKEN);
}
return res;
}
/**
* Associate Proxy state to thread
* @param triple {@link MutableTriple}
* @param localContext {@link HttpContext}
*/
private void saveProxyAuth(
MutableTriple<CloseableHttpClient, AuthState, PoolingHttpClientConnectionManager> triple,
HttpContext localContext) {
triple.setMiddle((AuthState) localContext.getAttribute(HttpClientContext.PROXY_AUTH_STATE));
}
/**
* Store in localContext Proxy auth state of triple
* @param triple {@link MutableTriple}
* @param localContext {@link HttpContext}
*/
private void setupProxyAuth(MutableTriple<CloseableHttpClient, AuthState, PoolingHttpClientConnectionManager> triple,
HttpContext localContext) {
if (triple != null) {
AuthState proxy = triple.getMiddle();
localContext.setAttribute(HttpClientContext.PROXY_AUTH_STATE, proxy);
}
}
/**
* @param uri {@link URI}
* @param method HTTP Method
* @param areFollowingRedirect Are we following redirects
* @return {@link HttpRequestBase}
*/
private HttpRequestBase createHttpRequest(URI uri, String method, boolean areFollowingRedirect) {
HttpRequestBase result;
if (method.equals(HTTPConstants.POST)) {
result = new HttpPost(uri);
} else if (method.equals(HTTPConstants.GET)) {
// Some servers fail if Content-Length is equal to 0
// so to avoid this we use HttpGet when there is no body (Content-Length will not be set)
// otherwise we use HttpGetWithEntity
if ( !areFollowingRedirect
&& ((!hasArguments() && getSendFileAsPostBody())
|| getSendParameterValuesAsPostBody()) ) {
result = new HttpGetWithEntity(uri);
} else {
result = new HttpGet(uri);
}
} else if (method.equals(HTTPConstants.PUT)) {
result = new HttpPut(uri);
} else if (method.equals(HTTPConstants.HEAD)) {
result = new HttpHead(uri);
} else if (method.equals(HTTPConstants.TRACE)) {
result = new HttpTrace(uri);
} else if (method.equals(HTTPConstants.OPTIONS)) {
result = new HttpOptions(uri);
} else if (method.equals(HTTPConstants.DELETE)) {
result = new HttpDelete(uri);
} else if (method.equals(HTTPConstants.PATCH)) {
result = new HttpPatch(uri);
} else if (HttpWebdav.isWebdavMethod(method)) {
result = new HttpWebdav(method, uri);
} else {
throw new IllegalArgumentException("Unexpected method: '"+method+"'");
}
return result;
}
/**
* Store in JMeter Variables the UserToken so that the SSL context is reused
* See <a href="https://bz.apache.org/bugzilla/show_bug.cgi?id=57804">Bug 57804</a>
* @param jMeterVariables {@link JMeterVariables}
* @param localContext {@link HttpContext}
*/
private void extractClientContextAfterSample(JMeterVariables jMeterVariables, HttpContext localContext) {
Object userToken = localContext.getAttribute(HttpClientContext.USER_TOKEN);
if(userToken != null) {
log.debug("Extracted from HttpContext user token:{} storing it as JMeter variable:{}", userToken, JMETER_VARIABLE_USER_TOKEN);
// During recording JMeterContextService.getContext().getVariables() is null
if (jMeterVariables != null) {
jMeterVariables.putObject(JMETER_VARIABLE_USER_TOKEN, userToken);
}
}
}
/**
* Configure the UserToken so that the SSL context is reused
* See <a href="https://bz.apache.org/bugzilla/show_bug.cgi?id=57804">Bug 57804</a>
* @param jMeterVariables {@link JMeterVariables}
* @param localContext {@link HttpContext}
*/
private void setupClientContextBeforeSample(JMeterVariables jMeterVariables, HttpContext localContext) {
Object userToken = null;
// During recording JMeterContextService.getContext().getVariables() is null
if(jMeterVariables != null) {
userToken = jMeterVariables.getObject(JMETER_VARIABLE_USER_TOKEN);
}
if(userToken != null) {
log.debug("Found user token:{} as JMeter variable:{}, storing it in HttpContext", userToken, JMETER_VARIABLE_USER_TOKEN);
localContext.setAttribute(HttpClientContext.USER_TOKEN, userToken);
} else {
// It would be better to create a ClientSessionManager that would compute this value
// for now it can be Thread.currentThread().getName() but must be changed when we would change
// the Thread per User model
String userId = Thread.currentThread().getName();
log.debug("Storing in HttpContext the user token: {}", userId);
localContext.setAttribute(HttpClientContext.USER_TOKEN, userId);
}
}
/**
* Setup Body of request if different from GET.
* Field HTTPSampleResult#queryString of result is modified in the 2 cases
*
* @param method
* String HTTP method
* @param result
* {@link HTTPSampleResult}
* @param httpRequest
* {@link HttpRequestBase}
* @param localContext
* {@link HttpContext}
* @throws IOException
* when posting data fails due to I/O
*/
protected void handleMethod(String method, HTTPSampleResult result,
HttpRequestBase httpRequest, HttpContext localContext) throws IOException {
// Handle the various methods
if (httpRequest instanceof HttpEntityEnclosingRequestBase) {
String entityBody = setupHttpEntityEnclosingRequestData((HttpEntityEnclosingRequestBase)httpRequest);
result.setQueryString(entityBody);
}
}
/**
* Create HTTPSampleResult filling url, method and SampleLabel.
* Monitor field is computed calling isMonitor()
* @param url URL
* @param method HTTP Method
* @return {@link HTTPSampleResult}
*/
protected HTTPSampleResult createSampleResult(URL url, String method) {
HTTPSampleResult res = new HTTPSampleResult();
configureSampleLabel(res, url);
res.setHTTPMethod(method);
res.setURL(url);
return res;
}
/**
* Execute request either as is or under PrivilegedAction
* if a Subject is available for url
* @param httpClient the {@link CloseableHttpClient} to be used to execute the httpRequest
* @param httpRequest the {@link HttpRequest} to be executed
* @param localContext th {@link HttpContext} to be used for execution
* @param url the target url (will be used to look up a possible subject for the execution)
* @return the result of the execution of the httpRequest
* @throws IOException
*/
private CloseableHttpResponse executeRequest(final CloseableHttpClient httpClient,
final HttpRequestBase httpRequest, final HttpContext localContext, final URL url)
throws IOException {
AuthManager authManager = getAuthManager();
if (authManager != null) {
Subject subject = authManager.getSubjectForUrl(url);
if (subject != null) {
try {
return Subject.doAs(subject,
(PrivilegedExceptionAction<CloseableHttpResponse>) () ->
httpClient.execute(httpRequest, localContext));
} catch (PrivilegedActionException e) {
log.error("Can't execute httpRequest with subject: {}", subject, e);
throw new IllegalArgumentException("Can't execute httpRequest with subject:" + subject, e);
}
}
}
return httpClient.execute(httpRequest, localContext);
}
/**
* Holder class for all fields that define an HttpClient instance;
* used as the key to the ThreadLocal map of HttpClient instances.
*/
private static final class HttpClientKey {
private final String target; // protocol://[user:pass@]host:[port]
private final boolean hasProxy;
private final String proxyScheme;
private final String proxyHost;
private final int proxyPort;
private final String proxyUser;
private final String proxyPass;
private final int hashCode; // Always create hash because we will always need it
/**
* @param url URL Only protocol and url authority are used (protocol://[user:pass@]host:[port])
* @param hasProxy has proxy
* @param proxyScheme scheme
* @param proxyHost proxy host
* @param proxyPort proxy port
* @param proxyUser proxy user
* @param proxyPass proxy password
*/
public HttpClientKey(URL url, boolean hasProxy, String proxyScheme, String proxyHost,
int proxyPort, String proxyUser, String proxyPass) {
// N.B. need to separate protocol from authority otherwise http://server would match https://erver (<= sic, not typo error)
// could use separate fields, but simpler to combine them
this.target = url.getProtocol()+"://"+url.getAuthority();
this.hasProxy = hasProxy;
this.proxyScheme = proxyScheme;
this.proxyHost = proxyHost;
this.proxyPort = proxyPort;
this.proxyUser = proxyUser;
this.proxyPass = proxyPass;
this.hashCode = getHash();
}
private int getHash() {
int hash = 17;
hash = hash*31 + (hasProxy ? 1 : 0);
if (hasProxy) {
hash = hash*31 + getHash(proxyScheme);
hash = hash*31 + getHash(proxyHost);
hash = hash*31 + proxyPort;
hash = hash*31 + getHash(proxyUser);
hash = hash*31 + getHash(proxyPass);
}
hash = hash*31 + target.hashCode();
return hash;
}
// Allow for null strings
private int getHash(String s) {
return s == null ? 0 : s.hashCode();
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (!(obj instanceof HttpClientKey)) {
return false;
}
HttpClientKey other = (HttpClientKey) obj;
if (this.hasProxy) { // otherwise proxy String fields may be null
if (proxyScheme == null) {
if (other.proxyScheme != null) {
return false;
}
} else if (!proxyScheme.equals(other.proxyScheme)) {
return false;
}
return
this.hasProxy == other.hasProxy &&
this.proxyPort == other.proxyPort &&
this.proxyHost.equals(other.proxyHost) &&
this.proxyUser.equals(other.proxyUser) &&
this.proxyPass.equals(other.proxyPass) &&
this.target.equals(other.target);
}
// No proxy, so don't check proxy fields
return
this.hasProxy == other.hasProxy &&
this.target.equals(other.target);
}
@Override
public int hashCode(){
return hashCode;
}
// For debugging
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(target);
if (hasProxy) {
sb.append(" via ");
sb.append(proxyUser);
sb.append('@');
sb.append(proxyScheme);
sb.append("://");
sb.append(proxyHost);
sb.append(':');
sb.append(proxyPort);
}
return sb.toString();
}
}
private CloseableHttpClient setupClient(HttpClientKey key, JMeterVariables jMeterVariables, HttpClientContext clientContext) throws GeneralSecurityException {
Map<HttpClientKey, MutableTriple<CloseableHttpClient, AuthState, PoolingHttpClientConnectionManager>> mapHttpClientPerHttpClientKey =
HTTPCLIENTS_CACHE_PER_THREAD_AND_HTTPCLIENTKEY.get();
clientContext.setAttribute(CONTEXT_ATTRIBUTE_CLIENT_KEY, key);
CloseableHttpClient httpClient = null;
boolean concurrentDwn = this.testElement.isConcurrentDwn();
if(concurrentDwn) {
httpClient = (CloseableHttpClient) JMeterContextService.getContext().getSamplerContext().get(CONTEXT_ATTRIBUTE_HTTPCLIENT_TOKEN);
}
MutableTriple<CloseableHttpClient, AuthState, PoolingHttpClientConnectionManager> triple =
mapHttpClientPerHttpClientKey.get(key);
if (httpClient == null) {
httpClient = triple != null ? triple.getLeft() : null;
}
setupProxyAuth(triple, clientContext);
resetStateIfNeeded(triple, jMeterVariables, clientContext, mapHttpClientPerHttpClientKey);
if (httpClient == null) { // One-time init for this client
DnsResolver resolver = this.testElement.getDNSResolver();
if (resolver == null) {
resolver = SystemDefaultDnsResolver.INSTANCE;
}
Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory> create().
register("https", new LazyLayeredConnectionSocketFactory()).
register("http", CONNECTION_SOCKET_FACTORY).
build();
// Modern browsers use more connections per host than the current httpclient default (2)
// when using parallel download the httpclient and connection manager are shared by the downloads threads
// to be realistic JMeter must set an higher value to DefaultMaxPerRoute
PoolingHttpClientConnectionManager pHCCM =
new PoolingHttpClientConnectionManager(
new JMeterDefaultHttpClientConnectionOperator(registry, null, resolver),
null, TIME_TO_LIVE, TimeUnit.MILLISECONDS);
pHCCM.setValidateAfterInactivity(VALIDITY_AFTER_INACTIVITY_TIMEOUT);
if(concurrentDwn) {
try {
int maxConcurrentDownloads = Integer.parseInt(this.testElement.getConcurrentPool());
pHCCM.setDefaultMaxPerRoute(Math.max(maxConcurrentDownloads, pHCCM.getDefaultMaxPerRoute()));
} catch (NumberFormatException nfe) {
// no need to log -> will be done by the sampler
}
}
CookieSpecProvider cookieSpecProvider = new IgnoreSpecProvider();
Lookup<CookieSpecProvider> cookieSpecRegistry = RegistryBuilder.<CookieSpecProvider>create()
.register(CookieSpecs.IGNORE_COOKIES, cookieSpecProvider)
.build();
HttpClientBuilder builder = HttpClients.custom().setConnectionManager(pHCCM).
setSchemePortResolver(new DefaultSchemePortResolver()).
setDnsResolver(resolver).
setRequestExecutor(REQUEST_EXECUTOR).
setSSLSocketFactory(new LazyLayeredConnectionSocketFactory()).
setDefaultCookieSpecRegistry(cookieSpecRegistry).
setDefaultSocketConfig(SocketConfig.DEFAULT).
setRedirectStrategy(new LaxRedirectStrategy()).
setConnectionTimeToLive(TIME_TO_LIVE, TimeUnit.MILLISECONDS).
setRetryHandler(new StandardHttpRequestRetryHandler(RETRY_COUNT, REQUEST_SENT_RETRY_ENABLED)).
setConnectionReuseStrategy(DefaultClientConnectionReuseStrategy.INSTANCE).
setProxyAuthenticationStrategy(getProxyAuthStrategy());
if(DISABLE_DEFAULT_UA) {
builder.disableDefaultUserAgent();
}
Lookup<AuthSchemeProvider> authSchemeRegistry =
RegistryBuilder.<AuthSchemeProvider>create()
.register(AuthSchemes.BASIC, new BasicSchemeFactory())
.register(AuthSchemes.DIGEST, new DigestSchemeFactory())
.register(AuthSchemes.NTLM, new NTLMSchemeFactory())
.register(AuthSchemes.SPNEGO, new DynamicSPNegoSchemeFactory(
AuthManager.STRIP_PORT, AuthManager.USE_CANONICAL_HOST_NAME))
.register(AuthSchemes.KERBEROS, new DynamicKerberosSchemeFactory(
AuthManager.STRIP_PORT, AuthManager.USE_CANONICAL_HOST_NAME))
.build();
builder.setDefaultAuthSchemeRegistry(authSchemeRegistry);
if (IDLE_TIMEOUT > 0) {
builder.setKeepAliveStrategy(IDLE_STRATEGY);
}
// Set up proxy details
if (key.hasProxy) {
HttpHost proxy = new HttpHost(key.proxyHost, key.proxyPort, key.proxyScheme);
builder.setProxy(proxy);
CredentialsProvider credsProvider = new BasicCredentialsProvider();
if (!key.proxyUser.isEmpty()) {
credsProvider.setCredentials(
new AuthScope(key.proxyHost, key.proxyPort),
new NTCredentials(key.proxyUser, key.proxyPass, LOCALHOST, PROXY_DOMAIN));
}
builder.setDefaultCredentialsProvider(credsProvider);
}
builder.disableContentCompression().addInterceptorLast(RESPONSE_CONTENT_ENCODING);
if(BASIC_AUTH_PREEMPTIVE) {
builder.addInterceptorFirst(PREEMPTIVE_AUTH_INTERCEPTOR);
}
httpClient = builder.build();
if (log.isDebugEnabled()) {
log.debug("Created new HttpClient: @{} {}", System.identityHashCode(httpClient), key);
}
mapHttpClientPerHttpClientKey.put(key, MutableTriple.of(httpClient, null, pHCCM)); // save the agent for next time round
} else {
if (log.isDebugEnabled()) {
log.debug("Reusing the HttpClient: @{} {}", System.identityHashCode(httpClient),key);
}
}
if(concurrentDwn) {
JMeterContextService.getContext().getSamplerContext().put(CONTEXT_ATTRIBUTE_HTTPCLIENT_TOKEN, httpClient);
}
return httpClient;
}
protected AuthenticationStrategy getProxyAuthStrategy() {
return ProxyAuthenticationStrategy.INSTANCE;
}
private HttpClientKey createHttpClientKey(URL url) {
final String host = url.getHost();
String proxyScheme = getProxyScheme();
String proxyHost = getProxyHost();
int proxyPort = getProxyPortInt();
String proxyPass = getProxyPass();
String proxyUser = getProxyUser();
// static proxy is the globally define proxy eg command line or properties
boolean useStaticProxy = isStaticProxy(host);
// dynamic proxy is the proxy defined for this sampler
boolean useDynamicProxy = isDynamicProxy(proxyHost, proxyPort);
boolean useProxy = useStaticProxy || useDynamicProxy;
// if both dynamic and static are used, the dynamic proxy has priority over static
if(!useDynamicProxy) {
proxyScheme = PROXY_SCHEME;
proxyHost = PROXY_HOST;
proxyPort = PROXY_PORT;
proxyUser = PROXY_USER;
proxyPass = PROXY_PASS;
}
// Lookup key - must agree with all the values used to create the HttpClient.
return new HttpClientKey(url, useProxy, proxyScheme, proxyHost, proxyPort, proxyUser, proxyPass);
}
/**
* Reset SSL State. <br/>
* In order to do that we need to:
* <ul>
* <li>Call resetContext() on SSLManager</li>
* <li>Close current Idle or Expired connections that hold SSL State</li>
* <li>Remove HttpClientContext.USER_TOKEN from {@link HttpClientContext}</li>
* </ul>
* @param jMeterVariables {@link JMeterVariables}
* @param clientContext {@link HttpClientContext}
* @param mapHttpClientPerHttpClientKey Map of {@link MutableTriple} holding {@link CloseableHttpClient} and {@link PoolingHttpClientConnectionManager}
*/
private void resetStateIfNeeded(
MutableTriple<CloseableHttpClient, AuthState, PoolingHttpClientConnectionManager> triple,
JMeterVariables jMeterVariables,
HttpClientContext clientContext,
Map<HttpClientKey, MutableTriple<CloseableHttpClient, AuthState, PoolingHttpClientConnectionManager>> mapHttpClientPerHttpClientKey) {
if (resetStateOnThreadGroupIteration.get()) {
closeCurrentConnections(mapHttpClientPerHttpClientKey);
clientContext.removeAttribute(HttpClientContext.USER_TOKEN);
clientContext.removeAttribute(HttpClientContext.PROXY_AUTH_STATE);
if (triple != null) {
triple.setMiddle(null);
}
jMeterVariables.remove(JMETER_VARIABLE_USER_TOKEN);
((JsseSSLManager) SSLManager.getInstance()).resetContext();
resetStateOnThreadGroupIteration.set(false);
}
}
/**
* @param mapHttpClientPerHttpClientKey
*/
private void closeCurrentConnections(
Map<HttpClientKey, MutableTriple<CloseableHttpClient, AuthState, PoolingHttpClientConnectionManager>> mapHttpClientPerHttpClientKey) {
for (MutableTriple<CloseableHttpClient, AuthState, PoolingHttpClientConnectionManager> triple :
mapHttpClientPerHttpClientKey.values()) {
PoolingHttpClientConnectionManager poolingHttpClientConnectionManager = triple.getRight();
poolingHttpClientConnectionManager.closeExpiredConnections();
poolingHttpClientConnectionManager.closeIdleConnections(1L, TimeUnit.MICROSECONDS);
}
}
/**
* Setup following elements on httpRequest:
* <ul>
* <li>ConnRoutePNames.LOCAL_ADDRESS enabling IP-SPOOFING</li>
* <li>Socket and connection timeout</li>
* <li>Redirect handling</li>
* <li>Keep Alive header or Connection Close</li>
* <li>Calls setConnectionHeaders to setup headers</li>
* <li>Calls setConnectionCookie to setup Cookie</li>
* </ul>
*
* @param url
* {@link URL} of the request
* @param httpRequest
* http request for the request
* @param res
* sample result to set cookies on
* @throws IOException
* if hostname/ip to use could not be figured out
*/
protected void setupRequest(URL url, HttpRequestBase httpRequest, HTTPSampleResult res)
throws IOException {
RequestConfig.Builder rCB = RequestConfig.custom();
// Set up the local address if one exists
final InetAddress inetAddr = getIpSourceAddress();
if (inetAddr != null) {// Use special field ip source address (for pseudo 'ip spoofing')
rCB.setLocalAddress(inetAddr);
} else if (localAddress != null){
rCB.setLocalAddress(localAddress);
}
int rto = getResponseTimeout();
if (rto > 0){
rCB.setSocketTimeout(rto);
}
int cto = getConnectTimeout();
if (cto > 0){
rCB.setConnectTimeout(cto);
}
rCB.setRedirectsEnabled(getAutoRedirects());
rCB.setMaxRedirects(HTTPSamplerBase.MAX_REDIRECTS);
httpRequest.setConfig(rCB.build());
// a well-behaved browser is supposed to send 'Connection: close'
// with the last request to an HTTP server. Instead, most browsers
// leave it to the server to close the connection after their
// timeout period. Leave it to the JMeter user to decide.
if (getUseKeepAlive()) {
httpRequest.setHeader(HTTPConstants.HEADER_CONNECTION, HTTPConstants.KEEP_ALIVE);
} else {
httpRequest.setHeader(HTTPConstants.HEADER_CONNECTION, HTTPConstants.CONNECTION_CLOSE);
}
setConnectionHeaders(httpRequest, url, getHeaderManager(), getCacheManager());
String cookies = setConnectionCookie(httpRequest, url, getCookieManager());
if (res != null) {
if(cookies != null && !cookies.isEmpty()) {
res.setCookies(cookies);
} else {
// During recording Cookie Manager doesn't handle cookies
res.setCookies(getOnlyCookieFromHeaders(httpRequest));
}
}
}
/**
* Set any default request headers to include
*
* @param request the HttpRequest to be used
*/
protected void setDefaultRequestHeaders(HttpRequest request) {
// Method left empty here, but allows subclasses to override
}
/**
* Gets the ResponseHeaders
*
* @param response
* containing the headers
* @return string containing the headers, one per line
*/
private String getResponseHeaders(HttpResponse response) {
Header[] rh = response.getAllHeaders();
StringBuilder headerBuf = new StringBuilder(40 * (rh.length+1));
headerBuf.append(response.getStatusLine());// header[0] is not the status line...
headerBuf.append("\n"); // $NON-NLS-1$
for (Header responseHeader : rh) {
writeHeader(headerBuf, responseHeader);
}
return headerBuf.toString();
}
/**
* Write header to headerBuffer in an optimized way
* @param headerBuffer {@link StringBuilder}
* @param header {@link Header}
*/
private void writeHeader(StringBuilder headerBuffer, Header header) {
if(header instanceof BufferedHeader) {
CharArrayBuffer buffer = ((BufferedHeader)header).getBuffer();
headerBuffer.append(buffer.buffer(), 0, buffer.length()).append('\n'); // $NON-NLS-1$
}
else {
headerBuffer.append(header.getName())
.append(": ") // $NON-NLS-1$
.append(header.getValue())
.append('\n'); // $NON-NLS-1$
}
}
/**
* Extracts all the required cookies for that particular URL request and
* sets them in the <code>HttpMethod</code> passed in.
*
* @param request <code>HttpRequest</code> for the request
* @param url <code>URL</code> of the request
* @param cookieManager the <code>CookieManager</code> containing all the cookies
* @return a String containing the cookie details (for the response)
* May be null
*/
protected String setConnectionCookie(HttpRequest request, URL url, CookieManager cookieManager) {
String cookieHeader = null;
if (cookieManager != null) {
cookieHeader = cookieManager.getCookieHeaderForURL(url);
if (cookieHeader != null) {
request.setHeader(HTTPConstants.HEADER_COOKIE, cookieHeader);
}
}
return cookieHeader;
}
/**
* Extracts all the required non-cookie headers for that particular URL request and
* sets them in the <code>HttpMethod</code> passed in
*
* @param request
* <code>HttpRequest</code> which represents the request
* @param url
* <code>URL</code> of the URL request
* @param headerManager
* the <code>HeaderManager</code> containing all the cookies
* for this <code>UrlConfig</code>
* @param cacheManager the CacheManager (may be null)
*/
protected void setConnectionHeaders(HttpRequestBase request, URL url, HeaderManager headerManager, CacheManager cacheManager) {
if (headerManager != null) {
CollectionProperty headers = headerManager.getHeaders();
if (headers != null) {
for (JMeterProperty jMeterProperty : headers) {
org.apache.jmeter.protocol.http.control.Header header
= (org.apache.jmeter.protocol.http.control.Header)
jMeterProperty.getObjectValue();
String headerName = header.getName();
// Don't allow override of Content-Length
if (!HTTPConstants.HEADER_CONTENT_LENGTH.equalsIgnoreCase(headerName)) {
String headerValue = header.getValue();
if (HTTPConstants.HEADER_HOST.equalsIgnoreCase(headerName)) {
int port = getPortFromHostHeader(headerValue, url.getPort());
// remove any port specification
headerValue = headerValue.replaceFirst(":\\d+$", ""); // $NON-NLS-1$ $NON-NLS-2$
if (port != -1 && port == url.getDefaultPort()) {
port = -1; // no need to specify the port if it is the default
}
if(port == -1) {
request.addHeader(HEADER_HOST, headerValue);
} else {
request.addHeader(HEADER_HOST, headerValue+":"+port);
}
} else {
request.addHeader(headerName, headerValue);
}
}
}
}
}
if (cacheManager != null) {
cacheManager.setHeaders(url, request);
}
}
/**
* Get port from the value of the Host header, or return the given
* defaultValue
*
* @param hostHeaderValue
* value of the http Host header
* @param defaultValue
* value to be used, when no port could be extracted from
* hostHeaderValue
* @return integer representing the port for the host header
*/
private int getPortFromHostHeader(String hostHeaderValue, int defaultValue) {
String[] hostParts = hostHeaderValue.split(":");
if (hostParts.length > 1) {
String portString = hostParts[hostParts.length - 1];
if (PORT_PATTERN.matcher(portString).matches()) {
return Integer.parseInt(portString);
}
}
return defaultValue;
}
/**
* Get all the request headers except Cookie for the <code>HttpRequest</code>
*
* @param method
* <code>HttpMethod</code> which represents the request
* @return the headers as a string
*/
private String getAllHeadersExceptCookie(HttpRequest method) {
return getFromHeadersMatchingPredicate(method, ALL_EXCEPT_COOKIE);
}
/**
* Get only Cookie header for the <code>HttpRequest</code>
*
* @param method
* <code>HttpMethod</code> which represents the request
* @return the headers as a string
*/
private String getOnlyCookieFromHeaders(HttpRequest method) {
String cookieHeader= getFromHeadersMatchingPredicate(method, ONLY_COOKIE).trim();
if(!cookieHeader.isEmpty()) {
return cookieHeader.substring((HTTPConstants.HEADER_COOKIE_IN_REQUEST).length(), cookieHeader.length()).trim();
}
return "";
}
/**
* Get only cookies from request headers for the <code>HttpRequest</code>
*
* @param method
* <code>HttpMethod</code> which represents the request
* @return the headers as a string
*/
private String getFromHeadersMatchingPredicate(HttpRequest method, Predicate<String> predicate) {
if(method != null) {
// Get all the request headers
StringBuilder hdrs = new StringBuilder(150);
Header[] requestHeaders = method.getAllHeaders();
for (Header requestHeader : requestHeaders) {
// Get header if it matches predicate
if (predicate.test(requestHeader.getName())) {
writeHeader(hdrs, requestHeader);
}
}
return hdrs.toString();
}
return ""; ////$NON-NLS-1$
}
// Helper class so we can generate request data without dumping entire file contents
private static class ViewableFileBody extends FileBody {
private boolean hideFileData;
public ViewableFileBody(File file, ContentType contentType) {
super(file, contentType);
hideFileData = false;
}
@Override
public void writeTo(final OutputStream out) throws IOException {
if (hideFileData) {
out.write("<actual file content, not shown here>".getBytes());// encoding does not really matter here
} else {
super.writeTo(out);
}
}
}
/**
* @param entityEnclosingRequest {@link HttpEntityEnclosingRequestBase}
* @return String body sent if computable
* @throws IOException if sending the data fails due to I/O
*/
protected String setupHttpEntityEnclosingRequestData(HttpEntityEnclosingRequestBase entityEnclosingRequest) throws IOException {
// Buffer to hold the post body, except file content
StringBuilder postedBody = new StringBuilder(1000);
HTTPFileArg[] files = getHTTPFiles();
final String contentEncoding = getContentEncodingOrNull();
final boolean haveContentEncoding = contentEncoding != null;
// Check if we should do a multipart/form-data or an
// application/x-www-form-urlencoded post request
if(getUseMultipart()) {
// If a content encoding is specified, we use that as the
// encoding of any parameter values
Charset charset;
if(haveContentEncoding) {
charset = Charset.forName(contentEncoding);
} else {
charset = MIME.DEFAULT_CHARSET;
}
if(log.isDebugEnabled()) {
log.debug("Building multipart with:getDoBrowserCompatibleMultipart(): {}, with charset:{}, haveContentEncoding:{}",
getDoBrowserCompatibleMultipart(), charset, haveContentEncoding);
}
// Write the request to our own stream
MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
if(getDoBrowserCompatibleMultipart()) {
multipartEntityBuilder.setLaxMode();
} else {
multipartEntityBuilder.setStrictMode();
}
// Create the parts
// Add any parameters
for (JMeterProperty jMeterProperty : getArguments()) {
HTTPArgument arg = (HTTPArgument) jMeterProperty.getObjectValue();
String parameterName = arg.getName();
if (arg.isSkippable(parameterName)) {
continue;
}
StringBody stringBody = new StringBody(arg.getValue(), ContentType.create(arg.getContentType(), charset));
FormBodyPart formPart = FormBodyPartBuilder.create(
parameterName, stringBody).build();
multipartEntityBuilder.addPart(formPart);
}
// Add any files
// Cannot retrieve parts once added to the MultiPartEntity, so have to save them here.
ViewableFileBody[] fileBodies = new ViewableFileBody[files.length];
for (int i=0; i < files.length; i++) {
HTTPFileArg file = files[i];
File reservedFile = FileServer.getFileServer().getResolvedFile(file.getPath());
fileBodies[i] = new ViewableFileBody(reservedFile, ContentType.create(file.getMimeType()));
multipartEntityBuilder.addPart(file.getParamName(), fileBodies[i] );
}
HttpEntity entity = multipartEntityBuilder.build();
entityEnclosingRequest.setEntity(entity);
writeEntityToSB(postedBody, entity, fileBodies, contentEncoding);
} else { // not multipart
// Check if the header manager had a content type header
// This allows the user to specify his own content-type for a POST request
Header contentTypeHeader = entityEnclosingRequest.getFirstHeader(HTTPConstants.HEADER_CONTENT_TYPE);
boolean hasContentTypeHeader = contentTypeHeader != null && contentTypeHeader.getValue() != null && contentTypeHeader.getValue().length() > 0;
// If there are no arguments, we can send a file as the body of the request
// TODO: needs a multiple file upload scenerio
if(!hasArguments() && getSendFileAsPostBody()) {
// If getSendFileAsPostBody returned true, it's sure that file is not null
HTTPFileArg file = files[0];
if(!hasContentTypeHeader) {
// Allow the mimetype of the file to control the content type
if(file.getMimeType() != null && file.getMimeType().length() > 0) {
entityEnclosingRequest.setHeader(HTTPConstants.HEADER_CONTENT_TYPE, file.getMimeType());
}
else if(ADD_CONTENT_TYPE_TO_POST_IF_MISSING) {
entityEnclosingRequest.setHeader(HTTPConstants.HEADER_CONTENT_TYPE, HTTPConstants.APPLICATION_X_WWW_FORM_URLENCODED);
}
}
FileEntity fileRequestEntity = new FileEntity(FileServer.getFileServer().getResolvedFile(file.getPath()), (ContentType) null);
entityEnclosingRequest.setEntity(fileRequestEntity);
// We just add placeholder text for file content
postedBody.append("<actual file content, not shown here>");
} else {
// In a post request which is not multipart, we only support
// parameters, no file upload is allowed
// If none of the arguments have a name specified, we
// just send all the values as the post body
if(getSendParameterValuesAsPostBody()) {
// Allow the mimetype of the file to control the content type
// This is not obvious in GUI if you are not uploading any files,
// but just sending the content of nameless parameters
// TODO: needs a multiple file upload scenario
if(!hasContentTypeHeader) {
HTTPFileArg file = files.length > 0? files[0] : null;
if(file != null && file.getMimeType() != null && file.getMimeType().length() > 0) {
entityEnclosingRequest.setHeader(HTTPConstants.HEADER_CONTENT_TYPE, file.getMimeType());
}
else if(ADD_CONTENT_TYPE_TO_POST_IF_MISSING) {
entityEnclosingRequest.setHeader(HTTPConstants.HEADER_CONTENT_TYPE, HTTPConstants.APPLICATION_X_WWW_FORM_URLENCODED);
}
}
// Just append all the parameter values, and use that as the post body
StringBuilder postBody = new StringBuilder();
for (JMeterProperty jMeterProperty : getArguments()) {
HTTPArgument arg = (HTTPArgument) jMeterProperty.getObjectValue();
// Note: if "Encoded?" is not selected, arg.getEncodedValue is equivalent to arg.getValue
if (haveContentEncoding) {
postBody.append(arg.getEncodedValue(contentEncoding));
} else {
postBody.append(arg.getEncodedValue());
}
}
// Let StringEntity perform the encoding
StringEntity requestEntity = new StringEntity(postBody.toString(), contentEncoding);
entityEnclosingRequest.setEntity(requestEntity);
postedBody.append(postBody.toString());
} else {
// It is a normal post request, with parameter names and values
// Set the content type
if(!hasContentTypeHeader && ADD_CONTENT_TYPE_TO_POST_IF_MISSING) {
entityEnclosingRequest.setHeader(HTTPConstants.HEADER_CONTENT_TYPE, HTTPConstants.APPLICATION_X_WWW_FORM_URLENCODED);
}
String urlContentEncoding = contentEncoding;
UrlEncodedFormEntity entity = createUrlEncodedFormEntity(urlContentEncoding);
entityEnclosingRequest.setEntity(entity);
writeEntityToSB(postedBody, entity, EMPTY_FILE_BODIES, contentEncoding);
}
}
}
return postedBody.toString();
}
/**
* @param postedBody
* @param entity
* @param fileBodies Array of {@link ViewableFileBody}
* @param contentEncoding
* @throws IOException
* @throws UnsupportedEncodingException
*/
private void writeEntityToSB(final StringBuilder postedBody, final HttpEntity entity,
final ViewableFileBody[] fileBodies, final String contentEncoding)
throws IOException {
if (entity.isRepeatable()){
ByteArrayOutputStream bos = new ByteArrayOutputStream();
for(ViewableFileBody fileBody : fileBodies){
fileBody.hideFileData = true;
}
entity.writeTo(bos);
for(ViewableFileBody fileBody : fileBodies){
fileBody.hideFileData = false;
}
bos.flush();
// We get the posted bytes using the encoding used to create it
postedBody.append(bos.toString(
contentEncoding == null ? SampleResult.DEFAULT_HTTP_ENCODING
: contentEncoding));
bos.close();
} else {
postedBody.append("<Entity was not repeatable, cannot view what was sent>"); // $NON-NLS-1$
}
}
/**
* Creates the entity data to be sent.
* <p>
* If there is a file entry with a non-empty MIME type we use that to
* set the request Content-Type header, otherwise we default to whatever
* header is present from a Header Manager.
* <p>
* If the content charset {@link #getContentEncoding()} is null or empty
* we use the HC4 default provided by {@link HTTP#DEF_CONTENT_CHARSET} which is
* ISO-8859-1.
*
* @param entity to be processed, e.g. PUT or PATCH
* @return the entity content, may be empty
* @throws UnsupportedEncodingException for invalid charset name
* @throws IOException cannot really occur for ByteArrayOutputStream methods
*/
protected String sendEntityData( HttpEntityEnclosingRequestBase entity) throws IOException {
boolean hasEntityBody = false;
final HTTPFileArg[] files = getHTTPFiles();
// Allow the mimetype of the file to control the content type
// This is not obvious in GUI if you are not uploading any files,
// but just sending the content of nameless parameters
final HTTPFileArg file = files.length > 0? files[0] : null;
String contentTypeValue;
if(file != null && file.getMimeType() != null && file.getMimeType().length() > 0) {
contentTypeValue = file.getMimeType();
entity.setHeader(HEADER_CONTENT_TYPE, contentTypeValue); // we provide the MIME type here
}
// Check for local contentEncoding (charset) override; fall back to default for content body
// we do this here rather so we can use the same charset to retrieve the data
final String charset = getContentEncoding(HTTP.DEF_CONTENT_CHARSET.name());
// Only create this if we are overriding whatever default there may be
// If there are no arguments, we can send a file as the body of the request
if(!hasArguments() && getSendFileAsPostBody()) {
hasEntityBody = true;
// If getSendFileAsPostBody returned true, it's sure that file is not null
File reservedFile = FileServer.getFileServer().getResolvedFile(files[0].getPath());
FileEntity fileRequestEntity = new FileEntity(reservedFile); // no need for content-type here
entity.setEntity(fileRequestEntity);
}
// If none of the arguments have a name specified, we
// just send all the values as the entity body
else if(getSendParameterValuesAsPostBody()) {
hasEntityBody = true;
// Just append all the parameter values, and use that as the entity body
Arguments arguments = getArguments();
StringBuilder entityBodyContent = new StringBuilder(arguments.getArgumentCount()*15);
for (JMeterProperty jMeterProperty : arguments) {
HTTPArgument arg = (HTTPArgument) jMeterProperty.getObjectValue();
// Note: if "Encoded?" is not selected, arg.getEncodedValue is equivalent to arg.getValue
if (charset != null) {
entityBodyContent.append(arg.getEncodedValue(charset));
} else {
entityBodyContent.append(arg.getEncodedValue());
}
}
StringEntity requestEntity = new StringEntity(entityBodyContent.toString(), charset);
entity.setEntity(requestEntity);
} else if (hasArguments()) {
hasEntityBody = true;
entity.setEntity(createUrlEncodedFormEntity(getContentEncodingOrNull()));
}
// Check if we have any content to send for body
if(hasEntityBody) {
// If the request entity is repeatable, we can send it first to
// our own stream, so we can return it
final HttpEntity entityEntry = entity.getEntity();
// Buffer to hold the entity body
StringBuilder entityBody = new StringBuilder(65);
writeEntityToSB(entityBody, entityEntry, EMPTY_FILE_BODIES, charset);
return entityBody.toString();
}
return ""; // may be the empty string
}
/**
* Create UrlEncodedFormEntity from parameters
* @param contentEncoding Content encoding may be null or empty
* @return {@link UrlEncodedFormEntity}
* @throws UnsupportedEncodingException
*/
private UrlEncodedFormEntity createUrlEncodedFormEntity(final String contentEncoding) throws UnsupportedEncodingException {
// It is a normal request, with parameter names and values
// Add the parameters
PropertyIterator args = getArguments().iterator();
List<NameValuePair> nvps = new ArrayList<>();
String urlContentEncoding = contentEncoding;
if (urlContentEncoding == null || urlContentEncoding.length() == 0) {
// Use the default encoding for urls
urlContentEncoding = EncoderCache.URL_ARGUMENT_ENCODING;
}
while (args.hasNext()) {
HTTPArgument arg = (HTTPArgument) args.next().getObjectValue();
// The HTTPClient always urlencodes both name and value,
// so if the argument is already encoded, we have to decode
// it before adding it to the post request
String parameterName = arg.getName();
if (arg.isSkippable(parameterName)) {
continue;
}
String parameterValue = arg.getValue();
if (!arg.isAlwaysEncoded()) {
// The value is already encoded by the user
// Must decode the value now, so that when the
// httpclient encodes it, we end up with the same value
// as the user had entered.
parameterName = URLDecoder.decode(parameterName, urlContentEncoding);
parameterValue = URLDecoder.decode(parameterValue, urlContentEncoding);
}
// Add the parameter, httpclient will urlencode it
nvps.add(new BasicNameValuePair(parameterName, parameterValue));
}
return new UrlEncodedFormEntity(nvps, urlContentEncoding);
}
/**
*
* @return the value of {@link #getContentEncoding()}; forced to null if empty
*/
private String getContentEncodingOrNull() {
return getContentEncoding(null);
}
/**
* @param dflt the default to be used
* @return the value of {@link #getContentEncoding()}; default if null or empty
*/
private String getContentEncoding(String dflt) {
String ce = getContentEncoding();
if (isNullOrEmptyTrimmed(ce)) {
return dflt;
} else {
return ce;
}
}
private void saveConnectionCookies(HttpResponse method, URL u, CookieManager cookieManager) {
if (cookieManager != null) {
Header[] hdrs = method.getHeaders(HTTPConstants.HEADER_SET_COOKIE);
for (Header hdr : hdrs) {
cookieManager.addCookieFromHeader(hdr.getValue(),u);
}
}
}
@Override
protected void notifyFirstSampleAfterLoopRestart() {
log.debug("notifyFirstSampleAfterLoopRestart called "
+ "with config(httpclient.reset_state_on_thread_group_iteration={})",
RESET_STATE_ON_THREAD_GROUP_ITERATION);
resetStateOnThreadGroupIteration.set(RESET_STATE_ON_THREAD_GROUP_ITERATION);
}
@Override
protected void threadFinished() {
log.debug("Thread Finished");
closeThreadLocalConnections();
}
/**
*
*/
private void closeThreadLocalConnections() {
// Does not need to be synchronised, as all access is from same thread
Map<HttpClientKey, MutableTriple<CloseableHttpClient, AuthState, PoolingHttpClientConnectionManager>>
mapHttpClientPerHttpClientKey = HTTPCLIENTS_CACHE_PER_THREAD_AND_HTTPCLIENTKEY.get();
if (mapHttpClientPerHttpClientKey != null ) {
for (MutableTriple<CloseableHttpClient, AuthState, PoolingHttpClientConnectionManager> triple : mapHttpClientPerHttpClientKey.values() ) {
JOrphanUtils.closeQuietly(triple.getLeft());
JOrphanUtils.closeQuietly(triple.getRight());
}
mapHttpClientPerHttpClientKey.clear();
}
}
@Override
public boolean interrupt() {
HttpUriRequest request = currentRequest;
if (request != null) {
currentRequest = null; // don't try twice
try {
request.abort();
} catch (UnsupportedOperationException e) {
log.warn("Could not abort pending request", e);
}
}
return request != null;
}
}
| Line too long
Make checkstyle -- and me -- happy.
Relates to #397
Bugzilla Id: 62672
git-svn-id: 5ccfe34f605a6c2f9041ff2965ab60012c62539a@1859858 13f79535-47bb-0310-9956-ffa450edef68
| src/protocol/http/org/apache/jmeter/protocol/http/sampler/HTTPHC4Impl.java | Line too long | <ide><path>rc/protocol/http/org/apache/jmeter/protocol/http/sampler/HTTPHC4Impl.java
<ide> }
<ide> }
<ide>
<del> private CloseableHttpClient setupClient(HttpClientKey key, JMeterVariables jMeterVariables, HttpClientContext clientContext) throws GeneralSecurityException {
<add> private CloseableHttpClient setupClient(HttpClientKey key, JMeterVariables jMeterVariables,
<add> HttpClientContext clientContext) throws GeneralSecurityException {
<ide> Map<HttpClientKey, MutableTriple<CloseableHttpClient, AuthState, PoolingHttpClientConnectionManager>> mapHttpClientPerHttpClientKey =
<ide> HTTPCLIENTS_CACHE_PER_THREAD_AND_HTTPCLIENTKEY.get();
<ide> clientContext.setAttribute(CONTEXT_ATTRIBUTE_CLIENT_KEY, key); |
|
JavaScript | apache-2.0 | 3312d8532d10aab419b96314688b6f7bad700e0a | 0 | stayup-io/kibana-cf_authentication | var Bell = require('bell');
var AuthCookie = require('hapi-auth-cookie');
var Promise = require('bluebird');
var request = Promise.promisify(require('request'));
module.exports = function (kibana) {
return new kibana.Plugin({
/*
This will set the name of the plugin and will be used by the server for
namespacing purposes in the configuration. In Hapi you can expose methods and
objects to the system via `server.expose()`. Access to these attributes are done
via `server.plugins.<name>.<attribute>`. See the `elasticsearch` plugin for an
example of how this is done. If you omit this attribute then the plugin loader
will try to set it to the name of the parent folder.
*/
name: 'authentication',
/*
This is an array of plugin names this plugin depends on. These are guaranteed
to load before the init() method for this plugin is executed.
*/
require: [],
/*
This method is executed to create a Joi schema for the plugin.
The Joi module is passed to every config method and config methods can return promises
if they need to execute an async operation before setting the defaults. If you're
returning a promise then you should resolve the promise with the Joi schema.
*/
config: function (Joi) {
var client_id = (process.env.KIBANA_OAUTH2_CLIENT_ID) ? process.env.KIBANA_OAUTH2_CLIENT_ID : 'client_id';
var client_secret = (process.env.KIBANA_OAUTH2_CLIENT_SECRET) ? process.env.KIBANA_OAUTH2_CLIENT_SECRET : 'client_secret';
var skip_ssl_validation = (process.env.SKIP_SSL_VALIDATION) ? (process.env.SKIP_SSL_VALIDATION.toLowerCase() === 'true') : false;
var cloudFoundryApiUri = (process.env.CF_API_URI) ? process.env.CF_API_URI.replace(/\/$/, '') : 'unknown';
var cfInfoUri = cloudFoundryApiUri + '/v2/info';
if (skip_ssl_validation) {
process.env.NODE_TLS_REJECT_UNAUTHORIZED = '0';
}
//Fetch location of login server, then set config
return request(cfInfoUri).spread(function (response, body) {
var cf_info = JSON.parse(body);
return Joi.object({
enabled: Joi.boolean().default(true),
client_id: Joi.string().default(client_id),
client_secret: Joi.string().default(client_secret),
skip_ssl_validation: Joi.boolean().default(skip_ssl_validation),
authorization_uri: Joi.string().default(cf_info.authorization_endpoint + '/oauth/authorize'),
logout_uri: Joi.string().default(cf_info.authorization_endpoint + '/logout.do'),
token_uri: Joi.string().default(cf_info.token_endpoint + '/oauth/token'),
account_info_uri: Joi.string().default(cf_info.token_endpoint + '/userinfo'),
}).default();
}).catch(function (error) {
console.log('ERROR fetching CF info from ' + cfInfoUri + ' : ' + error);
throw error;
});
},
/*
The init method is where all the magic happens. It's essentially the same as the
register method for a Hapi plugin except it uses promises instead of a callback
pattern. Just return a promise when you execute an async operation.
*/
init: function (server, options) {
var config = server.config();
server.log(['debug', 'authentication'], JSON.stringify(config.get('authentication')));
server.register([Bell, AuthCookie], function (err) {
if (err) {
server.log(['error', 'authentication'], JSON.stringify(err));
return;
}
server.auth.strategy('uaa-cookie', 'cookie', {
password: '397hkjhdhshs3uy02hjsdfnlskdfio3', //Password used for encryption
cookie: 'uaa-auth', // Name of cookie to set
redirectTo: '/login'
});
var uaaProvider = {
protocol: 'oauth2',
auth: config.get('authentication.authorization_uri'),
token: config.get('authentication.token_uri'),
scope: ['openid', 'oauth.approvals', 'scim.userids', 'cloud_controller.read'],
profile: function (credentials, params, get, callback) {
server.log(['debug', 'authentication'], JSON.stringify({ thecredentials: credentials, theparams: params }));
get(config.get('authentication.account_info_uri'), null, function (profile) {
server.log(['debug', 'authentication'], JSON.stringify({ theprofile: profile }));
credentials.profile = {
id: profile.id,
username: profile.username,
displayName: profile.name,
email: profile.email,
raw: profile
};
return callback();
});
}
};
server.auth.strategy('uaa-oauth', 'bell', {
provider: uaaProvider,
password: '397hkjhdhshs3uy02hjsdfnlskdfio3', //Password used for encryption
clientId: config.get('authentication.client_id'),
clientSecret: config.get('authentication.client_secret'),
forceHttps: true
});
server.auth.default('uaa-cookie');
server.route([{
method: 'GET',
path: '/login',
config: {
auth: 'uaa-oauth',
handler: function (request, reply) {
if (request.auth.isAuthenticated) {
request.auth.session.set(request.auth.credentials);
return reply.redirect('/');
}
reply('Not logged in...').code(401);
}
}
}, {
method: 'GET',
path: '/account',
config: {
handler: function (request, reply) {
reply(request.auth.credentials.profile);
}
}
}, {
method: 'GET',
path: '/logout',
config: {
auth: false,
handler: function (request, reply) {
request.auth.session.clear();
reply.redirect(config.get('authentication.logout_uri'));
}
}
}
]);
}); // end: server.register
}
});
};
| index.js | var Bell = require('bell');
var AuthCookie = require('hapi-auth-cookie');
var Promise = require('bluebird');
var request = Promise.promisify(require('request'));
module.exports = function (kibana) {
return new kibana.Plugin({
/*
This will set the name of the plugin and will be used by the server for
namespacing purposes in the configuration. In Hapi you can expose methods and
objects to the system via `server.expose()`. Access to these attributes are done
via `server.plugins.<name>.<attribute>`. See the `elasticsearch` plugin for an
example of how this is done. If you omit this attribute then the plugin loader
will try to set it to the name of the parent folder.
*/
name: 'authentication',
/*
This is an array of plugin names this plugin depends on. These are guaranteed
to load before the init() method for this plugin is executed.
*/
require: [],
/*
This method is executed to create a Joi schema for the plugin.
The Joi module is passed to every config method and config methods can return promises
if they need to execute an async operation before setting the defaults. If you're
returning a promise then you should resolve the promise with the Joi schema.
*/
config: function (Joi) {
var client_id = (process.env.KIBANA_OAUTH2_CLIENT_ID) ? process.env.KIBANA_OAUTH2_CLIENT_ID : 'client_id';
var client_secret = (process.env.KIBANA_OAUTH2_CLIENT_SECRET) ? process.env.KIBANA_OAUTH2_CLIENT_SECRET : 'client_secret';
var client_scope = (process.env.KIBANA_OAUTH_CLIENT_SCOPE) ? process.env.KIBANA_OAUTH_CLIENT_SCOPE : '';
var skip_ssl_validation = (process.env.SKIP_SSL_VALIDATION) ? (process.env.SKIP_SSL_VALIDATION.toLowerCase() === 'true') : false;
var cloudFoundryApiUri = (process.env.CF_API_URI) ? process.env.CF_API_URI.replace(/\/$/, '') : 'unknown';
var cfInfoUri = cloudFoundryApiUri + '/v2/info';
if (skip_ssl_validation) {
process.env.NODE_TLS_REJECT_UNAUTHORIZED = '0';
}
//Fetch location of login server, then set config
return request(cfInfoUri).spread(function (response, body) {
var cf_info = JSON.parse(body);
return Joi.object({
enabled: Joi.boolean().default(true),
client_id: Joi.string().default(client_id),
client_secret: Joi.string().default(client_secret),
skip_ssl_validation: Joi.boolean().default(skip_ssl_validation),
authorization_uri: Joi.string().default(cf_info.authorization_endpoint + '/oauth/authorize'),
logout_uri: Joi.string().default(cf_info.authorization_endpoint + '/logout.do'),
token_uri: Joi.string().default(cf_info.token_endpoint + '/oauth/token'),
account_info_uri: Joi.string().default(cf_info.token_endpoint + '/userinfo'),
}).default();
}).catch(function (error) {
console.log('ERROR fetching CF info from ' + cfInfoUri + ' : ' + error);
throw error;
});
},
/*
The init method is where all the magic happens. It's essentially the same as the
register method for a Hapi plugin except it uses promises instead of a callback
pattern. Just return a promise when you execute an async operation.
*/
init: function (server, options) {
var config = server.config();
server.log(['debug', 'authentication'], JSON.stringify(config.get('authentication')));
server.register([Bell, AuthCookie], function (err) {
if (err) {
server.log(['error', 'authentication'], JSON.stringify(err));
return;
}
server.auth.strategy('uaa-cookie', 'cookie', {
password: '397hkjhdhshs3uy02hjsdfnlskdfio3', //Password used for encryption
cookie: 'uaa-auth', // Name of cookie to set
redirectTo: '/login'
});
var uaaProvider = {
protocol: 'oauth2',
auth: config.get('authentication.authorization_uri'),
token: config.get('authentication.token_uri'),
scope: ['openid', 'oauth.approvals', 'scim.userids', 'cloud_controller.read'],
profile: function (credentials, params, get, callback) {
server.log(['debug', 'authentication'], JSON.stringify({ thecredentials: credentials, theparams: params }));
get(config.get('authentication.account_info_uri'), null, function (profile) {
server.log(['debug', 'authentication'], JSON.stringify({ theprofile: profile }));
credentials.profile = {
id: profile.id,
username: profile.username,
displayName: profile.name,
email: profile.email,
raw: profile
};
return callback();
});
}
};
server.auth.strategy('uaa-oauth', 'bell', {
provider: uaaProvider,
password: '397hkjhdhshs3uy02hjsdfnlskdfio3', //Password used for encryption
clientId: config.get('authentication.client_id'),
clientSecret: config.get('authentication.client_secret'),
forceHttps: true
});
server.auth.default('uaa-cookie');
server.route([{
method: 'GET',
path: '/login',
config: {
auth: 'uaa-oauth',
handler: function (request, reply) {
if (request.auth.isAuthenticated) {
request.auth.session.set(request.auth.credentials);
return reply.redirect('/');
}
reply('Not logged in...').code(401);
}
}
}, {
method: 'GET',
path: '/account',
config: {
handler: function (request, reply) {
reply(request.auth.credentials.profile);
}
}
}, {
method: 'GET',
path: '/logout',
config: {
auth: false,
handler: function (request, reply) {
request.auth.session.clear();
reply.redirect(config.get('authentication.logout_uri'));
}
}
}
]);
}); // end: server.register
}
});
};
| remove unneeded configuration option
[#112138459]
| index.js | remove unneeded configuration option | <ide><path>ndex.js
<ide> config: function (Joi) {
<ide> var client_id = (process.env.KIBANA_OAUTH2_CLIENT_ID) ? process.env.KIBANA_OAUTH2_CLIENT_ID : 'client_id';
<ide> var client_secret = (process.env.KIBANA_OAUTH2_CLIENT_SECRET) ? process.env.KIBANA_OAUTH2_CLIENT_SECRET : 'client_secret';
<del> var client_scope = (process.env.KIBANA_OAUTH_CLIENT_SCOPE) ? process.env.KIBANA_OAUTH_CLIENT_SCOPE : '';
<ide> var skip_ssl_validation = (process.env.SKIP_SSL_VALIDATION) ? (process.env.SKIP_SSL_VALIDATION.toLowerCase() === 'true') : false;
<ide> var cloudFoundryApiUri = (process.env.CF_API_URI) ? process.env.CF_API_URI.replace(/\/$/, '') : 'unknown';
<ide> var cfInfoUri = cloudFoundryApiUri + '/v2/info'; |
|
Java | mit | 23a4c4a842b1b5f293f27f8114e0e6f7729bfc4e | 0 | teinvdlugt/GameOfLife,teinvdlugt/GameOfLife | package com.teinproductions.tein.gameoflife;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.Build;
import android.preference.PreferenceManager;
import android.support.annotation.ColorInt;
import android.support.annotation.ColorRes;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import com.teinproductions.tein.gameoflife.files.Life;
import java.util.ArrayList;
import java.util.List;
public class ViewOfLife extends View {
private float cellWidth = 50;
private float startX = 0, startY = 0;
private int minGridCellWidth = 15;
private long speed = 50;
private float defaultCellWidth = 50;
/**
* 0: x position
* 1: y position
* 2: alive [0|1]
* 3: num of neighbours
*/
private List<short[]> cells = new ArrayList<>();
private final Object lock = new Object();
private Paint gridPaint, cellPaint;
private List<short[]> gen0 = new ArrayList<>();
private boolean running;
private int touchMode = TOUCH_MODE_MOVE;
public static final int TOUCH_MODE_ADD = 0;
public static final int TOUCH_MODE_REMOVE = 1;
public static final int TOUCH_MODE_MOVE = 2;
@Override
protected void onDraw(Canvas canvas) {
int width = getWidth(), height = getHeight();
int firstVerLine = (int) (cellWidth * (Math.ceil(startX) - startX));
int firstHorLine = (int) (cellWidth * (Math.ceil(startY) - startY));
// DRAW CELLS
short xStart = (short) Math.floor(startX);
short xEnd = (short) (xStart + width / cellWidth + 1);
short yStart = (short) Math.floor(startY);
short yEnd = (short) (yStart + height / cellWidth + 1);
synchronized (lock) {
for (short[] cell : cells) {
if (cell[2] == 1 && cell[0] >= xStart && cell[0] <= xEnd &&
cell[1] >= yStart && cell[1] <= yEnd) {
float left = (cell[0] - startX) * cellWidth;
float top = (cell[1] - startY) * cellWidth;
canvas.drawRect(left, top, left + cellWidth, top + cellWidth, cellPaint);
}
}
}
// DRAW GRID
if (cellWidth >= minGridCellWidth) {
// Vertical grid lines
for (float x = firstVerLine; x < width; x += cellWidth) {
canvas.drawLine(x, 0, x, height, gridPaint);
}
// Horizontal grid lines
for (float y = firstHorLine; y < height; y += cellWidth) {
canvas.drawLine(0, y, width, y, gridPaint);
}
}
}
private boolean isAlive(short x, short y) {
for (short[] cell : cells)
if (cell[0] == x && cell[1] == y) {
return cell[2] == 1;
}
return false;
}
private float prevXDrag1 = -1, prevYDrag1 = -1;
private float prevXDrag2 = -1, prevYDrag2 = -1;
private int zoomPointerId1 = -1, zoomPointerId2 = -1;
@Override
public boolean onTouchEvent(MotionEvent event) {
float x = event.getX() / cellWidth + startX;
float y = event.getY() / cellWidth + startY;
switch (event.getActionMasked()) {
case MotionEvent.ACTION_DOWN:
switch (touchMode) {
case TOUCH_MODE_ADD:
synchronized (lock) {
makeAlive((short) Math.floor(x), (short) Math.floor(y));
}
invalidate();
return true;
case TOUCH_MODE_REMOVE:
synchronized (lock) {
makeDead((short) Math.floor(x), (short) Math.floor(y));
}
invalidate();
return true;
case TOUCH_MODE_MOVE:
prevXDrag1 = event.getX();
prevYDrag1 = event.getY();
zoomPointerId1 = event.getPointerId(0);
invalidate();
return true;
default:
return false;
}
case MotionEvent.ACTION_POINTER_DOWN:
if (touchMode != TOUCH_MODE_MOVE) return false;
if (zoomPointerId2 != -1) return false;
zoomPointerId2 = event.getPointerId(event.getActionIndex());
int index = event.getActionIndex();
prevXDrag2 = event.getX(index);
prevYDrag2 = event.getY(index);
case MotionEvent.ACTION_MOVE:
switch (touchMode) {
case TOUCH_MODE_ADD:
synchronized (lock) {
makeAlive((short) Math.floor(x), (short) Math.floor(y));
}
invalidate();
return true;
case TOUCH_MODE_REMOVE:
synchronized (lock) {
makeDead((short) Math.floor(x), (short) Math.floor(y));
}
invalidate();
return true;
case TOUCH_MODE_MOVE:
if (event.getPointerCount() == 1) {
startX -= x - (prevXDrag1 / cellWidth + startX);
startY -= y - (prevYDrag1 / cellWidth + startY);
prevXDrag1 = event.getX();
prevYDrag1 = event.getY();
} else {
int indexCurrent = event.getActionIndex();
int index1 = event.findPointerIndex(zoomPointerId1);
int index2 = event.findPointerIndex(zoomPointerId2);
if ((indexCurrent != index1 && indexCurrent != index2) || zoomPointerId1 == -1 ||
zoomPointerId2 == -1 || prevXDrag1 == -1 || prevYDrag1 == -1 ||
prevXDrag2 == -1 || prevYDrag2 == -1) return false;
double xDist1 = prevXDrag2 - prevXDrag1;
double yDist1 = prevYDrag2 - prevYDrag1;
double dist1Sqr = xDist1 * xDist1 + yDist1 * yDist1;
double centerPointX1 = (prevXDrag1 + prevXDrag2) / 2d;
double centerPointY1 = (prevYDrag1 + prevYDrag2) / 2d;
double centerPointX1Cell = centerPointX1 / cellWidth + startX;
double centerPointY1Cell = centerPointY1 / cellWidth + startY;
prevXDrag1 = event.getX(index1);
prevYDrag1 = event.getY(index1);
prevXDrag2 = event.getX(index2);
prevYDrag2 = event.getY(index2);
// Change cellWidth
double xDist2 = prevXDrag2 - prevXDrag1;
double yDist2 = prevYDrag2 - prevYDrag1;
double dist2Sqr = xDist2 * xDist2 + yDist2 * yDist2;
cellWidth *= Math.sqrt(dist2Sqr / dist1Sqr);
// Change startX and startY
double centerPointX2 = (prevXDrag1 + prevXDrag2) / 2d;
double centerPointY2 = (prevYDrag1 + prevYDrag2) / 2d;
// The cell at grid-position (centerPointX1Cell, centerPointY1Cell) has to
// move to pixel-position (centerPointX2, centerPointY2)
//
// Written out version:
// double cellsLeft = centerPointX2 / cellWidth;
// startX = (float) (centerPointX1Cell - cellsLeft);
startX = (float) (centerPointX1Cell - centerPointX2 / cellWidth);
startY = (float) (centerPointY1Cell - centerPointY2 / cellWidth);
}
invalidate();
return true;
default:
return false;
}
case MotionEvent.ACTION_UP:
switch (touchMode) {
case TOUCH_MODE_ADD:
synchronized (lock) {
makeAlive((short) Math.floor(x), (short) Math.floor(y));
updateGen0();
}
invalidate();
return true;
case TOUCH_MODE_REMOVE:
synchronized (lock) {
makeDead((short) Math.floor(x), (short) Math.floor(y));
updateGen0();
}
invalidate();
return true;
case TOUCH_MODE_MOVE:
prevXDrag1 = prevXDrag2 = prevYDrag1 = prevYDrag2 =
zoomPointerId2 = zoomPointerId1 = -1;
default:
return false;
}
case MotionEvent.ACTION_POINTER_UP:
if (touchMode != TOUCH_MODE_MOVE) return false;
int pointerIndex = event.getActionIndex();
if (pointerIndex == event.findPointerIndex(zoomPointerId1)) {
// Transfer the data of pointer 2 to pointer 1,
zoomPointerId1 = zoomPointerId2;
prevXDrag1 = prevXDrag2;
prevYDrag1 = prevYDrag2;
// Get rid of pointer 2
zoomPointerId2 = -1;
prevXDrag2 = prevYDrag2 = -1;
Log.d("hi", "onTouchEvent: pointerId 1");
} else if (pointerIndex == event.findPointerIndex(zoomPointerId2)) {
zoomPointerId2 = -1;
prevXDrag2 = prevYDrag2 = -1;
Log.d("hi", "onTouchEvent: pointerId 2");
} else return false;
return true;
default:
return false;
}
}
/**
* Make the cell at the specified location alive, if it
* isn't already, and increment the number of neighbours of its
* neighbours.
*
* @param x X position of the cell in the grid
* @param y Y position of the cell in the grid
*/
private void makeAlive(short x, short y) {
for (short[] cell : cells) {
if (cell[0] == x && cell[1] == y) {
if (cell[2] == 0) {
cell[2] = 1;
notifyNeighbours(x, y, (byte) 1);
}
return;
}
}
// Cell not yet in array
cells.add(new short[]{x, y, 1, neighbours(x, y)});
notifyNeighbours(x, y, (byte) 1);
}
private void makeDead(short x, short y) {
for (int i = 0; i < cells.size(); i++) {
short[] cell = cells.get(i);
if (cell[0] == x && cell[1] == y) {
if (cell[2] == 1) {
cell[2] = 0;
if (cell[3] == 0) {
cells.remove(i);
}
notifyNeighbours(x, y, (byte) -1);
}
return;
}
}
}
/**
* Example: if the cell at position x, y became alive,
* its neighbours have to be notified (position 3 in their short[]
* has to be incremented by one).
*
* @param x X position of cell whose neighbours have to be notified
* @param y Y position of cell whose neighbours have to be notified
* @param toAdd Should be either 1 of -1; dependant on whether the cell at x, y
* became alive of died.
*/
private void notifyNeighbours(short x, short y, byte toAdd) {
incrementNeighbours((short) (x - 1), (short) (y - 1), toAdd);
incrementNeighbours(x, (short) (y - 1), toAdd);
incrementNeighbours((short) (x + 1), (short) (y - 1), toAdd);
incrementNeighbours((short) (x - 1), y, toAdd);
incrementNeighbours((short) (x + 1), y, toAdd);
incrementNeighbours((short) (x - 1), (short) (y + 1), toAdd);
incrementNeighbours(x, (short) (y + 1), toAdd);
incrementNeighbours((short) (x + 1), (short) (y + 1), toAdd);
}
/**
* Increment the number of neighbours of the cell on a specified location
* in the grid by a specified amount. If the cell isn't present yet in the
* {@code List<short[]> cells}, it will be added.
*
* @param x X position of cell in Game of Life grid
* @param y Y position of cell in Game of Life grid
* @param toAdd Amount of neighbours to add
*/
private void incrementNeighbours(short x, short y, byte toAdd) {
for (int i = 0; i < cells.size(); i++) {
short[] cell = cells.get(i);
if (cell[0] == x && cell[1] == y) {
cell[3] += toAdd;
if (cell[3] == 0 && cell[2] == 0)
cells.remove(i);
return;
}
}
// Cell not yet in array
cells.add(new short[]{x, y, 0, toAdd > 0 ? toAdd : 0});
}
private byte neighbours(short x, short y) {
byte neighbours = 0;
for (short[] cell : cells) {
if (cell[2] == 1 && (cell[0] == x - 1 || cell[0] == x || cell[0] == x + 1) &&
(cell[1] == y - 1 || cell[1] == y | cell[1] == y + 1) &&
!(cell[0] == x && cell[1] == y))
neighbours++;
}
return neighbours;
}
public void nextGeneration() {
synchronized (lock) {
List<short[]> cellsBackup = clone(cells);
for (int i = 0; i < cellsBackup.size(); i++) {
short[] cell = cellsBackup.get(i);
if (cell[2] == 0 && cell[3] == 3) {
makeAlive(cell[0], cell[1]);
} else if (cell[2] == 1 && (cell[3] < 2 || cell[3] > 3)) {
makeDead(cell[0], cell[1]);
}
}
}
}
private static List<short[]> clone(List<short[]> array) {
List<short[]> clone = new ArrayList<>();
for (short[] cell : array) {
clone.add(new short[]{
cell[0], cell[1], cell[2], cell[3]});
}
return clone;
}
public void start() {
running = true;
new Thread(new Runnable() {
@Override
public void run() {
while (running) {
long millis = System.currentTimeMillis();
nextGeneration();
postInvalidate();
long sleepTime = speed - System.currentTimeMillis() + millis;
if (sleepTime > 0) {
try {
Thread.sleep(sleepTime);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}).start();
}
public void stop() {
running = false;
}
public boolean isRunning() {
return running;
}
public int getTouchMode() {
return touchMode;
}
public void setTouchMode(int touchMode) {
if (!(touchMode == TOUCH_MODE_ADD || touchMode == TOUCH_MODE_REMOVE || touchMode == TOUCH_MODE_MOVE))
throw new IllegalArgumentException(
"Parameter touchMode must be one of TOUCH_MODE_ADD, TOUCH_MODE_REMOVE and TOUCH_MODE_MOVE");
this.touchMode = touchMode;
}
public int getMinGridCellWidth() {
return minGridCellWidth;
}
public void setMinGridCellWidth(int minGridCellWidth) {
this.minGridCellWidth = minGridCellWidth;
}
public float getDefaultCellWidth() {
return defaultCellWidth;
}
public void setDefaultCellWidth(float defaultCellWidth) {
this.defaultCellWidth = defaultCellWidth;
}
public long getSpeed() {
return speed;
}
public void setSpeed(long speed) {
this.speed = speed;
}
public void clear() {
synchronized (lock) {
cells.clear();
gen0.clear();
startX = startY = 0;
cellWidth = defaultCellWidth;
invalidate();
}
}
public void updateGen0() {
synchronized (lock) {
gen0 = clone(cells);
}
}
public void restoreGen0() {
if (gen0 != null) {
synchronized (lock) {
cells = clone(gen0);
invalidate();
}
}
}
public void load(Life life) {
running = false;
cells = life.getCells();
updateGen0();
startX = startY = 0;
invalidate();
}
public void setCellColor(@ColorInt int color) {
cellPaint.setColor(color);
}
public void setGridColor(@ColorInt int color) {
gridPaint.setColor(color);
}
public void init() {
gridPaint = new Paint();
gridPaint.setStyle(Paint.Style.STROKE);
cellPaint = new Paint();
cellPaint.setColor(MainActivity.getColor(getContext(), R.color.default_cell_color));
cellPaint.setStyle(Paint.Style.FILL);
}
public ViewOfLife(Context context) {
super(context);
init();
}
public ViewOfLife(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public ViewOfLife(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
}
}
| app/src/main/java/com/teinproductions/tein/gameoflife/ViewOfLife.java | package com.teinproductions.tein.gameoflife;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.Build;
import android.preference.PreferenceManager;
import android.support.annotation.ColorInt;
import android.support.annotation.ColorRes;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import com.teinproductions.tein.gameoflife.files.Life;
import java.util.ArrayList;
import java.util.List;
public class ViewOfLife extends View {
private float cellWidth = 50;
private float startX = 0, startY = 0;
private int minGridCellWidth = 15;
private long speed = 50;
private float defaultCellWidth = 50;
/**
* 0: x position
* 1: y position
* 2: alive [0|1]
* 3: num of neighbours
*/
private List<short[]> cells = new ArrayList<>();
private final Object lock = new Object();
private Paint gridPaint, cellPaint;
private List<short[]> gen0 = new ArrayList<>();
private boolean running;
private int touchMode = TOUCH_MODE_MOVE;
public static final int TOUCH_MODE_ADD = 0;
public static final int TOUCH_MODE_REMOVE = 1;
public static final int TOUCH_MODE_MOVE = 2;
@Override
protected void onDraw(Canvas canvas) {
int width = getWidth(), height = getHeight();
int firstVerLine = (int) (cellWidth * (Math.ceil(startX) - startX));
int firstHorLine = (int) (cellWidth * (Math.ceil(startY) - startY));
// DRAW CELLS
short xStart = (short) Math.floor(startX);
short xEnd = (short) (xStart + width / cellWidth + 1);
short yStart = (short) Math.floor(startY);
short yEnd = (short) (yStart + height / cellWidth + 1);
synchronized (lock) {
for (short[] cell : cells) {
if (cell[2] == 1 && cell[0] >= xStart && cell[0] <= xEnd &&
cell[1] >= yStart && cell[1] <= yEnd) {
float left = (cell[0] - startX) * cellWidth;
float top = (cell[1] - startY) * cellWidth;
canvas.drawRect(left, top, left + cellWidth, top + cellWidth, cellPaint);
}
}
}
// DRAW GRID
if (cellWidth >= minGridCellWidth) {
// Vertical grid lines
for (float x = firstVerLine; x < width; x += cellWidth) {
canvas.drawLine(x, 0, x, height, gridPaint);
}
// Horizontal grid lines
for (float y = firstHorLine; y < height; y += cellWidth) {
canvas.drawLine(0, y, width, y, gridPaint);
}
}
}
private boolean isAlive(short x, short y) {
for (short[] cell : cells)
if (cell[0] == x && cell[1] == y) {
return cell[2] == 1;
}
return false;
}
private float prevXDrag1 = -1, prevYDrag1 = -1;
private float prevXDrag2 = -1, prevYDrag2 = -1;
private int zoomPointerId1 = -1, zoomPointerId2 = -1;
@Override
public boolean onTouchEvent(MotionEvent event) {
float x = event.getX() / cellWidth + startX;
float y = event.getY() / cellWidth + startY;
switch (event.getActionMasked()) {
case MotionEvent.ACTION_DOWN:
switch (touchMode) {
case TOUCH_MODE_ADD:
synchronized (lock) {
makeAlive((short) Math.floor(x), (short) Math.floor(y));
}
invalidate();
return true;
case TOUCH_MODE_REMOVE:
synchronized (lock) {
makeDead((short) Math.floor(x), (short) Math.floor(y));
}
invalidate();
return true;
case TOUCH_MODE_MOVE:
prevXDrag1 = event.getX();
prevYDrag1 = event.getY();
zoomPointerId1 = event.getPointerId(0);
invalidate();
return true;
default:
return false;
}
case MotionEvent.ACTION_POINTER_DOWN:
if (touchMode != TOUCH_MODE_MOVE) return false;
if (zoomPointerId2 != -1) return false;
zoomPointerId2 = event.getPointerId(event.getActionIndex());
int index = event.getActionIndex();
prevXDrag2 = event.getX(index);
prevYDrag2 = event.getY(index);
case MotionEvent.ACTION_MOVE:
switch (touchMode) {
case TOUCH_MODE_ADD:
synchronized (lock) {
makeAlive((short) Math.floor(x), (short) Math.floor(y));
}
invalidate();
return true;
case TOUCH_MODE_REMOVE:
synchronized (lock) {
makeDead((short) Math.floor(x), (short) Math.floor(y));
}
invalidate();
return true;
case TOUCH_MODE_MOVE:
if (event.getPointerCount() == 1) {
startX -= x - (prevXDrag1 / cellWidth + startX);
startY -= y - (prevYDrag1 / cellWidth + startY);
prevXDrag1 = event.getX();
prevYDrag1 = event.getY();
} else {
int indexCurrent = event.getActionIndex();
int index1 = event.findPointerIndex(zoomPointerId1);
int index2 = event.findPointerIndex(zoomPointerId2);
if ((indexCurrent != index1 && indexCurrent != index2) || zoomPointerId1 == -1 ||
zoomPointerId2 == -1 || prevXDrag1 == -1 || prevYDrag1 == -1 ||
prevXDrag2 == -1 || prevYDrag2 == -1) return false;
double xDist1 = prevXDrag2 - prevXDrag1;
double yDist1 = prevYDrag2 - prevYDrag1;
double dist1Sqr = xDist1 * xDist1 + yDist1 * yDist1;
double centerPointX1 = (prevXDrag1 + prevXDrag2) / 2d;
double centerPointY1 = (prevYDrag1 + prevYDrag2) / 2d;
double centerPointX1Cell = centerPointX1 / cellWidth + startX;
double centerPointY1Cell = centerPointY1 / cellWidth + startY;
prevXDrag1 = event.getX(index1);
prevYDrag1 = event.getY(index1);
prevXDrag2 = event.getX(index2);
prevYDrag2 = event.getY(index2);
// Change cellWidth
double xDist2 = prevXDrag2 - prevXDrag1;
double yDist2 = prevYDrag2 - prevYDrag1;
double dist2Sqr = xDist2 * xDist2 + yDist2 * yDist2;
cellWidth *= Math.sqrt(dist2Sqr / dist1Sqr);
// Change startX and startY
double centerPointX2 = (prevXDrag1 + prevXDrag2) / 2d;
double centerPointY2 = (prevYDrag1 + prevYDrag2) / 2d;
// The cell at grid-position (centerPointX1Cell, centerPointY1Cell) has to
// move to pixel-position (centerPointX2, centerPointY2)
//
// Written out version:
// double cellsLeft = centerPointX2 / cellWidth;
// startX = (float) (centerPointX1Cell - cellsLeft);
startX = (float) (centerPointX1Cell - centerPointX2 / cellWidth);
startY = (float) (centerPointY1Cell - centerPointY2 / cellWidth);
}
invalidate();
return true;
default:
return false;
}
case MotionEvent.ACTION_UP:
switch (touchMode) {
case TOUCH_MODE_ADD:
synchronized (lock) {
makeAlive((short) Math.floor(x), (short) Math.floor(y));
updateGen0();
}
invalidate();
return true;
case TOUCH_MODE_REMOVE:
synchronized (lock) {
makeDead((short) Math.floor(x), (short) Math.floor(y));
updateGen0();
}
invalidate();
return true;
case TOUCH_MODE_MOVE:
prevXDrag1 = prevXDrag2 = prevYDrag1 = prevYDrag2 =
zoomPointerId2 = zoomPointerId1 = -1;
default:
return false;
}
case MotionEvent.ACTION_POINTER_UP:
if (touchMode != TOUCH_MODE_MOVE) return false;
int pointerIndex = event.getActionIndex();
if (pointerIndex == event.findPointerIndex(zoomPointerId1)) {
// Transfer the data of pointer 2 to pointer 1,
zoomPointerId1 = zoomPointerId2;
prevXDrag1 = prevXDrag2;
prevYDrag1 = prevYDrag2;
// Get rid of pointer 2
zoomPointerId2 = -1;
prevXDrag2 = prevYDrag2 = -1;
Log.d("hi", "onTouchEvent: pointerId 1");
} else if (pointerIndex == event.findPointerIndex(zoomPointerId2)) {
zoomPointerId2 = -1;
prevXDrag2 = prevYDrag2 = -1;
Log.d("hi", "onTouchEvent: pointerId 2");
} else return false;
return true;
default:
return false;
}
}
/**
* Make the cell at the specified location alive, if it
* isn't already, and increment the number of neighbours of its
* neighbours.
*
* @param x X position of the cell in the grid
* @param y Y position of the cell in the grid
*/
private void makeAlive(short x, short y) {
for (short[] cell : cells) {
if (cell[0] == x && cell[1] == y) {
if (cell[2] == 0) {
cell[2] = 1;
notifyNeighbours(x, y, (byte) 1);
}
return;
}
}
// Cell not yet in array
cells.add(new short[]{x, y, 1, neighbours(x, y)});
notifyNeighbours(x, y, (byte) 1);
}
private void makeDead(short x, short y) {
for (int i = 0; i < cells.size(); i++) {
short[] cell = cells.get(i);
if (cell[0] == x && cell[1] == y) {
if (cell[2] == 1) {
cell[2] = 0;
if (cell[3] == 0) {
cells.remove(i);
}
notifyNeighbours(x, y, (byte) -1);
}
return;
}
}
}
/**
* Example: if the cell at position x, y became alive,
* its neighbours have to be notified (position 3 in their short[]
* has to be incremented by one).
*
* @param x X position of cell whose neighbours have to be notified
* @param y Y position of cell whose neighbours have to be notified
* @param toAdd Should be either 1 of -1; dependant on whether the cell at x, y
* became alive of died.
*/
private void notifyNeighbours(short x, short y, byte toAdd) {
incrementNeighbours((short) (x - 1), (short) (y - 1), toAdd);
incrementNeighbours(x, (short) (y - 1), toAdd);
incrementNeighbours((short) (x + 1), (short) (y - 1), toAdd);
incrementNeighbours((short) (x - 1), y, toAdd);
incrementNeighbours((short) (x + 1), y, toAdd);
incrementNeighbours((short) (x - 1), (short) (y + 1), toAdd);
incrementNeighbours(x, (short) (y + 1), toAdd);
incrementNeighbours((short) (x + 1), (short) (y + 1), toAdd);
}
/**
* Increment the number of neighbours of the cell on a specified location
* in the grid by a specified amount. If the cell isn't present yet in the
* {@code List<short[]> cells}, it will be added.
*
* @param x X position of cell in Game of Life grid
* @param y Y position of cell in Game of Life grid
* @param toAdd Amount of neighbours to add
*/
private void incrementNeighbours(short x, short y, byte toAdd) {
for (int i = 0; i < cells.size(); i++) {
short[] cell = cells.get(i);
if (cell[0] == x && cell[1] == y) {
cell[3] += toAdd;
if (cell[3] == 0 && cell[2] == 0)
cells.remove(i);
return;
}
}
// Cell not yet in array
cells.add(new short[]{x, y, 0, toAdd > 0 ? toAdd : 0});
}
private byte neighbours(short x, short y) {
byte neighbours = 0;
for (short[] cell : cells) {
if (cell[2] == 1 && (cell[0] == x - 1 || cell[0] == x || cell[0] == x + 1) &&
(cell[1] == y - 1 || cell[1] == y | cell[1] == y + 1) &&
!(cell[0] == x && cell[1] == y))
neighbours++;
}
return neighbours;
}
public void nextGeneration() {
synchronized (lock) {
List<short[]> cellsBackup = clone(cells);
for (int i = 0; i < cellsBackup.size(); i++) {
short[] cell = cellsBackup.get(i);
if (cell[2] == 0 && cell[3] == 3) {
makeAlive(cell[0], cell[1]);
} else if (cell[2] == 1 && (cell[3] < 2 || cell[3] > 3)) {
makeDead(cell[0], cell[1]);
}
}
}
}
private static List<short[]> clone(List<short[]> array) {
List<short[]> clone = new ArrayList<>();
for (short[] cell : array) {
clone.add(new short[]{
cell[0], cell[1], cell[2], cell[3]});
}
return clone;
}
public void start() {
running = true;
new Thread(new Runnable() {
@Override
public void run() {
while (running) {
long millis = System.currentTimeMillis();
nextGeneration();
postInvalidate();
long sleepTime = speed - System.currentTimeMillis() + millis;
if (sleepTime > 0) {
try {
Thread.sleep(sleepTime);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}).start();
}
public void stop() {
running = false;
}
public boolean isRunning() {
return running;
}
public int getTouchMode() {
return touchMode;
}
public void setTouchMode(int touchMode) {
if (!(touchMode == TOUCH_MODE_ADD || touchMode == TOUCH_MODE_REMOVE || touchMode == TOUCH_MODE_MOVE))
throw new IllegalArgumentException(
"Parameter touchMode must be one of TOUCH_MODE_ADD, TOUCH_MODE_REMOVE and TOUCH_MODE_MOVE");
this.touchMode = touchMode;
}
public int getMinGridCellWidth() {
return minGridCellWidth;
}
public void setMinGridCellWidth(int minGridCellWidth) {
this.minGridCellWidth = minGridCellWidth;
}
public float getDefaultCellWidth() {
return defaultCellWidth;
}
public void setDefaultCellWidth(float defaultCellWidth) {
this.defaultCellWidth = defaultCellWidth;
}
public long getSpeed() {
return speed;
}
public void setSpeed(long speed) {
this.speed = speed;
}
public void clear() {
synchronized (lock) {
cells.clear();
gen0.clear();
startX = startY = 0;
cellWidth = defaultCellWidth;
invalidate();
}
}
public void updateGen0() {
synchronized (lock) {
gen0 = clone(cells);
}
}
public void restoreGen0() {
if (gen0 != null) {
synchronized (lock) {
cells = clone(gen0);
invalidate();
}
}
}
public void load(Life life) {
running = false;
cells = life.getCells();
/*checkCellsDocumented();
recountNeighbours();*/
updateGen0();
startX = startY = 0;
invalidate();
}
private void checkCellsDocumented() {
int numOfCells = cells.size();
for (int i = 0; i < numOfCells; i++) {
checkNeighboursDocumented(cells.get(i)[0], cells.get(i)[1]);
}
}
private void checkNeighboursDocumented(short x, short y) {
for (short[] neighbour : new short[][]{{(short) (x - 1), (short) (y - 1)}, {x, (short) (y - 1)},
{(short) (x + 1), (short) (y - 1)}, {(short) (x - 1), y}, {(short) (x + 1), y},
{(short) (x - 1), (short) (y + 1)}, {x, (short) (y + 1)}, {(short) (x + 1), (short) (y + 1)}}) {
checkCellDocumented(neighbour[0], neighbour[1]);
}
}
private void checkCellDocumented(short x, short y) {
for (short[] cell : cells) {
if (cell[0] == x && cell[1] == y) {
return;
}
}
cells.add(new short[]{x, y, 0, 0});
}
private void recountNeighbours() {
for (int i = 0; i < cells.size(); i++) {
short[] cell = cells.get(i);
cells.set(i, new short[]{cell[0], cell[1], cell[2], neighbours(cell[0], cell[1])});
}
}
public void setCellColor(@ColorInt int color) {
cellPaint.setColor(color);
}
public void setGridColor(@ColorInt int color) {
gridPaint.setColor(color);
}
public void init() {
gridPaint = new Paint();
gridPaint.setStyle(Paint.Style.STROKE);
cellPaint = new Paint();
cellPaint.setColor(MainActivity.getColor(getContext(), R.color.default_cell_color));
cellPaint.setStyle(Paint.Style.FILL);
}
public ViewOfLife(Context context) {
super(context);
init();
}
public ViewOfLife(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public ViewOfLife(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
}
}
| Remove redundant ViewOfLife methods
| app/src/main/java/com/teinproductions/tein/gameoflife/ViewOfLife.java | Remove redundant ViewOfLife methods | <ide><path>pp/src/main/java/com/teinproductions/tein/gameoflife/ViewOfLife.java
<ide> public void load(Life life) {
<ide> running = false;
<ide> cells = life.getCells();
<del> /*checkCellsDocumented();
<del> recountNeighbours();*/
<ide> updateGen0();
<ide> startX = startY = 0;
<ide> invalidate();
<ide> }
<ide>
<del> private void checkCellsDocumented() {
<del> int numOfCells = cells.size();
<del> for (int i = 0; i < numOfCells; i++) {
<del> checkNeighboursDocumented(cells.get(i)[0], cells.get(i)[1]);
<del> }
<del> }
<del>
<del> private void checkNeighboursDocumented(short x, short y) {
<del> for (short[] neighbour : new short[][]{{(short) (x - 1), (short) (y - 1)}, {x, (short) (y - 1)},
<del> {(short) (x + 1), (short) (y - 1)}, {(short) (x - 1), y}, {(short) (x + 1), y},
<del> {(short) (x - 1), (short) (y + 1)}, {x, (short) (y + 1)}, {(short) (x + 1), (short) (y + 1)}}) {
<del> checkCellDocumented(neighbour[0], neighbour[1]);
<del> }
<del> }
<del>
<del> private void checkCellDocumented(short x, short y) {
<del> for (short[] cell : cells) {
<del> if (cell[0] == x && cell[1] == y) {
<del> return;
<del> }
<del> }
<del>
<del> cells.add(new short[]{x, y, 0, 0});
<del> }
<del>
<del> private void recountNeighbours() {
<del> for (int i = 0; i < cells.size(); i++) {
<del> short[] cell = cells.get(i);
<del> cells.set(i, new short[]{cell[0], cell[1], cell[2], neighbours(cell[0], cell[1])});
<del> }
<del> }
<del>
<ide> public void setCellColor(@ColorInt int color) {
<ide> cellPaint.setColor(color);
<ide> } |
|
Java | apache-2.0 | bfa6666c304a8f5347fcb12b8d348d93596ac1b4 | 0 | kageiit/buck,JoelMarcey/buck,JoelMarcey/buck,zpao/buck,kageiit/buck,Addepar/buck,Addepar/buck,facebook/buck,kageiit/buck,zpao/buck,nguyentruongtho/buck,JoelMarcey/buck,facebook/buck,nguyentruongtho/buck,zpao/buck,nguyentruongtho/buck,Addepar/buck,kageiit/buck,Addepar/buck,nguyentruongtho/buck,nguyentruongtho/buck,facebook/buck,Addepar/buck,Addepar/buck,JoelMarcey/buck,facebook/buck,kageiit/buck,JoelMarcey/buck,zpao/buck,facebook/buck,JoelMarcey/buck,Addepar/buck,facebook/buck,JoelMarcey/buck,nguyentruongtho/buck,kageiit/buck,JoelMarcey/buck,Addepar/buck,zpao/buck,JoelMarcey/buck,Addepar/buck,Addepar/buck,Addepar/buck,JoelMarcey/buck,zpao/buck,facebook/buck,JoelMarcey/buck,nguyentruongtho/buck,JoelMarcey/buck,zpao/buck,kageiit/buck,Addepar/buck,Addepar/buck,JoelMarcey/buck | /*
* Copyright 2015-present Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License. You may obtain
* a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package com.facebook.buck.rules.keys;
import com.facebook.buck.core.rulekey.AddToRuleKey;
import com.facebook.buck.core.rulekey.AddsToRuleKey;
import com.facebook.buck.core.rulekey.ExcludeFromRuleKey;
import com.facebook.buck.core.rulekey.MissingExcludeReporter;
import com.facebook.buck.core.util.immutables.BuckStyleImmutable;
import com.facebook.buck.core.util.immutables.BuckStylePackageVisibleImmutable;
import com.facebook.buck.core.util.immutables.BuckStylePackageVisibleTuple;
import com.facebook.buck.core.util.immutables.BuckStyleTuple;
import com.google.common.base.Preconditions;
import com.google.common.cache.CacheLoader;
import com.google.common.collect.ImmutableCollection;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSortedMap;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.LinkedHashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
import java.util.stream.Stream;
class ReflectiveAlterKeyLoader extends CacheLoader<Class<?>, ImmutableCollection<AlterRuleKey>> {
private static final Comparator<ValueExtractor> COMPARATOR =
(o1, o2) -> {
String name1 = o1.getFullyQualifiedName();
String name2 = o2.getFullyQualifiedName();
return name1.compareTo(name2);
};
@Override
public ImmutableCollection<AlterRuleKey> load(Class<?> key) {
ImmutableList.Builder<AlterRuleKey> builder = ImmutableList.builder();
List<Class<?>> superClasses = new ArrayList<>();
// Collect the superclasses first so that they are added before interfaces. That seems more
// aesthetically pleasing to me.
for (Class<?> current = key; isBuckType(current); current = current.getSuperclass()) {
superClasses.add(current);
}
LinkedHashSet<Class<?>> superClassesAndInterfaces = new LinkedHashSet<>();
Queue<Class<?>> workQueue = new LinkedList<>(superClasses);
while (!workQueue.isEmpty()) {
Class<?> cls = workQueue.poll();
if (superClassesAndInterfaces.add(cls)) {
Stream.of(cls.getInterfaces()).filter(x -> isBuckType(x)).forEach(workQueue::add);
}
}
for (Class<?> current : superClassesAndInterfaces) {
ImmutableSortedMap.Builder<ValueExtractor, AlterRuleKey> sortedExtractors =
ImmutableSortedMap.orderedBy(COMPARATOR);
for (Field field : current.getDeclaredFields()) {
field.setAccessible(true);
AddToRuleKey annotation = field.getAnnotation(AddToRuleKey.class);
if (annotation != null) {
ValueExtractor valueExtractor = new FieldValueExtractor(field);
sortedExtractors.put(
valueExtractor, createAlterRuleKey(valueExtractor, annotation.stringify()));
} else {
ExcludeFromRuleKey excludeAnnotation = field.getAnnotation(ExcludeFromRuleKey.class);
if (excludeAnnotation != null) {
MissingExcludeReporter.reportExcludedField(key, field, excludeAnnotation);
} else {
MissingExcludeReporter.reportFieldMissingAnnotation(key, field);
}
}
}
for (Method method : current.getDeclaredMethods()) {
method.setAccessible(true);
AddToRuleKey annotation = method.getAnnotation(AddToRuleKey.class);
if (annotation != null) {
Preconditions.checkState(
hasImmutableAnnotation(current) && AddsToRuleKey.class.isAssignableFrom(current),
"AddToRuleKey can only be applied to methods of Immutables. It cannot be applied to %s.%s(...)",
current.getName(),
method.getName());
ValueExtractor valueExtractor = new ValueMethodValueExtractor(method);
sortedExtractors.put(
valueExtractor, createAlterRuleKey(valueExtractor, annotation.stringify()));
}
// For methods, we're unable here to determine whether we expect that a method should or
// shouldn't have an annotation.
}
builder.addAll(sortedExtractors.build().values());
}
return builder.build();
}
private static boolean isBuckType(Class<?> current) {
return current.getName().startsWith("com.facebook.buck.");
}
private boolean hasImmutableAnnotation(Class<?> current) {
// Value.Immutable only has CLASS retention, so we need to detect this based on our own
// annotations.
return current.getAnnotation(BuckStyleImmutable.class) != null
|| current.getAnnotation(BuckStylePackageVisibleImmutable.class) != null
|| current.getAnnotation(BuckStylePackageVisibleTuple.class) != null
|| current.getAnnotation(BuckStyleTuple.class) != null;
}
private AlterRuleKey createAlterRuleKey(ValueExtractor valueExtractor, boolean stringify) {
if (stringify) {
return new StringifyAlterRuleKey(valueExtractor);
} else {
return new DefaultAlterRuleKey(valueExtractor);
}
}
}
| src/com/facebook/buck/rules/keys/ReflectiveAlterKeyLoader.java | /*
* Copyright 2015-present Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License. You may obtain
* a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package com.facebook.buck.rules.keys;
import com.facebook.buck.core.rulekey.AddToRuleKey;
import com.facebook.buck.core.rulekey.AddsToRuleKey;
import com.facebook.buck.core.rulekey.ExcludeFromRuleKey;
import com.facebook.buck.core.rulekey.MissingExcludeReporter;
import com.facebook.buck.core.util.immutables.BuckStyleImmutable;
import com.facebook.buck.core.util.immutables.BuckStylePackageVisibleImmutable;
import com.facebook.buck.core.util.immutables.BuckStylePackageVisibleTuple;
import com.facebook.buck.core.util.immutables.BuckStyleTuple;
import com.google.common.base.Preconditions;
import com.google.common.cache.CacheLoader;
import com.google.common.collect.ImmutableCollection;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSortedMap;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.LinkedHashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
import java.util.stream.Collectors;
import java.util.stream.Stream;
class ReflectiveAlterKeyLoader extends CacheLoader<Class<?>, ImmutableCollection<AlterRuleKey>> {
private static final Comparator<ValueExtractor> COMPARATOR =
(o1, o2) -> {
String name1 = o1.getFullyQualifiedName();
String name2 = o2.getFullyQualifiedName();
return name1.compareTo(name2);
};
@Override
public ImmutableCollection<AlterRuleKey> load(Class<?> key) {
ImmutableList.Builder<AlterRuleKey> builder = ImmutableList.builder();
List<Class<?>> superClasses = new ArrayList<>();
// Collect the superclasses first so that they are added before interfaces. That seems more
// aesthetically pleasing to me.
for (Class<?> current = key; isBuckType(current); current = current.getSuperclass()) {
superClasses.add(current);
}
LinkedHashSet<Class<?>> superClassesAndInterfaces = new LinkedHashSet<>();
Queue<Class<?>> workQueue = new LinkedList<>(superClasses);
while (!workQueue.isEmpty()) {
Class<?> cls = workQueue.poll();
if (superClassesAndInterfaces.add(cls)) {
workQueue.addAll(
Stream.of(cls.getInterfaces()).filter(x -> isBuckType(x)).collect(Collectors.toList()));
}
}
for (Class<?> current : superClassesAndInterfaces) {
ImmutableSortedMap.Builder<ValueExtractor, AlterRuleKey> sortedExtractors =
ImmutableSortedMap.orderedBy(COMPARATOR);
for (Field field : current.getDeclaredFields()) {
field.setAccessible(true);
AddToRuleKey annotation = field.getAnnotation(AddToRuleKey.class);
if (annotation != null) {
ValueExtractor valueExtractor = new FieldValueExtractor(field);
sortedExtractors.put(
valueExtractor, createAlterRuleKey(valueExtractor, annotation.stringify()));
} else {
ExcludeFromRuleKey excludeAnnotation = field.getAnnotation(ExcludeFromRuleKey.class);
if (excludeAnnotation != null) {
MissingExcludeReporter.reportExcludedField(key, field, excludeAnnotation);
} else {
MissingExcludeReporter.reportFieldMissingAnnotation(key, field);
}
}
}
for (Method method : current.getDeclaredMethods()) {
method.setAccessible(true);
AddToRuleKey annotation = method.getAnnotation(AddToRuleKey.class);
if (annotation != null) {
Preconditions.checkState(
hasImmutableAnnotation(current) && AddsToRuleKey.class.isAssignableFrom(current),
"AddToRuleKey can only be applied to methods of Immutables. It cannot be applied to %s.%s(...)",
current.getName(),
method.getName());
ValueExtractor valueExtractor = new ValueMethodValueExtractor(method);
sortedExtractors.put(
valueExtractor, createAlterRuleKey(valueExtractor, annotation.stringify()));
}
// For methods, we're unable here to determine whether we expect that a method should or
// shouldn't have an annotation.
}
builder.addAll(sortedExtractors.build().values());
}
return builder.build();
}
private static boolean isBuckType(Class<?> current) {
return current.getName().startsWith("com.facebook.buck.");
}
private boolean hasImmutableAnnotation(Class<?> current) {
// Value.Immutable only has CLASS retention, so we need to detect this based on our own
// annotations.
return current.getAnnotation(BuckStyleImmutable.class) != null
|| current.getAnnotation(BuckStylePackageVisibleImmutable.class) != null
|| current.getAnnotation(BuckStylePackageVisibleTuple.class) != null
|| current.getAnnotation(BuckStyleTuple.class) != null;
}
private AlterRuleKey createAlterRuleKey(ValueExtractor valueExtractor, boolean stringify) {
if (stringify) {
return new StringifyAlterRuleKey(valueExtractor);
} else {
return new DefaultAlterRuleKey(valueExtractor);
}
}
}
| Do not create a list when loading class interfaces in ReflectiveAlterKeyLoader
Summary: No need to collect in a list
Reviewed By: jtorkkola
shipit-source-id: 101b7176ec
| src/com/facebook/buck/rules/keys/ReflectiveAlterKeyLoader.java | Do not create a list when loading class interfaces in ReflectiveAlterKeyLoader | <ide><path>rc/com/facebook/buck/rules/keys/ReflectiveAlterKeyLoader.java
<ide> import java.util.LinkedList;
<ide> import java.util.List;
<ide> import java.util.Queue;
<del>import java.util.stream.Collectors;
<ide> import java.util.stream.Stream;
<ide>
<ide> class ReflectiveAlterKeyLoader extends CacheLoader<Class<?>, ImmutableCollection<AlterRuleKey>> {
<ide> while (!workQueue.isEmpty()) {
<ide> Class<?> cls = workQueue.poll();
<ide> if (superClassesAndInterfaces.add(cls)) {
<del> workQueue.addAll(
<del> Stream.of(cls.getInterfaces()).filter(x -> isBuckType(x)).collect(Collectors.toList()));
<add> Stream.of(cls.getInterfaces()).filter(x -> isBuckType(x)).forEach(workQueue::add);
<ide> }
<ide> }
<ide> |
|
Java | agpl-3.0 | 30f1bad2c6617ed93af2bda42e8a11c60c5a108c | 0 | jvalue/cep-service | package org.jvalue.ceps.data;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.google.inject.Inject;
import com.google.inject.name.Named;
import org.jvalue.ceps.api.data.OdsRegistration;
import org.jvalue.ceps.db.OdsRegistrationRepository;
import org.jvalue.ceps.main.ConfigModule;
import org.jvalue.ceps.rest.RestModule;
import org.jvalue.ceps.utils.Assert;
import org.jvalue.ceps.utils.Log;
import org.jvalue.ods.api.DataSourceApi;
import org.jvalue.ods.api.NotificationApi;
import org.jvalue.ods.api.notifications.ClientDescription;
import org.jvalue.ods.api.notifications.HttpClient;
import org.jvalue.ods.api.notifications.HttpClientDescription;
import org.jvalue.ods.api.sources.DataSource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import io.dropwizard.lifecycle.Managed;
import retrofit.RetrofitError;
public final class DataManager implements Managed, DataSink {
// Name of this HTTP client on the ODS. Might need more dynamic approach in the future.
private static final String ODS_CLIENT_ID = "ceps";
private final DataSourceApi odsDataSourceApi;
private final NotificationApi odsNotificationApi;
private final OdsRegistrationRepository registrationRepository;
private final DataUpdateListener dataListener;
private final String cepsDataCallbackUrl;
@Inject
DataManager(
DataSourceApi odsDataSourceApi,
NotificationApi odsNotificationApi,
OdsRegistrationRepository registrationRepository,
DataUpdateListener dataListener,
@Named(ConfigModule.CEPS_BASE_URL) String cepsBaseUrl,
@Named(RestModule.URL_DATA) String dataUrl) {
this.odsDataSourceApi = odsDataSourceApi;
this.odsNotificationApi = odsNotificationApi;
this.registrationRepository = registrationRepository;
this.dataListener = dataListener;
this.cepsDataCallbackUrl = cepsBaseUrl + dataUrl;
}
public OdsRegistration startMonitoring(String sourceId) {
Assert.assertNotNull(sourceId);
if (isBeingMonitored(sourceId)) throw new IllegalStateException("source already being monitored");
// get source / schema
DataSource source = odsDataSourceApi.getSource(sourceId);
// register for updates
ClientDescription clientDescription = new HttpClientDescription(cepsDataCallbackUrl, true);
HttpClient client = (HttpClient) odsNotificationApi.registerClient(sourceId, ODS_CLIENT_ID, clientDescription);
// store result in db
OdsRegistration registration = new OdsRegistration(sourceId, source, client);
registrationRepository.add(registration);
// notify listener
dataListener.onSourceAdded(sourceId, source.getSchema());
return registration;
}
public void stopMonitoring(String sourceId) {
Assert.assertNotNull(sourceId);
OdsRegistration registration = getRegistrationForSourceId(sourceId);
if (registration == null) throw new IllegalStateException("source not being monitored");
try {
odsNotificationApi.unregisterClient(sourceId, registration.getClient().getId());
} catch (RetrofitError re) {
Log.error("failed to unregister from ODS", re);
} finally {
registrationRepository.remove(registration);
dataListener.onSourceRemoved(sourceId, registration.getDataSource().getSchema());
}
}
public boolean isBeingMonitored(String sourceId) {
Assert.assertNotNull(sourceId);
return getRegistrationForSourceId(sourceId) != null;
}
public List<OdsRegistration> getAll() {
return registrationRepository.getAll();
}
public OdsRegistration get(String sourceId) {
return registrationRepository.findById(sourceId);
}
@Override
public void onNewData(String sourceId, ArrayNode data) {
Log.info("Source " + sourceId + " has new data (" + data.size() + " items)");
dataListener.onNewSourceData(sourceId, data);
}
private OdsRegistration getRegistrationForSourceId(String sourceId) {
for (OdsRegistration registration : registrationRepository.getAll()) {
if (registration.getDataSource().getId().equals(sourceId)) return registration;
}
return null;
}
@Override
public void start() {
Map<String, JsonNode> sources = new HashMap<>();
for (OdsRegistration registration : registrationRepository.getAll()) {
sources.put(registration.getDataSource().getId(), registration.getDataSource().getSchema());
}
dataListener.onRestoreSources(sources);
}
@Override
public void stop() {
// nothing to do
}
}
| server/src/main/java/org/jvalue/ceps/data/DataManager.java | package org.jvalue.ceps.data;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.google.inject.Inject;
import com.google.inject.name.Named;
import org.jvalue.ceps.api.data.OdsRegistration;
import org.jvalue.ceps.db.OdsRegistrationRepository;
import org.jvalue.ceps.main.ConfigModule;
import org.jvalue.ceps.rest.RestModule;
import org.jvalue.ceps.utils.Assert;
import org.jvalue.ceps.utils.Log;
import org.jvalue.ods.api.DataSourceApi;
import org.jvalue.ods.api.NotificationApi;
import org.jvalue.ods.api.notifications.ClientDescription;
import org.jvalue.ods.api.notifications.HttpClient;
import org.jvalue.ods.api.notifications.HttpClientDescription;
import org.jvalue.ods.api.sources.DataSource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import io.dropwizard.lifecycle.Managed;
public final class DataManager implements Managed, DataSink {
// Name of this HTTP client on the ODS. Might need more dynamic approach in the future.
private static final String ODS_CLIENT_ID = "ceps";
private final DataSourceApi odsDataSourceApi;
private final NotificationApi odsNotificationApi;
private final OdsRegistrationRepository registrationRepository;
private final DataUpdateListener dataListener;
private final String cepsDataCallbackUrl;
@Inject
DataManager(
DataSourceApi odsDataSourceApi,
NotificationApi odsNotificationApi,
OdsRegistrationRepository registrationRepository,
DataUpdateListener dataListener,
@Named(ConfigModule.CEPS_BASE_URL) String cepsBaseUrl,
@Named(RestModule.URL_DATA) String dataUrl) {
this.odsDataSourceApi = odsDataSourceApi;
this.odsNotificationApi = odsNotificationApi;
this.registrationRepository = registrationRepository;
this.dataListener = dataListener;
this.cepsDataCallbackUrl = cepsBaseUrl + dataUrl;
}
public OdsRegistration startMonitoring(String sourceId) {
Assert.assertNotNull(sourceId);
if (isBeingMonitored(sourceId)) throw new IllegalStateException("source already being monitored");
// get source / schema
DataSource source = odsDataSourceApi.getSource(sourceId);
// register for updates
ClientDescription clientDescription = new HttpClientDescription(cepsDataCallbackUrl, true);
HttpClient client = (HttpClient) odsNotificationApi.registerClient(sourceId, ODS_CLIENT_ID, clientDescription);
// store result in db
OdsRegistration registration = new OdsRegistration(sourceId, source, client);
registrationRepository.add(registration);
// notify listener
dataListener.onSourceAdded(sourceId, source.getSchema());
return registration;
}
public void stopMonitoring(String sourceId) {
Assert.assertNotNull(sourceId);
OdsRegistration registration = getRegistrationForSourceId(sourceId);
if (registration == null) throw new IllegalStateException("source not being monitored");
odsNotificationApi.unregisterClient(sourceId, registration.getClient().getId());
registrationRepository.remove(registration);
dataListener.onSourceRemoved(sourceId, registration.getDataSource().getSchema());
}
public boolean isBeingMonitored(String sourceId) {
Assert.assertNotNull(sourceId);
return getRegistrationForSourceId(sourceId) != null;
}
public List<OdsRegistration> getAll() {
return registrationRepository.getAll();
}
public OdsRegistration get(String sourceId) {
return registrationRepository.findById(sourceId);
}
@Override
public void onNewData(String sourceId, ArrayNode data) {
Log.info("Source " + sourceId + " has new data (" + data.size() + " items)");
dataListener.onNewSourceData(sourceId, data);
}
private OdsRegistration getRegistrationForSourceId(String sourceId) {
for (OdsRegistration registration : registrationRepository.getAll()) {
if (registration.getDataSource().getId().equals(sourceId)) return registration;
}
return null;
}
@Override
public void start() {
Map<String, JsonNode> sources = new HashMap<>();
for (OdsRegistration registration : registrationRepository.getAll()) {
sources.put(registration.getDataSource().getId(), registration.getDataSource().getSchema());
}
dataListener.onRestoreSources(sources);
}
@Override
public void stop() {
// nothing to do
}
}
| data: removing sources from DataManager catches ODS exceptions
| server/src/main/java/org/jvalue/ceps/data/DataManager.java | data: removing sources from DataManager catches ODS exceptions | <ide><path>erver/src/main/java/org/jvalue/ceps/data/DataManager.java
<ide> import java.util.Map;
<ide>
<ide> import io.dropwizard.lifecycle.Managed;
<add>import retrofit.RetrofitError;
<ide>
<ide>
<ide> public final class DataManager implements Managed, DataSink {
<ide> OdsRegistration registration = getRegistrationForSourceId(sourceId);
<ide> if (registration == null) throw new IllegalStateException("source not being monitored");
<ide>
<del> odsNotificationApi.unregisterClient(sourceId, registration.getClient().getId());
<del> registrationRepository.remove(registration);
<del> dataListener.onSourceRemoved(sourceId, registration.getDataSource().getSchema());
<add> try {
<add> odsNotificationApi.unregisterClient(sourceId, registration.getClient().getId());
<add> } catch (RetrofitError re) {
<add> Log.error("failed to unregister from ODS", re);
<add> } finally {
<add> registrationRepository.remove(registration);
<add> dataListener.onSourceRemoved(sourceId, registration.getDataSource().getSchema());
<add> }
<ide> }
<ide>
<ide> |
|
Java | apache-2.0 | ed905885597f5bf32514890b0f7b399a70e95a0f | 0 | allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community | // Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.ui.content.impl;
import com.intellij.icons.AllIcons;
import com.intellij.openapi.Disposable;
import com.intellij.openapi.actionSystem.ActionGroup;
import com.intellij.openapi.util.BusyObject;
import com.intellij.openapi.util.Computable;
import com.intellij.openapi.util.Disposer;
import com.intellij.openapi.util.UserDataHolderBase;
import com.intellij.ui.LayeredIcon;
import com.intellij.ui.content.AlertIcon;
import com.intellij.ui.content.Content;
import com.intellij.ui.content.ContentManager;
import com.intellij.util.IconUtil;
import com.intellij.util.ObjectUtils;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import java.awt.*;
import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeSupport;
public class ContentImpl extends UserDataHolderBase implements Content {
private String myDisplayName;
private String myDescription;
private JComponent myComponent;
private Icon myIcon;
private final PropertyChangeSupport myChangeSupport = new PropertyChangeSupport(this);
private ContentManager myManager;
private boolean myIsLocked;
private boolean myPinnable;
private Icon myLayeredIcon = new LayeredIcon(2);
private Disposable myDisposer;
private boolean myShouldDisposeContent = true;
private String myTabName;
private String myToolwindowTitle;
private boolean myCloseable = true;
private ActionGroup myActions;
private String myPlace;
private AlertIcon myAlertIcon;
private JComponent myActionsContextComponent;
private JComponent mySearchComponent;
private Computable<? extends JComponent> myFocusRequest;
private BusyObject myBusyObject;
private String mySeparator;
private Icon myPopupIcon;
private long myExecutionId;
private String myHelpId;
public ContentImpl(JComponent component, String displayName, boolean isPinnable) {
myComponent = component;
myDisplayName = displayName;
myPinnable = isPinnable;
}
@NotNull
@Override
public JComponent getComponent() {
return myComponent;
}
@Override
public void setComponent(JComponent component) {
Component oldComponent = myComponent;
myComponent = component;
myChangeSupport.firePropertyChange(PROP_COMPONENT, oldComponent, myComponent);
}
@Override
public JComponent getPreferredFocusableComponent() {
if (myFocusRequest != null) return myFocusRequest.compute();
if (myComponent == null) return null;
Container traversalRoot = myComponent.isFocusCycleRoot() ? myComponent : myComponent.getFocusCycleRootAncestor();
if (traversalRoot == null) return null;
return ObjectUtils.tryCast(traversalRoot.getFocusTraversalPolicy().getDefaultComponent(myComponent), JComponent.class);
}
@Override
public void setPreferredFocusableComponent(JComponent c) {
setPreferredFocusedComponent(() -> c);
}
@Override
public void setPreferredFocusedComponent(Computable<? extends JComponent> computable) {
myFocusRequest = computable;
}
@Override
public void setIcon(Icon icon) {
Icon oldValue = getIcon();
myIcon = icon;
myLayeredIcon = LayeredIcon.create(myIcon, AllIcons.Nodes.TabPin);
myChangeSupport.firePropertyChange(PROP_ICON, oldValue, getIcon());
}
@Override
public Icon getIcon() {
if (myIsLocked) {
return myIcon == null ? getEmptyPinIcon() : myLayeredIcon;
}
else {
return myIcon;
}
}
private static class IconHolder {
private static final Icon ourEmptyPinIcon;
static {
Icon icon = AllIcons.Nodes.TabPin;
int width = icon.getIconWidth();
ourEmptyPinIcon = IconUtil.cropIcon(icon, new Rectangle(width / 2, 0, width - width / 2, icon.getIconHeight()));
}
}
@NotNull
private static Icon getEmptyPinIcon() {
return IconHolder.ourEmptyPinIcon;
}
@Override
public void setDisplayName(String displayName) {
String oldValue = myDisplayName;
myDisplayName = displayName;
myChangeSupport.firePropertyChange(PROP_DISPLAY_NAME, oldValue, myDisplayName);
}
@Override
public String getDisplayName() {
return myDisplayName;
}
@Override
public void setTabName(String tabName) {
myTabName = tabName;
}
@Override
public String getTabName() {
if (myTabName != null) return myTabName;
return myDisplayName;
}
@Override
public void setToolwindowTitle(String toolwindowTitle) {
myToolwindowTitle = toolwindowTitle;
}
@Override
public String getToolwindowTitle() {
if (myToolwindowTitle != null) return myToolwindowTitle;
return myDisplayName;
}
@Override
public Disposable getDisposer() {
return myDisposer;
}
@Override
public void setDisposer(@NotNull Disposable disposer) {
myDisposer = disposer;
}
@Override
public void setShouldDisposeContent(boolean value) {
myShouldDisposeContent = value;
}
@Override
public boolean shouldDisposeContent() {
return myShouldDisposeContent;
}
@Override
public String getDescription() {
return myDescription;
}
@Override
public void setDescription(String description) {
String oldValue = myDescription;
myDescription = description;
myChangeSupport.firePropertyChange(PROP_DESCRIPTION, oldValue, myDescription);
}
@Override
public void addPropertyChangeListener(PropertyChangeListener l) {
myChangeSupport.addPropertyChangeListener(l);
}
@Override
public void removePropertyChangeListener(PropertyChangeListener l) {
myChangeSupport.removePropertyChangeListener(l);
}
public void setManager(@Nullable ContentManager manager) {
myManager = manager;
}
@Override
public ContentManager getManager() {
return myManager;
}
@Override
public boolean isSelected() {
return myManager != null && myManager.isSelected(this);
}
@Override
public final void release() {
Disposer.dispose(this);
}
@Override
public boolean isValid() {
return myManager != null;
}
@Override
public boolean isPinned() {
return myIsLocked;
}
@Override
public void setPinned(boolean locked) {
if (isPinnable()) {
Icon oldIcon = getIcon();
myIsLocked = locked;
Icon newIcon = getIcon();
myChangeSupport.firePropertyChange(PROP_ICON, oldIcon, newIcon);
}
}
@Override
public boolean isPinnable() {
return myPinnable;
}
@Override
public void setPinnable(boolean pinnable) {
myPinnable = pinnable;
}
@Override
public boolean isCloseable() {
return myCloseable;
}
@Override
public void setCloseable(final boolean closeable) {
if(closeable == myCloseable) return;
boolean old = myCloseable;
myCloseable = closeable;
myChangeSupport.firePropertyChange(IS_CLOSABLE, old, closeable);
}
@Override
public void setActions(final ActionGroup actions, String place, @Nullable JComponent contextComponent) {
final ActionGroup oldActions = myActions;
myActions = actions;
myPlace = place;
myActionsContextComponent = contextComponent;
myChangeSupport.firePropertyChange(PROP_ACTIONS, oldActions, myActions);
}
@Override
public JComponent getActionsContextComponent() {
return myActionsContextComponent;
}
@Override
public ActionGroup getActions() {
return myActions;
}
@Override
public String getPlace() {
return myPlace;
}
@Override
@NonNls
public String toString() {
StringBuilder sb = new StringBuilder("Content name=").append(myDisplayName);
if (myIsLocked)
sb.append(", pinned");
if (myExecutionId != 0)
sb.append(", executionId=").append(myExecutionId);
return sb.toString();
}
@Override
public void dispose() {
if (myShouldDisposeContent && myComponent instanceof Disposable) {
Disposer.dispose((Disposable)myComponent);
}
if (myDisposer != null) {
Disposer.dispose(myDisposer);
myDisposer = null;
}
myComponent = null;
myFocusRequest = null;
myManager = null;
clearUserData();
}
@Override
@Nullable
public AlertIcon getAlertIcon() {
return myAlertIcon;
}
@Override
public void setAlertIcon(@Nullable final AlertIcon icon) {
myAlertIcon = icon;
}
@Override
public void fireAlert() {
myChangeSupport.firePropertyChange(PROP_ALERT, null, true);
}
@Override
public void setBusyObject(BusyObject object) {
myBusyObject = object;
}
@Override
public String getSeparator() {
return mySeparator;
}
@Override
public void setSeparator(String separator) {
mySeparator = separator;
}
@Override
public void setPopupIcon(Icon icon) {
myPopupIcon = icon;
}
@Override
public Icon getPopupIcon() {
return myPopupIcon != null ? myPopupIcon : getIcon();
}
@Override
public BusyObject getBusyObject() {
return myBusyObject;
}
@Override
public void setSearchComponent(@Nullable final JComponent comp) {
mySearchComponent = comp;
}
@Override
public JComponent getSearchComponent() {
return mySearchComponent;
}
@Override
public void setExecutionId(long executionId) {
myExecutionId = executionId;
}
@Override
public long getExecutionId() {
return myExecutionId;
}
@Override
public void setHelpId(String helpId) {
myHelpId = helpId;
}
@Nullable
@Override
public String getHelpId() {
return myHelpId;
}
} | platform/platform-impl/src/com/intellij/ui/content/impl/ContentImpl.java | // Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.ui.content.impl;
import com.intellij.icons.AllIcons;
import com.intellij.openapi.Disposable;
import com.intellij.openapi.actionSystem.ActionGroup;
import com.intellij.openapi.util.BusyObject;
import com.intellij.openapi.util.Computable;
import com.intellij.openapi.util.Disposer;
import com.intellij.openapi.util.UserDataHolderBase;
import com.intellij.ui.LayeredIcon;
import com.intellij.ui.content.AlertIcon;
import com.intellij.ui.content.Content;
import com.intellij.ui.content.ContentManager;
import com.intellij.util.IconUtil;
import com.intellij.util.ObjectUtils;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import java.awt.*;
import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeSupport;
public class ContentImpl extends UserDataHolderBase implements Content {
private String myDisplayName;
private String myDescription;
private JComponent myComponent;
private Icon myIcon;
private final PropertyChangeSupport myChangeSupport = new PropertyChangeSupport(this);
private ContentManager myManager;
private boolean myIsLocked;
private boolean myPinnable;
private Icon myLayeredIcon = new LayeredIcon(2);
private Disposable myDisposer;
private boolean myShouldDisposeContent = true;
private String myTabName;
private String myToolwindowTitle;
private boolean myCloseable = true;
private ActionGroup myActions;
private String myPlace;
private AlertIcon myAlertIcon;
private JComponent myActionsContextComponent;
private JComponent mySearchComponent;
private Computable<? extends JComponent> myFocusRequest;
private BusyObject myBusyObject;
private String mySeparator;
private Icon myPopupIcon;
private long myExecutionId;
private String myHelpId;
public ContentImpl(JComponent component, String displayName, boolean isPinnable) {
myComponent = component;
myDisplayName = displayName;
myPinnable = isPinnable;
}
@NotNull
@Override
public JComponent getComponent() {
return myComponent;
}
@Override
public void setComponent(JComponent component) {
Component oldComponent = myComponent;
myComponent = component;
myChangeSupport.firePropertyChange(PROP_COMPONENT, oldComponent, myComponent);
}
@Override
public JComponent getPreferredFocusableComponent() {
if (myFocusRequest != null) return myFocusRequest.compute();
if (myComponent == null) return null;
Container traversalRoot = myComponent.isFocusCycleRoot() ? myComponent : myComponent.getFocusCycleRootAncestor();
if (traversalRoot == null) return null;
return ObjectUtils.tryCast(traversalRoot.getFocusTraversalPolicy().getDefaultComponent(myComponent), JComponent.class);
}
@Override
public void setPreferredFocusableComponent(JComponent c) {
setPreferredFocusedComponent(() -> c);
}
@Override
public void setPreferredFocusedComponent(Computable<? extends JComponent> computable) {
myFocusRequest = computable;
}
@Override
public void setIcon(Icon icon) {
Icon oldValue = getIcon();
myIcon = icon;
myLayeredIcon = LayeredIcon.create(myIcon, AllIcons.Nodes.TabPin);
myChangeSupport.firePropertyChange(PROP_ICON, oldValue, getIcon());
}
@Override
public Icon getIcon() {
if (myIsLocked) {
return myIcon == null ? getEmptyPinIcon() : myLayeredIcon;
}
else {
return myIcon;
}
}
private static class IconHolder {
private static final Icon ourEmptyPinIcon;
static {
Icon icon = AllIcons.Nodes.TabPin;
int width = icon.getIconWidth();
ourEmptyPinIcon = IconUtil.cropIcon(icon, new Rectangle(width / 2, 0, width - width / 2, icon.getIconHeight()));
}
}
@NotNull
private static Icon getEmptyPinIcon() {
return IconHolder.ourEmptyPinIcon;
}
@Override
public void setDisplayName(String displayName) {
String oldValue = myDisplayName;
myDisplayName = displayName;
myChangeSupport.firePropertyChange(PROP_DISPLAY_NAME, oldValue, myDisplayName);
}
@Override
public String getDisplayName() {
return myDisplayName;
}
@Override
public void setTabName(String tabName) {
myTabName = tabName;
}
@Override
public String getTabName() {
if (myTabName != null) return myTabName;
return myDisplayName;
}
@Override
public void setToolwindowTitle(String toolwindowTitle) {
myToolwindowTitle = toolwindowTitle;
}
@Override
public String getToolwindowTitle() {
if (myToolwindowTitle != null) return myToolwindowTitle;
return myDisplayName;
}
@Override
public Disposable getDisposer() {
return myDisposer;
}
@Override
public void setDisposer(@NotNull Disposable disposer) {
myDisposer = disposer;
}
@Override
public void setShouldDisposeContent(boolean value) {
myShouldDisposeContent = value;
}
@Override
public boolean shouldDisposeContent() {
return myShouldDisposeContent;
}
@Override
public String getDescription() {
return myDescription;
}
@Override
public void setDescription(String description) {
String oldValue = myDescription;
myDescription = description;
myChangeSupport.firePropertyChange(PROP_DESCRIPTION, oldValue, myDescription);
}
@Override
public void addPropertyChangeListener(PropertyChangeListener l) {
myChangeSupport.addPropertyChangeListener(l);
}
@Override
public void removePropertyChangeListener(PropertyChangeListener l) {
myChangeSupport.removePropertyChangeListener(l);
}
public void setManager(@Nullable ContentManager manager) {
myManager = manager;
}
@Override
public ContentManager getManager() {
return myManager;
}
@Override
public boolean isSelected() {
return myManager != null && myManager.isSelected(this);
}
@Override
public final void release() {
Disposer.dispose(this);
}
@Override
public boolean isValid() {
return myManager != null;
}
@Override
public boolean isPinned() {
return myIsLocked;
}
@Override
public void setPinned(boolean locked) {
if (isPinnable()) {
Icon oldIcon = getIcon();
myIsLocked = locked;
Icon newIcon = getIcon();
myChangeSupport.firePropertyChange(PROP_ICON, oldIcon, newIcon);
}
}
@Override
public boolean isPinnable() {
return myPinnable;
}
@Override
public void setPinnable(boolean pinnable) {
myPinnable = pinnable;
}
@Override
public boolean isCloseable() {
return myCloseable;
}
@Override
public void setCloseable(final boolean closeable) {
if(closeable == myCloseable) return;
boolean old = myCloseable;
myCloseable = closeable;
myChangeSupport.firePropertyChange(IS_CLOSABLE, old, closeable);
}
@Override
public void setActions(final ActionGroup actions, String place, @Nullable JComponent contextComponent) {
final ActionGroup oldActions = myActions;
myActions = actions;
myPlace = place;
myActionsContextComponent = contextComponent;
myChangeSupport.firePropertyChange(PROP_ACTIONS, oldActions, myActions);
}
@Override
public JComponent getActionsContextComponent() {
return myActionsContextComponent;
}
@Override
public ActionGroup getActions() {
return myActions;
}
@Override
public String getPlace() {
return myPlace;
}
@Override
@NonNls
public String toString() {
StringBuilder sb = new StringBuilder("Content name=").append(myDisplayName);
if (myIsLocked)
sb.append(", pinned");
if (myExecutionId != 0)
sb.append(", executionId=").append(myExecutionId);
return sb.toString();
}
@Override
public void dispose() {
if (myShouldDisposeContent && myComponent instanceof Disposable) {
Disposer.dispose((Disposable)myComponent);
}
myComponent = null;
myFocusRequest = null;
myManager = null;
clearUserData();
if (myDisposer != null) {
Disposer.dispose(myDisposer);
myDisposer = null;
}
}
@Override
@Nullable
public AlertIcon getAlertIcon() {
return myAlertIcon;
}
@Override
public void setAlertIcon(@Nullable final AlertIcon icon) {
myAlertIcon = icon;
}
@Override
public void fireAlert() {
myChangeSupport.firePropertyChange(PROP_ALERT, null, true);
}
@Override
public void setBusyObject(BusyObject object) {
myBusyObject = object;
}
@Override
public String getSeparator() {
return mySeparator;
}
@Override
public void setSeparator(String separator) {
mySeparator = separator;
}
@Override
public void setPopupIcon(Icon icon) {
myPopupIcon = icon;
}
@Override
public Icon getPopupIcon() {
return myPopupIcon != null ? myPopupIcon : getIcon();
}
@Override
public BusyObject getBusyObject() {
return myBusyObject;
}
@Override
public void setSearchComponent(@Nullable final JComponent comp) {
mySearchComponent = comp;
}
@Override
public JComponent getSearchComponent() {
return mySearchComponent;
}
@Override
public void setExecutionId(long executionId) {
myExecutionId = executionId;
}
@Override
public long getExecutionId() {
return myExecutionId;
}
@Override
public void setHelpId(String helpId) {
myHelpId = helpId;
}
@Nullable
@Override
public String getHelpId() {
return myHelpId;
}
} | CPP-18558 IllegalStateException when build immediately after Reload CMake
- make data available in dispose call (see `ContentManagerImpl.removeContent`)
- continuation of Vladimir Krivosheev 12-Dec-19 16:54 `cleanup`
- continuation of Alexey Utkin 23-Dec-19 16:53 ``[TEST FIX] Remove "Build" tab in tool windows on dispose` (null from `ContentImpl.getComponent`)
GitOrigin-RevId: 17aea752ba52fcc425d4425afa0606105e4fea9b | platform/platform-impl/src/com/intellij/ui/content/impl/ContentImpl.java | CPP-18558 IllegalStateException when build immediately after Reload CMake | <ide><path>latform/platform-impl/src/com/intellij/ui/content/impl/ContentImpl.java
<ide> Disposer.dispose((Disposable)myComponent);
<ide> }
<ide>
<add> if (myDisposer != null) {
<add> Disposer.dispose(myDisposer);
<add> myDisposer = null;
<add> }
<add>
<ide> myComponent = null;
<ide> myFocusRequest = null;
<ide> myManager = null;
<del>
<ide> clearUserData();
<del> if (myDisposer != null) {
<del> Disposer.dispose(myDisposer);
<del> myDisposer = null;
<del> }
<ide> }
<ide>
<ide> @Override |
|
Java | apache-2.0 | d299540efceda6dc39ec09e1efc50776d6c7b134 | 0 | noddi/druid,nishantmonu51/druid,winval/druid,dclim/druid,erikdubbelboer/druid,michaelschiff/druid,andy256/druid,dkhwangbo/druid,KurtYoung/druid,druid-io/druid,noddi/druid,rasahner/druid,du00cs/druid,mrijke/druid,rasahner/druid,lizhanhui/data_druid,dkhwangbo/druid,b-slim/druid,rasahner/druid,Fokko/druid,pdeva/druid,solimant/druid,knoguchi/druid,dkhwangbo/druid,mghosh4/druid,mghosh4/druid,pjain1/druid,pjain1/druid,solimant/druid,rasahner/druid,gianm/druid,zhihuij/druid,himanshug/druid,zxs/druid,lizhanhui/data_druid,du00cs/druid,monetate/druid,taochaoqiang/druid,Fokko/druid,dclim/druid,andy256/druid,praveev/druid,taochaoqiang/druid,mghosh4/druid,mghosh4/druid,andy256/druid,potto007/druid-avro,zhihuij/druid,erikdubbelboer/druid,potto007/druid-avro,redBorder/druid,zhihuij/druid,yaochitc/druid-dev,himanshug/druid,rasahner/druid,mrijke/druid,pjain1/druid,deltaprojects/druid,implydata/druid,tubemogul/druid,redBorder/druid,druid-io/druid,druid-io/druid,praveev/druid,deltaprojects/druid,Fokko/druid,Fokko/druid,dclim/druid,potto007/druid-avro,solimant/druid,du00cs/druid,leventov/druid,implydata/druid,liquidm/druid,monetate/druid,monetate/druid,zxs/druid,KurtYoung/druid,michaelschiff/druid,mrijke/druid,guobingkun/druid,pdeva/druid,knoguchi/druid,liquidm/druid,guobingkun/druid,gianm/druid,Fokko/druid,taochaoqiang/druid,KurtYoung/druid,zxs/druid,pjain1/druid,gianm/druid,lizhanhui/data_druid,knoguchi/druid,praveev/druid,druid-io/druid,KurtYoung/druid,metamx/druid,winval/druid,tubemogul/druid,himanshug/druid,redBorder/druid,metamx/druid,deltaprojects/druid,implydata/druid,solimant/druid,michaelschiff/druid,guobingkun/druid,yaochitc/druid-dev,jon-wei/druid,nishantmonu51/druid,monetate/druid,zhihuij/druid,zxs/druid,metamx/druid,tubemogul/druid,tubemogul/druid,winval/druid,michaelschiff/druid,b-slim/druid,winval/druid,pjain1/druid,knoguchi/druid,monetate/druid,pdeva/druid,monetate/druid,potto007/druid-avro,liquidm/druid,leventov/druid,yaochitc/druid-dev,mghosh4/druid,b-slim/druid,b-slim/druid,b-slim/druid,druid-io/druid,jon-wei/druid,zxs/druid,michaelschiff/druid,dclim/druid,mrijke/druid,gianm/druid,gianm/druid,praveev/druid,pdeva/druid,KurtYoung/druid,jon-wei/druid,deltaprojects/druid,Fokko/druid,leventov/druid,mghosh4/druid,nishantmonu51/druid,jon-wei/druid,mrijke/druid,nishantmonu51/druid,erikdubbelboer/druid,lizhanhui/data_druid,deltaprojects/druid,du00cs/druid,mghosh4/druid,deltaprojects/druid,noddi/druid,dkhwangbo/druid,noddi/druid,jon-wei/druid,pjain1/druid,michaelschiff/druid,himanshug/druid,implydata/druid,metamx/druid,pjain1/druid,gianm/druid,nishantmonu51/druid,guobingkun/druid,noddi/druid,jon-wei/druid,liquidm/druid,leventov/druid,monetate/druid,lizhanhui/data_druid,michaelschiff/druid,nishantmonu51/druid,gianm/druid,redBorder/druid,Fokko/druid,winval/druid,taochaoqiang/druid,yaochitc/druid-dev,potto007/druid-avro,du00cs/druid,metamx/druid,knoguchi/druid,praveev/druid,leventov/druid,himanshug/druid,nishantmonu51/druid,zhihuij/druid,andy256/druid,implydata/druid,guobingkun/druid,solimant/druid,taochaoqiang/druid,liquidm/druid,jon-wei/druid,redBorder/druid,dclim/druid,andy256/druid,pdeva/druid,dkhwangbo/druid,implydata/druid,tubemogul/druid,yaochitc/druid-dev,deltaprojects/druid,erikdubbelboer/druid,liquidm/druid,erikdubbelboer/druid | /*
* Licensed to Metamarkets Group Inc. (Metamarkets) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. Metamarkets licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package io.druid.indexing.common.task;
import com.google.common.base.Joiner;
import com.google.common.base.Predicate;
import com.google.common.base.Throwables;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Lists;
import com.google.inject.Injector;
import com.metamx.common.logger.Logger;
import io.druid.guice.ExtensionsConfig;
import io.druid.guice.GuiceInjectors;
import io.druid.indexing.common.TaskToolbox;
import io.druid.initialization.Initialization;
import javax.annotation.Nullable;
import java.io.File;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.MalformedURLException;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLClassLoader;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
public abstract class HadoopTask extends AbstractTask
{
private static final Logger log = new Logger(HadoopTask.class);
private static final ExtensionsConfig extensionsConfig;
final static Injector injector = GuiceInjectors.makeStartupInjector();
static {
extensionsConfig = injector.getInstance(ExtensionsConfig.class);
}
private final List<String> hadoopDependencyCoordinates;
protected HadoopTask(
String id,
String dataSource,
List<String> hadoopDependencyCoordinates,
Map<String, Object> context
)
{
super(id, dataSource, context);
this.hadoopDependencyCoordinates = hadoopDependencyCoordinates;
}
public List<String> getHadoopDependencyCoordinates()
{
return hadoopDependencyCoordinates == null ? null : ImmutableList.copyOf(hadoopDependencyCoordinates);
}
// This could stand to have a more robust detection methodology.
// Right now it just looks for `druid.*\.jar`
// This is only used for classpath isolation in the runTask isolation stuff, so it shooouuullldddd be ok.
protected static final Predicate<URL> IS_DRUID_URL = new Predicate<URL>()
{
@Override
public boolean apply(@Nullable URL input)
{
try {
if (input == null) {
return false;
}
final String fName = Paths.get(input.toURI()).getFileName().toString();
return fName.startsWith("druid") && fName.endsWith(".jar") && !fName.endsWith("selfcontained.jar");
}
catch (URISyntaxException e) {
throw Throwables.propagate(e);
}
}
};
/**
* This makes an isolated classloader that has classes loaded in the "proper" priority.
*
* This isolation is *only* for the part of the HadoopTask that calls runTask in an isolated manner.
*
* Jars for the job are the same jars as for the classloader EXCEPT the hadoopDependencyCoordinates, which are not used in the job jars.
*
* The URLs in the resultant classloader are loaded in this priority:
*
* 1. Non-Druid jars (see IS_DRUID_URL) found in the ClassLoader for HadoopIndexTask.class. This will probably be the ApplicationClassLoader
* 2. Hadoop jars found in the hadoop dependency coordinates directory, loaded in the order they are specified in
* 3. Druid jars (see IS_DRUID_URL) found in the ClassLoader for HadoopIndexTask.class
* 4. Extension URLs maintaining the order specified in the extensions list in the extensions config
*
* At one point I tried making each one of these steps a URLClassLoader, but it is not easy to make a properly
* predictive IS_DRUID_URL that captures all things which reference druid classes. This lead to a case where the
* class loader isolation worked great for stock druid, but failed in many common use cases including extension
* jars on the classpath which were not listed in the extensions list.
*
* As such, the current approach is to make a list of URLs for a URLClassLoader based on the priority above, and use
* THAT ClassLoader with a null parent as the isolated loader for running hadoop or hadoop-like driver tasks.
* Such an approach combined with reasonable exclusions in io.druid.cli.PullDependencies#exclusions tries to maintain
* sanity in a ClassLoader where all jars (which are isolated by extension ClassLoaders in the Druid framework) are
* jumbled together into one ClassLoader for Hadoop and Hadoop-like tasks (Spark for example).
*
* @param toolbox The toolbox to pull the default coordinates from if not present in the task
* @return An isolated URLClassLoader not tied by parent chain to the ApplicationClassLoader
* @throws MalformedURLException from Initialization.getClassLoaderForExtension
*/
protected ClassLoader buildClassLoader(final TaskToolbox toolbox) throws MalformedURLException
{
final List<String> finalHadoopDependencyCoordinates = hadoopDependencyCoordinates != null
? hadoopDependencyCoordinates
: toolbox.getConfig().getDefaultHadoopCoordinates();
final List<URL> jobURLs = Lists.newArrayList(
Arrays.asList(((URLClassLoader) HadoopIndexTask.class.getClassLoader()).getURLs())
);
for (final File extension : Initialization.getExtensionFilesToLoad(extensionsConfig)) {
final ClassLoader extensionLoader = Initialization.getClassLoaderForExtension(extension);
jobURLs.addAll(Arrays.asList(((URLClassLoader) extensionLoader).getURLs()));
}
final List<URL> localClassLoaderURLs = new ArrayList<>(jobURLs);
// hadoop dependencies come before druid classes because some extensions depend on them
for (final File hadoopDependency :
Initialization.getHadoopDependencyFilesToLoad(
finalHadoopDependencyCoordinates,
extensionsConfig
)) {
final ClassLoader hadoopLoader = Initialization.getClassLoaderForExtension(hadoopDependency);
localClassLoaderURLs.addAll(Arrays.asList(((URLClassLoader) hadoopLoader).getURLs()));
}
final ClassLoader classLoader = new URLClassLoader(
localClassLoaderURLs.toArray(new URL[localClassLoaderURLs.size()]),
null
);
System.setProperty("druid.hadoop.internal.classpath", Joiner.on(File.pathSeparator).join(jobURLs));
return classLoader;
}
/**
* This method tries to isolate class loading during a Function call
*
* @param clazzName The Class which has a static method called `runTask`
* @param input The input for `runTask`, must have `input.getClass()` be the class of the input for runTask
* @param loader The loader to use as the context class loader during invocation
* @param <InputType> The input type of the method.
* @param <OutputType> The output type of the method. The result of runTask must be castable to this type.
*
* @return The result of the method invocation
*/
public static <InputType, OutputType> OutputType invokeForeignLoader(
final String clazzName,
final InputType input,
final ClassLoader loader
)
{
log.debug("Launching [%s] on class loader [%s] with input class [%s]", clazzName, loader, input.getClass());
final ClassLoader oldLoader = Thread.currentThread().getContextClassLoader();
try {
Thread.currentThread().setContextClassLoader(loader);
final Class<?> clazz = loader.loadClass(clazzName);
final Method method = clazz.getMethod("runTask", input.getClass());
return (OutputType) method.invoke(null, input);
}
catch (IllegalAccessException | InvocationTargetException | ClassNotFoundException | NoSuchMethodException e) {
throw Throwables.propagate(e);
}
finally {
Thread.currentThread().setContextClassLoader(oldLoader);
}
}
}
| indexing-service/src/main/java/io/druid/indexing/common/task/HadoopTask.java | /*
* Licensed to Metamarkets Group Inc. (Metamarkets) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. Metamarkets licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package io.druid.indexing.common.task;
import com.google.common.base.Joiner;
import com.google.common.base.Predicate;
import com.google.common.base.Throwables;
import com.google.common.collect.Collections2;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Lists;
import com.google.inject.Injector;
import com.metamx.common.logger.Logger;
import io.druid.guice.ExtensionsConfig;
import io.druid.guice.GuiceInjectors;
import io.druid.indexing.common.TaskToolbox;
import io.druid.initialization.Initialization;
import javax.annotation.Nullable;
import java.io.File;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.MalformedURLException;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLClassLoader;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
public abstract class HadoopTask extends AbstractTask
{
private static final Logger log = new Logger(HadoopTask.class);
private static final ExtensionsConfig extensionsConfig;
final static Injector injector = GuiceInjectors.makeStartupInjector();
static {
extensionsConfig = injector.getInstance(ExtensionsConfig.class);
}
private final List<String> hadoopDependencyCoordinates;
protected HadoopTask(
String id,
String dataSource,
List<String> hadoopDependencyCoordinates,
Map<String, Object> context
)
{
super(id, dataSource, context);
this.hadoopDependencyCoordinates = hadoopDependencyCoordinates;
}
public List<String> getHadoopDependencyCoordinates()
{
return hadoopDependencyCoordinates == null ? null : ImmutableList.copyOf(hadoopDependencyCoordinates);
}
// This could stand to have a more robust detection methodology.
// Right now it just looks for `druid.*\.jar`
// This is only used for classpath isolation in the runTask isolation stuff, so it shooouuullldddd be ok.
protected static final Predicate<URL> IS_DRUID_URL = new Predicate<URL>()
{
@Override
public boolean apply(@Nullable URL input)
{
try {
if (input == null) {
return false;
}
final String fName = Paths.get(input.toURI()).getFileName().toString();
return fName.startsWith("druid") && fName.endsWith(".jar") && !fName.endsWith("selfcontained.jar");
}
catch (URISyntaxException e) {
throw Throwables.propagate(e);
}
}
};
/**
* This makes an isolated classloader that has classes loaded in the "proper" priority.
*
* This isolation is *only* for the part of the HadoopTask that calls runTask in an isolated manner.
*
* Jars for the job are the same jars as for the classloader EXCEPT the hadoopDependencyCoordinates, which are not used in the job jars.
*
* The URLs in the resultant classloader are loaded in this priority:
*
* 1. Non-Druid jars (see IS_DRUID_URL) found in the ClassLoader for HadoopIndexTask.class. This will probably be the ApplicationClassLoader
* 2. Hadoop jars found in the hadoop dependency coordinates directory, loaded in the order they are specified in
* 3. Druid jars (see IS_DRUID_URL) found in the ClassLoader for HadoopIndexTask.class
* 4. Extension URLs maintaining the order specified in the extensions list in the extensions config
*
* At one point I tried making each one of these steps a URLClassLoader, but it is not easy to make a properly
* predictive IS_DRUID_URL that captures all things which reference druid classes. This lead to a case where the
* class loader isolation worked great for stock druid, but failed in many common use cases including extension
* jars on the classpath which were not listed in the extensions list.
*
* As such, the current approach is to make a list of URLs for a URLClassLoader based on the priority above, and use
* THAT ClassLoader with a null parent as the isolated loader for running hadoop or hadoop-like driver tasks.
* Such an approach combined with reasonable exclusions in io.druid.cli.PullDependencies#exclusions tries to maintain
* sanity in a ClassLoader where all jars (which are isolated by extension ClassLoaders in the Druid framework) are
* jumbled together into one ClassLoader for Hadoop and Hadoop-like tasks (Spark for example).
*
* @param toolbox The toolbox to pull the default coordinates from if not present in the task
* @return An isolated URLClassLoader not tied by parent chain to the ApplicationClassLoader
* @throws MalformedURLException from Initialization.getClassLoaderForExtension
*/
protected ClassLoader buildClassLoader(final TaskToolbox toolbox) throws MalformedURLException
{
final List<String> finalHadoopDependencyCoordinates = hadoopDependencyCoordinates != null
? hadoopDependencyCoordinates
: toolbox.getConfig().getDefaultHadoopCoordinates();
final List<URL> extensionURLs = Lists.newArrayList();
for (final File extension : Initialization.getExtensionFilesToLoad(extensionsConfig)) {
final ClassLoader extensionLoader = Initialization.getClassLoaderForExtension(extension);
extensionURLs.addAll(Arrays.asList(((URLClassLoader) extensionLoader).getURLs()));
}
final List<URL> nonHadoopURLs = Lists.newArrayList();
nonHadoopURLs.addAll(Arrays.asList(((URLClassLoader) HadoopIndexTask.class.getClassLoader()).getURLs()));
final List<URL> druidURLs = ImmutableList.copyOf(
Collections2.filter(nonHadoopURLs, IS_DRUID_URL)
);
final List<URL> nonHadoopNotDruidURLs = Lists.newArrayList(nonHadoopURLs);
nonHadoopNotDruidURLs.removeAll(druidURLs);
final List<URL> localClassLoaderURLs = new ArrayList<>();
localClassLoaderURLs.addAll(nonHadoopNotDruidURLs);
// hadoop dependencies come before druid classes because some extensions depend on them
for (final File hadoopDependency :
Initialization.getHadoopDependencyFilesToLoad(
finalHadoopDependencyCoordinates,
extensionsConfig
)) {
final ClassLoader hadoopLoader = Initialization.getClassLoaderForExtension(hadoopDependency);
localClassLoaderURLs.addAll(Arrays.asList(((URLClassLoader) hadoopLoader).getURLs()));
}
localClassLoaderURLs.addAll(druidURLs);
localClassLoaderURLs.addAll(extensionURLs);
final ClassLoader classLoader = new URLClassLoader(localClassLoaderURLs.toArray(new URL[localClassLoaderURLs.size()]), null);
final List<URL> jobUrls = Lists.newArrayList();
jobUrls.addAll(nonHadoopURLs);
jobUrls.addAll(extensionURLs);
System.setProperty("druid.hadoop.internal.classpath", Joiner.on(File.pathSeparator).join(jobUrls));
return classLoader;
}
/**
* This method tries to isolate class loading during a Function call
*
* @param clazzName The Class which has a static method called `runTask`
* @param input The input for `runTask`, must have `input.getClass()` be the class of the input for runTask
* @param loader The loader to use as the context class loader during invocation
* @param <InputType> The input type of the method.
* @param <OutputType> The output type of the method. The result of runTask must be castable to this type.
*
* @return The result of the method invocation
*/
public static <InputType, OutputType> OutputType invokeForeignLoader(
final String clazzName,
final InputType input,
final ClassLoader loader
)
{
log.debug("Launching [%s] on class loader [%s] with input class [%s]", clazzName, loader, input.getClass());
final ClassLoader oldLoader = Thread.currentThread().getContextClassLoader();
try {
Thread.currentThread().setContextClassLoader(loader);
final Class<?> clazz = loader.loadClass(clazzName);
final Method method = clazz.getMethod("runTask", input.getClass());
return (OutputType) method.invoke(null, input);
}
catch (IllegalAccessException | InvocationTargetException | ClassNotFoundException | NoSuchMethodException e) {
throw Throwables.propagate(e);
}
finally {
Thread.currentThread().setContextClassLoader(oldLoader);
}
}
}
| Make HadoopTask load hadoop dependency classes LAST for local isolated classrunner
| indexing-service/src/main/java/io/druid/indexing/common/task/HadoopTask.java | Make HadoopTask load hadoop dependency classes LAST for local isolated classrunner | <ide><path>ndexing-service/src/main/java/io/druid/indexing/common/task/HadoopTask.java
<ide> import com.google.common.base.Joiner;
<ide> import com.google.common.base.Predicate;
<ide> import com.google.common.base.Throwables;
<del>import com.google.common.collect.Collections2;
<ide> import com.google.common.collect.ImmutableList;
<ide> import com.google.common.collect.Lists;
<ide> import com.google.inject.Injector;
<ide> ? hadoopDependencyCoordinates
<ide> : toolbox.getConfig().getDefaultHadoopCoordinates();
<ide>
<del> final List<URL> extensionURLs = Lists.newArrayList();
<add> final List<URL> jobURLs = Lists.newArrayList(
<add> Arrays.asList(((URLClassLoader) HadoopIndexTask.class.getClassLoader()).getURLs())
<add> );
<add>
<ide> for (final File extension : Initialization.getExtensionFilesToLoad(extensionsConfig)) {
<ide> final ClassLoader extensionLoader = Initialization.getClassLoaderForExtension(extension);
<del> extensionURLs.addAll(Arrays.asList(((URLClassLoader) extensionLoader).getURLs()));
<add> jobURLs.addAll(Arrays.asList(((URLClassLoader) extensionLoader).getURLs()));
<ide> }
<ide>
<del> final List<URL> nonHadoopURLs = Lists.newArrayList();
<del> nonHadoopURLs.addAll(Arrays.asList(((URLClassLoader) HadoopIndexTask.class.getClassLoader()).getURLs()));
<del>
<del> final List<URL> druidURLs = ImmutableList.copyOf(
<del> Collections2.filter(nonHadoopURLs, IS_DRUID_URL)
<del> );
<del> final List<URL> nonHadoopNotDruidURLs = Lists.newArrayList(nonHadoopURLs);
<del> nonHadoopNotDruidURLs.removeAll(druidURLs);
<del>
<del> final List<URL> localClassLoaderURLs = new ArrayList<>();
<del> localClassLoaderURLs.addAll(nonHadoopNotDruidURLs);
<add> final List<URL> localClassLoaderURLs = new ArrayList<>(jobURLs);
<ide>
<ide> // hadoop dependencies come before druid classes because some extensions depend on them
<ide> for (final File hadoopDependency :
<ide> localClassLoaderURLs.addAll(Arrays.asList(((URLClassLoader) hadoopLoader).getURLs()));
<ide> }
<ide>
<del> localClassLoaderURLs.addAll(druidURLs);
<del> localClassLoaderURLs.addAll(extensionURLs);
<del> final ClassLoader classLoader = new URLClassLoader(localClassLoaderURLs.toArray(new URL[localClassLoaderURLs.size()]), null);
<add> final ClassLoader classLoader = new URLClassLoader(
<add> localClassLoaderURLs.toArray(new URL[localClassLoaderURLs.size()]),
<add> null
<add> );
<ide>
<del> final List<URL> jobUrls = Lists.newArrayList();
<del> jobUrls.addAll(nonHadoopURLs);
<del> jobUrls.addAll(extensionURLs);
<del>
<del> System.setProperty("druid.hadoop.internal.classpath", Joiner.on(File.pathSeparator).join(jobUrls));
<add> System.setProperty("druid.hadoop.internal.classpath", Joiner.on(File.pathSeparator).join(jobURLs));
<ide> return classLoader;
<ide> }
<ide> |
|
Java | apache-2.0 | 9c938cf96f7363e27dd8c19bf9bf5b69efa8c091 | 0 | suncycheng/intellij-community,allotria/intellij-community,allotria/intellij-community,MER-GROUP/intellij-community,ahb0327/intellij-community,FHannes/intellij-community,allotria/intellij-community,retomerz/intellij-community,kool79/intellij-community,michaelgallacher/intellij-community,supersven/intellij-community,gnuhub/intellij-community,MichaelNedzelsky/intellij-community,amith01994/intellij-community,MichaelNedzelsky/intellij-community,jagguli/intellij-community,wreckJ/intellij-community,mglukhikh/intellij-community,MER-GROUP/intellij-community,supersven/intellij-community,consulo/consulo,ryano144/intellij-community,xfournet/intellij-community,allotria/intellij-community,salguarnieri/intellij-community,Distrotech/intellij-community,da1z/intellij-community,idea4bsd/idea4bsd,da1z/intellij-community,tmpgit/intellij-community,FHannes/intellij-community,lucafavatella/intellij-community,fnouama/intellij-community,MichaelNedzelsky/intellij-community,slisson/intellij-community,samthor/intellij-community,kool79/intellij-community,kdwink/intellij-community,MichaelNedzelsky/intellij-community,kdwink/intellij-community,TangHao1987/intellij-community,fengbaicanhe/intellij-community,izonder/intellij-community,fitermay/intellij-community,slisson/intellij-community,mglukhikh/intellij-community,robovm/robovm-studio,fitermay/intellij-community,kdwink/intellij-community,muntasirsyed/intellij-community,ftomassetti/intellij-community,TangHao1987/intellij-community,da1z/intellij-community,fnouama/intellij-community,diorcety/intellij-community,ibinti/intellij-community,jagguli/intellij-community,amith01994/intellij-community,wreckJ/intellij-community,holmes/intellij-community,adedayo/intellij-community,blademainer/intellij-community,jagguli/intellij-community,michaelgallacher/intellij-community,allotria/intellij-community,wreckJ/intellij-community,SerCeMan/intellij-community,ibinti/intellij-community,xfournet/intellij-community,wreckJ/intellij-community,hurricup/intellij-community,blademainer/intellij-community,wreckJ/intellij-community,fengbaicanhe/intellij-community,jagguli/intellij-community,vvv1559/intellij-community,semonte/intellij-community,idea4bsd/idea4bsd,youdonghai/intellij-community,retomerz/intellij-community,tmpgit/intellij-community,vvv1559/intellij-community,ThiagoGarciaAlves/intellij-community,wreckJ/intellij-community,michaelgallacher/intellij-community,MichaelNedzelsky/intellij-community,ahb0327/intellij-community,wreckJ/intellij-community,gnuhub/intellij-community,izonder/intellij-community,asedunov/intellij-community,akosyakov/intellij-community,kool79/intellij-community,mglukhikh/intellij-community,vvv1559/intellij-community,FHannes/intellij-community,retomerz/intellij-community,robovm/robovm-studio,petteyg/intellij-community,izonder/intellij-community,orekyuu/intellij-community,fengbaicanhe/intellij-community,robovm/robovm-studio,SerCeMan/intellij-community,youdonghai/intellij-community,TangHao1987/intellij-community,alphafoobar/intellij-community,signed/intellij-community,ernestp/consulo,youdonghai/intellij-community,hurricup/intellij-community,tmpgit/intellij-community,ol-loginov/intellij-community,ahb0327/intellij-community,diorcety/intellij-community,vladmm/intellij-community,mglukhikh/intellij-community,semonte/intellij-community,orekyuu/intellij-community,slisson/intellij-community,ivan-fedorov/intellij-community,petteyg/intellij-community,caot/intellij-community,nicolargo/intellij-community,ftomassetti/intellij-community,MichaelNedzelsky/intellij-community,apixandru/intellij-community,retomerz/intellij-community,ryano144/intellij-community,diorcety/intellij-community,ibinti/intellij-community,slisson/intellij-community,MER-GROUP/intellij-community,MichaelNedzelsky/intellij-community,TangHao1987/intellij-community,lucafavatella/intellij-community,ol-loginov/intellij-community,Distrotech/intellij-community,ivan-fedorov/intellij-community,suncycheng/intellij-community,amith01994/intellij-community,lucafavatella/intellij-community,alphafoobar/intellij-community,SerCeMan/intellij-community,ryano144/intellij-community,tmpgit/intellij-community,da1z/intellij-community,robovm/robovm-studio,FHannes/intellij-community,vvv1559/intellij-community,idea4bsd/idea4bsd,consulo/consulo,MER-GROUP/intellij-community,vladmm/intellij-community,petteyg/intellij-community,muntasirsyed/intellij-community,ftomassetti/intellij-community,TangHao1987/intellij-community,clumsy/intellij-community,gnuhub/intellij-community,vvv1559/intellij-community,SerCeMan/intellij-community,supersven/intellij-community,suncycheng/intellij-community,SerCeMan/intellij-community,Lekanich/intellij-community,ol-loginov/intellij-community,suncycheng/intellij-community,FHannes/intellij-community,vladmm/intellij-community,lucafavatella/intellij-community,clumsy/intellij-community,gnuhub/intellij-community,ibinti/intellij-community,hurricup/intellij-community,fnouama/intellij-community,diorcety/intellij-community,signed/intellij-community,samthor/intellij-community,orekyuu/intellij-community,hurricup/intellij-community,adedayo/intellij-community,gnuhub/intellij-community,salguarnieri/intellij-community,allotria/intellij-community,youdonghai/intellij-community,samthor/intellij-community,hurricup/intellij-community,ryano144/intellij-community,mglukhikh/intellij-community,nicolargo/intellij-community,muntasirsyed/intellij-community,idea4bsd/idea4bsd,slisson/intellij-community,suncycheng/intellij-community,izonder/intellij-community,fengbaicanhe/intellij-community,signed/intellij-community,apixandru/intellij-community,fitermay/intellij-community,caot/intellij-community,Lekanich/intellij-community,signed/intellij-community,samthor/intellij-community,pwoodworth/intellij-community,dslomov/intellij-community,lucafavatella/intellij-community,ibinti/intellij-community,akosyakov/intellij-community,clumsy/intellij-community,ivan-fedorov/intellij-community,Distrotech/intellij-community,Distrotech/intellij-community,SerCeMan/intellij-community,suncycheng/intellij-community,pwoodworth/intellij-community,amith01994/intellij-community,fnouama/intellij-community,suncycheng/intellij-community,apixandru/intellij-community,vvv1559/intellij-community,idea4bsd/idea4bsd,da1z/intellij-community,slisson/intellij-community,pwoodworth/intellij-community,adedayo/intellij-community,izonder/intellij-community,pwoodworth/intellij-community,allotria/intellij-community,MER-GROUP/intellij-community,ibinti/intellij-community,idea4bsd/idea4bsd,adedayo/intellij-community,petteyg/intellij-community,asedunov/intellij-community,nicolargo/intellij-community,blademainer/intellij-community,akosyakov/intellij-community,kdwink/intellij-community,ahb0327/intellij-community,idea4bsd/idea4bsd,amith01994/intellij-community,diorcety/intellij-community,samthor/intellij-community,amith01994/intellij-community,amith01994/intellij-community,da1z/intellij-community,ernestp/consulo,kool79/intellij-community,MER-GROUP/intellij-community,fengbaicanhe/intellij-community,semonte/intellij-community,ryano144/intellij-community,fnouama/intellij-community,ahb0327/intellij-community,izonder/intellij-community,petteyg/intellij-community,mglukhikh/intellij-community,clumsy/intellij-community,asedunov/intellij-community,retomerz/intellij-community,samthor/intellij-community,petteyg/intellij-community,suncycheng/intellij-community,fengbaicanhe/intellij-community,ftomassetti/intellij-community,lucafavatella/intellij-community,orekyuu/intellij-community,holmes/intellij-community,samthor/intellij-community,xfournet/intellij-community,diorcety/intellij-community,akosyakov/intellij-community,vvv1559/intellij-community,youdonghai/intellij-community,MER-GROUP/intellij-community,Lekanich/intellij-community,xfournet/intellij-community,muntasirsyed/intellij-community,kool79/intellij-community,FHannes/intellij-community,Distrotech/intellij-community,MER-GROUP/intellij-community,semonte/intellij-community,muntasirsyed/intellij-community,caot/intellij-community,ThiagoGarciaAlves/intellij-community,kdwink/intellij-community,pwoodworth/intellij-community,samthor/intellij-community,hurricup/intellij-community,ol-loginov/intellij-community,hurricup/intellij-community,pwoodworth/intellij-community,akosyakov/intellij-community,adedayo/intellij-community,fnouama/intellij-community,SerCeMan/intellij-community,retomerz/intellij-community,holmes/intellij-community,fnouama/intellij-community,caot/intellij-community,jagguli/intellij-community,vvv1559/intellij-community,ryano144/intellij-community,robovm/robovm-studio,caot/intellij-community,akosyakov/intellij-community,salguarnieri/intellij-community,michaelgallacher/intellij-community,suncycheng/intellij-community,dslomov/intellij-community,holmes/intellij-community,adedayo/intellij-community,gnuhub/intellij-community,tmpgit/intellij-community,petteyg/intellij-community,consulo/consulo,petteyg/intellij-community,diorcety/intellij-community,fnouama/intellij-community,jagguli/intellij-community,Lekanich/intellij-community,vladmm/intellij-community,semonte/intellij-community,gnuhub/intellij-community,Lekanich/intellij-community,da1z/intellij-community,adedayo/intellij-community,holmes/intellij-community,ahb0327/intellij-community,dslomov/intellij-community,holmes/intellij-community,blademainer/intellij-community,vladmm/intellij-community,dslomov/intellij-community,ivan-fedorov/intellij-community,da1z/intellij-community,gnuhub/intellij-community,youdonghai/intellij-community,tmpgit/intellij-community,ThiagoGarciaAlves/intellij-community,Lekanich/intellij-community,diorcety/intellij-community,dslomov/intellij-community,salguarnieri/intellij-community,samthor/intellij-community,clumsy/intellij-community,vladmm/intellij-community,muntasirsyed/intellij-community,xfournet/intellij-community,mglukhikh/intellij-community,ryano144/intellij-community,caot/intellij-community,alphafoobar/intellij-community,samthor/intellij-community,Lekanich/intellij-community,ivan-fedorov/intellij-community,muntasirsyed/intellij-community,vladmm/intellij-community,pwoodworth/intellij-community,retomerz/intellij-community,idea4bsd/idea4bsd,ahb0327/intellij-community,ol-loginov/intellij-community,nicolargo/intellij-community,ivan-fedorov/intellij-community,fengbaicanhe/intellij-community,mglukhikh/intellij-community,holmes/intellij-community,semonte/intellij-community,nicolargo/intellij-community,muntasirsyed/intellij-community,supersven/intellij-community,FHannes/intellij-community,youdonghai/intellij-community,kool79/intellij-community,ernestp/consulo,supersven/intellij-community,idea4bsd/idea4bsd,hurricup/intellij-community,petteyg/intellij-community,alphafoobar/intellij-community,ibinti/intellij-community,suncycheng/intellij-community,lucafavatella/intellij-community,alphafoobar/intellij-community,nicolargo/intellij-community,akosyakov/intellij-community,Distrotech/intellij-community,pwoodworth/intellij-community,izonder/intellij-community,orekyuu/intellij-community,supersven/intellij-community,slisson/intellij-community,TangHao1987/intellij-community,allotria/intellij-community,dslomov/intellij-community,fengbaicanhe/intellij-community,fnouama/intellij-community,retomerz/intellij-community,lucafavatella/intellij-community,amith01994/intellij-community,robovm/robovm-studio,semonte/intellij-community,adedayo/intellij-community,kdwink/intellij-community,clumsy/intellij-community,ThiagoGarciaAlves/intellij-community,da1z/intellij-community,muntasirsyed/intellij-community,jagguli/intellij-community,ol-loginov/intellij-community,signed/intellij-community,SerCeMan/intellij-community,ibinti/intellij-community,michaelgallacher/intellij-community,mglukhikh/intellij-community,ibinti/intellij-community,fitermay/intellij-community,semonte/intellij-community,slisson/intellij-community,retomerz/intellij-community,youdonghai/intellij-community,akosyakov/intellij-community,Distrotech/intellij-community,amith01994/intellij-community,slisson/intellij-community,robovm/robovm-studio,ernestp/consulo,allotria/intellij-community,nicolargo/intellij-community,clumsy/intellij-community,akosyakov/intellij-community,apixandru/intellij-community,michaelgallacher/intellij-community,holmes/intellij-community,dslomov/intellij-community,vvv1559/intellij-community,kdwink/intellij-community,signed/intellij-community,hurricup/intellij-community,fitermay/intellij-community,semonte/intellij-community,blademainer/intellij-community,youdonghai/intellij-community,amith01994/intellij-community,orekyuu/intellij-community,asedunov/intellij-community,clumsy/intellij-community,xfournet/intellij-community,ahb0327/intellij-community,asedunov/intellij-community,ol-loginov/intellij-community,supersven/intellij-community,apixandru/intellij-community,kool79/intellij-community,salguarnieri/intellij-community,MER-GROUP/intellij-community,michaelgallacher/intellij-community,asedunov/intellij-community,apixandru/intellij-community,mglukhikh/intellij-community,lucafavatella/intellij-community,ivan-fedorov/intellij-community,ftomassetti/intellij-community,ryano144/intellij-community,signed/intellij-community,MER-GROUP/intellij-community,ivan-fedorov/intellij-community,michaelgallacher/intellij-community,asedunov/intellij-community,ivan-fedorov/intellij-community,wreckJ/intellij-community,caot/intellij-community,ftomassetti/intellij-community,slisson/intellij-community,kool79/intellij-community,gnuhub/intellij-community,youdonghai/intellij-community,salguarnieri/intellij-community,kool79/intellij-community,retomerz/intellij-community,retomerz/intellij-community,xfournet/intellij-community,ftomassetti/intellij-community,SerCeMan/intellij-community,MER-GROUP/intellij-community,ibinti/intellij-community,asedunov/intellij-community,akosyakov/intellij-community,apixandru/intellij-community,TangHao1987/intellij-community,jagguli/intellij-community,izonder/intellij-community,orekyuu/intellij-community,Lekanich/intellij-community,muntasirsyed/intellij-community,adedayo/intellij-community,tmpgit/intellij-community,fitermay/intellij-community,robovm/robovm-studio,clumsy/intellij-community,gnuhub/intellij-community,tmpgit/intellij-community,pwoodworth/intellij-community,izonder/intellij-community,MER-GROUP/intellij-community,dslomov/intellij-community,akosyakov/intellij-community,TangHao1987/intellij-community,apixandru/intellij-community,fitermay/intellij-community,suncycheng/intellij-community,lucafavatella/intellij-community,nicolargo/intellij-community,idea4bsd/idea4bsd,MichaelNedzelsky/intellij-community,kdwink/intellij-community,da1z/intellij-community,fitermay/intellij-community,vvv1559/intellij-community,fitermay/intellij-community,da1z/intellij-community,ol-loginov/intellij-community,kool79/intellij-community,petteyg/intellij-community,dslomov/intellij-community,ftomassetti/intellij-community,michaelgallacher/intellij-community,kdwink/intellij-community,apixandru/intellij-community,mglukhikh/intellij-community,asedunov/intellij-community,jagguli/intellij-community,ibinti/intellij-community,alphafoobar/intellij-community,michaelgallacher/intellij-community,Lekanich/intellij-community,salguarnieri/intellij-community,orekyuu/intellij-community,lucafavatella/intellij-community,idea4bsd/idea4bsd,wreckJ/intellij-community,hurricup/intellij-community,slisson/intellij-community,izonder/intellij-community,signed/intellij-community,ThiagoGarciaAlves/intellij-community,ibinti/intellij-community,dslomov/intellij-community,holmes/intellij-community,fitermay/intellij-community,kool79/intellij-community,ivan-fedorov/intellij-community,ftomassetti/intellij-community,apixandru/intellij-community,wreckJ/intellij-community,ftomassetti/intellij-community,allotria/intellij-community,nicolargo/intellij-community,caot/intellij-community,wreckJ/intellij-community,samthor/intellij-community,ThiagoGarciaAlves/intellij-community,vvv1559/intellij-community,MichaelNedzelsky/intellij-community,ol-loginov/intellij-community,TangHao1987/intellij-community,salguarnieri/intellij-community,ivan-fedorov/intellij-community,amith01994/intellij-community,ThiagoGarciaAlves/intellij-community,Distrotech/intellij-community,ryano144/intellij-community,ivan-fedorov/intellij-community,fitermay/intellij-community,asedunov/intellij-community,clumsy/intellij-community,TangHao1987/intellij-community,ThiagoGarciaAlves/intellij-community,SerCeMan/intellij-community,slisson/intellij-community,MichaelNedzelsky/intellij-community,izonder/intellij-community,ernestp/consulo,jagguli/intellij-community,FHannes/intellij-community,semonte/intellij-community,wreckJ/intellij-community,kdwink/intellij-community,xfournet/intellij-community,asedunov/intellij-community,FHannes/intellij-community,robovm/robovm-studio,fitermay/intellij-community,diorcety/intellij-community,caot/intellij-community,idea4bsd/idea4bsd,fnouama/intellij-community,signed/intellij-community,vladmm/intellij-community,dslomov/intellij-community,ol-loginov/intellij-community,FHannes/intellij-community,nicolargo/intellij-community,kdwink/intellij-community,michaelgallacher/intellij-community,pwoodworth/intellij-community,xfournet/intellij-community,blademainer/intellij-community,ahb0327/intellij-community,ThiagoGarciaAlves/intellij-community,hurricup/intellij-community,allotria/intellij-community,xfournet/intellij-community,salguarnieri/intellij-community,apixandru/intellij-community,holmes/intellij-community,gnuhub/intellij-community,blademainer/intellij-community,youdonghai/intellij-community,ahb0327/intellij-community,fnouama/intellij-community,petteyg/intellij-community,FHannes/intellij-community,pwoodworth/intellij-community,xfournet/intellij-community,orekyuu/intellij-community,semonte/intellij-community,Lekanich/intellij-community,fnouama/intellij-community,blademainer/intellij-community,ol-loginov/intellij-community,alphafoobar/intellij-community,salguarnieri/intellij-community,ThiagoGarciaAlves/intellij-community,semonte/intellij-community,orekyuu/intellij-community,signed/intellij-community,vladmm/intellij-community,robovm/robovm-studio,alphafoobar/intellij-community,idea4bsd/idea4bsd,supersven/intellij-community,muntasirsyed/intellij-community,mglukhikh/intellij-community,dslomov/intellij-community,pwoodworth/intellij-community,TangHao1987/intellij-community,jagguli/intellij-community,hurricup/intellij-community,da1z/intellij-community,signed/intellij-community,vladmm/intellij-community,retomerz/intellij-community,ftomassetti/intellij-community,TangHao1987/intellij-community,kdwink/intellij-community,consulo/consulo,asedunov/intellij-community,robovm/robovm-studio,Distrotech/intellij-community,mglukhikh/intellij-community,xfournet/intellij-community,caot/intellij-community,youdonghai/intellij-community,Lekanich/intellij-community,apixandru/intellij-community,gnuhub/intellij-community,nicolargo/intellij-community,consulo/consulo,signed/intellij-community,diorcety/intellij-community,fitermay/intellij-community,ftomassetti/intellij-community,allotria/intellij-community,Lekanich/intellij-community,ryano144/intellij-community,adedayo/intellij-community,adedayo/intellij-community,ol-loginov/intellij-community,clumsy/intellij-community,izonder/intellij-community,salguarnieri/intellij-community,apixandru/intellij-community,blademainer/intellij-community,robovm/robovm-studio,nicolargo/intellij-community,Distrotech/intellij-community,xfournet/intellij-community,retomerz/intellij-community,FHannes/intellij-community,SerCeMan/intellij-community,allotria/intellij-community,ryano144/intellij-community,diorcety/intellij-community,suncycheng/intellij-community,vvv1559/intellij-community,FHannes/intellij-community,orekyuu/intellij-community,vladmm/intellij-community,da1z/intellij-community,ahb0327/intellij-community,vvv1559/intellij-community,caot/intellij-community,adedayo/intellij-community,fengbaicanhe/intellij-community,tmpgit/intellij-community,supersven/intellij-community,tmpgit/intellij-community,supersven/intellij-community,holmes/intellij-community,akosyakov/intellij-community,petteyg/intellij-community,kool79/intellij-community,MichaelNedzelsky/intellij-community,jagguli/intellij-community,orekyuu/intellij-community,fengbaicanhe/intellij-community,blademainer/intellij-community,ryano144/intellij-community,apixandru/intellij-community,lucafavatella/intellij-community,fengbaicanhe/intellij-community,ThiagoGarciaAlves/intellij-community,alphafoobar/intellij-community,michaelgallacher/intellij-community,youdonghai/intellij-community,ernestp/consulo,salguarnieri/intellij-community,vladmm/intellij-community,alphafoobar/intellij-community,caot/intellij-community,holmes/intellij-community,supersven/intellij-community,diorcety/intellij-community,ThiagoGarciaAlves/intellij-community,alphafoobar/intellij-community,amith01994/intellij-community,lucafavatella/intellij-community,SerCeMan/intellij-community,samthor/intellij-community,consulo/consulo,ibinti/intellij-community,supersven/intellij-community,MichaelNedzelsky/intellij-community,tmpgit/intellij-community,Distrotech/intellij-community,blademainer/intellij-community,semonte/intellij-community,hurricup/intellij-community,Distrotech/intellij-community,blademainer/intellij-community,asedunov/intellij-community,muntasirsyed/intellij-community,signed/intellij-community,clumsy/intellij-community,alphafoobar/intellij-community,tmpgit/intellij-community,ahb0327/intellij-community,fengbaicanhe/intellij-community | /*
* Copyright 2000-2011 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.jps.server;
import com.google.protobuf.Message;
import com.intellij.compiler.notNullVerification.NotNullVerifyingInstrumenter;
import com.intellij.openapi.application.PathManager;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.util.io.FileUtil;
import com.intellij.uiDesigner.compiler.AlienFormFileException;
import com.intellij.uiDesigner.core.GridConstraints;
import com.intellij.util.SystemProperties;
import com.jgoodies.forms.layout.CellConstraints;
import net.n3.nanoxml.IXMLBuilder;
import org.codehaus.groovy.GroovyException;
import org.jboss.netty.util.Version;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.asm4.ClassVisitor;
import org.jetbrains.asm4.ClassWriter;
import org.jetbrains.jps.MacroExpander;
import org.jetbrains.jps.cmdline.BuildMain;
import org.jetbrains.jps.javac.JavacServer;
import javax.tools.*;
import java.io.File;
import java.util.*;
/**
* @author Eugene Zhuravlev
* Date: 9/12/11
*/
public class ClasspathBootstrap {
private static final Logger LOG = Logger.getInstance("#org.jetbrains.jps.server.ClasspathBootstrap");
private static class OptimizedFileManagerClassHolder {
static final String CLASS_NAME = "org.jetbrains.jps.javac.OptimizedFileManager";
static final Class<StandardJavaFileManager> managerClass;
static {
Class<StandardJavaFileManager> aClass = null;
try {
aClass = (Class<StandardJavaFileManager>)Class.forName(CLASS_NAME);
}
catch (Throwable e) {
aClass = null;
}
managerClass = aClass;
}
private OptimizedFileManagerClassHolder() {
}
}
private static class OptimizedFileManager17ClassHolder {
static final String CLASS_NAME = "org.jetbrains.jps.javac.OptimizedFileManager17";
static final Class<StandardJavaFileManager> managerClass;
static {
Class<StandardJavaFileManager> aClass = null;
try {
aClass = (Class<StandardJavaFileManager>)Class.forName(CLASS_NAME);
}
catch (Throwable e) {
aClass = null;
}
managerClass = aClass;
}
private OptimizedFileManager17ClassHolder() {
}
}
private ClasspathBootstrap() {
}
public static List<File> getBuildProcessApplicationClasspath() {
final Set<File> cp = new LinkedHashSet<File>();
cp.add(getResourcePath(BuildMain.class));
for (String path : PathManager.getUtilClassPath()) { // util
cp.add(new File(path));
}
cp.add(getResourcePath(Message.class)); // protobuf
cp.add(getResourcePath(Version.class)); // netty
cp.add(getResourcePath(ClassWriter.class)); // asm
cp.add(getResourcePath(ClassVisitor.class)); // asm-commons
cp.add(getResourcePath(MacroExpander.class)); // jps-model
cp.add(getResourcePath(AlienFormFileException.class)); // forms-compiler
cp.add(getResourcePath(GroovyException.class)); // groovy
cp.add(getResourcePath(GridConstraints.class)); // forms-rt
cp.add(getResourcePath(CellConstraints.class)); // jgoodies-forms
cp.add(getResourcePath(NotNullVerifyingInstrumenter.class)); // not-null
cp.add(getResourcePath(IXMLBuilder.class)); // nano-xml
final Class<StandardJavaFileManager> optimizedFileManagerClass = getOptimizedFileManagerClass();
if (optimizedFileManagerClass != null) {
cp.add(getResourcePath(optimizedFileManagerClass)); // optimizedFileManager
}
try {
final Class<?> cmdLineWrapper = Class.forName("com.intellij.rt.execution.CommandLineWrapper");
cp.add(getResourcePath(cmdLineWrapper)); // idea_rt.jar
}
catch (Throwable ignored) {
}
for (JavaCompiler javaCompiler : ServiceLoader.load(JavaCompiler.class)) { // Eclipse compiler
final File compilerResource = getResourcePath(javaCompiler.getClass());
final String name = compilerResource.getName();
if (name.startsWith("ecj-") && name.endsWith(".jar")) {
cp.add(compilerResource);
}
}
return new ArrayList<File>(cp);
}
public static List<File> getJavacServerClasspath(String sdkHome) {
final Set<File> cp = new LinkedHashSet<File>();
cp.add(getResourcePath(JavacServer.class)); // self
// util
for (String path : PathManager.getUtilClassPath()) {
cp.add(new File(path));
}
cp.add(getResourcePath(Message.class)); // protobuf
cp.add(getResourcePath(Version.class)); // netty
final Class<StandardJavaFileManager> optimizedFileManagerClass = getOptimizedFileManagerClass();
if (optimizedFileManagerClass != null) {
cp.add(getResourcePath(optimizedFileManagerClass)); // optimizedFileManager, if applicable
}
try {
final Class<?> cmdLineWrapper = Class.forName("com.intellij.rt.execution.CommandLineWrapper");
cp.add(getResourcePath(cmdLineWrapper)); // idea_rt.jar
}
catch (Throwable th) {
LOG.info(th);
}
final JavaCompiler systemCompiler = ToolProvider.getSystemJavaCompiler();
if (systemCompiler != null) {
try {
final String localJarPath = FileUtil.toSystemIndependentName(getResourcePath(systemCompiler.getClass()).getPath());
final String localJavaHome = FileUtil.toSystemIndependentName(SystemProperties.getJavaHome());
if (FileUtil.pathsEqual(localJavaHome, FileUtil.toSystemIndependentName(sdkHome))) {
cp.add(new File(localJarPath));
}
else {
// sdkHome is not the same as the sdk used to run this process
final File candidate = new File(sdkHome, "lib/tools.jar");
if (candidate.exists()) {
cp.add(candidate);
}
else {
// last resort
String relPath = FileUtil.getRelativePath(localJavaHome, localJarPath, '/');
if (relPath != null) {
if (relPath.contains("..")) {
relPath = FileUtil.getRelativePath(FileUtil.toSystemIndependentName(new File(localJavaHome).getParent()), localJarPath, '/');
}
if (relPath != null) {
final File targetFile = new File(sdkHome, relPath);
cp.add(targetFile); // tools.jar
}
}
}
}
}
catch (Throwable th) {
LOG.info(th);
}
}
return new ArrayList<File>(cp);
}
@Nullable
public static Class<StandardJavaFileManager> getOptimizedFileManagerClass() {
final Class<StandardJavaFileManager> aClass = OptimizedFileManagerClassHolder.managerClass;
if (aClass != null) {
return aClass;
}
return OptimizedFileManager17ClassHolder.managerClass;
}
public static File getResourcePath(Class aClass) {
return new File(PathManager.getResourceRoot(aClass, "/" + aClass.getName().replace('.', '/') + ".class"));
}
}
| jps/jps-builders/src/org/jetbrains/jps/server/ClasspathBootstrap.java | /*
* Copyright 2000-2011 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.jps.server;
import com.google.protobuf.Message;
import com.intellij.compiler.notNullVerification.NotNullVerifyingInstrumenter;
import com.intellij.openapi.application.PathManager;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.util.io.FileUtil;
import com.intellij.uiDesigner.compiler.AlienFormFileException;
import com.intellij.uiDesigner.core.GridConstraints;
import com.intellij.util.SystemProperties;
import com.jgoodies.forms.layout.CellConstraints;
import net.n3.nanoxml.IXMLBuilder;
import org.codehaus.groovy.GroovyException;
import org.jboss.netty.util.Version;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.asm4.ClassVisitor;
import org.jetbrains.asm4.ClassWriter;
import org.jetbrains.jps.MacroExpander;
import org.jetbrains.jps.javac.JavacServer;
import javax.tools.JavaCompiler;
import javax.tools.StandardJavaFileManager;
import javax.tools.ToolProvider;
import java.io.File;
import java.util.*;
/**
* @author Eugene Zhuravlev
* Date: 9/12/11
*/
public class ClasspathBootstrap {
private static final Logger LOG = Logger.getInstance("#org.jetbrains.jps.server.ClasspathBootstrap");
private static class OptimizedFileManagerClassHolder {
static final String CLASS_NAME = "org.jetbrains.jps.javac.OptimizedFileManager";
static final Class<StandardJavaFileManager> managerClass;
static {
Class<StandardJavaFileManager> aClass = null;
try {
aClass = (Class<StandardJavaFileManager>)Class.forName(CLASS_NAME);
}
catch (Throwable e) {
aClass = null;
}
managerClass = aClass;
}
private OptimizedFileManagerClassHolder() {
}
}
private static class OptimizedFileManager17ClassHolder {
static final String CLASS_NAME = "org.jetbrains.jps.javac.OptimizedFileManager17";
static final Class<StandardJavaFileManager> managerClass;
static {
Class<StandardJavaFileManager> aClass = null;
try {
aClass = (Class<StandardJavaFileManager>)Class.forName(CLASS_NAME);
}
catch (Throwable e) {
aClass = null;
}
managerClass = aClass;
}
private OptimizedFileManager17ClassHolder() {
}
}
private ClasspathBootstrap() {
}
public static List<File> getBuildProcessApplicationClasspath() {
final Set<File> cp = new LinkedHashSet<File>();
cp.add(getResourcePath(Server.class));
for (String path : PathManager.getUtilClassPath()) { cp.add(new File(path)); } // util
cp.add(getResourcePath(Message.class)); // protobuf
cp.add(getResourcePath(Version.class)); // netty
cp.add(getResourcePath(ClassWriter.class)); // asm
cp.add(getResourcePath(ClassVisitor.class)); // asm-commons
cp.add(getResourcePath(MacroExpander.class)); // jps-model
cp.add(getResourcePath(AlienFormFileException.class)); // forms-compiler
cp.add(getResourcePath(GroovyException.class)); // groovy
cp.add(getResourcePath(GridConstraints.class)); // forms-rt
cp.add(getResourcePath(CellConstraints.class)); // jgoodies-forms
cp.add(getResourcePath(NotNullVerifyingInstrumenter.class)); // not-null
cp.add(getResourcePath(IXMLBuilder.class)); // nano-xml
final Class<StandardJavaFileManager> optimizedFileManagerClass = getOptimizedFileManagerClass();
if (optimizedFileManagerClass != null) {
cp.add(getResourcePath(optimizedFileManagerClass)); // optimizedFileManager
}
try {
final Class<?> cmdLineWrapper = Class.forName("com.intellij.rt.execution.CommandLineWrapper");
cp.add(getResourcePath(cmdLineWrapper)); // idea_rt.jar
}
catch (Throwable ignored) {
}
for (JavaCompiler javaCompiler : ServiceLoader.load(JavaCompiler.class)) { // Eclipse compiler
final File compilerResource = getResourcePath(javaCompiler.getClass());
final String name = compilerResource.getName();
if (name.startsWith("ecj-") && name.endsWith(".jar")) {
cp.add(compilerResource);
}
}
return new ArrayList<File>(cp);
}
public static List<File> getJavacServerClasspath(String sdkHome) {
final Set<File> cp = new LinkedHashSet<File>();
cp.add(getResourcePath(JavacServer.class)); // self
// util
for (String path : PathManager.getUtilClassPath()) {
cp.add(new File(path));
}
cp.add(getResourcePath(Message.class)); // protobuf
cp.add(getResourcePath(Version.class)); // netty
final Class<StandardJavaFileManager> optimizedFileManagerClass = getOptimizedFileManagerClass();
if (optimizedFileManagerClass != null) {
cp.add(getResourcePath(optimizedFileManagerClass)); // optimizedFileManager, if applicable
}
try {
final Class<?> cmdLineWrapper = Class.forName("com.intellij.rt.execution.CommandLineWrapper");
cp.add(getResourcePath(cmdLineWrapper)); // idea_rt.jar
}
catch (Throwable th) {
LOG.info(th);
}
final JavaCompiler systemCompiler = ToolProvider.getSystemJavaCompiler();
if (systemCompiler != null) {
try {
final String localJarPath = FileUtil.toSystemIndependentName(getResourcePath(systemCompiler.getClass()).getPath());
final String localJavaHome = FileUtil.toSystemIndependentName(SystemProperties.getJavaHome());
if (FileUtil.pathsEqual(localJavaHome, FileUtil.toSystemIndependentName(sdkHome))) {
cp.add(new File(localJarPath));
}
else {
// sdkHome is not the same as the sdk used to run this process
final File candidate = new File(sdkHome, "lib/tools.jar");
if (candidate.exists()) {
cp.add(candidate);
}
else {
// last resort
String relPath = FileUtil.getRelativePath(localJavaHome, localJarPath, '/');
if (relPath != null) {
if (relPath.contains("..")) {
relPath = FileUtil.getRelativePath(FileUtil.toSystemIndependentName(new File(localJavaHome).getParent()), localJarPath, '/');
}
if (relPath != null) {
final File targetFile = new File(sdkHome, relPath);
cp.add(targetFile); // tools.jar
}
}
}
}
}
catch (Throwable th) {
LOG.info(th);
}
}
return new ArrayList<File>(cp);
}
@Nullable
public static Class<StandardJavaFileManager> getOptimizedFileManagerClass() {
final Class<StandardJavaFileManager> aClass = OptimizedFileManagerClassHolder.managerClass;
if (aClass != null) {
return aClass;
}
return OptimizedFileManager17ClassHolder.managerClass;
}
public static File getResourcePath(Class aClass) {
return new File(PathManager.getResourceRoot(aClass, "/" + aClass.getName().replace('.', '/') + ".class"));
}
}
| deps cleanup
| jps/jps-builders/src/org/jetbrains/jps/server/ClasspathBootstrap.java | deps cleanup | <ide><path>ps/jps-builders/src/org/jetbrains/jps/server/ClasspathBootstrap.java
<ide> import org.jetbrains.asm4.ClassVisitor;
<ide> import org.jetbrains.asm4.ClassWriter;
<ide> import org.jetbrains.jps.MacroExpander;
<add>import org.jetbrains.jps.cmdline.BuildMain;
<ide> import org.jetbrains.jps.javac.JavacServer;
<ide>
<del>import javax.tools.JavaCompiler;
<del>import javax.tools.StandardJavaFileManager;
<del>import javax.tools.ToolProvider;
<add>import javax.tools.*;
<ide> import java.io.File;
<ide> import java.util.*;
<ide>
<ide>
<ide> public static List<File> getBuildProcessApplicationClasspath() {
<ide> final Set<File> cp = new LinkedHashSet<File>();
<del> cp.add(getResourcePath(Server.class));
<del> for (String path : PathManager.getUtilClassPath()) { cp.add(new File(path)); } // util
<add> cp.add(getResourcePath(BuildMain.class));
<add> for (String path : PathManager.getUtilClassPath()) { // util
<add> cp.add(new File(path));
<add> }
<ide> cp.add(getResourcePath(Message.class)); // protobuf
<ide> cp.add(getResourcePath(Version.class)); // netty
<ide> cp.add(getResourcePath(ClassWriter.class)); // asm |
|
Java | apache-2.0 | fe7f837fe7e5653f9055f24e114854786ee33b96 | 0 | azkaban/azkaban,azkaban/azkaban,HappyRay/azkaban,HappyRay/azkaban,HappyRay/azkaban,HappyRay/azkaban,azkaban/azkaban,HappyRay/azkaban,HappyRay/azkaban,azkaban/azkaban,azkaban/azkaban,azkaban/azkaban | /*
* Copyright 2019 LinkedIn Corp.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package azkaban.jobtype;
import azkaban.flow.CommonJobProperties;
import azkaban.jobExecutor.JavaProcessJob;
import azkaban.security.commons.HadoopSecurityManager;
import azkaban.utils.FileIOUtils;
import azkaban.utils.Props;
import com.google.common.collect.ImmutableList;
import java.util.List;
import org.apache.log4j.Logger;
/**
* Abstract Hadoop Java Process Job for Job PlugIn
*/
public abstract class AbstractHadoopJavaProcessJob extends JavaProcessJob implements IHadoopJob {
private final HadoopProxy hadoopProxy;
public AbstractHadoopJavaProcessJob(String jobid, Props sysProps, Props jobProps, Logger logger) {
super(jobid, sysProps, jobProps, logger);
this.hadoopProxy = new HadoopProxy(sysProps, jobProps, logger);
}
@Override
public void run() throws Exception {
try {
super.run();
} catch (Throwable t) {
t.printStackTrace();
getLog().error("caught error running the job", t);
throw t;
} finally {
hadoopProxy.cancelHadoopTokens(getLog());
}
}
@Override
public void setupHadoopJobProperties() {
String[] tagKeys = new String[]{
CommonJobProperties.EXEC_ID,
CommonJobProperties.FLOW_ID,
CommonJobProperties.PROJECT_NAME
};
getJobProps().put(
HadoopConfigurationInjector.INJECT_PREFIX + HadoopJobUtils.MAPREDUCE_JOB_TAGS,
HadoopJobUtils.constructHadoopTags(getJobProps(), tagKeys)
);
}
protected String getJVMJobTypeParameters() {
String args = "";
String jobTypeUserGlobalJVMArgs = getJobProps().getString(HadoopJobUtils.JOBTYPE_GLOBAL_JVM_ARGS, null);
if (jobTypeUserGlobalJVMArgs != null) {
args += " " + jobTypeUserGlobalJVMArgs;
}
String jobTypeSysGlobalJVMArgs = getSysProps().getString(HadoopJobUtils.JOBTYPE_GLOBAL_JVM_ARGS, null);
if (jobTypeSysGlobalJVMArgs != null) {
args += " " + jobTypeSysGlobalJVMArgs;
}
String jobTypeUserJVMArgs = getJobProps().getString(HadoopJobUtils.JOBTYPE_JVM_ARGS, null);
if (jobTypeUserJVMArgs != null) {
args += " " + jobTypeUserJVMArgs;
}
String jobTypeSysJVMArgs = getSysProps().getString(HadoopJobUtils.JOBTYPE_JVM_ARGS, null);
if (jobTypeSysJVMArgs != null) {
args += " " + jobTypeSysJVMArgs;
}
return args;
}
protected String getJVMProxySecureArgument() {
return hadoopProxy.getJVMArgument(getSysProps(), getJobProps(), getLog());
}
protected List<String> getAzkabanCommonClassPaths() {
return ImmutableList.<String>builder()
.add(FileIOUtils.getSourcePathFromClass(Props.class)) // add az-core jar classpath
.add(FileIOUtils.getSourcePathFromClass(JavaProcessJob.class)) // add az-common jar classpath
.add(FileIOUtils.getSourcePathFromClass(HadoopSecureHiveWrapper.class))
.add(FileIOUtils.getSourcePathFromClass(HadoopSecurityManager.class))
.build();
}
@Override
public Props appendExtraProps(Props props) {
HadoopJobUtils.addAdditionalNamenodesToPropsFromMRJob(props, getLog());
return props;
}
@Override
public HadoopProxy getHadoopProxy() {
return hadoopProxy;
}
}
| az-hadoop-jobtype-plugin/src/main/java/azkaban/jobtype/AbstractHadoopJavaProcessJob.java | /*
* Copyright 2019 LinkedIn Corp.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package azkaban.jobtype;
import azkaban.flow.CommonJobProperties;
import azkaban.jobExecutor.JavaProcessJob;
import azkaban.security.commons.HadoopSecurityManager;
import azkaban.utils.FileIOUtils;
import azkaban.utils.Props;
import com.google.common.collect.ImmutableList;
import java.util.List;
import org.apache.log4j.Logger;
/**
* Abstract Hadoop Java Process Job for Job PlugIn
*/
public abstract class AbstractHadoopJavaProcessJob extends JavaProcessJob implements IHadoopJob {
private final HadoopProxy hadoopProxy;
public AbstractHadoopJavaProcessJob(String jobid, Props sysProps, Props jobProps, Logger logger) {
super(jobid, sysProps, jobProps, logger);
this.hadoopProxy = new HadoopProxy(sysProps, jobProps, logger);
}
@Override
public void run() throws Exception {
try {
super.run();
} catch (Throwable t) {
t.printStackTrace();
getLog().error("caught error running the job", t);
throw t;
} finally {
hadoopProxy.cancelHadoopTokens(getLog());
}
}
@Override
public void setupHadoopJobProperties() {
String[] tagKeys = new String[]{
CommonJobProperties.EXEC_ID,
CommonJobProperties.FLOW_ID,
CommonJobProperties.PROJECT_NAME,
CommonJobProperties.JOB_ID,
CommonJobProperties.SUBMIT_USER
};
getJobProps().put(
HadoopConfigurationInjector.INJECT_PREFIX + HadoopJobUtils.MAPREDUCE_JOB_TAGS,
HadoopJobUtils.constructHadoopTags(getJobProps(), tagKeys)
);
}
protected String getJVMJobTypeParameters() {
String args = "";
String jobTypeUserGlobalJVMArgs = getJobProps().getString(HadoopJobUtils.JOBTYPE_GLOBAL_JVM_ARGS, null);
if (jobTypeUserGlobalJVMArgs != null) {
args += " " + jobTypeUserGlobalJVMArgs;
}
String jobTypeSysGlobalJVMArgs = getSysProps().getString(HadoopJobUtils.JOBTYPE_GLOBAL_JVM_ARGS, null);
if (jobTypeSysGlobalJVMArgs != null) {
args += " " + jobTypeSysGlobalJVMArgs;
}
String jobTypeUserJVMArgs = getJobProps().getString(HadoopJobUtils.JOBTYPE_JVM_ARGS, null);
if (jobTypeUserJVMArgs != null) {
args += " " + jobTypeUserJVMArgs;
}
String jobTypeSysJVMArgs = getSysProps().getString(HadoopJobUtils.JOBTYPE_JVM_ARGS, null);
if (jobTypeSysJVMArgs != null) {
args += " " + jobTypeSysJVMArgs;
}
return args;
}
protected String getJVMProxySecureArgument() {
return hadoopProxy.getJVMArgument(getSysProps(), getJobProps(), getLog());
}
protected List<String> getAzkabanCommonClassPaths() {
return ImmutableList.<String>builder()
.add(FileIOUtils.getSourcePathFromClass(Props.class)) // add az-core jar classpath
.add(FileIOUtils.getSourcePathFromClass(JavaProcessJob.class)) // add az-common jar classpath
.add(FileIOUtils.getSourcePathFromClass(HadoopSecureHiveWrapper.class))
.add(FileIOUtils.getSourcePathFromClass(HadoopSecurityManager.class))
.build();
}
@Override
public Props appendExtraProps(Props props) {
HadoopJobUtils.addAdditionalNamenodesToPropsFromMRJob(props, getLog());
return props;
}
@Override
public HadoopProxy getHadoopProxy() {
return hadoopProxy;
}
}
| Revert "Adding Job Name and Submit user to the job metadata which is visible in applicationTags on YARN (#2352)" (#2387)
This reverts commit 86d2115db35ff265875ed0c508d5203f5d7a537f. | az-hadoop-jobtype-plugin/src/main/java/azkaban/jobtype/AbstractHadoopJavaProcessJob.java | Revert "Adding Job Name and Submit user to the job metadata which is visible in applicationTags on YARN (#2352)" (#2387) | <ide><path>z-hadoop-jobtype-plugin/src/main/java/azkaban/jobtype/AbstractHadoopJavaProcessJob.java
<ide> String[] tagKeys = new String[]{
<ide> CommonJobProperties.EXEC_ID,
<ide> CommonJobProperties.FLOW_ID,
<del> CommonJobProperties.PROJECT_NAME,
<del> CommonJobProperties.JOB_ID,
<del> CommonJobProperties.SUBMIT_USER
<add> CommonJobProperties.PROJECT_NAME
<ide> };
<ide> getJobProps().put(
<ide> HadoopConfigurationInjector.INJECT_PREFIX + HadoopJobUtils.MAPREDUCE_JOB_TAGS, |
|
Java | apache-2.0 | c6817eedc99e7c827f38d76dfc37d4b01d3705ba | 0 | RedRoma/YelpJavaClient | /*
* Copyright 2016 RedRoma, Inc..
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package tech.redroma.yelp.oauth;
import com.google.gson.JsonObject;
import java.net.URL;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import tech.sirwellington.alchemy.http.AlchemyHttp;
import tech.sirwellington.alchemy.http.mock.AlchemyHttpMock;
import tech.sirwellington.alchemy.test.junit.runners.AlchemyTestRunner;
import tech.sirwellington.alchemy.test.junit.runners.GenerateInteger;
import tech.sirwellington.alchemy.test.junit.runners.GenerateString;
import tech.sirwellington.alchemy.test.junit.runners.GenerateURL;
import tech.sirwellington.alchemy.test.junit.runners.Repeat;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.not;
import static org.junit.Assert.assertThat;
import static tech.sirwellington.alchemy.test.junit.runners.GenerateInteger.Type.RANGE;
import static tech.sirwellington.alchemy.test.junit.runners.GenerateString.Type.ALPHANUMERIC;
import static tech.sirwellington.alchemy.test.junit.runners.GenerateString.Type.HEXADECIMAL;
/**
*
* @author SirWellington
*/
@Repeat(50)
@RunWith(AlchemyTestRunner.class)
public class RenewingProviderTest
{
@Mock
private AlchemyHttp http;
@GenerateURL
private URL authURL;
private RenewingProvider instance;
private RenewingProvider other;
@GenerateString(HEXADECIMAL)
private String cliendId;
@GenerateString(ALPHANUMERIC)
private String clientSecret;
@GenerateString(HEXADECIMAL)
private String otherClientId;
@GenerateString(ALPHANUMERIC)
private String otherClientSecret;
private JsonObject authResponse;
@GenerateInteger(value = RANGE, min = 1_000, max = 100_000)
private Integer expiration;
@GenerateString
private String token;
@Before
public void setUp() throws Exception
{
setupData();
setupMocks();
instance = new RenewingProvider(http, authURL, cliendId, clientSecret);
other = new RenewingProvider(http, authURL, otherClientId, otherClientSecret);
}
private void setupData() throws Exception
{
authResponse = new JsonObject();
authResponse.addProperty(RenewingProvider.Keys.EXPIRATION, expiration);
authResponse.addProperty(RenewingProvider.Keys.TOKEN, token);
}
private void setupMocks() throws Exception
{
http = AlchemyHttpMock.begin()
.whenPost()
.noBody()
.at(authURL)
.thenReturnJson(authResponse)
.build();
}
@Test
public void testGetToken()
{
String result = instance.getToken();
assertThat(result, is(token));
AlchemyHttpMock.verifyAllRequestsMade(http);
}
@Test
public void testHashCode()
{
RenewingProvider copy = new RenewingProvider(http, authURL, cliendId, clientSecret);
assertThat(copy.hashCode(), is(instance.hashCode()));
}
@Test
public void testHashCodeWhenDifferent()
{
assertThat(instance.hashCode(), not(other.hashCode()));
}
@Test
public void testEquals()
{
RenewingProvider copy = new RenewingProvider(http, authURL, cliendId, clientSecret);
assertThat(copy, is(instance));
}
@Test
public void testEqualsWhenIsDifferent()
{
assertThat(instance, not(other));
}
@Test
public void testToString()
{
String string = instance.toString();
assertThat(string, not(containsString(clientSecret)));
}
}
| src/test/java/tech/redroma/yelp/oauth/RenewingProviderTest.java | /*
* Copyright 2016 RedRoma, Inc..
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package tech.redroma.yelp.oauth;
import com.google.gson.JsonObject;
import java.net.URL;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import tech.sirwellington.alchemy.http.AlchemyHttp;
import tech.sirwellington.alchemy.http.mock.AlchemyHttpMock;
import tech.sirwellington.alchemy.test.junit.runners.AlchemyTestRunner;
import tech.sirwellington.alchemy.test.junit.runners.GenerateInteger;
import tech.sirwellington.alchemy.test.junit.runners.GenerateString;
import tech.sirwellington.alchemy.test.junit.runners.GenerateURL;
import tech.sirwellington.alchemy.test.junit.runners.Repeat;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.not;
import static org.junit.Assert.assertThat;
import static tech.sirwellington.alchemy.test.junit.runners.GenerateInteger.Type.RANGE;
import static tech.sirwellington.alchemy.test.junit.runners.GenerateString.Type.ALPHANUMERIC;
import static tech.sirwellington.alchemy.test.junit.runners.GenerateString.Type.HEXADECIMAL;
/**
*
* @author SirWellington
*/
@Repeat(50)
@RunWith(AlchemyTestRunner.class)
public class RenewingProviderTest
{
@Mock
private AlchemyHttp http;
@GenerateURL
private URL authURL;
private RenewingProvider instance;
private RenewingProvider other;
@GenerateString(HEXADECIMAL)
private String cliendId;
@GenerateString(ALPHANUMERIC)
private String clientSecret;
@GenerateString(HEXADECIMAL)
private String otherClientId;
@GenerateString(ALPHANUMERIC)
private String otherClientSecret;
private JsonObject authResponse;
@GenerateInteger(value = RANGE, min = 1_000, max = 100_000)
private Integer expiration;
@GenerateString
private String token;
@Before
public void setUp() throws Exception
{
setupData();
setupMocks();
instance = new RenewingProvider(http, authURL, cliendId, clientSecret);
other = new RenewingProvider(http, authURL, otherClientId, otherClientSecret);
}
private void setupData() throws Exception
{
authResponse = new JsonObject();
authResponse.addProperty(RenewingProvider.Keys.CLIENT_ID, cliendId);
authResponse.addProperty(RenewingProvider.Keys.CLIENT_SECRET, clientSecret);
authResponse.addProperty(RenewingProvider.Keys.GRANT_TYPE, "client_credentials");
}
private void setupMocks() throws Exception
{
http = AlchemyHttpMock.begin()
.whenPost()
.noBody()
.at(authURL)
.thenReturnJson(authResponse)
.build();
}
@Test
public void testGetToken()
{
}
@Test
public void testHashCode()
{
RenewingProvider copy = new RenewingProvider(http, authURL, cliendId, clientSecret);
assertThat(copy.hashCode(), is(instance.hashCode()));
}
@Test
public void testHashCodeWhenDifferent()
{
assertThat(instance.hashCode(), not(other.hashCode()));
}
@Test
public void testEquals()
{
RenewingProvider copy = new RenewingProvider(http, authURL, cliendId, clientSecret);
assertThat(copy, is(instance));
}
@Test
public void testEqualsWhenIsDifferent()
{
assertThat(instance, not(other));
}
@Test
public void testToString()
{
String string = instance.toString();
assertThat(string, not(containsString(clientSecret)));
}
}
| Adds additional Unit Tests | src/test/java/tech/redroma/yelp/oauth/RenewingProviderTest.java | Adds additional Unit Tests | <ide><path>rc/test/java/tech/redroma/yelp/oauth/RenewingProviderTest.java
<ide> private void setupData() throws Exception
<ide> {
<ide> authResponse = new JsonObject();
<del> authResponse.addProperty(RenewingProvider.Keys.CLIENT_ID, cliendId);
<del> authResponse.addProperty(RenewingProvider.Keys.CLIENT_SECRET, clientSecret);
<del> authResponse.addProperty(RenewingProvider.Keys.GRANT_TYPE, "client_credentials");
<add> authResponse.addProperty(RenewingProvider.Keys.EXPIRATION, expiration);
<add> authResponse.addProperty(RenewingProvider.Keys.TOKEN, token);
<ide> }
<ide>
<ide> private void setupMocks() throws Exception
<ide> @Test
<ide> public void testGetToken()
<ide> {
<add> String result = instance.getToken();
<add> assertThat(result, is(token));
<add>
<add> AlchemyHttpMock.verifyAllRequestsMade(http);
<ide> }
<ide>
<ide> @Test |
|
JavaScript | mit | 8d3656354263c40270a2498ac10006d5923e4dc7 | 0 | Jhorzyto/barbara.js,Jhorzyto/barbara.js | //Iniciando o modulo Barbara-JS
var barbaraJs = angular.module('Barbara-Js', []);
//Configurações para CORS
barbaraJs.config(function ($httpProvider) {
$httpProvider.defaults.useXDomain = true;
delete $httpProvider.defaults.headers.common['X-Requested-With'];
});
//Inicializador do barbaraJs
barbaraJs.run(function(){
//Animação para icone de carregamento
//CSS não minificado
//
//.glyphicon.spinning {
// animation: spin 1s infinite linear;
// -webkit-animation: spin2 1s infinite linear;
//}
//
//@keyframes spin {
// from { transform: scale(1) rotate(0deg); }
// to { transform: scale(1) rotate(360deg); }
//}
//
//@-webkit-keyframes spin2 {
// from { -webkit-transform: rotate(0deg); }
// to { -webkit-transform: rotate(360deg); }
//}
//
var loadingStyle = "<style type='text/css'>.glyphicon.spinning{animation:spin 1s infinite linear;-webkit-animation:spin2 1s infinite linear}@keyframes spin{from{transform:scale(1) rotate(0)}to{transform:scale(1) rotate(360deg)}}@-webkit-keyframes spin2{from{-webkit-transform:rotate(0)}to{-webkit-transform:rotate(360deg)}}</style>";
//Atribuindo o style ao cabeçalho do HTML
angular.element(document).find('head').prepend(loadingStyle);
});
//Factory request para requisições ajax.
barbaraJs.factory("$request", function($http){
//Gerar meta a partir do response
var getMetaResponse = function(response){
return {
code : response.status,
error_message : response.status == 200 ? 'Bad structure response!' : response.statusText
};
};
//Callback quando o response.status for entre 200 e 299.
var callbackSuccess = function(response, request, success, error){
//Verificar se algum callback de loaded
if(angular.isDefined(request.callbackLoad))
request.callbackLoad.loaded();
//Chamar callback de sucesso caso for escolhido para "não" verificar meta no response.data
if(!request.checkMeta)
success(response);
//Chamar callback de error caso o response.data não for um objeto (json)
else if(!angular.isObject(response.data))
error(getMetaResponse(response), response.status, response);
//Verificar se há meta no response.data e se existe existe o atributo code para validar a requisição
else if(angular.isObject(response.data.meta) && angular.isDefined(response.data.meta.code)){
//Verificar se o meta.code corresponde ao código de sucesso, então chama o callback de sucesso
if(response.data.meta.code >= 200 && response.data.meta.code <= 299)
success(response.data.data, response.data.meta, response);
//Caso o meta.code não estiver entre 200 a 299, retornar como callback de erro.
else
error(response.data.meta, response.status, response);
//Caso seja definidos callbacks adicionais para determinados meta.code, serão executados aqui após.
angular.forEach(request.callback, function(callback) {
//Verificar se o meta.code do response for igual ao metacode definido pelo callback adicional.
// Se for, executa o callback
if(this.code == callback.metaCode)
callback.callback(response.data.data, response.data.meta, response);
}, response.data.meta);
}
//Caso não atenda nenhum dos requisitos, retorna o callback de erro se for definido.
else
error(getMetaResponse(response), response.status, response);
};
//Callback quando o response.status for considerado como erro.
var callbackError = function(response, request, error){
//Verificar se algum callback de loaded
if(angular.isDefined(request.callbackLoad))
request.callbackLoad.loaded();
error(getMetaResponse(response), response.status, response);
};
//Atributos e métodos do $request
return {
//Lista de parametros ou dados para enviar
parameter : {},
//Lista de cabeçalho adicional, caso necessário
headers : {},
//Método de requisição atual
method : 'GET',
//URL para requisição
url : undefined,
//Lista de Callbacks adicionais
callback : [],
//Configurações adicional para requisição
callbackLoad : undefined,
//Verificar o meta no response.data
checkMeta : true,
//Configurações adicional para requisição
config : {},
//Mudar a verificação do meta no response.data
checkResponse : function(check){
//Verifica se o atributo é valido ou não.
this.checkMeta = check ? true : false;
return this;
},
//Adicionar callbacks adicionais para o meta.code
addCallback : function(metaCode, callback){
//Verficar se o metaCode é um número e o callback é função.
// Se a condição for valida, adiciona o callback na lista
if(angular.isNumber(metaCode) && angular.isFunction(callback))
this.callback.push({ metaCode : metaCode, callback : callback });
return this;
},
//Adicionar método de requisição
addMethod : function(method){
//Verificar se o method é string, para adicionar ao método de requisição
this.method = angular.isString(method) ? method : 'GET';
return this;
},
//Adicionar dados ou parametros para enviar
addData : function(param){
//Verificar se o param é objeto, para adicionar ao dados/param para enviar
this.parameter = angular.isObject(param) ? param : {};
return this;
},
//Adicionar cabeçalho adicional
addHeaders : function(headers){
//Verificar se o headers é objeto, para adicionar ao cabeçalho adicional
this.headers = angular.isObject(headers) ? headers : {};
return this;
},
//Adicionar callback de carregamento.
load : function(onLoading, loaded){
//Verificar se o onLoading é um objeto do bootstrap.loading
if(angular.isObject(onLoading)){
//Verificar se os callbacks loading e loaded existem
if(angular.isFunction(onLoading.loading) && angular.isFunction(onLoading.loaded)){
loaded = onLoading.loaded;
onLoading = onLoading.loading;
}
}
//Verificar se onLoading e loaded são callbacks validos!
if(!angular.isFunction(onLoading) || !angular.isFunction(loaded))
throw "Load Callback invalid!";
//atribuindo os callbacks à variavel callbackLoad
this.callbackLoad = {
onLoading : onLoading,
loaded : loaded
};
return this;
},
//Obter $request para requisição get
get : function(url){
//Verificar se o url é string para adicionar ao url atual.
this.url = angular.isString(url) ? url : this.url;
//Mudar o método de requisição
this.addMethod('GET');
//Ajustar as configurações adicionais da requisição
this.config.headers = this.headers;
//Retornar copia do objeto.
return angular.copy(this);
},
//Obter $request para requisição post
post : function(url){
//Verificar se o url é string para adicionar ao url atual.
this.url = angular.isString(url) ? url : this.url;
//Mudar o método de requisição
this.addMethod('POST');
//Ajustar as configurações adicionais da requisição
this.config.headers = this.headers;
//Retornar copia do objeto.
return angular.copy(this);
},
//Obter $request para requisição put
put : function(url){
//Verificar se o url é string para adicionar ao url atual.
this.url = angular.isString(url) ? url : this.url;
//Mudar o método de requisição
this.addMethod('PUT');
//Ajustar as configurações adicionais da requisição
this.config.headers = this.headers;
//Retornar copia do objeto.
return angular.copy(this);
},
//Obter $request para requisição delete
delete : function(url){
//Verificar se o url é string para adicionar ao url atual.
this.url = angular.isString(url) ? url : this.url;
//Mudar o método de requisição
this.addMethod('DELETE');
//Ajustar as configurações adicionais da requisição
this.config.headers = this.headers;
//Retornar copia do objeto.
return angular.copy(this);
},
//Enviar requisição
send : function(success, error){
//Atribuir a referencia do objeto para variavel request
var request = this;
//Verificar se o parametro success é uma função
if(!angular.isFunction(success))
throw "Success Callback invalid in $request!";
//Caso não exista callback de erro, criar um.
if(!angular.isFunction(error))
error = function(){};
//Verificar se algum url foi definido para continuar a requisição
if(!angular.isDefined(request.url))
throw "No url defined in the request methods!";
//Verificar se algum callback de loading
if(angular.isDefined(request.callbackLoad))
request.callbackLoad.onLoading();
//Escolher qual método executar de acordo com o armazenado em request.method
switch (request.method){
case 'GET' :
request.config.params = request.parameter;
$http.get(request.url, request.config)
.then(function(response){
callbackSuccess(response, request, success, error);
}, function(response){
callbackError(response, request, error);
});
break;
case 'POST' :
$http.post(request.url, request.parameter, request.config)
.then(function(response){
callbackSuccess(response, request, success, error);
}, function(response){
callbackError(response, request, error);
});
break;
case 'PUT' :
$http.put(request.url, request.parameter, request.config)
.then(function(response){
callbackSuccess(response, request, success, error);
}, function(response){
callbackError(response, request, error);
});
break;
case 'DELETE' :
request.config.data = request.parameter;
$http.delete(request.url, request.config)
.then(function(response){
callbackSuccess(response, request, success, error);
}, function(response){
callbackError(response, request, error);
});
break;
}
}
};
});
//Factory bootstrap para alguns recursos do framework css
barbaraJs.factory("bootstrap", function(){
return {
//Configuração do alert para diretiva (alert-bootstrap)
alert : function(){
return {
//Visibilidade da diretiva
show : false,
//Mudar Visibilidade da direitva
changeShow : function( show ){
this.show = angular.isDefined(show) ? show : !this.show;
},
//Tipo de alerta (info, success, danger, warning)
type : undefined,
//Mudar tipo de alerta
changeType : function(type){
this.type = type;
},
//Título do alerta
title : undefined,
//Mudar título do alerta
changeTitle : function(title){
this.title = title;
},
//Mensagem do alerta
message : undefined,
//Mudar mensagem do alerta
changeMessage : function(message){
this.message = angular.isString(message) ? message : this.message;
},
//Personalizar alerta para response de sucesso
responseSuccess : function(message){
if(angular.isString(message)) {
this.changeTitle('Parabéns!');
this.changeType('success');
this.changeMessage(message);
this.changeShow(true);
}
},
//Personalizar alerta para response de erro
responseError : function(meta){
this.changeTitle('Algo deu errado!');
this.changeType('danger');
if(angular.isDefined(meta.error_message) && angular.isString(meta.error_message)){
this.changeMessage(meta.error_message);
this.changeType('warning');
} else
this.changeMessage("Ocorreu um erro na requisição! Talvez o servidor " +
"esteja em manutenção.");
this.changeShow(true);
}
};
},
//Configuração do loading para diretiva (loading-bootstrap)
loading : function(){
return {
//Visibilidade da diretiva
show : false,
//Mudar Visibilidade da direitva
changeShow : function( show ){
this.show = angular.isDefined(show) ? show : !this.show;
},
//Mensagem de loading
message : 'Carregando...',
//Mudar mensagem do loading
changeMessage : function(message){
this.message = angular.isString(message) ? message : this.message;
},
//Mostrar mensagem de carregamento
onLoading : function(message){
this.message = angular.isString(message) ? message : this.message;
this.changeShow(true);
},
//Deixar de exibir mensagem de carregamento
loaded : function(){
this.changeShow(false);
},
//Obter loading trabalhado para o $request
getRequestLoad : function(message){
var loading = this;
return {
loading : function(){
loading.onLoading(message);
},
loaded : function(){
loading.loaded();
}
};
}
};
}
};
});
//Direitava alert-bootstrap
barbaraJs.directive('alertBootstrap', function () {
return {
restrict : 'A',
//Template html da diretiva
//HTML Template não minificado
//
//<div class='alert alert-{{alert.type}} alert-dismissible' role='alert' ng-if='alert.show'>
// <button type='button' class='close' ng-click='alert.changeShow()'>
// <span aria-hidden='true'>×</span>
// </button>
// <strong>{{alert.title}}</strong> {{alert.message}}
//</div>
//
template : "<div class='alert alert-{{alert.type}} alert-dismissible' role='alert' ng-if='alert.show'><button type='button' class='close' ng-click='alert.changeShow()'><span aria-hidden='true'>×</span></button><strong>{{alert.title}}</strong> {{alert.message}}</div>"
};
});
//Direitava loading-bootstrap
barbaraJs.directive('loadingBootstrap', function () {
return {
restrict : 'A',
//Template html da diretiva
//HTML Template não minificado
//
//<div class='progress' ng-if='loading.show'>
// <div class='progress-bar progress-bar-striped active' role='progressbar' style='width: 100%'>
// <i class='glyphicon glyphicon-refresh spinning'></i> <strong>{{loading.message}}</strong>
// </div>
//</div>
//
template : "<div class='progress' ng-if='loading.show'> <div class='progress-bar progress-bar-striped active' role='progressbar' style='width: 100%'><i class='glyphicon glyphicon-refresh spinning'></i> <strong>{{loading.message}}</strong></div></div>"
};
});
//Filtro para mostrar data de forma mais amigável ex: (há 7d, há 32sm, há 4a)
barbaraJs.filter("timeago", function () {
return function (time) {
//Variavel para hora atual
var local = new Date().getTime();
//Verificar se há algum dado
if (!time)
return "indefinido";
//Verificar se time é um objeto Date
if (angular.isDate(time))
time = time.getTime();
//Verificar se o time é um timestamp
else if (angular.isNumber(time))
time = new Date(time * 1000).getTime();
//Verificar se o time é uma data em string
else if (angular.isString(time))
time = new Date(time).getTime();
//Verificar se retornou uma data válida
if (!angular.isNumber(time))
return "Data invalida";
//Atributos de configurações para calculos
var offset = Math.abs((local - time) / 1000),
span = [],
MINUTE = 60,
HOUR = 3600,
DAY = 86400,
WEEK = 604800,
YEAR = 31556926;
//Calculos para determinar o tempo decorrido
if (offset <= MINUTE) span = [ '', 'agora' ];
else if (offset < (MINUTE * 60)) span = [ Math.round(Math.abs(offset / MINUTE)), 'm' ];
else if (offset < (HOUR * 24)) span = [ Math.round(Math.abs(offset / HOUR)), 'h' ];
else if (offset < (DAY * 7)) span = [ Math.round(Math.abs(offset / DAY)), 'd' ];
else if (offset < (WEEK * 52)) span = [ Math.round(Math.abs(offset / WEEK)), 'sm' ];
else if (offset < (YEAR * 10)) span = [ Math.round(Math.abs(offset / YEAR)), 'a' ];
else span = [ '', '...' ];
//Transformar array em string separado por espaço
span = span.join('');
//Retornar data em formato decorrido
return (time <= local) ? 'há ' + span + '' : span;
}
});
//Filtro para truncar texto com opção de ignorar dinamicamente
barbaraJs.filter('cuttext', function () {
return function (value, ignoreFilter, max, tail) {
//Verificar se o valor é valido
if (!value || !angular.isString(value))
return '';
//Verificar se o tamanho maximo do texto é um número valido, caso contrario retorna o valor original
if (!max || !angular.isNumber(max))
return value;
//Converter maximo para inteiro
max = parseInt(max, 10);
//Verificar se o tamanho do texto é menor que o tamanho máximo ou se o filtro foi ignorado
//Caso a condição seja verdadeira, retornar o valor original
if (value.length <= max || ignoreFilter)
return value;
//Trunca o texto para o tamanho definido
value = value.substr(0, max);
//Verifica se o ultimo elemento do texto é um espaço
var lastspace = value.lastIndexOf(' ');
//Caso o ultimo elemento seja um espaço, ele é truncado novamente
if (lastspace != -1)
value = value.substr(0, lastspace);
//Retornar texto formatado
return value + (tail || ' …');
};
}); | barbarajs.js | //Iniciando o modulo Barbara-JS
var barbaraJs = angular.module('Barbara-Js', []);
//Configurações para CORS
barbaraJs.config( function ($httpProvider) {
$httpProvider.defaults.useXDomain = true;
delete $httpProvider.defaults.headers.common['X-Requested-With'];
});
//Factory request para requisições ajax.
barbaraJs.factory("$request", function($http){
//Gerar meta a partir do response
var getMetaResponse = function(response){
return {
code : response.status,
error_message : response.statusText
};
};
//Callback quando o response.status for entre 200 e 299.
var callbackSuccess = function(response, request, success, error){
//Chamar callback de sucesso caso for escolhido para "não" verificar meta no response.data
if(!request.checkMeta)
success(response);
//Chamar callback de error caso o response.data não for um objeto (json)
else if(!angular.isObject(response.data))
error(getMetaResponse(response), response.status, response);
//Verificar se há meta no response.data e se existe existe o atributo code para validar a requisição
else if(angular.isObject(response.data.meta) && angular.isDefined(response.data.meta.code)){
//Verificar se o meta.code corresponde ao código de sucesso, então chama o callback de sucesso
if(response.data.meta.code >= 200 && response.data.meta.code <= 299)
success(response.data.data, response.data.meta, response);
//Caso o meta.code não estiver entre 200 a 299, retornar como callback de erro.
else
error(response.data.meta, response.status, response);
//Caso seja definidos callbacks adicionais para determinados meta.code, serão executados aqui após.
angular.forEach(request.callback, function(callback) {
//Verificar se o meta.code do response for igual ao metacode definido pelo callback adicional.
// Se for, executa o callback
if(this.code == callback.metaCode)
callback.callback(response.data.data, response.data.meta, response);
}, response.data.meta);
}
//Caso não atenda nenhum dos requisitos, retorna o callback de erro se for definido.
else
error(getMetaResponse(response), response.status, response);
};
//Callback quando o response.status for considerado como erro.
var callbackError = function(response, error){
error(getMetaResponse(response), response.status, response);
};
//Atributos e métodos do $request
return {
//Lista de parametros ou dados para enviar
parameter : {},
//Lista de cabeçalho adicional, caso necessário
headers : {},
//Método de requisição atual
method : 'GET',
//URL para requisição
url : undefined,
//Lista de Callbacks adicionais
callback : [],
//Verificar o meta no response.data
checkMeta : true,
//Configurações adicional para requisição
config : {},
//Mudar a verificação do meta no response.data
checkResponse : function(check){
//Verifica se o atributo é valido ou não.
this.checkMeta = check ? true : false;
return this;
},
//Adicionar callbacks adicionais para o meta.code
addCallback : function(metaCode, callback){
//Verficar se o metaCode é um número e o callback é função.
// Se a condição for valida, adiciona o callback na lista
if(angular.isNumber(metaCode) && angular.isFunction(callback))
this.callback.push({ metaCode : metaCode, callback : callback });
return this;
},
//Adicionar método de requisição
addMethod : function(method){
//Verificar se o method é string, para adicionar ao método de requisição
this.method = angular.isString(method) ? method : 'GET';
return this;
},
//Adicionar dados ou parametros para enviar
addData : function(param){
//Verificar se o param é objeto, para adicionar ao dados/param para enviar
this.parameter = angular.isObject(param) ? param : {};
return this;
},
//Adicionar cabeçalho adicional
addHeaders : function(headers){
//Verificar se o headers é objeto, para adicionar ao cabeçalho adicional
this.headers = angular.isObject(headers) ? headers : {};
return this;
},
//Obter $request para requisição get
get : function(url){
//Verificar se o url é string para adicionar ao url atual.
this.url = angular.isString(url) ? url : this.url;
//Mudar o método de requisição
this.addMethod('GET');
//Ajustar as configurações adicionais da requisição
this.config = {
headers : this.headers
};
this.config.params = this.parameter;
//Retornar copia do objeto.
return angular.copy(this);
},
//Obter $request para requisição post
post : function(url){
//Verificar se o url é string para adicionar ao url atual.
this.url = angular.isString(url) ? url : this.url;
//Mudar o método de requisição
this.addMethod('POST');
//Ajustar as configurações adicionais da requisição
this.config = {
headers : this.headers
};
//Retornar copia do objeto.
return angular.copy(this);
},
//Obter $request para requisição put
put : function(url){
//Verificar se o url é string para adicionar ao url atual.
this.url = angular.isString(url) ? url : this.url;
//Mudar o método de requisição
this.addMethod('PUT');
//Ajustar as configurações adicionais da requisição
this.config = {
headers : this.headers
};
//Retornar copia do objeto.
return angular.copy(this);
},
//Obter $request para requisição delete
delete : function(url){
//Verificar se o url é string para adicionar ao url atual.
this.url = angular.isString(url) ? url : this.url;
//Mudar o método de requisição
this.addMethod('DELETE');
//Ajustar as configurações adicionais da requisição
this.config = {
headers : this.headers
};
this.config.params = this.parameter;
//Retornar copia do objeto.
return angular.copy(this);
},
//Enviar requisição
send : function(success, error){
//Atribuir a referencia do objeto para variavel request
var request = this;
//Verificar se o parametro success é uma função
if(!angular.isFunction(success))
throw "Success Callback invalid in $request!";
//Caso não exista callback de erro, criar um.
if(!angular.isFunction(error))
error = function(){};
//Verificar se algum url foi definido para continuar a requisição
if(!angular.isDefined(request.url))
throw "No url defined in the request methods!";
//Escolher qual método executar de acordo com o armazenado em request.method
switch (request.method){
case 'GET' :
$http.get(request.url, request.config)
.then(function(response){
callbackSuccess(response, request, success, error);
}, function(response){
callbackError(response, error);
});
break;
case 'POST' :
$http.post(request.url, request.parameter, request.config)
.then(function(response){
callbackSuccess(response, request, success, error);
}, function(response){
callbackError(response, error);
});
break;
case 'PUT' :
$http.put(request.url, request.parameter, request.config)
.then(function(response){
callbackSuccess(response, request, success, error);
}, function(response){
callbackError(response, error);
});
break;
case 'DELETE' :
$http.delete(request.url, request.config)
.then(function(response){
callbackSuccess(response, request, success, error);
}, function(response){
callbackError(response, error);
});
break;
}
}
};
});
//Factory bootstrap para alguns recursos do framework css
barbaraJs.factory("bootstrap", function(){
return {
//Configuração do alert para diretiva (alert-bootstrap)
alert : function(){
return {
//Visibilidade da diretiva
show : false,
//Mudar Visibilidade da direitva
changeShow : function( show ){
this.show = angular.isDefined(show) ? show : !this.show;
},
//Tipo de alerta (info, success, danger, warning)
type : undefined,
//Mudar tipo de alerta
changeType : function(type){
this.type = type;
},
//Título do alerta
title : undefined,
//Mudar título do alerta
changeTitle : function(title){
this.title = title;
},
//Mensagem do alerta
message : undefined,
//Mudar mensagem do alerta
changeMessage : function(message){
this.message = message;
},
//Personalizar alerta para response de sucesso
responseSuccess : function(message){
if(angular.isString(message)) {
this.changeTitle('Parabéns!');
this.changeType('success');
this.changeMessage(message);
this.changeShow(true);
}
},
//Personalizar alerta para response de erro
responseError : function(meta){
this.changeTitle('Algo deu errado!');
this.changeType('danger');
if(angular.isDefined(meta.error_message) && angular.isString(meta.error_message)){
this.changeMessage(meta.error_message);
this.changeType('warning');
} else
this.changeMessage("Ocorreu um erro na requisição! Talvez o servidor " +
"esteja em manutenção.");
this.changeShow(true);
}
};
}
};
});
//Direitava alert-bootstrap
barbaraJs.directive('alertBootstrap', function () {
return {
restrict : 'A',
//Template html da diretiva
template : "<div class='alert alert-{{alert.type}} alert-dismissible' role='alert' ng-if='alert.show'>"
+ "<button type='button' class='close' ng-click='alert.changeShow()'>"
+ "<span aria-hidden='true'>×</span>"
+ "</button>"
+ "<strong>{{alert.title}}</strong> {{alert.message}}"
+ "</div>"
};
});
//Filtro para mostrar data de forma mais amigável ex: (há 7d, há 32sm, há 4a)
barbaraJs.filter("timeago", function () {
return function (time) {
//Variavel para hora atual
var local = new Date().getTime();
//Verificar se há algum dado
if (!time)
return "indefinido";
//Verificar se time é um objeto Date
if (angular.isDate(time))
time = time.getTime();
//Verificar se o time é um timestamp
else if (angular.isNumber(time))
time = new Date(time * 1000).getTime();
//Verificar se o time é uma data em string
else if (angular.isString(time))
time = new Date(time).getTime();
//Verificar se retornou uma data válida
if (!angular.isNumber(time))
return "Data invalida";
//Atributos de configurações para calculos
var offset = Math.abs((local - time) / 1000),
span = [],
MINUTE = 60,
HOUR = 3600,
DAY = 86400,
WEEK = 604800,
YEAR = 31556926;
//Calculos para determinar o tempo decorrido
if (offset <= MINUTE) span = [ '', 'agora' ];
else if (offset < (MINUTE * 60)) span = [ Math.round(Math.abs(offset / MINUTE)), 'm' ];
else if (offset < (HOUR * 24)) span = [ Math.round(Math.abs(offset / HOUR)), 'h' ];
else if (offset < (DAY * 7)) span = [ Math.round(Math.abs(offset / DAY)), 'd' ];
else if (offset < (WEEK * 52)) span = [ Math.round(Math.abs(offset / WEEK)), 'sm' ];
else if (offset < (YEAR * 10)) span = [ Math.round(Math.abs(offset / YEAR)), 'a' ];
else span = [ '', '...' ];
//Transformar array em string separado por espaço
span = span.join('');
//Retornar data em formato decorrido
return (time <= local) ? 'há ' + span + '' : span;
}
});
//Filtro para truncar texto com opção de ignorar dinamicamente
barbaraJs.filter('cuttext', function () {
return function (value, ignoreFilter, max, tail) {
//Verificar se o valor é valido
if (!value || !angular.isString(value))
return '';
//Verificar se o tamanho maximo do texto é um número valido, caso contrario retorna o valor original
if (!max || !angular.isNumber(max))
return value;
//Converter maximo para inteiro
max = parseInt(max, 10);
//Verificar se o tamanho do texto é menor que o tamanho máximo ou se o filtro foi ignorado
//Caso a condição seja verdadeira, retornar o valor original
if (value.length <= max || ignoreFilter)
return value;
//Trunca o texto para o tamanho definido
value = value.substr(0, max);
//Verifica se o ultimo elemento do texto é um espaço
var lastspace = value.lastIndexOf(' ');
//Caso o ultimo elemento seja um espaço, ele é truncado novamente
if (lastspace != -1)
value = value.substr(0, lastspace);
//Retornar texto formatado
return value + (tail || ' …');
};
}); | Melhorias no factory em geral. Adicionado opção de dois callbacks para executar antes de requisitar e após receber alguma coisa. Ajustado o http delete para enviar dados no corpo da requisição.
| barbarajs.js | Melhorias no factory em geral. Adicionado opção de dois callbacks para executar antes de requisitar e após receber alguma coisa. Ajustado o http delete para enviar dados no corpo da requisição. | <ide><path>arbarajs.js
<ide> var barbaraJs = angular.module('Barbara-Js', []);
<ide>
<ide> //Configurações para CORS
<del>barbaraJs.config( function ($httpProvider) {
<add>barbaraJs.config(function ($httpProvider) {
<ide> $httpProvider.defaults.useXDomain = true;
<ide> delete $httpProvider.defaults.headers.common['X-Requested-With'];
<add>});
<add>
<add>//Inicializador do barbaraJs
<add>barbaraJs.run(function(){
<add> //Animação para icone de carregamento
<add> //CSS não minificado
<add> //
<add> //.glyphicon.spinning {
<add> // animation: spin 1s infinite linear;
<add> // -webkit-animation: spin2 1s infinite linear;
<add> //}
<add> //
<add> //@keyframes spin {
<add> // from { transform: scale(1) rotate(0deg); }
<add> // to { transform: scale(1) rotate(360deg); }
<add> //}
<add> //
<add> //@-webkit-keyframes spin2 {
<add> // from { -webkit-transform: rotate(0deg); }
<add> // to { -webkit-transform: rotate(360deg); }
<add> //}
<add> //
<add> var loadingStyle = "<style type='text/css'>.glyphicon.spinning{animation:spin 1s infinite linear;-webkit-animation:spin2 1s infinite linear}@keyframes spin{from{transform:scale(1) rotate(0)}to{transform:scale(1) rotate(360deg)}}@-webkit-keyframes spin2{from{-webkit-transform:rotate(0)}to{-webkit-transform:rotate(360deg)}}</style>";
<add>
<add> //Atribuindo o style ao cabeçalho do HTML
<add> angular.element(document).find('head').prepend(loadingStyle);
<ide> });
<ide>
<ide> //Factory request para requisições ajax.
<ide> var getMetaResponse = function(response){
<ide> return {
<ide> code : response.status,
<del> error_message : response.statusText
<add> error_message : response.status == 200 ? 'Bad structure response!' : response.statusText
<ide> };
<ide> };
<ide>
<ide> //Callback quando o response.status for entre 200 e 299.
<ide> var callbackSuccess = function(response, request, success, error){
<add> //Verificar se algum callback de loaded
<add> if(angular.isDefined(request.callbackLoad))
<add> request.callbackLoad.loaded();
<add>
<ide> //Chamar callback de sucesso caso for escolhido para "não" verificar meta no response.data
<ide> if(!request.checkMeta)
<ide> success(response);
<ide> };
<ide>
<ide> //Callback quando o response.status for considerado como erro.
<del> var callbackError = function(response, error){
<add> var callbackError = function(response, request, error){
<add> //Verificar se algum callback de loaded
<add> if(angular.isDefined(request.callbackLoad))
<add> request.callbackLoad.loaded();
<add>
<ide> error(getMetaResponse(response), response.status, response);
<ide> };
<ide>
<ide>
<ide> //Lista de Callbacks adicionais
<ide> callback : [],
<add>
<add> //Configurações adicional para requisição
<add> callbackLoad : undefined,
<ide>
<ide> //Verificar o meta no response.data
<ide> checkMeta : true,
<ide> return this;
<ide> },
<ide>
<add> //Adicionar callback de carregamento.
<add> load : function(onLoading, loaded){
<add>
<add> //Verificar se o onLoading é um objeto do bootstrap.loading
<add> if(angular.isObject(onLoading)){
<add> //Verificar se os callbacks loading e loaded existem
<add> if(angular.isFunction(onLoading.loading) && angular.isFunction(onLoading.loaded)){
<add> loaded = onLoading.loaded;
<add> onLoading = onLoading.loading;
<add> }
<add> }
<add>
<add> //Verificar se onLoading e loaded são callbacks validos!
<add> if(!angular.isFunction(onLoading) || !angular.isFunction(loaded))
<add> throw "Load Callback invalid!";
<add>
<add> //atribuindo os callbacks à variavel callbackLoad
<add> this.callbackLoad = {
<add> onLoading : onLoading,
<add> loaded : loaded
<add> };
<add>
<add> return this;
<add> },
<add>
<ide> //Obter $request para requisição get
<ide> get : function(url){
<ide> //Verificar se o url é string para adicionar ao url atual.
<ide> //Mudar o método de requisição
<ide> this.addMethod('GET');
<ide> //Ajustar as configurações adicionais da requisição
<del> this.config = {
<del> headers : this.headers
<del> };
<del> this.config.params = this.parameter;
<add> this.config.headers = this.headers;
<ide> //Retornar copia do objeto.
<ide> return angular.copy(this);
<ide> },
<ide> //Mudar o método de requisição
<ide> this.addMethod('POST');
<ide> //Ajustar as configurações adicionais da requisição
<del> this.config = {
<del> headers : this.headers
<del> };
<add> this.config.headers = this.headers;
<ide> //Retornar copia do objeto.
<ide> return angular.copy(this);
<ide> },
<ide> //Mudar o método de requisição
<ide> this.addMethod('PUT');
<ide> //Ajustar as configurações adicionais da requisição
<del> this.config = {
<del> headers : this.headers
<del> };
<add> this.config.headers = this.headers;
<ide> //Retornar copia do objeto.
<ide> return angular.copy(this);
<ide> },
<ide> //Mudar o método de requisição
<ide> this.addMethod('DELETE');
<ide> //Ajustar as configurações adicionais da requisição
<del> this.config = {
<del> headers : this.headers
<del> };
<del> this.config.params = this.parameter;
<add> this.config.headers = this.headers;
<ide> //Retornar copia do objeto.
<ide> return angular.copy(this);
<ide> },
<ide> if(!angular.isDefined(request.url))
<ide> throw "No url defined in the request methods!";
<ide>
<add> //Verificar se algum callback de loading
<add> if(angular.isDefined(request.callbackLoad))
<add> request.callbackLoad.onLoading();
<add>
<ide> //Escolher qual método executar de acordo com o armazenado em request.method
<ide> switch (request.method){
<ide>
<ide> case 'GET' :
<add> request.config.params = request.parameter;
<ide> $http.get(request.url, request.config)
<ide> .then(function(response){
<ide> callbackSuccess(response, request, success, error);
<ide> }, function(response){
<del> callbackError(response, error);
<add> callbackError(response, request, error);
<ide> });
<ide> break;
<ide>
<ide> .then(function(response){
<ide> callbackSuccess(response, request, success, error);
<ide> }, function(response){
<del> callbackError(response, error);
<add> callbackError(response, request, error);
<ide> });
<ide> break;
<ide>
<ide> .then(function(response){
<ide> callbackSuccess(response, request, success, error);
<ide> }, function(response){
<del> callbackError(response, error);
<add> callbackError(response, request, error);
<ide> });
<ide> break;
<ide>
<ide> case 'DELETE' :
<add> request.config.data = request.parameter;
<ide> $http.delete(request.url, request.config)
<ide> .then(function(response){
<ide> callbackSuccess(response, request, success, error);
<ide> }, function(response){
<del> callbackError(response, error);
<add> callbackError(response, request, error);
<ide> });
<ide> break;
<ide> }
<ide>
<ide> //Mudar mensagem do alerta
<ide> changeMessage : function(message){
<del> this.message = message;
<add> this.message = angular.isString(message) ? message : this.message;
<ide> },
<ide>
<ide> //Personalizar alerta para response de sucesso
<ide> this.changeShow(true);
<ide> }
<ide> };
<add> },
<add>
<add> //Configuração do loading para diretiva (loading-bootstrap)
<add> loading : function(){
<add> return {
<add> //Visibilidade da diretiva
<add> show : false,
<add>
<add> //Mudar Visibilidade da direitva
<add> changeShow : function( show ){
<add> this.show = angular.isDefined(show) ? show : !this.show;
<add> },
<add>
<add> //Mensagem de loading
<add> message : 'Carregando...',
<add>
<add> //Mudar mensagem do loading
<add> changeMessage : function(message){
<add> this.message = angular.isString(message) ? message : this.message;
<add> },
<add>
<add> //Mostrar mensagem de carregamento
<add> onLoading : function(message){
<add> this.message = angular.isString(message) ? message : this.message;
<add> this.changeShow(true);
<add> },
<add>
<add> //Deixar de exibir mensagem de carregamento
<add> loaded : function(){
<add> this.changeShow(false);
<add> },
<add>
<add> //Obter loading trabalhado para o $request
<add> getRequestLoad : function(message){
<add> var loading = this;
<add> return {
<add> loading : function(){
<add> loading.onLoading(message);
<add> },
<add> loaded : function(){
<add> loading.loaded();
<add> }
<add> };
<add> }
<add> };
<ide> }
<ide> };
<ide> });
<ide> return {
<ide> restrict : 'A',
<ide> //Template html da diretiva
<del> template : "<div class='alert alert-{{alert.type}} alert-dismissible' role='alert' ng-if='alert.show'>"
<del> + "<button type='button' class='close' ng-click='alert.changeShow()'>"
<del> + "<span aria-hidden='true'>×</span>"
<del> + "</button>"
<del> + "<strong>{{alert.title}}</strong> {{alert.message}}"
<del> + "</div>"
<add> //HTML Template não minificado
<add> //
<add> //<div class='alert alert-{{alert.type}} alert-dismissible' role='alert' ng-if='alert.show'>
<add> // <button type='button' class='close' ng-click='alert.changeShow()'>
<add> // <span aria-hidden='true'>×</span>
<add> // </button>
<add> // <strong>{{alert.title}}</strong> {{alert.message}}
<add> //</div>
<add> //
<add> template : "<div class='alert alert-{{alert.type}} alert-dismissible' role='alert' ng-if='alert.show'><button type='button' class='close' ng-click='alert.changeShow()'><span aria-hidden='true'>×</span></button><strong>{{alert.title}}</strong> {{alert.message}}</div>"
<add> };
<add>});
<add>
<add>//Direitava loading-bootstrap
<add>barbaraJs.directive('loadingBootstrap', function () {
<add> return {
<add> restrict : 'A',
<add> //Template html da diretiva
<add> //HTML Template não minificado
<add> //
<add> //<div class='progress' ng-if='loading.show'>
<add> // <div class='progress-bar progress-bar-striped active' role='progressbar' style='width: 100%'>
<add> // <i class='glyphicon glyphicon-refresh spinning'></i> <strong>{{loading.message}}</strong>
<add> // </div>
<add> //</div>
<add> //
<add> template : "<div class='progress' ng-if='loading.show'> <div class='progress-bar progress-bar-striped active' role='progressbar' style='width: 100%'><i class='glyphicon glyphicon-refresh spinning'></i> <strong>{{loading.message}}</strong></div></div>"
<ide> };
<ide> });
<ide> |
|
Java | apache-2.0 | a8f6b626db89cf44188c8d3cc7a5833267f15e9e | 0 | hamnis/funclite | /*
* Copyright 2013 Erlend Hamnaberg
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.hamnaberg.funclite;
import java.util.Iterator;
import java.util.Objects;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.Stream;
public abstract class Optional<A> implements Iterable<A> {
public static None<Object> NONE = new None<Object>();
Optional() {
}
public abstract A get();
public abstract boolean isSome();
@Override
public abstract int hashCode();
@Override
public abstract boolean equals(Object obj);
public final boolean isNone() {
return !isSome();
}
public boolean isPresent() { return isSome(); }
public boolean isEmpty() { return isNone(); }
public final <B> Optional<B> map(Function<A, B> f) {
if (isNone()) {
return none();
}
else {
return new Some<>(f.apply(get()));
}
}
public final <B> Optional<B> flatMap(Function<A, Optional<B>> f) {
if (isNone()) {
return none();
}
else {
return Objects.requireNonNull(f.apply(get()), "Optional.flatMap produced null");
}
}
public Stream<A> stream() {
return CollectionOps.stream(this);
}
public final void foreach(Consumer<A> e) {
CollectionOps.foreach(this, e);
}
public final Optional<A> filter(Predicate<A> input) {
if (isSome() && input.test(get())) {
return this;
}
else {
return none();
}
}
public boolean forall(Predicate<A> input) {
return CollectionOps.forall(this, input);
}
public boolean exists(Predicate<A> input) {
return CollectionOps.exists(this, input);
}
public boolean contains(A value) {
return exists(v -> v.equals(value));
}
public static <A> Optional<A> fromNullable(A value) {
return value != null ? some(value) : Optional.<A>none();
}
public static <A> Optional<A> ofNullable(A value) {
return fromNullable(value);
}
public static <A> Optional<A> some(A value) {
return new Some<A>(Objects.requireNonNull(value));
}
public static <A> Optional<A> of(A value) {
return new Some<A>(Objects.requireNonNull(value));
}
@SuppressWarnings("unchecked")
public static <A> Optional<A> none() {
return (Optional<A>) NONE;
}
@SuppressWarnings("unchecked")
public static <A> Optional<A> empty() {
return none();
}
public A orNull() {
return isSome() ? get() : null;
}
public A getOrElse(A orElse) {
return isSome() ? get() : orElse;
}
public A getOrElse(Supplier<A> orElse) {
return isSome() ? get() : orElse.get();
}
public Optional<A> or(Optional<A> orElse) {
return isSome() ? this : orElse;
}
public <B> B fold(Supplier<B> noneF, Function<A, B> someF) {
return isNone() ? noneF.get() : someF.apply(get());
}
@Override
public final Iterator<A> iterator() {
return new Iterator<A>() {
private volatile boolean used = false;
@Override
public boolean hasNext() {
return !used && isSome();
}
@Override
public A next() {
A value = get();
used = true;
return value;
}
@Override
public void remove() {
throw new UnsupportedOperationException("Not supported");
}
};
}
}
final class Some<A> extends Optional<A> {
private final A value;
Some(A value) {
this.value = value;
}
@Override
public A get() {
return value;
}
@Override
public boolean isSome() {
return true;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Some some = (Some) o;
if (value != null ? !value.equals(some.value) : some.value != null) return false;
return true;
}
@Override
public int hashCode() {
return value != null ? value.hashCode() : 0;
}
@Override
public String toString() {
return String.format("Some{%s}", value);
}
}
final class None<A> extends Optional<A> {
@Override
public A get() {
throw new UnsupportedOperationException("Cannot get from None");
}
@Override
public boolean equals(Object obj) {
return obj instanceof None;
}
@Override
public int hashCode() {
return 31;
}
@Override
public boolean isSome() {
return false;
}
@Override
public String toString() {
return "None";
}
}
| src/main/java/net/hamnaberg/funclite/Optional.java | /*
* Copyright 2013 Erlend Hamnaberg
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.hamnaberg.funclite;
import java.util.Iterator;
import java.util.Objects;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.Stream;
public abstract class Optional<A> implements Iterable<A> {
public static None<Object> NONE = new None<Object>();
Optional() {
}
public abstract A get();
public abstract boolean isSome();
@Override
public abstract int hashCode();
@Override
public abstract boolean equals(Object obj);
public final boolean isNone() {
return !isSome();
}
public final <B> Optional<B> map(Function<A, B> f) {
if (isNone()) {
return none();
}
else {
return fromNullable(f.apply(get()));
}
}
public final <B> Optional<B> flatMap(Function<A, Optional<B>> f) {
if (isNone()) {
return none();
}
else {
return Objects.requireNonNull(f.apply(get()), "Optional.flatMap produced null");
}
}
public Stream<A> stream() {
return CollectionOps.stream(this);
}
public final void foreach(Consumer<A> e) {
CollectionOps.foreach(this, e);
}
public final Optional<A> filter(Predicate<A> input) {
if (isSome() && input.test(get())) {
return this;
}
else {
return none();
}
}
public boolean forall(Predicate<A> input) {
return CollectionOps.forall(this, input);
}
public boolean exists(Predicate<A> input) {
return CollectionOps.exists(this, input);
}
public boolean contains(A value) {
return exists(v -> v.equals(value));
}
public static <A> Optional<A> fromNullable(A value) {
return value != null ? some(value) : Optional.<A>none();
}
public static <A> Optional<A> some(A value) {
return new Some<A>(Objects.requireNonNull(value));
}
@SuppressWarnings("unchecked")
public static <A> Optional<A> none() {
return (Optional<A>) NONE;
}
public A orNull() {
return isSome() ? get() : null;
}
public A getOrElse(A orElse) {
return isSome() ? get() : orElse;
}
public A getOrElse(Supplier<A> orElse) {
return isSome() ? get() : orElse.get();
}
public Optional<A> or(Optional<A> orElse) {
return isSome() ? this : orElse;
}
public <B> B fold(Supplier<B> noneF, Function<A, B> someF) {
return isNone() ? noneF.get() : someF.apply(get());
}
@Override
public final Iterator<A> iterator() {
return new Iterator<A>() {
private volatile boolean used = false;
@Override
public boolean hasNext() {
return !used && isSome();
}
@Override
public A next() {
A value = get();
used = true;
return value;
}
@Override
public void remove() {
throw new UnsupportedOperationException("Not supported");
}
};
}
}
final class Some<A> extends Optional<A> {
private final A value;
Some(A value) {
this.value = value;
}
@Override
public A get() {
return value;
}
@Override
public boolean isSome() {
return true;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Some some = (Some) o;
if (value != null ? !value.equals(some.value) : some.value != null) return false;
return true;
}
@Override
public int hashCode() {
return value != null ? value.hashCode() : 0;
}
@Override
public String toString() {
return String.format("Some{%s}", value);
}
}
final class None<A> extends Optional<A> {
@Override
public A get() {
throw new UnsupportedOperationException("Cannot get from None");
}
@Override
public boolean equals(Object obj) {
return obj instanceof None;
}
@Override
public int hashCode() {
return 31;
}
@Override
public boolean isSome() {
return false;
}
@Override
public String toString() {
return "None";
}
}
| Obey functor laws, More API compability with Java 8
| src/main/java/net/hamnaberg/funclite/Optional.java | Obey functor laws, More API compability with Java 8 | <ide><path>rc/main/java/net/hamnaberg/funclite/Optional.java
<ide> return !isSome();
<ide> }
<ide>
<add> public boolean isPresent() { return isSome(); }
<add>
<add> public boolean isEmpty() { return isNone(); }
<add>
<ide> public final <B> Optional<B> map(Function<A, B> f) {
<ide> if (isNone()) {
<ide> return none();
<ide> }
<ide> else {
<del> return fromNullable(f.apply(get()));
<add> return new Some<>(f.apply(get()));
<ide> }
<ide> }
<ide>
<ide> return value != null ? some(value) : Optional.<A>none();
<ide> }
<ide>
<add> public static <A> Optional<A> ofNullable(A value) {
<add> return fromNullable(value);
<add> }
<add>
<ide> public static <A> Optional<A> some(A value) {
<add> return new Some<A>(Objects.requireNonNull(value));
<add> }
<add>
<add> public static <A> Optional<A> of(A value) {
<ide> return new Some<A>(Objects.requireNonNull(value));
<ide> }
<ide>
<ide> @SuppressWarnings("unchecked")
<ide> public static <A> Optional<A> none() {
<ide> return (Optional<A>) NONE;
<add> }
<add>
<add> @SuppressWarnings("unchecked")
<add> public static <A> Optional<A> empty() {
<add> return none();
<ide> }
<ide>
<ide> public A orNull() { |
|
Java | lgpl-2.1 | 5acb035d4b67f2fa3725b51f05961dc282bbffba | 0 | kenweezy/teiid,kenweezy/teiid,kenweezy/teiid,jagazee/teiid-8.7,jagazee/teiid-8.7 | /*
* JBoss, Home of Professional Open Source.
* See the COPYRIGHT.txt file distributed with this work for information
* regarding copyright ownership. Some portions may be licensed
* to Red Hat, Inc. under one or more contributor license agreements.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301 USA.
*/
package org.teiid.query.function;
import static org.junit.Assert.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import org.junit.Test;
import org.mockito.Mockito;
import org.teiid.core.TeiidRuntimeException;
import org.teiid.core.types.BinaryType;
import org.teiid.core.types.DataTypeManager;
import org.teiid.metadata.FunctionMethod;
import org.teiid.metadata.FunctionParameter;
import org.teiid.metadata.FunctionMethod.Determinism;
import org.teiid.metadata.FunctionMethod.PushDown;
import org.teiid.query.function.metadata.FunctionCategoryConstants;
import org.teiid.query.function.source.SystemSource;
import org.teiid.query.unittest.RealMetadataFactory;
@SuppressWarnings("nls")
public class TestFunctionTree {
/**
* Walk through all functions by metadata and verify that we can look
* each one up by signature
*/
@Test public void testWalkTree() {
SystemSource source = new SystemSource(false);
FunctionTree ft = new FunctionTree("foo", source);
Collection<String> categories = ft.getCategories();
for (String category : categories) {
Collection<FunctionForm> functions = ft.getFunctionForms(category);
assertTrue(functions.size() > 0);
}
}
public String z() {
return null;
}
protected static String x() {
return null;
}
public static String y() {
return null;
}
public static String toString(byte[] bytes) {
return new String(bytes);
}
@Test public void testLoadErrors() {
FunctionMethod method = new FunctionMethod(
"dummy", null, null, PushDown.CAN_PUSHDOWN, null, "noMethod", //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
new ArrayList<FunctionParameter>(0),
new FunctionParameter("output", DataTypeManager.DefaultDataTypes.STRING), false, Determinism.DETERMINISTIC); //$NON-NLS-1$
//allowed, since we're not validating the class
new FunctionLibrary(RealMetadataFactory.SFM.getSystemFunctions(), new FunctionTree("foo", new UDFSource(Arrays.asList(method))));
//should fail, no class
try {
new FunctionLibrary(RealMetadataFactory.SFM.getSystemFunctions(), new FunctionTree("foo", new UDFSource(Arrays.asList(method)), true));
fail();
} catch (TeiidRuntimeException e) {
assertEquals("TEIID31123 Could not load non-FOREIGN UDF \"dummy\", since both invocation class and invocation method are required.", e.getMessage());
}
method.setInvocationClass("nonexistantClass");
//should fail, no class
try {
new FunctionLibrary(RealMetadataFactory.SFM.getSystemFunctions(), new FunctionTree("foo", new UDFSource(Arrays.asList(method)), true));
fail();
} catch (TeiidRuntimeException e) {
}
method.setInvocationClass(TestFunctionTree.class.getName());
//should fail, no method
try {
new FunctionLibrary(RealMetadataFactory.SFM.getSystemFunctions(), new FunctionTree("foo", new UDFSource(Arrays.asList(method)), true));
fail();
} catch (TeiidRuntimeException e) {
}
method.setInvocationMethod("testLoadErrors");
//should fail, not void
try {
new FunctionLibrary(RealMetadataFactory.SFM.getSystemFunctions(), new FunctionTree("foo", new UDFSource(Arrays.asList(method)), true));
fail();
} catch (TeiidRuntimeException e) {
}
method.setInvocationMethod("x");
//should fail, not public
try {
new FunctionLibrary(RealMetadataFactory.SFM.getSystemFunctions(), new FunctionTree("foo", new UDFSource(Arrays.asList(method)), true));
fail();
} catch (TeiidRuntimeException e) {
}
method.setInvocationMethod("z");
//should fail, not static
try {
new FunctionLibrary(RealMetadataFactory.SFM.getSystemFunctions(), new FunctionTree("foo", new UDFSource(Arrays.asList(method)), true));
fail();
} catch (TeiidRuntimeException e) {
}
method.setInvocationMethod("y");
//valid!
new FunctionLibrary(RealMetadataFactory.SFM.getSystemFunctions(), new FunctionTree("foo", new UDFSource(Arrays.asList(method)), true));
}
@Test public void testNullCategory() {
FunctionMethod method = new FunctionMethod(
"dummy", null, null, PushDown.MUST_PUSHDOWN, "nonexistentClass", "noMethod", //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
new ArrayList<FunctionParameter>(0),
new FunctionParameter("output", DataTypeManager.DefaultDataTypes.STRING), //$NON-NLS-1$
false, Determinism.DETERMINISTIC);
Collection<org.teiid.metadata.FunctionMethod> list = Arrays.asList(method);
FunctionMetadataSource fms = Mockito.mock(FunctionMetadataSource.class);
Mockito.stub(fms.getFunctionMethods()).toReturn(list);
FunctionTree ft = new FunctionTree("foo", fms);
assertEquals(1, ft.getFunctionForms(FunctionCategoryConstants.MISCELLANEOUS).size());
}
@Test public void testVarbinary() throws Exception {
FunctionMethod method = new FunctionMethod(
"dummy", null, null, PushDown.CANNOT_PUSHDOWN, TestFunctionTree.class.getName(), "toString", //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
Arrays.asList(new FunctionParameter("in", DataTypeManager.DefaultDataTypes.VARBINARY)), //$NON-NLS-1$
new FunctionParameter("output", DataTypeManager.DefaultDataTypes.STRING), //$NON-NLS-1$
true, Determinism.DETERMINISTIC);
FunctionTree sys = RealMetadataFactory.SFM.getSystemFunctions();
FunctionLibrary fl = new FunctionLibrary(sys, new FunctionTree("foo", new UDFSource(Arrays.asList(method)), true));
FunctionDescriptor fd = fl.findFunction("dummy", new Class<?>[] {DataTypeManager.DefaultDataClasses.VARBINARY});
String hello = "hello";
assertEquals(hello, fd.invokeFunction(new Object[] {new BinaryType(hello.getBytes())}, null, null));
}
/*
//DEBUGGING CODE - this will print out the tree root in readable form
//(This code will either have to be pasted in to FunctionTree class, or
//somehow the Map treeRoot must be gotten from the FunctionTree)
private static void debugPrintTreeRoot(Map treeRoot){
System.out.println("<!><!><!><!><!><!><!><!><!><!><!><!>");
System.out.println("FunctionTree treeRoot");
StringBuffer s = new StringBuffer();
debugPrintNode(treeRoot, 0, s);
System.out.println(s.toString());
System.out.println("<!><!><!><!><!><!><!><!><!><!><!><!>");
}
private static void debugPrintNode(Map node, int depth, StringBuffer s){
Iterator i = node.entrySet().iterator();
Map.Entry anEntry = null;
while(i.hasNext()) {
anEntry = (Map.Entry)i.next();
appendLine(s, depth, "Key: " + anEntry.getKey());
Object value = anEntry.getValue();
if (value instanceof Map){
s.append(" Map... ");
debugPrintNode((Map)value, depth + 1, s);
} else {
s.append(" Value: " + value);
}
}
}
private static void appendLine(StringBuffer s, int depth, String value){
s.append("\n");
for (int i = 0; i< depth; i++){
s.append(" ");
}
s.append(value);
}
*/
}
| engine/src/test/java/org/teiid/query/function/TestFunctionTree.java | /*
* JBoss, Home of Professional Open Source.
* See the COPYRIGHT.txt file distributed with this work for information
* regarding copyright ownership. Some portions may be licensed
* to Red Hat, Inc. under one or more contributor license agreements.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301 USA.
*/
package org.teiid.query.function;
import static org.junit.Assert.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import org.junit.Test;
import org.mockito.Mockito;
import org.teiid.core.TeiidRuntimeException;
import org.teiid.core.types.BinaryType;
import org.teiid.core.types.DataTypeManager;
import org.teiid.metadata.FunctionMethod;
import org.teiid.metadata.FunctionParameter;
import org.teiid.metadata.FunctionMethod.Determinism;
import org.teiid.metadata.FunctionMethod.PushDown;
import org.teiid.query.function.metadata.FunctionCategoryConstants;
import org.teiid.query.function.source.SystemSource;
import org.teiid.query.unittest.RealMetadataFactory;
@SuppressWarnings("nls")
public class TestFunctionTree {
/**
* Walk through all functions by metadata and verify that we can look
* each one up by signature
*/
@Test public void testWalkTree() {
SystemSource source = new SystemSource(false);
FunctionTree ft = new FunctionTree("foo", source);
Collection<String> categories = ft.getCategories();
for (String category : categories) {
Collection<FunctionForm> functions = ft.getFunctionForms(category);
assertTrue(functions.size() > 0);
}
}
public String z() {
return null;
}
protected static String x() {
return null;
}
public static String y() {
return null;
}
public static String toString(byte[] bytes) {
return new String(bytes);
}
@Test public void testLoadErrors() {
FunctionMethod method = new FunctionMethod(
"dummy", null, null, PushDown.CAN_PUSHDOWN, "nonexistentClass", "noMethod", //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
new ArrayList<FunctionParameter>(0),
new FunctionParameter("output", DataTypeManager.DefaultDataTypes.STRING), false, Determinism.DETERMINISTIC); //$NON-NLS-1$
//allowed, since we're not validating the class
new FunctionLibrary(RealMetadataFactory.SFM.getSystemFunctions(), new FunctionTree("foo", new UDFSource(Arrays.asList(method))));
//should fail, no class
try {
new FunctionLibrary(RealMetadataFactory.SFM.getSystemFunctions(), new FunctionTree("foo", new UDFSource(Arrays.asList(method)), true));
fail();
} catch (TeiidRuntimeException e) {
}
method.setInvocationClass(TestFunctionTree.class.getName());
//should fail, no method
try {
new FunctionLibrary(RealMetadataFactory.SFM.getSystemFunctions(), new FunctionTree("foo", new UDFSource(Arrays.asList(method)), true));
fail();
} catch (TeiidRuntimeException e) {
}
method.setInvocationMethod("testLoadErrors");
//should fail, not void
try {
new FunctionLibrary(RealMetadataFactory.SFM.getSystemFunctions(), new FunctionTree("foo", new UDFSource(Arrays.asList(method)), true));
fail();
} catch (TeiidRuntimeException e) {
}
method.setInvocationMethod("x");
//should fail, not public
try {
new FunctionLibrary(RealMetadataFactory.SFM.getSystemFunctions(), new FunctionTree("foo", new UDFSource(Arrays.asList(method)), true));
fail();
} catch (TeiidRuntimeException e) {
}
method.setInvocationMethod("z");
//should fail, not static
try {
new FunctionLibrary(RealMetadataFactory.SFM.getSystemFunctions(), new FunctionTree("foo", new UDFSource(Arrays.asList(method)), true));
fail();
} catch (TeiidRuntimeException e) {
}
method.setInvocationMethod("y");
//valid!
new FunctionLibrary(RealMetadataFactory.SFM.getSystemFunctions(), new FunctionTree("foo", new UDFSource(Arrays.asList(method)), true));
}
@Test public void testNullCategory() {
FunctionMethod method = new FunctionMethod(
"dummy", null, null, PushDown.MUST_PUSHDOWN, "nonexistentClass", "noMethod", //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
new ArrayList<FunctionParameter>(0),
new FunctionParameter("output", DataTypeManager.DefaultDataTypes.STRING), //$NON-NLS-1$
false, Determinism.DETERMINISTIC);
Collection<org.teiid.metadata.FunctionMethod> list = Arrays.asList(method);
FunctionMetadataSource fms = Mockito.mock(FunctionMetadataSource.class);
Mockito.stub(fms.getFunctionMethods()).toReturn(list);
FunctionTree ft = new FunctionTree("foo", fms);
assertEquals(1, ft.getFunctionForms(FunctionCategoryConstants.MISCELLANEOUS).size());
}
@Test public void testVarbinary() throws Exception {
FunctionMethod method = new FunctionMethod(
"dummy", null, null, PushDown.CANNOT_PUSHDOWN, TestFunctionTree.class.getName(), "toString", //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
Arrays.asList(new FunctionParameter("in", DataTypeManager.DefaultDataTypes.VARBINARY)), //$NON-NLS-1$
new FunctionParameter("output", DataTypeManager.DefaultDataTypes.STRING), //$NON-NLS-1$
true, Determinism.DETERMINISTIC);
FunctionTree sys = RealMetadataFactory.SFM.getSystemFunctions();
FunctionLibrary fl = new FunctionLibrary(sys, new FunctionTree("foo", new UDFSource(Arrays.asList(method)), true));
FunctionDescriptor fd = fl.findFunction("dummy", new Class<?>[] {DataTypeManager.DefaultDataClasses.VARBINARY});
String hello = "hello";
assertEquals(hello, fd.invokeFunction(new Object[] {new BinaryType(hello.getBytes())}, null, null));
}
/*
//DEBUGGING CODE - this will print out the tree root in readable form
//(This code will either have to be pasted in to FunctionTree class, or
//somehow the Map treeRoot must be gotten from the FunctionTree)
private static void debugPrintTreeRoot(Map treeRoot){
System.out.println("<!><!><!><!><!><!><!><!><!><!><!><!>");
System.out.println("FunctionTree treeRoot");
StringBuffer s = new StringBuffer();
debugPrintNode(treeRoot, 0, s);
System.out.println(s.toString());
System.out.println("<!><!><!><!><!><!><!><!><!><!><!><!>");
}
private static void debugPrintNode(Map node, int depth, StringBuffer s){
Iterator i = node.entrySet().iterator();
Map.Entry anEntry = null;
while(i.hasNext()) {
anEntry = (Map.Entry)i.next();
appendLine(s, depth, "Key: " + anEntry.getKey());
Object value = anEntry.getValue();
if (value instanceof Map){
s.append(" Map... ");
debugPrintNode((Map)value, depth + 1, s);
} else {
s.append(" Value: " + value);
}
}
}
private static void appendLine(StringBuffer s, int depth, String value){
s.append("\n");
for (int i = 0; i< depth; i++){
s.append(" ");
}
s.append(value);
}
*/
}
| TEIID-2233 adding a functiontree test
| engine/src/test/java/org/teiid/query/function/TestFunctionTree.java | TEIID-2233 adding a functiontree test | <ide><path>ngine/src/test/java/org/teiid/query/function/TestFunctionTree.java
<ide>
<ide> @Test public void testLoadErrors() {
<ide> FunctionMethod method = new FunctionMethod(
<del> "dummy", null, null, PushDown.CAN_PUSHDOWN, "nonexistentClass", "noMethod", //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
<add> "dummy", null, null, PushDown.CAN_PUSHDOWN, null, "noMethod", //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
<ide> new ArrayList<FunctionParameter>(0),
<ide> new FunctionParameter("output", DataTypeManager.DefaultDataTypes.STRING), false, Determinism.DETERMINISTIC); //$NON-NLS-1$
<ide>
<ide> //allowed, since we're not validating the class
<ide> new FunctionLibrary(RealMetadataFactory.SFM.getSystemFunctions(), new FunctionTree("foo", new UDFSource(Arrays.asList(method))));
<add>
<add> //should fail, no class
<add> try {
<add> new FunctionLibrary(RealMetadataFactory.SFM.getSystemFunctions(), new FunctionTree("foo", new UDFSource(Arrays.asList(method)), true));
<add> fail();
<add> } catch (TeiidRuntimeException e) {
<add> assertEquals("TEIID31123 Could not load non-FOREIGN UDF \"dummy\", since both invocation class and invocation method are required.", e.getMessage());
<add> }
<add>
<add> method.setInvocationClass("nonexistantClass");
<ide>
<ide> //should fail, no class
<ide> try { |
|
Java | mit | f70dfe93af71ffa122f5e22c4d515510be551403 | 0 | MuShiiii/mockito,ze-pequeno/mockito,Jam71/mockito,zorosteven/mockito,bric3/mockito,mbrukman/mockito,icefoggy/mockito,icefoggy/mockito,Jam71/mockito,bric3/mockito,MuShiiii/mockito,TimvdLippe/mockito,LilaQin/mockito,lukasz-szewc/mockito,rototor/mockito,diboy2/mockito,windofthesky/mockito,Jazzepi/mockito,LilaQin/mockito,smarkwell/mockito,bric3/mockito,hansjoachim/mockito,stefanbirkner/mockito,mockito/mockito,rototor/mockito,zorosteven/mockito,TimvdLippe/mockito,hansjoachim/mockito,mbrukman/mockito,JeremybellEU/mockito,diboy2/mockito,terebesirobert/mockito,Jazzepi/mockito,mohanaraosv/mockito,ze-pequeno/mockito,stefanbirkner/mockito,mockito/mockito,windofthesky/mockito,JeremybellEU/mockito,ignaciotcrespo/mockito,smarkwell/mockito,Ariel-Isaacm/mockito,mockito/mockito,mohanaraosv/mockito,lukasz-szewc/mockito,Ariel-Isaacm/mockito,ignaciotcrespo/mockito | /*
* Copyright (c) 2007 Mockito contributors
* This program is made available under the terms of the MIT License.
*/
package org.mockito.internal.matchers;
import org.junit.Test;
import org.mockitoutil.TestBase;
public class EqualsTest extends TestBase {
@Test
public void shouldBeEqual() {
assertEquals(new Equals(null), new Equals(null));
assertEquals(new Equals(new Integer(2)), new Equals(new Integer(2)));
assertFalse(new Equals(null).equals(null));
assertFalse(new Equals(null).equals("Test"));
assertEquals(1, new Equals(null).hashCode());
}
@Test
public void shouldArraysBeEqual() {
assertTrue(new Equals(new int[] {1, 2}).matches(new int[] {1, 2}));
assertFalse(new Equals(new Object[] {"1"}).matches(new Object[] {"1.0"}));
}
@Test
public void shouldDescribeWithExtraTypeInfo() throws Exception {
String descStr = new Equals(100).getTypedDescription();
assertEquals("(Integer) 100", descStr);
}
@Test
public void shouldDescribeWithExtraTypeInfoOfLong() throws Exception {
String descStr = new Equals(100L).getTypedDescription();
assertEquals("(Long) 100", descStr);
}
@Test
public void shouldDescribeWithTypeOfString() throws Exception {
String descStr = new Equals("x").getTypedDescription();
assertEquals("(String) \"x\"", descStr);
}
@Test
public void shouldAppendQuotingForString() {
String descStr = describe(new Equals("str"));
assertEquals("\"str\"", descStr);
}
@Test
public void shouldAppendQuotingForChar() {
String descStr = describe(new Equals('s'));
assertEquals("'s'", descStr);
}
@Test
public void shouldDescribeUsingToString() {
String descStr = describe(new Equals(100));
assertEquals("100", descStr);
}
@Test
public void shouldDescribeNull() {
String descStr = describe(new Equals(null));
assertEquals("null", descStr);
}
@Test
public void shouldMatchTypes() throws Exception {
//when
ContainsTypedDescription equals = new Equals(10);
//then
assertTrue(equals.typeMatches(10));
assertFalse(equals.typeMatches(10L));
}
@Test
public void shouldMatchTypesSafelyWhenActualIsNull() throws Exception {
//when
ContainsTypedDescription equals = new Equals(null);
//then
assertFalse(equals.typeMatches(10));
}
@Test
public void shouldMatchTypesSafelyWhenGivenIsNull() throws Exception {
//when
ContainsTypedDescription equals = new Equals(10);
//then
assertFalse(equals.typeMatches(null));
}
} | test/org/mockito/internal/matchers/EqualsTest.java | /*
* Copyright (c) 2007 Mockito contributors
* This program is made available under the terms of the MIT License.
*/
package org.mockito.internal.matchers;
import org.junit.Test;
import org.mockitoutil.TestBase;
public class EqualsTest extends TestBase {
@Test
public void shouldBeEqual() {
assertEquals(new Equals(null), new Equals(null));
assertEquals(new Equals(new Integer(2)), new Equals(new Integer(2)));
assertFalse(new Equals(null).equals(null));
assertFalse(new Equals(null).equals("Test"));
assertEquals(1, new Equals(null).hashCode());
}
@Test
public void shouldArraysBeEqual() {
assertTrue(new Equals(new int[] {1, 2}).matches(new int[] {1, 2}));
assertFalse(new Equals(new Object[] {"1"}).matches(new Object[] {"1.0"}));
}
@Test
public void shouldDescribeWithExtraTypeInfo() throws Exception {
String descStr = new Equals(100).getTypedDescription();
assertEquals("(Integer) 100", descStr);
}
@Test
public void shouldDescribeWithExtraTypeInfoOfLong() throws Exception {
String descStr = new Equals(100L).getTypedDescription();
assertEquals("(Long) 100", descStr);
}
@Test
public void shouldAppendQuotingForString() {
String descStr = describe(new Equals("str"));
assertEquals("\"str\"", descStr);
}
@Test
public void shouldAppendQuotingForChar() {
String descStr = describe(new Equals('s'));
assertEquals("'s'", descStr);
}
@Test
public void shouldDescribeUsingToString() {
String descStr = describe(new Equals(100));
assertEquals("100", descStr);
}
@Test
public void shouldDescribeNull() {
String descStr = describe(new Equals(null));
assertEquals("null", descStr);
}
@Test
public void shouldMatchTypes() throws Exception {
//when
ContainsTypedDescription equals = new Equals(10);
//then
assertTrue(equals.typeMatches(10));
assertFalse(equals.typeMatches(10L));
}
@Test
public void shouldMatchTypesSafelyWhenActualIsNull() throws Exception {
//when
ContainsTypedDescription equals = new Equals(null);
//then
assertFalse(equals.typeMatches(10));
}
@Test
public void shouldMatchTypesSafelyWhenGivenIsNull() throws Exception {
//when
ContainsTypedDescription equals = new Equals(10);
//then
assertFalse(equals.typeMatches(null));
}
} | Tightened coverage
| test/org/mockito/internal/matchers/EqualsTest.java | Tightened coverage | <ide><path>est/org/mockito/internal/matchers/EqualsTest.java
<ide> String descStr = new Equals(100L).getTypedDescription();
<ide>
<ide> assertEquals("(Long) 100", descStr);
<add> }
<add>
<add> @Test
<add> public void shouldDescribeWithTypeOfString() throws Exception {
<add> String descStr = new Equals("x").getTypedDescription();
<add>
<add> assertEquals("(String) \"x\"", descStr);
<ide> }
<ide>
<ide> @Test |
|
Java | apache-2.0 | 9f884ed4250273e16f1e838d86c494740cc5b014 | 0 | raphw/byte-buddy,DALDEI/byte-buddy,PascalSchumacher/byte-buddy,mches/byte-buddy,CodingFabian/byte-buddy,raphw/byte-buddy,vic/byte-buddy,raphw/byte-buddy | package net.bytebuddy.dynamic.scaffold.subclass;
import net.bytebuddy.description.method.MethodDescription;
import net.bytebuddy.description.type.TypeDescription;
import net.bytebuddy.matcher.ElementMatcher;
import net.bytebuddy.matcher.LatentMethodMatcher;
import net.bytebuddy.test.utility.MockitoRule;
import net.bytebuddy.test.utility.ObjectPropertyAssertion;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TestRule;
import org.mockito.Mock;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
import static org.mockito.Mockito.when;
public class SubclassDynamicTypeBuilderInstrumentableMatcherTest {
@Rule
public TestRule mockitoRule = new MockitoRule(this);
@Mock
private MethodDescription methodDescription;
@Mock
private TypeDescription typeDescription, otherType;
@Mock
private ElementMatcher<? super MethodDescription> ignoredMethods;
private LatentMethodMatcher latentMethodMatcher;
@Before
public void setUp() throws Exception {
latentMethodMatcher = new SubclassDynamicTypeBuilder.InstrumentableMatcher(ignoredMethods);
}
@Test
public void testMatchesOverridable() throws Exception {
when(methodDescription.isOverridable()).thenReturn(true);
when(ignoredMethods.matches(methodDescription)).thenReturn(false);
when(methodDescription.getDeclaringType()).thenReturn(otherType);
when(methodDescription.isVisibleTo(typeDescription)).thenReturn(true);
assertThat(latentMethodMatcher.resolve(typeDescription).matches(methodDescription), is(true));
}
@Test
public void testNotMatchesOverridableIfNotVisible() throws Exception {
when(methodDescription.isOverridable()).thenReturn(true);
when(ignoredMethods.matches(methodDescription)).thenReturn(false);
when(methodDescription.getDeclaringType()).thenReturn(otherType);
when(methodDescription.isVisibleTo(typeDescription)).thenReturn(false);
assertThat(latentMethodMatcher.resolve(typeDescription).matches(methodDescription), is(false));
}
@Test
public void testNotMatchesNonOverridableIfNotDeclared() throws Exception {
when(methodDescription.isOverridable()).thenReturn(false);
when(ignoredMethods.matches(methodDescription)).thenReturn(false);
when(methodDescription.getDeclaringType()).thenReturn(otherType);
assertThat(latentMethodMatcher.resolve(typeDescription).matches(methodDescription), is(false));
}
@Test
public void testNotMatchesIgnoredMethodIfNotDeclared() throws Exception {
when(methodDescription.isOverridable()).thenReturn(true);
when(ignoredMethods.matches(methodDescription)).thenReturn(true);
when(methodDescription.getDeclaringType()).thenReturn(otherType);
assertThat(latentMethodMatcher.resolve(typeDescription).matches(methodDescription), is(false));
}
@Test
public void testMatchesDeclaredMethod() throws Exception {
when(methodDescription.isOverridable()).thenReturn(true);
when(ignoredMethods.matches(methodDescription)).thenReturn(false);
when(methodDescription.getDeclaringType()).thenReturn(typeDescription);
assertThat(latentMethodMatcher.resolve(typeDescription).matches(methodDescription), is(true));
}
@Test
public void testMatchesDeclaredMethodIfIgnored() throws Exception {
when(methodDescription.isOverridable()).thenReturn(true);
when(ignoredMethods.matches(methodDescription)).thenReturn(true);
when(methodDescription.getDeclaringType()).thenReturn(typeDescription);
assertThat(latentMethodMatcher.resolve(typeDescription).matches(methodDescription), is(true));
}
@Test
public void testMatchesDeclaredMethodIfNotOverridable() throws Exception {
when(methodDescription.isOverridable()).thenReturn(false);
when(ignoredMethods.matches(methodDescription)).thenReturn(false);
when(methodDescription.getDeclaringType()).thenReturn(typeDescription);
assertThat(latentMethodMatcher.resolve(typeDescription).matches(methodDescription), is(true));
}
@Test
public void testObjectProperties() throws Exception {
ObjectPropertyAssertion.of(SubclassDynamicTypeBuilder.InstrumentableMatcher.class).apply();
}
}
| byte-buddy-dep/src/test/java/net/bytebuddy/dynamic/scaffold/subclass/SubclassDynamicTypeBuilderInstrumentableMatcherTest.java | package net.bytebuddy.dynamic.scaffold.subclass;
import net.bytebuddy.description.method.MethodDescription;
import net.bytebuddy.description.type.TypeDescription;
import net.bytebuddy.matcher.ElementMatcher;
import net.bytebuddy.matcher.LatentMethodMatcher;
import net.bytebuddy.test.utility.MockitoRule;
import net.bytebuddy.test.utility.ObjectPropertyAssertion;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TestRule;
import org.mockito.Mock;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
import static org.mockito.Mockito.when;
public class SubclassDynamicTypeBuilderInstrumentableMatcherTest {
@Rule
public TestRule mockitoRule = new MockitoRule(this);
@Mock
private MethodDescription methodDescription;
@Mock
private TypeDescription typeDescription, otherType;
@Mock
private ElementMatcher<? super MethodDescription> ignoredMethods;
private LatentMethodMatcher latentMethodMatcher;
@Before
public void setUp() throws Exception {
latentMethodMatcher = new SubclassDynamicTypeBuilder.InstrumentableMatcher(ignoredMethods);
}
@Test
public void testMatchesOverridable() throws Exception {
when(methodDescription.isOverridable()).thenReturn(true);
when(ignoredMethods.matches(methodDescription)).thenReturn(false);
when(methodDescription.getDeclaringType()).thenReturn(otherType);
assertThat(latentMethodMatcher.resolve(typeDescription).matches(methodDescription), is(true));
}
@Test
public void testNotMatchesNonOverridableIfNotDeclared() throws Exception {
when(methodDescription.isOverridable()).thenReturn(false);
when(ignoredMethods.matches(methodDescription)).thenReturn(false);
when(methodDescription.getDeclaringType()).thenReturn(otherType);
assertThat(latentMethodMatcher.resolve(typeDescription).matches(methodDescription), is(false));
}
@Test
public void testNotMatchesIgnoredMethodIfNotDeclared() throws Exception {
when(methodDescription.isOverridable()).thenReturn(true);
when(ignoredMethods.matches(methodDescription)).thenReturn(true);
when(methodDescription.getDeclaringType()).thenReturn(otherType);
assertThat(latentMethodMatcher.resolve(typeDescription).matches(methodDescription), is(false));
}
@Test
public void testMatchesDeclaredMethod() throws Exception {
when(methodDescription.isOverridable()).thenReturn(true);
when(ignoredMethods.matches(methodDescription)).thenReturn(false);
when(methodDescription.getDeclaringType()).thenReturn(typeDescription);
assertThat(latentMethodMatcher.resolve(typeDescription).matches(methodDescription), is(true));
}
@Test
public void testMatchesDeclaredMethodIfIgnored() throws Exception {
when(methodDescription.isOverridable()).thenReturn(true);
when(ignoredMethods.matches(methodDescription)).thenReturn(true);
when(methodDescription.getDeclaringType()).thenReturn(typeDescription);
assertThat(latentMethodMatcher.resolve(typeDescription).matches(methodDescription), is(true));
}
@Test
public void testMatchesDeclaredMethodIfNotOverridable() throws Exception {
when(methodDescription.isOverridable()).thenReturn(false);
when(ignoredMethods.matches(methodDescription)).thenReturn(false);
when(methodDescription.getDeclaringType()).thenReturn(typeDescription);
assertThat(latentMethodMatcher.resolve(typeDescription).matches(methodDescription), is(true));
}
@Test
public void testObjectProperties() throws Exception {
ObjectPropertyAssertion.of(SubclassDynamicTypeBuilder.InstrumentableMatcher.class).apply();
}
}
| Adapted matcher tests for subclass generation.
| byte-buddy-dep/src/test/java/net/bytebuddy/dynamic/scaffold/subclass/SubclassDynamicTypeBuilderInstrumentableMatcherTest.java | Adapted matcher tests for subclass generation. | <ide><path>yte-buddy-dep/src/test/java/net/bytebuddy/dynamic/scaffold/subclass/SubclassDynamicTypeBuilderInstrumentableMatcherTest.java
<ide> when(methodDescription.isOverridable()).thenReturn(true);
<ide> when(ignoredMethods.matches(methodDescription)).thenReturn(false);
<ide> when(methodDescription.getDeclaringType()).thenReturn(otherType);
<add> when(methodDescription.isVisibleTo(typeDescription)).thenReturn(true);
<ide> assertThat(latentMethodMatcher.resolve(typeDescription).matches(methodDescription), is(true));
<add> }
<add>
<add> @Test
<add> public void testNotMatchesOverridableIfNotVisible() throws Exception {
<add> when(methodDescription.isOverridable()).thenReturn(true);
<add> when(ignoredMethods.matches(methodDescription)).thenReturn(false);
<add> when(methodDescription.getDeclaringType()).thenReturn(otherType);
<add> when(methodDescription.isVisibleTo(typeDescription)).thenReturn(false);
<add> assertThat(latentMethodMatcher.resolve(typeDescription).matches(methodDescription), is(false));
<ide> }
<ide>
<ide> @Test |
|
Java | mit | 0f4aa9b53680eefb609b33093e82c4552efa0410 | 0 | peterjosling/scroball | package com.peterjosling.scroball;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.util.Log;
import com.google.common.base.Optional;
import com.peterjosling.scroball.db.ScroballDB;
import java.util.ArrayList;
import java.util.List;
import de.umass.lastfm.Caller;
import de.umass.lastfm.Result;
import de.umass.lastfm.scrobble.ScrobbleResult;
public class Scrobbler {
private static final String TAG = Scrobbler.class.getName();
private static final int SCROBBLE_THRESHOLD = 4 * 60 * 1000;
private static final int MINIMUM_SCROBBLE_TIME = 30 * 1000;
private static final int MAX_SCROBBLES = 50;
private final LastfmClient client;
private final ScrobbleNotificationManager notificationManager;
private final ScroballDB scroballDB;
private final ConnectivityManager connectivityManager;
private final List<PlaybackItem> pendingPlaybackItems;
private final List<Scrobble> pending;
private boolean isScrobbling = false;
public Scrobbler(
LastfmClient client,
ScrobbleNotificationManager notificationManager,
ScroballDB scroballDB,
ConnectivityManager connectivityManager) {
this.client = client;
this.notificationManager = notificationManager;
this.scroballDB = scroballDB;
this.connectivityManager = connectivityManager;
// TODO write unit test to ensure non-network plays get scrobbled with duration lookup.
this.pendingPlaybackItems = new ArrayList<>(scroballDB.readPendingPlaybackItems());
this.pending = new ArrayList<>(scroballDB.readPendingScrobbles());
}
public void updateNowPlaying(Track track) {
if (!client.isAuthenticated()) {
Log.i(TAG, "Skipping now playing update, not logged in.");
return;
}
NetworkInfo activeNetwork = connectivityManager.getActiveNetworkInfo();
boolean isConnected = activeNetwork != null && activeNetwork.isConnectedOrConnecting();
if (!isConnected) {
return;
}
client.updateNowPlaying(
track,
message -> {
ScrobbleResult result = (ScrobbleResult) message.obj;
int errorCode = 1;
if (result != null) {
errorCode = result.getErrorCode();
}
if (LastfmClient.isAuthenticationError(errorCode)) {
notificationManager.notifyAuthError();
ScroballApplication.getEventBus().post(AuthErrorEvent.create(errorCode));
}
return true;
});
}
public void submit(PlaybackItem playbackItem) {
// Set final value for amount played, in case it was playing up until now.
playbackItem.updateAmountPlayed();
// Generate one scrobble per played period.
Track track = playbackItem.getTrack();
if (!track.duration().isPresent()) {
fetchTrackDurationAndSubmit(playbackItem);
return;
}
long timestamp = playbackItem.getTimestamp();
long duration = track.duration().get();
long playTime = playbackItem.getAmountPlayed();
if (playTime < 1) {
return;
}
// Handle cases where player does not report duration *and* Last.fm does not report it either.
if (duration == 0) {
duration = playTime;
}
int playCount = (int) (playTime / duration);
long scrobbleThreshold = Math.min(SCROBBLE_THRESHOLD, duration / 2);
if (duration < MINIMUM_SCROBBLE_TIME) {
return;
}
if (playTime % duration > scrobbleThreshold) {
playCount++;
}
playCount -= playbackItem.getPlaysScrobbled();
for (int i = 0; i < playCount; i++) {
int itemTimestamp = (int) ((timestamp + i * duration) / 1000);
Scrobble scrobble = Scrobble.builder().track(track).timestamp(itemTimestamp).build();
pending.add(scrobble);
scroballDB.writeScrobble(scrobble);
playbackItem.addScrobble();
}
if (playCount > 0) {
Log.i(TAG, String.format("Queued %d scrobbles", playCount));
}
notificationManager.notifyScrobbled(track, playCount);
scrobblePending();
}
public void fetchTrackDurationAndSubmit(final PlaybackItem playbackItem) {
NetworkInfo activeNetwork = connectivityManager.getActiveNetworkInfo();
boolean isConnected = activeNetwork != null && activeNetwork.isConnectedOrConnecting();
if (!isConnected || !client.isAuthenticated()) {
Log.i(TAG, "Offline or unauthenticated, can't fetch track duration. Saving for later.");
queuePendingPlaybackItem(playbackItem);
return;
}
Track track = playbackItem.getTrack();
client.getTrackInfo(
track,
message -> {
if (message.obj == null) {
Result result = Caller.getInstance().getLastResult();
int errorCode = 1;
if (result != null) {
errorCode = result.getErrorCode();
}
if (errorCode == 6) {
Log.w(TAG, "Track not found, cannot scrobble.");
// TODO prompt user to scrobble anyway
} else {
if (LastfmClient.isTransientError(errorCode)) {
Log.w(TAG, "Failed to fetch track duration, saving for later.");
queuePendingPlaybackItem(playbackItem);
}
if (LastfmClient.isAuthenticationError(errorCode)) {
notificationManager.notifyAuthError();
ScroballApplication.getEventBus().post(AuthErrorEvent.create(errorCode));
}
}
return true;
}
Track updatedTrack = (Track) message.obj;
playbackItem.updateTrack(updatedTrack);
Log.i(TAG, String.format("Track info updated: %s", playbackItem));
submit(playbackItem);
return true;
});
}
public void scrobblePending() {
NetworkInfo activeNetwork = connectivityManager.getActiveNetworkInfo();
boolean isConnected = activeNetwork != null && activeNetwork.isConnectedOrConnecting();
boolean tracksPending = !(pending.isEmpty() && pendingPlaybackItems.isEmpty());
if (isScrobbling || !tracksPending || !isConnected || !client.isAuthenticated()) {
return;
}
List<PlaybackItem> playbackItems = new ArrayList<>(pendingPlaybackItems);
pendingPlaybackItems.clear();
scroballDB.clearPendingPlaybackItems();
if (!playbackItems.isEmpty()) {
Log.i(TAG, "Re-processing queued items with missing durations.");
}
for (PlaybackItem playbackItem : playbackItems) {
fetchTrackDurationAndSubmit(playbackItem);
}
if (pending.isEmpty()) {
return;
}
isScrobbling = true;
final List<Scrobble> tracksToScrobble = new ArrayList<>(pending);
while (tracksToScrobble.size() > MAX_SCROBBLES) {
tracksToScrobble.remove(tracksToScrobble.size() - 1);
}
client.scrobbleTracks(
tracksToScrobble,
message -> {
List<ScrobbleResult> results = (List<ScrobbleResult>) message.obj;
boolean didError = false;
for (int i = 0; i < results.size(); i++) {
ScrobbleResult result = results.get(i);
Scrobble scrobble = tracksToScrobble.get(i);
if (result != null && result.isSuccessful()) {
scrobble.status().setScrobbled(true);
scroballDB.writeScrobble(scrobble);
pending.remove(scrobble);
} else {
int errorCode = 1;
if (result != null) {
errorCode = result.getErrorCode();
}
if (!LastfmClient.isTransientError(errorCode)) {
pending.remove(scrobble);
}
if (LastfmClient.isAuthenticationError(errorCode)) {
notificationManager.notifyAuthError();
ScroballApplication.getEventBus().post(AuthErrorEvent.create(errorCode));
}
scrobble.status().setErrorCode(errorCode);
scroballDB.writeScrobble(scrobble);
didError = true;
}
}
isScrobbling = false;
// TODO need to wait if there was an error/rate limiting
if (!didError) {
scrobblePending();
}
return false;
});
}
/**
* Calculates the number of milliseconds of playback time remaining until the specified {@param
* PlaybackItem} can be scrobbled, i.e. reaches 50% of track duration or SCROBBLE_THRESHOLD.
*
* @return The number of milliseconds remaining until the next scrobble for the current playback
* item can be submitted, or -1 if the track's duration is below MINIMUM_SCROBBLE_TIME.
*/
public long getMillisecondsUntilScrobble(PlaybackItem playbackItem) {
if (playbackItem == null) {
return -1;
}
Optional<Long> optionalDuration = playbackItem.getTrack().duration();
long duration = optionalDuration.or(0L);
if (duration < MINIMUM_SCROBBLE_TIME) {
if (optionalDuration.isPresent()) {
Log.i(TAG, String.format("Not scheduling scrobble, track is too short (%d)", duration));
} else {
Log.i(TAG, "Not scheduling scrobble, track duration not known");
}
return -1;
}
long scrobbleThreshold = Math.min(duration / 2, SCROBBLE_THRESHOLD);
long nextScrobbleAt = playbackItem.getPlaysScrobbled() * duration + scrobbleThreshold;
return Math.max(0, nextScrobbleAt - playbackItem.getAmountPlayed());
}
private void queuePendingPlaybackItem(PlaybackItem playbackItem) {
pendingPlaybackItems.add(playbackItem);
scroballDB.writePendingPlaybackItem(playbackItem);
}
}
| app/src/main/java/com/peterjosling/scroball/Scrobbler.java | package com.peterjosling.scroball;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.util.Log;
import com.google.common.base.Optional;
import com.peterjosling.scroball.db.ScroballDB;
import java.util.ArrayList;
import java.util.List;
import de.umass.lastfm.Caller;
import de.umass.lastfm.Result;
import de.umass.lastfm.scrobble.ScrobbleResult;
public class Scrobbler {
private static final String TAG = Scrobbler.class.getName();
private static final int SCROBBLE_THRESHOLD = 4 * 60 * 1000;
private static final int MINIMUM_SCROBBLE_TIME = 30 * 1000;
private static final int MAX_SCROBBLES = 50;
private final LastfmClient client;
private final ScrobbleNotificationManager notificationManager;
private final ScroballDB scroballDB;
private final ConnectivityManager connectivityManager;
private final List<PlaybackItem> pendingPlaybackItems;
private final List<Scrobble> pending;
private boolean isScrobbling = false;
public Scrobbler(
LastfmClient client,
ScrobbleNotificationManager notificationManager,
ScroballDB scroballDB,
ConnectivityManager connectivityManager) {
this.client = client;
this.notificationManager = notificationManager;
this.scroballDB = scroballDB;
this.connectivityManager = connectivityManager;
// TODO write unit test to ensure non-network plays get scrobbled with duration lookup.
this.pendingPlaybackItems = new ArrayList<>(scroballDB.readPendingPlaybackItems());
this.pending = new ArrayList<>(scroballDB.readPendingScrobbles());
}
public void updateNowPlaying(Track track) {
if (!client.isAuthenticated()) {
Log.i(TAG, "Skipping now playing update, not logged in.");
return;
}
NetworkInfo activeNetwork = connectivityManager.getActiveNetworkInfo();
boolean isConnected = activeNetwork != null && activeNetwork.isConnectedOrConnecting();
if (!isConnected) {
return;
}
client.updateNowPlaying(
track,
message -> {
ScrobbleResult result = (ScrobbleResult) message.obj;
int errorCode = 1;
if (result != null) {
errorCode = result.getErrorCode();
}
if (LastfmClient.isAuthenticationError(errorCode)) {
notificationManager.notifyAuthError();
ScroballApplication.getEventBus().post(AuthErrorEvent.create(errorCode));
}
return true;
});
}
public void submit(PlaybackItem playbackItem) {
// Set final value for amount played, in case it was playing up until now.
playbackItem.updateAmountPlayed();
// Generate one scrobble per played period.
Track track = playbackItem.getTrack();
if (!track.duration().isPresent()) {
fetchTrackDurationAndSubmit(playbackItem);
return;
}
long timestamp = playbackItem.getTimestamp();
long duration = track.duration().get();
long playTime = playbackItem.getAmountPlayed();
if (playTime < 1) {
return;
}
// Handle cases where player does not report duration *and* Last.fm does not report it either.
if (duration == 0) {
duration = playTime;
}
int playCount = (int) (playTime / duration);
long scrobbleThreshold = Math.min(SCROBBLE_THRESHOLD, duration / 2);
if (duration < MINIMUM_SCROBBLE_TIME) {
return;
}
if (playTime % duration > scrobbleThreshold) {
playCount++;
}
playCount -= playbackItem.getPlaysScrobbled();
for (int i = 0; i < playCount; i++) {
int itemTimestamp = (int) ((timestamp + i * duration) / 1000);
Scrobble scrobble = Scrobble.builder().track(track).timestamp(itemTimestamp).build();
pending.add(scrobble);
scroballDB.writeScrobble(scrobble);
playbackItem.addScrobble();
}
if (playCount > 0) {
Log.i(TAG, String.format("Queued %d scrobbles", playCount));
}
notificationManager.notifyScrobbled(track, playCount);
scrobblePending();
}
public void fetchTrackDurationAndSubmit(final PlaybackItem playbackItem) {
NetworkInfo activeNetwork = connectivityManager.getActiveNetworkInfo();
boolean isConnected = activeNetwork != null && activeNetwork.isConnectedOrConnecting();
if (!isConnected || !client.isAuthenticated()) {
Log.i(TAG, "Offline or unauthenticated, can't fetch track duration. Saving for later.");
queuePendingPlaybackItem(playbackItem);
return;
}
Track track = playbackItem.getTrack();
client.getTrackInfo(
track,
message -> {
if (message.obj == null) {
Result result = Caller.getInstance().getLastResult();
int errorCode = 1;
if (result != null) {
errorCode = result.getErrorCode();
}
if (errorCode == 6) {
Log.w(TAG, "Track not found, cannot scrobble.");
// TODO prompt user to scrobble anyway
} else {
if (LastfmClient.isTransientError(errorCode)) {
Log.w(TAG, "Failed to fetch track duration, saving for later.");
queuePendingPlaybackItem(playbackItem);
}
if (LastfmClient.isAuthenticationError(errorCode)) {
notificationManager.notifyAuthError();
ScroballApplication.getEventBus().post(AuthErrorEvent.create(errorCode));
}
}
return true;
}
Track updatedTrack = (Track) message.obj;
playbackItem.updateTrack(updatedTrack);
Log.i(TAG, String.format("Track info updated: %s", playbackItem));
submit(playbackItem);
return true;
});
}
public void scrobblePending() {
NetworkInfo activeNetwork = connectivityManager.getActiveNetworkInfo();
boolean isConnected = activeNetwork != null && activeNetwork.isConnectedOrConnecting();
boolean tracksPending = !(pending.isEmpty() && pendingPlaybackItems.isEmpty());
// TODO listen for changes in connectivity and trigger this method then.
if (isScrobbling || !tracksPending || !isConnected || !client.isAuthenticated()) {
return;
}
List<PlaybackItem> playbackItems = new ArrayList<>(pendingPlaybackItems);
pendingPlaybackItems.clear();
scroballDB.clearPendingPlaybackItems();
if (!playbackItems.isEmpty()) {
Log.i(TAG, "Re-processing queued items with missing durations.");
}
for (PlaybackItem playbackItem : playbackItems) {
fetchTrackDurationAndSubmit(playbackItem);
}
if (pending.isEmpty()) {
return;
}
isScrobbling = true;
final List<Scrobble> tracksToScrobble = new ArrayList<>(pending);
while (tracksToScrobble.size() > MAX_SCROBBLES) {
tracksToScrobble.remove(tracksToScrobble.size() - 1);
}
client.scrobbleTracks(
tracksToScrobble,
message -> {
List<ScrobbleResult> results = (List<ScrobbleResult>) message.obj;
boolean didError = false;
for (int i = 0; i < results.size(); i++) {
ScrobbleResult result = results.get(i);
Scrobble scrobble = tracksToScrobble.get(i);
if (result != null && result.isSuccessful()) {
scrobble.status().setScrobbled(true);
scroballDB.writeScrobble(scrobble);
pending.remove(scrobble);
} else {
int errorCode = 1;
if (result != null) {
errorCode = result.getErrorCode();
}
if (!LastfmClient.isTransientError(errorCode)) {
pending.remove(scrobble);
}
if (LastfmClient.isAuthenticationError(errorCode)) {
notificationManager.notifyAuthError();
ScroballApplication.getEventBus().post(AuthErrorEvent.create(errorCode));
}
scrobble.status().setErrorCode(errorCode);
scroballDB.writeScrobble(scrobble);
didError = true;
}
}
isScrobbling = false;
// TODO need to wait if there was an error/rate limiting
if (!didError) {
scrobblePending();
}
return false;
});
}
/**
* Calculates the number of milliseconds of playback time remaining until the specified {@param
* PlaybackItem} can be scrobbled, i.e. reaches 50% of track duration or SCROBBLE_THRESHOLD.
*
* @return The number of milliseconds remaining until the next scrobble for the current playback
* item can be submitted, or -1 if the track's duration is below MINIMUM_SCROBBLE_TIME.
*/
public long getMillisecondsUntilScrobble(PlaybackItem playbackItem) {
if (playbackItem == null) {
return -1;
}
Optional<Long> optionalDuration = playbackItem.getTrack().duration();
long duration = optionalDuration.or(0L);
if (duration < MINIMUM_SCROBBLE_TIME) {
if (optionalDuration.isPresent()) {
Log.i(TAG, String.format("Not scheduling scrobble, track is too short (%d)", duration));
} else {
Log.i(TAG, "Not scheduling scrobble, track duration not known");
}
return -1;
}
long scrobbleThreshold = Math.min(duration / 2, SCROBBLE_THRESHOLD);
long nextScrobbleAt = playbackItem.getPlaysScrobbled() * duration + scrobbleThreshold;
return Math.max(0, nextScrobbleAt - playbackItem.getAmountPlayed());
}
private void queuePendingPlaybackItem(PlaybackItem playbackItem) {
pendingPlaybackItems.add(playbackItem);
scroballDB.writePendingPlaybackItem(playbackItem);
}
}
| Remove completed TODO
| app/src/main/java/com/peterjosling/scroball/Scrobbler.java | Remove completed TODO | <ide><path>pp/src/main/java/com/peterjosling/scroball/Scrobbler.java
<ide> boolean isConnected = activeNetwork != null && activeNetwork.isConnectedOrConnecting();
<ide> boolean tracksPending = !(pending.isEmpty() && pendingPlaybackItems.isEmpty());
<ide>
<del> // TODO listen for changes in connectivity and trigger this method then.
<ide> if (isScrobbling || !tracksPending || !isConnected || !client.isAuthenticated()) {
<ide> return;
<ide> } |
|
Java | apache-2.0 | c4a0837d2d6617106c14fe87168f21d335590435 | 0 | SharedHealth/openmrs-module-bdshrclient,SharedHealth/openmrs-module-bdshrclient,SharedHealth/openmrs-module-bdshrclient | package org.openmrs.module.bdshrclient.web.controller;
import org.openmrs.api.context.Context;
import org.openmrs.module.addresshierarchy.AddressHierarchyEntry;
import org.openmrs.module.addresshierarchy.service.AddressHierarchyService;
import org.openmrs.module.bdshrclient.model.Address;
import org.openmrs.module.bdshrclient.model.Patient;
import org.openmrs.module.bdshrclient.service.MciPatientService;
import org.openmrs.module.bdshrclient.util.GenderEnum;
import org.openmrs.module.bdshrclient.util.MciProperties;
import org.openmrs.module.bdshrclient.util.WebClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
@Controller
@RequestMapping(value = "/mci")
public class MciPatientLookupController {
@Autowired
MciPatientService mciPatientService;
private String mciPatientUrl = null;
@RequestMapping(method = RequestMethod.GET, value = "/search")
@ResponseBody
public Object search(MciPatientSearchRequest request) {
Patient mciPatient = null;
if (!isBlankString(request.getNid())) {
mciPatient = searchPatientByNationalId(request.getNid());
} else if (!isBlankString(request.getHid())) {
mciPatient = searchPatientByHealthId(request.getHid());
}
if (mciPatient != null) {
return mapToPatientUIModel(mciPatient);
}
return null;
}
//@RequestMapping(method = RequestMethod.POST, value = "/download")
@RequestMapping(method = RequestMethod.GET, value = "/download")
@ResponseBody
public Object download(MciPatientSearchRequest request) {
Patient mciPatient = searchPatientByHealthId(request.getHid());
if (mciPatient != null) {
Map<String, String> downloadResponse = new HashMap<String, String>();
org.openmrs.Patient emrPatient = mciPatientService.createOrUpdatePatient(mciPatient);
downloadResponse.put("uuid", emrPatient.getUuid());
return downloadResponse;
}
return null;
}
private Map<String, Object> mapToPatientUIModel(Patient mciPatient) {
Map<String, Object> patientModel = new HashMap<String, Object>();
patientModel.put("firstName", mciPatient.getFirstName());
patientModel.put("middleName", mciPatient.getMiddleName());
patientModel.put("lastName", mciPatient.getLastName());
patientModel.put("gender", GenderEnum.forCode(mciPatient.getGender()).name());
patientModel.put("nationalId", mciPatient.getNationalId());
patientModel.put("healthId", mciPatient.getHealthId());
patientModel.put("primaryContact", mciPatient.getPrimaryContact());
Map<String, String> addressModel = new HashMap<String, String>();
Address address = mciPatient.getAddress();
addressModel.put("address_line", address.getAddressLine());
addressModel.put("division", getAddressEntryText(address.getDivisionId()));
addressModel.put("district", getAddressEntryText(address.getDistrictId()));
addressModel.put("upazilla", getAddressEntryText(address.getUpazillaId()));
addressModel.put("union", getAddressEntryText(address.getUnionId()));
patientModel.put("address", addressModel);
return patientModel;
}
private boolean isBlankString(String value) {
if ((value != null) && !"".equals(value)) {
return false;
}
return true;
}
private Patient searchPatientByNationalId(String nid) {
String mciNationIdSearchUrl = null;
try {
mciNationIdSearchUrl = String.format("%s?nid=%s", getMciPatientBaseUrl(), nid);
WebClient webClient = new WebClient();
Patient mciPatient = webClient.get(mciNationIdSearchUrl, Patient.class);
return mciPatient;
} catch (IOException e) {
throw new RuntimeException("Error occurred while trying to query MCI", e);
}
}
private Patient searchPatientByHealthId(String hid) {
if ((hid == null) || "".equals(hid)) return null;
try {
String mciPatientUrl = String.format("%s/%s", getMciPatientBaseUrl(), hid);
WebClient webClient = new WebClient();
Patient mciPatient = webClient.get(mciPatientUrl, Patient.class);
return mciPatient;
} catch (IOException e) {
throw new RuntimeException("Error occurred while trying to query MCI", e);
}
}
private String getMciPatientBaseUrl() throws IOException {
if (mciPatientUrl == null) {
MciProperties mciProperties = new MciProperties(new Properties());
mciProperties.loadProperties();
mciPatientUrl = mciProperties.getMciPatientBaseURL();
}
return mciPatientUrl;
}
private String getAddressEntryText(String code) {
AddressHierarchyService addressHierarchyService = Context.getService(AddressHierarchyService.class);
AddressHierarchyEntry entry = addressHierarchyService.getAddressHierarchyEntryByUserGenId(code);
return entry.getName();
}
public static void main(String[] args) throws IOException {
MciPatientLookupController mciPatientLookupController = new MciPatientLookupController();
Patient nid107 = mciPatientLookupController.searchPatientByNationalId("nid107");
System.out.println(nid107);
}
}
| omod/src/main/java/org/openmrs/module/bdshrclient/web/controller/MciPatientLookupController.java | package org.openmrs.module.bdshrclient.web.controller;
import org.openmrs.api.context.Context;
import org.openmrs.module.addresshierarchy.AddressHierarchyEntry;
import org.openmrs.module.addresshierarchy.service.AddressHierarchyService;
import org.openmrs.module.bdshrclient.model.Address;
import org.openmrs.module.bdshrclient.model.Patient;
import org.openmrs.module.bdshrclient.service.MciPatientService;
import org.openmrs.module.bdshrclient.util.GenderEnum;
import org.openmrs.module.bdshrclient.util.MciProperties;
import org.openmrs.module.bdshrclient.util.WebClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
@Controller
@RequestMapping(value = "/mci")
public class MciPatientLookupController {
@Autowired
MciPatientService mciPatientService;
private String mciPatientUrl = null;
@RequestMapping(method = RequestMethod.GET, value = "/search")
@ResponseBody
public Object search(MciPatientSearchRequest request) {
if (request.getNid() != null) {
Patient mciPatient = searchPatientByNationalId(request.getNid());
if (mciPatient != null) {
return mapToPatientUIModel(mciPatient);
}
}
return null;
}
//@RequestMapping(method = RequestMethod.POST, value = "/download")
@RequestMapping(method = RequestMethod.GET, value = "/download")
@ResponseBody
public Object download(MciPatientSearchRequest request) {
Patient mciPatient = searchPatientByHealthId(request.getHid());
if (mciPatient != null) {
Map<String, String> downloadResponse = new HashMap<String, String>();
org.openmrs.Patient emrPatient = mciPatientService.createOrUpdatePatient(mciPatient);
downloadResponse.put("uuid", emrPatient.getUuid());
return downloadResponse;
}
return null;
}
private Map<String, Object> mapToPatientUIModel(Patient mciPatient) {
Map<String, Object> patientModel = new HashMap<String, Object>();
patientModel.put("firstName", mciPatient.getFirstName());
patientModel.put("middleName", mciPatient.getMiddleName());
patientModel.put("lastName", mciPatient.getLastName());
patientModel.put("gender", GenderEnum.forCode(mciPatient.getGender()).name());
patientModel.put("nationalId", mciPatient.getNationalId());
patientModel.put("healthId", mciPatient.getHealthId());
patientModel.put("primaryContact", mciPatient.getPrimaryContact());
Map<String, String> addressModel = new HashMap<String, String>();
Address address = mciPatient.getAddress();
addressModel.put("address_line", address.getAddressLine());
addressModel.put("division", getAddressEntryText(address.getDivisionId()));
addressModel.put("district", getAddressEntryText(address.getDistrictId()));
addressModel.put("upazilla", getAddressEntryText(address.getUpazillaId()));
addressModel.put("union", getAddressEntryText(address.getUnionId()));
patientModel.put("address", addressModel);
return patientModel;
}
private Patient searchPatientByNationalId(String nid) {
String mciNationIdSearchUrl = null;
try {
mciNationIdSearchUrl = String.format("%s?nid=%s", getMciPatientBaseUrl(), nid);
WebClient webClient = new WebClient();
Patient mciPatient = webClient.get(mciNationIdSearchUrl, Patient.class);
return mciPatient;
} catch (IOException e) {
throw new RuntimeException("Error occurred while trying to query MCI", e);
}
}
private Patient searchPatientByHealthId(String hid) {
if ((hid == null) || "".equals(hid)) return null;
try {
String mciPatientUrl = String.format("%s/%s", getMciPatientBaseUrl(), hid);
WebClient webClient = new WebClient();
Patient mciPatient = webClient.get(mciPatientUrl, Patient.class);
return mciPatient;
} catch (IOException e) {
throw new RuntimeException("Error occurred while trying to query MCI", e);
}
}
private String getMciPatientBaseUrl() throws IOException {
if (mciPatientUrl == null) {
MciProperties mciProperties = new MciProperties(new Properties());
mciProperties.loadProperties();
mciPatientUrl = mciProperties.getMciPatientBaseURL();
}
return mciPatientUrl;
}
private String getAddressEntryText(String code) {
AddressHierarchyService addressHierarchyService = Context.getService(AddressHierarchyService.class);
AddressHierarchyEntry entry = addressHierarchyService.getAddressHierarchyEntryByUserGenId(code);
return entry.getName();
}
public static void main(String[] args) throws IOException {
MciPatientLookupController mciPatientLookupController = new MciPatientLookupController();
Patient nid107 = mciPatientLookupController.searchPatientByNationalId("nid107");
System.out.println(nid107);
}
}
| angshu | fixed searching by Health ID
| omod/src/main/java/org/openmrs/module/bdshrclient/web/controller/MciPatientLookupController.java | angshu | fixed searching by Health ID | <ide><path>mod/src/main/java/org/openmrs/module/bdshrclient/web/controller/MciPatientLookupController.java
<ide> import org.openmrs.module.bdshrclient.util.WebClient;
<ide> import org.springframework.beans.factory.annotation.Autowired;
<ide> import org.springframework.stereotype.Controller;
<del>import org.springframework.web.bind.annotation.RequestBody;
<ide> import org.springframework.web.bind.annotation.RequestMapping;
<ide> import org.springframework.web.bind.annotation.RequestMethod;
<ide> import org.springframework.web.bind.annotation.ResponseBody;
<ide> @RequestMapping(method = RequestMethod.GET, value = "/search")
<ide> @ResponseBody
<ide> public Object search(MciPatientSearchRequest request) {
<del> if (request.getNid() != null) {
<del> Patient mciPatient = searchPatientByNationalId(request.getNid());
<del> if (mciPatient != null) {
<del> return mapToPatientUIModel(mciPatient);
<del> }
<add> Patient mciPatient = null;
<add> if (!isBlankString(request.getNid())) {
<add> mciPatient = searchPatientByNationalId(request.getNid());
<add>
<add> } else if (!isBlankString(request.getHid())) {
<add> mciPatient = searchPatientByHealthId(request.getHid());
<add> }
<add>
<add> if (mciPatient != null) {
<add> return mapToPatientUIModel(mciPatient);
<ide> }
<ide> return null;
<ide> }
<ide>
<ide> patientModel.put("address", addressModel);
<ide> return patientModel;
<add> }
<add>
<add> private boolean isBlankString(String value) {
<add> if ((value != null) && !"".equals(value)) {
<add> return false;
<add> }
<add> return true;
<ide> }
<ide>
<ide> private Patient searchPatientByNationalId(String nid) { |
|
Java | lgpl-2.1 | 1310372777ee2e5d12fe202fc9b1a5adf1bf2456 | 0 | csrg-utfsm/acscb,csrg-utfsm/acscb,jbarriosc/ACSUFRO,jbarriosc/ACSUFRO,jbarriosc/ACSUFRO,csrg-utfsm/acscb,jbarriosc/ACSUFRO,csrg-utfsm/acscb,ACS-Community/ACS,csrg-utfsm/acscb,ACS-Community/ACS,ACS-Community/ACS,csrg-utfsm/acscb,jbarriosc/ACSUFRO,ACS-Community/ACS,jbarriosc/ACSUFRO,jbarriosc/ACSUFRO,csrg-utfsm/acscb,ACS-Community/ACS,ACS-Community/ACS,jbarriosc/ACSUFRO,csrg-utfsm/acscb,jbarriosc/ACSUFRO,ACS-Community/ACS,ACS-Community/ACS | package alma.acs.concurrent;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;
/**
* Helper class that allows tests (but also other code) to be executed concurrently.
* One of the advantages of using this class is that it synchronizes the actual execution of all threads,
* while simple creation and starting of threads does not guarantee that these threads run after {@link Thread#start()} returns.
*
* Thus using this class should be particularly helpful for "mean" tests that try to bombard a tested class with parallel calls,
* all arriving in the smallest possible time window.
*
* @author hsommer
*/
public class ParallelExecutor
{
private final ThreadFactory tf;
private final CountDownLatch threadGate;
private volatile boolean executed = false;
/**
* @param tf For components, clients and unit tests, this should be taken from container services method getThreadFactory.
*/
public ParallelExecutor(ThreadFactory tf) {
this.tf = tf;
threadGate = new CountDownLatch(1);
}
/**
* Creates and starts a new thread, waits until it runs,
* but blocks it from calling {@code runnable#run}
* until {@link #execute()} is called.
*
* @param runnable your code that should be run in a separate thread
* @param timeoutMillis timeout in milliseconds: code will not be run if {@link #execute()}
* is not called within this time.
* This is meant to avoid troubles with deadlocked threads in case something goes wrong.
* @throws InterruptedException
* @throws IllegalStateException If called after {@link #execute()} or {@link #execute(List, long)}.
*/
public void scheduleForExecution(Runnable runnable, long timeoutMillis) throws InterruptedException {
if (executed) {
throw new IllegalStateException();
}
CountDownLatch confirmWaiting = new CountDownLatch(1);
InterceptingRunnable interceptingRunnable = new InterceptingRunnable(runnable, threadGate, confirmWaiting, timeoutMillis);
Thread t = tf.newThread(interceptingRunnable);
t.start();
// wait till the thread has started, otherwise the execute() call might come too early
// and the threads would wait for it till they time out.
confirmWaiting.await(timeoutMillis, TimeUnit.MILLISECONDS);
}
/**
* Unleash all threads. The run methods of all runnables submitted to {@link #scheduleForExecution(Runnable, long)}
* should then be called immediately.
*/
public void execute() {
threadGate.countDown();
executed = true;
}
/**
* Convenience method that combines {@link #scheduleForExecution(Runnable)} and {@link #execute()}.
* @param runnables
* @throws InterruptedException
*/
public void execute(List<Runnable> runnables, long timeoutMillis) throws InterruptedException {
for (Runnable runnable : runnables) {
scheduleForExecution(runnable, timeoutMillis);
}
execute();
}
private static class InterceptingRunnable implements Runnable {
private final Runnable delegate;
private final CountDownLatch threadGate;
private final CountDownLatch confirmWaiting;
private final long timeoutMillis;
InterceptingRunnable(Runnable delegate, CountDownLatch threadGate, CountDownLatch confirmWaiting, long timeoutMillis) {
this.delegate = delegate;
this.threadGate = threadGate;
this.confirmWaiting = confirmWaiting;
this.timeoutMillis = timeoutMillis;
}
public void run() {
boolean success = false;
try {
confirmWaiting.countDown();
// condition.await will unlock the lock and wait...
if(threadGate.await(timeoutMillis, TimeUnit.MILLISECONDS) == false) {
// got a timeout
System.out.println("Got a timeout from condition.await()");
}
else {
delegate.run();
success = true;
}
} catch (InterruptedException ex) {
// TODO Auto-generated catch block
ex.printStackTrace();
}
// TODO: handle !success better than this
if (!success) {
System.out.println("Damn, run() failed in thread " + Thread.currentThread().getName());
}
}
}
}
| LGPL/CommonSoftware/jacsutil/src/alma/acs/concurrent/ParallelExecutor.java | package alma.acs.concurrent;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
/**
* Helper class that allows tests (but also other code) to be executed concurrently.
* One of the advantages of using this class is that it synchronizes the actual execution of all threads,
* while simple creation and starting of threads does not guarantee that these threads run after {@link Thread#start()} returns.
*
* Thus using this class should be particularly helpful for "mean" tests that try to bombard a tested class with parallel calls,
* all arriving in the smallest possible time window.
*
* @author hsommer
*/
public class ParallelExecutor
{
private final ThreadFactory tf;
private final ReentrantLock lock;
private final Condition readyToRun;
private final List<Thread> scheduledThreads;
/**
* @param tf For components, clients and unit tests, this should be taken from container services method getThreadFactory.
*/
public ParallelExecutor(ThreadFactory tf) {
this.tf = tf;
lock = new ReentrantLock();
readyToRun = lock.newCondition();
scheduledThreads = new ArrayList<Thread>();
}
/**
* Creates and starts a new thread, waits until it runs,
* but blocks it from calling {@code runnable#run}
* until {@link #execute()} is called.
*
* @param runnable your code that should be run in a separate thread
* @param timeoutMillis timeout in milliseconds: code will not be run if {@link #execute()}
* is not called within this time.
* This is meant to avoid troubles with deadlocked threads in case something goes wrong.
* @throws InterruptedException
*/
public void scheduleForExecution(Runnable runnable, long timeoutMillis) throws InterruptedException {
CountDownLatch confirmWaiting = new CountDownLatch(1);
InterceptingRunnable interceptingRunnable = new InterceptingRunnable(runnable, lock, readyToRun, confirmWaiting, timeoutMillis);
Thread t = tf.newThread(interceptingRunnable);
scheduledThreads.add(t);
t.start();
// wait till the thread has started, otherwise the execute() call might come too early
// and the threads would wait for it till they time out.
confirmWaiting.await(timeoutMillis, TimeUnit.MILLISECONDS);
// now that the thread has confirmed that it's running, we also know from the implementation
// of InterceptingRunnable#run that it already holds the lock.
// It will release this lock a few lines down by calling condition.await, so that by the time we can get the lock here,
// we know that the runnable is really parked on condition and will therefore be woken up by a future call to #execute()
lock.lock();
lock.unlock();
}
/**
* Unleash all threads. The run methods of all runnables submitted to {@link #scheduleForExecution(Runnable, long)}
* should then be called immediately.
*/
public void execute() {
lock.lock();
try {
readyToRun.signalAll();
}
finally {
lock.unlock();
}
}
/**
* Convenience method that combines {@link #scheduleForExecution(Runnable)} and {@link #execute()}.
* @param runnables
* @throws InterruptedException
*/
public void execute(List<Runnable> runnables, long timeoutMillis) throws InterruptedException {
for (Runnable runnable : runnables) {
scheduleForExecution(runnable, timeoutMillis);
}
execute();
}
private static class InterceptingRunnable implements Runnable {
private final Runnable delegate;
private final Lock lock;
private final Condition condition;
private final CountDownLatch confirmWaiting;
private final long timeoutMillis;
InterceptingRunnable(Runnable delegate, Lock lock, Condition condition, CountDownLatch confirmWaiting, long timeoutMillis) {
this.delegate = delegate;
this.lock = lock;
this.condition = condition;
this.confirmWaiting = confirmWaiting;
this.timeoutMillis = timeoutMillis;
}
public void run() {
boolean success = false;
lock.lock();
try {
confirmWaiting.countDown();
// condition.await will unlock the lock and wait...
if(condition.await(timeoutMillis, TimeUnit.MILLISECONDS) == false) {
// got a timeout
System.out.println("Got a timeout from condition.await()");
}
else {
delegate.run();
success = true;
}
} catch (InterruptedException ex) {
// TODO Auto-generated catch block
ex.printStackTrace();
}
finally {
lock.unlock();
}
// TODO: handle !success
}
}
}
| Changed implementation to use good old CountDownLatch as the thread gate, after the previous stab at using concurrent.locks.Condition failed to actually run the threads in parallel.
git-svn-id: afcf11d89342f630bd950d18a70234a9e277d909@104117 523d945c-050c-4681-91ec-863ad3bb968a
| LGPL/CommonSoftware/jacsutil/src/alma/acs/concurrent/ParallelExecutor.java | Changed implementation to use good old CountDownLatch as the thread gate, after the previous stab at using concurrent.locks.Condition failed to actually run the threads in parallel. | <ide><path>GPL/CommonSoftware/jacsutil/src/alma/acs/concurrent/ParallelExecutor.java
<ide> package alma.acs.concurrent;
<ide>
<del>import java.util.ArrayList;
<ide> import java.util.List;
<ide> import java.util.concurrent.CountDownLatch;
<ide> import java.util.concurrent.ThreadFactory;
<ide> import java.util.concurrent.TimeUnit;
<del>import java.util.concurrent.locks.Condition;
<del>import java.util.concurrent.locks.Lock;
<del>import java.util.concurrent.locks.ReentrantLock;
<ide>
<ide> /**
<ide> * Helper class that allows tests (but also other code) to be executed concurrently.
<ide> public class ParallelExecutor
<ide> {
<ide> private final ThreadFactory tf;
<del> private final ReentrantLock lock;
<del> private final Condition readyToRun;
<del> private final List<Thread> scheduledThreads;
<add> private final CountDownLatch threadGate;
<add> private volatile boolean executed = false;
<ide>
<ide> /**
<ide> * @param tf For components, clients and unit tests, this should be taken from container services method getThreadFactory.
<ide> */
<ide> public ParallelExecutor(ThreadFactory tf) {
<ide> this.tf = tf;
<del> lock = new ReentrantLock();
<del> readyToRun = lock.newCondition();
<del> scheduledThreads = new ArrayList<Thread>();
<add> threadGate = new CountDownLatch(1);
<ide> }
<ide>
<ide>
<ide> * @param timeoutMillis timeout in milliseconds: code will not be run if {@link #execute()}
<ide> * is not called within this time.
<ide> * This is meant to avoid troubles with deadlocked threads in case something goes wrong.
<del> * @throws InterruptedException
<add> * @throws InterruptedException
<add> * @throws IllegalStateException If called after {@link #execute()} or {@link #execute(List, long)}.
<ide> */
<ide> public void scheduleForExecution(Runnable runnable, long timeoutMillis) throws InterruptedException {
<add> if (executed) {
<add> throw new IllegalStateException();
<add> }
<ide> CountDownLatch confirmWaiting = new CountDownLatch(1);
<del> InterceptingRunnable interceptingRunnable = new InterceptingRunnable(runnable, lock, readyToRun, confirmWaiting, timeoutMillis);
<add> InterceptingRunnable interceptingRunnable = new InterceptingRunnable(runnable, threadGate, confirmWaiting, timeoutMillis);
<ide> Thread t = tf.newThread(interceptingRunnable);
<del> scheduledThreads.add(t);
<ide> t.start();
<ide> // wait till the thread has started, otherwise the execute() call might come too early
<ide> // and the threads would wait for it till they time out.
<ide> confirmWaiting.await(timeoutMillis, TimeUnit.MILLISECONDS);
<del> // now that the thread has confirmed that it's running, we also know from the implementation
<del> // of InterceptingRunnable#run that it already holds the lock.
<del> // It will release this lock a few lines down by calling condition.await, so that by the time we can get the lock here,
<del> // we know that the runnable is really parked on condition and will therefore be woken up by a future call to #execute()
<del> lock.lock();
<del> lock.unlock();
<ide> }
<ide>
<ide>
<ide> * should then be called immediately.
<ide> */
<ide> public void execute() {
<del> lock.lock();
<del> try {
<del> readyToRun.signalAll();
<del> }
<del> finally {
<del> lock.unlock();
<del> }
<add> threadGate.countDown();
<add> executed = true;
<ide> }
<ide>
<ide> /**
<ide>
<ide> private static class InterceptingRunnable implements Runnable {
<ide> private final Runnable delegate;
<del> private final Lock lock;
<del> private final Condition condition;
<add> private final CountDownLatch threadGate;
<ide> private final CountDownLatch confirmWaiting;
<ide> private final long timeoutMillis;
<ide>
<del> InterceptingRunnable(Runnable delegate, Lock lock, Condition condition, CountDownLatch confirmWaiting, long timeoutMillis) {
<add> InterceptingRunnable(Runnable delegate, CountDownLatch threadGate, CountDownLatch confirmWaiting, long timeoutMillis) {
<ide> this.delegate = delegate;
<del> this.lock = lock;
<del> this.condition = condition;
<add> this.threadGate = threadGate;
<ide> this.confirmWaiting = confirmWaiting;
<ide> this.timeoutMillis = timeoutMillis;
<ide> }
<ide>
<ide> public void run() {
<ide> boolean success = false;
<del> lock.lock();
<ide> try {
<ide> confirmWaiting.countDown();
<ide> // condition.await will unlock the lock and wait...
<del> if(condition.await(timeoutMillis, TimeUnit.MILLISECONDS) == false) {
<add> if(threadGate.await(timeoutMillis, TimeUnit.MILLISECONDS) == false) {
<ide> // got a timeout
<ide> System.out.println("Got a timeout from condition.await()");
<ide> }
<ide> // TODO Auto-generated catch block
<ide> ex.printStackTrace();
<ide> }
<del> finally {
<del> lock.unlock();
<add> // TODO: handle !success better than this
<add> if (!success) {
<add> System.out.println("Damn, run() failed in thread " + Thread.currentThread().getName());
<ide> }
<del> // TODO: handle !success
<ide> }
<ide> }
<ide> } |
|
JavaScript | mit | 05a034e1a4c52e43ad38b34863cd3462f4f9beac | 0 | kittn/generator-kittn,kittn/generator-kittn,kittn/generator-kittn,kittn/generator-kittn | /**
* Webpack Config for Javascript and CSS Bundling
*
* @package generator-mh-boilerplate
* @author Martin Herweg <[email protected]>
*/
import webpack from 'webpack'
import { getIfUtils, removeEmpty } from 'webpack-config-utils'
import path from 'path'
import config from '../config.json'
import ExtractTextPlugin from 'extract-text-webpack-plugin'
import HtmlWebpackPlugin from 'html-webpack-plugin'
import WriteFilePlugin from 'write-file-webpack-plugin'
import FriendlyErrorsWebpackPlugin from 'friendly-errors-webpack-plugin'
import Webpack2Polyfill from 'webpack2-polyfill-plugin'<% if ( projectjsframework === 'vue' && projectstylelint) { %>
import StylelintPlugin from 'stylelint-webpack-plugin'<% } %>
import { BundleAnalyzerPlugin } from 'webpack-bundle-analyzer'
const {
ifProduction,
ifDevelopment
} = getIfUtils(process.env.NODE_ENV)
/*
|--------------------------------------------------------------------------
| Setting some paths for our Application
|--------------------------------------------------------------------------
*/
const BASE_PATH = path.join(path.resolve(__dirname, '../'))
const ASSETS_ROOT = path.resolve(BASE_PATH, config.dist.base)
const JS_ROOT = path.resolve(BASE_PATH, config.src.js)
const JS_DIST = path.resolve(BASE_PATH, config.dist.js)
let outputPath = ASSETS_ROOT
if (ifDevelopment()) {
outputPath = JS_DIST
}
/*
|--------------------------------------------------------------------------
| Hot Middleware Client
|--------------------------------------------------------------------------
*/
const hotClient =
'webpack-hot-middleware/client?path=/__webpack_hmr&timeout=20000&reload=true&overlay=true'
/*
|--------------------------------------------------------------------------
| Defining Entry Points, could be used to manually split Parts of the Application, for example
| Admin Javascript and FrontEnd JavaScript
|--------------------------------------------------------------------------
*/
const entryPoints = {}
Object.keys(config.src.jsEntryPoints).forEach(
entry => (entryPoints[entry] = ifDevelopment() ? [hotClient].concat(`${JS_ROOT}/${config.src.jsEntryPoints[entry]}`) : `${JS_ROOT}/${config.src.jsEntryPoints[entry]}`)
)
function assetsPath (_path) {
return path.posix.join('assets/', _path)
}
const chunks = []
const chunksInject = [
{
filename: path.resolve(`${config.dist.markup}index.html`),
file: null,
inject: false
}
]
chunksInject.forEach((chunk) => {
const plugin = new HtmlWebpackPlugin({
filename: chunk.filename,
inject: chunk.inject,
minify: false,
// necessary to consistently work with multiple chunks via CommonsChunkPlugin
chunksSortMode: 'dependency'
})
chunks.push(plugin)
})
/*
|--------------------------------------------------------------------------
| return webpack config object
|--------------------------------------------------------------------------
*/
export default {
// we have to use source map for css source maps, slightly longer compile times
// devtool: 'source-map',
context: BASE_PATH,
// entry is a function so that we can use environment variables
entry: removeEmpty(entryPoints),
output: {
path: outputPath,
publicPath: '',
filename: ifProduction(
assetsPath('js/[name].js')
),
chunkFilename: assetsPath('js/[id].js')
},
resolve: {
extensions: ['.js', '.json', '.vue'],
modules: [resolve(config.src.base), resolve('node_modules')],
alias: {
src: resolve(config.src.base)
}
},
module: {
rules: [
{
test: /\.(js)$/,
loader: 'eslint-loader',
options: {
formatter: require('eslint-friendly-formatter')
},
enforce: 'pre',
include: resolve(config.src.base)
},
{
test: /\.js$/,
use: 'babel-loader',
include: resolve(config.src.base)
},<% if ( projectjsframework === 'vue') { %>
{
test: /\.vue$/,
loader: 'vue-loader',
options: {
loaders: {
scss: ifProduction(
ExtractTextPlugin.extract({
use: 'css-loader!postcss-loader!sass-loader',
fallback: 'vue-style-loader'
}),
'vue-style-loader!css-loader!postcss-loader!sass-loader'
)
}
}
},<% } %>
{
test: /\.json$/,
use: 'json-loader'
}
]
},
plugins: removeEmpty([
new Webpack2Polyfill(),
ifProduction(
new BundleAnalyzerPlugin({
analyzerMode: 'disabled',
generateStatsFile: true,
statsFilename: `${BASE_PATH}/webpack/stats.json`,
logLevel: 'info'
})
),
ifDevelopment(new webpack.HotModuleReplacementPlugin()),
ifDevelopment(new webpack.NamedModulesPlugin()),
ifDevelopment(new webpack.NoEmitOnErrorsPlugin()),
ifDevelopment(new FriendlyErrorsWebpackPlugin()),
ifProduction(
new webpack.DefinePlugin({
'process.env': {
NODE_ENV: '"production"'
}
})
),
ifProduction(
new webpack.optimize.UglifyJsPlugin({
sourceMap: true,
compress: {
warnings: false
}
})
),
ifProduction(
new webpack.LoaderOptionsPlugin({
minimize: true,
options: {
eslint: {
configFile: './.eslintrc.js'
}
}
})
),
ifDevelopment(
new webpack.LoaderOptionsPlugin({
options: {
eslint: {
failOnError: false,
failOnWarning: false,
configFile: './.eslintrc-dev.js',
formatter: require('eslint-formatter-pretty')
}
}
})
),
new ExtractTextPlugin({
filename: assetsPath('css/vue-style.css')
}),<% if ( projectjsframework === 'vue' && projectstylelint) { %>
new StylelintPlugin({
context: JS_ROOT,
syntax: 'scss'
}),<% } %>
...chunks,
new WriteFilePlugin({
log: true,
test: /^(?!.+(?:hot-update.(js|json))).+$/
}),
new webpack.optimize.ModuleConcatenationPlugin()
])
}
function resolve (dir) {
return path.join(__dirname, '..', dir)
}
| generators/app/templates/webpack/webpack.config.babel.js | /**
* Webpack Config for Javascript and CSS Bundling
*
* @package generator-mh-boilerplate
* @author Martin Herweg <[email protected]>
*/
import webpack from 'webpack'
import { getIfUtils, removeEmpty } from 'webpack-config-utils'
import path from 'path'
import config from '../config.json'
import ExtractTextPlugin from 'extract-text-webpack-plugin'
import HtmlWebpackPlugin from 'html-webpack-plugin'
import WriteFilePlugin from 'write-file-webpack-plugin'
import FriendlyErrorsWebpackPlugin from 'friendly-errors-webpack-plugin'
import Webpack2Polyfill from 'webpack2-polyfill-plugin'<% if ( projectjsframework === 'vue' && projectstylelint) { %>
import StylelintPlugin from 'stylelint-webpack-plugin'<% } %>
import { BundleAnalyzerPlugin } from 'webpack-bundle-analyzer'
const {
ifProduction,
ifDevelopment
} = getIfUtils(process.env.NODE_ENV)
/*
|--------------------------------------------------------------------------
| Setting some paths for our Application
|--------------------------------------------------------------------------
*/
const BASE_PATH = path.join(path.resolve(__dirname, '../'))
const ASSETS_ROOT = path.resolve(BASE_PATH, config.dist.base)
const JS_ROOT = path.resolve(BASE_PATH, config.src.js)
const JS_DIST = path.resolve(BASE_PATH, config.dist.js)
let outputPath = ASSETS_ROOT
if (ifDevelopment()) {
outputPath = JS_DIST
}
/*
|--------------------------------------------------------------------------
| Hot Middleware Client
|--------------------------------------------------------------------------
*/
const hotClient =
'webpack-hot-middleware/client?path=/__webpack_hmr&timeout=20000&reload=true&overlay=true'
/*
|--------------------------------------------------------------------------
| Defining Entry Points, could be used to manually split Parts of the Application, for example
| Admin Javascript and FrontEnd JavaScript
|--------------------------------------------------------------------------
*/
const entryPoints = {}
Object.keys(config.src.jsEntryPoints).forEach(
entry => (entryPoints[entry] = ifDevelopment() ? [hotClient].concat(`${JS_ROOT}/${config.src.jsEntryPoints[entry]}`) : `${JS_ROOT}/${config.src.jsEntryPoints[entry]}`)
)
function assetsPath (_path) {
return path.posix.join('assets/', _path)
}
const chunks = []
const chunksInject = [
{
filename: path.resolve(`${config.dist.markup}index.html`),
file: null,
inject: false
}
]
chunksInject.forEach((chunk) => {
const plugin = new HtmlWebpackPlugin({
filename: chunk.filename,
inject: chunk.inject,
minify: false,
// necessary to consistently work with multiple chunks via CommonsChunkPlugin
chunksSortMode: 'dependency'
})
chunks.push(plugin)
})
/*
|--------------------------------------------------------------------------
| return webpack config object
|--------------------------------------------------------------------------
*/
export default {
// we have to use source map for css source maps, slightly longer compile times
// devtool: 'source-map',
context: BASE_PATH,
// entry is a function so that we can use environment variables
entry: removeEmpty(entryPoints),
output: {
path: outputPath,
publicPath: '',
filename: ifProduction(
assetsPath('js/[name].js')
),
chunkFilename: assetsPath('js/[id].js')
},
resolve: {
extensions: ['.js', '.json', '.vue'],
modules: [resolve(config.src.base), resolve('node_modules')],
alias: {
src: resolve(config.src.base)
}
},
module: {
rules: [
{
test: /\.(js)$/,
loader: 'eslint-loader',
options: {
formatter: require('eslint-friendly-formatter')
},
enforce: 'pre',
include: resolve(config.src.base)
},
{
test: /\.js$/,
use: 'babel-loader',
include: resolve(config.src.base)
},<% if ( projectjsframework === 'vue') { %>
{
test: /\.vue$/,
use: 'vue-loader',
options: {
loaders: {
scss: ifProduction(
ExtractTextPlugin.extract({
use: 'css-loader!postcss-loader!sass-loader',
fallback: 'vue-style-loader'
}),
'vue-style-loader!css-loader!postcss-loader!sass-loader'
)
}
}
},<% } %>
{
test: /\.json$/,
use: 'json-loader'
}
// {
// test: /\.scss$/,
// include: resolve(config.src.css),
// exclude: [resolve('node_modules'), resolve('dist/')],
// use: ExtractTextPlugin.extract({
// fallback: 'style-loader',
// use: [
// {
// loader: 'css-loader',
// options: {
// autoprefixer: false,
// sourceMap: true,
// importLoaders: 3,
// url: false
// }
// },
// {
// loader: 'postcss-loader',
// options: {
// sourceMap: true
// }
// },
// {
// loader: 'sass-loader',
// options: {
// sourceMap: true
// }
// }
// ]
// })
// }
]
},
plugins: removeEmpty([
new Webpack2Polyfill(),
// new CleanWebpackPlugin([config.dist.css, config.dist.js], {
// root: BASE_PATH,
// verbose: true
// }),
ifProduction(
new BundleAnalyzerPlugin({
analyzerMode: 'disabled',
generateStatsFile: true,
statsFilename: `${BASE_PATH}/webpack/stats.json`,
logLevel: 'info'
})
),
ifDevelopment(new webpack.HotModuleReplacementPlugin()),
ifDevelopment(new webpack.NamedModulesPlugin()),
ifDevelopment(new webpack.NoEmitOnErrorsPlugin()),
ifDevelopment(new FriendlyErrorsWebpackPlugin()),
ifProduction(
new webpack.DefinePlugin({
'process.env': {
NODE_ENV: '"production"'
}
})
),
ifProduction(
new webpack.optimize.UglifyJsPlugin({
sourceMap: true,
compress: {
warnings: false
}
})
),
ifProduction(
new webpack.optimize.CommonsChunkPlugin({
name: 'vendor',
minChunks: function (module) {
// this assumes your vendor imports exist in the node_modules directory
return (
module.context && module.context.indexOf('node_modules') !== -1
)
}
})
),
ifProduction(
// extract webpack runtime and module manifest to its own file in order to
// prevent vendor hash from being updated whenever app bundle is updated
new webpack.optimize.CommonsChunkPlugin({
name: 'manifest',
chunks: ['vendor']
})
),
ifProduction(
new webpack.LoaderOptionsPlugin({
minimize: true,
options: {
eslint: {
configFile: './.eslintrc.js'
}
}
})
),
ifDevelopment(
new webpack.LoaderOptionsPlugin({
options: {
eslint: {
failOnError: false,
failOnWarning: false,
configFile: './.eslintrc-dev.js',
formatter: require('eslint-formatter-pretty')
}
}
})
),
new ExtractTextPlugin({
filename: assetsPath('css/vue-style.css')
}),<% if ( projectjsframework === 'vue' && projectstylelint) { %>
new StylelintPlugin({
context: JS_ROOT,
syntax: 'scss'
}),<% } %>
...chunks,
new WriteFilePlugin({
log: true,
test: /^(?!.+(?:hot-update.(js|json))).+$/
}),
new webpack.optimize.ModuleConcatenationPlugin()
])
}
function resolve (dir) {
return path.join(__dirname, '..', dir)
}
| Fix Vue-Loader
Disable manifest and vendor-chunks
| generators/app/templates/webpack/webpack.config.babel.js | Fix Vue-Loader Disable manifest and vendor-chunks | <ide><path>enerators/app/templates/webpack/webpack.config.babel.js
<ide> },<% if ( projectjsframework === 'vue') { %>
<ide> {
<ide> test: /\.vue$/,
<del> use: 'vue-loader',
<add> loader: 'vue-loader',
<ide> options: {
<ide> loaders: {
<ide> scss: ifProduction(
<ide> test: /\.json$/,
<ide> use: 'json-loader'
<ide> }
<del> // {
<del> // test: /\.scss$/,
<del> // include: resolve(config.src.css),
<del> // exclude: [resolve('node_modules'), resolve('dist/')],
<del> // use: ExtractTextPlugin.extract({
<del> // fallback: 'style-loader',
<del> // use: [
<del> // {
<del> // loader: 'css-loader',
<del> // options: {
<del> // autoprefixer: false,
<del> // sourceMap: true,
<del> // importLoaders: 3,
<del> // url: false
<del> // }
<del> // },
<del> // {
<del> // loader: 'postcss-loader',
<del> // options: {
<del> // sourceMap: true
<del> // }
<del> // },
<del> // {
<del> // loader: 'sass-loader',
<del> // options: {
<del> // sourceMap: true
<del> // }
<del> // }
<del> // ]
<del> // })
<del> // }
<ide> ]
<ide> },
<ide> plugins: removeEmpty([
<ide> new Webpack2Polyfill(),
<del> // new CleanWebpackPlugin([config.dist.css, config.dist.js], {
<del> // root: BASE_PATH,
<del> // verbose: true
<del> // }),
<ide> ifProduction(
<ide> new BundleAnalyzerPlugin({
<ide> analyzerMode: 'disabled',
<ide> compress: {
<ide> warnings: false
<ide> }
<del> })
<del> ),
<del> ifProduction(
<del> new webpack.optimize.CommonsChunkPlugin({
<del> name: 'vendor',
<del> minChunks: function (module) {
<del> // this assumes your vendor imports exist in the node_modules directory
<del> return (
<del> module.context && module.context.indexOf('node_modules') !== -1
<del> )
<del> }
<del> })
<del> ),
<del> ifProduction(
<del> // extract webpack runtime and module manifest to its own file in order to
<del> // prevent vendor hash from being updated whenever app bundle is updated
<del> new webpack.optimize.CommonsChunkPlugin({
<del> name: 'manifest',
<del> chunks: ['vendor']
<ide> })
<ide> ),
<ide> ifProduction( |
|
Java | apache-2.0 | afd12b2c1af3f605092d0679aac8afd46a861159 | 0 | darshanasbg/identity-inbound-auth-oauth,chirankavinda123/identity-inbound-auth-oauth,darshanasbg/identity-inbound-auth-oauth,chirankavinda123/identity-inbound-auth-oauth,IsuraD/identity-inbound-auth-oauth,wso2-extensions/identity-inbound-auth-oauth,IsuraD/identity-inbound-auth-oauth,wso2-extensions/identity-inbound-auth-oauth | /*
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.wso2.carbon.identity.oauth2.internal;
import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.StringUtils;
import org.wso2.carbon.identity.application.common.IdentityApplicationManagementException;
import org.wso2.carbon.identity.application.common.model.InboundAuthenticationConfig;
import org.wso2.carbon.identity.application.common.model.InboundAuthenticationRequestConfig;
import org.wso2.carbon.identity.application.common.model.Property;
import org.wso2.carbon.identity.application.common.model.ServiceProvider;
import org.wso2.carbon.identity.application.mgt.ApplicationManagementService;
import org.wso2.carbon.identity.application.mgt.listener.AbstractApplicationMgtListener;
import org.wso2.carbon.identity.oauth.IdentityOAuthAdminException;
import org.wso2.carbon.identity.oauth.cache.AppInfoCache;
import org.wso2.carbon.identity.oauth.cache.AuthorizationGrantCache;
import org.wso2.carbon.identity.oauth.cache.AuthorizationGrantCacheEntry;
import org.wso2.carbon.identity.oauth.cache.AuthorizationGrantCacheKey;
import org.wso2.carbon.identity.oauth.cache.CacheEntry;
import org.wso2.carbon.identity.oauth.cache.OAuthCache;
import org.wso2.carbon.identity.oauth.cache.OAuthCacheKey;
import org.wso2.carbon.identity.oauth.config.OAuthServerConfiguration;
import org.wso2.carbon.identity.oauth.dao.OAuthAppDAO;
import org.wso2.carbon.identity.oauth.dao.OAuthConsumerDAO;
import org.wso2.carbon.identity.oauth2.IdentityOAuth2Exception;
import org.wso2.carbon.identity.oauth2.dao.TokenMgtDAO;
import java.util.HashSet;
import java.util.Set;
public class OAuthApplicationMgtListener extends AbstractApplicationMgtListener {
public static final String OAUTH2 = "oauth2";
public static final String OAUTH2_CONSUMER_SECRET = "oauthConsumerSecret";
private static final String OAUTH = "oauth";
@Override
public int getDefaultOrderId() {
return 11;
}
public boolean doPreUpdateApplication(ServiceProvider serviceProvider, String tenantDomain, String userName)
throws IdentityApplicationManagementException {
removeClientSecret(serviceProvider);
return true;
}
public boolean doPostGetServiceProvider(ServiceProvider serviceProvider, String serviceProviderName, String tenantDomain)
throws IdentityApplicationManagementException {
addClientSecret(serviceProvider);
return true;
}
public boolean doPostGetServiceProviderByClientId(ServiceProvider serviceProvider, String clientId, String clientType,
String tenantDomain) throws IdentityApplicationManagementException {
addClientSecret(serviceProvider);
return true;
}
public boolean doPostCreateApplication(ServiceProvider serviceProvider, String tenantDomain, String userName) throws IdentityApplicationManagementException {
addClientSecret(serviceProvider);
return true;
}
public boolean doPostUpdateApplication(ServiceProvider serviceProvider, String tenantDomain, String userName) throws IdentityApplicationManagementException {
addClientSecret(serviceProvider);
updateAuthApplication(serviceProvider);
if (OAuthServerConfiguration.getInstance().isCacheEnabled()) {
removeEntriesFromCache(serviceProvider, tenantDomain, userName);
}
return true;
}
@Override
public boolean doPostGetApplicationExcludingFileBasedSPs(ServiceProvider serviceProvider, String applicationName, String tenantDomain) throws IdentityApplicationManagementException {
addClientSecret(serviceProvider);
return true;
}
@Override
public boolean doPreDeleteApplication(String applicationName, String tenantDomain, String userName) throws IdentityApplicationManagementException {
ApplicationManagementService applicationMgtService = OAuth2ServiceComponentHolder.getApplicationMgtService();
ServiceProvider serviceProvider = applicationMgtService.getApplicationExcludingFileBasedSPs(applicationName, tenantDomain);
if (OAuthServerConfiguration.getInstance().isCacheEnabled()) {
removeEntriesFromCache(serviceProvider, tenantDomain, userName);
}
return true;
}
private void removeClientSecret(ServiceProvider serviceProvider) {
InboundAuthenticationConfig inboundAuthenticationConfig = serviceProvider.getInboundAuthenticationConfig();
if (inboundAuthenticationConfig != null) {
InboundAuthenticationRequestConfig[] inboundRequestConfigs = inboundAuthenticationConfig.
getInboundAuthenticationRequestConfigs();
if (inboundRequestConfigs != null) {
for (InboundAuthenticationRequestConfig inboundRequestConfig : inboundRequestConfigs) {
if (inboundRequestConfig.getInboundAuthType().equals(OAUTH2)) {
Property[] props = inboundRequestConfig.getProperties();
for (Property prop : props) {
if (prop.getName().equalsIgnoreCase(OAUTH2_CONSUMER_SECRET)) {
props = (Property[]) ArrayUtils.removeElement(props, prop);
inboundRequestConfig.setProperties(props);
continue; //we are interested only on this property
} else {
//ignore
}
}
continue;// we are interested only on oauth2 config. Only one will be present.
} else {
//ignore
}
}
} else {
//ignore
}
} else {
//nothing to do
}
}
private void addClientSecret(ServiceProvider serviceProvider) throws IdentityApplicationManagementException {
if (serviceProvider == null) {
return; // if service provider is not present no need to add this information
}
try {
InboundAuthenticationConfig inboundAuthenticationConfig = serviceProvider.getInboundAuthenticationConfig();
if (inboundAuthenticationConfig != null) {
InboundAuthenticationRequestConfig[] inboundRequestConfigs = inboundAuthenticationConfig.
getInboundAuthenticationRequestConfigs();
if (inboundRequestConfigs != null) {
for (InboundAuthenticationRequestConfig inboundRequestConfig : inboundRequestConfigs) {
if (inboundRequestConfig.getInboundAuthType().equals(OAUTH2)) {
Property[] props = inboundRequestConfig.getProperties();
Property property = new Property();
property.setName(OAUTH2_CONSUMER_SECRET);
property.setValue(getClientSecret(inboundRequestConfig.getInboundAuthKey()));
props = (Property[]) ArrayUtils.add(props, property);
inboundRequestConfig.setProperties(props);
continue;// we are interested only on oauth2 config. Only one will be present.
} else {
//ignore
}
}
} else {
//ignore
}
} else {
//nothing to do
}
} catch (IdentityOAuthAdminException e) {
throw new IdentityApplicationManagementException("Injecting client secret failed.", e);
}
return;
}
private String getClientSecret(String inboundAuthKey) throws IdentityOAuthAdminException {
OAuthConsumerDAO dao = new OAuthConsumerDAO();
return dao.getOAuthConsumerSecret(inboundAuthKey);
}
/**
* Update the application name if OAuth application presents.
*
* @param serviceProvider Service provider
* @throws IdentityApplicationManagementException
*/
private void updateAuthApplication(ServiceProvider serviceProvider)
throws IdentityApplicationManagementException {
InboundAuthenticationRequestConfig authenticationRequestConfigConfig = null;
if (serviceProvider.getInboundAuthenticationConfig() != null &&
serviceProvider.getInboundAuthenticationConfig()
.getInboundAuthenticationRequestConfigs() != null) {
for (InboundAuthenticationRequestConfig authConfig : serviceProvider.getInboundAuthenticationConfig()
.getInboundAuthenticationRequestConfigs()) {
if (StringUtils.equals(authConfig.getInboundAuthType(), "oauth") ||
StringUtils.equals(authConfig.getInboundAuthType(), "oauth2")) {
authenticationRequestConfigConfig = authConfig;
break;
}
}
}
if (authenticationRequestConfigConfig == null) {
return;
}
OAuthAppDAO dao = new OAuthAppDAO();
dao.updateOAuthConsumerApp(serviceProvider.getApplicationName(),
authenticationRequestConfigConfig.getInboundAuthKey());
}
private void removeEntriesFromCache(ServiceProvider serviceProvider, String tenantDomain, String userName)
throws IdentityApplicationManagementException {
TokenMgtDAO tokenMgtDAO = new TokenMgtDAO();
Set<String> accessTokens = new HashSet<>();
Set<String> authorizationCodes = new HashSet<>();
Set<String> oauthKeys = new HashSet<>();
try {
InboundAuthenticationConfig inboundAuthenticationConfig = serviceProvider.getInboundAuthenticationConfig();
if (inboundAuthenticationConfig != null) {
InboundAuthenticationRequestConfig[] inboundRequestConfigs = inboundAuthenticationConfig.
getInboundAuthenticationRequestConfigs();
if (inboundRequestConfigs != null) {
for (InboundAuthenticationRequestConfig inboundRequestConfig : inboundRequestConfigs) {
if (StringUtils.equals(OAUTH2, inboundRequestConfig.getInboundAuthType()) || StringUtils
.equals(inboundRequestConfig.getInboundAuthType(), OAUTH)) {
oauthKeys.add(inboundRequestConfig.getInboundAuthKey());
}
}
}
}
if (oauthKeys.size() > 0) {
AppInfoCache appInfoCache = AppInfoCache.getInstance();
for (String oauthKey : oauthKeys) {
accessTokens.addAll(tokenMgtDAO.getActiveTokensForConsumerKey(oauthKey));
authorizationCodes.addAll(tokenMgtDAO.getAuthorizationCodesForConsumerKey(oauthKey));
// Remove client credential from AppInfoCache
appInfoCache.clearCacheEntry(oauthKey);
}
}
if (accessTokens.size() > 0) {
for (String accessToken : accessTokens) {
// Remove access token from AuthorizationGrantCache
AuthorizationGrantCacheKey grantCacheKey = new AuthorizationGrantCacheKey(accessToken);
AuthorizationGrantCacheEntry grantCacheEntry = (AuthorizationGrantCacheEntry) AuthorizationGrantCache
.getInstance().getValueFromCacheByToken(grantCacheKey);
if (grantCacheEntry != null) {
AuthorizationGrantCache.getInstance().clearCacheEntryByToken(grantCacheKey);
}
// Remove access token from OAuthCache
OAuthCacheKey oauthCacheKey = new OAuthCacheKey(accessToken);
CacheEntry oauthCacheEntry = OAuthCache.getInstance().getValueFromCache(oauthCacheKey);
if (oauthCacheEntry != null) {
OAuthCache.getInstance().clearCacheEntry(oauthCacheKey);
}
}
}
if (authorizationCodes.size() > 0) {
for (String authorizationCode : authorizationCodes) {
// Remove authorization code from AuthorizationGrantCache
AuthorizationGrantCacheKey grantCacheKey = new AuthorizationGrantCacheKey(authorizationCode);
AuthorizationGrantCacheEntry grantCacheEntry = (AuthorizationGrantCacheEntry) AuthorizationGrantCache
.getInstance().getValueFromCacheByToken(grantCacheKey);
if (grantCacheEntry != null) {
AuthorizationGrantCache.getInstance().clearCacheEntryByCode(grantCacheKey);
}
// Remove authorization code from OAuthCache
OAuthCacheKey oauthCacheKey = new OAuthCacheKey(authorizationCode);
CacheEntry oauthCacheEntry = OAuthCache.getInstance().getValueFromCache(oauthCacheKey);
if (oauthCacheEntry != null) {
OAuthCache.getInstance().clearCacheEntry(oauthCacheKey);
}
}
}
} catch (IdentityOAuth2Exception e) {
throw new IdentityApplicationManagementException("Error occurred when removing oauth cache entries upon " +
"service provider update. ", e);
}
}
} | components/org.wso2.carbon.identity.oauth/src/main/java/org/wso2/carbon/identity/oauth2/internal/OAuthApplicationMgtListener.java | /*
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.wso2.carbon.identity.oauth2.internal;
import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.StringUtils;
import org.wso2.carbon.identity.application.common.IdentityApplicationManagementException;
import org.wso2.carbon.identity.application.common.model.InboundAuthenticationConfig;
import org.wso2.carbon.identity.application.common.model.InboundAuthenticationRequestConfig;
import org.wso2.carbon.identity.application.common.model.Property;
import org.wso2.carbon.identity.application.common.model.ServiceProvider;
import org.wso2.carbon.identity.application.mgt.listener.AbstractApplicationMgtListener;
import org.wso2.carbon.identity.oauth.IdentityOAuthAdminException;
import org.wso2.carbon.identity.oauth.cache.AuthorizationGrantCache;
import org.wso2.carbon.identity.oauth.cache.AuthorizationGrantCacheEntry;
import org.wso2.carbon.identity.oauth.cache.AuthorizationGrantCacheKey;
import org.wso2.carbon.identity.oauth.dao.OAuthAppDAO;
import org.wso2.carbon.identity.oauth.dao.OAuthConsumerDAO;
import org.wso2.carbon.identity.oauth2.IdentityOAuth2Exception;
import org.wso2.carbon.identity.oauth2.dao.TokenMgtDAO;
import java.util.HashSet;
import java.util.Set;
public class OAuthApplicationMgtListener extends AbstractApplicationMgtListener {
public static final String OAUTH2 = "oauth2";
public static final String OAUTH2_CONSUMER_SECRET = "oauthConsumerSecret";
private static final String OAUTH = "oauth";
@Override
public int getDefaultOrderId() {
return 11;
}
public boolean doPreUpdateApplication(ServiceProvider serviceProvider, String tenantDomain, String userName)
throws IdentityApplicationManagementException {
removeClientSecret(serviceProvider);
return true;
}
public boolean doPostGetServiceProvider(ServiceProvider serviceProvider, String serviceProviderName, String tenantDomain)
throws IdentityApplicationManagementException {
addClientSecret(serviceProvider);
return true;
}
public boolean doPostGetServiceProviderByClientId(ServiceProvider serviceProvider, String clientId, String clientType,
String tenantDomain) throws IdentityApplicationManagementException {
addClientSecret(serviceProvider);
return true;
}
public boolean doPostCreateApplication(ServiceProvider serviceProvider, String tenantDomain, String userName) throws IdentityApplicationManagementException {
addClientSecret(serviceProvider);
return true;
}
public boolean doPostUpdateApplication(ServiceProvider serviceProvider, String tenantDomain, String userName) throws IdentityApplicationManagementException {
addClientSecret(serviceProvider);
updateAuthApplication(serviceProvider);
removeAccessTokensAndAuthCodeFromCache(serviceProvider, tenantDomain, userName);
return true;
}
@Override
public boolean doPostGetApplicationExcludingFileBasedSPs(ServiceProvider serviceProvider, String applicationName, String tenantDomain) throws IdentityApplicationManagementException {
addClientSecret(serviceProvider);
return true;
}
private void removeClientSecret(ServiceProvider serviceProvider) {
InboundAuthenticationConfig inboundAuthenticationConfig = serviceProvider.getInboundAuthenticationConfig();
if (inboundAuthenticationConfig != null) {
InboundAuthenticationRequestConfig[] inboundRequestConfigs = inboundAuthenticationConfig.
getInboundAuthenticationRequestConfigs();
if (inboundRequestConfigs != null) {
for (InboundAuthenticationRequestConfig inboundRequestConfig : inboundRequestConfigs) {
if (inboundRequestConfig.getInboundAuthType().equals(OAUTH2)) {
Property[] props = inboundRequestConfig.getProperties();
for (Property prop : props) {
if (prop.getName().equalsIgnoreCase(OAUTH2_CONSUMER_SECRET)) {
props = (Property[]) ArrayUtils.removeElement(props, prop);
inboundRequestConfig.setProperties(props);
continue; //we are interested only on this property
} else {
//ignore
}
}
continue;// we are interested only on oauth2 config. Only one will be present.
} else {
//ignore
}
}
} else {
//ignore
}
} else {
//nothing to do
}
}
private void addClientSecret(ServiceProvider serviceProvider) throws IdentityApplicationManagementException {
if (serviceProvider == null) {
return ; // if service provider is not present no need to add this information
}
try {
InboundAuthenticationConfig inboundAuthenticationConfig = serviceProvider.getInboundAuthenticationConfig();
if (inboundAuthenticationConfig != null) {
InboundAuthenticationRequestConfig[] inboundRequestConfigs = inboundAuthenticationConfig.
getInboundAuthenticationRequestConfigs();
if (inboundRequestConfigs != null) {
for (InboundAuthenticationRequestConfig inboundRequestConfig : inboundRequestConfigs) {
if (inboundRequestConfig.getInboundAuthType().equals(OAUTH2)) {
Property[] props = inboundRequestConfig.getProperties();
Property property = new Property();
property.setName(OAUTH2_CONSUMER_SECRET);
property.setValue(getClientSecret(inboundRequestConfig.getInboundAuthKey()));
props = (Property[]) ArrayUtils.add(props, property);
inboundRequestConfig.setProperties(props);
continue;// we are interested only on oauth2 config. Only one will be present.
} else {
//ignore
}
}
} else {
//ignore
}
} else {
//nothing to do
}
} catch (IdentityOAuthAdminException e) {
throw new IdentityApplicationManagementException("Injecting client secret failed.", e);
}
return;
}
private String getClientSecret(String inboundAuthKey) throws IdentityOAuthAdminException {
OAuthConsumerDAO dao = new OAuthConsumerDAO();
return dao.getOAuthConsumerSecret(inboundAuthKey);
}
/**
* Update the application name if OAuth application presents.
* @param serviceProvider Service provider
* @throws IdentityApplicationManagementException
*/
private void updateAuthApplication(ServiceProvider serviceProvider)
throws IdentityApplicationManagementException {
InboundAuthenticationRequestConfig authenticationRequestConfigConfig = null;
if (serviceProvider.getInboundAuthenticationConfig() != null &&
serviceProvider.getInboundAuthenticationConfig()
.getInboundAuthenticationRequestConfigs() != null) {
for (InboundAuthenticationRequestConfig authConfig : serviceProvider.getInboundAuthenticationConfig()
.getInboundAuthenticationRequestConfigs()) {
if (StringUtils.equals(authConfig.getInboundAuthType(), "oauth") ||
StringUtils.equals(authConfig.getInboundAuthType(), "oauth2")) {
authenticationRequestConfigConfig = authConfig;
break;
}
}
}
if (authenticationRequestConfigConfig == null) {
return;
}
OAuthAppDAO dao = new OAuthAppDAO();
dao.updateOAuthConsumerApp(serviceProvider.getApplicationName(),
authenticationRequestConfigConfig.getInboundAuthKey());
}
private void removeAccessTokensAndAuthCodeFromCache(ServiceProvider serviceProvider, String tenantDomain, String
userName) throws IdentityApplicationManagementException {
TokenMgtDAO tokenMgtDAO = new TokenMgtDAO();
Set<String> accessTokens = new HashSet<>();
Set<String> authorizationCodes = new HashSet<>();
Set<String> oauthKeys = new HashSet<>();
try {
InboundAuthenticationConfig inboundAuthenticationConfig = serviceProvider.getInboundAuthenticationConfig();
if (inboundAuthenticationConfig != null) {
InboundAuthenticationRequestConfig[] inboundRequestConfigs = inboundAuthenticationConfig.
getInboundAuthenticationRequestConfigs();
if (inboundRequestConfigs != null) {
for (InboundAuthenticationRequestConfig inboundRequestConfig : inboundRequestConfigs) {
if (StringUtils.equals(OAUTH2, inboundRequestConfig.getInboundAuthType()) || StringUtils
.equals(inboundRequestConfig.getInboundAuthType(), OAUTH)) {
oauthKeys.add(inboundRequestConfig.getInboundAuthKey());
}
}
}
}
if (oauthKeys.size() > 0) {
for (String oauthKey : oauthKeys) {
accessTokens.addAll(tokenMgtDAO.getActiveTokensForConsumerKey(oauthKey));
authorizationCodes.addAll(tokenMgtDAO.getAuthorizationCodesForConsumerKey(oauthKey));
}
}
if (accessTokens.size() > 0) {
for (String accessToken : accessTokens) {
AuthorizationGrantCacheKey cacheKey = new AuthorizationGrantCacheKey(accessToken);
AuthorizationGrantCacheEntry cacheEntry = (AuthorizationGrantCacheEntry) AuthorizationGrantCache
.getInstance().getValueFromCacheByToken(cacheKey);
if (cacheEntry != null) {
AuthorizationGrantCache.getInstance().clearCacheEntryByToken(cacheKey);
}
}
}
if (authorizationCodes.size() > 0) {
for (String accessToken : authorizationCodes) {
AuthorizationGrantCacheKey cacheKey = new AuthorizationGrantCacheKey(accessToken);
AuthorizationGrantCacheEntry cacheEntry = (AuthorizationGrantCacheEntry) AuthorizationGrantCache
.getInstance().getValueFromCacheByToken(cacheKey);
if (cacheEntry != null) {
AuthorizationGrantCache.getInstance().clearCacheEntryByCode(cacheKey);
}
}
}
} catch (IdentityOAuth2Exception e) {
throw new IdentityApplicationManagementException("Error occurred when removing oauth cache entries upon " +
"service provider update. ", e);
}
}
} | Fixed IDENTITY-4965
| components/org.wso2.carbon.identity.oauth/src/main/java/org/wso2/carbon/identity/oauth2/internal/OAuthApplicationMgtListener.java | Fixed IDENTITY-4965 | <ide><path>omponents/org.wso2.carbon.identity.oauth/src/main/java/org/wso2/carbon/identity/oauth2/internal/OAuthApplicationMgtListener.java
<ide> import org.wso2.carbon.identity.application.common.model.InboundAuthenticationRequestConfig;
<ide> import org.wso2.carbon.identity.application.common.model.Property;
<ide> import org.wso2.carbon.identity.application.common.model.ServiceProvider;
<add>import org.wso2.carbon.identity.application.mgt.ApplicationManagementService;
<ide> import org.wso2.carbon.identity.application.mgt.listener.AbstractApplicationMgtListener;
<ide> import org.wso2.carbon.identity.oauth.IdentityOAuthAdminException;
<add>import org.wso2.carbon.identity.oauth.cache.AppInfoCache;
<ide> import org.wso2.carbon.identity.oauth.cache.AuthorizationGrantCache;
<ide> import org.wso2.carbon.identity.oauth.cache.AuthorizationGrantCacheEntry;
<ide> import org.wso2.carbon.identity.oauth.cache.AuthorizationGrantCacheKey;
<add>import org.wso2.carbon.identity.oauth.cache.CacheEntry;
<add>import org.wso2.carbon.identity.oauth.cache.OAuthCache;
<add>import org.wso2.carbon.identity.oauth.cache.OAuthCacheKey;
<add>import org.wso2.carbon.identity.oauth.config.OAuthServerConfiguration;
<ide> import org.wso2.carbon.identity.oauth.dao.OAuthAppDAO;
<ide> import org.wso2.carbon.identity.oauth.dao.OAuthConsumerDAO;
<ide> import org.wso2.carbon.identity.oauth2.IdentityOAuth2Exception;
<ide>
<ide> addClientSecret(serviceProvider);
<ide> updateAuthApplication(serviceProvider);
<del> removeAccessTokensAndAuthCodeFromCache(serviceProvider, tenantDomain, userName);
<add> if (OAuthServerConfiguration.getInstance().isCacheEnabled()) {
<add> removeEntriesFromCache(serviceProvider, tenantDomain, userName);
<add> }
<ide> return true;
<ide> }
<ide>
<ide> return true;
<ide> }
<ide>
<add> @Override
<add> public boolean doPreDeleteApplication(String applicationName, String tenantDomain, String userName) throws IdentityApplicationManagementException {
<add> ApplicationManagementService applicationMgtService = OAuth2ServiceComponentHolder.getApplicationMgtService();
<add> ServiceProvider serviceProvider = applicationMgtService.getApplicationExcludingFileBasedSPs(applicationName, tenantDomain);
<add> if (OAuthServerConfiguration.getInstance().isCacheEnabled()) {
<add> removeEntriesFromCache(serviceProvider, tenantDomain, userName);
<add> }
<add> return true;
<add> }
<ide>
<ide> private void removeClientSecret(ServiceProvider serviceProvider) {
<ide> InboundAuthenticationConfig inboundAuthenticationConfig = serviceProvider.getInboundAuthenticationConfig();
<ide> private void addClientSecret(ServiceProvider serviceProvider) throws IdentityApplicationManagementException {
<ide>
<ide> if (serviceProvider == null) {
<del> return ; // if service provider is not present no need to add this information
<add> return; // if service provider is not present no need to add this information
<ide> }
<ide>
<ide> try {
<ide>
<ide> /**
<ide> * Update the application name if OAuth application presents.
<add> *
<ide> * @param serviceProvider Service provider
<ide> * @throws IdentityApplicationManagementException
<ide> */
<ide> authenticationRequestConfigConfig.getInboundAuthKey());
<ide> }
<ide>
<del> private void removeAccessTokensAndAuthCodeFromCache(ServiceProvider serviceProvider, String tenantDomain, String
<del> userName) throws IdentityApplicationManagementException {
<add> private void removeEntriesFromCache(ServiceProvider serviceProvider, String tenantDomain, String userName)
<add> throws IdentityApplicationManagementException {
<ide> TokenMgtDAO tokenMgtDAO = new TokenMgtDAO();
<ide> Set<String> accessTokens = new HashSet<>();
<ide> Set<String> authorizationCodes = new HashSet<>();
<ide> }
<ide> }
<ide> if (oauthKeys.size() > 0) {
<add> AppInfoCache appInfoCache = AppInfoCache.getInstance();
<ide> for (String oauthKey : oauthKeys) {
<ide> accessTokens.addAll(tokenMgtDAO.getActiveTokensForConsumerKey(oauthKey));
<ide> authorizationCodes.addAll(tokenMgtDAO.getAuthorizationCodesForConsumerKey(oauthKey));
<add> // Remove client credential from AppInfoCache
<add> appInfoCache.clearCacheEntry(oauthKey);
<ide> }
<ide> }
<ide> if (accessTokens.size() > 0) {
<ide> for (String accessToken : accessTokens) {
<del> AuthorizationGrantCacheKey cacheKey = new AuthorizationGrantCacheKey(accessToken);
<del> AuthorizationGrantCacheEntry cacheEntry = (AuthorizationGrantCacheEntry) AuthorizationGrantCache
<del> .getInstance().getValueFromCacheByToken(cacheKey);
<del> if (cacheEntry != null) {
<del> AuthorizationGrantCache.getInstance().clearCacheEntryByToken(cacheKey);
<del> }
<del> }
<del> }
<add> // Remove access token from AuthorizationGrantCache
<add> AuthorizationGrantCacheKey grantCacheKey = new AuthorizationGrantCacheKey(accessToken);
<add> AuthorizationGrantCacheEntry grantCacheEntry = (AuthorizationGrantCacheEntry) AuthorizationGrantCache
<add> .getInstance().getValueFromCacheByToken(grantCacheKey);
<add> if (grantCacheEntry != null) {
<add> AuthorizationGrantCache.getInstance().clearCacheEntryByToken(grantCacheKey);
<add> }
<add>
<add> // Remove access token from OAuthCache
<add> OAuthCacheKey oauthCacheKey = new OAuthCacheKey(accessToken);
<add> CacheEntry oauthCacheEntry = OAuthCache.getInstance().getValueFromCache(oauthCacheKey);
<add> if (oauthCacheEntry != null) {
<add> OAuthCache.getInstance().clearCacheEntry(oauthCacheKey);
<add> }
<add> }
<add> }
<add>
<ide> if (authorizationCodes.size() > 0) {
<del> for (String accessToken : authorizationCodes) {
<del> AuthorizationGrantCacheKey cacheKey = new AuthorizationGrantCacheKey(accessToken);
<del> AuthorizationGrantCacheEntry cacheEntry = (AuthorizationGrantCacheEntry) AuthorizationGrantCache
<del> .getInstance().getValueFromCacheByToken(cacheKey);
<del> if (cacheEntry != null) {
<del> AuthorizationGrantCache.getInstance().clearCacheEntryByCode(cacheKey);
<add> for (String authorizationCode : authorizationCodes) {
<add> // Remove authorization code from AuthorizationGrantCache
<add> AuthorizationGrantCacheKey grantCacheKey = new AuthorizationGrantCacheKey(authorizationCode);
<add> AuthorizationGrantCacheEntry grantCacheEntry = (AuthorizationGrantCacheEntry) AuthorizationGrantCache
<add> .getInstance().getValueFromCacheByToken(grantCacheKey);
<add> if (grantCacheEntry != null) {
<add> AuthorizationGrantCache.getInstance().clearCacheEntryByCode(grantCacheKey);
<add> }
<add>
<add> // Remove authorization code from OAuthCache
<add> OAuthCacheKey oauthCacheKey = new OAuthCacheKey(authorizationCode);
<add> CacheEntry oauthCacheEntry = OAuthCache.getInstance().getValueFromCache(oauthCacheKey);
<add> if (oauthCacheEntry != null) {
<add> OAuthCache.getInstance().clearCacheEntry(oauthCacheKey);
<ide> }
<ide> }
<ide> } |
|
Java | apache-2.0 | de2522771ea0c1c360cd4bba30840495938dba34 | 0 | Wisser/Jailer,Wisser/Jailer,Wisser/Jailer | /*
* Copyright 2007 - 2019 Ralf Wisser.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.sf.jailer.ui;
import java.awt.Component;
import java.awt.Container;
import java.awt.Cursor;
import java.awt.Dialog;
import java.awt.Dimension;
import java.awt.FileDialog;
import java.awt.Font;
import java.awt.Frame;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.Window;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.StringSelection;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.WeakHashMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JCheckBoxMenuItem;
import javax.swing.JComponent;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JOptionPane;
import javax.swing.JPopupMenu;
import javax.swing.JTable;
import javax.swing.RowSorter;
import javax.swing.SwingUtilities;
import javax.swing.WindowConstants;
import javax.swing.table.TableColumnModel;
import javax.swing.table.TableModel;
import org.apache.log4j.Logger;
import net.sf.jailer.ExecutionContext;
import net.sf.jailer.Jailer;
import net.sf.jailer.JailerVersion;
import net.sf.jailer.database.BasicDataSource;
import net.sf.jailer.database.PrimaryKeyValidator;
import net.sf.jailer.database.Session;
import net.sf.jailer.database.SqlException;
import net.sf.jailer.datamodel.DataModel;
import net.sf.jailer.datamodel.Table;
import net.sf.jailer.extractionmodel.ExtractionModel.IncompatibleModelException;
import net.sf.jailer.progress.ProgressListener;
import net.sf.jailer.ui.databrowser.BrowserContentPane.TableModelItem;
import net.sf.jailer.ui.databrowser.Row;
import net.sf.jailer.ui.scrollmenu.JScrollC2PopupMenu;
import net.sf.jailer.ui.scrollmenu.JScrollPopupMenu;
import net.sf.jailer.ui.syntaxtextarea.RSyntaxTextAreaWithSQLSyntaxStyle;
import net.sf.jailer.ui.util.ConcurrentTaskControl;
import net.sf.jailer.ui.util.HttpUtil;
import net.sf.jailer.ui.util.UISettings;
import net.sf.jailer.util.CancellationException;
import net.sf.jailer.util.CancellationHandler;
import net.sf.jailer.util.CycleFinder;
import net.sf.jailer.util.JobManager;
/**
* Some utility methods.
*
* @author Ralf Wisser
*/
public class UIUtil {
/**
* The logger.
*/
private static final Logger _log = Logger.getLogger(UIUtil.class);
/**
* Opens file chooser.
*
* @param selectedFile
* if not <code>null</code> this file will be selected initially
* @param startDir
* directory to start with
* @param description
* description of file to chose
*/
public static String choseFile(File selectedFile, String startDir, final String description, final String extension,
Component parent, boolean addExtension, boolean forLoad) {
return choseFile(selectedFile, startDir, description, extension, parent, addExtension, forLoad, true);
}
/**
* Opens file chooser.
*
* @param selectedFile
* if not <code>null</code> this file will be selected initially
* @param startDir
* directory to start with
* @param description
* description of file to chose
*/
public static String choseFile(File selectedFile, String startDir, final String description, final String extension,
Component parent, boolean addExtension, boolean forLoad, final boolean allowZip) {
String newStartDir = restoreCurrentDir(extension);
if (newStartDir != null) {
startDir = newStartDir;
try {
if (!new File(startDir).isDirectory()) {
startDir = new File(startDir).getParent();
}
} catch (Exception e) {
// ignore
}
} else {
if (!new File(startDir).isAbsolute()) {
startDir = Environment.newFile(startDir).getPath();
}
}
Window ancestor = SwingUtilities.getWindowAncestor(parent);
if (ancestor != null) {
parent = ancestor;
}
FileDialog fileChooser;
if (parent instanceof Dialog) {
fileChooser = new FileDialog((Dialog) parent);
} else if (parent instanceof Frame) {
fileChooser = new FileDialog((Frame) parent);
} else {
fileChooser = new FileDialog(new Frame());
}
fileChooser.setDirectory(startDir);
fileChooser.setTitle(description);
if (selectedFile != null) {
fileChooser.setFile(selectedFile.getName());
} else if (extension != null && extension.length() > 0) {
if (System.getProperty("os.name", "").toLowerCase().startsWith("windows")) {
// workaround: http://bugs.java.com/view_bug.do?bug_id=8021943
boolean set = true;
Matcher m = Pattern.compile("1.7.0_(\\d+).*").matcher(System.getProperty("java.version", ""));
if (m.matches()) {
try {
set = Integer.parseInt(m.group(1)) > 40;
} catch (NumberFormatException e) {
// ignore;
}
}
if (set) {
fileChooser.setFile("*" + extension + (allowZip ? ";*" + ".zip;*" + ".gz" : ""));
}
}
}
FilenameFilter filter = new FilenameFilter() {
@Override
public boolean accept(File dir, String name) {
return name.toLowerCase().endsWith(extension)
|| allowZip && name.toLowerCase().endsWith(extension + ".gz")
|| allowZip && name.toLowerCase().endsWith(extension + ".zip");
}
};
fileChooser.setFilenameFilter(filter);
fileChooser.setMode(forLoad ? FileDialog.LOAD : FileDialog.SAVE);
fileChooser.setVisible(true);
String fn = fileChooser.getFile();
if (fn != null) {
File selFile = new File(fileChooser.getDirectory(), fn);
try {
File f = selFile;
String work = new File(".").getCanonicalPath();
if (f.getCanonicalPath().startsWith(work)) {
fn = f.getName();
f = f.getParentFile();
while (f != null && !f.getCanonicalPath().equals(work)) {
fn = f.getName() + File.separator + fn;
f = f.getParentFile();
}
} else {
fn = f.getCanonicalPath();
}
if (addExtension && !(fn.endsWith(extension)
|| (allowZip && (fn.endsWith(extension + ".zip") || fn.endsWith(extension + ".gz"))))) {
fn += extension;
}
try {
storeCurrentDir(extension, selFile.getParent());
} catch (Exception e) {
// ignore
}
return fn;
} catch (IOException e1) {
try {
fn = selFile.getCanonicalPath();
if (addExtension && !(fn.endsWith(extension)
|| (allowZip && (fn.endsWith(extension + ".zip") || fn.endsWith(extension + ".gz"))))) {
fn += extension;
}
return fn;
} catch (IOException e) {
throw new RuntimeException(e.getMessage(), e);
}
}
}
return null;
}
/**
* File to store current directory of file chooser.
*/
private final static String cdSettingsName = ".cdsettings";
/**
* Stores current directory of file chooser.
*
* @param key
* the key under which to store current directory
* @param currentDir
* the current directory
*/
@SuppressWarnings("unchecked")
private static void storeCurrentDir(String key, String currentDir) {
try {
File cdSettings = Environment.newFile(cdSettingsName);
Map<String, String> cd = new HashMap<String, String>();
if (cdSettings.exists()) {
try {
ObjectInputStream in = new ObjectInputStream(new FileInputStream(cdSettings));
cd = (Map<String, String>) in.readObject();
in.close();
} catch (Exception e) {
// ignore
}
}
cdSettings.delete();
cd.put(key, currentDir);
ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(cdSettings));
out.writeObject(cd);
out.close();
} catch (Exception e) {
// ignore
}
}
/**
* Restores current directory of file chooser.
*
* @param key
* the key of the current directory to restore
* @return the current directory, or <code>null</code> if no directory has
* been stored under the key
*/
@SuppressWarnings("unchecked")
private static String restoreCurrentDir(String key) {
File cdSettings = Environment.newFile(cdSettingsName);
if (cdSettings.exists()) {
try {
ObjectInputStream in = new ObjectInputStream(new FileInputStream(cdSettings));
Map<String, String> map = ((Map<String, String>) in.readObject());
String cd = map.get(key);
if (cd == null && ".jm".equals(key)) {
cd = map.get(".csv");
}
in.close();
return cd;
} catch (Exception e) {
// ignore
}
}
return null;
}
/**
* Calls the Jailer export engine via CLI.
*
* @param ownerOfConsole
* owner component of jailer console
* @param cliArgs
* CLI arguments
* @param showLogfileButton
* console property
* @param printCommandLine
* if true, print CLI command line
* @param showExplainLogButton
* console property
* @param closeOutputWindow
* if <code>true</code>, close console immediately after call
* @param continueOnErrorQuestion
* to ask when call fails
* @param password
* CLI argument to print as "*****"
* @return <code>true</code> iff call succeeded
*/
public static boolean runJailer(Window ownerOfConsole, List<String> cliArgs, boolean showLogfileButton,
final boolean printCommandLine, boolean showExplainLogButton, final boolean closeOutputWindow,
String continueOnErrorQuestion, String user, String password, final ProgressListener progressListener,
final ProgressPanel progressPanel, final boolean showExeptions, boolean fullSize,
boolean returnFalseOnError, ExecutionContext executionContext) {
return runJailer(ownerOfConsole, cliArgs, showLogfileButton, printCommandLine, showExplainLogButton,
closeOutputWindow, continueOnErrorQuestion, user, password, progressListener, progressPanel, showExeptions,
fullSize, false, returnFalseOnError, false, executionContext);
}
/**
* Calls the Jailer export engine via CLI.
*
* @param ownerOfConsole
* owner component of jailer console
* @param cliArgs
* CLI arguments
* @param showLogfileButton
* console property
* @param printCommandLine
* if true, print CLI command line
* @param showExplainLogButton
* console property
* @param closeOutputWindow
* if <code>true</code>, close console immediately after call
* @param continueOnErrorQuestion
* to ask when call fails
* @param password
* CLI argument to print as "*****"
* @return <code>true</code> iff call succeeded
*/
public static boolean runJailer(Window ownerOfConsole, List<String> cliArgs, boolean showLogfileButton,
final boolean printCommandLine, boolean showExplainLogButton, final boolean closeOutputWindow,
String continueOnErrorQuestion, String user, String password, final ProgressListener progressListener,
final ProgressPanel progressPanel, final boolean showExeptions, boolean fullSize,
final boolean closeOutputWindowOnError, boolean returnFalseOnError, boolean throwException, ExecutionContext executionContext) {
JDialog dialog = new JDialog(ownerOfConsole);
List<String> args = new ArrayList<String>(cliArgs);
final StringBuffer arglist = createCLIArgumentString(user, password, args, executionContext);
final List<String> argslist = new ArrayList<String>();
boolean esc = true;
for (String arg : args) {
if (esc && arg.startsWith("-")) {
if (arg.equals(user) || arg.equals(password)) {
argslist.add("-");
} else {
esc = false;
}
}
argslist.add(arg);
}
final String[] argsarray = new String[argslist.size()];
int i = 0;
for (String arg : argslist) {
argsarray[i++] = arg;
}
final JailerConsole outputView = new JailerConsole(ownerOfConsole, dialog, showLogfileButton,
showExplainLogButton, progressPanel, fullSize);
final PrintStream originalOut = System.out;
final boolean[] ready = new boolean[] { true };
System.setOut(new PrintStream(new OutputStream() {
private int lineNr = 0;
StringBuffer buffer = new StringBuffer();
@Override
public synchronized void write(byte[] arg0, int arg1, int arg2) throws IOException {
super.write(arg0, arg1, arg2);
}
@Override
public void write(int b) throws IOException {
if (b != '@') {
originalOut.write(b);
}
boolean wasReady;
synchronized (buffer) {
wasReady = ready[0];
if (b != '@') {
buffer.append((char) b);
}
}
if ((char) b == '\n') {
++lineNr;
}
if ((char) b == '\n' && lineNr % 60 == 0 || (char) b == '@') {
if (wasReady) {
synchronized (buffer) {
ready[0] = false;
}
UIUtil.invokeLater(new Runnable() {
@Override
public void run() {
synchronized (buffer) {
if (buffer.length() > 0) {
outputView.appendText(buffer.toString());
buffer.setLength(0);
}
}
ready[0] = true;
}
});
}
}
}
}));
final boolean[] exceptionShown = new boolean[1];
try {
try {
File exportLog = Environment.newFile("export.log");
File sqlLog = Environment.newFile("sql.log");
if (exportLog.exists()) {
FileOutputStream out = new FileOutputStream(exportLog);
out.close();
}
if (sqlLog.exists()) {
FileOutputStream out = new FileOutputStream(sqlLog);
out.close();
}
} catch (Exception e) {
// UIUtil.showException(null, "Error", e, arglist);
}
final boolean[] result = new boolean[] { false };
final Throwable[] exp = new Throwable[1];
final StringBuffer warnings = new StringBuffer();
final boolean[] fin = new boolean[] { false };
outputView.dialog.addWindowListener(new WindowAdapter() {
boolean cancelled = false;
@Override
public void windowClosing(WindowEvent e) {
boolean f;
synchronized (UIUtil.class) {
f = exp[0] == null;
}
try {
CancellationHandler.checkForCancellation(null);
} catch (CancellationException ce) {
cancelled = true;
}
if (cancelled && f) {
cancel();
JOptionPane.showMessageDialog(outputView.dialog, "Cancellation in progress...", "Cancellation",
JOptionPane.INFORMATION_MESSAGE);
} else if (exp[0] == null && !fin[0] && !cancelled) {
if (JOptionPane.showConfirmDialog(outputView.dialog, "Cancel operation?", "Cancellation",
JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE) == JOptionPane.YES_OPTION) {
if (!outputView.hasFinished) {
cancel();
outputView.dialog.setTitle("Jailer Console - cancelling...");
if (progressListener != null) {
progressListener.newStage("cancelling...", true, true);
}
outputView.getCancelButton().setEnabled(false);
cancelled = true;
}
}
}
}
private void cancel() {
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
CancellationHandler.cancel(null);
}
});
thread.setDaemon(true);
thread.start();
}
});
new Thread(new Runnable() {
@Override
public void run() {
for (int i = 0;; ++i) {
try {
Thread.sleep(i == 0 ? 500 : 1000);
} catch (InterruptedException e) {
}
synchronized (fin) {
if (fin[0]) {
break;
}
System.out.print("@");
}
}
}
}).start();
new Thread(new Runnable() {
@Override
public void run() {
try {
if (printCommandLine) {
_log.info("arguments: " + arglist.toString().trim());
}
result[0] = Jailer.jailerMain(argsarray, disableWarnings ? new StringBuffer() : warnings,
progressListener);
} catch (Throwable t) {
synchronized (UIUtil.class) {
exp[0] = t;
}
} finally {
// flush
System.out.println("@");
synchronized (UIUtil.class) {
fin[0] = true;
}
}
UIUtil.invokeLater(new Runnable() {
@Override
public void run() {
synchronized (UIUtil.class) {
outputView.dialog.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
if (progressListener != null) {
progressListener.newStage(outputView.hasCancelled ? "cancelled"
: exp[0] == null ? "finished" : "failed", exp[0] != null, true);
}
if ((exp[0] instanceof CancellationException) || closeOutputWindowOnError
|| (closeOutputWindow && result[0] && exp[0] == null
&& warnings.length() == 0)) {
if (!outputView.hasCancelled) {
outputView.dialog.setVisible(false);
}
} else {
outputView.finish(result[0] && exp[0] == null);
if (result[0] && warnings.length() > 0) {
JOptionPane.showMessageDialog(outputView.dialog,
warnings.length() > 800 ? warnings.substring(0, 800) + "..."
: warnings.toString(),
"Warning", JOptionPane.INFORMATION_MESSAGE);
outputView.dialog.setVisible(false);
} else if (showExeptions && exp[0] != null
&& !(exp[0] instanceof CancellationException)) {
UIUtil.showException(outputView.dialog, "Error", exp[0], arglist);
exceptionShown[0] = true;
}
if (result[0] && progressPanel != null) {
progressPanel.confirm();
}
}
}
}
});
}
}, "jailer-main").start();
outputView.dialog.setVisible(true);
synchronized (UIUtil.class) {
if (exp[0] != null) {
if (returnFalseOnError) {
result[0] = false;
} else {
throw exp[0];
}
}
}
if (!result[0] && continueOnErrorQuestion != null) {
result[0] = JOptionPane.showConfirmDialog(outputView.dialog, continueOnErrorQuestion, "Error",
JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION;
}
return result[0];
} catch (Throwable t) {
if (t instanceof CancellationException) {
CancellationHandler.reset(null);
} else {
boolean shown = false;
synchronized (UIUtil.class) {
shown = exceptionShown[0];
}
if (throwException) {
throw new RuntimeException(t);
}
if (!shown) {
UIUtil.showException(null, "Error", t, arglist);
}
}
return false;
} finally {
System.setOut(originalOut);
}
}
public static StringBuffer createCLIArgumentString(String user, String password, List<String> args, ExecutionContext executionContext) {
args.add("-datamodel");
args.add(executionContext.getQualifiedDatamodelFolder());
return createPlainCLIArguments(user, password, args);
}
public static StringBuffer createPlainCLIArguments(String user, String password, List<String> args) {
final StringBuffer arglist = new StringBuffer();
int pwi = -1;
for (int i = args.size() - 1; i >= 0; --i) {
if (args.get(i) != null && args.get(i).equals(password) && password.length() > 0) {
pwi = i;
break;
}
}
for (int i = 0; i < args.size(); ++i) {
String arg = args.get(i);
if (i == pwi) {
arglist.append(" - \"<password>\"");
} else {
if (arg.startsWith("-") && arg.equals(user)) {
arglist.append(" -");
}
if ("".equals(arg) || arg.contains(" ") || arg.contains("<") || arg.contains(">") || arg.contains("*")
|| arg.contains("?") || arg.contains("|") || arg.contains("$") || arg.contains("\"")
|| arg.contains("'") || arg.contains("\\") || arg.contains(";") || arg.contains("&")) {
arglist.append(" \"");
for (int j = 0; j < arg.length(); ++j) {
char c = arg.charAt(j);
if (c == '\"' || c == '$') {
arglist.append("\\");
}
arglist.append(c);
}
arglist.append("\"");
} else {
arglist.append(" " + arg);
}
}
}
return arglist;
}
public static Object EXCEPTION_CONTEXT_USER_ERROR = new Object();
public static Object EXCEPTION_CONTEXT_USER_WARNING = new Object();
/**
* Shows an exception.
*
* @param parent
* parent component of option pane
* @param title
* title of option pane
* @param t
* the exception
*/
public static void showException(Component parent, String title, Throwable t) {
showException(parent, title, t, null);
}
/**
* Shows an exception.
*
* @param parent
* parent component of option pane
* @param title
* title of option pane
* @param context
* optional context object. String or Session is supported.
* @param t
* the exception
*/
public static void showException(Component parent, String title, Throwable t, Object context) {
showException(parent, title, t, context, null);
}
/**
* Shows an exception.
*
* @param parent
* parent component of option pane
* @param title
* title of option pane
* @param context
* optional context object. String or Session is supported.
* @param t
* the exception
*/
public static void showException(Component parent, String title, Throwable t, Object context, JComponent additionalControl) {
if (context == EXCEPTION_CONTEXT_USER_ERROR) {
if (t instanceof IndexOutOfBoundsException
|| t instanceof NullPointerException
|| t instanceof ClassCastException
|| t instanceof IllegalStateException
|| t instanceof IllegalArgumentException) {
context = null;
}
}
if (t instanceof DataModel.NoPrimaryKeyException || t instanceof CycleFinder.CycleFoundException || t instanceof IncompatibleModelException) {
context = EXCEPTION_CONTEXT_USER_ERROR;
}
t.printStackTrace();
if (!(t instanceof ClassNotFoundException)) {
while (t.getCause() != null && t != t.getCause() && !(t instanceof SqlException)) {
t = t.getCause();
}
}
if (t instanceof DataModel.NoPrimaryKeyException || t instanceof CycleFinder.CycleFoundException || t instanceof IncompatibleModelException) {
context = EXCEPTION_CONTEXT_USER_ERROR;
}
if (t instanceof SqlException) {
String message = ((SqlException) t).message;
String sql = ((SqlException) t).sqlStatement;
if (message != null) {
if (sql != null) {
String iMsg = message.toString() + "\n" + JailerVersion.VERSION + "\n" + sql;
sendIssue("internalSQL", iMsg);
}
}
new SqlErrorDialog(parent == null ? null : parent instanceof Window? (Window) parent : SwingUtilities.getWindowAncestor(parent),
((SqlException) t).isFormatted()? message : lineWrap(message, 120).toString(), sql, ((SqlException) t).isFormatted(), true, null, false, additionalControl);
return;
}
if (t instanceof CancellationException) {
return;
}
String message = t.getMessage();
if (message == null || "".equals(message.trim())) {
message = t.getClass().getName();
}
StringBuilder msg = lineWrap(message, 80);
String contextDesc = "";
if (context != null) {
if (context instanceof Session) {
Session session = (Session) context;
contextDesc = session.dbUrl + " (" + session.dbms + ")";
} else if (context != EXCEPTION_CONTEXT_USER_ERROR) {
contextDesc = lineWrap(context.toString(), 80).toString();
}
}
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
t.printStackTrace(pw);
if (context != EXCEPTION_CONTEXT_USER_ERROR) {
contextDesc += "\nHelp Desk: https://sourceforge.net/p/jailer/discussion/";
contextDesc += "\nMail: [email protected]\n";
contextDesc += "\n" + JailerVersion.APPLICATION_NAME + " " + JailerVersion.VERSION + "\n\n" + sw.toString();
String iMsg = msg.toString() + "\n" + JailerVersion.APPLICATION_NAME + " " + JailerVersion.VERSION + "\n\n" + sw.toString();
iMsg = iMsg
.replaceAll("\\bat [^\\n]*/", "at ")
.replaceAll("\\bat java.", "atj..")
.replaceAll("\\bat javax.swing.", "atjs..")
.replaceAll("\\bat net.sf.jailer.", "atn..")
.replaceAll("\\s*(\\n)\\s*", "$1");
sendIssue("internal", iMsg);
}
new SqlErrorDialog(parent == null ? null : parent instanceof Window? (Window) parent : SwingUtilities.getWindowAncestor(parent), msg.toString(),
contextDesc, false, false, context == EXCEPTION_CONTEXT_USER_ERROR || context == EXCEPTION_CONTEXT_USER_WARNING? title : null, context == EXCEPTION_CONTEXT_USER_WARNING, additionalControl);
}
private static StringBuilder lineWrap(String message, int maxwidth) {
StringBuilder msg = new StringBuilder();
Pattern wrapRE = Pattern.compile("(\\S\\S{" + maxwidth + ",}|.{1," + maxwidth + "})(\\s+|$)");
Matcher m = wrapRE.matcher(message == null ? "" : message);
while (m.find()) {
String line = m.group();
while (line.length() > maxwidth + 10) {
msg.append(line.substring(0, maxwidth) + "\n");
line = line.substring(maxwidth);
}
msg.append(line + (line.contains("\n") ? "" : "\n"));
}
return msg;
}
/**
* Initializes peer of newly created window.
*
* Should not be neccassary, but there is a strange bug in AWT of jre 6 on
* multi-core/processor systems. Sleeping a little after creating peer and
* before making peer visible seems to help.
*/
public static void initPeer() {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
}
}
public static void fit(Window d) {
try {
// Get the size of the screen
Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
int hd = d.getY() + d.getHeight() - (dim.height - 60);
if (hd > 0) {
d.setSize(d.getWidth(), Math.max(d.getHeight() - hd, 150));
}
d.setLocation(Math.max(0, d.getX()), Math.max(0, d.getY()));
} catch (Throwable t) {
// ignore
}
}
public static boolean disableWarnings = false;
/**
* Tries to get as much memory as possible and shows it's size.
*/
public static void showMaxMemory() {
long memSize = 0;
try {
final int MB = 1024 * 1024;
List<byte[]> mem = new ArrayList<byte[]>();
while (true) {
mem.add(new byte[MB]);
memSize += MB;
}
} catch (OutOfMemoryError e) {
JOptionPane.showConfirmDialog(null, "MaxMem=" + memSize, "", JOptionPane.INFORMATION_MESSAGE);
}
}
public static void replace(JComponent component, JComponent replacement) {
Container parent = component.getParent();
GridBagConstraints c = ((GridBagLayout) parent.getLayout()).getConstraints(component);
parent.remove(component);
if (replacement != null) {
parent.add(replacement, c);
}
}
public static void wireComponentWithButton(JComponent component, final JButton button) {
component.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
if (e.getButton() == MouseEvent.BUTTON1 && e.getClickCount() > 1) {
if (button.isEnabled()) {
button.doClick();
}
}
}
});
component.addKeyListener(new KeyListener() {
@Override
public void keyTyped(KeyEvent e) {
if (e.getKeyChar() == '\n') {
if (button.isEnabled()) {
button.doClick();
}
}
}
@Override
public void keyReleased(KeyEvent arg0) {
}
@Override
public void keyPressed(KeyEvent arg0) {
}
});
}
public static void fit(JPopupMenu popup) {
if (!(popup instanceof JScrollPopupMenu || popup instanceof JScrollC2PopupMenu)) {
final int MAX_ITEMS = 40;
Component[] comps = popup.getComponents();
popup.removeAll();
JMenu current = null;
int ci = 1;
for (int i = 0; i < comps.length; ++i) {
if (ci > MAX_ITEMS && i < comps.length - 5) {
ci = 1;
JMenu newMenu = new JMenu("more...");
if (current == null) {
popup.add(newMenu);
} else {
current.add(newMenu);
}
current = newMenu;
}
if (current == null) {
popup.add(comps[i]);
} else {
current.add(comps[i]);
}
++ci;
}
}
}
public static void checkTermination() {
for (Window w : Window.getWindows()) {
if (w.isShowing()) {
return;
}
}
System.exit(0);
}
public static void sendIssue(final String type, final String issue) {
new Thread(new Runnable() {
@Override
public void run() {
try {
final int MAX_CL = 1300;
int maxEIssueLength = 4 * MAX_CL;
String url;
do {
String eIssue = URLEncoder.encode(issue, "UTF-8");
if (eIssue.length() > maxEIssueLength) {
eIssue = eIssue.substring(0, maxEIssueLength);
}
url = "http://jailer.sf.net/issueReport.php?type=" + URLEncoder.encode(type, "UTF-8") + "&" + "issue=" + eIssue
+ "&uuid=" + URLEncoder.encode(String.valueOf(UISettings.restore("uuid")), "UTF-8")
+ "&ts=" + URLEncoder.encode(new Date().toString(), "UTF-8")
+ "&jversion=" + URLEncoder.encode(System.getProperty("java.version") + "/" + System.getProperty("java.vm.vendor") + "/" + System.getProperty("java.vm.name") + "/" + System.getProperty("os.name"), "UTF-8") + "/(" + Environment.state + ")";
maxEIssueLength -= 10;
} while (url.length() > MAX_CL && maxEIssueLength > 100);
HttpUtil.get(url);
} catch (UnsupportedEncodingException e) {
// ignore
}
}
}).start();
}
public static String toHTML(String plainText, int maxLineLength) {
plainText = plainText.trim();
if (maxLineLength > 0) {
StringBuilder sb = new StringBuilder();
int MAXLINES = 50;
int lineNr = 0;
for (String line: plainText.split("\n")) {
if (line.length() > maxLineLength) {
sb.append(line.substring(0, maxLineLength) + "...");
} else {
sb.append(line);
}
if (++lineNr > MAXLINES) {
sb.append("...");
break;
}
sb.append("\n");
}
plainText = sb.toString();
}
return "<html>" +
plainText
.replace("&", "&")
.replace("<", "<")
.replace(">", ">")
.replace("\n", "<br>")
.replace(" ", " ")
.replace("\t"," ");
}
public static ImageIcon scaleIcon(JComponent component, ImageIcon icon) {
if (icon != null) {
int heigth = component.getFontMetrics(new JLabel("M").getFont()).getHeight();
double s = heigth / (double) icon.getIconHeight();
try {
return new ImageIcon(icon.getImage().getScaledInstance((int)(icon.getIconWidth() * s), (int)(icon.getIconHeight() * s), Image.SCALE_SMOOTH));
} catch (Exception e) {
return null;
}
}
return null;
}
/**
* Represents "null"-value in rows tables.
*/
public static final String NULL = "null";
public static String LINE_SEPARATOR = System.getProperty("line.separator", "\n");
/**
* Copies selected cells of a rows table into the clipboard.
*
* @param table the table
*/
public static void copyToClipboard(JTable table, boolean lineOnSingeCell) {
String nl = System.getProperty("line.separator", "\n");
StringBuilder sb = new StringBuilder();
boolean prepNL = table.getSelectedRows().length > 1;
int[] selectedColumns = table.getSelectedColumns();
if (table.getSelectedColumnCount() == 1 && table.getSelectedRowCount() == 1 && lineOnSingeCell) {
prepNL = true;
selectedColumns = new int[table.getColumnCount()];
for (int i = 0; i < selectedColumns.length; ++i) {
selectedColumns[i] = i;
}
}
RowSorter<? extends TableModel> rowSorter = table.getRowSorter();
TableColumnModel columnModel = table.getColumnModel();
boolean firstLine = true;
for (int row: table.getSelectedRows()) {
if (!firstLine) {
sb.append(nl);
}
boolean f = true;
for (int col: selectedColumns) {
Object value = table.getModel().getValueAt(
rowSorter == null? row : rowSorter.convertRowIndexToModel(row),
columnModel.getColumn(col).getModelIndex());
if (value instanceof Row) {
Object[] values = ((Row) value).values;
for (Object v: values) {
if (v instanceof TableModelItem) {
v = ((TableModelItem) v).value;
}
if (!f) {
sb.append("\t");
}
f = false;
sb.append(v == NULL || v == null? "" : v);
}
} else {
if (value instanceof TableModelItem) {
value = ((TableModelItem) value).value;
}
if (!f) {
sb.append("\t");
}
f = false;
sb.append(value == NULL || value == null? "" : value);
}
}
firstLine = false;
}
if (prepNL) {
sb.append(nl);
}
StringSelection selection = new StringSelection(sb.toString());
Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
clipboard.setContents(selection, selection);
}
/**
* Pair of Icon and Text.
*/
public static class IconWithText implements Comparable<IconWithText> {
public final String text;
public final ImageIcon icon;
public IconWithText(String text, ImageIcon icon) {
this.text = text;
this.icon = icon;
}
@Override
public String toString() {
return text;
}
@Override
public int compareTo(IconWithText o) {
return text.compareTo(o.text);
}
}
private static boolean isPopupActive = false;
public static synchronized boolean isPopupActive() {
return isPopupActive;
}
private static synchronized void setPopupActive(boolean b) {
isPopupActive = b;
}
public static void showPopup(final Component invoker, final int x, final int y, final JPopupMenu popup) {
popup.addPropertyChangeListener("visible", new PropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent evt) {
if (Boolean.FALSE.equals(evt.getNewValue())) {
setPopupActive(false);
}
}
});
UIUtil.invokeLater(new Runnable() {
@Override
public void run() {
setPopupActive(true);
popup.show(invoker, x, y);
}
});
}
public static void invokeLater(final Runnable runnable) {
SwingUtilities.invokeLater(runnable);
}
public static void invokeLater(final int ticks, final Runnable runnable) {
SwingUtilities.invokeLater(new Runnable() {
int count = ticks;
@Override
public void run() {
--count;
if (count <= 0) {
runnable.run();
} else {
SwingUtilities.invokeLater(this);
}
}
});
}
private static Map<Component, Integer> waitLevel = new WeakHashMap<Component, Integer>();
public static void setWaitCursor(Component component) {
if (component != null) {
Integer level = waitLevel.get(component);
if (level != null) {
waitLevel.put(component, level + 1);
} else {
waitLevel.put(component, 1);
component.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
}
}
}
public static void resetWaitCursor(Component component) {
if (component != null) {
Integer level = waitLevel.get(component);
if (level != null) {
if (level == 1) {
component.setCursor(null);
waitLevel.remove(component);
} else {
waitLevel.put(component, level - 1);
}
}
}
}
/**
* Triggers UI initializations.
*/
public static void prepareUI() {
new RSyntaxTextAreaWithSQLSyntaxStyle(false, false);
}
/**
* Calls the {@link PrimaryKeyValidator}.
* @param i
*/
@SuppressWarnings("serial")
public static void validatePrimaryKeys(final Window windowAncestor, final BasicDataSource basicDataSource, final Set<Table> tables) {
final ConcurrentTaskControl concurrentTaskControl = new ConcurrentTaskControl(null,
"<html>"
+ "Checking the primary key definitions in the data model <br>for uniqueness...</html>".replace(" ", " ")) {
@Override
protected void onError(Throwable error) {
UIUtil.showException(windowAncestor, "Error", error);
closeWindow();
}
@Override
protected void onCancellation() {
closeWindow();
CancellationHandler.cancel(null);
}
};
ConcurrentTaskControl.openInModalDialog(windowAncestor, concurrentTaskControl,
new ConcurrentTaskControl.Task() {
@Override
public void run() throws Throwable {
Session session = new Session(basicDataSource, basicDataSource.dbms, null);
JobManager jobManager = new JobManager(tables.size() > 1? 4 : 1);
try {
new PrimaryKeyValidator().validatePrimaryKey(session, tables, false, jobManager);
} finally {
session.shutDown();
jobManager.shutdown();
}
invokeLater(new Runnable() {
@Override
public void run() {
JOptionPane.showMessageDialog(windowAncestor, tables.size() == 1? "The primary key definition is valid." : "All primary key definitions are valid.");
concurrentTaskControl.closeWindow();
}
});
}
}, "Checking Primary Keys...");
invokeLater(4, new Runnable() {
@Override
public void run() {
CancellationHandler.reset(null);
}
});
}
/**
* Initializes the "Native L&F" menu items.
*
* @param nativeLAFCheckBoxMenuItem the menu item
*/
public static void initPLAFMenuItem(final JCheckBoxMenuItem nativeLAFCheckBoxMenuItem, final Component parentComponent) {
nativeLAFCheckBoxMenuItem.setSelected(Boolean.TRUE.equals(UISettings.restore(UISettings.USE_NATIVE_PLAF)));
nativeLAFCheckBoxMenuItem.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
boolean nativeLF = nativeLAFCheckBoxMenuItem.isSelected();
UISettings.store(UISettings.USE_NATIVE_PLAF, nativeLF);
JOptionPane.showMessageDialog(parentComponent, "The look and feel has been changed.\n(Will be effective after restart)", "Look&Feel", JOptionPane.INFORMATION_MESSAGE);
}
});
}
public static String format(long number) {
return NumberFormat.getInstance().format(number);
}
private static Font defaultFont = null;
public static Font defaultTitleFont() {
if (defaultFont == null) {
defaultFont = new JLabel().getFont();
defaultFont = defaultFont.deriveFont(defaultFont.getStyle() | Font.BOLD);
}
return defaultFont;
}
}
| src/main/gui/net/sf/jailer/ui/UIUtil.java | /*
* Copyright 2007 - 2019 Ralf Wisser.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.sf.jailer.ui;
import java.awt.Component;
import java.awt.Container;
import java.awt.Cursor;
import java.awt.Dialog;
import java.awt.Dimension;
import java.awt.FileDialog;
import java.awt.Font;
import java.awt.Frame;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.Window;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.StringSelection;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.WeakHashMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JCheckBoxMenuItem;
import javax.swing.JComponent;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JOptionPane;
import javax.swing.JPopupMenu;
import javax.swing.JTable;
import javax.swing.RowSorter;
import javax.swing.SwingUtilities;
import javax.swing.WindowConstants;
import javax.swing.table.TableColumnModel;
import javax.swing.table.TableModel;
import org.apache.log4j.Logger;
import net.sf.jailer.ExecutionContext;
import net.sf.jailer.Jailer;
import net.sf.jailer.JailerVersion;
import net.sf.jailer.database.BasicDataSource;
import net.sf.jailer.database.PrimaryKeyValidator;
import net.sf.jailer.database.Session;
import net.sf.jailer.database.SqlException;
import net.sf.jailer.datamodel.DataModel;
import net.sf.jailer.datamodel.Table;
import net.sf.jailer.extractionmodel.ExtractionModel.IncompatibleModelException;
import net.sf.jailer.progress.ProgressListener;
import net.sf.jailer.ui.databrowser.BrowserContentPane.TableModelItem;
import net.sf.jailer.ui.databrowser.Row;
import net.sf.jailer.ui.scrollmenu.JScrollC2PopupMenu;
import net.sf.jailer.ui.scrollmenu.JScrollPopupMenu;
import net.sf.jailer.ui.syntaxtextarea.RSyntaxTextAreaWithSQLSyntaxStyle;
import net.sf.jailer.ui.util.ConcurrentTaskControl;
import net.sf.jailer.ui.util.HttpUtil;
import net.sf.jailer.ui.util.UISettings;
import net.sf.jailer.util.CancellationException;
import net.sf.jailer.util.CancellationHandler;
import net.sf.jailer.util.CycleFinder;
import net.sf.jailer.util.JobManager;
/**
* Some utility methods.
*
* @author Ralf Wisser
*/
public class UIUtil {
/**
* The logger.
*/
private static final Logger _log = Logger.getLogger(UIUtil.class);
/**
* Opens file chooser.
*
* @param selectedFile
* if not <code>null</code> this file will be selected initially
* @param startDir
* directory to start with
* @param description
* description of file to chose
*/
public static String choseFile(File selectedFile, String startDir, final String description, final String extension,
Component parent, boolean addExtension, boolean forLoad) {
return choseFile(selectedFile, startDir, description, extension, parent, addExtension, forLoad, true);
}
/**
* Opens file chooser.
*
* @param selectedFile
* if not <code>null</code> this file will be selected initially
* @param startDir
* directory to start with
* @param description
* description of file to chose
*/
public static String choseFile(File selectedFile, String startDir, final String description, final String extension,
Component parent, boolean addExtension, boolean forLoad, final boolean allowZip) {
String newStartDir = restoreCurrentDir(extension);
if (newStartDir != null) {
startDir = newStartDir;
try {
if (!new File(startDir).isDirectory()) {
startDir = new File(startDir).getParent();
}
} catch (Exception e) {
// ignore
}
} else {
if (!new File(startDir).isAbsolute()) {
startDir = Environment.newFile(startDir).getPath();
}
}
Window ancestor = SwingUtilities.getWindowAncestor(parent);
if (ancestor != null) {
parent = ancestor;
}
FileDialog fileChooser;
if (parent instanceof Dialog) {
fileChooser = new FileDialog((Dialog) parent);
} else if (parent instanceof Frame) {
fileChooser = new FileDialog((Frame) parent);
} else {
fileChooser = new FileDialog(new Frame());
}
fileChooser.setDirectory(startDir);
fileChooser.setTitle(description);
if (selectedFile != null) {
fileChooser.setFile(selectedFile.getName());
} else if (extension != null && extension.length() > 0) {
if (System.getProperty("os.name", "").toLowerCase().startsWith("windows")) {
// workaround: http://bugs.java.com/view_bug.do?bug_id=8021943
boolean set = true;
Matcher m = Pattern.compile("1.7.0_(\\d+).*").matcher(System.getProperty("java.version", ""));
if (m.matches()) {
try {
set = Integer.parseInt(m.group(1)) > 40;
} catch (NumberFormatException e) {
// ignore;
}
}
if (set) {
fileChooser.setFile("*" + extension + (allowZip ? ";*" + ".zip;*" + ".gz" : ""));
}
}
}
FilenameFilter filter = new FilenameFilter() {
@Override
public boolean accept(File dir, String name) {
return name.toLowerCase().endsWith(extension)
|| allowZip && name.toLowerCase().endsWith(extension + ".gz")
|| allowZip && name.toLowerCase().endsWith(extension + ".zip");
}
};
fileChooser.setFilenameFilter(filter);
fileChooser.setMode(forLoad ? FileDialog.LOAD : FileDialog.SAVE);
fileChooser.setVisible(true);
String fn = fileChooser.getFile();
if (fn != null) {
File selFile = new File(fileChooser.getDirectory(), fn);
try {
File f = selFile;
String work = new File(".").getCanonicalPath();
if (f.getCanonicalPath().startsWith(work)) {
fn = f.getName();
f = f.getParentFile();
while (f != null && !f.getCanonicalPath().equals(work)) {
fn = f.getName() + File.separator + fn;
f = f.getParentFile();
}
} else {
fn = f.getCanonicalPath();
}
if (addExtension && !(fn.endsWith(extension)
|| (allowZip && (fn.endsWith(extension + ".zip") || fn.endsWith(extension + ".gz"))))) {
fn += extension;
}
try {
storeCurrentDir(extension, selFile.getParent());
} catch (Exception e) {
// ignore
}
return fn;
} catch (IOException e1) {
try {
fn = selFile.getCanonicalPath();
if (addExtension && !(fn.endsWith(extension)
|| (allowZip && (fn.endsWith(extension + ".zip") || fn.endsWith(extension + ".gz"))))) {
fn += extension;
}
return fn;
} catch (IOException e) {
throw new RuntimeException(e.getMessage(), e);
}
}
}
return null;
}
/**
* File to store current directory of file chooser.
*/
private final static String cdSettingsName = ".cdsettings";
/**
* Stores current directory of file chooser.
*
* @param key
* the key under which to store current directory
* @param currentDir
* the current directory
*/
@SuppressWarnings("unchecked")
private static void storeCurrentDir(String key, String currentDir) {
try {
File cdSettings = Environment.newFile(cdSettingsName);
Map<String, String> cd = new HashMap<String, String>();
if (cdSettings.exists()) {
try {
ObjectInputStream in = new ObjectInputStream(new FileInputStream(cdSettings));
cd = (Map<String, String>) in.readObject();
in.close();
} catch (Exception e) {
// ignore
}
}
cdSettings.delete();
cd.put(key, currentDir);
ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(cdSettings));
out.writeObject(cd);
out.close();
} catch (Exception e) {
// ignore
}
}
/**
* Restores current directory of file chooser.
*
* @param key
* the key of the current directory to restore
* @return the current directory, or <code>null</code> if no directory has
* been stored under the key
*/
@SuppressWarnings("unchecked")
private static String restoreCurrentDir(String key) {
File cdSettings = Environment.newFile(cdSettingsName);
if (cdSettings.exists()) {
try {
ObjectInputStream in = new ObjectInputStream(new FileInputStream(cdSettings));
Map<String, String> map = ((Map<String, String>) in.readObject());
String cd = map.get(key);
if (cd == null && ".jm".equals(key)) {
cd = map.get(".csv");
}
in.close();
return cd;
} catch (Exception e) {
// ignore
}
}
return null;
}
/**
* Calls the Jailer export engine via CLI.
*
* @param ownerOfConsole
* owner component of jailer console
* @param cliArgs
* CLI arguments
* @param showLogfileButton
* console property
* @param printCommandLine
* if true, print CLI command line
* @param showExplainLogButton
* console property
* @param closeOutputWindow
* if <code>true</code>, close console immediately after call
* @param continueOnErrorQuestion
* to ask when call fails
* @param password
* CLI argument to print as "*****"
* @return <code>true</code> iff call succeeded
*/
public static boolean runJailer(Window ownerOfConsole, List<String> cliArgs, boolean showLogfileButton,
final boolean printCommandLine, boolean showExplainLogButton, final boolean closeOutputWindow,
String continueOnErrorQuestion, String user, String password, final ProgressListener progressListener,
final ProgressPanel progressPanel, final boolean showExeptions, boolean fullSize,
boolean returnFalseOnError, ExecutionContext executionContext) {
return runJailer(ownerOfConsole, cliArgs, showLogfileButton, printCommandLine, showExplainLogButton,
closeOutputWindow, continueOnErrorQuestion, user, password, progressListener, progressPanel, showExeptions,
fullSize, false, returnFalseOnError, false, executionContext);
}
/**
* Calls the Jailer export engine via CLI.
*
* @param ownerOfConsole
* owner component of jailer console
* @param cliArgs
* CLI arguments
* @param showLogfileButton
* console property
* @param printCommandLine
* if true, print CLI command line
* @param showExplainLogButton
* console property
* @param closeOutputWindow
* if <code>true</code>, close console immediately after call
* @param continueOnErrorQuestion
* to ask when call fails
* @param password
* CLI argument to print as "*****"
* @return <code>true</code> iff call succeeded
*/
public static boolean runJailer(Window ownerOfConsole, List<String> cliArgs, boolean showLogfileButton,
final boolean printCommandLine, boolean showExplainLogButton, final boolean closeOutputWindow,
String continueOnErrorQuestion, String user, String password, final ProgressListener progressListener,
final ProgressPanel progressPanel, final boolean showExeptions, boolean fullSize,
final boolean closeOutputWindowOnError, boolean returnFalseOnError, boolean throwException, ExecutionContext executionContext) {
JDialog dialog = new JDialog(ownerOfConsole);
List<String> args = new ArrayList<String>(cliArgs);
final StringBuffer arglist = createCLIArgumentString(user, password, args, executionContext);
final List<String> argslist = new ArrayList<String>();
boolean esc = true;
for (String arg : args) {
if (esc && arg.startsWith("-")) {
if (arg.equals(user) || arg.equals(password)) {
argslist.add("-");
} else {
esc = false;
}
}
argslist.add(arg);
}
final String[] argsarray = new String[argslist.size()];
int i = 0;
for (String arg : argslist) {
argsarray[i++] = arg;
}
final JailerConsole outputView = new JailerConsole(ownerOfConsole, dialog, showLogfileButton,
showExplainLogButton, progressPanel, fullSize);
final PrintStream originalOut = System.out;
final boolean[] ready = new boolean[] { true };
System.setOut(new PrintStream(new OutputStream() {
private int lineNr = 0;
StringBuffer buffer = new StringBuffer();
@Override
public synchronized void write(byte[] arg0, int arg1, int arg2) throws IOException {
super.write(arg0, arg1, arg2);
}
@Override
public void write(int b) throws IOException {
if (b != '@') {
originalOut.write(b);
}
boolean wasReady;
synchronized (buffer) {
wasReady = ready[0];
if (b != '@') {
buffer.append((char) b);
}
}
if ((char) b == '\n') {
++lineNr;
}
if ((char) b == '\n' && lineNr % 60 == 0 || (char) b == '@') {
if (wasReady) {
synchronized (buffer) {
ready[0] = false;
}
UIUtil.invokeLater(new Runnable() {
@Override
public void run() {
synchronized (buffer) {
if (buffer.length() > 0) {
outputView.appendText(buffer.toString());
buffer.setLength(0);
}
}
ready[0] = true;
}
});
}
}
}
}));
final boolean[] exceptionShown = new boolean[1];
try {
try {
File exportLog = Environment.newFile("export.log");
File sqlLog = Environment.newFile("sql.log");
if (exportLog.exists()) {
FileOutputStream out = new FileOutputStream(exportLog);
out.close();
}
if (sqlLog.exists()) {
FileOutputStream out = new FileOutputStream(sqlLog);
out.close();
}
} catch (Exception e) {
// UIUtil.showException(null, "Error", e, arglist);
}
final boolean[] result = new boolean[] { false };
final Throwable[] exp = new Throwable[1];
final StringBuffer warnings = new StringBuffer();
final boolean[] fin = new boolean[] { false };
outputView.dialog.addWindowListener(new WindowAdapter() {
boolean cancelled = false;
@Override
public void windowClosing(WindowEvent e) {
boolean f;
synchronized (UIUtil.class) {
f = exp[0] == null;
}
try {
CancellationHandler.checkForCancellation(null);
} catch (CancellationException ce) {
cancelled = true;
}
if (cancelled && f) {
cancel();
JOptionPane.showMessageDialog(outputView.dialog, "Cancellation in progress...", "Cancellation",
JOptionPane.INFORMATION_MESSAGE);
} else if (exp[0] == null && !fin[0] && !cancelled) {
if (JOptionPane.showConfirmDialog(outputView.dialog, "Cancel operation?", "Cancellation",
JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE) == JOptionPane.YES_OPTION) {
if (!outputView.hasFinished) {
cancel();
outputView.dialog.setTitle("Jailer Console - cancelling...");
if (progressListener != null) {
progressListener.newStage("cancelling...", true, true);
}
outputView.getCancelButton().setEnabled(false);
cancelled = true;
}
}
}
}
private void cancel() {
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
CancellationHandler.cancel(null);
}
});
thread.setDaemon(true);
thread.start();
}
});
new Thread(new Runnable() {
@Override
public void run() {
for (int i = 0;; ++i) {
try {
Thread.sleep(i == 0 ? 500 : 1000);
} catch (InterruptedException e) {
}
synchronized (fin) {
if (fin[0]) {
break;
}
System.out.print("@");
}
}
}
}).start();
new Thread(new Runnable() {
@Override
public void run() {
try {
if (printCommandLine) {
_log.info("arguments: " + arglist.toString().trim());
}
result[0] = Jailer.jailerMain(argsarray, disableWarnings ? new StringBuffer() : warnings,
progressListener);
} catch (Throwable t) {
synchronized (UIUtil.class) {
exp[0] = t;
}
} finally {
// flush
System.out.println("@");
synchronized (UIUtil.class) {
fin[0] = true;
}
}
UIUtil.invokeLater(new Runnable() {
@Override
public void run() {
synchronized (UIUtil.class) {
outputView.dialog.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
if (progressListener != null) {
progressListener.newStage(outputView.hasCancelled ? "cancelled"
: exp[0] == null ? "finished" : "failed", exp[0] != null, true);
}
if ((exp[0] instanceof CancellationException) || closeOutputWindowOnError
|| (closeOutputWindow && result[0] && exp[0] == null
&& warnings.length() == 0)) {
if (!outputView.hasCancelled) {
outputView.dialog.setVisible(false);
}
} else {
outputView.finish(result[0] && exp[0] == null);
if (result[0] && warnings.length() > 0) {
JOptionPane.showMessageDialog(outputView.dialog,
warnings.length() > 800 ? warnings.substring(0, 800) + "..."
: warnings.toString(),
"Warning", JOptionPane.INFORMATION_MESSAGE);
outputView.dialog.setVisible(false);
} else if (showExeptions && exp[0] != null
&& !(exp[0] instanceof CancellationException)) {
UIUtil.showException(outputView.dialog, "Error", exp[0], arglist);
exceptionShown[0] = true;
}
if (result[0] && progressPanel != null) {
progressPanel.confirm();
}
}
}
}
});
}
}, "jailer-main").start();
outputView.dialog.setVisible(true);
synchronized (UIUtil.class) {
if (exp[0] != null) {
if (returnFalseOnError) {
result[0] = false;
} else {
throw exp[0];
}
}
}
if (!result[0] && continueOnErrorQuestion != null) {
result[0] = JOptionPane.showConfirmDialog(outputView.dialog, continueOnErrorQuestion, "Error",
JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION;
}
return result[0];
} catch (Throwable t) {
if (t instanceof CancellationException) {
CancellationHandler.reset(null);
} else {
boolean shown = false;
synchronized (UIUtil.class) {
shown = exceptionShown[0];
}
if (throwException) {
throw new RuntimeException(t);
}
if (!shown) {
UIUtil.showException(null, "Error", t, arglist);
}
}
return false;
} finally {
System.setOut(originalOut);
}
}
public static StringBuffer createCLIArgumentString(String user, String password, List<String> args, ExecutionContext executionContext) {
args.add("-datamodel");
args.add(executionContext.getQualifiedDatamodelFolder());
return createPlainCLIArguments(user, password, args);
}
public static StringBuffer createPlainCLIArguments(String user, String password, List<String> args) {
final StringBuffer arglist = new StringBuffer();
int pwi = -1;
for (int i = args.size() - 1; i >= 0; --i) {
if (args.get(i) != null && args.get(i).equals(password) && password.length() > 0) {
pwi = i;
break;
}
}
for (int i = 0; i < args.size(); ++i) {
String arg = args.get(i);
if (i == pwi) {
arglist.append(" - \"<password>\"");
} else {
if (arg.startsWith("-") && arg.equals(user)) {
arglist.append(" -");
}
if ("".equals(arg) || arg.contains(" ") || arg.contains("<") || arg.contains(">") || arg.contains("*")
|| arg.contains("?") || arg.contains("|") || arg.contains("$") || arg.contains("\"")
|| arg.contains("'") || arg.contains("\\") || arg.contains(";") || arg.contains("&")) {
arglist.append(" \"");
for (int j = 0; j < arg.length(); ++j) {
char c = arg.charAt(j);
if (c == '\"' || c == '$') {
arglist.append("\\");
}
arglist.append(c);
}
arglist.append("\"");
} else {
arglist.append(" " + arg);
}
}
}
return arglist;
}
public static Object EXCEPTION_CONTEXT_USER_ERROR = new Object();
public static Object EXCEPTION_CONTEXT_USER_WARNING = new Object();
/**
* Shows an exception.
*
* @param parent
* parent component of option pane
* @param title
* title of option pane
* @param t
* the exception
*/
public static void showException(Component parent, String title, Throwable t) {
showException(parent, title, t, null);
}
/**
* Shows an exception.
*
* @param parent
* parent component of option pane
* @param title
* title of option pane
* @param context
* optional context object. String or Session is supported.
* @param t
* the exception
*/
public static void showException(Component parent, String title, Throwable t, Object context) {
showException(parent, title, t, context, null);
}
/**
* Shows an exception.
*
* @param parent
* parent component of option pane
* @param title
* title of option pane
* @param context
* optional context object. String or Session is supported.
* @param t
* the exception
*/
public static void showException(Component parent, String title, Throwable t, Object context, JComponent additionalControl) {
if (context == EXCEPTION_CONTEXT_USER_ERROR) {
if (t instanceof IndexOutOfBoundsException
|| t instanceof NullPointerException
|| t instanceof ClassCastException
|| t instanceof IllegalStateException
|| t instanceof IllegalArgumentException) {
context = null;
}
}
if (t instanceof DataModel.NoPrimaryKeyException || t instanceof CycleFinder.CycleFoundException || t instanceof IncompatibleModelException) {
context = EXCEPTION_CONTEXT_USER_ERROR;
}
t.printStackTrace();
if (!(t instanceof ClassNotFoundException)) {
while (t.getCause() != null && t != t.getCause() && !(t instanceof SqlException)) {
t = t.getCause();
}
}
if (t instanceof DataModel.NoPrimaryKeyException || t instanceof CycleFinder.CycleFoundException || t instanceof IncompatibleModelException) {
context = EXCEPTION_CONTEXT_USER_ERROR;
}
if (t instanceof SqlException) {
String message = ((SqlException) t).message;
String sql = ((SqlException) t).sqlStatement;
if (message != null) {
if (sql != null) {
String iMsg = message.toString() + "\n" + JailerVersion.VERSION + "\n" + sql;
sendIssue("internalSQL", iMsg);
}
}
new SqlErrorDialog(parent == null ? null : parent instanceof Window? (Window) parent : SwingUtilities.getWindowAncestor(parent),
((SqlException) t).isFormatted()? message : lineWrap(message, 120).toString(), sql, ((SqlException) t).isFormatted(), true, null, false, additionalControl);
return;
}
if (t instanceof CancellationException) {
return;
}
String message = t.getMessage();
if (message == null || "".equals(message.trim())) {
message = t.getClass().getName();
}
StringBuilder msg = lineWrap(message, 80);
String contextDesc = "";
if (context != null) {
if (context instanceof Session) {
Session session = (Session) context;
contextDesc = session.dbUrl + " (" + session.dbms + ")";
} else if (context != EXCEPTION_CONTEXT_USER_ERROR) {
contextDesc = lineWrap(context.toString(), 80).toString();
}
}
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
t.printStackTrace(pw);
if (context != EXCEPTION_CONTEXT_USER_ERROR) {
contextDesc += "\nHelp Desk: https://sourceforge.net/p/jailer/discussion/";
contextDesc += "\nMail: [email protected]\n";
contextDesc += "\n" + JailerVersion.APPLICATION_NAME + " " + JailerVersion.VERSION + "\n\n" + sw.toString();
String iMsg = msg.toString() + "\n" + JailerVersion.APPLICATION_NAME + " " + JailerVersion.VERSION + "\n\n" + sw.toString();
iMsg = iMsg
.replaceAll("\\bat [^\\n]*/", "at ")
.replaceAll("\\bat java.", "atj..")
.replaceAll("\\bat javax.swing.", "atjs..")
.replaceAll("\\bat net.sf.jailer.", "atn..")
.replaceAll("\\s*(\\n)\\s*", "$1");
sendIssue("internal", iMsg);
}
new SqlErrorDialog(parent == null ? null : parent instanceof Window? (Window) parent : SwingUtilities.getWindowAncestor(parent), msg.toString(),
contextDesc, false, false, context == EXCEPTION_CONTEXT_USER_ERROR || context == EXCEPTION_CONTEXT_USER_WARNING? title : null, context == EXCEPTION_CONTEXT_USER_WARNING, additionalControl);
}
private static StringBuilder lineWrap(String message, int maxwidth) {
StringBuilder msg = new StringBuilder();
Pattern wrapRE = Pattern.compile("(\\S\\S{" + maxwidth + ",}|.{1," + maxwidth + "})(\\s+|$)");
Matcher m = wrapRE.matcher(message == null ? "" : message);
while (m.find()) {
String line = m.group();
while (line.length() > maxwidth + 10) {
msg.append(line.substring(0, maxwidth) + "\n");
line = line.substring(maxwidth);
}
msg.append(line + (line.contains("\n") ? "" : "\n"));
}
return msg;
}
/**
* Initializes peer of newly created window.
*
* Should not be neccassary, but there is a strange bug in AWT of jre 6 on
* multi-core/processor systems. Sleeping a little after creating peer and
* before making peer visible seems to help.
*/
public static void initPeer() {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
}
}
public static void fit(Window d) {
try {
// Get the size of the screen
Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
int hd = d.getY() + d.getHeight() - (dim.height - 60);
if (hd > 0) {
d.setSize(d.getWidth(), Math.max(d.getHeight() - hd, 150));
}
d.setLocation(Math.max(0, d.getX()), Math.max(0, d.getY()));
} catch (Throwable t) {
// ignore
}
}
public static boolean disableWarnings = false;
/**
* Tries to get as much memory as possible and shows it's size.
*/
public static void showMaxMemory() {
long memSize = 0;
try {
final int MB = 1024 * 1024;
List<byte[]> mem = new ArrayList<byte[]>();
while (true) {
mem.add(new byte[MB]);
memSize += MB;
}
} catch (OutOfMemoryError e) {
JOptionPane.showConfirmDialog(null, "MaxMem=" + memSize, "", JOptionPane.INFORMATION_MESSAGE);
}
}
public static void replace(JComponent component, JComponent replacement) {
Container parent = component.getParent();
GridBagConstraints c = ((GridBagLayout) parent.getLayout()).getConstraints(component);
parent.remove(component);
if (replacement != null) {
parent.add(replacement, c);
}
}
public static void wireComponentWithButton(JComponent component, final JButton button) {
component.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
if (e.getButton() == MouseEvent.BUTTON1 && e.getClickCount() > 1) {
if (button.isEnabled()) {
button.doClick();
}
}
}
});
component.addKeyListener(new KeyListener() {
@Override
public void keyTyped(KeyEvent e) {
if (e.getKeyChar() == '\n') {
if (button.isEnabled()) {
button.doClick();
}
}
}
@Override
public void keyReleased(KeyEvent arg0) {
}
@Override
public void keyPressed(KeyEvent arg0) {
}
});
}
public static void fit(JPopupMenu popup) {
if (!(popup instanceof JScrollPopupMenu || popup instanceof JScrollC2PopupMenu)) {
final int MAX_ITEMS = 40;
Component[] comps = popup.getComponents();
popup.removeAll();
JMenu current = null;
int ci = 1;
for (int i = 0; i < comps.length; ++i) {
if (ci > MAX_ITEMS && i < comps.length - 5) {
ci = 1;
JMenu newMenu = new JMenu("more...");
if (current == null) {
popup.add(newMenu);
} else {
current.add(newMenu);
}
current = newMenu;
}
if (current == null) {
popup.add(comps[i]);
} else {
current.add(comps[i]);
}
++ci;
}
}
}
public static void checkTermination() {
for (Window w : Window.getWindows()) {
if (w.isShowing()) {
return;
}
}
System.exit(0);
}
public static void sendIssue(final String type, final String issue) {
new Thread(new Runnable() {
@Override
public void run() {
try {
final int MAX_CL = 1400;
int maxEIssueLength = 4 * MAX_CL;
String url;
do {
String eIssue = URLEncoder.encode(issue, "UTF-8");
if (eIssue.length() > maxEIssueLength) {
eIssue = eIssue.substring(0, maxEIssueLength);
}
url = "http://jailer.sf.net/issueReport.php?type=" + URLEncoder.encode(type, "UTF-8") + "&" + "issue=" + eIssue
+ "&uuid=" + URLEncoder.encode(String.valueOf(UISettings.restore("uuid")), "UTF-8")
+ "&ts=" + URLEncoder.encode(new Date().toString(), "UTF-8")
+ "&jversion=" + URLEncoder.encode(System.getProperty("java.version") + "/" + System.getProperty("java.vm.vendor") + "/" + System.getProperty("java.vm.name") + "/" + System.getProperty("os.name"), "UTF-8") + "/(" + Environment.state + ")";
maxEIssueLength -= 10;
} while (url.length() > MAX_CL && maxEIssueLength > 100);
HttpUtil.get(url);
} catch (UnsupportedEncodingException e) {
// ignore
}
}
}).start();
}
public static String toHTML(String plainText, int maxLineLength) {
plainText = plainText.trim();
if (maxLineLength > 0) {
StringBuilder sb = new StringBuilder();
int MAXLINES = 50;
int lineNr = 0;
for (String line: plainText.split("\n")) {
if (line.length() > maxLineLength) {
sb.append(line.substring(0, maxLineLength) + "...");
} else {
sb.append(line);
}
if (++lineNr > MAXLINES) {
sb.append("...");
break;
}
sb.append("\n");
}
plainText = sb.toString();
}
return "<html>" +
plainText
.replace("&", "&")
.replace("<", "<")
.replace(">", ">")
.replace("\n", "<br>")
.replace(" ", " ")
.replace("\t"," ");
}
public static ImageIcon scaleIcon(JComponent component, ImageIcon icon) {
if (icon != null) {
int heigth = component.getFontMetrics(new JLabel("M").getFont()).getHeight();
double s = heigth / (double) icon.getIconHeight();
try {
return new ImageIcon(icon.getImage().getScaledInstance((int)(icon.getIconWidth() * s), (int)(icon.getIconHeight() * s), Image.SCALE_SMOOTH));
} catch (Exception e) {
return null;
}
}
return null;
}
/**
* Represents "null"-value in rows tables.
*/
public static final String NULL = "null";
public static String LINE_SEPARATOR = System.getProperty("line.separator", "\n");
/**
* Copies selected cells of a rows table into the clipboard.
*
* @param table the table
*/
public static void copyToClipboard(JTable table, boolean lineOnSingeCell) {
String nl = System.getProperty("line.separator", "\n");
StringBuilder sb = new StringBuilder();
boolean prepNL = table.getSelectedRows().length > 1;
int[] selectedColumns = table.getSelectedColumns();
if (table.getSelectedColumnCount() == 1 && table.getSelectedRowCount() == 1 && lineOnSingeCell) {
prepNL = true;
selectedColumns = new int[table.getColumnCount()];
for (int i = 0; i < selectedColumns.length; ++i) {
selectedColumns[i] = i;
}
}
RowSorter<? extends TableModel> rowSorter = table.getRowSorter();
TableColumnModel columnModel = table.getColumnModel();
boolean firstLine = true;
for (int row: table.getSelectedRows()) {
if (!firstLine) {
sb.append(nl);
}
boolean f = true;
for (int col: selectedColumns) {
Object value = table.getModel().getValueAt(
rowSorter == null? row : rowSorter.convertRowIndexToModel(row),
columnModel.getColumn(col).getModelIndex());
if (value instanceof Row) {
Object[] values = ((Row) value).values;
for (Object v: values) {
if (v instanceof TableModelItem) {
v = ((TableModelItem) v).value;
}
if (!f) {
sb.append("\t");
}
f = false;
sb.append(v == NULL || v == null? "" : v);
}
} else {
if (value instanceof TableModelItem) {
value = ((TableModelItem) value).value;
}
if (!f) {
sb.append("\t");
}
f = false;
sb.append(value == NULL || value == null? "" : value);
}
}
firstLine = false;
}
if (prepNL) {
sb.append(nl);
}
StringSelection selection = new StringSelection(sb.toString());
Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
clipboard.setContents(selection, selection);
}
/**
* Pair of Icon and Text.
*/
public static class IconWithText implements Comparable<IconWithText> {
public final String text;
public final ImageIcon icon;
public IconWithText(String text, ImageIcon icon) {
this.text = text;
this.icon = icon;
}
@Override
public String toString() {
return text;
}
@Override
public int compareTo(IconWithText o) {
return text.compareTo(o.text);
}
}
private static boolean isPopupActive = false;
public static synchronized boolean isPopupActive() {
return isPopupActive;
}
private static synchronized void setPopupActive(boolean b) {
isPopupActive = b;
}
public static void showPopup(final Component invoker, final int x, final int y, final JPopupMenu popup) {
popup.addPropertyChangeListener("visible", new PropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent evt) {
if (Boolean.FALSE.equals(evt.getNewValue())) {
setPopupActive(false);
}
}
});
UIUtil.invokeLater(new Runnable() {
@Override
public void run() {
setPopupActive(true);
popup.show(invoker, x, y);
}
});
}
public static void invokeLater(final Runnable runnable) {
SwingUtilities.invokeLater(runnable);
}
public static void invokeLater(final int ticks, final Runnable runnable) {
SwingUtilities.invokeLater(new Runnable() {
int count = ticks;
@Override
public void run() {
--count;
if (count <= 0) {
runnable.run();
} else {
SwingUtilities.invokeLater(this);
}
}
});
}
private static Map<Component, Integer> waitLevel = new WeakHashMap<Component, Integer>();
public static void setWaitCursor(Component component) {
if (component != null) {
Integer level = waitLevel.get(component);
if (level != null) {
waitLevel.put(component, level + 1);
} else {
waitLevel.put(component, 1);
component.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
}
}
}
public static void resetWaitCursor(Component component) {
if (component != null) {
Integer level = waitLevel.get(component);
if (level != null) {
if (level == 1) {
component.setCursor(null);
waitLevel.remove(component);
} else {
waitLevel.put(component, level - 1);
}
}
}
}
/**
* Triggers UI initializations.
*/
public static void prepareUI() {
new RSyntaxTextAreaWithSQLSyntaxStyle(false, false);
}
/**
* Calls the {@link PrimaryKeyValidator}.
* @param i
*/
@SuppressWarnings("serial")
public static void validatePrimaryKeys(final Window windowAncestor, final BasicDataSource basicDataSource, final Set<Table> tables) {
final ConcurrentTaskControl concurrentTaskControl = new ConcurrentTaskControl(null,
"<html>"
+ "Checking the primary key definitions in the data model <br>for uniqueness...</html>".replace(" ", " ")) {
@Override
protected void onError(Throwable error) {
UIUtil.showException(windowAncestor, "Error", error);
closeWindow();
}
@Override
protected void onCancellation() {
closeWindow();
CancellationHandler.cancel(null);
}
};
ConcurrentTaskControl.openInModalDialog(windowAncestor, concurrentTaskControl,
new ConcurrentTaskControl.Task() {
@Override
public void run() throws Throwable {
Session session = new Session(basicDataSource, basicDataSource.dbms, null);
JobManager jobManager = new JobManager(tables.size() > 1? 4 : 1);
try {
new PrimaryKeyValidator().validatePrimaryKey(session, tables, false, jobManager);
} finally {
session.shutDown();
jobManager.shutdown();
}
invokeLater(new Runnable() {
@Override
public void run() {
JOptionPane.showMessageDialog(windowAncestor, tables.size() == 1? "The primary key definition is valid." : "All primary key definitions are valid.");
concurrentTaskControl.closeWindow();
}
});
}
}, "Checking Primary Keys...");
invokeLater(4, new Runnable() {
@Override
public void run() {
CancellationHandler.reset(null);
}
});
}
/**
* Initializes the "Native L&F" menu items.
*
* @param nativeLAFCheckBoxMenuItem the menu item
*/
public static void initPLAFMenuItem(final JCheckBoxMenuItem nativeLAFCheckBoxMenuItem, final Component parentComponent) {
nativeLAFCheckBoxMenuItem.setSelected(Boolean.TRUE.equals(UISettings.restore(UISettings.USE_NATIVE_PLAF)));
nativeLAFCheckBoxMenuItem.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
boolean nativeLF = nativeLAFCheckBoxMenuItem.isSelected();
UISettings.store(UISettings.USE_NATIVE_PLAF, nativeLF);
JOptionPane.showMessageDialog(parentComponent, "The look and feel has been changed.\n(Will be effective after restart)", "Look&Feel", JOptionPane.INFORMATION_MESSAGE);
}
});
}
public static String format(long number) {
return NumberFormat.getInstance().format(number);
}
private static Font defaultFont = null;
public static Font defaultTitleFont() {
if (defaultFont == null) {
defaultFont = new JLabel().getFont();
defaultFont = defaultFont.deriveFont(defaultFont.getStyle() | Font.BOLD);
}
return defaultFont;
}
}
| reduced max issue length | src/main/gui/net/sf/jailer/ui/UIUtil.java | reduced max issue length | <ide><path>rc/main/gui/net/sf/jailer/ui/UIUtil.java
<ide> @Override
<ide> public void run() {
<ide> try {
<del> final int MAX_CL = 1400;
<add> final int MAX_CL = 1300;
<ide> int maxEIssueLength = 4 * MAX_CL;
<ide> String url;
<ide> do { |
|
Java | mit | c77812d2a892603a5d58d4dff7ce7e3674744f94 | 0 | JetBrains/ideavim,JetBrains/ideavim | /*
* IdeaVim - Vim emulator for IDEs based on the IntelliJ platform
* Copyright (C) 2003-2014 The IdeaVim authors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.maddyhome.idea.vim.ex.handler;
import com.intellij.openapi.actionSystem.DataContext;
import com.intellij.openapi.editor.Editor;
import com.maddyhome.idea.vim.VimPlugin;
import com.maddyhome.idea.vim.command.MappingMode;
import com.maddyhome.idea.vim.ex.CommandHandler;
import com.maddyhome.idea.vim.ex.CommandName;
import com.maddyhome.idea.vim.ex.ExCommand;
import com.maddyhome.idea.vim.ex.VimrcCommandHandler;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static com.maddyhome.idea.vim.helper.StringHelper.parseKeys;
/**
* @author vlan
*/
public class MapHandler extends CommandHandler implements VimrcCommandHandler {
// TODO: Support xmap, smap, map!, lmap
public static final CommandInfo[] COMMAND_INFOS = new CommandInfo[] {
new CommandInfo("map", "", MappingMode.NVO, true),
new CommandInfo("nm", "ap", MappingMode.N, true),
new CommandInfo("vm", "ap", MappingMode.V, true),
new CommandInfo("om", "ap", MappingMode.O, true),
new CommandInfo("im", "ap", MappingMode.I, true),
new CommandInfo("cm", "ap", MappingMode.C, true),
};
public static final CommandName[] COMMAND_NAMES = createCommandNames();
private static final Pattern RE_MAP_ARGUMENTS = Pattern.compile("([^ ]+) +(.+)");
public MapHandler() {
super(COMMAND_NAMES, RANGE_FORBIDDEN | ARGUMENT_OPTIONAL);
}
@Override
public boolean execute(@NotNull Editor editor, @NotNull DataContext context, @NotNull ExCommand cmd) {
return executeCommand(cmd, editor);
}
@Override
public void execute(@NotNull ExCommand cmd) {
executeCommand(cmd, null);
}
private boolean executeCommand(@NotNull ExCommand cmd, @Nullable Editor editor) {
final CommandInfo commandInfo = getCommandInfo(cmd.getCommand());
if (commandInfo != null) {
final String argument = cmd.getArgument();
final Set<MappingMode> modes = commandInfo.getMappingModes();
if (argument.isEmpty()) {
return editor != null && VimPlugin.getKey().showKeyMappings(modes, editor);
}
else {
final Matcher matcher = RE_MAP_ARGUMENTS.matcher(argument);
if (matcher.matches()) {
VimPlugin.getKey().putKeyMapping(modes, parseKeys(matcher.group(1)), parseKeys(matcher.group(2)),
commandInfo.isRecursive());
return true;
}
}
}
return false;
}
@Nullable
private CommandInfo getCommandInfo(@NotNull String command) {
for (CommandInfo commandInfo : COMMAND_INFOS) {
if (command.startsWith(commandInfo.getPrefix())) {
return commandInfo;
}
}
return null;
}
private static CommandName[] createCommandNames() {
final List<CommandName> commandNames = new ArrayList<CommandName>();
for (CommandInfo commandInfo : COMMAND_INFOS) {
commandNames.add(new CommandName(commandInfo.getPrefix(), commandInfo.getSuffix()));
}
return commandNames.toArray(new CommandName[commandNames.size()]);
}
private static class CommandInfo {
@NotNull private final String myPrefix;
@NotNull private final String mySuffix;
@NotNull private final Set<MappingMode> myMappingModes;
private final boolean myRecursive;
public CommandInfo(@NotNull String prefix, @NotNull String suffix, @NotNull Set<MappingMode> mappingModes,
boolean recursive) {
myPrefix = prefix;
mySuffix = suffix;
myMappingModes = mappingModes;
myRecursive = recursive;
}
@NotNull
public String getPrefix() {
return myPrefix;
}
@NotNull
public String getSuffix() {
return mySuffix;
}
@NotNull
public Set<MappingMode> getMappingModes() {
return myMappingModes;
}
public boolean isRecursive() {
return myRecursive;
}
}
}
| src/com/maddyhome/idea/vim/ex/handler/MapHandler.java | /*
* IdeaVim - Vim emulator for IDEs based on the IntelliJ platform
* Copyright (C) 2003-2014 The IdeaVim authors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.maddyhome.idea.vim.ex.handler;
import com.intellij.openapi.actionSystem.DataContext;
import com.intellij.openapi.editor.Editor;
import com.maddyhome.idea.vim.VimPlugin;
import com.maddyhome.idea.vim.command.MappingMode;
import com.maddyhome.idea.vim.ex.CommandHandler;
import com.maddyhome.idea.vim.ex.CommandName;
import com.maddyhome.idea.vim.ex.ExCommand;
import com.maddyhome.idea.vim.ex.VimrcCommandHandler;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static com.maddyhome.idea.vim.helper.StringHelper.parseKeys;
/**
* @author vlan
*/
public class MapHandler extends CommandHandler implements VimrcCommandHandler {
public static final Pattern RE_MAP_ARGUMENTS = Pattern.compile("([^ ]+) +(.+)");
public MapHandler() {
super(new CommandName[]{
// TODO: Support xmap, smap, map!, lmap
new CommandName("map", ""),
new CommandName("nm", "ap"),
new CommandName("vm", "ap"),
new CommandName("om", "ap"),
new CommandName("im", "ap"),
new CommandName("cm", "ap")
}, RANGE_FORBIDDEN | ARGUMENT_OPTIONAL);
}
@Override
public boolean execute(@NotNull Editor editor, @NotNull DataContext context, @NotNull ExCommand cmd) {
return executeCommand(cmd, editor);
}
@Override
public void execute(@NotNull ExCommand cmd) {
executeCommand(cmd, null);
}
private boolean executeCommand(@NotNull ExCommand cmd, @Nullable Editor editor) {
final Set<MappingMode> modes = getMappingModes(cmd.getCommand());
if (modes != null) {
final String argument = cmd.getArgument();
if (argument.isEmpty()) {
return editor != null && VimPlugin.getKey().showKeyMappings(modes, editor);
}
else {
final Matcher matcher = RE_MAP_ARGUMENTS.matcher(argument);
if (matcher.matches()) {
VimPlugin.getKey().putKeyMapping(modes, parseKeys(matcher.group(1)), parseKeys(matcher.group(2)), true);
return true;
}
}
}
return false;
}
@Nullable
private Set<MappingMode> getMappingModes(@NotNull String command) {
if (command.equals("map")) {
return MappingMode.NVO;
}
else if (command.startsWith("nm")) {
return MappingMode.N;
}
else if (command.startsWith("vm")) {
return MappingMode.V;
}
else if (command.startsWith("om")) {
return MappingMode.O;
}
else if (command.equals("map!")) {
return MappingMode.IC;
}
else if (command.startsWith("im")) {
return MappingMode.I;
}
else if (command.startsWith("cm")) {
return MappingMode.C;
}
return null;
}
}
| Refactored MapHandler to be more declarative
| src/com/maddyhome/idea/vim/ex/handler/MapHandler.java | Refactored MapHandler to be more declarative | <ide><path>rc/com/maddyhome/idea/vim/ex/handler/MapHandler.java
<ide> import org.jetbrains.annotations.NotNull;
<ide> import org.jetbrains.annotations.Nullable;
<ide>
<add>import java.util.ArrayList;
<add>import java.util.List;
<ide> import java.util.Set;
<ide> import java.util.regex.Matcher;
<ide> import java.util.regex.Pattern;
<ide> * @author vlan
<ide> */
<ide> public class MapHandler extends CommandHandler implements VimrcCommandHandler {
<del> public static final Pattern RE_MAP_ARGUMENTS = Pattern.compile("([^ ]+) +(.+)");
<add> // TODO: Support xmap, smap, map!, lmap
<add> public static final CommandInfo[] COMMAND_INFOS = new CommandInfo[] {
<add> new CommandInfo("map", "", MappingMode.NVO, true),
<add> new CommandInfo("nm", "ap", MappingMode.N, true),
<add> new CommandInfo("vm", "ap", MappingMode.V, true),
<add> new CommandInfo("om", "ap", MappingMode.O, true),
<add> new CommandInfo("im", "ap", MappingMode.I, true),
<add> new CommandInfo("cm", "ap", MappingMode.C, true),
<add> };
<add> public static final CommandName[] COMMAND_NAMES = createCommandNames();
<add>
<add> private static final Pattern RE_MAP_ARGUMENTS = Pattern.compile("([^ ]+) +(.+)");
<ide>
<ide> public MapHandler() {
<del> super(new CommandName[]{
<del> // TODO: Support xmap, smap, map!, lmap
<del> new CommandName("map", ""),
<del> new CommandName("nm", "ap"),
<del> new CommandName("vm", "ap"),
<del> new CommandName("om", "ap"),
<del> new CommandName("im", "ap"),
<del> new CommandName("cm", "ap")
<del> }, RANGE_FORBIDDEN | ARGUMENT_OPTIONAL);
<add> super(COMMAND_NAMES, RANGE_FORBIDDEN | ARGUMENT_OPTIONAL);
<ide> }
<add>
<ide>
<ide> @Override
<ide> public boolean execute(@NotNull Editor editor, @NotNull DataContext context, @NotNull ExCommand cmd) {
<ide> }
<ide>
<ide> private boolean executeCommand(@NotNull ExCommand cmd, @Nullable Editor editor) {
<del> final Set<MappingMode> modes = getMappingModes(cmd.getCommand());
<del> if (modes != null) {
<add> final CommandInfo commandInfo = getCommandInfo(cmd.getCommand());
<add> if (commandInfo != null) {
<ide> final String argument = cmd.getArgument();
<add> final Set<MappingMode> modes = commandInfo.getMappingModes();
<ide> if (argument.isEmpty()) {
<ide> return editor != null && VimPlugin.getKey().showKeyMappings(modes, editor);
<ide> }
<ide> else {
<ide> final Matcher matcher = RE_MAP_ARGUMENTS.matcher(argument);
<ide> if (matcher.matches()) {
<del> VimPlugin.getKey().putKeyMapping(modes, parseKeys(matcher.group(1)), parseKeys(matcher.group(2)), true);
<add> VimPlugin.getKey().putKeyMapping(modes, parseKeys(matcher.group(1)), parseKeys(matcher.group(2)),
<add> commandInfo.isRecursive());
<ide> return true;
<ide> }
<ide> }
<ide> }
<ide>
<ide> @Nullable
<del> private Set<MappingMode> getMappingModes(@NotNull String command) {
<del> if (command.equals("map")) {
<del> return MappingMode.NVO;
<del> }
<del> else if (command.startsWith("nm")) {
<del> return MappingMode.N;
<del> }
<del> else if (command.startsWith("vm")) {
<del> return MappingMode.V;
<del> }
<del> else if (command.startsWith("om")) {
<del> return MappingMode.O;
<del> }
<del> else if (command.equals("map!")) {
<del> return MappingMode.IC;
<del> }
<del> else if (command.startsWith("im")) {
<del> return MappingMode.I;
<del> }
<del> else if (command.startsWith("cm")) {
<del> return MappingMode.C;
<add> private CommandInfo getCommandInfo(@NotNull String command) {
<add> for (CommandInfo commandInfo : COMMAND_INFOS) {
<add> if (command.startsWith(commandInfo.getPrefix())) {
<add> return commandInfo;
<add> }
<ide> }
<ide> return null;
<ide> }
<add>
<add> private static CommandName[] createCommandNames() {
<add> final List<CommandName> commandNames = new ArrayList<CommandName>();
<add> for (CommandInfo commandInfo : COMMAND_INFOS) {
<add> commandNames.add(new CommandName(commandInfo.getPrefix(), commandInfo.getSuffix()));
<add> }
<add> return commandNames.toArray(new CommandName[commandNames.size()]);
<add> }
<add>
<add> private static class CommandInfo {
<add> @NotNull private final String myPrefix;
<add> @NotNull private final String mySuffix;
<add> @NotNull private final Set<MappingMode> myMappingModes;
<add> private final boolean myRecursive;
<add>
<add> public CommandInfo(@NotNull String prefix, @NotNull String suffix, @NotNull Set<MappingMode> mappingModes,
<add> boolean recursive) {
<add>
<add> myPrefix = prefix;
<add> mySuffix = suffix;
<add> myMappingModes = mappingModes;
<add> myRecursive = recursive;
<add> }
<add>
<add> @NotNull
<add> public String getPrefix() {
<add> return myPrefix;
<add> }
<add>
<add> @NotNull
<add> public String getSuffix() {
<add> return mySuffix;
<add> }
<add>
<add> @NotNull
<add> public Set<MappingMode> getMappingModes() {
<add> return myMappingModes;
<add> }
<add>
<add> public boolean isRecursive() {
<add> return myRecursive;
<add> }
<add> }
<ide> } |
|
Java | apache-2.0 | 5d084aa3a461291f2b0481aa98d6ccec6fc275c7 | 0 | ppavlidis/Gemma,ppavlidis/Gemma,ppavlidis/Gemma,ppavlidis/Gemma,ppavlidis/Gemma,ppavlidis/Gemma,ppavlidis/Gemma | /*
* The Gemma project
*
* Copyright (c) 2006 University of British Columbia
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package ubic.gemma.web.controller.expression.experiment;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Map.Entry;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.parsers.ParserConfigurationException;
import org.apache.commons.lang.StringUtils;
import org.apache.tools.ant.filters.StringInputStream;
import org.springframework.validation.BindException;
import org.springframework.validation.ObjectError;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.RedirectView;
import org.xml.sax.SAXException;
import ubic.gemma.loader.entrez.pubmed.PubMedSearch;
import ubic.gemma.model.common.auditAndSecurity.AuditTrailService;
import ubic.gemma.model.common.auditAndSecurity.ContactService;
import ubic.gemma.model.common.auditAndSecurity.eventType.AuditEventType;
import ubic.gemma.model.common.auditAndSecurity.eventType.CommentedEvent;
import ubic.gemma.model.common.description.BibliographicReference;
import ubic.gemma.model.common.description.BibliographicReferenceService;
import ubic.gemma.model.common.description.DatabaseEntry;
import ubic.gemma.model.common.description.DatabaseType;
import ubic.gemma.model.common.description.ExternalDatabase;
import ubic.gemma.model.common.description.ExternalDatabaseService;
import ubic.gemma.model.common.quantitationtype.GeneralType;
import ubic.gemma.model.common.quantitationtype.PrimitiveType;
import ubic.gemma.model.common.quantitationtype.QuantitationType;
import ubic.gemma.model.common.quantitationtype.QuantitationTypeService;
import ubic.gemma.model.common.quantitationtype.ScaleType;
import ubic.gemma.model.common.quantitationtype.StandardQuantitationType;
import ubic.gemma.model.expression.bioAssay.BioAssay;
import ubic.gemma.model.expression.bioAssay.BioAssayService;
import ubic.gemma.model.expression.biomaterial.BioMaterial;
import ubic.gemma.model.expression.biomaterial.BioMaterialService;
import ubic.gemma.model.expression.experiment.ExpressionExperiment;
import ubic.gemma.model.expression.experiment.ExpressionExperimentService;
import ubic.gemma.persistence.PersisterHelper;
import ubic.gemma.web.controller.BaseFormController;
import antlr.RecognitionException;
import antlr.TokenStreamException;
import com.sdicons.json.model.JSONArray;
import com.sdicons.json.model.JSONInteger;
import com.sdicons.json.model.JSONObject;
import com.sdicons.json.model.JSONString;
import com.sdicons.json.model.JSONValue;
import com.sdicons.json.parser.JSONParser;
/**
* Handle editing of expression experiments.
*
* @author keshav
* @version $Id$
* @spring.bean id="expressionExperimentFormController"
* @spring.property name = "commandName" value="expressionExperiment"
* @spring.property name="commandClass"
* value="ubic.gemma.web.controller.expression.experiment.ExpressionExperimentEditCommand"
* @spring.property name = "formView" value="expressionExperiment.edit"
* @spring.property name = "successView" value="redirect:/expressionExperiment/showAllExpressionExperiments.html"
* @spring.property name = "expressionExperimentService" ref="expressionExperimentService"
* @spring.property name = "bioAssayService" ref="bioAssayService"
* @spring.property name = "bioMaterialService" ref="bioMaterialService"
* @spring.property name = "contactService" ref="contactService"
* @spring.property name = "externalDatabaseService" ref="externalDatabaseService"
* @spring.property name = "bibliographicReferenceService" ref="bibliographicReferenceService"
* @spring.property name = "persisterHelper" ref="persisterHelper"
* @spring.property name = "validator" ref="expressionExperimentValidator"
* @spring.property name = "quantitationTypeService" ref="quantitationTypeService"
* @spring.property name="auditTrailService" ref="auditTrailService"
*/
public class ExpressionExperimentFormController extends BaseFormController {
ExpressionExperimentService expressionExperimentService = null;
ContactService contactService = null;
BioAssayService bioAssayService = null;
BioMaterialService bioMaterialService = null;
BibliographicReferenceService bibliographicReferenceService = null;
PersisterHelper persisterHelper = null;
QuantitationTypeService quantitationTypeService;
AuditTrailService auditTrailService;
/**
* @param auditTrailService the auditTrailService to set
*/
public void setAuditTrailService( AuditTrailService auditTrailService ) {
this.auditTrailService = auditTrailService;
}
private ExternalDatabaseService externalDatabaseService = null;
public void setExternalDatabaseService( ExternalDatabaseService externalDatabaseService ) {
this.externalDatabaseService = externalDatabaseService;
}
/**
* @param persisterHelper the persisterHelper to set
*/
public void setPersisterHelper( PersisterHelper persisterHelper ) {
this.persisterHelper = persisterHelper;
}
/**
* @param bibliographicReferenceService the bibliographicReferenceService to set
*/
public void setBibliographicReferenceService( BibliographicReferenceService bibliographicReferenceService ) {
this.bibliographicReferenceService = bibliographicReferenceService;
}
public ExpressionExperimentFormController() {
/*
* if true, reuses the same command object across the edit-submit-process (get-post-process).
*/
setSessionForm( true );
setCommandClass( ExpressionExperiment.class );
}
/**
* @param request
* @return Object
* @throws ServletException
*/
@Override
protected Object formBackingObject( HttpServletRequest request ) {
Long id = null;
try {
id = Long.parseLong( request.getParameter( "id" ) );
} catch ( NumberFormatException e ) {
saveMessage( request, "Id was not a number " + id );
throw new IllegalArgumentException( "Id was not a number " + id );
}
ExpressionExperiment ee = ExpressionExperiment.Factory.newInstance();
List<QuantitationType> qts = new ArrayList<QuantitationType>();
log.debug( id );
ExpressionExperimentEditCommand obj;
if ( id != null ) {
ee = expressionExperimentService.load( id );
qts.addAll( expressionExperimentService.getQuantitationTypes( ee ) );
obj = new ExpressionExperimentEditCommand( ee, qts );
} else {
obj = new ExpressionExperimentEditCommand( ee, qts );
}
if ( ee.getId() != null ) {
this.saveMessage( request, "Editing dataset" );
}
return obj;
}
/**
* @param request
* @param response
* @param command
* @param errors
* @return ModelAndView
* @throws Exception
*/
@Override
public ModelAndView processFormSubmission( HttpServletRequest request, HttpServletResponse response,
Object command, BindException errors ) throws Exception {
log.debug( "entering processFormSubmission" );
Long id = ( ( ExpressionExperimentEditCommand ) command ).getId();
if ( request.getParameter( "cancel" ) != null ) {
if ( id != null ) {
return new ModelAndView( new RedirectView( "http://" + request.getServerName() + ":"
+ request.getServerPort() + request.getContextPath()
+ "/expressionExperiment/showExpressionExperiment.html?id=" + id ) );
}
log.warn( "Cannot find details view due to null id. Redirecting to overview" );
return new ModelAndView( new RedirectView( "http://" + request.getServerName() + ":"
+ request.getServerPort() + request.getContextPath()
+ "/expressionExperiment/showAllExpressionExperiments.html" ) );
}
ModelAndView mav = super.processFormSubmission( request, response, command, errors );
Set<Entry<QuantitationType, Long>> s = expressionExperimentService.getQuantitationTypeCountById( id )
.entrySet();
mav.addObject( "qtCountSet", s );
// add count of designElementDataVectors
mav.addObject( "designElementDataVectorCount", new Long( expressionExperimentService
.getDesignElementDataVectorCountById( id ) ) );
return mav;
}
/**
* @param request
* @param response
* @param command
* @param errors
* @return ModelAndView
* @throws Exception
*/
@Override
public ModelAndView onSubmit( HttpServletRequest request, HttpServletResponse response, Object command,
BindException errors ) throws Exception {
log.debug( "entering onSubmit" );
ExpressionExperimentEditCommand eeCommand = ( ExpressionExperimentEditCommand ) command;
if ( eeCommand == null || eeCommand.getId() == null ) {
errors.addError( new ObjectError( command.toString(), null, null,
"Expression experiment was null or had null id" ) );
return processFormSubmission( request, response, command, errors );
}
ExpressionExperiment expressionExperiment = eeCommand.toExpressionExperiment();
// create bibliographicReference if necessary
updatePubMed( request, expressionExperiment );
/**
* Takes care of the basics.
*/
expressionExperimentService.update( expressionExperiment );
/**
* Much more complicated
*/
updateQuantTypes( request, expressionExperiment, eeCommand.getQuantitationTypes() );
updateBioMaterialMap( request, expressionExperiment );
updateAccession( request, expressionExperiment );
// saveMessage( request, "object.saved", new Object[] { expressionExperiment.getClass().getSimpleName(),
// expressionExperiment.getId() }, "Saved" );
return new ModelAndView( new RedirectView( "http://" + request.getServerName() + ":" + request.getServerPort()
+ request.getContextPath() + "/expressionExperiment/showExpressionExperiment.html?id="
+ eeCommand.getId() ) );
}
/**
* @param arrayDesign
*/
private void audit( ExpressionExperiment ee, AuditEventType eventType, String note ) {
auditTrailService.addUpdateEvent( ee, eventType, note );
}
/**
* @param request
* @param expressionExperiment
*/
private void updateAccession( HttpServletRequest request, ExpressionExperiment expressionExperiment ) {
String accession = request.getParameter( "expressionExperiment.accession.accession" );
if ( accession == null ) {
// do nothing
} else if ( expressionExperiment.getAccession() != null ) {
/* database entry */
expressionExperiment.getAccession().setAccession( accession );
/* external database */
ExternalDatabase ed = ( expressionExperiment.getAccession().getExternalDatabase() );
ed = externalDatabaseService.findOrCreate( ed );
expressionExperiment.getAccession().setExternalDatabase( ed );
}
}
/**
* Change the relationship between bioassays and biomaterials.
*
* @param request
* @param expressionExperiment
*/
private void updateBioMaterialMap( HttpServletRequest request, ExpressionExperiment expressionExperiment ) {
// parse JSON-serialized map
String jsonSerialization = request.getParameter( "assayToMaterialMap" );
// convert back to a map
JSONParser parser = new JSONParser( new StringInputStream( jsonSerialization ) );
Map<String, JSONValue> bioAssayMap = null;
try {
bioAssayMap = ( ( JSONObject ) parser.nextValue() ).getValue();
} catch ( TokenStreamException e ) {
throw new RuntimeException( e );
} catch ( RecognitionException e ) {
throw new RuntimeException( e );
}
Map<BioAssay, BioMaterial> deleteAssociations = new HashMap<BioAssay, BioMaterial>();
// set the bioMaterial - bioAssay associations if they are different
Set<Entry<String, JSONValue>> bioAssays = bioAssayMap.entrySet();
for ( Entry<String, JSONValue> entry : bioAssays ) {
// check if the bioAssayId is a nullElement
// if it is, skip over this entry
if ( entry.getKey().equalsIgnoreCase( "nullElement" ) ) {
continue;
}
Long bioAssayId = Long.parseLong( entry.getKey() );
Collection<JSONValue> bioMaterialValues = ( ( JSONArray ) entry.getValue() ).getValue();
Collection<Long> newBioMaterials = new ArrayList<Long>();
for ( JSONValue value : bioMaterialValues ) {
if ( value.isString() ) {
Long newMaterial = Long.parseLong( ( ( JSONString ) value ).getValue() );
newBioMaterials.add( newMaterial );
} else {
Long newMaterial = ( ( JSONInteger ) value ).getValue().longValue();
newBioMaterials.add( newMaterial );
}
}
BioAssay bioAssay = bioAssayService.load( bioAssayId );
Collection<BioMaterial> bMats = bioAssay.getSamplesUsed();
Collection<Long> oldBioMaterials = new ArrayList<Long>();
for ( BioMaterial material : bMats ) {
oldBioMaterials.add( material.getId() );
}
// try to find the bioMaterials in the list of current samples
// if it is not in the current samples, add it
// if it is in the current sample list, skip to next entry
// if the current sample does not exist in the new bioMaterial list, remove it
for ( Long newBioMaterialId : newBioMaterials ) {
if ( oldBioMaterials.contains( newBioMaterialId ) ) {
continue;
}
BioMaterial newMaterial;
if ( newBioMaterialId < 0 ) { // This kludge signifies that it is a 'brand new' biomaterial.
// model the new biomaterial after the old one for the bioassay (we're taking a guess here.)
if ( bMats.size() > 1 ) {
// log.warn("");
}
BioMaterial oldBioMaterial = bMats.iterator().next();
newMaterial = bioMaterialService.copy( oldBioMaterial );
newMaterial.setName( "Modeled after " + oldBioMaterial.getName() );
newMaterial = ( BioMaterial ) persisterHelper.persist( newMaterial );
} else {
newMaterial = bioMaterialService.load( newBioMaterialId );
}
bioAssayService.addBioMaterialAssociation( bioAssay, newMaterial );
}
// put all unnecessary associations in a collection
// they are not deleted immediately to let all new associations be added first
// before any deletions are made. This makes sure that
// no bioMaterials are removed unnecessarily
for ( Long oldBioMaterialId : oldBioMaterials ) {
if ( newBioMaterials.contains( oldBioMaterialId ) ) {
continue;
}
BioMaterial oldMaterial = bioMaterialService.load( oldBioMaterialId );
deleteAssociations.put( bioAssay, oldMaterial );
}
}
// remove unnecessary biomaterial associations
Collection<BioAssay> deleteKeys = deleteAssociations.keySet();
for ( BioAssay assay : deleteKeys ) {
bioAssayService.removeBioMaterialAssociation( assay, deleteAssociations.get( assay ) );
}
/*
* TODO: make this a separate event class, so we can flag experiments that need to be reanalyzed after doing this.
*/
audit( expressionExperiment, CommentedEvent.Factory.newInstance(), "Updated biomaterial -> bioassay map" );
}
/**
* Check old vs. new quantitation types, and update any affected data vectors.
*
* @param request
* @param expressionExperiment
* @param updatedQuantitationTypes
*/
private void updateQuantTypes( HttpServletRequest request, ExpressionExperiment expressionExperiment,
Collection<QuantitationType> updatedQuantitationTypes ) {
Collection<QuantitationType> oldQuantitationTypes = expressionExperimentService
.getQuantitationTypes( expressionExperiment );
for ( QuantitationType qType : oldQuantitationTypes ) {
assert qType != null;
Long id = qType.getId();
boolean dirty = false;
QuantitationType revisedType = QuantitationType.Factory.newInstance();
for ( QuantitationType newQtype : updatedQuantitationTypes ) {
if ( newQtype.getId().equals( id ) ) {
String oldName = qType.getName();
String oldDescription = qType.getDescription();
GeneralType gentype = qType.getGeneralType();
boolean isBkg = qType.getIsBackground();
boolean isBkgSub = qType.getIsBackgroundSubtracted();
boolean isNormalized = qType.getIsNormalized();
PrimitiveType rep = qType.getRepresentation();
ScaleType scale = qType.getScale();
StandardQuantitationType type = qType.getType();
boolean isPreferred = qType.getIsPreferred();
boolean isMaskedPreferred = qType.getIsMaskedPreferred();
boolean isRatio = qType.getIsRatio();
String newName = newQtype.getName();
String newDescription = newQtype.getDescription();
GeneralType newgentype = newQtype.getGeneralType();
boolean newisBkg = newQtype.getIsBackground();
boolean newisBkgSub = newQtype.getIsBackgroundSubtracted();
boolean newisNormalized = newQtype.getIsNormalized();
PrimitiveType newrep = newQtype.getRepresentation();
ScaleType newscale = newQtype.getScale();
StandardQuantitationType newType = newQtype.getType();
boolean newisPreferred = newQtype.getIsPreferred();
boolean newIsmaskedPreferred = newQtype.getIsMaskedPreferred();
boolean newisRatio = newQtype.getIsRatio();
// make it a copy.
revisedType.setIsBackgroundSubtracted( newisBkgSub );
revisedType.setIsBackground( newisBkg );
revisedType.setIsPreferred( newisPreferred );
revisedType.setIsMaskedPreferred( newIsmaskedPreferred );
revisedType.setIsRatio( newisRatio );
revisedType.setRepresentation( newrep );
revisedType.setType( newType );
revisedType.setScale( newscale );
revisedType.setGeneralType( newgentype );
revisedType.setDescription( newDescription );
revisedType.setName( newName );
revisedType.setIsNormalized( newisNormalized );
qType.setIsBackgroundSubtracted( newisBkgSub );
qType.setIsBackground( newisBkg );
qType.setIsPreferred( newisPreferred );
qType.setIsMaskedPreferred( newIsmaskedPreferred );
qType.setIsRatio( newisRatio );
qType.setRepresentation( newrep );
qType.setType( newType );
qType.setScale( newscale );
qType.setGeneralType( newgentype );
qType.setDescription( newDescription );
qType.setName( newName );
qType.setIsNormalized( newisNormalized );
if ( newName != null && ( oldName == null || !oldName.equals( newName ) ) ) {
dirty = true;
}
if ( newDescription != null
&& ( oldDescription == null || !oldDescription.equals( newDescription ) ) ) {
dirty = true;
}
if ( !gentype.equals( newgentype ) ) {
dirty = true;
}
if ( !scale.equals( newscale ) ) {
dirty = true;
}
if ( !type.equals( newType ) ) {
dirty = true;
}
if ( !rep.equals( newrep ) ) {
dirty = true;
}
if ( isPreferred != newisPreferred ) {
// special case - make sure there is only one preferred per platform?
dirty = true;
}
if ( isMaskedPreferred != newIsmaskedPreferred ) {
// special case - make sure there is only one preferred per platform?
dirty = true;
}
if ( isBkg != newisBkg ) {
dirty = true;
}
if ( isBkgSub != newisBkgSub ) {
dirty = true;
}
if ( isNormalized != newisNormalized ) {
dirty = true;
}
if ( isRatio != newisRatio ) {
dirty = true;
}
break;
}
}
if ( dirty ) {
// update the quantitation type
quantitationTypeService.update( qType );
}
}
}
/**
* @param request
* @param command
* @throws IOException
* @throws SAXException
* @throws ParserConfigurationException
*/
private void updatePubMed( HttpServletRequest request, ExpressionExperiment command ) throws IOException,
SAXException, ParserConfigurationException {
String pubMedId = request.getParameter( "expressionExperiment.PubMedId" );
if ( StringUtils.isBlank( pubMedId ) ) {
return;
}
// first, search for the pubMedId in the database
// if it is in the database, then just point the EE to that
// if it doesn't, then grab the BibliographicReference from PubMed and persist. Then point EE to the new
// entry.
BibliographicReference publication = bibliographicReferenceService.findByExternalId( pubMedId );
if ( publication != null ) {
command.setPrimaryPublication( publication );
} else {
// search for pubmedId
PubMedSearch pms = new PubMedSearch();
Collection<String> searchTerms = new ArrayList<String>();
searchTerms.add( pubMedId );
Collection<BibliographicReference> publications = pms.searchAndRetrieveIdByHTTP( searchTerms );
// check to see if there are publications found
// if there are none, or more than one, add an error message and do nothing
if ( publications.size() == 0 ) {
this.saveMessage( request, "Cannot find PubMed ID " + pubMedId );
} else if ( publications.size() > 1 ) {
this.saveMessage( request, "PubMed ID " + pubMedId + "" );
} else {
publication = publications.iterator().next();
DatabaseEntry pubAccession = DatabaseEntry.Factory.newInstance();
pubAccession.setAccession( pubMedId );
ExternalDatabase ed = ExternalDatabase.Factory.newInstance();
ed.setName( "PubMed" );
pubAccession.setExternalDatabase( ed );
publication.setPubAccession( pubAccession );
// persist new publication
publication = ( BibliographicReference ) persisterHelper.persist( publication );
// publication = bibliographicReferenceService.findOrCreate( publication );
// assign to expressionExperiment
command.setPrimaryPublication( publication );
}
}
}
/**
* @param request
* @return Map
*/
@SuppressWarnings("unchecked")
@Override
protected Map referenceData( HttpServletRequest request ) {
Map<Object, Object> referenceData = new HashMap<Object, Object>();
Collection<ExternalDatabase> edCol = externalDatabaseService.loadAll();
Collection<ExternalDatabase> keepers = new HashSet<ExternalDatabase>();
for ( ExternalDatabase database : edCol ) {
if ( database.getType() == null ) continue;
if ( database.getType().equals( DatabaseType.EXPRESSION ) ) {
keepers.add( database );
}
}
referenceData.put( "externalDatabases", keepers );
referenceData.put( "standardQuantitationTypes", new ArrayList<String>( StandardQuantitationType.literals() ) );
referenceData.put( "scaleTypes", new ArrayList<String>( ScaleType.literals() ) );
referenceData.put( "generalQuantitationTypes", new ArrayList<String>( GeneralType.literals() ) );
referenceData.put( "representations", new ArrayList<String>( PrimitiveType.literals() ) );
return referenceData;
}
/**
* @param expressionExperimentService
*/
public void setExpressionExperimentService( ExpressionExperimentService expressionExperimentService ) {
this.expressionExperimentService = expressionExperimentService;
}
/**
* @param contactService
*/
public void setContactService( ContactService contactService ) {
this.contactService = contactService;
}
/**
* @param bioAssayService the bioAssayService to set
*/
public void setBioAssayService( BioAssayService bioAssayService ) {
this.bioAssayService = bioAssayService;
}
/**
* @param bioMaterialService the bioMaterialService to set
*/
public void setBioMaterialService( BioMaterialService bioMaterialService ) {
this.bioMaterialService = bioMaterialService;
}
public void setQuantitationTypeService( QuantitationTypeService quantitationTypeService ) {
this.quantitationTypeService = quantitationTypeService;
}
}
| gemma-web/src/main/java/ubic/gemma/web/controller/expression/experiment/ExpressionExperimentFormController.java | /*
* The Gemma project
*
* Copyright (c) 2006 University of British Columbia
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package ubic.gemma.web.controller.expression.experiment;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Map.Entry;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.parsers.ParserConfigurationException;
import org.apache.commons.lang.StringUtils;
import org.apache.tools.ant.filters.StringInputStream;
import org.springframework.validation.BindException;
import org.springframework.validation.ObjectError;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.RedirectView;
import org.xml.sax.SAXException;
import ubic.gemma.loader.entrez.pubmed.PubMedSearch;
import ubic.gemma.model.common.auditAndSecurity.ContactService;
import ubic.gemma.model.common.description.BibliographicReference;
import ubic.gemma.model.common.description.BibliographicReferenceService;
import ubic.gemma.model.common.description.DatabaseEntry;
import ubic.gemma.model.common.description.DatabaseType;
import ubic.gemma.model.common.description.ExternalDatabase;
import ubic.gemma.model.common.description.ExternalDatabaseService;
import ubic.gemma.model.common.quantitationtype.GeneralType;
import ubic.gemma.model.common.quantitationtype.PrimitiveType;
import ubic.gemma.model.common.quantitationtype.QuantitationType;
import ubic.gemma.model.common.quantitationtype.QuantitationTypeService;
import ubic.gemma.model.common.quantitationtype.ScaleType;
import ubic.gemma.model.common.quantitationtype.StandardQuantitationType;
import ubic.gemma.model.expression.bioAssay.BioAssay;
import ubic.gemma.model.expression.bioAssay.BioAssayService;
import ubic.gemma.model.expression.biomaterial.BioMaterial;
import ubic.gemma.model.expression.biomaterial.BioMaterialService;
import ubic.gemma.model.expression.experiment.ExpressionExperiment;
import ubic.gemma.model.expression.experiment.ExpressionExperimentService;
import ubic.gemma.persistence.PersisterHelper;
import ubic.gemma.web.controller.BaseFormController;
import antlr.RecognitionException;
import antlr.TokenStreamException;
import com.sdicons.json.model.JSONArray;
import com.sdicons.json.model.JSONInteger;
import com.sdicons.json.model.JSONObject;
import com.sdicons.json.model.JSONString;
import com.sdicons.json.model.JSONValue;
import com.sdicons.json.parser.JSONParser;
/**
* Handle editing of expression experiments.
*
* @author keshav
* @version $Id$
* @spring.bean id="expressionExperimentFormController"
* @spring.property name = "commandName" value="expressionExperiment"
* @spring.property name="commandClass"
* value="ubic.gemma.web.controller.expression.experiment.ExpressionExperimentEditCommand"
* @spring.property name = "formView" value="expressionExperiment.edit"
* @spring.property name = "successView" value="redirect:/expressionExperiment/showAllExpressionExperiments.html"
* @spring.property name = "expressionExperimentService" ref="expressionExperimentService"
* @spring.property name = "bioAssayService" ref="bioAssayService"
* @spring.property name = "bioMaterialService" ref="bioMaterialService"
* @spring.property name = "contactService" ref="contactService"
* @spring.property name = "externalDatabaseService" ref="externalDatabaseService"
* @spring.property name = "bibliographicReferenceService" ref="bibliographicReferenceService"
* @spring.property name = "persisterHelper" ref="persisterHelper"
* @spring.property name = "validator" ref="expressionExperimentValidator"
* @spring.property name = "quantitationTypeService" ref="quantitationTypeService"
*/
public class ExpressionExperimentFormController extends BaseFormController {
ExpressionExperimentService expressionExperimentService = null;
ContactService contactService = null;
BioAssayService bioAssayService = null;
BioMaterialService bioMaterialService = null;
BibliographicReferenceService bibliographicReferenceService = null;
PersisterHelper persisterHelper = null;
QuantitationTypeService quantitationTypeService;
private ExternalDatabaseService externalDatabaseService = null;
public void setExternalDatabaseService( ExternalDatabaseService externalDatabaseService ) {
this.externalDatabaseService = externalDatabaseService;
}
/**
* @param persisterHelper the persisterHelper to set
*/
public void setPersisterHelper( PersisterHelper persisterHelper ) {
this.persisterHelper = persisterHelper;
}
/**
* @param bibliographicReferenceService the bibliographicReferenceService to set
*/
public void setBibliographicReferenceService( BibliographicReferenceService bibliographicReferenceService ) {
this.bibliographicReferenceService = bibliographicReferenceService;
}
public ExpressionExperimentFormController() {
/*
* if true, reuses the same command object across the edit-submit-process (get-post-process).
*/
setSessionForm( true );
setCommandClass( ExpressionExperiment.class );
}
/**
* @param request
* @return Object
* @throws ServletException
*/
@Override
protected Object formBackingObject( HttpServletRequest request ) {
Long id = null;
try {
id = Long.parseLong( request.getParameter( "id" ) );
} catch ( NumberFormatException e ) {
saveMessage( request, "Id was not a number " + id );
throw new IllegalArgumentException( "Id was not a number " + id );
}
ExpressionExperiment ee = ExpressionExperiment.Factory.newInstance();
List<QuantitationType> qts = new ArrayList<QuantitationType>();
log.debug( id );
ExpressionExperimentEditCommand obj;
if ( id != null ) {
ee = expressionExperimentService.load( id );
qts.addAll( expressionExperimentService.getQuantitationTypes( ee ) );
obj = new ExpressionExperimentEditCommand( ee, qts );
} else {
obj = new ExpressionExperimentEditCommand( ee, qts );
}
if ( ee.getId() != null ) {
this.saveMessage( request, "Editing dataset" );
}
return obj;
}
/**
* @param request
* @param response
* @param command
* @param errors
* @return ModelAndView
* @throws Exception
*/
@Override
public ModelAndView processFormSubmission( HttpServletRequest request, HttpServletResponse response,
Object command, BindException errors ) throws Exception {
log.debug( "entering processFormSubmission" );
Long id = ( ( ExpressionExperimentEditCommand ) command ).getId();
if ( request.getParameter( "cancel" ) != null ) {
if ( id != null ) {
return new ModelAndView( new RedirectView( "http://" + request.getServerName() + ":"
+ request.getServerPort() + request.getContextPath()
+ "/expressionExperiment/showExpressionExperiment.html?id=" + id ) );
}
log.warn( "Cannot find details view due to null id. Redirecting to overview" );
return new ModelAndView( new RedirectView( "http://" + request.getServerName() + ":"
+ request.getServerPort() + request.getContextPath()
+ "/expressionExperiment/showAllExpressionExperiments.html" ) );
}
ModelAndView mav = super.processFormSubmission( request, response, command, errors );
Set<Entry<QuantitationType, Long>> s = expressionExperimentService.getQuantitationTypeCountById( id )
.entrySet();
mav.addObject( "qtCountSet", s );
// add count of designElementDataVectors
mav.addObject( "designElementDataVectorCount", new Long( expressionExperimentService
.getDesignElementDataVectorCountById( id ) ) );
return mav;
}
/**
* @param request
* @param response
* @param command
* @param errors
* @return ModelAndView
* @throws Exception
*/
@Override
public ModelAndView onSubmit( HttpServletRequest request, HttpServletResponse response, Object command,
BindException errors ) throws Exception {
log.debug( "entering onSubmit" );
ExpressionExperimentEditCommand eeCommand = ( ExpressionExperimentEditCommand ) command;
if ( eeCommand == null || eeCommand.getId() == null ) {
errors.addError( new ObjectError( command.toString(), null, null,
"Expression experiment was null or had null id" ) );
return processFormSubmission( request, response, command, errors );
}
ExpressionExperiment expressionExperiment = eeCommand.toExpressionExperiment();
// create bibliographicReference if necessary
updatePubMed( request, expressionExperiment );
/**
* Takes care of the basics.
*/
expressionExperimentService.update( expressionExperiment );
/**
* Much more complicated
*/
updateQuantTypes( request, expressionExperiment, eeCommand.getQuantitationTypes() );
updateBioMaterialMap( request );
updateAccession( request, expressionExperiment );
// saveMessage( request, "object.saved", new Object[] { expressionExperiment.getClass().getSimpleName(),
// expressionExperiment.getId() }, "Saved" );
return new ModelAndView( new RedirectView( "http://" + request.getServerName() + ":" + request.getServerPort()
+ request.getContextPath() + "/expressionExperiment/showExpressionExperiment.html?id="
+ eeCommand.getId() ) );
}
/**
* @param request
* @param expressionExperiment
*/
private void updateAccession( HttpServletRequest request, ExpressionExperiment expressionExperiment ) {
String accession = request.getParameter( "expressionExperiment.accession.accession" );
if ( accession == null ) {
// do nothing
} else if ( expressionExperiment.getAccession() != null ) {
/* database entry */
expressionExperiment.getAccession().setAccession( accession );
/* external database */
ExternalDatabase ed = ( expressionExperiment.getAccession().getExternalDatabase() );
ed = externalDatabaseService.findOrCreate( ed );
expressionExperiment.getAccession().setExternalDatabase( ed );
}
}
/**
* @param request
* @throws TokenStreamException
* @throws RecognitionException
*/
private void updateBioMaterialMap( HttpServletRequest request ) {
// parse JSON-serialized map
String jsonSerialization = request.getParameter( "assayToMaterialMap" );
// convert back to a map
JSONParser parser = new JSONParser( new StringInputStream( jsonSerialization ) );
Map<String, JSONValue> bioAssayMap = null;
try {
bioAssayMap = ( ( JSONObject ) parser.nextValue() ).getValue();
} catch ( TokenStreamException e ) {
throw new RuntimeException( e );
} catch ( RecognitionException e ) {
throw new RuntimeException( e );
}
Map<BioAssay, BioMaterial> deleteAssociations = new HashMap<BioAssay, BioMaterial>();
// set the bioMaterial - bioAssay associations if they are different
Set<Entry<String, JSONValue>> bioAssays = bioAssayMap.entrySet();
for ( Entry<String, JSONValue> entry : bioAssays ) {
// check if the bioAssayId is a nullElement
// if it is, skip over this entry
if ( entry.getKey().equalsIgnoreCase( "nullElement" ) ) {
continue;
}
Long bioAssayId = Long.parseLong( entry.getKey() );
Collection<JSONValue> bioMaterialValues = ( ( JSONArray ) entry.getValue() ).getValue();
Collection<Long> newBioMaterials = new ArrayList<Long>();
for ( JSONValue value : bioMaterialValues ) {
if ( value.isString() ) {
Long newMaterial = Long.parseLong( ( ( JSONString ) value ).getValue() );
newBioMaterials.add( newMaterial );
} else {
Long newMaterial = ( ( JSONInteger ) value ).getValue().longValue();
newBioMaterials.add( newMaterial );
}
}
BioAssay bioAssay = bioAssayService.load( bioAssayId );
Collection<BioMaterial> bMats = bioAssay.getSamplesUsed();
Collection<Long> oldBioMaterials = new ArrayList<Long>();
for ( BioMaterial material : bMats ) {
oldBioMaterials.add( material.getId() );
}
// try to find the bioMaterials in the list of current samples
// if it is not in the current samples, add it
// if it is in the current sample list, skip to next entry
// if the current sample does not exist in the new bioMaterial list, remove it
for ( Long newBioMaterialId : newBioMaterials ) {
if ( oldBioMaterials.contains( newBioMaterialId ) ) {
continue;
}
BioMaterial newMaterial;
if ( newBioMaterialId < 0 ) { // This kludge signifies that it is a 'brand new' biomaterial.
// model the new biomaterial after the old one for the bioassay (we're taking a guess here.)
if ( bMats.size() > 1 ) {
// log.warn("");
}
BioMaterial oldBioMaterial = bMats.iterator().next();
// newMaterial = BioMaterial.Factory.newInstance();
newMaterial = bioMaterialService.copy( oldBioMaterial );
// newMaterial.setDescription( oldBioMaterial.getDescription() + " [Created by Gemma]" );
// newMaterial.setMaterialType( oldBioMaterial.getMaterialType() );
// newMaterial.setCharacteristics( oldBioMaterial.getCharacteristics() );
// newMaterial.setTreatments( oldBioMaterial.getTreatments() );
// newMaterial.setSourceTaxon( oldBioMaterial.getSourceTaxon() );
// newMaterial.setFactorValues( oldBioMaterial.getFactorValues() );
newMaterial.setName( "Modeled after " + oldBioMaterial.getName() );
newMaterial = ( BioMaterial ) persisterHelper.persist( newMaterial );
} else {
newMaterial = bioMaterialService.load( newBioMaterialId );
}
bioAssayService.addBioMaterialAssociation( bioAssay, newMaterial );
}
// put all unnecessary associations in a collection
// they are not deleted immediately to let all new associations be added first
// before any deletions are made. This makes sure that
// no bioMaterials are removed unnecessarily
for ( Long oldBioMaterialId : oldBioMaterials ) {
if ( newBioMaterials.contains( oldBioMaterialId ) ) {
continue;
}
BioMaterial oldMaterial = bioMaterialService.load( oldBioMaterialId );
deleteAssociations.put( bioAssay, oldMaterial );
}
}
// remove unnecessary biomaterial associations
Collection<BioAssay> deleteKeys = deleteAssociations.keySet();
for ( BioAssay assay : deleteKeys ) {
bioAssayService.removeBioMaterialAssociation( assay, deleteAssociations.get( assay ) );
}
}
/**
* Check old vs. new quantitation types, and update any affected data vectors.
*
* @param request
* @param expressionExperiment
* @param updatedQuantitationTypes
*/
private void updateQuantTypes( HttpServletRequest request, ExpressionExperiment expressionExperiment,
Collection<QuantitationType> updatedQuantitationTypes ) {
Collection<QuantitationType> oldQuantitationTypes = expressionExperimentService
.getQuantitationTypes( expressionExperiment );
for ( QuantitationType qType : oldQuantitationTypes ) {
assert qType != null;
Long id = qType.getId();
boolean dirty = false;
QuantitationType revisedType = QuantitationType.Factory.newInstance();
for ( QuantitationType newQtype : updatedQuantitationTypes ) {
if ( newQtype.getId().equals( id ) ) {
String oldName = qType.getName();
String oldDescription = qType.getDescription();
GeneralType gentype = qType.getGeneralType();
boolean isBkg = qType.getIsBackground();
boolean isBkgSub = qType.getIsBackgroundSubtracted();
boolean isNormalized = qType.getIsNormalized();
PrimitiveType rep = qType.getRepresentation();
ScaleType scale = qType.getScale();
StandardQuantitationType type = qType.getType();
boolean isPreferred = qType.getIsPreferred();
boolean isMaskedPreferred = qType.getIsMaskedPreferred();
boolean isRatio = qType.getIsRatio();
String newName = newQtype.getName();
String newDescription = newQtype.getDescription();
GeneralType newgentype = newQtype.getGeneralType();
boolean newisBkg = newQtype.getIsBackground();
boolean newisBkgSub = newQtype.getIsBackgroundSubtracted();
boolean newisNormalized = newQtype.getIsNormalized();
PrimitiveType newrep = newQtype.getRepresentation();
ScaleType newscale = newQtype.getScale();
StandardQuantitationType newType = newQtype.getType();
boolean newisPreferred = newQtype.getIsPreferred();
boolean newIsmaskedPreferred = newQtype.getIsMaskedPreferred();
boolean newisRatio = newQtype.getIsRatio();
// make it a copy.
revisedType.setIsBackgroundSubtracted( newisBkgSub );
revisedType.setIsBackground( newisBkg );
revisedType.setIsPreferred( newisPreferred );
revisedType.setIsMaskedPreferred( newIsmaskedPreferred );
revisedType.setIsRatio( newisRatio );
revisedType.setRepresentation( newrep );
revisedType.setType( newType );
revisedType.setScale( newscale );
revisedType.setGeneralType( newgentype );
revisedType.setDescription( newDescription );
revisedType.setName( newName );
revisedType.setIsNormalized( newisNormalized );
qType.setIsBackgroundSubtracted( newisBkgSub );
qType.setIsBackground( newisBkg );
qType.setIsPreferred( newisPreferred );
qType.setIsMaskedPreferred( newIsmaskedPreferred );
qType.setIsRatio( newisRatio );
qType.setRepresentation( newrep );
qType.setType( newType );
qType.setScale( newscale );
qType.setGeneralType( newgentype );
qType.setDescription( newDescription );
qType.setName( newName );
qType.setIsNormalized( newisNormalized );
if ( newName != null && ( oldName == null || !oldName.equals( newName ) ) ) {
dirty = true;
}
if ( newDescription != null
&& ( oldDescription == null || !oldDescription.equals( newDescription ) ) ) {
dirty = true;
}
if ( !gentype.equals( newgentype ) ) {
dirty = true;
}
if ( !scale.equals( newscale ) ) {
dirty = true;
}
if ( !type.equals( newType ) ) {
dirty = true;
}
if ( !rep.equals( newrep ) ) {
dirty = true;
}
if ( isPreferred != newisPreferred ) {
// special case - make sure there is only one preferred per platform?
dirty = true;
}
if ( isMaskedPreferred != newIsmaskedPreferred ) {
// special case - make sure there is only one preferred per platform?
dirty = true;
}
if ( isBkg != newisBkg ) {
dirty = true;
}
if ( isBkgSub != newisBkgSub ) {
dirty = true;
}
if ( isNormalized != newisNormalized ) {
dirty = true;
}
if ( isRatio != newisRatio ) {
dirty = true;
}
break;
}
}
if ( dirty ) {
// update the quantitation type
quantitationTypeService.update( qType );
}
}
}
/**
* @param request
* @param command
* @throws IOException
* @throws SAXException
* @throws ParserConfigurationException
*/
private void updatePubMed( HttpServletRequest request, ExpressionExperiment command ) throws IOException,
SAXException, ParserConfigurationException {
String pubMedId = request.getParameter( "expressionExperiment.PubMedId" );
if ( StringUtils.isBlank( pubMedId ) ) {
return;
}
// first, search for the pubMedId in the database
// if it is in the database, then just point the EE to that
// if it doesn't, then grab the BibliographicReference from PubMed and persist. Then point EE to the new
// entry.
BibliographicReference publication = bibliographicReferenceService.findByExternalId( pubMedId );
if ( publication != null ) {
command.setPrimaryPublication( publication );
} else {
// search for pubmedId
PubMedSearch pms = new PubMedSearch();
Collection<String> searchTerms = new ArrayList<String>();
searchTerms.add( pubMedId );
Collection<BibliographicReference> publications = pms.searchAndRetrieveIdByHTTP( searchTerms );
// check to see if there are publications found
// if there are none, or more than one, add an error message and do nothing
if ( publications.size() == 0 ) {
this.saveMessage( request, "Cannot find PubMed ID " + pubMedId );
} else if ( publications.size() > 1 ) {
this.saveMessage( request, "PubMed ID " + pubMedId + "" );
} else {
publication = publications.iterator().next();
DatabaseEntry pubAccession = DatabaseEntry.Factory.newInstance();
pubAccession.setAccession( pubMedId );
ExternalDatabase ed = ExternalDatabase.Factory.newInstance();
ed.setName( "PubMed" );
pubAccession.setExternalDatabase( ed );
publication.setPubAccession( pubAccession );
// persist new publication
publication = ( BibliographicReference ) persisterHelper.persist( publication );
// publication = bibliographicReferenceService.findOrCreate( publication );
// assign to expressionExperiment
command.setPrimaryPublication( publication );
}
}
}
/**
* @param request
* @return Map
*/
@SuppressWarnings("unchecked")
@Override
protected Map referenceData( HttpServletRequest request ) {
Map<Object, Object> referenceData = new HashMap<Object, Object>();
Collection<ExternalDatabase> edCol = externalDatabaseService.loadAll();
Collection<ExternalDatabase> keepers = new HashSet<ExternalDatabase>();
for ( ExternalDatabase database : edCol ) {
if ( database.getType() == null ) continue;
if ( database.getType().equals( DatabaseType.EXPRESSION ) ) {
keepers.add( database );
}
}
referenceData.put( "externalDatabases", keepers );
referenceData.put( "standardQuantitationTypes", new ArrayList<String>( StandardQuantitationType.literals() ) );
referenceData.put( "scaleTypes", new ArrayList<String>( ScaleType.literals() ) );
referenceData.put( "generalQuantitationTypes", new ArrayList<String>( GeneralType.literals() ) );
referenceData.put( "representations", new ArrayList<String>( PrimitiveType.literals() ) );
return referenceData;
}
/**
* @param expressionExperimentService
*/
public void setExpressionExperimentService( ExpressionExperimentService expressionExperimentService ) {
this.expressionExperimentService = expressionExperimentService;
}
/**
* @param contactService
*/
public void setContactService( ContactService contactService ) {
this.contactService = contactService;
}
/**
* @param bioAssayService the bioAssayService to set
*/
public void setBioAssayService( BioAssayService bioAssayService ) {
this.bioAssayService = bioAssayService;
}
/**
* @param bioMaterialService the bioMaterialService to set
*/
public void setBioMaterialService( BioMaterialService bioMaterialService ) {
this.bioMaterialService = bioMaterialService;
}
public void setQuantitationTypeService( QuantitationTypeService quantitationTypeService ) {
this.quantitationTypeService = quantitationTypeService;
}
}
| add audit event when biomaterial mapping is changed; cleanup
| gemma-web/src/main/java/ubic/gemma/web/controller/expression/experiment/ExpressionExperimentFormController.java | add audit event when biomaterial mapping is changed; cleanup | <ide><path>emma-web/src/main/java/ubic/gemma/web/controller/expression/experiment/ExpressionExperimentFormController.java
<ide> import org.xml.sax.SAXException;
<ide>
<ide> import ubic.gemma.loader.entrez.pubmed.PubMedSearch;
<add>import ubic.gemma.model.common.auditAndSecurity.AuditTrailService;
<ide> import ubic.gemma.model.common.auditAndSecurity.ContactService;
<add>import ubic.gemma.model.common.auditAndSecurity.eventType.AuditEventType;
<add>import ubic.gemma.model.common.auditAndSecurity.eventType.CommentedEvent;
<ide> import ubic.gemma.model.common.description.BibliographicReference;
<ide> import ubic.gemma.model.common.description.BibliographicReferenceService;
<ide> import ubic.gemma.model.common.description.DatabaseEntry;
<ide> * @spring.property name = "persisterHelper" ref="persisterHelper"
<ide> * @spring.property name = "validator" ref="expressionExperimentValidator"
<ide> * @spring.property name = "quantitationTypeService" ref="quantitationTypeService"
<add> * @spring.property name="auditTrailService" ref="auditTrailService"
<ide> */
<ide> public class ExpressionExperimentFormController extends BaseFormController {
<ide>
<ide> BibliographicReferenceService bibliographicReferenceService = null;
<ide> PersisterHelper persisterHelper = null;
<ide> QuantitationTypeService quantitationTypeService;
<add> AuditTrailService auditTrailService;
<add>
<add> /**
<add> * @param auditTrailService the auditTrailService to set
<add> */
<add> public void setAuditTrailService( AuditTrailService auditTrailService ) {
<add> this.auditTrailService = auditTrailService;
<add> }
<add>
<ide> private ExternalDatabaseService externalDatabaseService = null;
<ide>
<ide> public void setExternalDatabaseService( ExternalDatabaseService externalDatabaseService ) {
<ide> */
<ide> updateQuantTypes( request, expressionExperiment, eeCommand.getQuantitationTypes() );
<ide>
<del> updateBioMaterialMap( request );
<add> updateBioMaterialMap( request, expressionExperiment );
<ide>
<ide> updateAccession( request, expressionExperiment );
<ide>
<ide> return new ModelAndView( new RedirectView( "http://" + request.getServerName() + ":" + request.getServerPort()
<ide> + request.getContextPath() + "/expressionExperiment/showExpressionExperiment.html?id="
<ide> + eeCommand.getId() ) );
<add> }
<add>
<add> /**
<add> * @param arrayDesign
<add> */
<add> private void audit( ExpressionExperiment ee, AuditEventType eventType, String note ) {
<add> auditTrailService.addUpdateEvent( ee, eventType, note );
<ide> }
<ide>
<ide> /**
<ide> }
<ide>
<ide> /**
<del> * @param request
<del> * @throws TokenStreamException
<del> * @throws RecognitionException
<del> */
<del> private void updateBioMaterialMap( HttpServletRequest request ) {
<add> * Change the relationship between bioassays and biomaterials.
<add> *
<add> * @param request
<add> * @param expressionExperiment
<add> */
<add> private void updateBioMaterialMap( HttpServletRequest request, ExpressionExperiment expressionExperiment ) {
<ide> // parse JSON-serialized map
<ide> String jsonSerialization = request.getParameter( "assayToMaterialMap" );
<ide> // convert back to a map
<ide> }
<ide>
<ide> BioMaterial oldBioMaterial = bMats.iterator().next();
<del> // newMaterial = BioMaterial.Factory.newInstance();
<ide> newMaterial = bioMaterialService.copy( oldBioMaterial );
<del> // newMaterial.setDescription( oldBioMaterial.getDescription() + " [Created by Gemma]" );
<del> // newMaterial.setMaterialType( oldBioMaterial.getMaterialType() );
<del> // newMaterial.setCharacteristics( oldBioMaterial.getCharacteristics() );
<del> // newMaterial.setTreatments( oldBioMaterial.getTreatments() );
<del> // newMaterial.setSourceTaxon( oldBioMaterial.getSourceTaxon() );
<del> // newMaterial.setFactorValues( oldBioMaterial.getFactorValues() );
<ide> newMaterial.setName( "Modeled after " + oldBioMaterial.getName() );
<ide> newMaterial = ( BioMaterial ) persisterHelper.persist( newMaterial );
<ide> } else {
<ide> for ( BioAssay assay : deleteKeys ) {
<ide> bioAssayService.removeBioMaterialAssociation( assay, deleteAssociations.get( assay ) );
<ide> }
<add>
<add> /*
<add> * TODO: make this a separate event class, so we can flag experiments that need to be reanalyzed after doing this.
<add> */
<add> audit( expressionExperiment, CommentedEvent.Factory.newInstance(), "Updated biomaterial -> bioassay map" );
<ide> }
<ide>
<ide> /** |
|
Java | bsd-3-clause | 103a7b0b784c8e8c6c31cb16a35498fa3706245d | 0 | FIRST-4030/2013 | package edu.wpi.first.wpilibj.templates.helpers.imageprocess;
/**
*
*/
public class VisionTarget {
/**
* X position of closest vertex to origin
*/
private int x;
/**
* Z position of closest vertex to origin
*/
private int y;
/**
* Z position of closest vertex to origin
*/
private int z;
/**
* Delta y from extrema
*/
private int height;
/**
* Hypotenuse of delta x and delta z from extrema
*/
private int width;
/**
* Angle from x axis on the x-z plain
*/
private double angle;
public VisionTarget(int x, int y, int z, int height, int width, double angle) {
this.x = x;
this.y = y;
this.z = z;
this.height = height;
this.width = width;
this.angle = angle;
}
public VisionTarget(int x, int y, int z, int height, int width) {
this(x, y, z, height, width, 0);
}
public int getX() {
return x;
}
public int getY() {
return y;
}
public int getZ() {
return z;
}
public int getHeight() {
return height;
}
public int getWidth() {
return width;
}
public double getAngle() {
return angle;
}
public RobotPositionReport GetLocBasedOnTarget(VisionTarget ideal) {
// Not Finished?
return null;
}
}
| src/edu/wpi/first/wpilibj/templates/helpers/imageprocess/VisionTarget.java | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package edu.wpi.first.wpilibj.templates.helpers.imageprocess;
/**
*
* @author Ingyram
*/
public class VisionTarget {
/**
* x position of closest vertex to origin
*/
private int x;
/**
* y position of closest vertex to origin
*/
private int y;
/**
* z position of closest vertex to origin
*/
private int z;
/**
* delta y from extrema
*/
private int height;
/**
* hypotonus of delta x and delta z from extrema
*/
private int width;
/**
* angle from x axis on the x-z plain
*/
private double angle;
public VisionTarget(int x, int y, int z, int height, int width, double angle){
this.x=x;
this.y=y;
this.z=z;
this.height=height;
this.width=width;
this.angle=angle;
}
public VisionTarget(int x, int y, int z, int height, int width){
this(x,y,z,height,width,0);
}
public int getX() {
return x;
}
public int getY() {
return y;
}
public int getZ() {
return z;
}
public int getHeight() {
return height;
}
public int getWidth() {
return width;
}
public double getAngle() {
return angle;
}
public RobotPositionReport GetLocBasedOnTarget(VisionTarget ideal){
int viewAngle=0;
return null;
}
}
| Formated | src/edu/wpi/first/wpilibj/templates/helpers/imageprocess/VisionTarget.java | Formated | <ide><path>rc/edu/wpi/first/wpilibj/templates/helpers/imageprocess/VisionTarget.java
<del>/*
<del> * To change this template, choose Tools | Templates
<del> * and open the template in the editor.
<del> */
<ide> package edu.wpi.first.wpilibj.templates.helpers.imageprocess;
<ide>
<ide> /**
<ide> *
<del> * @author Ingyram
<ide> */
<ide> public class VisionTarget {
<add>
<ide> /**
<del> * x position of closest vertex to origin
<add> * X position of closest vertex to origin
<ide> */
<ide> private int x;
<ide> /**
<del> * y position of closest vertex to origin
<add> * Z position of closest vertex to origin
<ide> */
<ide> private int y;
<ide> /**
<del> * z position of closest vertex to origin
<add> * Z position of closest vertex to origin
<ide> */
<ide> private int z;
<ide> /**
<del> * delta y from extrema
<add> * Delta y from extrema
<ide> */
<ide> private int height;
<ide> /**
<del> * hypotonus of delta x and delta z from extrema
<add> * Hypotenuse of delta x and delta z from extrema
<ide> */
<ide> private int width;
<ide> /**
<del> * angle from x axis on the x-z plain
<add> * Angle from x axis on the x-z plain
<ide> */
<ide> private double angle;
<del>
<del> public VisionTarget(int x, int y, int z, int height, int width, double angle){
<del> this.x=x;
<del> this.y=y;
<del> this.z=z;
<del> this.height=height;
<del> this.width=width;
<del> this.angle=angle;
<add>
<add> public VisionTarget(int x, int y, int z, int height, int width, double angle) {
<add> this.x = x;
<add> this.y = y;
<add> this.z = z;
<add> this.height = height;
<add> this.width = width;
<add> this.angle = angle;
<ide> }
<del> public VisionTarget(int x, int y, int z, int height, int width){
<del> this(x,y,z,height,width,0);
<add>
<add> public VisionTarget(int x, int y, int z, int height, int width) {
<add> this(x, y, z, height, width, 0);
<ide> }
<ide>
<ide> public int getX() {
<ide> public double getAngle() {
<ide> return angle;
<ide> }
<del>
<del> public RobotPositionReport GetLocBasedOnTarget(VisionTarget ideal){
<del> int viewAngle=0;
<del> return null;
<add>
<add> public RobotPositionReport GetLocBasedOnTarget(VisionTarget ideal) {
<add> // Not Finished?
<add> return null;
<ide> }
<del>
<del>
<del>
<ide> } |
|
JavaScript | agpl-3.0 | 417642a7d92d27e0730f23f53898408d7d66ee8a | 0 | CelineBoudier/rapid-router,mikebryant/rapid-router,mikebryant/rapid-router,CelineBoudier/rapid-router,CelineBoudier/rapid-router,CelineBoudier/rapid-router,mikebryant/rapid-router,mikebryant/rapid-router | 'use strict';
var ocargo = ocargo || {};
ocargo.LevelEditor = function() {
/*************/
/* Constants */
/*************/
var LIGHT_RED_URL = '/static/game/image/trafficLight_red.svg';
var LIGHT_GREEN_URL = '/static/game/image/trafficLight_green.svg';
var VALID_LIGHT_COLOUR = '#87E34D';
var INVALID_LIGHT_COLOUR = '#E35F4D';
var ADD_ROAD_MODE = 'Add road';
var DELETE_ROAD_MODE = 'Delete road';
var MARK_DESTINATION_MODE = 'Mark destination';
var MARK_ORIGIN_MODE = 'Mark origin';
var DELETE_DECOR_MODE = 'Delete decor';
/*********/
/* State */
/*********/
ocargo.saving = new ocargo.Saving();
ocargo.drawing = new ocargo.Drawing();
// Level information
var nodes = [];
var decor = [];
var trafficLights = [];
var originNode = null;
var destinationNode = null;
var currentTheme = THEMES["grass"];
// Reference to the Raphael elements for each square
var grid = initialiseVisited();
// Current mode the user is in
var mode = ADD_ROAD_MODE;
// Holds the state for when the user is drawing or deleting roads
var strikeStart = null;
// holds the state to do with saving
var savedState = null;
var savedLevelID = -1;
// so that we store the current state when the page unloads
window.addEventListener('unload', storeStateInLocalStorage);
// setup the toolbox
setupToolbox();
// If there's any previous state in local storage retrieve it
retrieveStateFromLocalStorage();
// initialises paper
drawAll();
// set the default theme
setTheme(THEMES["grass"]);
/***************/
/* Setup tools */
/***************/
// Sets up the left hand side toolbox (listeners/images etc.)
function setupToolbox() {
var tabs = [];
var currentTabSelected = null;
tabs['play'] = new ocargo.Tab($('#play_radio'), $('#play_radio + label'));
tabs['map'] = new ocargo.Tab($('#map_radio'), $('#map_radio + label'), $('#map_pane'));
tabs['decor'] = new ocargo.Tab($('#decor_radio'), $('#decor_radio + label'), $('#decor_pane'));
tabs['character'] = new ocargo.Tab($('#character_radio'), $('#character_radio + label'), $('#character_pane'));
tabs['blocks'] = new ocargo.Tab($('#blocks_radio'), $('#blocks_radio + label'), $('#blocks_pane'));
tabs['random'] = new ocargo.Tab($('#random_radio'), $('#random_radio + label'), $('#random_pane'));
tabs['load'] = new ocargo.Tab($('#load_radio'), $('#load_radio + label'), $('#load_pane'));
tabs['save'] = new ocargo.Tab($('#save_radio'), $('#save_radio + label'), $('#save_pane'));
tabs['share'] = new ocargo.Tab($('#share_radio'), $('#share_radio + label'), $('#share_pane'));
tabs['help'] = new ocargo.Tab($('#help_radio'), $('#help_radio + label'), $('#help_pane'));
tabs['quit'] = new ocargo.Tab($('#quit_radio'), $('#quit_radio + label'));
setupPlayTab();
setupMapTab();
setupDecorTab();
setupCharacterTab();
setupBlocksTab();
setupRandomTab();
setupLoadTab();
setupSaveTab();
setupShareTab();
setupHelpTab();
setupQuitTab();
// enable the map tab by default
currentTabSelected = tabs['map'];
tabs['map'].select();
function setupPlayTab() {
tabs['play'].setOnChange(function() {
if(isLevelSaved()) {
window.location.href = "/game/" + savedLevelID;
}
else {
currentTabSelected.select();
};
})
}
function setupMapTab() {
tabs['map'].setOnChange(function() {
transitionTab(tabs['map']);
});
$('#clear').click(function() {
new ocargo.LevelEditor();
});
$('#start').click(function() {
mode = MARK_ORIGIN_MODE;
});
$('#end').click(function() {
mode = MARK_DESTINATION_MODE;
});
$('#add_road').click(function() {
mode = ADD_ROAD_MODE;
});
$('#delete_road').click(function() {
mode = DELETE_ROAD_MODE;
});
}
function setupDecorTab() {
tabs['decor'].setOnChange(function() {
transitionTab(tabs['decor']);
});
$('#theme_select').change(function() {
setTheme(THEMES[$(this).val()]);
});
$('#bush').click(function() {
new InternalDecor('bush');
});
$('#tree1').click(function() {
new InternalDecor('tree1');
});
$('#tree2').click(function() {
new InternalDecor('tree2');
});
$('#pond').click(function() {
new InternalDecor('pond');
});
$('#trafficLightRed').click(function() {
new InternalTrafficLight({"redDuration": 3, "greenDuration": 3, "startTime": 0,
"startingState": ocargo.TrafficLight.RED,
"controlledNode": -1, "sourceNode": -1});
});
$('#trafficLightGreen').click(function() {
new InternalTrafficLight({"redDuration": 3, "greenDuration": 3, "startTime": 0,
"startingState": ocargo.TrafficLight.GREEN,
"controlledNode": -1, "sourceNode": -1});
});
$('#delete_decor').click(function() {
if (mode === DELETE_DECOR_MODE) {
mode = ADD_ROAD_MODE;
} else {
mode = DELETE_DECOR_MODE;
}
});
}
function setupCharacterTab() {
tabs['character'].setOnChange(function() {
transitionTab(tabs['character']);
});
$('#Van_radio').prop("checked", true);
$("#character-form").on('change', ':input', function() {
CHARACTER_NAME = $('input:checked', '#character-form').val();
redrawRoad();
});
}
function setupBlocksTab() {
tabs['blocks'].setOnChange(function() {
transitionTab(tabs['blocks']);
});
// Hacky, if a way can be found without initialising the entire work space that would be great!
// Initial selection
$('#move_forwards_checkbox').prop('checked', true);
$('#turn_left_checkbox').prop('checked', true);
$('#turn_right_checkbox').prop('checked', true);
// Select all functionality
var selectAll = $('#select_all_checkbox');
selectAll.change(function() {
var checked = selectAll.prop('checked');
$('.block_checkbox').each(function() {
if($(this) !== selectAll) {
$(this).prop('checked', checked);
}
})
})
// Setup the block images
function addListenerToImage(type) {
$('#' + type + '_image').click(function() {
$('#' + type + '_checkbox').click();
});
}
initCustomBlocksDescription();
var blockly = document.getElementById('blockly');
var toolbox = document.getElementById('toolbox');
Blockly.inject(blockly, {
path: '/static/game/js/blockly/',
toolbox: toolbox,
trashcan: true
});
for(var i = 0; i < BLOCKS.length; i++) {
var type = BLOCKS[i];
var block = Blockly.Block.obtain(Blockly.mainWorkspace, type);
block.initSvg();
block.render();
var svg = block.getSvgRoot();
var large = type === "controls_whileUntil" ||
type === "controls_repeat" ||
type === "controls_if" ||
type === "declare_proc";
var content = '<svg class="block_image' + (large ? ' large' : '') + '">';
content += '<g transform="translate(10,0)"';
content += svg.innerHTML + '</g></svg>';
$('#' + type + '_image').html(content);
addListenerToImage(type);
}
$('#blockly').css('display','none');
}
function setupRandomTab() {
tabs['random'].setOnChange(function() {
transitionTab(tabs['random']);
});
$('#generate').click(function() {
var data = {numberOfTiles: $('#size').val(),
branchiness: $('#branchiness').val()/10,
loopiness: $('#loopiness').val()/10,
curviness: $('#curviness').val()/10,
trafficLightsEnabled: true,
csrfmiddlewaretoken: $("#csrfmiddlewaretoken").val()};
ocargo.saving.retrieveRandomLevel(data, function(error, mapData) {
if(error) {
console.debug(error);
ocargo.Drawing.startPopup("Error","",ocargo.messages.internetDown);
return;
}
clear();
var path = JSON.parse(mapData.path);
var i;
for (i = 0; i < path.length; i++) {
var node = new ocargo.Node(new ocargo.Coordinate(path[i].coordinate[0],
path[i].coordinate[1]));
nodes.push(node);
}
for (i = 0; i < path.length; i++) {
nodes[i].connectedNodes = [];
for(var j = 0; j < path[i].connectedNodes.length; j++) {
nodes[i].connectedNodes.push(nodes[path[i].connectedNodes[j]]);
}
}
// TODO add in support for multiple destinations
var destination = JSON.parse(mapData.destinations)[0];
var destinationCoord = new ocargo.Coordinate(destination[0], destination[1]);
destinationNode = ocargo.Node.findNodeByCoordinate(destinationCoord, nodes);
originNode = nodes[0];
var tls = JSON.parse(mapData.traffic_lights);
for(i = 0; i < tls.length; i++) {
new InternalTrafficLight(tls[i]);
}
drawAll();
});
});
}
function setupLoadTab() {
var selectedLevel = null;
tabs['load'].setOnChange(function() {
ocargo.saving.retrieveListOfLevels(function(err, ownLevels, sharedLevels) {
if (err != null) {
console.debug(err);
currentTabSelected.select();
ocargo.Drawing.startPopup("Error","",ocargo.messages.internetDown);
return;
}
populateLoadSaveTable("loadOwnLevelTable", ownLevels);
// Add click listeners to all rows
$('#loadOwnLevelTable tr').on('click', function(event) {
$('#loadOwnLevelTable tr').css('background-color', '#FFFFFF');
$('#loadSharedLevelTable tr').css('background-color', '#FFFFFF');
$(this).css('background-color', '#C0C0C0');
$('#loadLevel').removeAttr('disabled');
$('#deleteLevel').removeAttr('disabled');
selectedLevel = $(this).attr('value');
});
populateLoadSaveTable("loadSharedLevelTable", sharedLevels);
// Add click listeners to all rows
$('#loadSharedLevelTable tr').on('click', function(event) {
$('#loadOwnLevelTable tr').css('background-color', '#FFFFFF');
$('#loadSharedLevelTable tr').css('background-color', '#FFFFFF');
$(this).css('background-color', '#C0C0C0');
$('#loadLevel').removeAttr('disabled');
$('#deleteLevel').removeAttr('disabled');
selectedLevel = $(this).attr('value');
});
// But disable all the modal buttons as nothing is selected yet
selectedLevel = null;
$('#loadLevel').attr('disabled', 'disabled');
$('#deleteLevel').attr('disabled', 'disabled');
transitionTab(tabs['load']);
});
});
// Setup own/shared levels radio
$('#own_levels_radio').change(function() {
$('#loadOwnLevelTable').css('display','table');
$('#loadSharedLevelTable').css('display','none');
});
$('#shared_levels_radio').change(function() {
$('#loadOwnLevelTable').css('display','none');
$('#loadSharedLevelTable').css('display','table');
});
$('#own_levels_radio').change();
$('#loadLevel').click(function() {
if(selectedLevel) {
loadLevel(selectedLevel);
}
});
$('#deleteLevel').click(function() {
if(!selectedLevel) {
return;
}
ocargo.saving.deleteLevel(selectedLevel, function(err) {
if (err != null) {
console.debug(err);
return;
}
$('#loadOwnLevelTable tr[value=' + selectedLevel + ']').remove();
selectedLevel = null;
});
});
}
function setupSaveTab() {
var selectedLevel = null;
tabs['save'].setOnChange(function () {
if(!isLevelValid()) {
currentTabSelected.select();
return;
}
ocargo.saving.retrieveListOfLevels(function(err, ownLevels, sharedLevels) {
if (err != null) {
console.debug(err);
ocargo.Drawing.startPopup("Error","",ocargo.messages.internetDown);
return;
}
populateLoadSaveTable("saveLevelTable", ownLevels);
// Add click listeners to all rows
$('#saveLevelTable tr').on('click', function(event) {
var rowSelected = $(event.target.parentElement);
$('#saveLevelTable tr').css('background-color', '#FFFFFF');
rowSelected.css('background-color', '#C0C0C0');
$('#saveLevel').removeAttr('disabled');
selectedLevel = parseInt(rowSelected.attr('value'));
for(var i = 0; i < ownLevels.length; i++) {
if(ownLevels[i].id === selectedLevel) {
$("#levelNameInput").val(ownLevels[i].name);
}
}
});
transitionTab(tabs['save']);
selectedLevel = null;
});
});
$('#saveLevel').click(function() {
var newName = $('#levelNameInput').val();
if (!newName || newName === "") {
// TODO error message?
return;
}
// Test to see if we already have the level saved
var table = $("#saveLevelTable");
var existingID = -1;
for (var i = 0; i < table[0].rows.length; i++) {
var row = table[0].rows[i];
var existingName = row.cells[0].innerHTML;
if (existingName === newName) {
existingID = row.getAttribute('value');
break;
}
}
if(existingID != -1) {
if(existingID != savedLevelID) {
var onYes = function() {
saveLevel(newName, existingID);
}
//ocargo.Drawing.startPopup("Overwriting","Warning",ocargo.messages.saveOverwriteWarning(newName, onYes));
saveLevel(newName, existingID)
}
else {
saveLevel(newName, existingID)
}
}
else {
saveLevel(newName, null);
}
});
}
function setupShareTab() {
tabs['share'].setOnChange(function() {
if(!isLevelSaved()) {
currentTabSelected.select();
return;
}
ocargo.saving.getSharingInformation(savedLevelID, function(error, recipientData, role) {
if(error !== null) {
console.debug(error);
ocargo.Drawing.startPopup("Error","",ocargo.messages.internetDown);
return;
}
if(role !== "student" && role !== 'teacher') {
ocargo.Drawing.startPopup("Not logged in", "", ocargo.messages.notLoggedIn);
currentTabSelected.select();
return;
}
if(role === "student") {
$('#teacher_sharing').css('display','none');
$('#student_sharing').css('display','block');
var classmates = recipientData.validRecipients.classmates;
var teacher = recipientData.validRecipients.teacher;
populateSharingTable(classmates, teacher);
}
else if(role == "teacher") {
$('#teacher_sharing').css('display','block');
$('#student_sharing').css('display','none');
var teachers = recipientData.validRecipients.teachers;
var classes = recipientData.validRecipients.classes;
$('teacher_select').empty();
for(var i = 0; i < teachers.length; i++) {
var teacher = teachers[i]
var item = '<option value=' + teacher.id + '>' + teacher.name + '</option>';
$('#teacher_select').append(item);
}
}
transitionTab(tabs['share']);
});
});
$('#teachers_radio').change(function() {
$('#class_selection').css('display','none');
$('#teacher_selection').css('display','block');
});
$('#classes_radio').change(function() {
$('#class_selection').css('display','block');
$('#teacher_selection').css('display','none');
});
$('#classes_radio').change();
$('#share').click(function() {
var recipientID;
if($('#pupil_sharing').css('display') === 'block') {
recipientID = $('#user_select option').is('selected').attr('value')
}
else {
if($('#class_selection').css('display') === 'block') {
recipientID = $('#student_select option').is('selected').attr('value')
}
else {
recipientID = $('#teacher_select option').is('selected').attr('value')
}
}
shareLevel(levelID, recipients);
});
$('#unshare').click(function() {
console.log("Unshare!");
});
}
function setupHelpTab() {
tabs['help'].setOnChange(function() {
transitionTab(tabs['help']);
});
$('#help.tab_pane').html(ocargo.messages.levelEditorHelpText);
}
function setupQuitTab() {
tabs['quit'].setOnChange(function() {
window.location.href = "/game/";
});
}
// Helper methods
function transitionTab(newTab) {
currentTabSelected.setPaneEnabled(false);
newTab.setPaneEnabled(true);
currentTabSelected = newTab;
}
function populateLoadSaveTable(tableName, levels) {
var table = $('#'+tableName);
// Remove click listeners to avoid memory leak and remove all rows
$('#'+tableName+' tr').off('click');
table.empty();
// Order them alphabetically
levels.sort(function(a, b) {
if (a.name < b.name) {
return -1;
}
else if (a.name > b.name) {
return 1;
}
return 0;
});
// Add a row to the table for each workspace saved in the database
table.append('<tr> <th>Name</th> <th>Owner</th> <th>Shared</th> </tr>');
for (var i = 0, ii = levels.length; i < ii; i++) {
var level = levels[i];
table.append('<tr value=' + level.id + '> <td>' + level.name + '</td> <td>' +
level.owner + '</td> <td>false</td>');
}
}
function populateSharingTable(mainRecipients, specialRecipient) {
// Remove click listeners to avoid memory leak and remove all rows
var table = $('#levelSharingTable');
$('#levelSharingTable tr').off('click');
table.empty();
table.append('<tr> <th>Name</th> <th>Shared</th> </tr>');
if(specialRecipient) {
table.append('<tr value=' + specialRecipient.id + '>' +
'<td>' + specialRecipient.name + '</td>' +
'<td>' + specialRecipient.shared + '</td>' +
'</tr>');
}
// Order them alphabetically
mainRecipients.sort(function(a, b) {
if (a.name < b.name) {
return -1;
}
else if (a.name > b.name) {
return 1;
}
return 0;
});
// Add a row to the table for each workspace saved in the database
for (var i = 0; i < mainRecipients.length; i++) {
var recipient = mainRecipients[i];
table.append('<tr value=' + recipient.id + '>' +
'<td>' + recipient.name + '</td>' +
'<td>' + "Yes" + '</td>' +
'</tr>');
}
}
}
/************************/
/** Current state tests */
/************************/
// Functions simply to improve readability of complex conditional code
function isOriginCoordinate(coordinate) {
return originNode && originNode.coordinate.equals(coordinate);
}
function isDestinationCoordinate(coordinate) {
return destinationNode && destinationNode.coordinate.equals(coordinate);
}
function isCoordinateOnGrid(coordinate) {
return coordinate.x >= 0 && coordinate.x < GRID_WIDTH && coordinate.y >= 0 && coordinate.y < GRID_HEIGHT;
}
function canPlaceCFC(node) {
return node.connectedNodes.length <= 1;
}
/*************/
/* Rendering */
/*************/
function clear() {
for(var i = 0; i < trafficLights.length; i++) {
trafficLights[i].destroy();
}
trafficLights = [];
decor = [];
nodes = [];
grid = initialiseVisited();
strikeStart = null;
originNode = null;
destinationNode = null;
ocargo.drawing.clearPaper();
}
function drawAll() {
createGrid(paper);
redrawRoad();
}
function redrawRoad() {
ocargo.drawing.renderRoad(nodes);
clearMarkings();
bringTrafficLightsToFront();
bringDecorToFront();
}
function bringDecorToFront() {
for (var i = 0; i < decor.length; i++) {
decor[i].image.toFront();
}
}
function bringTrafficLightsToFront() {
for(var i = 0; i < trafficLights.length; i++) {
trafficLights[i].image.toFront();
}
}
/************/
/* Marking */
/************/
// Methods for highlighting squares
function mark(coordMap, colour, opacity, occupied) {
var coordPaper = ocargo.Drawing.translate(coordMap);
var element = grid[coordPaper.x][coordPaper.y];
element.attr({fill:colour, "fill-opacity": opacity});
}
function markAsOrigin(coordinate) {
mark(coordinate, 'red', 0.7, true);
}
function markAsDestination(coordinate) {
mark(coordinate, 'blue', 0.7, true);
}
function markAsBackground(coordinate) {
mark(coordinate, currentTheme.background, 0, false);
}
function markAsSelected(coordinate) {
mark(coordinate, currentTheme.selected, 1, true);
}
function markAsHighlighted(coordinate) {
mark(coordinate, currentTheme.selected, 0.3, true);
}
function clearMarkings() {
for (var i = 0; i < GRID_WIDTH; i++) {
for (var j = 0; j < GRID_HEIGHT; j++) {
markAsBackground(new ocargo.Coordinate(i,j));
grid[i][j].toFront();
}
}
if(originNode) {
markAsOrigin(originNode.coordinate);
}
if(destinationNode) {
markAsDestination(destinationNode.coordinate);
}
bringTrafficLightsToFront();
bringDecorToFront();
}
function markTentativeRoad(currentEnd) {
clearMarkings();
applyAlongStrike(setup, currentEnd);
var previousNode = null;
function setup(x, y) {
var coordinate = new ocargo.Coordinate(x, y);
var node = new ocargo.Node(coordinate);
if(previousNode)
{
node.addConnectedNodeWithBacklink(previousNode);
}
previousNode = node;
markAsSelected(coordinate);
}
}
/***************************/
/* Paper interaction logic */
/***************************/
function handleMouseDown(this_rect) {
return function () {
var getBBox = this_rect.getBBox();
var coordPaper = new ocargo.Coordinate(getBBox.x / GRID_SPACE_SIZE,
getBBox.y / GRID_SPACE_SIZE);
var coordMap = ocargo.Drawing.translate(coordPaper);
var existingNode = ocargo.Node.findNodeByCoordinate(coordMap, nodes);
if(mode === MARK_ORIGIN_MODE && existingNode && canPlaceCFC(existingNode))
{
if (originNode) {
var prevStart = originNode.coordinate;
markAsBackground(prevStart);
}
// Check if same as destination node
if (isDestinationCoordinate(coordMap)) {
destinationNode = null;
}
markAsOrigin(coordMap);
var newStartIndex = ocargo.Node.findNodeIndexByCoordinate(coordMap, nodes);
// Putting the new start in the front of the nodes list.
var temp = nodes[newStartIndex];
nodes[newStartIndex] = nodes[0];
nodes[0] = temp;
originNode = nodes[0];
}
else if (mode === MARK_DESTINATION_MODE && existingNode)
{
if (destinationNode) {
var prevEnd = destinationNode.coordinate;
markAsBackground(prevEnd);
}
// Check if same as starting node
if (isOriginCoordinate(coordMap)) {
originNode = null;
}
markAsDestination(coordMap);
var newEnd = ocargo.Node.findNodeIndexByCoordinate(coordMap, nodes);
destinationNode = nodes[newEnd];
}
else if (mode === ADD_ROAD_MODE || mode === DELETE_ROAD_MODE) {
strikeStart = coordMap;
markAsSelected(coordMap);
}
};
}
function handleMouseOver(this_rect) {
return function() {
var getBBox = this_rect.getBBox();
var coordPaper = new ocargo.Coordinate(getBBox.x / 100, getBBox.y / 100);
var coordMap = ocargo.Drawing.translate(coordPaper);
if (mode === ADD_ROAD_MODE || mode === DELETE_ROAD_MODE)
{
if(strikeStart !== null)
{
markTentativeRoad(coordMap);
}
else if(!isOriginCoordinate(coordMap) && !isDestinationCoordinate(coordMap))
{
markAsHighlighted(coordMap);
}
}
else if(mode === MARK_ORIGIN_MODE || mode === MARK_DESTINATION_MODE)
{
var node = ocargo.Node.findNodeByCoordinate(coordMap, nodes);
if (node && destinationNode !== node && originNode !== node)
{
if(mode === MARK_DESTINATION_MODE)
{
mark(coordMap, 'blue', 0.3, true);
}
else if(canPlaceCFC(node))
{
mark(coordMap, 'red', 0.5, true);
}
}
}
};
}
function handleMouseOut(this_rect) {
return function() {
var getBBox = this_rect.getBBox();
var coordPaper = new ocargo.Coordinate(getBBox.x/GRID_SPACE_SIZE,
getBBox.y/GRID_SPACE_SIZE);
var coordMap = ocargo.Drawing.translate(coordPaper);
if(mode === MARK_ORIGIN_MODE || mode === MARK_DESTINATION_MODE)
{
var node = ocargo.Node.findNodeByCoordinate(coordMap, nodes);
if (node && destinationNode !== node && originNode !== node)
{
markAsBackground(coordMap);
}
}
else if(mode === ADD_ROAD_MODE || mode === DELETE_ROAD_MODE)
{
if(!isOriginCoordinate(coordMap) && !isDestinationCoordinate(coordMap))
{
markAsBackground(coordMap);
}
}
};
}
function handleMouseUp(this_rect) {
return function() {
if (mode === ADD_ROAD_MODE || mode === DELETE_ROAD_MODE) {
var getBBox = this_rect.getBBox();
var coordPaper = new ocargo.Coordinate(getBBox.x/GRID_SPACE_SIZE,
getBBox.y/GRID_SPACE_SIZE);
var coordMap = ocargo.Drawing.translate(coordPaper);
if (mode === DELETE_ROAD_MODE) {
finaliseDelete(coordMap);
}
else {
finaliseMove(coordMap);
}
sortNodes(nodes);
redrawRoad();
}
};
}
function setupDecorListeners(decor) {
var image = decor.image;
var originX;
var originY;
var paperX;
var paperY;
var paperWidth;
var paperHeight;
var imageWidth;
var imageHeight;
function onDragMove(dx, dy) {
paperX = dx + originX;
paperY = dy + originY;
// Stop it being dragged off the edge of the page
if(paperX < 0) {
paperX = 0;
}
else if(paperX + imageWidth > paperWidth) {
paperX = paperWidth - imageWidth;
}
if(paperY < 0) {
paperY = 0;
}
else if(paperY + imageHeight > paperHeight) {
paperY = paperHeight - imageHeight;
}
image.transform('t' + paperX + ',' + paperY);
}
function onDragStart(x, y) {
var bBox = image.getBBox();
imageWidth = bBox.width;
imageHeight = bBox.height;
var paperPosition = $('#paper').position();
originX = x - paperPosition.left - imageWidth/2;
originY = y - paperPosition.top - imageHeight/2;
paperWidth = GRID_WIDTH * GRID_SPACE_SIZE;
paperHeight = GRID_HEIGHT * GRID_SPACE_SIZE;
}
function onDragEnd() {
originX = paperX;
originY = paperY;
}
image.drag(onDragMove, onDragStart, onDragEnd);
image.click(function() {
if(mode === DELETE_DECOR_MODE) {
decor.destroy();
}
});
}
function setupTrafficLightListeners(trafficLight) {
var image = trafficLight.image;
// Position in map coordinates.
var sourceCoord;
var controlledCoord;
// Current position of the element in paper coordinates
var paperX;
var paperY;
// Where the drag started in paper coordinates
var originX;
var originY;
// Size of the paper
var paperWidth;
var paperHeight;
// Size of the image
var imageWidth;
var imageHeight;
// Orientation and rotation transformations
var scaling;
var rotation;
var moved = false;
function onDragMove(dx, dy) {
// Needs to be in onDragMove, not in onDragStart, to stop clicks triggering drag behaviour
trafficLight.valid = false;
image.attr({'cursor':'default'});
moved = dx !== 0 || dy !== 0;
// Update image's position
paperX = dx + originX;
paperY = dy + originY;
// Stop it being dragged off the edge of the page
if(paperX < 0) {
paperX = 0;
}
else if(paperX + imageWidth > paperWidth) {
paperX = paperWidth - imageWidth;
}
if(paperY < 0) {
paperY = 0;
}
else if(paperY + imageHeight > paperHeight) {
paperY = paperHeight - imageHeight;
}
// Adjust for the fact that we've rotated the image
if(rotation === 90 || rotation === 270) {
paperX += (imageWidth - imageHeight)/2;
paperY -= (imageWidth - imageHeight)/2;
}
// And perform the updatee
image.transform('t' + paperX + ',' + paperY + 'r' + rotation + 's' + scaling);
// Unmark the squares the light previously occupied
if(sourceCoord) {
markAsBackground(sourceCoord);
}
if(controlledCoord) {
markAsBackground(controlledCoord);
}
if(originNode) {
markAsOrigin(originNode.coordinate);
}
if(destinationNode) {
markAsDestination(destinationNode.coordinate);
}
// Now calculate the source coordinate
var box = image.getBBox();
var absX = (box.x + box.width/2) / GRID_SPACE_SIZE;
var absY = (box.y + box.height/2) / GRID_SPACE_SIZE;
switch(rotation) {
case 0:
absY += 0.5;
break;
case 90:
absX -= 0.5;
break;
case 180:
absY -= 0.5;
break;
case 270:
absX += 0.5;
break;
}
var x = Math.min(Math.max(0, Math.floor(absX)), GRID_WIDTH - 1);
var y = GRID_HEIGHT - Math.min(Math.max(0, Math.floor(absY)), GRID_HEIGHT - 1) - 1;
sourceCoord = new ocargo.Coordinate(x,y);
// Find controlled position in map coordinates
switch(rotation) {
case 0:
controlledCoord = new ocargo.Coordinate(sourceCoord.x, sourceCoord.y + 1);
break;
case 90:
controlledCoord = new ocargo.Coordinate(sourceCoord.x + 1, sourceCoord.y);
break;
case 180:
controlledCoord = new ocargo.Coordinate(sourceCoord.x, sourceCoord.y - 1);
break;
case 270:
controlledCoord = new ocargo.Coordinate(sourceCoord.x - 1, sourceCoord.y);
break;
}
// If controlled node is not on grid, remove it
if(!isCoordinateOnGrid(controlledCoord)) {
controlledCoord = null;
}
// If source node is not on grid remove it
if(!isCoordinateOnGrid(sourceCoord)) {
sourceCoord = null;
}
if(sourceCoord && controlledCoord) {
var colour;
if(canGetFromSourceToControlled(sourceCoord, controlledCoord))
{
// Valid placement
colour = VALID_LIGHT_COLOUR;
ocargo.drawing.setTrafficLightImagePosition(sourceCoord, controlledCoord, image);
}
else
{
// Invalid placement
colour = INVALID_LIGHT_COLOUR;
}
mark(controlledCoord, colour, 0.7, false);
mark(sourceCoord, colour, 0.7, false);
}
}
function onDragStart(x, y) {
moved = false;
scaling = getScaling(image);
rotation = (image.matrix.split().rotate + 360) % 360;
var bBox = image.getBBox();
imageWidth = bBox.width;
imageHeight = bBox.height;
paperWidth = GRID_WIDTH * GRID_SPACE_SIZE;
paperHeight = GRID_HEIGHT * GRID_SPACE_SIZE;
var paperPosition = $('#paper').position();
var mouseX = x - paperPosition.left;
var mouseY = y - paperPosition.top;
originX = mouseX - imageWidth/2;
originY = mouseY - imageHeight/2;
}
function onDragEnd() {
if(moved) {
// Unmark squares currently occupied
if(sourceCoord) {
markAsBackground(sourceCoord);
}
if(controlledCoord) {
markAsBackground(controlledCoord);
}
if(originNode) {
markAsOrigin(originNode.coordinate);
}
if(destinationNode) {
markAsDestination(destinationNode.coordinate);
}
// Add back to the list of traffic lights if on valid nodes
if(canGetFromSourceToControlled(sourceCoord, controlledCoord)) {
var sourceIndex = ocargo.Node.findNodeIndexByCoordinate(sourceCoord, nodes);
var controlledIndex = ocargo.Node.findNodeIndexByCoordinate(controlledCoord, nodes);
trafficLight.valid = true;
trafficLight.sourceNode = sourceIndex;
trafficLight.controlledNode = controlledIndex;
ocargo.drawing.setTrafficLightImagePosition(sourceCoord, controlledCoord, image);
}
}
image.attr({'cursor':'pointer'});
}
image.drag(onDragMove, onDragStart, onDragEnd);
image.dblclick(function() {
image.transform('...r90');
});
image.click(function() {
if(mode === DELETE_DECOR_MODE) {
trafficLight.destroy();
}
});
function getScaling(object) {
var transform = object.transform();
for(var i = 0; i < transform.length; i++) {
if(transform[i][0] === 's') {
return transform[i][1] + ',' + transform[i][2];
}
}
return "0,0";
}
function canGetFromSourceToControlled(sourceCoord, controlledCoord) {
var sourceNode = ocargo.Node.findNodeByCoordinate(sourceCoord, nodes);
var controlledNode = ocargo.Node.findNodeByCoordinate(controlledCoord, nodes);
if(sourceNode && controlledNode) {
for(var i = 0; i < sourceNode.connectedNodes.length; i++) {
if(sourceNode.connectedNodes[i] === controlledNode) {
return true;
}
}
}
return false;
}
}
/********************************/
/* Miscaellaneous state methods */
/********************************/
function initialiseVisited() {
var visited = new Array(10);
for (var i = 0; i < 10; i++) {
visited[i] = new Array(8);
}
return visited;
}
function createGrid() {
grid = ocargo.drawing.renderGrid(currentTheme);
for(var i = 0; i < grid.length; i++) {
for(var j = 0; j < grid[i].length; j++) {
grid[i][j].node.onmousedown = handleMouseDown(grid[i][j]);
grid[i][j].node.onmouseover = handleMouseOver(grid[i][j]);
grid[i][j].node.onmouseout = handleMouseOut(grid[i][j]);
grid[i][j].node.onmouseup = handleMouseUp(grid[i][j]);
grid[i][j].node.ontouchstart = handleMouseDown(grid[i][j]);
grid[i][j].node.ontouchmove = handleMouseOver(grid[i][j]);
grid[i][j].node.ontouchend = handleMouseUp(grid[i][j]);
}
}
}
function finaliseDelete(strikeEnd) {
applyAlongStrike(deleteNode, strikeEnd);
strikeStart = null;
// Delete any nodes isolated through deletion
for (var i = nodes.length - 1; i >= 0; i--) {
if (nodes[i].connectedNodes.length === 0) {
var coordinate = nodes[i].coordinate;
deleteNode(coordinate.x, coordinate.y);
}
}
function deleteNode(x, y) {
var coord = new ocargo.Coordinate(x, y);
var node = ocargo.Node.findNodeByCoordinate(coord, nodes);
if(node) {
// Remove all the references to the node we're removing.
for (var i = node.connectedNodes.length - 1; i >= 0; i--) {
node.removeDoublyConnectedNode(node.connectedNodes[i]);
}
var index = nodes.indexOf(node);
nodes.splice(index, 1);
}
// Check if start or destination node
if(isOriginCoordinate(coord)) {
markAsBackground(originNode.coordinate);
originNode = null;
}
if(isDestinationCoordinate(coord)) {
markAsBackground(destinationNode.coordinate);
destinationNode = null;
}
}
}
function finaliseMove(strikeEnd) {
applyAlongStrike(addNode, strikeEnd);
strikeStart = null;
var previousNode = null;
function addNode(x, y) {
var coord = new ocargo.Coordinate(x,y);
var node = ocargo.Node.findNodeByCoordinate(coord, nodes);
if (!node) {
node = new ocargo.Node(coord);
nodes.push(node);
}
else
{
// If we've overwritten the origin node remove it as
// we can no longer place the CFC there
if(node === originNode) {
markAsBackground(originNode.coordinate);
originNode = null;
}
}
// Now connect it up with it's new neighbours
if(previousNode && node.connectedNodes.indexOf(previousNode) === -1) {
node.addConnectedNodeWithBacklink(previousNode);
}
previousNode = node;
}
}
function applyAlongStrike(func, strikeEnd) {
var x, y;
if (strikeStart.x === strikeEnd.x && strikeStart.y === strikeEnd.y) {
return;
}
if (strikeStart.x <= strikeEnd.x) {
for (x = strikeStart.x; x <= strikeEnd.x; x++) {
func(x, strikeStart.y);
}
}
else {
for (x = strikeStart.x; x >= strikeEnd.x; x--) {
func(x, strikeStart.y);
}
}
if (strikeStart.y <= strikeEnd.y) {
for (y = strikeStart.y + 1; y <= strikeEnd.y; y++) {
func(strikeEnd.x, y);
}
}
else {
for (y = strikeStart.y - 1; y >= strikeEnd.y; y--) {
func(strikeEnd.x, y);
}
}
}
function findTrafficLight(firstIndex, secondIndex) {
var light;
for (var i = 0; i < trafficLights.length; i++) {
light = trafficLights[i];
if (light.node === firstIndex && light.sourceNode === secondIndex) {
return i;
}
}
return -1;
}
function setTheme(theme) {
currentTheme = theme;
for (var x = 0; x < GRID_WIDTH; x++) {
for (var y = 0; y < GRID_HEIGHT; y++) {
grid[x][y].attr({stroke: theme.border});
}
}
for (var i = 0; i < decor.length; i++) {
decor[i].updateTheme();
}
$('.decor_button').each(function(index, element) {
element.src = theme.decor[element.id].url;
});
$('#wrapper').css({'background-color': theme.background});
}
function sortNodes(nodes) {
for (var i = 0; i < nodes.length; i++) {
// Remove duplicates.
var newConnected = [];
for (var j = 0; j < nodes[i].connectedNodes.length; j++) {
if (newConnected.indexOf(nodes[i].connectedNodes[j]) === -1) {
newConnected.push(nodes[i].connectedNodes[j]);
}
}
nodes[i].connectedNodes.sort(function(a, b) {
return comparator(a, b, nodes[i]);
}).reverse();
}
function comparator(node1, node2, centralNode) {
var a1 = ocargo.calculateNodeAngle(centralNode, node1);
var a2 = ocargo.calculateNodeAngle(centralNode, node2);
if (a1 < a2) {
return -1;
} else if (a1 > a2) {
return 1;
} else {
return 0;
}
}
}
/**********************************/
/* Loading/saving/sharing methods */
/**********************************/
function extractState() {
var state = {};
// Create node data
sortNodes(nodes);
state.path = JSON.stringify(ocargo.Node.composePathData(nodes));
// Create traffic light data
var trafficLightData = [];
var i;
for(i = 0; i < trafficLights.length; i++) {
var tl = trafficLights[i];
if(tl.valid) {
trafficLightData.push(tl.getData());
}
}
state.traffic_lights = JSON.stringify(trafficLightData);
// Create block data
var blockData = [];
for(i = 0; i < BLOCKS.length; i++) {
var type = BLOCKS[i];
if($('#' + type + "_checkbox").is(':checked')) {
blockData.push(type);
}
}
state.block_types = JSON.stringify(blockData);
// Create decor data
var decorData = [];
for(i = 0; i < decor.length; i++) {
decorData.push(decor[i].getData());
}
state.decor = JSON.stringify(decorData);
// Create other data
if(destinationNode) {
var destinationCoord = destinationNode.coordinate;
state.destinations = JSON.stringify([[destinationCoord.x, destinationCoord.y]]);
}
state.max_fuel = $('#max_fuel').val();
state.themeID = currentTheme.id;
state.character_name = CHARACTER_NAME;
return state;
}
function restoreState(state) {
clear();
// Load node data
nodes = ocargo.Node.parsePathData(JSON.parse(state.path));
// Load traffic light data
var trafficLightData = JSON.parse(state.traffic_lights);
for(var i = 0; i < trafficLightData.length; i++) {
new InternalTrafficLight(trafficLightData[i]);
}
// Load other data
originNode = nodes[0];
// TODO needs to be fixed in the long term with multiple destinations
if(state.destinations) {
var destinationList = JSON.parse(state.destinations)[0];
var destinationCoordinate = new ocargo.Coordinate(destinationList[0],
destinationList[1]);
destinationNode = ocargo.Node.findNodeByCoordinate(destinationCoordinate, nodes);
}
drawAll();
var themeID = state.themeID;
for(var theme in THEMES) {
if(THEMES[theme]['id'] === themeID) {
setTheme(THEMES[theme]);
}
}
// Load in the decor data
var decorData = JSON.parse(state.decor);
for(var i = 0; i < decorData.length; i++) {
var decorObject = new InternalDecor(decorData[i].name);
decorObject.setCoordinate(decorData[i].coordinate);
}
}
function loadLevel(levelID) {
ocargo.saving.retrieveLevel(levelID, function(err, level) {
if (err != null) {
console.debug(err);
return;
}
restoreState(level);
});
}
function saveLevel(name, levelID) {
var level = extractState();
level.name = name;
ocargo.saving.saveLevel(level, levelID, function(err, newLevelID) {
if (err != null) {
console.debug(err);
return;
}
// Delete name so that we can use if for comparison purposes
// to see if changes have been made to the level later on
delete level.name;
savedState = JSON.stringify(level);
savedLevelID = newLevelID;
ocargo.Drawing.startPopup("Saving","",ocargo.messages.saveSuccesful);
});
}
function shareLevel(recipient) {
ocargo.saving.shareLevel(savedLevelID, function(error) {
if(err) {
console.debug(error);
return;
}
ocargo.Drawing.startPopup("Saving","",ocargo.messages.shareSuccesful(recipient.name));
});
}
function storeStateInLocalStorage() {
if(localStorage) {
var state = extractState();
// Append additional non-level orientated editor state
state.savedLevelID = savedLevelID;
state.savedState = savedState;
localStorage['levelEditorState'] = JSON.stringify(state);
}
}
function retrieveStateFromLocalStorage() {
if(localStorage) {
var state = JSON.parse(localStorage['levelEditorState']);
if(state) {
restoreState(state);
}
// Restore additional non-level orientated editor state
savedLevelID = state.savedLevelID;
savedState = state.savedState;
}
}
function isLevelValid() {
// Check to see if start and end nodes have been marked
if (!originNode || !destinationNode) {
ocargo.Drawing.startPopup(ocargo.messages.ohNo,
ocargo.messages.noStartOrEndSubtitle,
ocargo.messages.noStartOrEnd);
return false;
}
// Check to see if path exists from start to end
var destination = new ocargo.Destination(0, destinationNode);
var pathToDestination = getOptimalPath(nodes, [destination]);
if (pathToDestination.length === 0) {
ocargo.Drawing.startPopup(ocargo.messages.somethingWrong,
ocargo.messages.noStartEndRouteSubtitle,
ocargo.messages.noStartEndRoute);
return false;
}
return true;
}
function isLevelSaved() {
var currentState = JSON.stringify(extractState());
if(!savedState) {
ocargo.Drawing.startPopup("Sharing", "", ocargo.messages.notSaved);
return false;
}
else if(currentState !== savedState) {
ocargo.Drawing.startPopup("Sharing", "", ocargo.messages.changesSinceLastSave);
return false;
}
return true;
}
/*****************************************/
/* Internal traffic light representation */
/*****************************************/
function InternalTrafficLight(data) {
// public methods
this.getData = function() {
if(!this.valid) {
throw "Error: cannot create actual traffic light from invalid internal traffic light!";
}
return {"redDuration": this.redDuration, "greenDuration": this.greenDuration,
"sourceNode": this.sourceNode, "controlledNode": this.controlledNode,
"startTime": this.startTime, "startingState": this.startingState};
};
this.destroy = function() {
this.image.remove();
var index = trafficLights.indexOf(this);
if(index !== -1) {
trafficLights.splice(index, 1);
}
};
// data
this.redDuration = data.redDuration;
this.greenDuration = data.greenDuration;
this.startTime = data.startTime;
this.startingState = data.startingState;
this.controlledNode = data.controlledNode;
this.sourceNode = data.sourceNode;
this.valid = false;
var imgStr = this.startingState === ocargo.TrafficLight.RED ? LIGHT_RED_URL : LIGHT_GREEN_URL;
this.image = ocargo.drawing.createTrafficLightImage(imgStr);
this.image.transform('...s-1,1');
if(this.controlledNode !== -1 && this.sourceNode !== -1) {
var sourceCoord = nodes[this.sourceNode].coordinate;
var controlledCoord = nodes[this.controlledNode].coordinate;
this.valid = true;
ocargo.drawing.setTrafficLightImagePosition(sourceCoord, controlledCoord, this.image);
}
setupTrafficLightListeners(this);
this.image.attr({'cursor':'pointer'});
trafficLights.push(this);
}
/*********************************/
/* Internal decor representation */
/*********************************/
function InternalDecor(name) {
// public methods
this.getData = function() {
var bBox = this.image.getBBox();
return {'coordinate': new ocargo.Coordinate(Math.floor(bBox.x),
PAPER_HEIGHT - bBox.height - Math.floor(bBox.y)),
'name': this.name};
};
this.setCoordinate = function(coordinate) {
this.image.transform('t' + coordinate.x + ',' + coordinate.y);
};
this.updateTheme = function() {
var description = currentTheme.decor[this.name];
var newImage = ocargo.drawing.createImage(description.url, 0, 0, description.width,
description.height);
if(this.image) {
newImage.transform(this.image.matrix.toTransformString());
this.image.remove();
}
this.image = newImage;
this.image.attr({'cursor':'pointer'});
setupDecorListeners(this);
};
this.destroy = function() {
this.image.remove();
var index = decor.indexOf(this);
if(index !== -1) {
decor.splice(index, 1);
}
};
// data
this.name = name;
this.image = null;
this.updateTheme();
decor.push(this);
}
};
/******************/
/* Initialisation */
/******************/
$(function() {
new ocargo.LevelEditor();
});
| game/static/game/js/level_editor.js | 'use strict';
var ocargo = ocargo || {};
ocargo.LevelEditor = function() {
/*************/
/* Constants */
/*************/
var LIGHT_RED_URL = '/static/game/image/trafficLight_red.svg';
var LIGHT_GREEN_URL = '/static/game/image/trafficLight_green.svg';
var VALID_LIGHT_COLOUR = '#87E34D';
var INVALID_LIGHT_COLOUR = '#E35F4D';
var ADD_ROAD_MODE = 'Add road';
var DELETE_ROAD_MODE = 'Delete road';
var MARK_DESTINATION_MODE = 'Mark destination';
var MARK_ORIGIN_MODE = 'Mark origin';
var DELETE_DECOR_MODE = 'Delete decor';
/*********/
/* State */
/*********/
ocargo.saving = new ocargo.Saving();
ocargo.drawing = new ocargo.Drawing();
// Level information
var nodes = [];
var decor = [];
var trafficLights = [];
var originNode = null;
var destinationNode = null;
var currentTheme = THEMES["grass"];
// Reference to the Raphael elements for each square
var grid = initialiseVisited();
// Current mode the user is in
var mode = ADD_ROAD_MODE;
// Holds the state for when the user is drawing or deleting roads
var strikeStart = null;
// holds the state to do with saving
var savedState = null;
var savedLevelID = -1;
// so that we store the current state when the page unloads
window.addEventListener('unload', storeStateInLocalStorage);
// setup the toolbox
setupToolbox();
// If there's any previous state in local storage retrieve it
retrieveStateFromLocalStorage();
// initialises paper
drawAll();
// set the default theme
setTheme(THEMES["grass"]);
/***************/
/* Setup tools */
/***************/
// Sets up the left hand side toolbox (listeners/images etc.)
function setupToolbox() {
var tabs = [];
var currentTabSelected = null;
tabs['play'] = new ocargo.Tab($('#play_radio'), $('#play_radio + label'));
tabs['map'] = new ocargo.Tab($('#map_radio'), $('#map_radio + label'), $('#map_pane'));
tabs['decor'] = new ocargo.Tab($('#decor_radio'), $('#decor_radio + label'), $('#decor_pane'));
tabs['character'] = new ocargo.Tab($('#character_radio'), $('#character_radio + label'), $('#character_pane'));
tabs['blocks'] = new ocargo.Tab($('#blocks_radio'), $('#blocks_radio + label'), $('#blocks_pane'));
tabs['random'] = new ocargo.Tab($('#random_radio'), $('#random_radio + label'), $('#random_pane'));
tabs['load'] = new ocargo.Tab($('#load_radio'), $('#load_radio + label'), $('#load_pane'));
tabs['save'] = new ocargo.Tab($('#save_radio'), $('#save_radio + label'), $('#save_pane'));
tabs['share'] = new ocargo.Tab($('#share_radio'), $('#share_radio + label'), $('#share_pane'));
tabs['help'] = new ocargo.Tab($('#help_radio'), $('#help_radio + label'), $('#help_pane'));
tabs['quit'] = new ocargo.Tab($('#quit_radio'), $('#quit_radio + label'));
setupPlayTab();
setupMapTab();
setupDecorTab();
setupCharacterTab();
setupBlocksTab();
setupRandomTab();
setupLoadTab();
setupSaveTab();
setupShareTab();
setupHelpTab();
setupQuitTab();
// enable the map tab by default
currentTabSelected = tabs['map'];
tabs['map'].select();
function setupPlayTab() {
tabs['play'].setOnChange(function() {
if(isLevelSaved()) {
window.location.href = "/game/" + savedLevelID;
}
else {
currentTabSelected.select();
};
})
}
function setupMapTab() {
tabs['map'].setOnChange(function() {
transitionTab(tabs['map']);
});
$('#clear').click(function() {
new ocargo.LevelEditor();
});
$('#start').click(function() {
mode = MARK_ORIGIN_MODE;
});
$('#end').click(function() {
mode = MARK_DESTINATION_MODE;
});
$('#add_road').click(function() {
mode = ADD_ROAD_MODE;
});
$('#delete_road').click(function() {
mode = DELETE_ROAD_MODE;
});
}
function setupDecorTab() {
tabs['decor'].setOnChange(function() {
transitionTab(tabs['decor']);
});
$('#theme_select').change(function() {
setTheme(THEMES[$(this).val()]);
});
$('#bush').click(function() {
new InternalDecor('bush');
});
$('#tree1').click(function() {
new InternalDecor('tree1');
});
$('#tree2').click(function() {
new InternalDecor('tree2');
});
$('#pond').click(function() {
new InternalDecor('pond');
});
$('#trafficLightRed').click(function() {
new InternalTrafficLight({"redDuration": 3, "greenDuration": 3, "startTime": 0,
"startingState": ocargo.TrafficLight.RED,
"controlledNode": -1, "sourceNode": -1});
});
$('#trafficLightGreen').click(function() {
new InternalTrafficLight({"redDuration": 3, "greenDuration": 3, "startTime": 0,
"startingState": ocargo.TrafficLight.GREEN,
"controlledNode": -1, "sourceNode": -1});
});
$('#delete_decor').click(function() {
mode = DELETE_DECOR_MODE;
});
}
function setupCharacterTab() {
tabs['character'].setOnChange(function() {
transitionTab(tabs['character']);
});
$('#Van_radio').prop("checked", true);
$("#character-form").on('change', ':input', function() {
CHARACTER_NAME = $('input:checked', '#character-form').val();
redrawRoad();
});
}
function setupBlocksTab() {
tabs['blocks'].setOnChange(function() {
transitionTab(tabs['blocks']);
});
// Hacky, if a way can be found without initialising the entire work space that would be great!
// Initial selection
$('#move_forwards_checkbox').prop('checked', true);
$('#turn_left_checkbox').prop('checked', true);
$('#turn_right_checkbox').prop('checked', true);
// Select all functionality
var selectAll = $('#select_all_checkbox');
selectAll.change(function() {
var checked = selectAll.prop('checked');
$('.block_checkbox').each(function() {
if($(this) !== selectAll) {
$(this).prop('checked', checked);
}
})
})
// Setup the block images
function addListenerToImage(type) {
$('#' + type + '_image').click(function() {
$('#' + type + '_checkbox').click();
});
}
initCustomBlocksDescription();
var blockly = document.getElementById('blockly');
var toolbox = document.getElementById('toolbox');
Blockly.inject(blockly, {
path: '/static/game/js/blockly/',
toolbox: toolbox,
trashcan: true
});
for(var i = 0; i < BLOCKS.length; i++) {
var type = BLOCKS[i];
var block = Blockly.Block.obtain(Blockly.mainWorkspace, type);
block.initSvg();
block.render();
var svg = block.getSvgRoot();
var large = type === "controls_whileUntil" ||
type === "controls_repeat" ||
type === "controls_if" ||
type === "declare_proc";
var content = '<svg class="block_image' + (large ? ' large' : '') + '">';
content += '<g transform="translate(10,0)"';
content += svg.innerHTML + '</g></svg>';
$('#' + type + '_image').html(content);
addListenerToImage(type);
}
$('#blockly').css('display','none');
}
function setupRandomTab() {
tabs['random'].setOnChange(function() {
transitionTab(tabs['random']);
});
$('#generate').click(function() {
var data = {numberOfTiles: $('#size').val(),
branchiness: $('#branchiness').val()/10,
loopiness: $('#loopiness').val()/10,
curviness: $('#curviness').val()/10,
trafficLightsEnabled: true,
csrfmiddlewaretoken: $("#csrfmiddlewaretoken").val()};
ocargo.saving.retrieveRandomLevel(data, function(error, mapData) {
if(error) {
console.debug(error);
ocargo.Drawing.startPopup("Error","",ocargo.messages.internetDown);
return;
}
clear();
var path = JSON.parse(mapData.path);
var i;
for (i = 0; i < path.length; i++) {
var node = new ocargo.Node(new ocargo.Coordinate(path[i].coordinate[0],
path[i].coordinate[1]));
nodes.push(node);
}
for (i = 0; i < path.length; i++) {
nodes[i].connectedNodes = [];
for(var j = 0; j < path[i].connectedNodes.length; j++) {
nodes[i].connectedNodes.push(nodes[path[i].connectedNodes[j]]);
}
}
// TODO add in support for multiple destinations
var destination = JSON.parse(mapData.destinations)[0];
var destinationCoord = new ocargo.Coordinate(destination[0], destination[1]);
destinationNode = ocargo.Node.findNodeByCoordinate(destinationCoord, nodes);
originNode = nodes[0];
var tls = JSON.parse(mapData.traffic_lights);
for(i = 0; i < tls.length; i++) {
new InternalTrafficLight(tls[i]);
}
drawAll();
});
});
}
function setupLoadTab() {
var selectedLevel = null;
tabs['load'].setOnChange(function() {
ocargo.saving.retrieveListOfLevels(function(err, ownLevels, sharedLevels) {
if (err != null) {
console.debug(err);
currentTabSelected.select();
ocargo.Drawing.startPopup("Error","",ocargo.messages.internetDown);
return;
}
populateLoadSaveTable("loadOwnLevelTable", ownLevels);
// Add click listeners to all rows
$('#loadOwnLevelTable tr').on('click', function(event) {
$('#loadOwnLevelTable tr').css('background-color', '#FFFFFF');
$('#loadSharedLevelTable tr').css('background-color', '#FFFFFF');
$(this).css('background-color', '#C0C0C0');
$('#loadLevel').removeAttr('disabled');
$('#deleteLevel').removeAttr('disabled');
selectedLevel = $(this).attr('value');
});
populateLoadSaveTable("loadSharedLevelTable", sharedLevels);
// Add click listeners to all rows
$('#loadSharedLevelTable tr').on('click', function(event) {
$('#loadOwnLevelTable tr').css('background-color', '#FFFFFF');
$('#loadSharedLevelTable tr').css('background-color', '#FFFFFF');
$(this).css('background-color', '#C0C0C0');
$('#loadLevel').removeAttr('disabled');
$('#deleteLevel').removeAttr('disabled');
selectedLevel = $(this).attr('value');
});
// But disable all the modal buttons as nothing is selected yet
selectedLevel = null;
$('#loadLevel').attr('disabled', 'disabled');
$('#deleteLevel').attr('disabled', 'disabled');
transitionTab(tabs['load']);
});
});
// Setup own/shared levels radio
$('#own_levels_radio').change(function() {
$('#loadOwnLevelTable').css('display','table');
$('#loadSharedLevelTable').css('display','none');
});
$('#shared_levels_radio').change(function() {
$('#loadOwnLevelTable').css('display','none');
$('#loadSharedLevelTable').css('display','table');
});
$('#own_levels_radio').change();
$('#loadLevel').click(function() {
if(selectedLevel) {
loadLevel(selectedLevel);
}
});
$('#deleteLevel').click(function() {
if(!selectedLevel) {
return;
}
ocargo.saving.deleteLevel(selectedLevel, function(err) {
if (err != null) {
console.debug(err);
return;
}
$('#loadOwnLevelTable tr[value=' + selectedLevel + ']').remove();
selectedLevel = null;
});
});
}
function setupSaveTab() {
var selectedLevel = null;
tabs['save'].setOnChange(function () {
if(!isLevelValid()) {
currentTabSelected.select();
return;
}
ocargo.saving.retrieveListOfLevels(function(err, ownLevels, sharedLevels) {
if (err != null) {
console.debug(err);
ocargo.Drawing.startPopup("Error","",ocargo.messages.internetDown);
return;
}
populateLoadSaveTable("saveLevelTable", ownLevels);
// Add click listeners to all rows
$('#saveLevelTable tr').on('click', function(event) {
var rowSelected = $(event.target.parentElement);
$('#saveLevelTable tr').css('background-color', '#FFFFFF');
rowSelected.css('background-color', '#C0C0C0');
$('#saveLevel').removeAttr('disabled');
selectedLevel = parseInt(rowSelected.attr('value'));
for(var i = 0; i < ownLevels.length; i++) {
if(ownLevels[i].id === selectedLevel) {
$("#levelNameInput").val(ownLevels[i].name);
}
}
});
transitionTab(tabs['save']);
selectedLevel = null;
});
});
$('#saveLevel').click(function() {
var newName = $('#levelNameInput').val();
if (!newName || newName === "") {
// TODO error message?
return;
}
// Test to see if we already have the level saved
var table = $("#saveLevelTable");
var existingID = -1;
for (var i = 0; i < table[0].rows.length; i++) {
var row = table[0].rows[i];
var existingName = row.cells[0].innerHTML;
if (existingName === newName) {
existingID = row.getAttribute('value');
break;
}
}
if(existingID != -1) {
if(existingID != savedLevelID) {
var onYes = function() {
saveLevel(newName, existingID);
}
//ocargo.Drawing.startPopup("Overwriting","Warning",ocargo.messages.saveOverwriteWarning(newName, onYes));
saveLevel(newName, existingID)
}
else {
saveLevel(newName, existingID)
}
}
else {
saveLevel(newName, null);
}
});
}
function setupShareTab() {
tabs['share'].setOnChange(function() {
if(!isLevelSaved()) {
currentTabSelected.select();
return;
}
ocargo.saving.getSharingInformation(savedLevelID, function(error, recipientData, role) {
if(error !== null) {
console.debug(error);
ocargo.Drawing.startPopup("Error","",ocargo.messages.internetDown);
return;
}
if(role !== "student" && role !== 'teacher') {
ocargo.Drawing.startPopup("Not logged in", "", ocargo.messages.notLoggedIn);
currentTabSelected.select();
return;
}
if(role === "student") {
$('#teacher_sharing').css('display','none');
$('#student_sharing').css('display','block');
var classmates = recipientData.validRecipients.classmates;
var teacher = recipientData.validRecipients.teacher;
populateSharingTable(classmates, teacher);
}
else if(role == "teacher") {
$('#teacher_sharing').css('display','block');
$('#student_sharing').css('display','none');
var teachers = recipientData.validRecipients.teachers;
var classes = recipientData.validRecipients.classes;
$('teacher_select').empty();
for(var i = 0; i < teachers.length; i++) {
var teacher = teachers[i]
var item = '<option value=' + teacher.id + '>' + teacher.name + '</option>';
$('#teacher_select').append(item);
}
}
transitionTab(tabs['share']);
});
});
$('#teachers_radio').change(function() {
$('#class_selection').css('display','none');
$('#teacher_selection').css('display','block');
});
$('#classes_radio').change(function() {
$('#class_selection').css('display','block');
$('#teacher_selection').css('display','none');
});
$('#classes_radio').change();
$('#share').click(function() {
var recipientID;
if($('#pupil_sharing').css('display') === 'block') {
recipientID = $('#user_select option').is('selected').attr('value')
}
else {
if($('#class_selection').css('display') === 'block') {
recipientID = $('#student_select option').is('selected').attr('value')
}
else {
recipientID = $('#teacher_select option').is('selected').attr('value')
}
}
shareLevel(levelID, recipients);
});
$('#unshare').click(function() {
console.log("Unshare!");
});
}
function setupHelpTab() {
tabs['help'].setOnChange(function() {
transitionTab(tabs['help']);
});
$('#help.tab_pane').html(ocargo.messages.levelEditorHelpText);
}
function setupQuitTab() {
tabs['quit'].setOnChange(function() {
window.location.href = "/game/";
});
}
// Helper methods
function transitionTab(newTab) {
currentTabSelected.setPaneEnabled(false);
newTab.setPaneEnabled(true);
currentTabSelected = newTab;
}
function populateLoadSaveTable(tableName, levels) {
var table = $('#'+tableName);
// Remove click listeners to avoid memory leak and remove all rows
$('#'+tableName+' tr').off('click');
table.empty();
// Order them alphabetically
levels.sort(function(a, b) {
if (a.name < b.name) {
return -1;
}
else if (a.name > b.name) {
return 1;
}
return 0;
});
// Add a row to the table for each workspace saved in the database
table.append('<tr> <th>Name</th> <th>Owner</th> <th>Shared</th> </tr>');
for (var i = 0, ii = levels.length; i < ii; i++) {
var level = levels[i];
table.append('<tr value=' + level.id + '> <td>' + level.name + '</td> <td>' +
level.owner + '</td> <td>false</td>');
}
}
function populateSharingTable(mainRecipients, specialRecipient) {
// Remove click listeners to avoid memory leak and remove all rows
var table = $('#levelSharingTable');
$('#levelSharingTable tr').off('click');
table.empty();
table.append('<tr> <th>Name</th> <th>Shared</th> </tr>');
if(specialRecipient) {
table.append('<tr value=' + specialRecipient.id + '>' +
'<td>' + specialRecipient.name + '</td>' +
'<td>' + specialRecipient.shared + '</td>' +
'</tr>');
}
// Order them alphabetically
mainRecipients.sort(function(a, b) {
if (a.name < b.name) {
return -1;
}
else if (a.name > b.name) {
return 1;
}
return 0;
});
// Add a row to the table for each workspace saved in the database
for (var i = 0; i < mainRecipients.length; i++) {
var recipient = mainRecipients[i];
table.append('<tr value=' + recipient.id + '>' +
'<td>' + recipient.name + '</td>' +
'<td>' + "Yes" + '</td>' +
'</tr>');
}
}
}
/************************/
/** Current state tests */
/************************/
// Functions simply to improve readability of complex conditional code
function isOriginCoordinate(coordinate) {
return originNode && originNode.coordinate.equals(coordinate);
}
function isDestinationCoordinate(coordinate) {
return destinationNode && destinationNode.coordinate.equals(coordinate);
}
function isCoordinateOnGrid(coordinate) {
return coordinate.x >= 0 && coordinate.x < GRID_WIDTH && coordinate.y >= 0 && coordinate.y < GRID_HEIGHT;
}
function canPlaceCFC(node) {
return node.connectedNodes.length <= 1;
}
/*************/
/* Rendering */
/*************/
function clear() {
for(var i = 0; i < trafficLights.length; i++) {
trafficLights[i].destroy();
}
trafficLights = [];
decor = [];
nodes = [];
grid = initialiseVisited();
strikeStart = null;
originNode = null;
destinationNode = null;
ocargo.drawing.clearPaper();
}
function drawAll() {
createGrid(paper);
redrawRoad();
}
function redrawRoad() {
ocargo.drawing.renderRoad(nodes);
clearMarkings();
bringTrafficLightsToFront();
bringDecorToFront();
}
function bringDecorToFront() {
for (var i = 0; i < decor.length; i++) {
decor[i].image.toFront();
}
}
function bringTrafficLightsToFront() {
for(var i = 0; i < trafficLights.length; i++) {
trafficLights[i].image.toFront();
}
}
/************/
/* Marking */
/************/
// Methods for highlighting squares
function mark(coordMap, colour, opacity, occupied) {
var coordPaper = ocargo.Drawing.translate(coordMap);
var element = grid[coordPaper.x][coordPaper.y];
element.attr({fill:colour, "fill-opacity": opacity});
}
function markAsOrigin(coordinate) {
mark(coordinate, 'red', 0.7, true);
}
function markAsDestination(coordinate) {
mark(coordinate, 'blue', 0.7, true);
}
function markAsBackground(coordinate) {
mark(coordinate, currentTheme.background, 0, false);
}
function markAsSelected(coordinate) {
mark(coordinate, currentTheme.selected, 1, true);
}
function markAsHighlighted(coordinate) {
mark(coordinate, currentTheme.selected, 0.3, true);
}
function clearMarkings() {
for (var i = 0; i < GRID_WIDTH; i++) {
for (var j = 0; j < GRID_HEIGHT; j++) {
markAsBackground(new ocargo.Coordinate(i,j));
grid[i][j].toFront();
}
}
if(originNode) {
markAsOrigin(originNode.coordinate);
}
if(destinationNode) {
markAsDestination(destinationNode.coordinate);
}
bringTrafficLightsToFront();
bringDecorToFront();
}
function markTentativeRoad(currentEnd) {
clearMarkings();
applyAlongStrike(setup, currentEnd);
var previousNode = null;
function setup(x, y) {
var coordinate = new ocargo.Coordinate(x, y);
var node = new ocargo.Node(coordinate);
if(previousNode)
{
node.addConnectedNodeWithBacklink(previousNode);
}
previousNode = node;
markAsSelected(coordinate);
}
}
/***************************/
/* Paper interaction logic */
/***************************/
function handleMouseDown(this_rect) {
return function () {
var getBBox = this_rect.getBBox();
var coordPaper = new ocargo.Coordinate(getBBox.x / GRID_SPACE_SIZE,
getBBox.y / GRID_SPACE_SIZE);
var coordMap = ocargo.Drawing.translate(coordPaper);
var existingNode = ocargo.Node.findNodeByCoordinate(coordMap, nodes);
if(mode === MARK_ORIGIN_MODE && existingNode && canPlaceCFC(existingNode))
{
if (originNode) {
var prevStart = originNode.coordinate;
markAsBackground(prevStart);
}
// Check if same as destination node
if (isDestinationCoordinate(coordMap)) {
destinationNode = null;
}
markAsOrigin(coordMap);
var newStartIndex = ocargo.Node.findNodeIndexByCoordinate(coordMap, nodes);
// Putting the new start in the front of the nodes list.
var temp = nodes[newStartIndex];
nodes[newStartIndex] = nodes[0];
nodes[0] = temp;
originNode = nodes[0];
}
else if (mode === MARK_DESTINATION_MODE && existingNode)
{
if (destinationNode) {
var prevEnd = destinationNode.coordinate;
markAsBackground(prevEnd);
}
// Check if same as starting node
if (isOriginCoordinate(coordMap)) {
originNode = null;
}
markAsDestination(coordMap);
var newEnd = ocargo.Node.findNodeIndexByCoordinate(coordMap, nodes);
destinationNode = nodes[newEnd];
}
else if (mode === ADD_ROAD_MODE || mode === DELETE_ROAD_MODE) {
strikeStart = coordMap;
markAsSelected(coordMap);
}
};
}
function handleMouseOver(this_rect) {
return function() {
var getBBox = this_rect.getBBox();
var coordPaper = new ocargo.Coordinate(getBBox.x / 100, getBBox.y / 100);
var coordMap = ocargo.Drawing.translate(coordPaper);
if (mode === ADD_ROAD_MODE || mode === DELETE_ROAD_MODE)
{
if(strikeStart !== null)
{
markTentativeRoad(coordMap);
}
else if(!isOriginCoordinate(coordMap) && !isDestinationCoordinate(coordMap))
{
markAsHighlighted(coordMap);
}
}
else if(mode === MARK_ORIGIN_MODE || mode === MARK_DESTINATION_MODE)
{
var node = ocargo.Node.findNodeByCoordinate(coordMap, nodes);
if (node && destinationNode !== node && originNode !== node)
{
if(mode === MARK_DESTINATION_MODE)
{
mark(coordMap, 'blue', 0.3, true);
}
else if(canPlaceCFC(node))
{
mark(coordMap, 'red', 0.5, true);
}
}
}
};
}
function handleMouseOut(this_rect) {
return function() {
var getBBox = this_rect.getBBox();
var coordPaper = new ocargo.Coordinate(getBBox.x/GRID_SPACE_SIZE,
getBBox.y/GRID_SPACE_SIZE);
var coordMap = ocargo.Drawing.translate(coordPaper);
if(mode === MARK_ORIGIN_MODE || mode === MARK_DESTINATION_MODE)
{
var node = ocargo.Node.findNodeByCoordinate(coordMap, nodes);
if (node && destinationNode !== node && originNode !== node)
{
markAsBackground(coordMap);
}
}
else if(mode === ADD_ROAD_MODE || mode === DELETE_ROAD_MODE)
{
if(!isOriginCoordinate(coordMap) && !isDestinationCoordinate(coordMap))
{
markAsBackground(coordMap);
}
}
};
}
function handleMouseUp(this_rect) {
return function() {
if (mode === ADD_ROAD_MODE || mode === DELETE_ROAD_MODE) {
var getBBox = this_rect.getBBox();
var coordPaper = new ocargo.Coordinate(getBBox.x/GRID_SPACE_SIZE,
getBBox.y/GRID_SPACE_SIZE);
var coordMap = ocargo.Drawing.translate(coordPaper);
if (mode === DELETE_ROAD_MODE) {
finaliseDelete(coordMap);
}
else {
finaliseMove(coordMap);
}
sortNodes(nodes);
redrawRoad();
}
};
}
function setupDecorListeners(decor) {
var image = decor.image;
var originX;
var originY;
var paperX;
var paperY;
var paperWidth;
var paperHeight;
var imageWidth;
var imageHeight;
function onDragMove(dx, dy) {
paperX = dx + originX;
paperY = dy + originY;
// Stop it being dragged off the edge of the page
if(paperX < 0) {
paperX = 0;
}
else if(paperX + imageWidth > paperWidth) {
paperX = paperWidth - imageWidth;
}
if(paperY < 0) {
paperY = 0;
}
else if(paperY + imageHeight > paperHeight) {
paperY = paperHeight - imageHeight;
}
image.transform('t' + paperX + ',' + paperY);
}
function onDragStart(x, y) {
var bBox = image.getBBox();
imageWidth = bBox.width;
imageHeight = bBox.height;
var paperPosition = $('#paper').position();
originX = x - paperPosition.left - imageWidth/2;
originY = y - paperPosition.top - imageHeight/2;
paperWidth = GRID_WIDTH * GRID_SPACE_SIZE;
paperHeight = GRID_HEIGHT * GRID_SPACE_SIZE;
}
function onDragEnd() {
originX = paperX;
originY = paperY;
}
image.drag(onDragMove, onDragStart, onDragEnd);
image.click(function() {
if(mode === DELETE_DECOR_MODE) {
decor.destroy();
}
});
}
function setupTrafficLightListeners(trafficLight) {
var image = trafficLight.image;
// Position in map coordinates.
var sourceCoord;
var controlledCoord;
// Current position of the element in paper coordinates
var paperX;
var paperY;
// Where the drag started in paper coordinates
var originX;
var originY;
// Size of the paper
var paperWidth;
var paperHeight;
// Size of the image
var imageWidth;
var imageHeight;
// Orientation and rotation transformations
var scaling;
var rotation;
var moved = false;
function onDragMove(dx, dy) {
// Needs to be in onDragMove, not in onDragStart, to stop clicks triggering drag behaviour
trafficLight.valid = false;
image.attr({'cursor':'default'});
moved = dx !== 0 || dy !== 0;
// Update image's position
paperX = dx + originX;
paperY = dy + originY;
// Stop it being dragged off the edge of the page
if(paperX < 0) {
paperX = 0;
}
else if(paperX + imageWidth > paperWidth) {
paperX = paperWidth - imageWidth;
}
if(paperY < 0) {
paperY = 0;
}
else if(paperY + imageHeight > paperHeight) {
paperY = paperHeight - imageHeight;
}
// Adjust for the fact that we've rotated the image
if(rotation === 90 || rotation === 270) {
paperX += (imageWidth - imageHeight)/2;
paperY -= (imageWidth - imageHeight)/2;
}
// And perform the updatee
image.transform('t' + paperX + ',' + paperY + 'r' + rotation + 's' + scaling);
// Unmark the squares the light previously occupied
if(sourceCoord) {
markAsBackground(sourceCoord);
}
if(controlledCoord) {
markAsBackground(controlledCoord);
}
if(originNode) {
markAsOrigin(originNode.coordinate);
}
if(destinationNode) {
markAsDestination(destinationNode.coordinate);
}
// Now calculate the source coordinate
var box = image.getBBox();
var absX = (box.x + box.width/2) / GRID_SPACE_SIZE;
var absY = (box.y + box.height/2) / GRID_SPACE_SIZE;
switch(rotation) {
case 0:
absY += 0.5;
break;
case 90:
absX -= 0.5;
break;
case 180:
absY -= 0.5;
break;
case 270:
absX += 0.5;
break;
}
var x = Math.min(Math.max(0, Math.floor(absX)), GRID_WIDTH - 1);
var y = GRID_HEIGHT - Math.min(Math.max(0, Math.floor(absY)), GRID_HEIGHT - 1) - 1;
sourceCoord = new ocargo.Coordinate(x,y);
// Find controlled position in map coordinates
switch(rotation) {
case 0:
controlledCoord = new ocargo.Coordinate(sourceCoord.x, sourceCoord.y + 1);
break;
case 90:
controlledCoord = new ocargo.Coordinate(sourceCoord.x + 1, sourceCoord.y);
break;
case 180:
controlledCoord = new ocargo.Coordinate(sourceCoord.x, sourceCoord.y - 1);
break;
case 270:
controlledCoord = new ocargo.Coordinate(sourceCoord.x - 1, sourceCoord.y);
break;
}
// If controlled node is not on grid, remove it
if(!isCoordinateOnGrid(controlledCoord)) {
controlledCoord = null;
}
// If source node is not on grid remove it
if(!isCoordinateOnGrid(sourceCoord)) {
sourceCoord = null;
}
if(sourceCoord && controlledCoord) {
var colour;
if(canGetFromSourceToControlled(sourceCoord, controlledCoord))
{
// Valid placement
colour = VALID_LIGHT_COLOUR;
ocargo.drawing.setTrafficLightImagePosition(sourceCoord, controlledCoord, image);
}
else
{
// Invalid placement
colour = INVALID_LIGHT_COLOUR;
}
mark(controlledCoord, colour, 0.7, false);
mark(sourceCoord, colour, 0.7, false);
}
}
function onDragStart(x, y) {
moved = false;
scaling = getScaling(image);
rotation = (image.matrix.split().rotate + 360) % 360;
var bBox = image.getBBox();
imageWidth = bBox.width;
imageHeight = bBox.height;
paperWidth = GRID_WIDTH * GRID_SPACE_SIZE;
paperHeight = GRID_HEIGHT * GRID_SPACE_SIZE;
var paperPosition = $('#paper').position();
var mouseX = x - paperPosition.left;
var mouseY = y - paperPosition.top;
originX = mouseX - imageWidth/2;
originY = mouseY - imageHeight/2;
}
function onDragEnd() {
if(moved) {
// Unmark squares currently occupied
if(sourceCoord) {
markAsBackground(sourceCoord);
}
if(controlledCoord) {
markAsBackground(controlledCoord);
}
if(originNode) {
markAsOrigin(originNode.coordinate);
}
if(destinationNode) {
markAsDestination(destinationNode.coordinate);
}
// Add back to the list of traffic lights if on valid nodes
if(canGetFromSourceToControlled(sourceCoord, controlledCoord)) {
var sourceIndex = ocargo.Node.findNodeIndexByCoordinate(sourceCoord, nodes);
var controlledIndex = ocargo.Node.findNodeIndexByCoordinate(controlledCoord, nodes);
trafficLight.valid = true;
trafficLight.sourceNode = sourceIndex;
trafficLight.controlledNode = controlledIndex;
ocargo.drawing.setTrafficLightImagePosition(sourceCoord, controlledCoord, image);
}
}
image.attr({'cursor':'pointer'});
}
image.drag(onDragMove, onDragStart, onDragEnd);
image.dblclick(function() {
image.transform('...r90');
});
image.click(function() {
if(mode === DELETE_DECOR_MODE) {
trafficLight.destroy();
}
});
function getScaling(object) {
var transform = object.transform();
for(var i = 0; i < transform.length; i++) {
if(transform[i][0] === 's') {
return transform[i][1] + ',' + transform[i][2];
}
}
return "0,0";
}
function canGetFromSourceToControlled(sourceCoord, controlledCoord) {
var sourceNode = ocargo.Node.findNodeByCoordinate(sourceCoord, nodes);
var controlledNode = ocargo.Node.findNodeByCoordinate(controlledCoord, nodes);
if(sourceNode && controlledNode) {
for(var i = 0; i < sourceNode.connectedNodes.length; i++) {
if(sourceNode.connectedNodes[i] === controlledNode) {
return true;
}
}
}
return false;
}
}
/********************************/
/* Miscaellaneous state methods */
/********************************/
function initialiseVisited() {
var visited = new Array(10);
for (var i = 0; i < 10; i++) {
visited[i] = new Array(8);
}
return visited;
}
function createGrid() {
grid = ocargo.drawing.renderGrid(currentTheme);
for(var i = 0; i < grid.length; i++) {
for(var j = 0; j < grid[i].length; j++) {
grid[i][j].node.onmousedown = handleMouseDown(grid[i][j]);
grid[i][j].node.onmouseover = handleMouseOver(grid[i][j]);
grid[i][j].node.onmouseout = handleMouseOut(grid[i][j]);
grid[i][j].node.onmouseup = handleMouseUp(grid[i][j]);
grid[i][j].node.ontouchstart = handleMouseDown(grid[i][j]);
grid[i][j].node.ontouchmove = handleMouseOver(grid[i][j]);
grid[i][j].node.ontouchend = handleMouseUp(grid[i][j]);
}
}
}
function finaliseDelete(strikeEnd) {
applyAlongStrike(deleteNode, strikeEnd);
strikeStart = null;
// Delete any nodes isolated through deletion
for (var i = nodes.length - 1; i >= 0; i--) {
if (nodes[i].connectedNodes.length === 0) {
var coordinate = nodes[i].coordinate;
deleteNode(coordinate.x, coordinate.y);
}
}
function deleteNode(x, y) {
var coord = new ocargo.Coordinate(x, y);
var node = ocargo.Node.findNodeByCoordinate(coord, nodes);
if(node) {
// Remove all the references to the node we're removing.
for (var i = node.connectedNodes.length - 1; i >= 0; i--) {
node.removeDoublyConnectedNode(node.connectedNodes[i]);
}
var index = nodes.indexOf(node);
nodes.splice(index, 1);
}
// Check if start or destination node
if(isOriginCoordinate(coord)) {
markAsBackground(originNode.coordinate);
originNode = null;
}
if(isDestinationCoordinate(coord)) {
markAsBackground(destinationNode.coordinate);
destinationNode = null;
}
}
}
function finaliseMove(strikeEnd) {
applyAlongStrike(addNode, strikeEnd);
strikeStart = null;
var previousNode = null;
function addNode(x, y) {
var coord = new ocargo.Coordinate(x,y);
var node = ocargo.Node.findNodeByCoordinate(coord, nodes);
if (!node) {
node = new ocargo.Node(coord);
nodes.push(node);
}
else
{
// If we've overwritten the origin node remove it as
// we can no longer place the CFC there
if(node === originNode) {
markAsBackground(originNode.coordinate);
originNode = null;
}
}
// Now connect it up with it's new neighbours
if(previousNode && node.connectedNodes.indexOf(previousNode) === -1) {
node.addConnectedNodeWithBacklink(previousNode);
}
previousNode = node;
}
}
function applyAlongStrike(func, strikeEnd) {
var x, y;
if (strikeStart.x === strikeEnd.x && strikeStart.y === strikeEnd.y) {
return;
}
if (strikeStart.x <= strikeEnd.x) {
for (x = strikeStart.x; x <= strikeEnd.x; x++) {
func(x, strikeStart.y);
}
}
else {
for (x = strikeStart.x; x >= strikeEnd.x; x--) {
func(x, strikeStart.y);
}
}
if (strikeStart.y <= strikeEnd.y) {
for (y = strikeStart.y + 1; y <= strikeEnd.y; y++) {
func(strikeEnd.x, y);
}
}
else {
for (y = strikeStart.y - 1; y >= strikeEnd.y; y--) {
func(strikeEnd.x, y);
}
}
}
function findTrafficLight(firstIndex, secondIndex) {
var light;
for (var i = 0; i < trafficLights.length; i++) {
light = trafficLights[i];
if (light.node === firstIndex && light.sourceNode === secondIndex) {
return i;
}
}
return -1;
}
function setTheme(theme) {
currentTheme = theme;
for (var x = 0; x < GRID_WIDTH; x++) {
for (var y = 0; y < GRID_HEIGHT; y++) {
grid[x][y].attr({stroke: theme.border});
}
}
for (var i = 0; i < decor.length; i++) {
decor[i].updateTheme();
}
$('.decor_button').each(function(index, element) {
element.src = theme.decor[element.id].url;
});
$('#wrapper').css({'background-color': theme.background});
}
function sortNodes(nodes) {
for (var i = 0; i < nodes.length; i++) {
// Remove duplicates.
var newConnected = [];
for (var j = 0; j < nodes[i].connectedNodes.length; j++) {
if (newConnected.indexOf(nodes[i].connectedNodes[j]) === -1) {
newConnected.push(nodes[i].connectedNodes[j]);
}
}
nodes[i].connectedNodes.sort(function(a, b) {
return comparator(a, b, nodes[i]);
}).reverse();
}
function comparator(node1, node2, centralNode) {
var a1 = ocargo.calculateNodeAngle(centralNode, node1);
var a2 = ocargo.calculateNodeAngle(centralNode, node2);
if (a1 < a2) {
return -1;
} else if (a1 > a2) {
return 1;
} else {
return 0;
}
}
}
/**********************************/
/* Loading/saving/sharing methods */
/**********************************/
function extractState() {
var state = {};
// Create node data
sortNodes(nodes);
state.path = JSON.stringify(ocargo.Node.composePathData(nodes));
// Create traffic light data
var trafficLightData = [];
var i;
for(i = 0; i < trafficLights.length; i++) {
var tl = trafficLights[i];
if(tl.valid) {
trafficLightData.push(tl.getData());
}
}
state.traffic_lights = JSON.stringify(trafficLightData);
// Create block data
var blockData = [];
for(i = 0; i < BLOCKS.length; i++) {
var type = BLOCKS[i];
if($('#' + type + "_checkbox").is(':checked')) {
blockData.push(type);
}
}
state.block_types = JSON.stringify(blockData);
// Create decor data
var decorData = [];
for(i = 0; i < decor.length; i++) {
decorData.push(decor[i].getData());
}
state.decor = JSON.stringify(decorData);
// Create other data
if(destinationNode) {
var destinationCoord = destinationNode.coordinate;
state.destinations = JSON.stringify([[destinationCoord.x, destinationCoord.y]]);
}
state.max_fuel = $('#max_fuel').val();
state.themeID = currentTheme.id;
state.character_name = CHARACTER_NAME;
return state;
}
function restoreState(state) {
clear();
// Load node data
nodes = ocargo.Node.parsePathData(JSON.parse(state.path));
// Load traffic light data
var trafficLightData = JSON.parse(state.traffic_lights);
for(var i = 0; i < trafficLightData.length; i++) {
new InternalTrafficLight(trafficLightData[i]);
}
// Load other data
originNode = nodes[0];
// TODO needs to be fixed in the long term with multiple destinations
if(state.destinations) {
var destinationList = JSON.parse(state.destinations)[0];
var destinationCoordinate = new ocargo.Coordinate(destinationList[0],
destinationList[1]);
destinationNode = ocargo.Node.findNodeByCoordinate(destinationCoordinate, nodes);
}
drawAll();
var themeID = state.themeID;
for(var theme in THEMES) {
if(THEMES[theme]['id'] === themeID) {
setTheme(THEMES[theme]);
}
}
// Load in the decor data
var decorData = JSON.parse(state.decor);
for(var i = 0; i < decorData.length; i++) {
var decorObject = new InternalDecor(decorData[i].name);
decorObject.setCoordinate(decorData[i].coordinate);
}
}
function loadLevel(levelID) {
ocargo.saving.retrieveLevel(levelID, function(err, level) {
if (err != null) {
console.debug(err);
return;
}
restoreState(level);
});
}
function saveLevel(name, levelID) {
var level = extractState();
level.name = name;
ocargo.saving.saveLevel(level, levelID, function(err, newLevelID) {
if (err != null) {
console.debug(err);
return;
}
// Delete name so that we can use if for comparison purposes
// to see if changes have been made to the level later on
delete level.name;
savedState = JSON.stringify(level);
savedLevelID = newLevelID;
ocargo.Drawing.startPopup("Saving","",ocargo.messages.saveSuccesful);
});
}
function shareLevel(recipient) {
ocargo.saving.shareLevel(savedLevelID, function(error) {
if(err) {
console.debug(error);
return;
}
ocargo.Drawing.startPopup("Saving","",ocargo.messages.shareSuccesful(recipient.name));
});
}
function storeStateInLocalStorage() {
if(localStorage) {
var state = extractState();
// Append additional non-level orientated editor state
state.savedLevelID = savedLevelID;
state.savedState = savedState;
localStorage['levelEditorState'] = JSON.stringify(state);
}
}
function retrieveStateFromLocalStorage() {
if(localStorage) {
var state = JSON.parse(localStorage['levelEditorState']);
if(state) {
restoreState(state);
}
// Restore additional non-level orientated editor state
savedLevelID = state.savedLevelID;
savedState = state.savedState;
}
}
function isLevelValid() {
// Check to see if start and end nodes have been marked
if (!originNode || !destinationNode) {
ocargo.Drawing.startPopup(ocargo.messages.ohNo,
ocargo.messages.noStartOrEndSubtitle,
ocargo.messages.noStartOrEnd);
return false;
}
// Check to see if path exists from start to end
var destination = new ocargo.Destination(0, destinationNode);
var pathToDestination = getOptimalPath(nodes, [destination]);
if (pathToDestination.length === 0) {
ocargo.Drawing.startPopup(ocargo.messages.somethingWrong,
ocargo.messages.noStartEndRouteSubtitle,
ocargo.messages.noStartEndRoute);
return false;
}
return true;
}
function isLevelSaved() {
var currentState = JSON.stringify(extractState());
if(!savedState) {
ocargo.Drawing.startPopup("Sharing", "", ocargo.messages.notSaved);
return false;
}
else if(currentState !== savedState) {
ocargo.Drawing.startPopup("Sharing", "", ocargo.messages.changesSinceLastSave);
return false;
}
return true;
}
/*****************************************/
/* Internal traffic light representation */
/*****************************************/
function InternalTrafficLight(data) {
// public methods
this.getData = function() {
if(!this.valid) {
throw "Error: cannot create actual traffic light from invalid internal traffic light!";
}
return {"redDuration": this.redDuration, "greenDuration": this.greenDuration,
"sourceNode": this.sourceNode, "controlledNode": this.controlledNode,
"startTime": this.startTime, "startingState": this.startingState};
};
this.destroy = function() {
this.image.remove();
var index = trafficLights.indexOf(this);
if(index !== -1) {
trafficLights.splice(index, 1);
}
};
// data
this.redDuration = data.redDuration;
this.greenDuration = data.greenDuration;
this.startTime = data.startTime;
this.startingState = data.startingState;
this.controlledNode = data.controlledNode;
this.sourceNode = data.sourceNode;
this.valid = false;
var imgStr = this.startingState === ocargo.TrafficLight.RED ? LIGHT_RED_URL : LIGHT_GREEN_URL;
this.image = ocargo.drawing.createTrafficLightImage(imgStr);
this.image.transform('...s-1,1');
if(this.controlledNode !== -1 && this.sourceNode !== -1) {
var sourceCoord = nodes[this.sourceNode].coordinate;
var controlledCoord = nodes[this.controlledNode].coordinate;
this.valid = true;
ocargo.drawing.setTrafficLightImagePosition(sourceCoord, controlledCoord, this.image);
}
setupTrafficLightListeners(this);
this.image.attr({'cursor':'pointer'});
trafficLights.push(this);
}
/*********************************/
/* Internal decor representation */
/*********************************/
function InternalDecor(name) {
// public methods
this.getData = function() {
var bBox = this.image.getBBox();
return {'coordinate': new ocargo.Coordinate(Math.floor(bBox.x),
PAPER_HEIGHT - bBox.height - Math.floor(bBox.y)),
'name': this.name};
};
this.setCoordinate = function(coordinate) {
this.image.transform('t' + coordinate.x + ',' + coordinate.y);
};
this.updateTheme = function() {
var description = currentTheme.decor[this.name];
var newImage = ocargo.drawing.createImage(description.url, 0, 0, description.width,
description.height);
if(this.image) {
newImage.transform(this.image.matrix.toTransformString());
this.image.remove();
}
this.image = newImage;
this.image.attr({'cursor':'pointer'});
setupDecorListeners(this);
};
this.destroy = function() {
this.image.remove();
var index = decor.indexOf(this);
if(index !== -1) {
decor.splice(index, 1);
}
};
// data
this.name = name;
this.image = null;
this.updateTheme();
decor.push(this);
}
};
/******************/
/* Initialisation */
/******************/
$(function() {
new ocargo.LevelEditor();
});
| Level editor - fix delete decor.
| game/static/game/js/level_editor.js | Level editor - fix delete decor. | <ide><path>ame/static/game/js/level_editor.js
<ide> });
<ide>
<ide> $('#delete_decor').click(function() {
<del> mode = DELETE_DECOR_MODE;
<add> if (mode === DELETE_DECOR_MODE) {
<add> mode = ADD_ROAD_MODE;
<add> } else {
<add> mode = DELETE_DECOR_MODE;
<add> }
<ide> });
<ide> }
<ide> |
|
Java | bsd-2-clause | d653ce6542e30e3a54c5aa8ea212fe94bbdf2dae | 0 | UCSFMemoryAndAging/lava,UCSFMemoryAndAging/lava,UCSFMemoryAndAging/lava | package edu.ucsf.lava.core.file;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import org.apache.commons.lang.StringUtils;
import org.springframework.util.FileCopyUtils;
import edu.ucsf.lava.core.file.exception.AlreadyExistsFileAccessException;
import edu.ucsf.lava.core.file.exception.FileAccessException;
import edu.ucsf.lava.core.file.exception.FileNotFoundException;
import edu.ucsf.lava.core.file.model.LavaFile;
public class LocalFileSystemRepositoryStrategy extends AbstractFileRepositoryStrategy {
public static String DEFAULT_REPOSITORY_ID = "lava_default";
protected String rootPath = "";
public static String MISSING_ID_FOLDER = "NO_ID";
/**
* with a local file system repository there is no connect / disconnect
*/
public boolean connect() throws FileAccessException {
return true;
}
/**
* with a local file system repository there is no connect / disconnect
*/
public boolean disconnect() throws FileAccessException {
return true;
}
/**
* with a local file system repository there is no connect / disconnect
*/
@Override
public boolean isConnected() throws FileAccessException {
return true;
}
/**
* Default behavior is to handle files for the default repository so
* subclasses should override to handle files belonging to a specific
* repository or content type etc.
*/
public boolean handlesFile(LavaFile file) {
// alternatively could handle files based on contentType or something else
if (file.getRepositoryId().equals(DEFAULT_REPOSITORY_ID)) {
return true;
}
else {
return false;
}
}
/**
* Default implementation is to use the record id of the FileEntity. If for
* some reason this is called prior to persistence of the FileEntity, then
* use checksum of file contents or current timestamp (neither of these is
* guaranteed to be unique, but will be close to unique in most use cases).
*/
@Override
public String generateFileId(LavaFile lavaFile) throws FileAccessException {
if(lavaFile.getId()!=null){
return lavaFile.getId().toString();
}else{
//should not find ourselves here as the FileEntity should be persisted
//before the file save.
if(lavaFile.getChecksum()!=null){
return lavaFile.getChecksum();
}else{
//use date/time
DateFormat formatter = new SimpleDateFormat("yyyymmdd_HHmmss_SSS", Locale.getDefault());
return formatter.format(new Date());
}
}
}
/**
* Default implementation is to organize files into levels of folders each with
* 256 subfolders and 256 files.
*
*/
@Override
public String generateLocation(LavaFile lavaFile) throws FileAccessException {
StringBuffer location = new StringBuffer();
//build subfolders
try{
long dividend = Long.valueOf(lavaFile.getFileId()).longValue();
long divisor = (long)256;
// put files with id < 256 in a subfolder labeled '0'
if(dividend < divisor){
location.append("0").append(File.separatorChar);
}
while(dividend > divisor){
location.append(divisor - (dividend % divisor)).append(File.separatorChar);
dividend = dividend/divisor;
}
}catch(NumberFormatException nfe){
location.append(MISSING_ID_FOLDER);
}
return location.toString();
}
/**
* Check to see if the file exists. If location / file id aren't set then
* set them.
*
*/
@Override
public boolean fileExists(LavaFile lavaFile) throws FileAccessException {
try{
File fsFile = getFileSystemObject(lavaFile,true);
return true;
}catch (FileNotFoundException e){
return false;
}
}
@Override
public LavaFile getFile(LavaFile lavaFile) throws FileAccessException {
try {
File fsFile = getFileSystemObject(lavaFile,true);
InputStream in = new FileInputStream(fsFile);
byte[] buffer = new byte[(int) fsFile.length()];
in.read(buffer);
lavaFile.setContent(buffer);
return lavaFile;
} catch (IOException ioe) {
this.logRepositoryError("Error reading file from repository",lavaFile);
throw new FileAccessException(
"There was a problem reading the file.",lavaFile);
}
}
@Override
public void deleteFile(LavaFile lavaFile) throws FileAccessException {
try {
File fsFile = getFileSystemObject(lavaFile,false);
if (fsFile.exists() && fsFile.isFile()) {
fsFile.delete();
lavaFile.setFileId(null);
lavaFile.setLocation(null);
}else{
this.logRepositoryError("Warning: attempt to delete non-existent file", lavaFile);
return;
}
}catch(SecurityException e){
this.logRepositoryError("Error deleting file from repository", lavaFile);
throw new FileAccessException("There was a problem deleting the file.",lavaFile,e);
}
}
@Override
public LavaFile saveFile(LavaFile lavaFile) throws FileAccessException {
return this.saveFile(lavaFile,false);
}
@Override
public LavaFile saveOrUpdateFile(LavaFile lavaFile) throws FileAccessException {
return this.saveFile(lavaFile, true);
}
protected LavaFile saveFile(LavaFile lavaFile, boolean overwrite) throws FileAccessException{
File fsFile = getFileSystemObject(lavaFile,false);
if(fsFile.exists() && !overwrite){
this.logRepositoryError("Error saving, file already exists", lavaFile);
throw new AlreadyExistsFileAccessException("Error storing file, it already exists.'",lavaFile);
}
try{
File dir = fsFile.getParentFile();
if (dir != null && !dir.exists()){
dir.mkdirs();
}
FileCopyUtils.copy(lavaFile.getContent(), fsFile);
return lavaFile;
}catch(IOException e){
this.logRepositoryError("Error saving file in repository", lavaFile);
throw new FileAccessException("Error saving file in repository",lavaFile,e);
}
}
/**
* Get the file system object reference. Standard implementation finds file based on
* location property of lavaFile. If fileId and location not set, generates them from
* other properties in a repository specific manner.
*
* @throws FileAccessException
*/
protected File getFileSystemObject(LavaFile lavaFile, boolean verify) throws FileAccessException{
if(lavaFile.getFileId()==null){
lavaFile.setFileId(this.generateFileId(lavaFile));
if(lavaFile.getFileId()==null){
this.logRepositoryError("Missing fileId when locating file on file system.", lavaFile);
throw new FileAccessException("Missing fileId when locating file on file system.",lavaFile);
}
}
if(lavaFile.getLocation()==null){
lavaFile.setLocation(this.generateLocation(lavaFile));
if(lavaFile.getLocation()==null){
this.logRepositoryError("Unable to determine location of file on file system.", lavaFile);
throw new FileAccessException("Unable to determine location of file on file system.",lavaFile);
}
}
File file = new File(getFileSystemObjectLocation(lavaFile));
if(verify &&(!file.exists() || !file.isFile())){
logger.error("File does not exist, path=" + file.getAbsolutePath());
throw new FileAccessException("There was a problem accessing the file: " + file.getAbsolutePath());
}
return file;
}
/**
* Return the absolute file system path to the file. Assumes that fileId and Location
* have already been set / verified.
* @param lavaFile
* @return the file system location of the file.
*/
public String getFileSystemObjectLocation(LavaFile lavaFile) throws FileAccessException{
return new StringBuffer(this.rootPath).append(File.separatorChar)
.append(lavaFile.getLocation()).append(File.separatorChar)
.append(lavaFile.getFileId()).toString();
}
public String getRootPath() {
return rootPath;
}
public void setRootPath(String rootPath) {
this.rootPath = rootPath;
}
}
| lava-core/src/edu/ucsf/lava/core/file/LocalFileSystemRepositoryStrategy.java | package edu.ucsf.lava.core.file;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import org.apache.commons.lang.StringUtils;
import org.springframework.util.FileCopyUtils;
import edu.ucsf.lava.core.file.exception.AlreadyExistsFileAccessException;
import edu.ucsf.lava.core.file.exception.FileAccessException;
import edu.ucsf.lava.core.file.exception.FileNotFoundException;
import edu.ucsf.lava.core.file.model.LavaFile;
public class LocalFileSystemRepositoryStrategy extends AbstractFileRepositoryStrategy {
protected String rootPath = "";
public static String MISSING_ID_FOLDER = "NO_ID";
/**
* with a local file system repository there is no connect / disconnect
*/
public boolean connect() throws FileAccessException {
return true;
}
/**
* with a local file system repository there is no connect / disconnect
*/
public boolean disconnect() throws FileAccessException {
return true;
}
/**
* with a local file system repository there is no connect / disconnect
*/
@Override
public boolean isConnected() throws FileAccessException {
return true;
}
/**
* Default behavior is to handle all files. This should be overridden in
* subclasses to provide multiple repositories to handle different classes
* of FileEntity.
*/
public boolean handlesFile(LavaFile file) {
return true;
}
/**
* Default implementation is to use the record id of the FileEntity. If for
* some reason this is called prior to persistence of the FileEntity, then
* use checksum of file contents or current timestamp (neither of these is
* guaranteed to be unique, but will be close to unique in most use cases).
*/
@Override
public String generateFileId(LavaFile lavaFile) throws FileAccessException {
if(lavaFile.getId()!=null){
return lavaFile.getId().toString();
}else{
//should not find ourselves here as the FileEntity should be persisted
//before the file save.
if(lavaFile.getChecksum()!=null){
return lavaFile.getChecksum();
}else{
//use date/time
DateFormat formatter = new SimpleDateFormat("yyyymmdd_HHmmss_SSS", Locale.getDefault());
return formatter.format(new Date());
}
}
}
/**
* Default implementation is to organize files into levels of folders each with
* 256 subfolders and 256 files.
*
*/
@Override
public String generateLocation(LavaFile lavaFile) throws FileAccessException {
StringBuffer location = new StringBuffer();
//build subfolders
try{
long dividend = Long.valueOf(lavaFile.getFileId()).longValue();
long divisor = (long)256;
// put files with id < 256 in a subfolder labeled '0'
if(dividend < divisor){
location.append("0").append(File.separatorChar);
}
while(dividend > divisor){
location.append(divisor - (dividend % divisor)).append(File.separatorChar);
dividend = dividend/divisor;
}
}catch(NumberFormatException nfe){
location.append(MISSING_ID_FOLDER);
}
return location.toString();
}
/**
* Check to see if the file exists. If location / file id aren't set then
* set them.
*
*/
@Override
public boolean fileExists(LavaFile lavaFile) throws FileAccessException {
try{
File fsFile = getFileSystemObject(lavaFile,true);
return true;
}catch (FileNotFoundException e){
return false;
}
}
@Override
public LavaFile getFile(LavaFile lavaFile) throws FileAccessException {
try {
File fsFile = getFileSystemObject(lavaFile,true);
InputStream in = new FileInputStream(fsFile);
byte[] buffer = new byte[(int) fsFile.length()];
in.read(buffer);
lavaFile.setContent(buffer);
return lavaFile;
} catch (IOException ioe) {
this.logRepositoryError("Error reading file from repository",lavaFile);
throw new FileAccessException(
"There was a problem reading the file.",lavaFile);
}
}
@Override
public void deleteFile(LavaFile lavaFile) throws FileAccessException {
try {
File fsFile = getFileSystemObject(lavaFile,false);
if (fsFile.exists() && fsFile.isFile()) {
fsFile.delete();
}else{
this.logRepositoryError("Warning: attempt to delete non-existent file", lavaFile);
return;
}
}catch(SecurityException e){
this.logRepositoryError("Error deleting file from repository", lavaFile);
throw new FileAccessException("There was a problem deleting the file.",lavaFile,e);
}
}
@Override
public LavaFile saveFile(LavaFile lavaFile) throws FileAccessException {
return this.saveFile(lavaFile,false);
}
@Override
public LavaFile saveOrUpdateFile(LavaFile lavaFile) throws FileAccessException {
return this.saveFile(lavaFile, true);
}
protected LavaFile saveFile(LavaFile lavaFile, boolean overwrite) throws FileAccessException{
File fsFile = getFileSystemObject(lavaFile,false);
if(fsFile.exists() && !overwrite){
this.logRepositoryError("Error saving, file already exists", lavaFile);
throw new AlreadyExistsFileAccessException("Error storing file, it already exists.'",lavaFile);
}
try{
File dir = fsFile.getParentFile();
if (dir != null && !dir.exists()){
dir.mkdirs();
}
FileCopyUtils.copy(lavaFile.getContent(), fsFile);
return lavaFile;
}catch(IOException e){
this.logRepositoryError("Error saving file in repository", lavaFile);
throw new FileAccessException("Error saving file in repository",lavaFile,e);
}
}
/**
* Get the file system object reference. Standard implementation finds file based on
* location property of lavaFile. If fileId and location not set, generates them from
* other properties in a repository specific manner.
*
* @throws FileAccessException
*/
protected File getFileSystemObject(LavaFile lavaFile, boolean verify) throws FileAccessException{
if(lavaFile.getFileId()==null){
lavaFile.setFileId(this.generateFileId(lavaFile));
if(lavaFile.getFileId()==null){
this.logRepositoryError("Missing fileId when locating file on file system.", lavaFile);
throw new FileAccessException("Missing fileId when locating file on file system.",lavaFile);
}
}
if(lavaFile.getLocation()==null){
lavaFile.setLocation(this.generateLocation(lavaFile));
if(lavaFile.getLocation()==null){
this.logRepositoryError("Unable to determine location of file on file system.", lavaFile);
throw new FileAccessException("Unable to determine location of file on file system.",lavaFile);
}
}
File file = new File(getFileSystemObjectLocation(lavaFile));
if(verify &&(!file.exists() || !file.isFile())){
logger.error("File does not exist, path=" + file.getAbsolutePath());
throw new FileAccessException("There was a problem accessing the file: " + file.getAbsolutePath());
}
return file;
}
/**
* Return the absolute file system path to the file. Assumes that fileId and Location
* have already been set / verified.
* @param lavaFile
* @return the file system location of the file.
*/
public String getFileSystemObjectLocation(LavaFile lavaFile) throws FileAccessException{
return new StringBuffer(this.rootPath).append(File.separatorChar)
.append(lavaFile.getLocation()).append(File.separatorChar)
.append(lavaFile.getFileId()).toString();
}
public String getRootPath() {
return rootPath;
}
public void setRootPath(String rootPath) {
this.rootPath = rootPath;
}
}
| 1) changed handlesFiles so it does return true for every file so that
when iterating thru strategies it will not handle a file that it should
not (now only handles files in the default repository) | lava-core/src/edu/ucsf/lava/core/file/LocalFileSystemRepositoryStrategy.java | 1) changed handlesFiles so it does return true for every file so that when iterating thru strategies it will not handle a file that it should not (now only handles files in the default repository) | <ide><path>ava-core/src/edu/ucsf/lava/core/file/LocalFileSystemRepositoryStrategy.java
<ide> import edu.ucsf.lava.core.file.model.LavaFile;
<ide>
<ide> public class LocalFileSystemRepositoryStrategy extends AbstractFileRepositoryStrategy {
<add> public static String DEFAULT_REPOSITORY_ID = "lava_default";
<add>
<ide> protected String rootPath = "";
<ide> public static String MISSING_ID_FOLDER = "NO_ID";
<ide>
<ide>
<ide>
<ide> /**
<del> * Default behavior is to handle all files. This should be overridden in
<del> * subclasses to provide multiple repositories to handle different classes
<del> * of FileEntity.
<del> */
<del>
<add> * Default behavior is to handle files for the default repository so
<add> * subclasses should override to handle files belonging to a specific
<add> * repository or content type etc.
<add> */
<ide> public boolean handlesFile(LavaFile file) {
<del> return true;
<del> }
<add> // alternatively could handle files based on contentType or something else
<add> if (file.getRepositoryId().equals(DEFAULT_REPOSITORY_ID)) {
<add> return true;
<add> }
<add> else {
<add> return false;
<add> }
<add> }
<add>
<ide> /**
<ide> * Default implementation is to use the record id of the FileEntity. If for
<ide> * some reason this is called prior to persistence of the FileEntity, then
<ide> File fsFile = getFileSystemObject(lavaFile,false);
<ide> if (fsFile.exists() && fsFile.isFile()) {
<ide> fsFile.delete();
<add> lavaFile.setFileId(null);
<add> lavaFile.setLocation(null);
<ide> }else{
<ide> this.logRepositoryError("Warning: attempt to delete non-existent file", lavaFile);
<ide> return; |
|
Java | mit | 3b3989bbc46c9c0ca6d3c037f82567d70653d6ea | 0 | rlviana/pricegrabber-app | package net.rlviana.pricegrabber.model.repository;
import java.io.Serializable;
import javax.persistence.Query;
import javax.persistence.criteria.CriteriaQuery;
import net.rlviana.pricegrabber.model.entity.IEntity;
import net.rlviana.pricegrabber.model.search.AbstractSearchCriteria;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Base JPA implementation for repositories requiring read operations based on JPA.<br/>
* It's required to inject an EntityManager.
*
* @author ramon
* @param <T> Entity class
* @param <K> Entity key class
*/
public abstract class AbstractJpaReadOnlyObjectRepository<T extends IEntity<K>, K extends Serializable> extends
AbstractBaseJpaReadOnlyObjectRepository<T, K> {
private static final Logger LOGGER = LoggerFactory.getLogger(AbstractJpaReadOnlyObjectRepository.class);
/**
* Constructor
*
* @param instanceClass
*/
public AbstractJpaReadOnlyObjectRepository(final Class<T> instanceClass) {
super(instanceClass);
}
/**
* Creates a JPA criteria query for the given searchCriteria.<br/>
* Delegates the building on the search criteria object<br/>
* If the given criteria is empty it will return a <code>SELECT * FROM <T></code> <br/>
* If the given criteria is null will throw an {@see java.lang.IllegalArgumentException}
*
* @param criteria to apply
* @return the builded criteria
*/
private CriteriaQuery<T> getQuery(final AbstractSearchCriteria<T, K> criteria) {
CriteriaQuery<T> query = null;
if (criteria == null) {
throw new IllegalArgumentException("Criteria = null");
} else {
query = criteria.buildQuery(getEntityManager());
}
return query;
}
/**
* Creates a JPA count criteria query for the given searchCriteria.<br/>
* Delegates the building on the search criteria object<br/>
* If the given criteria is empty it will return a <code>SELECT * FROM <T></code><br/>
* If the given criteria is null will throw an {@see java.lang.IllegalArgumentException}
*
* @param criteria to apply
* @return the builded criteria
*/
private CriteriaQuery<Long> getCountQuery(final AbstractSearchCriteria<T, K> criteria) {
CriteriaQuery<Long> query = null;
if (criteria == null) {
throw new IllegalArgumentException("Criteria = null");
} else {
query = criteria.buildCountQuery(getEntityManager());
}
return query;
}
/**
* Creates a JPA Query for the given searchCriteria
*
* @param criteria for searching
* @return created query
*/
@Override
protected Query getCriteriaQuery(final AbstractSearchCriteria<T, K> criteria) {
LOGGER.debug("Obtaining query for criteria: {}", criteria);
Query query = getEntityManager().createQuery(getQuery(criteria));
query.setFirstResult(criteria == null ? 0 : criteria.getFirstResult());
query.setMaxResults(criteria == null ? 0 : criteria.getMaxResults());
LOGGER.debug("Query: {}", query);
return query;
}
/**
* Creates a count query for the given searchCriteria
*
* @param criteria for searching
* @return query created
*/
@Override
protected Query getCountCriteriaQuery(final AbstractSearchCriteria<T, K> criteria) {
LOGGER.debug("Obtaining Count query for criteria: {}", criteria);
Query query = getEntityManager().createQuery(getCountQuery(criteria));
LOGGER.debug("Count query: {}", query);
return query;
}
}
| pricegrabber-model/src/main/java/net/rlviana/pricegrabber/model/repository/AbstractJpaReadOnlyObjectRepository.java | package net.rlviana.pricegrabber.model.repository;
import java.io.Serializable;
import javax.persistence.Query;
import javax.persistence.criteria.CriteriaQuery;
import net.rlviana.pricegrabber.model.entity.IEntity;
import net.rlviana.pricegrabber.model.search.AbstractSearchCriteria;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Base JPA implementation for repositories requiring read operations based on JPA.<br/>
* It's required to inject an EntityManager.
*
* @author ramon
* @param <T> Entity class
* @param <K> Entity key class
*/
public abstract class AbstractJpaReadOnlyObjectRepository<T extends IEntity<K>, K extends Serializable> extends
AbstractBaseJpaReadOnlyObjectRepository<T, K> {
/**
* Constructor
*
* @param instanceClass
*/
public AbstractJpaReadOnlyObjectRepository(final Class<T> instanceClass) {
super(instanceClass);
}
private static final Logger LOGGER = LoggerFactory.getLogger(AbstractJpaReadOnlyObjectRepository.class);
/**
* Creates a JPA criteria query for the given searchCriteria.<br/>
* Delegates the building on the search criteria object<br/>
* If the given criteria is empty it will return a <code>SELECT * FROM <T></code> <br/>
* If the given criteria is null will throw an {@see java.lang.IllegalArgumentException}
*
* @param criteria to apply
* @return the builded criteria
*/
private CriteriaQuery<T> getQuery(final AbstractSearchCriteria<T, K> criteria) {
CriteriaQuery<T> query = null;
if (criteria == null) {
throw new IllegalArgumentException("Criteria = null");
} else {
query = criteria.buildQuery(getEntityManager());
}
return query;
}
/**
* Creates a JPA count criteria query for the given searchCriteria.<br/>
* Delegates the building on the search criteria object<br/>
* If the given criteria is empty it will return a <code>SELECT * FROM <T></code><br/>
* If the given criteria is null will throw an {@see java.lang.IllegalArgumentException}
*
* @param criteria to apply
* @return the builded criteria
*/
private CriteriaQuery<Long> getCountQuery(final AbstractSearchCriteria<T, K> criteria) {
CriteriaQuery<Long> query = null;
if (criteria == null) {
throw new IllegalArgumentException("Criteria = null");
} else {
query = criteria.buildCountQuery(getEntityManager());
}
return query;
}
/**
* Creates a JPA Query for the given searchCriteria
*
* @param criteria for searching
* @return created query
*/
@Override
protected Query getCriteriaQuery(final AbstractSearchCriteria<T, K> criteria) {
LOGGER.debug("Obtaining query for criteria: {}", criteria);
Query query = getEntityManager().createQuery(getQuery(criteria));
query.setFirstResult(criteria == null ? 0 : criteria.getFirstResult());
query.setMaxResults(criteria == null ? 0 : criteria.getMaxResults());
LOGGER.debug("Query: {}", query);
return query;
}
/**
* Creates a count query for the given searchCriteria
*
* @param criteria for searching
* @return query created
*/
@Override
protected Query getCountCriteriaQuery(final AbstractSearchCriteria<T, K> criteria) {
LOGGER.debug("Obtaining Count query for criteria: {}", criteria);
Query query = getEntityManager().createQuery(getCountQuery(criteria));
LOGGER.debug("Count query: {}", query);
return query;
}
}
| Fixed minor error | pricegrabber-model/src/main/java/net/rlviana/pricegrabber/model/repository/AbstractJpaReadOnlyObjectRepository.java | Fixed minor error | <ide><path>ricegrabber-model/src/main/java/net/rlviana/pricegrabber/model/repository/AbstractJpaReadOnlyObjectRepository.java
<ide> public abstract class AbstractJpaReadOnlyObjectRepository<T extends IEntity<K>, K extends Serializable> extends
<ide> AbstractBaseJpaReadOnlyObjectRepository<T, K> {
<ide>
<add> private static final Logger LOGGER = LoggerFactory.getLogger(AbstractJpaReadOnlyObjectRepository.class);
<add>
<ide> /**
<ide> * Constructor
<ide> *
<ide> public AbstractJpaReadOnlyObjectRepository(final Class<T> instanceClass) {
<ide> super(instanceClass);
<ide> }
<del>
<del> private static final Logger LOGGER = LoggerFactory.getLogger(AbstractJpaReadOnlyObjectRepository.class);
<ide>
<ide> /**
<ide> * Creates a JPA criteria query for the given searchCriteria.<br/> |
|
JavaScript | mit | 865fbe8811c821e262380397b8e9fb89a7940240 | 0 | Oletus/gameutils.js,Oletus/gameutils.js | 'use strict';
/**
* Helpers for doing platforming physics, including tile classes and a function to evaluate movement with collisions.
* Using the platforming physics classes requires TileMap.
*/
var PlatformingPhysics = {};
/**
* A character that moves in the platforming level, colliding into other objects and tile maps.
* @constructor
*/
var PlatformingCharacter = function() {
};
PlatformingCharacter.prototype.init = function(options) {
var defaults = {
x: 0,
y: 0
};
for(var key in defaults) {
if (!options.hasOwnProperty(key)) {
this[key] = defaults[key];
} else {
this[key] = options[key];
}
}
this.lastX = this.x;
this.lastY = this.y;
this.dx = 0;
this.dy = 0;
this.color = '#f00';
this.onGround = true;
this.airTime = 0;
this.lastDeltaTime = 0;
this._collisionGroup = '_all';
};
PlatformingCharacter.prototype.decideDx = function(deltaTime) {
};
PlatformingCharacter.prototype.updateX = function(deltaTime, colliders) {
this.lastDeltaTime = deltaTime;
this.stayOnGround = this.onGround;
PlatformingPhysics.moveAndCollide(this, deltaTime, 'x', colliders, this.stayOnGround);
};
PlatformingCharacter.prototype.decideDy = function(deltaTime) {
this.dy += 1.0 * deltaTime;
};
PlatformingCharacter.prototype.updateY = function(deltaTime, colliders) {
this.onGround = false;
PlatformingPhysics.moveAndCollide(this, deltaTime, 'y', colliders, this.stayOnGround);
if (this.onGround) {
this.airTime = 0.0;
} else {
this.airTime += deltaTime;
}
};
PlatformingCharacter.prototype.touchGround = function() {
this.onGround = true;
this.dy = Math.max((this.y - this.lastY) / this.lastDeltaTime, 0);
};
PlatformingCharacter.prototype.touchCeiling = function() {
this.dy = 0;
};
PlatformingCharacter.prototype.render = function(ctx) {
ctx.fillStyle = this.color;
var rect = this.getRect();
ctx.fillRect(rect.left, rect.top, rect.right - rect.left, rect.bottom - rect.top);
};
PlatformingCharacter.prototype.getRect = function() {
var width = 1.0;
var height = 2.0;
return new Rect(this.x - width * 0.5, this.x + width * 0.5,
this.y - height * 0.5, this.y + height * 0.5);
};
PlatformingCharacter.prototype.getLastRect = function() {
var width = 1.0;
var height = 2.0;
return new Rect(this.lastX - width * 0.5, this.lastX + width * 0.5,
this.lastY - height * 0.5, this.lastY + height * 0.5);
};
/**
* A tile map that can be a part of a platforming level.
* @constructor
*/
var PlatformingTileMap = function() {
};
PlatformingTileMap.prototype = new PlatformingCharacter();
PlatformingTileMap.prototype.init = function(options) {
PlatformingCharacter.prototype.init.call(this, options);
var defaults = {
tileMap: null
};
for(var key in defaults) {
if (!options.hasOwnProperty(key)) {
this[key] = defaults[key];
} else {
this[key] = options[key];
}
}
this.frameDeltaX = 0;
this.frameDeltaY = 0;
this._collisionGroup = '_none';
};
PlatformingTileMap.prototype.getRect = function() {
return new Rect(this.x, this.x + this.tileMap.width,
this.y, this.y + this.tileMap.height);
};
PlatformingTileMap.prototype.getLastRect = function() {
return new Rect(this.lastX, this.lastX + this.tileMap.width,
this.lastY, this.lastY + this.tileMap.height);
};
PlatformingTileMap.prototype.decideDx = function() {
this.dx = 0;
};
PlatformingTileMap.prototype.decideDy = function() {
this.dy = 0;
};
/**
* A platforming level composed of tilemaps and objects that collide against them (or against each other).
* @constructor
*/
var PlatformingLevel = function() {
};
PlatformingLevel.prototype.init = function() {
this._objects = [];
this._tileMapObjects = [];
this._colliders = {'_all': []}; // All is a special collision group that includes all objects.
};
PlatformingLevel.prototype.pushObject = function(object, collisionGroups) {
if (object instanceof PlatformingTileMap) {
this._tileMapObjects.push(object);
} else {
this._objects.push(object);
}
for (var i = 0; i < collisionGroups.length; ++i) {
if (collisionGroups[i] !== '_all' && collisionGroups[i] !== '_none') {
this._colliders[collisionGroups[i]].push(object);
}
}
this._colliders['_all'].push(object);
};
/**
* Tilemap objects may move. Their movement only affects the movement of other objects via collisions (so for example
* logic for player movement matching moving platforms must be implemented in the decideDx function).
* When the movement of the tilemap objects themselves is evaluated, the tilemap doesn't affect possible collisions,
* only the object's bounding geometry does.
*/
PlatformingLevel.prototype.update = function(deltaTime) {
for (var i = 0; i < this._tileMapObjects.length; ++i) {
var object = this._tileMapObjects[i];
object.lastX = object.x;
object.lastY = object.y;
object.decideDx(deltaTime);
}
for (var i = 0; i < this._tileMapObjects.length; ++i) {
var object = this._tileMapObjects[i];
object.updateX(deltaTime, this._colliders[object._collisionGroup]);
// Save the real x movement of the tilemap this frame, so that other objects can take it into account
// when colliding against it.
object.frameDeltaX = object.x - object.lastX;
}
for (var i = 0; i < this._objects.length; ++i) {
var object = this._objects[i];
object.lastX = object.x;
object.lastY = object.y;
object.decideDx(deltaTime);
}
for (var i = 0; i < this._objects.length; ++i) {
var object = this._objects[i];
object.updateX(deltaTime, this._colliders[object._collisionGroup]);
}
for (var i = 0; i < this._tileMapObjects.length; ++i) {
var object = this._tileMapObjects[i];
object.decideDy(deltaTime);
}
for (var i = 0; i < this._tileMapObjects.length; ++i) {
var object = this._tileMapObjects[i];
object.updateY(deltaTime, this._colliders[object._collisionGroup]);
// Save the real y movement of the tilemap this frame, so that other objects can take it into account
// when colliding against it.
object.frameDeltaY = object.y - object.lastY;
}
for (var i = 0; i < this._objects.length; ++i) {
var object = this._objects[i];
object.decideDy(deltaTime);
}
for (var i = 0; i < this._objects.length; ++i) {
var object = this._objects[i];
object.updateY(deltaTime, this._colliders[object._collisionGroup]);
}
};
/**
* A platforming tile.
* @constructor
*/
var PlatformingTile = function() {
};
/**
* @return {number} floor height inside sloping tile.
*/
PlatformingTile.prototype.getFloorRelativeHeight = function(xInTile) {
return 0.0;
};
/**
* Set the position of the tile.
*/
PlatformingTile.prototype.setPos = function(x, y) {
this._x = x;
this._y = y;
};
/**
* @return {number} maximum floor height inside sloping tile.
*/
PlatformingTile.prototype.getMaxFloorRelativeHeight = function() {
return Math.max(this.getFloorRelativeHeight(0), this.getFloorRelativeHeight(1));
};
/**
* @return {boolean} True if the tile is a wall for movement towards any direction.
*/
PlatformingTile.prototype.isWall = function() {
return false;
};
/**
* @return {boolean} True if the tile is a wall for upwards movement (negative y).
*/
PlatformingTile.prototype.isWallUp = function() {
return false;
};
/**
* @return {boolean} True if the tile is sloped for objects moving above it.
*/
PlatformingTile.prototype.isFloorSlope = function() {
return false;
};
/**
* A tile with a sloped floor.
* @constructor
*/
var SlopedFloorTile = function(floorLeft, floorRight) {
this._floorLeft = floorLeft;
this._floorRight = floorRight;
this._maxFloor = Math.max(floorLeft, floorRight);
this._minFloor = Math.min(floorLeft, floorRight);
};
SlopedFloorTile.prototype = new PlatformingTile();
/**
* @return {number} floor height inside sloping tile. Must be monotonically increasing or decreasing inside the tile.
*/
SlopedFloorTile.prototype.getFloorRelativeHeight = function(xInTile) {
return mathUtil.clamp(this._minFloor, this._maxFloor, mathUtil.mix(this._floorLeft, this._floorRight, xInTile));
};
/**
* @return {boolean} True if the tile is sloped for objects moving above it.
*/
SlopedFloorTile.prototype.isFloorSlope = function() {
return true;
};
/**
* Render the sloped tile on a canvas.
* @param {CanvasRenderingContext2D} ctx 2D rendering context to use for drawing.
*/
SlopedFloorTile.prototype.render = function(ctx) {
ctx.beginPath();
ctx.moveTo(this._x, this._y + 1);
for (var x = 0; x <= 1; x += 0.25) {
var h = mathUtil.clamp(0, 1, this.getFloorRelativeHeight(x));
ctx.lineTo(this._x + x, this._y + 1 - h);
}
ctx.lineTo(this._x + 1, this._y + 1);
ctx.fill();
};
/**
* A tile that's a wall.
* @constructor
* @param {boolean} wallUp True if the wall affects upwards movement (negative y).
*/
var WallTile = function(wallUp) {
if (wallUp === undefined) {
wallUp = true;
}
this._wallUp = wallUp;
};
WallTile.prototype = new PlatformingTile();
/**
* @return {boolean} True if the tile is a wall for movement towards any direction.
*/
WallTile.prototype.isWall = function() {
return true;
};
/**
* @return {boolean} True if the tile is a wall for upwards movement (negative y).
*/
WallTile.prototype.isWallUp = function() {
return this._wallUp;
};
/**
* Get a tile map initializer based on an array of character codes representing tiles.
* @param {Array} data Tile letter codes in an array in row-major form. Example:
* ['xxx. /xxx ',
* ' xx^^^^^^xx '],
* Character codes are:
* x: wall.
* ^: can be jumped through from below, not passable from above.
* .: 45 degree slope rising towards left.
* /: 45 degree slope rising towards right.
* l: low 26 degree slope rising towards left.
* L: high 26 degree slope rising towards left.
* r: low 26 degree slope rising towards right.
* R: high 26 degree slope rising towards right.
* : empty space.
*
* @param {boolean?} flippedX Set to true to flip the data in the x direction.
* @return {function} Function that will initialize a TileMap with PlatformingTiles.
*/
PlatformingPhysics.initFromData = function(data, flippedX) {
if (flippedX === undefined) {
flippedX = false;
}
var transformedData = [];
for (var i = 0; i < data.length; ++i) {
var row = data[i];
var transformedRow = [];
for (var j = 0; j < row.length; ++j) {
var tile = null;
if (row[j] == 'x') {
tile = new WallTile(true);
} else if (row[j] == '^') {
tile = new WallTile(false);
} else if ((row[j] == '/' && !flippedX) || (row[j] == '.' && flippedX)) {
tile = new SlopedFloorTile(0, 1);
} else if ((row[j] == '.' && !flippedX) || (row[j] == '/' && flippedX)) {
tile = new SlopedFloorTile(1, 0);
} else if ((row[j] == 'L' && !flippedX) || (row[j] == 'R' && flippedX)) {
tile = new SlopedFloorTile(1, 0.5);
} else if ((row[j] == 'R' && !flippedX) || (row[j] == 'L' && flippedX)) {
tile = new SlopedFloorTile(0.5, 1);
} else if ((row[j] == 'l' && !flippedX) || (row[j] == 'r' && flippedX)) {
tile = new SlopedFloorTile(0.5, 0);
} else if ((row[j] == 'r' && !flippedX) || (row[j] == 'l' && flippedX)) {
tile = new SlopedFloorTile(0, 0.5);
} else {
tile = new PlatformingTile();
}
var x = j;
if (flippedX) {
x = row.length - j - 1;
}
tile.setPos(x, i);
transformedRow.push(tile);
}
transformedData.push(transformedRow);
}
return TileMap.initFromData(transformedData, flippedX);
};
/**
* Move an object along one axis, reacting to collisions.
* @param {Object} movingObj Object that moves. Needs to have the following properties in the world coordinate system:
* x, y, dx, dy, getRect()
* Properties to react to y collisions:
* touchGround(), touchCeiling()
* @param {number} deltaTime Time step to use to move the object.
* @param {string} dim Either 'x' or 'y' to move the object horizontally or vertically.
* @param {Array?} colliders List of objects to collide against. The moved object is automatically excluded in case it
* is in this array. Colliders must report coordinates relative to the world. Colliders must be PlatformingCharacters.
* @param {boolean} stayOnGround True if the character should try to follow the ground when going down on a slope.
*/
PlatformingPhysics.moveAndCollide = function(movingObj, deltaTime, dim, colliders, stayOnGround) {
var maxStepUp = 0.1;
var isWall = function(tile) {
return tile.isWall();
};
var isWallUp = function(tile) {
return tile.isWallUp();
};
var isFloorSlope = function(tile) {
return tile.isFloorSlope();
};
var done = false;
var delta = 0;
if (dim == 'x') {
delta = movingObj.dx * deltaTime;
} else {
delta = movingObj.dy * deltaTime;
}
var lastDelta = delta;
while (!done) {
var rect = movingObj.getRect();
done = true;
if (dim == 'x') {
var rectRightHalfWidth = rect.right - movingObj.x;
var rectLeftHalfWidth = movingObj.x - rect.left;
var rectBottomHalfHeight = rect.bottom - movingObj.y;
if (Math.abs(delta) > 0) {
movingObj.x += delta;
var xColliders = [];
if (colliders !== undefined) {
for (var i = 0; i < colliders.length; ++i) {
if (colliders[i] === movingObj) {
continue;
}
var collider = colliders[i].getRect();
if (rect.top < collider.bottom && collider.top < rect.bottom) {
if (colliders[i] instanceof PlatformingTileMap) {
xColliders.push(colliders[i]);
} else {
xColliders.push(collider);
}
}
}
}
var slopeFloorY = movingObj.y + rectBottomHalfHeight + TileMap.epsilon * 2;
if (delta > 0) {
var wallXRight = movingObj.x + rectRightHalfWidth + TileMap.epsilon * 2;
var slopeEndX = wallXRight;
for (var i = 0; i < xColliders.length; ++i) {
if (xColliders[i] instanceof PlatformingTileMap) {
var fromWorldToTileMap = new Vec2(-xColliders[i].lastX, -xColliders[i].lastY);
var relativeDelta = delta - xColliders[i].frameDeltaX;
var relativeRect = new Rect(rect.left, rect.right, rect.top, rect.bottom);
relativeRect.translate(fromWorldToTileMap);
var wallTileX = xColliders[i].tileMap.nearestTileRightFromRect(relativeRect, isWallUp, Math.abs(relativeDelta));
if (wallTileX != -1 && wallXRight > wallTileX + xColliders[i].x) {
wallXRight = wallTileX + xColliders[i].x;
}
var slopeTiles = xColliders[i].tileMap.getNearestTilesRightFromRect(relativeRect, isFloorSlope, Math.abs(relativeDelta));
if (slopeTiles.length != 0) {
var possibleWallX = slopeTiles[0]._x + xColliders[i].x;
for (var j = 0; j < slopeTiles.length; ++j) {
var slopeTile = slopeTiles[j];
var slopeBaseY = slopeTile._y + 1 + xColliders[i].y;
var slopeIsEffectivelyWall = (slopeBaseY - slopeTile.getFloorRelativeHeight(0) < rect.bottom - maxStepUp);
if (wallXRight > possibleWallX && slopeIsEffectivelyWall) {
wallXRight = possibleWallX;
}
if (!slopeIsEffectivelyWall) {
slopeEndX = slopeTile._x + 1 + xColliders[i].x;
var relativeX = movingObj.x - (slopeEndX - 1);
var slopeYRight = slopeBaseY -
slopeTile.getFloorRelativeHeight(relativeX + rectRightHalfWidth);
if (slopeFloorY > slopeYRight) {
slopeFloorY = slopeYRight;
}
}
}
}
} else {
if (xColliders[i].right > rect.left && wallXRight > xColliders[i].left) {
wallXRight = xColliders[i].left;
}
}
}
if (movingObj.x > slopeEndX - rectRightHalfWidth + TileMap.epsilon * 2) {
var afterOriginalMove = movingObj.x;
movingObj.x = slopeEndX - rectRightHalfWidth + TileMap.epsilon * 2;
delta = afterOriginalMove - movingObj.x;
// Finish this iteration on the tile boundary and continue movement on the next slope tile.
if (delta > TileMap.epsilon * 2 && delta < lastDelta) {
done = false;
lastDelta = delta;
}
}
if (movingObj.y > slopeFloorY - rectBottomHalfHeight - TileMap.epsilon) {
movingObj.y = slopeFloorY - rectBottomHalfHeight - TileMap.epsilon;
}
// Apply walls only when movement is done. When moving along a slope, the code may have placed
// the object right beyond the tile boundary for the next iteration so that movement wouldn't
// be stuck in a case like below:
// /
// obj-> /x
if (movingObj.x > wallXRight - rectRightHalfWidth - TileMap.epsilon && done) {
movingObj.x = wallXRight - rectRightHalfWidth - TileMap.epsilon;
}
} else {
var wallXLeft = movingObj.x - rectLeftHalfWidth - TileMap.epsilon * 2;
var slopeEndX = wallXLeft;
for (var i = 0; i < xColliders.length; ++i) {
if (xColliders[i] instanceof PlatformingTileMap) {
var fromWorldToTileMap = new Vec2(-xColliders[i].lastX, -xColliders[i].lastY);
var relativeDelta = delta - xColliders[i].frameDeltaX;
var relativeRect = new Rect(rect.left, rect.right, rect.top, rect.bottom);
relativeRect.translate(fromWorldToTileMap);
var wallTileX = xColliders[i].tileMap.nearestTileLeftFromRect(relativeRect, isWallUp, Math.abs(relativeDelta));
if (wallTileX != -1 && wallXLeft < wallTileX + 1 + xColliders[i].x) {
wallXLeft = wallTileX + 1 + xColliders[i].x;
}
var slopeTiles = xColliders[i].tileMap.getNearestTilesLeftFromRect(relativeRect, isFloorSlope, Math.abs(relativeDelta));
if (slopeTiles.length != 0) {
var possibleWallX = slopeTiles[0]._x + 1 + xColliders[i].x;
for (var j = 0; j < slopeTiles.length; ++j) {
var slopeTile = slopeTiles[j];
var slopeBaseY = slopeTile._y + 1 + xColliders[i].y;
var slopeIsEffectivelyWall = (slopeBaseY - slopeTile.getFloorRelativeHeight(1) < rect.bottom - maxStepUp);
if (wallXLeft < possibleWallX && slopeIsEffectivelyWall) {
wallXLeft = possibleWallX;
}
if (!slopeIsEffectivelyWall) {
slopeEndX = slopeTile._x + xColliders[i].x;
var relativeX = movingObj.x - slopeEndX;
var slopeYRight = slopeBaseY -
slopeTile.getFloorRelativeHeight(relativeX - rectLeftHalfWidth);
if (slopeFloorY > slopeYRight) {
slopeFloorY = slopeYRight;
}
}
}
}
} else {
if (xColliders[i].left < rect.right && wallXLeft < xColliders[i].right) {
wallXLeft = xColliders[i].right;
}
}
}
if (movingObj.x < slopeEndX + rectLeftHalfWidth - TileMap.epsilon * 2) {
var afterOriginalMove = movingObj.x;
movingObj.x = slopeEndX + rectLeftHalfWidth - TileMap.epsilon * 2;
delta = afterOriginalMove - movingObj.x;
// Finish this iteration on the tile boundary and continue movement on the next slope tile.
if (delta < -TileMap.epsilon * 2 && delta > lastDelta) {
done = false;
lastDelta = delta;
}
}
if (movingObj.y > slopeFloorY - rectBottomHalfHeight - TileMap.epsilon) {
movingObj.y = slopeFloorY - rectBottomHalfHeight - TileMap.epsilon;
}
// Apply walls only when movement is done. When moving along a slope, the code may have placed
// the object right beyond the tile boundary for the next iteration so that movement wouldn't
// be stuck in a case like below:
// .
// x. <- obj
if (movingObj.x < wallXLeft + rectLeftHalfWidth + TileMap.epsilon && done) {
movingObj.x = wallXLeft + rectLeftHalfWidth + TileMap.epsilon;
}
}
}
} // dim == 'x'
if (dim == 'y') {
var delta = movingObj.dy * deltaTime;
var rectBottomHalfHeight = rect.bottom - movingObj.y;
var rectTopHalfHeight = movingObj.y - rect.top;
var rectRightHalfWidth = rect.right - movingObj.x;
var rectLeftHalfWidth = movingObj.x - rect.left;
if (Math.abs(delta) > 0) {
var lastY = movingObj.y;
movingObj.y += delta;
var yColliders = [];
if (colliders !== undefined) {
for (var i = 0; i < colliders.length; ++i) {
if (colliders[i] === movingObj) {
continue;
}
var collider = colliders[i].getRect();
if (rect.left < collider.right && collider.left < rect.right) {
if (colliders[i] instanceof PlatformingTileMap) {
yColliders.push(colliders[i]);
} else {
yColliders.push(collider);
}
}
}
}
if (delta > 0) {
var wallYDown = movingObj.y + rectBottomHalfHeight + 1 + TileMap.epsilon;
var hitSlope = false;
for (var i = 0; i < yColliders.length; ++i) {
if (yColliders[i] instanceof PlatformingTileMap) {
// X movement has already been fully evaluated
var fromWorldToTileMap = new Vec2(-yColliders[i].x, -yColliders[i].lastY);
var relativeDelta = delta - yColliders[i].frameDeltaY;
var relativeRect = new Rect(rect.left, rect.right, rect.top, rect.bottom);
relativeRect.translate(fromWorldToTileMap);
var origBottom = relativeRect.bottom;
relativeRect.bottom += 1;
var wallTileY = yColliders[i].tileMap.nearestTileDownFromRect(relativeRect, isWall, Math.abs(relativeDelta));
if (wallTileY != -1 && wallYDown > wallTileY + yColliders[i].y) {
wallYDown = wallTileY + yColliders[i].y;
hitSlope = false;
}
relativeRect.bottom = origBottom;
var slopeTiles = yColliders[i].tileMap.getNearestTilesDownFromRect(relativeRect, isFloorSlope,
Math.max(Math.abs(relativeDelta), 1));
if (slopeTiles.length != 0 && wallYDown > slopeTiles[0]._y + yColliders[i].y) {
for (var j = 0; j < slopeTiles.length; ++j) {
var slopeTile = slopeTiles[j];
var relativeX = movingObj.x - (slopeTile._x + yColliders[i].x);
var slopeBaseY = slopeTile._y + 1 + yColliders[i].y;
var slopeYLeft = slopeBaseY -
slopeTile.getFloorRelativeHeight(relativeX - rectLeftHalfWidth);
var slopeYRight = slopeBaseY -
slopeTile.getFloorRelativeHeight(relativeX + rectRightHalfWidth);
if (slopeYLeft < wallYDown) {
wallYDown = slopeYLeft;
hitSlope = true;
}
if (slopeYRight < wallYDown) {
wallYDown = slopeYRight;
hitSlope = true;
}
}
}
} else {
if (yColliders[i].bottom > rect.top && wallYDown > yColliders[i].top) {
wallYDown = yColliders[i].top;
}
}
}
if (movingObj.y > wallYDown - rectBottomHalfHeight - TileMap.epsilon) {
movingObj.y = wallYDown - rectBottomHalfHeight - TileMap.epsilon;
movingObj.touchGround();
} else if (hitSlope && stayOnGround) {
// TODO: There's still a bug where the character teleports downwards when there's a slope like this:
// .
// xl
movingObj.y = wallYDown - rectBottomHalfHeight - TileMap.epsilon;
movingObj.touchGround();
}
} else {
var wallYUp = movingObj.y - rectTopHalfHeight - TileMap.epsilon * 2;
for (var i = 0; i < yColliders.length; ++i) {
if (yColliders[i] instanceof PlatformingTileMap) {
// X movement has already been fully evaluated
var fromWorldToTileMap = new Vec2(-yColliders[i].x, -yColliders[i].lastY);
var relativeDelta = delta - yColliders[i].frameDeltaY;
var relativeRect = new Rect(rect.left, rect.right, rect.top, rect.bottom);
relativeRect.translate(fromWorldToTileMap);
var wallTileY = yColliders[i].tileMap.nearestTileUpFromRect(relativeRect, isWallUp, Math.abs(relativeDelta));
if (wallTileY != -1 && wallYUp < wallTileY + 1 + yColliders[i].y) {
wallYUp = wallTileY + 1 + yColliders[i].y;
}
} else {
if (yColliders[i].top < rect.bottom && wallYUp < yColliders[i].bottom) {
wallYUp = yColliders[i].bottom;
}
}
}
if (movingObj.y < wallYUp + rectTopHalfHeight + TileMap.epsilon) {
movingObj.y = wallYUp + rectTopHalfHeight + TileMap.epsilon;
movingObj.touchCeiling();
}
}
}
}
}
};
/**
* Render sloped tiles to a canvas.
* @param {TileMap} tileMap Map to render.
* @param {CanvasRenderingContext2D} ctx 2D rendering context to use for drawing.
*/
PlatformingPhysics.renderSlopes = function(tileMap, ctx) {
for (var y = 0; y < tileMap.height; ++y) {
for (var x = 0; x < tileMap.width; ++x) {
var tile = tileMap.tiles[y][x];
if (tile.isFloorSlope()) {
tile.render(ctx);
}
}
}
};
| src/platformingphysics.js | 'use strict';
/**
* Helpers for doing platforming physics, including tile classes and a function to evaluate movement with collisions.
* Using the platforming physics classes requires TileMap.
*/
var PlatformingPhysics = {};
/**
* A character that moves in the platforming level, colliding into other objects and tile maps.
* @constructor
*/
var PlatformingCharacter = function() {
};
PlatformingCharacter.prototype.init = function(options) {
var defaults = {
x: 0,
y: 0
};
for(var key in defaults) {
if (!options.hasOwnProperty(key)) {
this[key] = defaults[key];
} else {
this[key] = options[key];
}
}
this.lastX = this.x;
this.lastY = this.y;
this.dx = 0;
this.dy = 0;
this.color = '#f00';
this.onGround = true;
this.airTime = 0;
this.lastDeltaTime = 0;
this._collisionGroup = '_all';
};
PlatformingCharacter.prototype.decideDx = function(deltaTime) {
};
PlatformingCharacter.prototype.updateX = function(deltaTime, colliders) {
this.lastDeltaTime = deltaTime;
this.stayOnGround = this.onGround;
PlatformingPhysics.moveAndCollide(this, deltaTime, 'x', colliders, this.stayOnGround);
};
PlatformingCharacter.prototype.decideDy = function(deltaTime) {
this.dy += 1.0 * deltaTime;
};
PlatformingCharacter.prototype.updateY = function(deltaTime, colliders) {
this.onGround = false;
PlatformingPhysics.moveAndCollide(this, deltaTime, 'y', colliders, this.stayOnGround);
if (this.onGround) {
this.airTime = 0.0;
} else {
this.airTime += deltaTime;
}
};
PlatformingCharacter.prototype.touchGround = function() {
this.onGround = true;
this.dy = Math.max((this.y - this.lastY) / this.lastDeltaTime, 0);
};
PlatformingCharacter.prototype.touchCeiling = function() {
this.dy = 0;
};
PlatformingCharacter.prototype.render = function(ctx) {
ctx.fillStyle = this.color;
var rect = this.getRect();
ctx.fillRect(rect.left, rect.top, rect.right - rect.left, rect.bottom - rect.top);
};
PlatformingCharacter.prototype.getRect = function() {
var width = 1.0;
var height = 2.0;
return new Rect(this.x - width * 0.5, this.x + width * 0.5,
this.y - height * 0.5, this.y + height * 0.5);
};
PlatformingCharacter.prototype.getLastRect = function() {
var width = 1.0;
var height = 2.0;
return new Rect(this.lastX - width * 0.5, this.lastX + width * 0.5,
this.lastY - height * 0.5, this.lastY + height * 0.5);
};
/**
* A tile map that can be a part of a platforming level.
* @constructor
*/
var PlatformingTileMap = function() {
};
PlatformingTileMap.prototype = new PlatformingCharacter();
PlatformingTileMap.prototype.init = function(options) {
PlatformingCharacter.prototype.init.call(this, options);
var defaults = {
tileMap: null
};
for(var key in defaults) {
if (!options.hasOwnProperty(key)) {
this[key] = defaults[key];
} else {
this[key] = options[key];
}
}
this.frameDeltaX = 0;
this.frameDeltaY = 0;
this._collisionGroup = '_none';
};
PlatformingTileMap.prototype.getRect = function() {
return new Rect(this.x, this.x + this.tileMap.width,
this.y, this.y + this.tileMap.height);
};
PlatformingTileMap.prototype.getLastRect = function() {
return new Rect(this.lastX, this.lastX + this.tileMap.width,
this.lastY, this.lastY + this.tileMap.height);
};
PlatformingTileMap.prototype.decideDx = function() {
this.dx = 0;
};
PlatformingTileMap.prototype.decideDy = function() {
this.dy = 0;
};
/**
* A platforming level composed of tilemaps and objects that collide against them (or against each other).
* @constructor
*/
var PlatformingLevel = function() {
};
PlatformingLevel.prototype.init = function() {
this._objects = [];
this._tileMapObjects = [];
this._colliders = {'_all': []}; // All is a special collision group that includes all objects.
};
PlatformingLevel.prototype.pushObject = function(object, collisionGroups) {
if (object instanceof PlatformingTileMap) {
this._tileMapObjects.push(object);
} else {
this._objects.push(object);
}
for (var i = 0; i < collisionGroups.length; ++i) {
if (collisionGroups[i] !== '_all' && collisionGroups[i] !== '_none') {
this._colliders[collisionGroups[i]].push(object);
}
}
this._colliders['_all'].push(object);
};
/**
* Tilemap objects may move. Their movement only affects the movement of other objects via collisions (so for example
* logic for player movement matching moving platforms must be implemented in the decideDx function).
* When the movement of the tilemap objects themselves is evaluated, the tilemap doesn't affect possible collisions,
* only the object's bounding geometry does.
*/
PlatformingLevel.prototype.update = function(deltaTime) {
for (var i = 0; i < this._tileMapObjects.length; ++i) {
var object = this._tileMapObjects[i];
object.lastX = object.x;
object.lastY = object.y;
object.decideDx(deltaTime);
}
for (var i = 0; i < this._tileMapObjects.length; ++i) {
var object = this._tileMapObjects[i];
object.updateX(deltaTime, this._colliders[object._collisionGroup]);
// Save the real x movement of the tilemap this frame, so that other objects can take it into account
// when colliding against it.
object.frameDeltaX = object.x - object.lastX;
}
for (var i = 0; i < this._objects.length; ++i) {
var object = this._objects[i];
object.lastX = object.x;
object.lastY = object.y;
object.decideDx(deltaTime);
}
for (var i = 0; i < this._objects.length; ++i) {
var object = this._objects[i];
object.updateX(deltaTime, this._colliders[object._collisionGroup]);
}
for (var i = 0; i < this._tileMapObjects.length; ++i) {
var object = this._tileMapObjects[i];
object.decideDy(deltaTime);
}
for (var i = 0; i < this._tileMapObjects.length; ++i) {
var object = this._tileMapObjects[i];
object.updateY(deltaTime, this._colliders[object._collisionGroup]);
// Save the real y movement of the tilemap this frame, so that other objects can take it into account
// when colliding against it.
object.frameDeltaY = object.y - object.lastY;
}
for (var i = 0; i < this._objects.length; ++i) {
var object = this._objects[i];
object.decideDy(deltaTime);
}
for (var i = 0; i < this._objects.length; ++i) {
var object = this._objects[i];
object.updateY(deltaTime, this._colliders[object._collisionGroup]);
}
};
/**
* A platforming tile.
* @constructor
*/
var PlatformingTile = function() {
};
/**
* @return {number} floor height inside sloping tile.
*/
PlatformingTile.prototype.getFloorRelativeHeight = function(xInTile) {
return 0.0;
};
/**
* Set the position of the tile.
*/
PlatformingTile.prototype.setPos = function(x, y) {
this._x = x;
this._y = y;
};
/**
* @return {number} maximum floor height inside sloping tile.
*/
PlatformingTile.prototype.getMaxFloorRelativeHeight = function() {
return Math.max(this.getFloorRelativeHeight(0), this.getFloorRelativeHeight(1));
};
/**
* @return {boolean} True if the tile is a wall for movement towards any direction.
*/
PlatformingTile.prototype.isWall = function() {
return false;
};
/**
* @return {boolean} True if the tile is a wall for upwards movement (negative y).
*/
PlatformingTile.prototype.isWallUp = function() {
return false;
};
/**
* @return {boolean} True if the tile is sloped for objects moving above it.
*/
PlatformingTile.prototype.isFloorSlope = function() {
return false;
};
/**
* A tile with a sloped floor.
* @constructor
*/
var SlopedFloorTile = function(floorLeft, floorRight) {
this._floorLeft = floorLeft;
this._floorRight = floorRight;
this._maxFloor = Math.max(floorLeft, floorRight);
this._minFloor = Math.min(floorLeft, floorRight);
};
SlopedFloorTile.prototype = new PlatformingTile();
/**
* @return {number} floor height inside sloping tile. Must be monotonically increasing or decreasing inside the tile.
*/
SlopedFloorTile.prototype.getFloorRelativeHeight = function(xInTile) {
return mathUtil.clamp(this._minFloor, this._maxFloor, mathUtil.mix(this._floorLeft, this._floorRight, xInTile));
};
/**
* @return {boolean} True if the tile is sloped for objects moving above it.
*/
SlopedFloorTile.prototype.isFloorSlope = function() {
return true;
};
/**
* Render the sloped tile on a canvas.
* @param {CanvasRenderingContext2D} ctx 2D rendering context to use for drawing.
*/
SlopedFloorTile.prototype.render = function(ctx) {
ctx.beginPath();
ctx.moveTo(this._x, this._y + 1);
for (var x = 0; x <= 1; x += 0.25) {
var h = mathUtil.clamp(0, 1, this.getFloorRelativeHeight(x));
ctx.lineTo(this._x + x, this._y + 1 - h);
}
ctx.lineTo(this._x + 1, this._y + 1);
ctx.fill();
};
/**
* A tile that's a wall.
* @constructor
* @param {boolean} wallUp True if the wall affects upwards movement (negative y).
*/
var WallTile = function(wallUp) {
if (wallUp === undefined) {
wallUp = true;
}
this._wallUp = wallUp;
};
WallTile.prototype = new PlatformingTile();
/**
* @return {boolean} True if the tile is a wall for movement towards any direction.
*/
WallTile.prototype.isWall = function() {
return true;
};
/**
* @return {boolean} True if the tile is a wall for upwards movement (negative y).
*/
WallTile.prototype.isWallUp = function() {
return this._wallUp;
};
/**
* Get a tile map initializer based on an array of character codes representing tiles.
* @param {Array} data Tile letter codes in an array in row-major form. Example:
* ['xxx. /xxx ',
* ' xx^^^^^^xx '],
* Character codes are:
* x: wall.
* ^: can be jumped through from below, not passable from above.
* .: 45 degree slope rising towards left.
* /: 45 degree slope rising towards right.
* l: low 26 degree slope rising towards left.
* L: high 26 degree slope rising towards left.
* r: low 26 degree slope rising towards right.
* R: high 26 degree slope rising towards right.
* : empty space.
*
* @param {boolean?} flippedX Set to true to flip the data in the x direction.
* @return {function} Function that will initialize a TileMap with PlatformingTiles.
*/
PlatformingPhysics.initFromData = function(data, flippedX) {
if (flippedX === undefined) {
flippedX = false;
}
var transformedData = [];
for (var i = 0; i < data.length; ++i) {
var row = data[i];
var transformedRow = [];
for (var j = 0; j < row.length; ++j) {
var tile = null;
if (row[j] == 'x') {
tile = new WallTile(true);
} else if (row[j] == '^') {
tile = new WallTile(false);
} else if ((row[j] == '/' && !flippedX) || (row[j] == '.' && flippedX)) {
tile = new SlopedFloorTile(0, 1);
} else if ((row[j] == '.' && !flippedX) || (row[j] == '/' && flippedX)) {
tile = new SlopedFloorTile(1, 0);
} else if ((row[j] == 'L' && !flippedX) || (row[j] == 'R' && flippedX)) {
tile = new SlopedFloorTile(1, 0.5);
} else if ((row[j] == 'R' && !flippedX) || (row[j] == 'L' && flippedX)) {
tile = new SlopedFloorTile(0.5, 1);
} else if ((row[j] == 'l' && !flippedX) || (row[j] == 'r' && flippedX)) {
tile = new SlopedFloorTile(0.5, 0);
} else if ((row[j] == 'r' && !flippedX) || (row[j] == 'l' && flippedX)) {
tile = new SlopedFloorTile(0, 0.5);
} else {
tile = new PlatformingTile();
}
var x = j;
if (flippedX) {
x = row.length - j - 1;
}
tile.setPos(x, i);
transformedRow.push(tile);
}
transformedData.push(transformedRow);
}
return TileMap.initFromData(transformedData, flippedX);
};
/**
* Move an object along one axis, reacting to collisions.
* @param {Object} movingObj Object that moves. Needs to have the following properties in the world coordinate system:
* x, y, dx, dy, getRect()
* Properties to react to y collisions:
* touchGround(), touchCeiling()
* @param {number} deltaTime Time step to use to move the object.
* @param {string} dim Either 'x' or 'y' to move the object horizontally or vertically.
* @param {Array?} colliders List of objects to collide against. The moved object is automatically excluded in case it
* is in this array. Colliders must report coordinates relative to the world. Colliders must be PlatformingCharacters.
* @param {boolean} stayOnGround True if the character should try to follow the ground when going down on a slope.
*/
PlatformingPhysics.moveAndCollide = function(movingObj, deltaTime, dim, colliders, stayOnGround) {
var maxStepUp = 0.1;
var isWall = function(tile) {
return tile.isWall();
};
var isWallUp = function(tile) {
return tile.isWallUp();
};
var isFloorSlope = function(tile) {
return tile.isFloorSlope();
};
var done = false;
var delta = 0;
if (dim == 'x') {
delta = movingObj.dx * deltaTime;
} else {
delta = movingObj.dy * deltaTime;
}
var lastDelta = delta;
while (!done) {
var rect = movingObj.getRect();
done = true;
if (dim == 'x') {
var rectRightHalfWidth = rect.right - movingObj.x;
var rectLeftHalfWidth = movingObj.x - rect.left;
var rectBottomHalfHeight = rect.bottom - movingObj.y;
if (Math.abs(delta) > 0) {
movingObj.x += delta;
var xColliders = [];
if (colliders !== undefined) {
for (var i = 0; i < colliders.length; ++i) {
if (colliders[i] === movingObj) {
continue;
}
var collider = colliders[i].getRect();
if (rect.top < collider.bottom && collider.top < rect.bottom) {
if (colliders[i] instanceof PlatformingTileMap) {
xColliders.push(colliders[i]);
} else {
xColliders.push(collider);
}
}
}
}
var slopeFloorY = movingObj.y + rectBottomHalfHeight + TileMap.epsilon * 2;
if (delta > 0) {
var wallX = movingObj.x + rectRightHalfWidth + TileMap.epsilon * 2;
var slopeEndX = wallX;
for (var i = 0; i < xColliders.length; ++i) {
if (xColliders[i] instanceof PlatformingTileMap) {
var fromWorldToTileMap = new Vec2(-xColliders[i].lastX, -xColliders[i].lastY);
var relativeDelta = delta - xColliders[i].frameDeltaX;
var relativeRect = new Rect(rect.left, rect.right, rect.top, rect.bottom);
relativeRect.translate(fromWorldToTileMap);
var wallTileX = xColliders[i].tileMap.nearestTileRightFromRect(relativeRect, isWallUp, Math.abs(relativeDelta));
if (wallTileX != -1 && wallX > wallTileX + xColliders[i].x) {
wallX = wallTileX + xColliders[i].x;
}
var slopeTiles = xColliders[i].tileMap.getNearestTilesRightFromRect(relativeRect, isFloorSlope, Math.abs(relativeDelta));
if (slopeTiles.length != 0) {
var possibleWallX = slopeTiles[0]._x + xColliders[i].x;
for (var j = 0; j < slopeTiles.length; ++j) {
var slopeTile = slopeTiles[j];
var slopeBaseY = slopeTile._y + 1 + xColliders[i].y;
var slopeIsEffectivelyWall = (slopeBaseY - slopeTile.getFloorRelativeHeight(0) < rect.bottom - maxStepUp);
if (wallX > possibleWallX && slopeIsEffectivelyWall) {
wallX = possibleWallX;
}
if (!slopeIsEffectivelyWall) {
slopeEndX = slopeTile._x + 1 + xColliders[i].x;
var relativeX = movingObj.x - (slopeEndX - 1);
var slopeYRight = slopeBaseY -
slopeTile.getFloorRelativeHeight(relativeX + rectRightHalfWidth);
if (slopeFloorY > slopeYRight) {
slopeFloorY = slopeYRight;
}
}
}
}
} else {
if (xColliders[i].right > rect.left && wallX > xColliders[i].left) {
wallX = xColliders[i].left;
}
}
}
if (movingObj.x > slopeEndX - rectRightHalfWidth + TileMap.epsilon * 2) {
var afterOriginalMove = movingObj.x;
movingObj.x = slopeEndX - rectRightHalfWidth + TileMap.epsilon * 2;
delta = afterOriginalMove - movingObj.x;
// Finish this iteration on the tile boundary and continue movement on the next slope tile.
if (delta > TileMap.epsilon * 2 && delta < lastDelta) {
done = false;
lastDelta = delta;
}
}
if (movingObj.y > slopeFloorY - rectBottomHalfHeight - TileMap.epsilon) {
movingObj.y = slopeFloorY - rectBottomHalfHeight - TileMap.epsilon;
}
// Apply walls only when movement is done. When moving along a slope, the code may have placed
// the object right beyond the tile boundary for the next iteration so that movement wouldn't
// be stuck in a case like below:
// /
// obj-> /x
if (movingObj.x > wallX - rectRightHalfWidth - TileMap.epsilon && done) {
movingObj.x = wallX - rectRightHalfWidth - TileMap.epsilon;
}
} else {
var wallX = movingObj.x - rectLeftHalfWidth - TileMap.epsilon * 2;
var slopeEndX = wallX;
for (var i = 0; i < xColliders.length; ++i) {
if (xColliders[i] instanceof PlatformingTileMap) {
var fromWorldToTileMap = new Vec2(-xColliders[i].lastX, -xColliders[i].lastY);
var relativeDelta = delta - xColliders[i].frameDeltaX;
var relativeRect = new Rect(rect.left, rect.right, rect.top, rect.bottom);
relativeRect.translate(fromWorldToTileMap);
var wallTileX = xColliders[i].tileMap.nearestTileLeftFromRect(relativeRect, isWallUp, Math.abs(relativeDelta));
if (wallTileX != -1 && wallX < wallTileX + 1 + xColliders[i].x) {
wallX = wallTileX + 1 + xColliders[i].x;
}
var slopeTiles = xColliders[i].tileMap.getNearestTilesLeftFromRect(relativeRect, isFloorSlope, Math.abs(relativeDelta));
if (slopeTiles.length != 0) {
var possibleWallX = slopeTiles[0]._x + 1 + xColliders[i].x;
for (var j = 0; j < slopeTiles.length; ++j) {
var slopeTile = slopeTiles[j];
var slopeBaseY = slopeTile._y + 1 + xColliders[i].y;
var slopeIsEffectivelyWall = (slopeBaseY - slopeTile.getFloorRelativeHeight(1) < rect.bottom - maxStepUp);
if (wallX < possibleWallX && slopeIsEffectivelyWall) {
wallX = possibleWallX;
}
if (!slopeIsEffectivelyWall) {
slopeEndX = slopeTile._x + xColliders[i].x;
var relativeX = movingObj.x - slopeEndX;
var slopeYRight = slopeBaseY -
slopeTile.getFloorRelativeHeight(relativeX - rectLeftHalfWidth);
if (slopeFloorY > slopeYRight) {
slopeFloorY = slopeYRight;
}
}
}
}
} else {
if (xColliders[i].left < rect.right && wallX < xColliders[i].right) {
wallX = xColliders[i].right;
}
}
}
if (movingObj.x < slopeEndX + rectLeftHalfWidth - TileMap.epsilon * 2) {
var afterOriginalMove = movingObj.x;
movingObj.x = slopeEndX + rectLeftHalfWidth - TileMap.epsilon * 2;
delta = afterOriginalMove - movingObj.x;
// Finish this iteration on the tile boundary and continue movement on the next slope tile.
if (delta < -TileMap.epsilon * 2 && delta > lastDelta) {
done = false;
lastDelta = delta;
}
}
if (movingObj.y > slopeFloorY - rectBottomHalfHeight - TileMap.epsilon) {
movingObj.y = slopeFloorY - rectBottomHalfHeight - TileMap.epsilon;
}
// Apply walls only when movement is done. When moving along a slope, the code may have placed
// the object right beyond the tile boundary for the next iteration so that movement wouldn't
// be stuck in a case like below:
// .
// x. <- obj
if (movingObj.x < wallX + rectLeftHalfWidth + TileMap.epsilon && done) {
movingObj.x = wallX + rectLeftHalfWidth + TileMap.epsilon;
}
}
}
}
if (dim == 'y') {
var delta = movingObj.dy * deltaTime;
var rectBottomHalfHeight = rect.bottom - movingObj.y;
var rectTopHalfHeight = movingObj.y - rect.top;
var rectRightHalfWidth = rect.right - movingObj.x;
var rectLeftHalfWidth = movingObj.x - rect.left;
if (Math.abs(delta) > 0) {
var lastY = movingObj.y;
movingObj.y += delta;
var yColliders = [];
if (colliders !== undefined) {
for (var i = 0; i < colliders.length; ++i) {
if (colliders[i] === movingObj) {
continue;
}
var collider = colliders[i].getRect();
if (rect.left < collider.right && collider.left < rect.right) {
if (colliders[i] instanceof PlatformingTileMap) {
yColliders.push(colliders[i]);
} else {
yColliders.push(collider);
}
}
}
}
if (delta > 0) {
var wallY = movingObj.y + rectBottomHalfHeight + 1 + TileMap.epsilon;
var hitSlope = false;
for (var i = 0; i < yColliders.length; ++i) {
if (yColliders[i] instanceof PlatformingTileMap) {
// X movement has already been fully evaluated
var fromWorldToTileMap = new Vec2(-yColliders[i].x, -yColliders[i].lastY);
var relativeDelta = delta - yColliders[i].frameDeltaY;
var relativeRect = new Rect(rect.left, rect.right, rect.top, rect.bottom);
relativeRect.translate(fromWorldToTileMap);
var origBottom = relativeRect.bottom;
relativeRect.bottom += 1;
var wallTileY = yColliders[i].tileMap.nearestTileDownFromRect(relativeRect, isWall, Math.abs(relativeDelta));
if (wallTileY != -1 && wallY > wallTileY + yColliders[i].y) {
wallY = wallTileY + yColliders[i].y;
hitSlope = false;
}
relativeRect.bottom = origBottom;
var slopeTiles = yColliders[i].tileMap.getNearestTilesDownFromRect(relativeRect, isFloorSlope,
Math.max(Math.abs(relativeDelta), 1));
if (slopeTiles.length != 0 && wallY > slopeTiles[0]._y + yColliders[i].y) {
for (var j = 0; j < slopeTiles.length; ++j) {
var slopeTile = slopeTiles[j];
var relativeX = movingObj.x - (slopeTile._x + yColliders[i].x);
var slopeBaseY = slopeTile._y + 1 + yColliders[i].y;
var slopeYLeft = slopeBaseY -
slopeTile.getFloorRelativeHeight(relativeX - rectLeftHalfWidth);
var slopeYRight = slopeBaseY -
slopeTile.getFloorRelativeHeight(relativeX + rectRightHalfWidth);
if (slopeYLeft < wallY) {
wallY = slopeYLeft;
hitSlope = true;
}
if (slopeYRight < wallY) {
wallY = slopeYRight;
hitSlope = true;
}
}
}
} else {
if (yColliders[i].bottom > rect.top && wallY > yColliders[i].top) {
wallY = yColliders[i].top;
}
}
}
if (movingObj.y > wallY - rectBottomHalfHeight - TileMap.epsilon) {
movingObj.y = wallY - rectBottomHalfHeight - TileMap.epsilon;
movingObj.touchGround();
} else if (hitSlope && stayOnGround) {
// TODO: There's still a bug where the character teleports downwards when there's a slope like this:
// .
// xl
movingObj.y = wallY - rectBottomHalfHeight - TileMap.epsilon;
movingObj.touchGround();
}
} else {
var wallY = movingObj.y - rectTopHalfHeight - TileMap.epsilon * 2;
for (var i = 0; i < yColliders.length; ++i) {
if (yColliders[i] instanceof PlatformingTileMap) {
// X movement has already been fully evaluated
var fromWorldToTileMap = new Vec2(-yColliders[i].x, -yColliders[i].lastY);
var relativeDelta = delta - yColliders[i].frameDeltaY;
var relativeRect = new Rect(rect.left, rect.right, rect.top, rect.bottom);
relativeRect.translate(fromWorldToTileMap);
var wallTileY = yColliders[i].tileMap.nearestTileUpFromRect(relativeRect, isWallUp, Math.abs(relativeDelta));
if (wallTileY != -1 && wallY < wallTileY + 1 + yColliders[i].y) {
wallY = wallTileY + 1 + yColliders[i].y;
}
} else {
if (yColliders[i].top < rect.bottom && wallY < yColliders[i].bottom) {
wallY = yColliders[i].bottom;
}
}
}
if (movingObj.y < wallY + rectTopHalfHeight + TileMap.epsilon) {
movingObj.y = wallY + rectTopHalfHeight + TileMap.epsilon;
movingObj.touchCeiling();
}
}
}
}
}
};
/**
* Render sloped tiles to a canvas.
* @param {TileMap} tileMap Map to render.
* @param {CanvasRenderingContext2D} ctx 2D rendering context to use for drawing.
*/
PlatformingPhysics.renderSlopes = function(tileMap, ctx) {
for (var y = 0; y < tileMap.height; ++y) {
for (var x = 0; x < tileMap.width; ++x) {
var tile = tileMap.tiles[y][x];
if (tile.isFloorSlope()) {
tile.render(ctx);
}
}
}
};
| Rename wall variables to indicate direction
An object moving to the right might still be pushed by a wall moving in
from the left, so the code needs to be refactored to support that.
| src/platformingphysics.js | Rename wall variables to indicate direction | <ide><path>rc/platformingphysics.js
<ide> }
<ide> var slopeFloorY = movingObj.y + rectBottomHalfHeight + TileMap.epsilon * 2;
<ide> if (delta > 0) {
<del> var wallX = movingObj.x + rectRightHalfWidth + TileMap.epsilon * 2;
<del> var slopeEndX = wallX;
<add> var wallXRight = movingObj.x + rectRightHalfWidth + TileMap.epsilon * 2;
<add> var slopeEndX = wallXRight;
<ide> for (var i = 0; i < xColliders.length; ++i) {
<ide> if (xColliders[i] instanceof PlatformingTileMap) {
<ide> var fromWorldToTileMap = new Vec2(-xColliders[i].lastX, -xColliders[i].lastY);
<ide> var relativeRect = new Rect(rect.left, rect.right, rect.top, rect.bottom);
<ide> relativeRect.translate(fromWorldToTileMap);
<ide> var wallTileX = xColliders[i].tileMap.nearestTileRightFromRect(relativeRect, isWallUp, Math.abs(relativeDelta));
<del> if (wallTileX != -1 && wallX > wallTileX + xColliders[i].x) {
<del> wallX = wallTileX + xColliders[i].x;
<add> if (wallTileX != -1 && wallXRight > wallTileX + xColliders[i].x) {
<add> wallXRight = wallTileX + xColliders[i].x;
<ide> }
<ide> var slopeTiles = xColliders[i].tileMap.getNearestTilesRightFromRect(relativeRect, isFloorSlope, Math.abs(relativeDelta));
<ide> if (slopeTiles.length != 0) {
<ide> var slopeTile = slopeTiles[j];
<ide> var slopeBaseY = slopeTile._y + 1 + xColliders[i].y;
<ide> var slopeIsEffectivelyWall = (slopeBaseY - slopeTile.getFloorRelativeHeight(0) < rect.bottom - maxStepUp);
<del> if (wallX > possibleWallX && slopeIsEffectivelyWall) {
<del> wallX = possibleWallX;
<add> if (wallXRight > possibleWallX && slopeIsEffectivelyWall) {
<add> wallXRight = possibleWallX;
<ide> }
<ide> if (!slopeIsEffectivelyWall) {
<ide> slopeEndX = slopeTile._x + 1 + xColliders[i].x;
<ide> }
<ide> }
<ide> } else {
<del> if (xColliders[i].right > rect.left && wallX > xColliders[i].left) {
<del> wallX = xColliders[i].left;
<add> if (xColliders[i].right > rect.left && wallXRight > xColliders[i].left) {
<add> wallXRight = xColliders[i].left;
<ide> }
<ide> }
<ide> }
<ide> // be stuck in a case like below:
<ide> // /
<ide> // obj-> /x
<del> if (movingObj.x > wallX - rectRightHalfWidth - TileMap.epsilon && done) {
<del> movingObj.x = wallX - rectRightHalfWidth - TileMap.epsilon;
<add> if (movingObj.x > wallXRight - rectRightHalfWidth - TileMap.epsilon && done) {
<add> movingObj.x = wallXRight - rectRightHalfWidth - TileMap.epsilon;
<ide> }
<ide> } else {
<del> var wallX = movingObj.x - rectLeftHalfWidth - TileMap.epsilon * 2;
<del> var slopeEndX = wallX;
<add> var wallXLeft = movingObj.x - rectLeftHalfWidth - TileMap.epsilon * 2;
<add> var slopeEndX = wallXLeft;
<ide> for (var i = 0; i < xColliders.length; ++i) {
<ide> if (xColliders[i] instanceof PlatformingTileMap) {
<ide> var fromWorldToTileMap = new Vec2(-xColliders[i].lastX, -xColliders[i].lastY);
<ide> var relativeRect = new Rect(rect.left, rect.right, rect.top, rect.bottom);
<ide> relativeRect.translate(fromWorldToTileMap);
<ide> var wallTileX = xColliders[i].tileMap.nearestTileLeftFromRect(relativeRect, isWallUp, Math.abs(relativeDelta));
<del> if (wallTileX != -1 && wallX < wallTileX + 1 + xColliders[i].x) {
<del> wallX = wallTileX + 1 + xColliders[i].x;
<add> if (wallTileX != -1 && wallXLeft < wallTileX + 1 + xColliders[i].x) {
<add> wallXLeft = wallTileX + 1 + xColliders[i].x;
<ide> }
<ide> var slopeTiles = xColliders[i].tileMap.getNearestTilesLeftFromRect(relativeRect, isFloorSlope, Math.abs(relativeDelta));
<ide> if (slopeTiles.length != 0) {
<ide> var slopeTile = slopeTiles[j];
<ide> var slopeBaseY = slopeTile._y + 1 + xColliders[i].y;
<ide> var slopeIsEffectivelyWall = (slopeBaseY - slopeTile.getFloorRelativeHeight(1) < rect.bottom - maxStepUp);
<del> if (wallX < possibleWallX && slopeIsEffectivelyWall) {
<del> wallX = possibleWallX;
<add> if (wallXLeft < possibleWallX && slopeIsEffectivelyWall) {
<add> wallXLeft = possibleWallX;
<ide> }
<ide> if (!slopeIsEffectivelyWall) {
<ide> slopeEndX = slopeTile._x + xColliders[i].x;
<ide> }
<ide> }
<ide> } else {
<del> if (xColliders[i].left < rect.right && wallX < xColliders[i].right) {
<del> wallX = xColliders[i].right;
<add> if (xColliders[i].left < rect.right && wallXLeft < xColliders[i].right) {
<add> wallXLeft = xColliders[i].right;
<ide> }
<ide> }
<ide> }
<ide> // be stuck in a case like below:
<ide> // .
<ide> // x. <- obj
<del> if (movingObj.x < wallX + rectLeftHalfWidth + TileMap.epsilon && done) {
<del> movingObj.x = wallX + rectLeftHalfWidth + TileMap.epsilon;
<add> if (movingObj.x < wallXLeft + rectLeftHalfWidth + TileMap.epsilon && done) {
<add> movingObj.x = wallXLeft + rectLeftHalfWidth + TileMap.epsilon;
<ide> }
<ide> }
<ide> }
<del> }
<add> } // dim == 'x'
<ide> if (dim == 'y') {
<ide> var delta = movingObj.dy * deltaTime;
<ide> var rectBottomHalfHeight = rect.bottom - movingObj.y;
<ide> }
<ide> }
<ide> if (delta > 0) {
<del> var wallY = movingObj.y + rectBottomHalfHeight + 1 + TileMap.epsilon;
<add> var wallYDown = movingObj.y + rectBottomHalfHeight + 1 + TileMap.epsilon;
<ide> var hitSlope = false;
<ide> for (var i = 0; i < yColliders.length; ++i) {
<ide> if (yColliders[i] instanceof PlatformingTileMap) {
<ide> var origBottom = relativeRect.bottom;
<ide> relativeRect.bottom += 1;
<ide> var wallTileY = yColliders[i].tileMap.nearestTileDownFromRect(relativeRect, isWall, Math.abs(relativeDelta));
<del> if (wallTileY != -1 && wallY > wallTileY + yColliders[i].y) {
<del> wallY = wallTileY + yColliders[i].y;
<add> if (wallTileY != -1 && wallYDown > wallTileY + yColliders[i].y) {
<add> wallYDown = wallTileY + yColliders[i].y;
<ide> hitSlope = false;
<ide> }
<ide> relativeRect.bottom = origBottom;
<ide> var slopeTiles = yColliders[i].tileMap.getNearestTilesDownFromRect(relativeRect, isFloorSlope,
<ide> Math.max(Math.abs(relativeDelta), 1));
<del> if (slopeTiles.length != 0 && wallY > slopeTiles[0]._y + yColliders[i].y) {
<add> if (slopeTiles.length != 0 && wallYDown > slopeTiles[0]._y + yColliders[i].y) {
<ide> for (var j = 0; j < slopeTiles.length; ++j) {
<ide> var slopeTile = slopeTiles[j];
<ide> var relativeX = movingObj.x - (slopeTile._x + yColliders[i].x);
<ide> slopeTile.getFloorRelativeHeight(relativeX - rectLeftHalfWidth);
<ide> var slopeYRight = slopeBaseY -
<ide> slopeTile.getFloorRelativeHeight(relativeX + rectRightHalfWidth);
<del> if (slopeYLeft < wallY) {
<del> wallY = slopeYLeft;
<add> if (slopeYLeft < wallYDown) {
<add> wallYDown = slopeYLeft;
<ide> hitSlope = true;
<ide> }
<del> if (slopeYRight < wallY) {
<del> wallY = slopeYRight;
<add> if (slopeYRight < wallYDown) {
<add> wallYDown = slopeYRight;
<ide> hitSlope = true;
<ide> }
<ide> }
<ide> }
<ide> } else {
<del> if (yColliders[i].bottom > rect.top && wallY > yColliders[i].top) {
<del> wallY = yColliders[i].top;
<del> }
<del> }
<del> }
<del> if (movingObj.y > wallY - rectBottomHalfHeight - TileMap.epsilon) {
<del> movingObj.y = wallY - rectBottomHalfHeight - TileMap.epsilon;
<add> if (yColliders[i].bottom > rect.top && wallYDown > yColliders[i].top) {
<add> wallYDown = yColliders[i].top;
<add> }
<add> }
<add> }
<add> if (movingObj.y > wallYDown - rectBottomHalfHeight - TileMap.epsilon) {
<add> movingObj.y = wallYDown - rectBottomHalfHeight - TileMap.epsilon;
<ide> movingObj.touchGround();
<ide> } else if (hitSlope && stayOnGround) {
<ide> // TODO: There's still a bug where the character teleports downwards when there's a slope like this:
<ide> // .
<ide> // xl
<del> movingObj.y = wallY - rectBottomHalfHeight - TileMap.epsilon;
<add> movingObj.y = wallYDown - rectBottomHalfHeight - TileMap.epsilon;
<ide> movingObj.touchGround();
<ide> }
<ide> } else {
<del> var wallY = movingObj.y - rectTopHalfHeight - TileMap.epsilon * 2;
<add> var wallYUp = movingObj.y - rectTopHalfHeight - TileMap.epsilon * 2;
<ide> for (var i = 0; i < yColliders.length; ++i) {
<ide> if (yColliders[i] instanceof PlatformingTileMap) {
<ide> // X movement has already been fully evaluated
<ide> var relativeRect = new Rect(rect.left, rect.right, rect.top, rect.bottom);
<ide> relativeRect.translate(fromWorldToTileMap);
<ide> var wallTileY = yColliders[i].tileMap.nearestTileUpFromRect(relativeRect, isWallUp, Math.abs(relativeDelta));
<del> if (wallTileY != -1 && wallY < wallTileY + 1 + yColliders[i].y) {
<del> wallY = wallTileY + 1 + yColliders[i].y;
<add> if (wallTileY != -1 && wallYUp < wallTileY + 1 + yColliders[i].y) {
<add> wallYUp = wallTileY + 1 + yColliders[i].y;
<ide> }
<ide> } else {
<del> if (yColliders[i].top < rect.bottom && wallY < yColliders[i].bottom) {
<del> wallY = yColliders[i].bottom;
<del> }
<del> }
<del> }
<del> if (movingObj.y < wallY + rectTopHalfHeight + TileMap.epsilon) {
<del> movingObj.y = wallY + rectTopHalfHeight + TileMap.epsilon;
<add> if (yColliders[i].top < rect.bottom && wallYUp < yColliders[i].bottom) {
<add> wallYUp = yColliders[i].bottom;
<add> }
<add> }
<add> }
<add> if (movingObj.y < wallYUp + rectTopHalfHeight + TileMap.epsilon) {
<add> movingObj.y = wallYUp + rectTopHalfHeight + TileMap.epsilon;
<ide> movingObj.touchCeiling();
<ide> }
<ide> } |
|
Java | mit | cbaf8bbcbbf1bc064a3a66139d999313d595bd3f | 0 | objectify/objectify,naveen514/objectify-appengine,asolfre/objectify-appengine,zenmeso/objectify-appengine,google-code-export/objectify-appengine,qickrooms/objectify-appengine,RudiaMoon/objectify-appengine | /*
*/
package com.googlecode.objectify.test;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import com.google.appengine.api.memcache.MemcacheService;
import com.google.appengine.api.memcache.MemcacheServiceFactory;
import com.googlecode.objectify.Key;
import com.googlecode.objectify.Ref;
import com.googlecode.objectify.annotation.Entity;
import com.googlecode.objectify.annotation.Id;
import com.googlecode.objectify.annotation.Load;
import com.googlecode.objectify.test.RefTests.HasRef.Foo;
import com.googlecode.objectify.test.entity.Trivial;
import com.googlecode.objectify.test.util.TestBase;
import com.googlecode.objectify.test.util.TestObjectify;
/**
* Tests the behavior of Refs.
*
* @author Jeff Schnitzer <[email protected]>
*/
public class RefTests extends TestBase
{
Trivial t1;
Trivial t2;
Key<Trivial> k1;
Key<Trivial> k2;
Key<Trivial> kNone;
/** */
@BeforeMethod
public void createTwo() {
fact.register(Trivial.class);
TestObjectify ofy = fact.begin();
t1 = new Trivial("foo", 11);
k1 = ofy.put(t1);
t2 = new Trivial("bar", 22);
k2 = ofy.put(t2);
kNone = Key.create(Trivial.class, 12345L);
}
// /** */
// @Test
// public void testGet() throws Exception {
// TestObjectify ofy = fact.begin();
//
// Ref<Trivial> ref = Ref.create(k1);
//
// ofy.getRef(ref);
// assert ref.value().getSomeString().equals(t1);
//
// try {
// ofy.getRef(Ref.create(kNone));
// assert false;
// } catch (NotFoundException ex) {}
// }
/** */
@Test
public void standaloneLoad() throws Exception {
Ref<Trivial> ref = Ref.create(k1);
assert !ref.isLoaded();
Trivial loaded = ref.get();
assert ref.isLoaded();
assert loaded.getSomeString().equals(t1.getSomeString());
}
/** */
@Test
public void loadRefFromOfy() throws Exception {
TestObjectify ofy = fact.begin();
Ref<Trivial> ref = Ref.create(k1);
assert !ref.isLoaded();
Ref<Trivial> ref2 = ofy.load().ref(ref);
assert ref.isLoaded();
assert ref2.isLoaded();
assert ref2.get().getSomeString().equals(t1.getSomeString());
}
/** */
@Test
public void testGetRefsVarargs() throws Exception {
TestObjectify ofy = fact.begin();
Ref<Trivial> ref1 = Ref.create(k1);
Ref<Trivial> ref2 = Ref.create(k2);
Ref<Trivial> refNone = Ref.create(kNone);
@SuppressWarnings({ "unused", "unchecked" })
Object foo = ofy.load().refs(ref1, ref2, refNone);
assert ref1.isLoaded();
assert ref2.isLoaded();
assert refNone.isLoaded();
assert ref1.get().getSomeString().equals(t1.getSomeString());
assert ref2.get().getSomeString().equals(t2.getSomeString());
assert refNone.get() == null;
}
/** */
@Test
public void testGetRefsIterable() throws Exception {
TestObjectify ofy = fact.begin();
Ref<Trivial> ref1 = Ref.create(k1);
Ref<Trivial> ref2 = Ref.create(k2);
Ref<Trivial> refNone = Ref.create(kNone);
List<Ref<Trivial>> list = new ArrayList<Ref<Trivial>>();
list.add(ref1);
list.add(ref2);
list.add(refNone);
ofy.load().refs(list);
assert ref1.isLoaded();
assert ref2.isLoaded();
assert refNone.isLoaded();
assert ref1.get().getSomeString().equals(t1.getSomeString());
assert ref2.get().getSomeString().equals(t2.getSomeString());
assert refNone.get() == null;
}
/** */
@Entity
static class HasRef implements Serializable {
private static final long serialVersionUID = 1L;
public static class Foo {}
public @Id Long id;
public @Load(Foo.class) Ref<Trivial> triv;
}
/** */
@Test
public void refsMustBeSerializable() throws Exception {
fact.register(HasRef.class);
HasRef hr = new HasRef();
hr.triv = Ref.create(k1);
HasRef fetched = putClearGet(hr);
// Now try to serialize it in memcache.
MemcacheService ms = MemcacheServiceFactory.getMemcacheService();
ms.put("thing", fetched);
HasRef serialized = (HasRef)ms.get("thing");
assert serialized.id.equals(hr.id);
}
/** */
@Test
public void refsLoadedMustBeSerializable() throws Exception {
fact.register(HasRef.class);
HasRef hr = new HasRef();
hr.triv = Ref.create(k1);
TestObjectify ofy = fact.begin();
ofy.put(hr);
ofy.clear();
HasRef fetched = ofy.load().group(Foo.class).entity(hr).get();
// Now try to serialize it in memcache.
MemcacheService ms = MemcacheServiceFactory.getMemcacheService();
ms.put("thing", fetched);
HasRef serialized = (HasRef)ms.get("thing");
assert serialized.id.equals(hr.id);
assert serialized.triv.get().getSomeString().equals(t1.getSomeString());
}
} | src/test/java/com/googlecode/objectify/test/RefTests.java | /*
*/
package com.googlecode.objectify.test;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import com.google.appengine.api.memcache.MemcacheService;
import com.google.appengine.api.memcache.MemcacheServiceFactory;
import com.googlecode.objectify.Key;
import com.googlecode.objectify.Ref;
import com.googlecode.objectify.annotation.Entity;
import com.googlecode.objectify.annotation.Id;
import com.googlecode.objectify.annotation.Load;
import com.googlecode.objectify.test.RefTests.HasRef.Foo;
import com.googlecode.objectify.test.entity.Trivial;
import com.googlecode.objectify.test.util.TestBase;
import com.googlecode.objectify.test.util.TestObjectify;
/**
* Tests simple use of the getRef() methods on Objectify
*
* @author Jeff Schnitzer <[email protected]>
*/
public class RefTests extends TestBase
{
Trivial t1;
Trivial t2;
Key<Trivial> k1;
Key<Trivial> k2;
Key<Trivial> kNone;
/** */
@BeforeMethod
public void createTwo() {
fact.register(Trivial.class);
TestObjectify ofy = fact.begin();
t1 = new Trivial("foo", 11);
k1 = ofy.put(t1);
t2 = new Trivial("bar", 22);
k2 = ofy.put(t2);
kNone = Key.create(Trivial.class, 12345L);
}
// /** */
// @Test
// public void testGet() throws Exception {
// TestObjectify ofy = fact.begin();
//
// Ref<Trivial> ref = Ref.create(k1);
//
// ofy.getRef(ref);
// assert ref.value().getSomeString().equals(t1);
//
// try {
// ofy.getRef(Ref.create(kNone));
// assert false;
// } catch (NotFoundException ex) {}
// }
/** */
@Test
public void testFind() throws Exception {
TestObjectify ofy = fact.begin();
Ref<Trivial> ref = Ref.create(k1);
ofy.load().ref(ref);
assert ref.get().getSomeString().equals(t1.getSomeString());
}
/** */
@Test
public void testGetRefsVarargs() throws Exception {
TestObjectify ofy = fact.begin();
Ref<Trivial> ref1 = Ref.create(k1);
Ref<Trivial> ref2 = Ref.create(k2);
Ref<Trivial> refNone = Ref.create(kNone);
@SuppressWarnings({ "unused", "unchecked" })
Object foo = ofy.load().refs(ref1, ref2, refNone);
assert ref1.get().getSomeString().equals(t1.getSomeString());
assert ref2.get().getSomeString().equals(t2.getSomeString());
assert refNone.get() == null;
}
/** */
@Test
public void testGetRefsIterable() throws Exception {
TestObjectify ofy = fact.begin();
Ref<Trivial> ref1 = Ref.create(k1);
Ref<Trivial> ref2 = Ref.create(k2);
Ref<Trivial> refNone = Ref.create(kNone);
List<Ref<Trivial>> list = new ArrayList<Ref<Trivial>>();
list.add(ref1);
list.add(ref2);
list.add(refNone);
ofy.load().refs(list);
assert ref1.get().getSomeString().equals(t1.getSomeString());
assert ref2.get().getSomeString().equals(t2.getSomeString());
assert refNone.get() == null;
}
/** */
@Entity
static class HasRef implements Serializable {
private static final long serialVersionUID = 1L;
public static class Foo {}
public @Id Long id;
public @Load(Foo.class) Ref<Trivial> triv;
}
/** */
@Test
public void refsMustBeSerializable() throws Exception {
fact.register(HasRef.class);
HasRef hr = new HasRef();
hr.triv = Ref.create(k1);
HasRef fetched = putClearGet(hr);
// Now try to serialize it in memcache.
MemcacheService ms = MemcacheServiceFactory.getMemcacheService();
ms.put("thing", fetched);
HasRef serialized = (HasRef)ms.get("thing");
assert serialized.id.equals(hr.id);
}
/** */
@Test
public void refsLoadedMustBeSerializable() throws Exception {
fact.register(HasRef.class);
HasRef hr = new HasRef();
hr.triv = Ref.create(k1);
TestObjectify ofy = fact.begin();
ofy.put(hr);
ofy.clear();
HasRef fetched = ofy.load().group(Foo.class).entity(hr).get();
// Now try to serialize it in memcache.
MemcacheService ms = MemcacheServiceFactory.getMemcacheService();
ms.put("thing", fetched);
HasRef serialized = (HasRef)ms.get("thing");
assert serialized.id.equals(hr.id);
assert serialized.triv.get().getSomeString().equals(t1.getSomeString());
}
} | Better ref tests
| src/test/java/com/googlecode/objectify/test/RefTests.java | Better ref tests | <ide><path>rc/test/java/com/googlecode/objectify/test/RefTests.java
<ide> import com.googlecode.objectify.test.util.TestObjectify;
<ide>
<ide> /**
<del> * Tests simple use of the getRef() methods on Objectify
<add> * Tests the behavior of Refs.
<ide> *
<ide> * @author Jeff Schnitzer <[email protected]>
<ide> */
<ide>
<ide> /** */
<ide> @Test
<del> public void testFind() throws Exception {
<add> public void standaloneLoad() throws Exception {
<add> Ref<Trivial> ref = Ref.create(k1);
<add> assert !ref.isLoaded();
<add>
<add> Trivial loaded = ref.get();
<add> assert ref.isLoaded();
<add> assert loaded.getSomeString().equals(t1.getSomeString());
<add> }
<add>
<add> /** */
<add> @Test
<add> public void loadRefFromOfy() throws Exception {
<ide> TestObjectify ofy = fact.begin();
<ide>
<ide> Ref<Trivial> ref = Ref.create(k1);
<add> assert !ref.isLoaded();
<ide>
<del> ofy.load().ref(ref);
<del> assert ref.get().getSomeString().equals(t1.getSomeString());
<add> Ref<Trivial> ref2 = ofy.load().ref(ref);
<add> assert ref.isLoaded();
<add> assert ref2.isLoaded();
<add>
<add> assert ref2.get().getSomeString().equals(t1.getSomeString());
<ide> }
<ide>
<ide> /** */
<ide>
<ide> @SuppressWarnings({ "unused", "unchecked" })
<ide> Object foo = ofy.load().refs(ref1, ref2, refNone);
<add>
<add> assert ref1.isLoaded();
<add> assert ref2.isLoaded();
<add> assert refNone.isLoaded();
<ide>
<ide> assert ref1.get().getSomeString().equals(t1.getSomeString());
<ide> assert ref2.get().getSomeString().equals(t2.getSomeString());
<ide> list.add(refNone);
<ide>
<ide> ofy.load().refs(list);
<add>
<add> assert ref1.isLoaded();
<add> assert ref2.isLoaded();
<add> assert refNone.isLoaded();
<ide>
<ide> assert ref1.get().getSomeString().equals(t1.getSomeString());
<ide> assert ref2.get().getSomeString().equals(t2.getSomeString()); |
|
JavaScript | mit | 1ba2b18af2dd629b4895921c266040c88abd5c83 | 0 | tgriesser/bookshelf,tgriesser/bookshelf,bookshelf/bookshelf,bookshelf/bookshelf | 'use strict';
const _ = require('lodash');
const helpers = require('./helpers');
// We've supplemented `Events` with a `triggerThen` method to allow for
// asynchronous event handling via promises. We also mix this into the
// prototypes of the main objects in the library.
const Events = require('./base/events');
// All core modules required for the bookshelf instance.
const BookshelfModel = require('./model');
const BookshelfCollection = require('./collection');
const BookshelfRelation = require('./relation');
const Errors = require('./errors');
/**
* @class Bookshelf
* @classdesc
*
* The Bookshelf library is initialized by passing an initialized Knex client
* instance. The knex documentation provides a number of examples for different
* databases.
*
* @constructor
* @param {Knex} knex Knex instance.
*/
function Bookshelf(knex) {
if (!knex || knex.name !== 'knex') {
throw new Error('Invalid knex instance');
}
const bookshelf = {
VERSION: require('../package.json').version
};
const Model = (bookshelf.Model = BookshelfModel.extend(
{
_builder: builderFn,
// The `Model` constructor is referenced as a property on the `Bookshelf`
// instance, mixing in the correct `builder` method, as well as the
// `relation` method, passing in the correct `Model` & `Collection`
// constructors for later reference.
_relation(type, Target, options) {
if (type !== 'morphTo' && !_.isFunction(Target)) {
throw new Error(
'A valid target model must be defined for the ' + _.result(this, 'tableName') + ' ' + type + ' relation'
);
}
return new Relation(type, Target, options);
}
},
{
/**
* @method Model.forge
* @belongsTo Model
* @description
*
* A simple helper function to instantiate a new Model without needing `new`.
*
* @param {Object=} attributes Initial values for this model's attributes.
* @param {Object=} options Hash of options.
* @param {string=} options.tableName Initial value for {@linkcode Model#tableName tableName}.
* @param {Boolean=} [options.hasTimestamps=false]
*
* Initial value for {@linkcode Model#hasTimestamps hasTimestamps}.
*
* @param {Boolean} [options.parse=false]
*
* Convert attributes by {@linkcode Model#parse parse} before being
* {@linkcode Model#set set} on the `model`.
*/
forge: function forge(attributes, options) {
return new this(attributes, options);
},
/**
* @method Model.collection
* @belongsTo Model
* @description
*
* A simple static helper to instantiate a new {@link Collection}, setting
* the current `model` as the collection's target.
*
* @example
*
* Customer.collection().fetch().then(function(collection) {
* // ...
* });
*
* @param {(Model[])=} models
* @param {Object=} options
* @returns {Collection}
*/
collection(models, options) {
return new bookshelf.Collection(models || [], _.extend({}, options, {model: this}));
},
/**
* @method Model.count
* @belongsTo Model
* @since 0.8.2
* @description
*
* Gets the number of matching records in the database, respecting any
* previous calls to {@link Model#query query}. If a `column` is provided,
* records with a null value in that column will be excluded from the count.
*
* @param {string} [column='*']
* Specify a column to count - rows with null values in this column will be excluded.
* @param {Object=} options
* Hash of options.
* @returns {Promise<Number>}
* A promise resolving to the number of matching rows.
*/
count(column, options) {
return this.forge().count(column, options);
},
/**
* @method Model.fetchAll
* @belongsTo Model
* @description
*
* Simple helper function for retrieving all instances of the given model.
*
* @see Model#fetchAll
* @returns {Promise<Collection>}
*/
fetchAll(options) {
return this.forge().fetchAll(options);
}
}
));
const Collection = (bookshelf.Collection = BookshelfCollection.extend(
{
_builder: builderFn
},
{
/**
* @method Collection.forge
* @belongsTo Collection
* @description
*
* A simple helper function to instantiate a new Collection without needing
* new.
*
* @param {(Object[]|Model[])=} [models]
* Set of models (or attribute hashes) with which to initialize the
* collection.
* @param {Object} options Hash of options.
*
* @example
*
* var Promise = require('bluebird');
* var Accounts = bookshelf.Collection.extend({
* model: Account
* });
*
* var accounts = Accounts.forge([
* {name: 'Person1'},
* {name: 'Person2'}
* ]);
*
* Promise.all(accounts.invokeMap('save')).then(function() {
* // collection models should now be saved...
* });
*/
forge: function forge(models, options) {
return new this(models, options);
}
}
));
// The collection also references the correct `Model`, specified above, for
// creating new `Model` instances in the collection.
Collection.prototype.model = Model;
Model.prototype.Collection = Collection;
const Relation = BookshelfRelation.extend({Model, Collection});
// A `Bookshelf` instance may be used as a top-level pub-sub bus, as it mixes
// in the `Events` object. It also contains the version number, and a
// `Transaction` method referencing the correct version of `knex` passed into
// the object.
_.extend(bookshelf, Events, Errors, {
/**
* An alias to `{@link http://knexjs.org/#Transactions Knex#transaction}`. The `transaction`
* object must be passed along in the options of any relevant Bookshelf calls, to ensure all
* queries are on the same connection. The entire transaction block is wrapped around a Promise
* that will commit the transaction if it resolves successfully, or roll it back if the Promise
* is rejected.
*
* Note that there is no need to explicitly call `transaction.commit()` or
* `transaction.rollback()` since the entire transaction will be committed if there are no
* errors inside the transaction block.
*
* When fetching inside a transaction it's possible to specify a row-level lock by passing the
* wanted lock type in the `lock` option to {@linkcode Model#fetch fetch}. Available options are
* `lock: 'forUpdate'` and `lock: 'forShare'`.
*
* @example
* var Promise = require('bluebird')
*
* Bookshelf.transaction((t) => {
* return new Library({name: 'Old Books'})
* .save(null, {transacting: t})
* .tap(function(model) {
* return Promise.map([
* {title: 'Canterbury Tales'},
* {title: 'Moby Dick'},
* {title: 'Hamlet'}
* ], (info) => {
* return new Book(info).save({'shelf_id': model.id}, {transacting: t})
* })
* })
* }).then((library) => {
* console.log(library.related('books').pluck('title'))
* }).catch((err) => {
* console.error(err)
* })
*
* @method Bookshelf#transaction
* @param {Bookshelf~transactionCallback} transactionCallback
* Callback containing transaction logic. The callback should return a Promise.
* @returns {Promise}
* A promise resolving to the value returned from
* {@link Bookshelf~transactionCallback transactionCallback}.
*/
transaction() {
return this.knex.transaction.apply(this.knex, arguments);
},
/**
* This is a transaction block to be provided to {@link Bookshelf#transaction}. All of the
* database operations inside it can be part of the same transaction by passing the
* `transacting: transaction` option to {@link Model#fetch fetch}, {@link Model#save save} or
* {@link Model#destroy destroy}.
*
* Note that unless you explicitly pass the `transaction` object along to any relevant model
* operations, those operations will not be part of the transaction, even though they may be
* inside the transaction callback.
*
* @callback Bookshelf~transactionCallback
* @see {@link http://knexjs.org/#Transactions Knex#transaction}
* @see Bookshelf#transaction
*
* @param {Transaction} transaction
* @returns {Promise}
* The Promise will resolve to the return value of the callback, or be rejected with an error
* thrown inside it. If it resolves, the entire transaction is committed, otherwise it is
* rolled back.
*/
/**
* @method Bookshelf#plugin
* @memberOf Bookshelf
* @description
*
* This method provides a nice, tested, standardized way of adding plugins
* to a `Bookshelf` instance, injecting the current instance into the
* plugin, which should be a `module.exports`.
*
* You can add a plugin by specifying a string with the name of the plugin
* to load. In this case it will try to find a module. It will first check
* for a match within the `bookshelf/plugins` directory. If nothing is
* found it will pass the string to `require()`, so you can either require
* an npm dependency by name or one of your own modules by relative path:
*
* bookshelf.plugin('./bookshelf-plugins/my-favourite-plugin');
* bookshelf.plugin('plugin-from-npm');
*
* There are a few built-in plugins already, along with many independently
* developed ones. See [the list of available plugins](#plugins).
*
* You can also provide an array of strings or functions, which is the same
* as calling `bookshelf.plugin()` multiple times. In this case the same
* options object will be reused:
*
* bookshelf.plugin(['registry', './my-plugins/special-parse-format']);
*
* Example plugin:
*
* // Converts all string values to lower case when setting attributes on a model
* module.exports = function(bookshelf) {
* bookshelf.Model = bookshelf.Model.extend({
* set: function(key, value, options) {
* if (!key) return this;
* if (typeof value === 'string') value = value.toLowerCase();
* return bookshelf.Model.prototype.set.call(this, key, value, options);
* }
* });
* }
*
* @param {string|array|Function} plugin
* The plugin or plugins to add. If you provide a string it can
* represent a built-in plugin, an npm package or a file somewhere on
* your project. You can also pass a function as argument to add it as a
* plugin. Finally, it's also possible to pass an array of strings or
* functions to add them all at once.
* @param {mixed} options
* This can be anything you want and it will be passed directly to the
* plugin as the second argument when loading it.
*/
plugin(plugin, options) {
if (_.isString(plugin)) {
try {
require('./plugins/' + plugin)(this, options);
} catch (e) {
if (e.code !== 'MODULE_NOT_FOUND') {
throw e;
}
if (!process.browser) {
require(plugin)(this, options);
}
}
} else if (Array.isArray(plugin)) {
plugin.forEach((p) => this.plugin(p, options));
} else {
plugin(this, options);
}
return this;
}
});
/**
* @member Bookshelf#knex
* @memberOf Bookshelf
* @type {Knex}
* @description
* A reference to the {@link http://knexjs.org Knex.js} instance being used by Bookshelf.
*/
bookshelf.knex = knex;
function builderFn(tableNameOrBuilder) {
let builder = null;
if (_.isString(tableNameOrBuilder)) {
builder = bookshelf.knex(tableNameOrBuilder);
} else if (tableNameOrBuilder == null) {
builder = bookshelf.knex.queryBuilder();
} else {
// Assuming here that `tableNameOrBuilder` is a QueryBuilder instance. Not
// aware of a way to check that this is the case (ie. using
// `Knex.isQueryBuilder` or equivalent).
builder = tableNameOrBuilder;
}
return builder.on('query', (data) => this.trigger('query', data));
}
// Attach `where`, `query`, and `fetchAll` as static methods.
['where', 'query'].forEach((method) => {
Model[method] = Collection[method] = function() {
const model = this.forge();
return model[method].apply(model, arguments);
};
});
return bookshelf;
}
// Constructor for a new `Bookshelf` object, it accepts an active `knex`
// instance and initializes the appropriate `Model` and `Collection`
// constructors for use in the current instance.
Bookshelf.initialize = function(knex) {
helpers.warn("Bookshelf.initialize is deprecated, pass knex directly: require('bookshelf')(knex)");
return new Bookshelf(knex);
};
module.exports = Bookshelf;
| lib/bookshelf.js | 'use strict';
const _ = require('lodash');
const helpers = require('./helpers');
// We've supplemented `Events` with a `triggerThen` method to allow for
// asynchronous event handling via promises. We also mix this into the
// prototypes of the main objects in the library.
const Events = require('./base/events');
// All core modules required for the bookshelf instance.
const BookshelfModel = require('./model');
const BookshelfCollection = require('./collection');
const BookshelfRelation = require('./relation');
const Errors = require('./errors');
/**
* @class Bookshelf
* @classdesc
*
* The Bookshelf library is initialized by passing an initialized Knex client
* instance. The knex documentation provides a number of examples for different
* databases.
*
* @constructor
* @param {Knex} knex Knex instance.
*/
function Bookshelf(knex) {
if (!knex || knex.name !== 'knex') {
throw new Error('Invalid knex instance');
}
const bookshelf = {
VERSION: require('../package.json').version
};
const Model = (bookshelf.Model = BookshelfModel.extend(
{
_builder: builderFn,
// The `Model` constructor is referenced as a property on the `Bookshelf`
// instance, mixing in the correct `builder` method, as well as the
// `relation` method, passing in the correct `Model` & `Collection`
// constructors for later reference.
_relation(type, Target, options) {
if (type !== 'morphTo' && !_.isFunction(Target)) {
throw new Error(
'A valid target model must be defined for the ' + _.result(this, 'tableName') + ' ' + type + ' relation'
);
}
return new Relation(type, Target, options);
}
},
{
/**
* @method Model.forge
* @belongsTo Model
* @description
*
* A simple helper function to instantiate a new Model without needing `new`.
*
* @param {Object=} attributes Initial values for this model's attributes.
* @param {Object=} options Hash of options.
* @param {string=} options.tableName Initial value for {@linkcode Model#tableName tableName}.
* @param {Boolean=} [options.hasTimestamps=false]
*
* Initial value for {@linkcode Model#hasTimestamps hasTimestamps}.
*
* @param {Boolean} [options.parse=false]
*
* Convert attributes by {@linkcode Model#parse parse} before being
* {@linkcode Model#set set} on the `model`.
*/
forge: function forge(attributes, options) {
return new this(attributes, options);
},
/**
* @method Model.collection
* @belongsTo Model
* @description
*
* A simple static helper to instantiate a new {@link Collection}, setting
* the current `model` as the collection's target.
*
* @example
*
* Customer.collection().fetch().then(function(collection) {
* // ...
* });
*
* @param {(Model[])=} models
* @param {Object=} options
* @returns {Collection}
*/
collection(models, options) {
return new bookshelf.Collection(models || [], _.extend({}, options, {model: this}));
},
/**
* @method Model.count
* @belongsTo Model
* @since 0.8.2
* @description
*
* Gets the number of matching records in the database, respecting any
* previous calls to {@link Model#query query}. If a `column` is provided,
* records with a null value in that column will be excluded from the count.
*
* @param {string} [column='*']
* Specify a column to count - rows with null values in this column will be excluded.
* @param {Object=} options
* Hash of options.
* @returns {Promise<Number>}
* A promise resolving to the number of matching rows.
*/
count(column, options) {
return this.forge().count(column, options);
},
/**
* @method Model.fetchAll
* @belongsTo Model
* @description
*
* Simple helper function for retrieving all instances of the given model.
*
* @see Model#fetchAll
* @returns {Promise<Collection>}
*/
fetchAll(options) {
return this.forge().fetchAll(options);
}
}
));
const Collection = (bookshelf.Collection = BookshelfCollection.extend(
{
_builder: builderFn
},
{
/**
* @method Collection.forge
* @belongsTo Collection
* @description
*
* A simple helper function to instantiate a new Collection without needing
* new.
*
* @param {(Object[]|Model[])=} [models]
* Set of models (or attribute hashes) with which to initialize the
* collection.
* @param {Object} options Hash of options.
*
* @example
*
* var Promise = require('bluebird');
* var Accounts = bookshelf.Collection.extend({
* model: Account
* });
*
* var accounts = Accounts.forge([
* {name: 'Person1'},
* {name: 'Person2'}
* ]);
*
* Promise.all(accounts.invokeMap('save')).then(function() {
* // collection models should now be saved...
* });
*/
forge: function forge(models, options) {
return new this(models, options);
}
}
));
// The collection also references the correct `Model`, specified above, for
// creating new `Model` instances in the collection.
Collection.prototype.model = Model;
Model.prototype.Collection = Collection;
const Relation = BookshelfRelation.extend({Model, Collection});
// A `Bookshelf` instance may be used as a top-level pub-sub bus, as it mixes
// in the `Events` object. It also contains the version number, and a
// `Transaction` method referencing the correct version of `knex` passed into
// the object.
_.extend(bookshelf, Events, Errors, {
/**
* @method Bookshelf#transaction
* @memberOf Bookshelf
* @description
*
* An alias to `{@link http://knexjs.org/#Transactions
* Knex#transaction}`, the `transaction` object must be passed along in the
* options of any relevant Bookshelf calls, to ensure all queries are on the
* same connection. The entire transaction block is a promise that will
* resolve when the transaction is committed, or fail if the transaction is
* rolled back.
*
* When fetching inside a transaction it's possible to specify a row-level
* lock by passing the wanted lock type in the `lock` option to
* {@linkcode Model#fetch fetch}. Available options are `forUpdate` and
* `forShare`.
*
* var Promise = require('bluebird');
*
* Bookshelf.transaction(function(t) {
* return new Library({name: 'Old Books'})
* .save(null, {transacting: t})
* .tap(function(model) {
* return Promise.map([
* {title: 'Canterbury Tales'},
* {title: 'Moby Dick'},
* {title: 'Hamlet'}
* ], function(info) {
* // Some validation could take place here.
* return new Book(info).save({'shelf_id': model.id}, {transacting: t});
* });
* });
* }).then(function(library) {
* console.log(library.related('books').pluck('title'));
* }).catch(function(err) {
* console.error(err);
* });
*
* @param {Bookshelf~transactionCallback} transactionCallback
* Callback containing transaction logic. The callback should return a
* promise.
*
* @returns {Promise<mixed>}
* A promise resolving to the value returned from {@link
* Bookshelf~transactionCallback transactionCallback}.
*/
transaction() {
return this.knex.transaction.apply(this.knex, arguments);
},
/**
* @callback Bookshelf~transactionCallback
* @description
*
* A transaction block to be provided to {@link Bookshelf#transaction}.
*
* @see {@link http://knexjs.org/#Transactions Knex#transaction}
* @see Bookshelf#transaction
*
* @param {Transaction} transaction
* @returns {Promise<mixed>}
*/
/**
* @method Bookshelf#plugin
* @memberOf Bookshelf
* @description
*
* This method provides a nice, tested, standardized way of adding plugins
* to a `Bookshelf` instance, injecting the current instance into the
* plugin, which should be a `module.exports`.
*
* You can add a plugin by specifying a string with the name of the plugin
* to load. In this case it will try to find a module. It will first check
* for a match within the `bookshelf/plugins` directory. If nothing is
* found it will pass the string to `require()`, so you can either require
* an npm dependency by name or one of your own modules by relative path:
*
* bookshelf.plugin('./bookshelf-plugins/my-favourite-plugin');
* bookshelf.plugin('plugin-from-npm');
*
* There are a few built-in plugins already, along with many independently
* developed ones. See [the list of available plugins](#plugins).
*
* You can also provide an array of strings or functions, which is the same
* as calling `bookshelf.plugin()` multiple times. In this case the same
* options object will be reused:
*
* bookshelf.plugin(['registry', './my-plugins/special-parse-format']);
*
* Example plugin:
*
* // Converts all string values to lower case when setting attributes on a model
* module.exports = function(bookshelf) {
* bookshelf.Model = bookshelf.Model.extend({
* set: function(key, value, options) {
* if (!key) return this;
* if (typeof value === 'string') value = value.toLowerCase();
* return bookshelf.Model.prototype.set.call(this, key, value, options);
* }
* });
* }
*
* @param {string|array|Function} plugin
* The plugin or plugins to add. If you provide a string it can
* represent a built-in plugin, an npm package or a file somewhere on
* your project. You can also pass a function as argument to add it as a
* plugin. Finally, it's also possible to pass an array of strings or
* functions to add them all at once.
* @param {mixed} options
* This can be anything you want and it will be passed directly to the
* plugin as the second argument when loading it.
*/
plugin(plugin, options) {
if (_.isString(plugin)) {
try {
require('./plugins/' + plugin)(this, options);
} catch (e) {
if (e.code !== 'MODULE_NOT_FOUND') {
throw e;
}
if (!process.browser) {
require(plugin)(this, options);
}
}
} else if (Array.isArray(plugin)) {
plugin.forEach((p) => this.plugin(p, options));
} else {
plugin(this, options);
}
return this;
}
});
/**
* @member Bookshelf#knex
* @memberOf Bookshelf
* @type {Knex}
* @description
* A reference to the {@link http://knexjs.org Knex.js} instance being used by Bookshelf.
*/
bookshelf.knex = knex;
function builderFn(tableNameOrBuilder) {
let builder = null;
if (_.isString(tableNameOrBuilder)) {
builder = bookshelf.knex(tableNameOrBuilder);
} else if (tableNameOrBuilder == null) {
builder = bookshelf.knex.queryBuilder();
} else {
// Assuming here that `tableNameOrBuilder` is a QueryBuilder instance. Not
// aware of a way to check that this is the case (ie. using
// `Knex.isQueryBuilder` or equivalent).
builder = tableNameOrBuilder;
}
return builder.on('query', (data) => this.trigger('query', data));
}
// Attach `where`, `query`, and `fetchAll` as static methods.
['where', 'query'].forEach((method) => {
Model[method] = Collection[method] = function() {
const model = this.forge();
return model[method].apply(model, arguments);
};
});
return bookshelf;
}
// Constructor for a new `Bookshelf` object, it accepts an active `knex`
// instance and initializes the appropriate `Model` and `Collection`
// constructors for use in the current instance.
Bookshelf.initialize = function(knex) {
helpers.warn("Bookshelf.initialize is deprecated, pass knex directly: require('bookshelf')(knex)");
return new Bookshelf(knex);
};
module.exports = Bookshelf;
| Expand on the transaction and its callback docs
| lib/bookshelf.js | Expand on the transaction and its callback docs | <ide><path>ib/bookshelf.js
<ide> // the object.
<ide> _.extend(bookshelf, Events, Errors, {
<ide> /**
<add> * An alias to `{@link http://knexjs.org/#Transactions Knex#transaction}`. The `transaction`
<add> * object must be passed along in the options of any relevant Bookshelf calls, to ensure all
<add> * queries are on the same connection. The entire transaction block is wrapped around a Promise
<add> * that will commit the transaction if it resolves successfully, or roll it back if the Promise
<add> * is rejected.
<add> *
<add> * Note that there is no need to explicitly call `transaction.commit()` or
<add> * `transaction.rollback()` since the entire transaction will be committed if there are no
<add> * errors inside the transaction block.
<add> *
<add> * When fetching inside a transaction it's possible to specify a row-level lock by passing the
<add> * wanted lock type in the `lock` option to {@linkcode Model#fetch fetch}. Available options are
<add> * `lock: 'forUpdate'` and `lock: 'forShare'`.
<add> *
<add> * @example
<add> * var Promise = require('bluebird')
<add> *
<add> * Bookshelf.transaction((t) => {
<add> * return new Library({name: 'Old Books'})
<add> * .save(null, {transacting: t})
<add> * .tap(function(model) {
<add> * return Promise.map([
<add> * {title: 'Canterbury Tales'},
<add> * {title: 'Moby Dick'},
<add> * {title: 'Hamlet'}
<add> * ], (info) => {
<add> * return new Book(info).save({'shelf_id': model.id}, {transacting: t})
<add> * })
<add> * })
<add> * }).then((library) => {
<add> * console.log(library.related('books').pluck('title'))
<add> * }).catch((err) => {
<add> * console.error(err)
<add> * })
<add> *
<ide> * @method Bookshelf#transaction
<del> * @memberOf Bookshelf
<del> * @description
<del> *
<del> * An alias to `{@link http://knexjs.org/#Transactions
<del> * Knex#transaction}`, the `transaction` object must be passed along in the
<del> * options of any relevant Bookshelf calls, to ensure all queries are on the
<del> * same connection. The entire transaction block is a promise that will
<del> * resolve when the transaction is committed, or fail if the transaction is
<del> * rolled back.
<del> *
<del> * When fetching inside a transaction it's possible to specify a row-level
<del> * lock by passing the wanted lock type in the `lock` option to
<del> * {@linkcode Model#fetch fetch}. Available options are `forUpdate` and
<del> * `forShare`.
<del> *
<del> * var Promise = require('bluebird');
<del> *
<del> * Bookshelf.transaction(function(t) {
<del> * return new Library({name: 'Old Books'})
<del> * .save(null, {transacting: t})
<del> * .tap(function(model) {
<del> * return Promise.map([
<del> * {title: 'Canterbury Tales'},
<del> * {title: 'Moby Dick'},
<del> * {title: 'Hamlet'}
<del> * ], function(info) {
<del> * // Some validation could take place here.
<del> * return new Book(info).save({'shelf_id': model.id}, {transacting: t});
<del> * });
<del> * });
<del> * }).then(function(library) {
<del> * console.log(library.related('books').pluck('title'));
<del> * }).catch(function(err) {
<del> * console.error(err);
<del> * });
<del> *
<ide> * @param {Bookshelf~transactionCallback} transactionCallback
<del> * Callback containing transaction logic. The callback should return a
<del> * promise.
<del> *
<del> * @returns {Promise<mixed>}
<del> * A promise resolving to the value returned from {@link
<del> * Bookshelf~transactionCallback transactionCallback}.
<add> * Callback containing transaction logic. The callback should return a Promise.
<add> * @returns {Promise}
<add> * A promise resolving to the value returned from
<add> * {@link Bookshelf~transactionCallback transactionCallback}.
<ide> */
<ide> transaction() {
<ide> return this.knex.transaction.apply(this.knex, arguments);
<ide> },
<ide>
<ide> /**
<add> * This is a transaction block to be provided to {@link Bookshelf#transaction}. All of the
<add> * database operations inside it can be part of the same transaction by passing the
<add> * `transacting: transaction` option to {@link Model#fetch fetch}, {@link Model#save save} or
<add> * {@link Model#destroy destroy}.
<add> *
<add> * Note that unless you explicitly pass the `transaction` object along to any relevant model
<add> * operations, those operations will not be part of the transaction, even though they may be
<add> * inside the transaction callback.
<add> *
<ide> * @callback Bookshelf~transactionCallback
<del> * @description
<del> *
<del> * A transaction block to be provided to {@link Bookshelf#transaction}.
<del> *
<ide> * @see {@link http://knexjs.org/#Transactions Knex#transaction}
<ide> * @see Bookshelf#transaction
<ide> *
<ide> * @param {Transaction} transaction
<del> * @returns {Promise<mixed>}
<add> * @returns {Promise}
<add> * The Promise will resolve to the return value of the callback, or be rejected with an error
<add> * thrown inside it. If it resolves, the entire transaction is committed, otherwise it is
<add> * rolled back.
<ide> */
<ide>
<ide> /** |
|
Java | apache-2.0 | 6c142bf647dc8a7793248e5e9f71bc9959da1d45 | 0 | fnouama/intellij-community,fitermay/intellij-community,fnouama/intellij-community,signed/intellij-community,ivan-fedorov/intellij-community,xfournet/intellij-community,fnouama/intellij-community,muntasirsyed/intellij-community,slisson/intellij-community,izonder/intellij-community,ernestp/consulo,vladmm/intellij-community,supersven/intellij-community,caot/intellij-community,allotria/intellij-community,michaelgallacher/intellij-community,apixandru/intellij-community,salguarnieri/intellij-community,da1z/intellij-community,joewalnes/idea-community,ol-loginov/intellij-community,youdonghai/intellij-community,gnuhub/intellij-community,suncycheng/intellij-community,kdwink/intellij-community,SerCeMan/intellij-community,apixandru/intellij-community,consulo/consulo,asedunov/intellij-community,diorcety/intellij-community,muntasirsyed/intellij-community,clumsy/intellij-community,vvv1559/intellij-community,MER-GROUP/intellij-community,amith01994/intellij-community,mglukhikh/intellij-community,blademainer/intellij-community,holmes/intellij-community,SerCeMan/intellij-community,da1z/intellij-community,apixandru/intellij-community,ahb0327/intellij-community,mglukhikh/intellij-community,michaelgallacher/intellij-community,diorcety/intellij-community,Distrotech/intellij-community,fnouama/intellij-community,MER-GROUP/intellij-community,alphafoobar/intellij-community,samthor/intellij-community,Distrotech/intellij-community,clumsy/intellij-community,vladmm/intellij-community,fitermay/intellij-community,signed/intellij-community,jagguli/intellij-community,asedunov/intellij-community,fitermay/intellij-community,jexp/idea2,TangHao1987/intellij-community,alphafoobar/intellij-community,wreckJ/intellij-community,izonder/intellij-community,hurricup/intellij-community,TangHao1987/intellij-community,apixandru/intellij-community,orekyuu/intellij-community,signed/intellij-community,idea4bsd/idea4bsd,holmes/intellij-community,jexp/idea2,MichaelNedzelsky/intellij-community,Distrotech/intellij-community,idea4bsd/idea4bsd,FHannes/intellij-community,muntasirsyed/intellij-community,xfournet/intellij-community,muntasirsyed/intellij-community,retomerz/intellij-community,SerCeMan/intellij-community,ryano144/intellij-community,Lekanich/intellij-community,dslomov/intellij-community,ryano144/intellij-community,nicolargo/intellij-community,Distrotech/intellij-community,joewalnes/idea-community,amith01994/intellij-community,samthor/intellij-community,samthor/intellij-community,retomerz/intellij-community,clumsy/intellij-community,jexp/idea2,diorcety/intellij-community,blademainer/intellij-community,ibinti/intellij-community,orekyuu/intellij-community,mglukhikh/intellij-community,da1z/intellij-community,samthor/intellij-community,TangHao1987/intellij-community,ftomassetti/intellij-community,tmpgit/intellij-community,lucafavatella/intellij-community,vvv1559/intellij-community,gnuhub/intellij-community,ftomassetti/intellij-community,apixandru/intellij-community,holmes/intellij-community,ol-loginov/intellij-community,vvv1559/intellij-community,retomerz/intellij-community,muntasirsyed/intellij-community,ivan-fedorov/intellij-community,kool79/intellij-community,fengbaicanhe/intellij-community,gnuhub/intellij-community,semonte/intellij-community,FHannes/intellij-community,xfournet/intellij-community,tmpgit/intellij-community,mglukhikh/intellij-community,MichaelNedzelsky/intellij-community,suncycheng/intellij-community,wreckJ/intellij-community,youdonghai/intellij-community,suncycheng/intellij-community,hurricup/intellij-community,joewalnes/idea-community,robovm/robovm-studio,youdonghai/intellij-community,petteyg/intellij-community,MER-GROUP/intellij-community,Lekanich/intellij-community,MER-GROUP/intellij-community,dslomov/intellij-community,ivan-fedorov/intellij-community,FHannes/intellij-community,ThiagoGarciaAlves/intellij-community,pwoodworth/intellij-community,retomerz/intellij-community,retomerz/intellij-community,kdwink/intellij-community,ivan-fedorov/intellij-community,jagguli/intellij-community,wreckJ/intellij-community,diorcety/intellij-community,izonder/intellij-community,MER-GROUP/intellij-community,FHannes/intellij-community,FHannes/intellij-community,pwoodworth/intellij-community,ryano144/intellij-community,adedayo/intellij-community,MER-GROUP/intellij-community,asedunov/intellij-community,MichaelNedzelsky/intellij-community,ol-loginov/intellij-community,hurricup/intellij-community,vvv1559/intellij-community,apixandru/intellij-community,consulo/consulo,kool79/intellij-community,pwoodworth/intellij-community,slisson/intellij-community,fnouama/intellij-community,slisson/intellij-community,ThiagoGarciaAlves/intellij-community,TangHao1987/intellij-community,TangHao1987/intellij-community,kool79/intellij-community,amith01994/intellij-community,fitermay/intellij-community,diorcety/intellij-community,izonder/intellij-community,akosyakov/intellij-community,petteyg/intellij-community,MichaelNedzelsky/intellij-community,ahb0327/intellij-community,jagguli/intellij-community,MichaelNedzelsky/intellij-community,slisson/intellij-community,FHannes/intellij-community,ahb0327/intellij-community,hurricup/intellij-community,idea4bsd/idea4bsd,holmes/intellij-community,vvv1559/intellij-community,pwoodworth/intellij-community,adedayo/intellij-community,ryano144/intellij-community,alphafoobar/intellij-community,MichaelNedzelsky/intellij-community,salguarnieri/intellij-community,ol-loginov/intellij-community,lucafavatella/intellij-community,ol-loginov/intellij-community,ol-loginov/intellij-community,suncycheng/intellij-community,gnuhub/intellij-community,allotria/intellij-community,kool79/intellij-community,lucafavatella/intellij-community,ibinti/intellij-community,mglukhikh/intellij-community,samthor/intellij-community,orekyuu/intellij-community,signed/intellij-community,Distrotech/intellij-community,ibinti/intellij-community,fengbaicanhe/intellij-community,semonte/intellij-community,idea4bsd/idea4bsd,clumsy/intellij-community,da1z/intellij-community,supersven/intellij-community,izonder/intellij-community,SerCeMan/intellij-community,ryano144/intellij-community,TangHao1987/intellij-community,Lekanich/intellij-community,xfournet/intellij-community,vladmm/intellij-community,asedunov/intellij-community,ernestp/consulo,ibinti/intellij-community,vvv1559/intellij-community,petteyg/intellij-community,amith01994/intellij-community,jexp/idea2,petteyg/intellij-community,allotria/intellij-community,ftomassetti/intellij-community,Lekanich/intellij-community,akosyakov/intellij-community,lucafavatella/intellij-community,MER-GROUP/intellij-community,xfournet/intellij-community,muntasirsyed/intellij-community,ThiagoGarciaAlves/intellij-community,da1z/intellij-community,Lekanich/intellij-community,fengbaicanhe/intellij-community,jagguli/intellij-community,izonder/intellij-community,izonder/intellij-community,ftomassetti/intellij-community,Lekanich/intellij-community,ernestp/consulo,fitermay/intellij-community,ftomassetti/intellij-community,robovm/robovm-studio,suncycheng/intellij-community,alphafoobar/intellij-community,da1z/intellij-community,semonte/intellij-community,orekyuu/intellij-community,wreckJ/intellij-community,asedunov/intellij-community,ftomassetti/intellij-community,blademainer/intellij-community,FHannes/intellij-community,jagguli/intellij-community,ivan-fedorov/intellij-community,robovm/robovm-studio,michaelgallacher/intellij-community,hurricup/intellij-community,slisson/intellij-community,amith01994/intellij-community,slisson/intellij-community,youdonghai/intellij-community,izonder/intellij-community,jagguli/intellij-community,fitermay/intellij-community,idea4bsd/idea4bsd,da1z/intellij-community,dslomov/intellij-community,wreckJ/intellij-community,apixandru/intellij-community,wreckJ/intellij-community,clumsy/intellij-community,dslomov/intellij-community,semonte/intellij-community,adedayo/intellij-community,dslomov/intellij-community,youdonghai/intellij-community,hurricup/intellij-community,akosyakov/intellij-community,salguarnieri/intellij-community,SerCeMan/intellij-community,holmes/intellij-community,fitermay/intellij-community,semonte/intellij-community,jexp/idea2,jagguli/intellij-community,semonte/intellij-community,vvv1559/intellij-community,MichaelNedzelsky/intellij-community,samthor/intellij-community,tmpgit/intellij-community,caot/intellij-community,TangHao1987/intellij-community,consulo/consulo,blademainer/intellij-community,retomerz/intellij-community,kdwink/intellij-community,kdwink/intellij-community,apixandru/intellij-community,holmes/intellij-community,clumsy/intellij-community,vladmm/intellij-community,fengbaicanhe/intellij-community,samthor/intellij-community,orekyuu/intellij-community,ThiagoGarciaAlves/intellij-community,muntasirsyed/intellij-community,fengbaicanhe/intellij-community,akosyakov/intellij-community,allotria/intellij-community,lucafavatella/intellij-community,ftomassetti/intellij-community,michaelgallacher/intellij-community,consulo/consulo,idea4bsd/idea4bsd,ol-loginov/intellij-community,fnouama/intellij-community,FHannes/intellij-community,diorcety/intellij-community,alphafoobar/intellij-community,slisson/intellij-community,Lekanich/intellij-community,semonte/intellij-community,slisson/intellij-community,nicolargo/intellij-community,orekyuu/intellij-community,akosyakov/intellij-community,ThiagoGarciaAlves/intellij-community,orekyuu/intellij-community,alphafoobar/intellij-community,holmes/intellij-community,kool79/intellij-community,MER-GROUP/intellij-community,youdonghai/intellij-community,wreckJ/intellij-community,muntasirsyed/intellij-community,Distrotech/intellij-community,tmpgit/intellij-community,orekyuu/intellij-community,izonder/intellij-community,asedunov/intellij-community,mglukhikh/intellij-community,FHannes/intellij-community,ivan-fedorov/intellij-community,allotria/intellij-community,ThiagoGarciaAlves/intellij-community,Lekanich/intellij-community,supersven/intellij-community,hurricup/intellij-community,SerCeMan/intellij-community,TangHao1987/intellij-community,diorcety/intellij-community,amith01994/intellij-community,da1z/intellij-community,diorcety/intellij-community,signed/intellij-community,Distrotech/intellij-community,akosyakov/intellij-community,mglukhikh/intellij-community,blademainer/intellij-community,supersven/intellij-community,vvv1559/intellij-community,gnuhub/intellij-community,ryano144/intellij-community,signed/intellij-community,ryano144/intellij-community,ahb0327/intellij-community,salguarnieri/intellij-community,xfournet/intellij-community,Distrotech/intellij-community,diorcety/intellij-community,allotria/intellij-community,salguarnieri/intellij-community,holmes/intellij-community,robovm/robovm-studio,vladmm/intellij-community,samthor/intellij-community,tmpgit/intellij-community,orekyuu/intellij-community,dslomov/intellij-community,TangHao1987/intellij-community,ThiagoGarciaAlves/intellij-community,FHannes/intellij-community,idea4bsd/idea4bsd,blademainer/intellij-community,petteyg/intellij-community,salguarnieri/intellij-community,suncycheng/intellij-community,nicolargo/intellij-community,ol-loginov/intellij-community,robovm/robovm-studio,Lekanich/intellij-community,joewalnes/idea-community,adedayo/intellij-community,supersven/intellij-community,SerCeMan/intellij-community,muntasirsyed/intellij-community,salguarnieri/intellij-community,FHannes/intellij-community,slisson/intellij-community,semonte/intellij-community,clumsy/intellij-community,caot/intellij-community,TangHao1987/intellij-community,caot/intellij-community,nicolargo/intellij-community,ftomassetti/intellij-community,pwoodworth/intellij-community,jexp/idea2,MER-GROUP/intellij-community,ernestp/consulo,blademainer/intellij-community,tmpgit/intellij-community,petteyg/intellij-community,adedayo/intellij-community,ahb0327/intellij-community,SerCeMan/intellij-community,blademainer/intellij-community,asedunov/intellij-community,adedayo/intellij-community,idea4bsd/idea4bsd,petteyg/intellij-community,alphafoobar/intellij-community,kool79/intellij-community,allotria/intellij-community,idea4bsd/idea4bsd,ibinti/intellij-community,kool79/intellij-community,ThiagoGarciaAlves/intellij-community,akosyakov/intellij-community,xfournet/intellij-community,kool79/intellij-community,consulo/consulo,holmes/intellij-community,diorcety/intellij-community,SerCeMan/intellij-community,idea4bsd/idea4bsd,dslomov/intellij-community,michaelgallacher/intellij-community,retomerz/intellij-community,xfournet/intellij-community,jagguli/intellij-community,izonder/intellij-community,Distrotech/intellij-community,vladmm/intellij-community,ibinti/intellij-community,youdonghai/intellij-community,fitermay/intellij-community,alphafoobar/intellij-community,kdwink/intellij-community,michaelgallacher/intellij-community,clumsy/intellij-community,ftomassetti/intellij-community,kdwink/intellij-community,ftomassetti/intellij-community,vvv1559/intellij-community,salguarnieri/intellij-community,MichaelNedzelsky/intellij-community,ibinti/intellij-community,nicolargo/intellij-community,nicolargo/intellij-community,fengbaicanhe/intellij-community,mglukhikh/intellij-community,ryano144/intellij-community,amith01994/intellij-community,asedunov/intellij-community,ThiagoGarciaAlves/intellij-community,akosyakov/intellij-community,fengbaicanhe/intellij-community,Distrotech/intellij-community,petteyg/intellij-community,jexp/idea2,salguarnieri/intellij-community,fnouama/intellij-community,michaelgallacher/intellij-community,nicolargo/intellij-community,signed/intellij-community,hurricup/intellij-community,amith01994/intellij-community,ol-loginov/intellij-community,robovm/robovm-studio,petteyg/intellij-community,jagguli/intellij-community,wreckJ/intellij-community,xfournet/intellij-community,adedayo/intellij-community,akosyakov/intellij-community,fengbaicanhe/intellij-community,samthor/intellij-community,hurricup/intellij-community,caot/intellij-community,kdwink/intellij-community,joewalnes/idea-community,vvv1559/intellij-community,mglukhikh/intellij-community,pwoodworth/intellij-community,MichaelNedzelsky/intellij-community,signed/intellij-community,fitermay/intellij-community,salguarnieri/intellij-community,ryano144/intellij-community,MichaelNedzelsky/intellij-community,ibinti/intellij-community,amith01994/intellij-community,jagguli/intellij-community,wreckJ/intellij-community,michaelgallacher/intellij-community,ol-loginov/intellij-community,asedunov/intellij-community,vvv1559/intellij-community,xfournet/intellij-community,fnouama/intellij-community,ivan-fedorov/intellij-community,youdonghai/intellij-community,pwoodworth/intellij-community,ThiagoGarciaAlves/intellij-community,fengbaicanhe/intellij-community,tmpgit/intellij-community,fengbaicanhe/intellij-community,signed/intellij-community,jexp/idea2,gnuhub/intellij-community,adedayo/intellij-community,ahb0327/intellij-community,ol-loginov/intellij-community,ThiagoGarciaAlves/intellij-community,apixandru/intellij-community,adedayo/intellij-community,michaelgallacher/intellij-community,clumsy/intellij-community,da1z/intellij-community,MER-GROUP/intellij-community,alphafoobar/intellij-community,kool79/intellij-community,youdonghai/intellij-community,retomerz/intellij-community,fnouama/intellij-community,clumsy/intellij-community,Distrotech/intellij-community,youdonghai/intellij-community,ernestp/consulo,joewalnes/idea-community,suncycheng/intellij-community,robovm/robovm-studio,kool79/intellij-community,da1z/intellij-community,ahb0327/intellij-community,TangHao1987/intellij-community,lucafavatella/intellij-community,fitermay/intellij-community,retomerz/intellij-community,petteyg/intellij-community,kdwink/intellij-community,MichaelNedzelsky/intellij-community,ahb0327/intellij-community,tmpgit/intellij-community,tmpgit/intellij-community,asedunov/intellij-community,slisson/intellij-community,Distrotech/intellij-community,suncycheng/intellij-community,Lekanich/intellij-community,lucafavatella/intellij-community,apixandru/intellij-community,vladmm/intellij-community,kdwink/intellij-community,ernestp/consulo,blademainer/intellij-community,vladmm/intellij-community,SerCeMan/intellij-community,gnuhub/intellij-community,diorcety/intellij-community,michaelgallacher/intellij-community,dslomov/intellij-community,dslomov/intellij-community,allotria/intellij-community,supersven/intellij-community,ol-loginov/intellij-community,pwoodworth/intellij-community,mglukhikh/intellij-community,supersven/intellij-community,hurricup/intellij-community,fnouama/intellij-community,robovm/robovm-studio,ahb0327/intellij-community,ivan-fedorov/intellij-community,robovm/robovm-studio,fnouama/intellij-community,caot/intellij-community,lucafavatella/intellij-community,alphafoobar/intellij-community,slisson/intellij-community,tmpgit/intellij-community,xfournet/intellij-community,vvv1559/intellij-community,supersven/intellij-community,xfournet/intellij-community,ibinti/intellij-community,mglukhikh/intellij-community,robovm/robovm-studio,ahb0327/intellij-community,ibinti/intellij-community,wreckJ/intellij-community,MER-GROUP/intellij-community,tmpgit/intellij-community,da1z/intellij-community,asedunov/intellij-community,ahb0327/intellij-community,fengbaicanhe/intellij-community,ivan-fedorov/intellij-community,suncycheng/intellij-community,akosyakov/intellij-community,samthor/intellij-community,signed/intellij-community,ftomassetti/intellij-community,idea4bsd/idea4bsd,orekyuu/intellij-community,salguarnieri/intellij-community,SerCeMan/intellij-community,kool79/intellij-community,allotria/intellij-community,kdwink/intellij-community,allotria/intellij-community,semonte/intellij-community,wreckJ/intellij-community,blademainer/intellij-community,muntasirsyed/intellij-community,clumsy/intellij-community,ibinti/intellij-community,vvv1559/intellij-community,petteyg/intellij-community,salguarnieri/intellij-community,caot/intellij-community,pwoodworth/intellij-community,mglukhikh/intellij-community,gnuhub/intellij-community,jagguli/intellij-community,xfournet/intellij-community,blademainer/intellij-community,holmes/intellij-community,youdonghai/intellij-community,suncycheng/intellij-community,muntasirsyed/intellij-community,izonder/intellij-community,gnuhub/intellij-community,amith01994/intellij-community,nicolargo/intellij-community,slisson/intellij-community,signed/intellij-community,fitermay/intellij-community,ibinti/intellij-community,gnuhub/intellij-community,jagguli/intellij-community,hurricup/intellij-community,kdwink/intellij-community,allotria/intellij-community,adedayo/intellij-community,lucafavatella/intellij-community,michaelgallacher/intellij-community,lucafavatella/intellij-community,idea4bsd/idea4bsd,pwoodworth/intellij-community,ftomassetti/intellij-community,robovm/robovm-studio,ivan-fedorov/intellij-community,youdonghai/intellij-community,asedunov/intellij-community,lucafavatella/intellij-community,amith01994/intellij-community,pwoodworth/intellij-community,semonte/intellij-community,apixandru/intellij-community,nicolargo/intellij-community,joewalnes/idea-community,nicolargo/intellij-community,signed/intellij-community,ryano144/intellij-community,vladmm/intellij-community,adedayo/intellij-community,gnuhub/intellij-community,consulo/consulo,pwoodworth/intellij-community,vladmm/intellij-community,FHannes/intellij-community,semonte/intellij-community,allotria/intellij-community,dslomov/intellij-community,da1z/intellij-community,diorcety/intellij-community,MER-GROUP/intellij-community,idea4bsd/idea4bsd,holmes/intellij-community,retomerz/intellij-community,supersven/intellij-community,supersven/intellij-community,suncycheng/intellij-community,holmes/intellij-community,allotria/intellij-community,adedayo/intellij-community,asedunov/intellij-community,akosyakov/intellij-community,ivan-fedorov/intellij-community,samthor/intellij-community,caot/intellij-community,TangHao1987/intellij-community,supersven/intellij-community,da1z/intellij-community,blademainer/intellij-community,ivan-fedorov/intellij-community,apixandru/intellij-community,MichaelNedzelsky/intellij-community,samthor/intellij-community,signed/intellij-community,clumsy/intellij-community,vladmm/intellij-community,tmpgit/intellij-community,youdonghai/intellij-community,Lekanich/intellij-community,semonte/intellij-community,izonder/intellij-community,orekyuu/intellij-community,retomerz/intellij-community,wreckJ/intellij-community,fengbaicanhe/intellij-community,orekyuu/intellij-community,caot/intellij-community,lucafavatella/intellij-community,ThiagoGarciaAlves/intellij-community,gnuhub/intellij-community,caot/intellij-community,joewalnes/idea-community,amith01994/intellij-community,dslomov/intellij-community,suncycheng/intellij-community,petteyg/intellij-community,retomerz/intellij-community,alphafoobar/intellij-community,vladmm/intellij-community,hurricup/intellij-community,mglukhikh/intellij-community,supersven/intellij-community,semonte/intellij-community,akosyakov/intellij-community,ibinti/intellij-community,dslomov/intellij-community,caot/intellij-community,retomerz/intellij-community,kdwink/intellij-community,kool79/intellij-community,hurricup/intellij-community,apixandru/intellij-community,SerCeMan/intellij-community,fitermay/intellij-community,alphafoobar/intellij-community,robovm/robovm-studio,lucafavatella/intellij-community,muntasirsyed/intellij-community,ryano144/intellij-community,caot/intellij-community,ryano144/intellij-community,nicolargo/intellij-community,joewalnes/idea-community,fitermay/intellij-community,Lekanich/intellij-community,fnouama/intellij-community,nicolargo/intellij-community,FHannes/intellij-community,ahb0327/intellij-community,michaelgallacher/intellij-community,apixandru/intellij-community | package com.intellij.psi.impl.source.tree;
import com.intellij.lang.ASTNode;
import com.intellij.lang.StdLanguages;
import com.intellij.lexer.Lexer;
import com.intellij.openapi.project.Project;
import com.intellij.psi.JavaTokenType;
import com.intellij.psi.PsiManager;
import com.intellij.psi.impl.source.parsing.JavaParsingContext;
import com.intellij.psi.impl.source.parsing.FileTextParsing;
import com.intellij.psi.impl.source.parsing.Parsing;
import com.intellij.psi.tree.IChameleonElementType;
import com.intellij.psi.tree.IElementType;
import com.intellij.psi.tree.IErrorCounterChameleonElementType;
import com.intellij.psi.tree.java.IJavaElementType;
import com.intellij.util.text.CharArrayUtil;
import com.intellij.util.CharTable;
public interface JavaElementType {
//chameleons
IElementType TYPE_PARAMETER = new IJavaElementType("TYPE_PARAMETER");
IElementType TYPE_PARAMETER_LIST = new IJavaElementType("TYPE_PARAMETER_LIST");
IElementType ERROR_ELEMENT = new IJavaElementType("ERROR_ELEMENT");
IElementType JAVA_CODE_REFERENCE = new IJavaElementType("JAVA_CODE_REFERENCE");
IElementType PACKAGE_STATEMENT = new IJavaElementType("PACKAGE_STATEMENT");
IElementType CLASS = new IJavaElementType("CLASS");
IElementType ANONYMOUS_CLASS = new IJavaElementType("ANONYMOUS_CLASS");
IElementType ENUM_CONSTANT_INITIALIZER = new IJavaElementType("ENUM_CONSTANT_INITIALIZER");
IElementType IMPORT_STATEMENT = new IJavaElementType("IMPORT_STATEMENT");
IElementType IMPORT_STATIC_STATEMENT = new IJavaElementType("IMPORT_STATIC_STATEMENT");
IElementType IMPORT_STATIC_REFERENCE = new IJavaElementType("IMPORT_STATIC_REFERENCE");
IElementType MODIFIER_LIST = new IJavaElementType("MODIFIER_LIST");
IElementType EXTENDS_LIST = new IJavaElementType("EXTENDS_LIST");
IElementType IMPLEMENTS_LIST = new IJavaElementType("IMPLEMENTS_LIST");
IElementType FIELD = new IJavaElementType("FIELD");
IElementType ENUM_CONSTANT = new IJavaElementType("ENUM_CONSTANT");
IElementType METHOD = new IJavaElementType("METHOD");
IElementType LOCAL_VARIABLE = new IJavaElementType("LOCAL_VARIABLE");
IElementType CLASS_INITIALIZER = new IJavaElementType("CLASS_INITIALIZER");
IElementType PARAMETER = new IJavaElementType("PARAMETER");
IElementType TYPE = new IJavaElementType("TYPE");
IElementType PARAMETER_LIST = new IJavaElementType("PARAMETER_LIST");
IElementType EXTENDS_BOUND_LIST = new IJavaElementType("EXTENDS_BOUND_LIST");
IElementType THROWS_LIST = new IJavaElementType("THROWS_LIST");
IElementType REFERENCE_PARAMETER_LIST = new IJavaElementType("REFERENCE_PARAMETER_LIST");
IElementType REFERENCE_EXPRESSION = new IJavaElementType("REFERENCE_EXPRESSION");
IElementType LITERAL_EXPRESSION = new IJavaElementType("LITERAL_EXPRESSION");
IElementType THIS_EXPRESSION = new IJavaElementType("THIS_EXPRESSION");
IElementType SUPER_EXPRESSION = new IJavaElementType("SUPER_EXPRESSION");
IElementType PARENTH_EXPRESSION = new IJavaElementType("PARENTH_EXPRESSION");
IElementType METHOD_CALL_EXPRESSION = new IJavaElementType("METHOD_CALL_EXPRESSION");
IElementType TYPE_CAST_EXPRESSION = new IJavaElementType("TYPE_CAST_EXPRESSION");
IElementType PREFIX_EXPRESSION = new IJavaElementType("PREFIX_EXPRESSION");
IElementType POSTFIX_EXPRESSION = new IJavaElementType("POSTFIX_EXPRESSION");
IElementType BINARY_EXPRESSION = new IJavaElementType("BINARY_EXPRESSION");
IElementType CONDITIONAL_EXPRESSION = new IJavaElementType("CONDITIONAL_EXPRESSION");
IElementType ASSIGNMENT_EXPRESSION = new IJavaElementType("ASSIGNMENT_EXPRESSION");
IElementType NEW_EXPRESSION = new IJavaElementType("NEW_EXPRESSION");
IElementType ARRAY_ACCESS_EXPRESSION = new IJavaElementType("ARRAY_ACCESS_EXPRESSION");
IElementType ARRAY_INITIALIZER_EXPRESSION = new IJavaElementType("ARRAY_INITIALIZER_EXPRESSION");
IElementType INSTANCE_OF_EXPRESSION = new IJavaElementType("INSTANCE_OF_EXPRESSION");
IElementType CLASS_OBJECT_ACCESS_EXPRESSION = new IJavaElementType("CLASS_OBJECT_ACCESS_EXPRESSION");
IElementType EMPTY_EXPRESSION = new IJavaElementType("EMPTY_EXPRESSION");
IElementType EXPRESSION_LIST = new IJavaElementType("EXPRESSION_LIST");
IElementType EMPTY_STATEMENT = new IJavaElementType("EMPTY_STATEMENT");
IElementType BLOCK_STATEMENT = new IJavaElementType("BLOCK_STATEMENT");
IElementType EXPRESSION_LIST_STATEMENT = new IJavaElementType("EXPRESSION_LIST_STATEMENT");
IElementType DECLARATION_STATEMENT = new IJavaElementType("DECLARATION_STATEMENT");
IElementType IF_STATEMENT = new IJavaElementType("IF_STATEMENT");
IElementType WHILE_STATEMENT = new IJavaElementType("WHILE_STATEMENT");
IElementType FOR_STATEMENT = new IJavaElementType("FOR_STATEMENT");
IElementType FOREACH_STATEMENT = new IJavaElementType("FOREACH_STATEMENT");
IElementType DO_WHILE_STATEMENT = new IJavaElementType("DO_WHILE_STATEMENT");
IElementType SWITCH_STATEMENT = new IJavaElementType("SWITCH_STATEMENT");
IElementType SWITCH_LABEL_STATEMENT = new IJavaElementType("SWITCH_LABEL_STATEMENT");
IElementType BREAK_STATEMENT = new IJavaElementType("BREAK_STATEMENT");
IElementType CONTINUE_STATEMENT = new IJavaElementType("CONTINUE_STATEMENT");
IElementType RETURN_STATEMENT = new IJavaElementType("RETURN_STATEMENT");
IElementType THROW_STATEMENT = new IJavaElementType("THROW_STATEMENT");
IElementType SYNCHRONIZED_STATEMENT = new IJavaElementType("SYNCHRONIZED_STATEMENT");
IElementType TRY_STATEMENT = new IJavaElementType("TRY_STATEMENT");
IElementType LABELED_STATEMENT = new IJavaElementType("LABELED_STATEMENT");
IElementType ASSERT_STATEMENT = new IJavaElementType("ASSERT_STATEMENT");
IElementType CATCH_SECTION = new IJavaElementType("CATCH_SECTION");
IElementType ANNOTATION_METHOD = new IJavaElementType("ANNOTATION_METHOD");
IElementType ANNOTATION_ARRAY_INITIALIZER = new IJavaElementType("ANNOTATION_ARRAY_INITIALIZER");
IElementType ANNOTATION = new IJavaElementType("ANNOTATION");
IElementType NAME_VALUE_PAIR = new IJavaElementType("NAME_VALUE_PAIR");
IElementType ANNOTATION_PARAMETER_LIST = new IJavaElementType("ANNOTATION_PARAMETER_LIST");
IElementType JAVA_FILE = new IChameleonElementType("JAVA_FILE_TEXT", StdLanguages.JAVA){
public ASTNode parseContents(ASTNode chameleon) {
final char[] chars = ((LeafElement)chameleon).textToCharArray();
final PsiManager manager = chameleon.getTreeParent().getPsi().getManager();
final Project project = manager.getProject();
return FileTextParsing.parseFileText(manager, getLanguage().getParserDefinition().createLexer(project),
chars, 0, chars.length, SharedImplUtil.findCharTableByTree(chameleon));
}
public boolean isParsable(CharSequence buffer, final Project project) {return true;}
};
IElementType IMPORT_LIST = new IChameleonElementType("IMPORT_LIST_TEXT", StdLanguages.JAVA){
public ASTNode parseContents(ASTNode chameleon) {
final char[] chars = ((LeafElement)chameleon).textToCharArray();
final PsiManager manager = chameleon.getTreeParent().getPsi().getManager();
final JavaParsingContext context = new JavaParsingContext(SharedImplUtil.findCharTableByTree(chameleon), manager.getEffectiveLanguageLevel());
return context.getImportsTextParsing().parseImportsText(manager, getLanguage().getParserDefinition().createLexer(manager.getProject()),
chars, 0, chars.length, ((LeafElement)chameleon).getState());
}
public boolean isParsable(CharSequence buffer, final Project project) {return false;}
};
IElementType CODE_BLOCK = new IErrorCounterChameleonElementType("CODE_BLOCK", StdLanguages.JAVA){
public ASTNode parseContents(ASTNode chameleon) {
final char[] chars = ((LeafElement)chameleon).textToCharArray();
final PsiManager manager = chameleon.getTreeParent().getPsi().getManager();
final CharTable table = SharedImplUtil.findCharTableByTree(chameleon);
JavaParsingContext context = new JavaParsingContext(table, manager.getEffectiveLanguageLevel());
return context.getStatementParsing().parseCodeBlockText(manager, getLanguage().getParserDefinition().createLexer(manager.getProject()),
chars, 0, chars.length, ((LeafElement)chameleon).getState()).getFirstChildNode();
}
public int getErrorsCount(CharSequence seq, Project project) {
final Lexer lexer = getLanguage().getParserDefinition().createLexer(project);
final char[] chars = CharArrayUtil.fromSequence(seq);
lexer.start(chars, 0, chars.length);
if(lexer.getTokenType() != JavaTokenType.LBRACE) return FATAL_ERROR;
lexer.advance();
int balance = 1;
IElementType type;
while(true){
type = lexer.getTokenType();
if (type == null) break;
if(balance == 0) return FATAL_ERROR;
if (type == JavaTokenType.LBRACE) {
balance++;
}
else if (type == JavaTokenType.RBRACE) {
balance--;
}
lexer.advance();
}
return balance;
}
};
IElementType EXPRESSION_STATEMENT = new IChameleonElementType("EXPRESSION_STATEMENT", StdLanguages.JAVA){
public ASTNode parseContents(ASTNode chameleon) {
final char[] chars = ((LeafElement)chameleon).textToCharArray();
final PsiManager manager = chameleon.getTreeParent().getPsi().getManager();
final JavaParsingContext context = new JavaParsingContext(SharedImplUtil.findCharTableByTree(chameleon), manager.getEffectiveLanguageLevel());
return context.getExpressionParsing().parseExpressionTextFragment(manager, chars, 0, chars.length, ((LeafElement)chameleon).getState());
}
public boolean isParsable(CharSequence buffer, final Project project) {return false;}
};
//The following are the children of code fragment
IElementType STATEMENTS = new ICodeFragmentElementType("STATEMENTS", StdLanguages.JAVA){
public ASTNode parseContents(ASTNode chameleon) {
final char[] chars = ((LeafElement)chameleon).textToCharArray();
final PsiManager manager = chameleon.getTreeParent().getPsi().getManager();
final CharTable table = SharedImplUtil.findCharTableByTree(chameleon);
JavaParsingContext context = new JavaParsingContext(table, manager.getEffectiveLanguageLevel());
return context.getStatementParsing().parseStatements(manager, getLanguage().getParserDefinition().createLexer(manager.getProject()), chars, 0, chars.length,
((LeafElement)chameleon).getState());
}
public boolean isParsable(CharSequence buffer, final Project project) {return false;}
};
IElementType EXPRESSION_TEXT = new ICodeFragmentElementType("EXPRESSION_TEXT", StdLanguages.JAVA){
public ASTNode parseContents(ASTNode chameleon) {
final char[] chars = ((LeafElement)chameleon).textToCharArray();
final PsiManager manager = chameleon.getTreeParent().getPsi().getManager();
final JavaParsingContext context = new JavaParsingContext(SharedImplUtil.findCharTableByTree(chameleon), manager.getEffectiveLanguageLevel());
return context.getExpressionParsing().parseExpressionTextFragment(manager, chars, 0, chars.length, ((LeafElement)chameleon).getState());
}
public boolean isParsable(CharSequence buffer, final Project project) {return false;}
};
IElementType REFERENCE_TEXT = new ICodeFragmentElementType("REFERENCE_TEXT", StdLanguages.JAVA){
public ASTNode parseContents(ASTNode chameleon) {
final char[] chars = ((LeafElement)chameleon).textToCharArray();
return Parsing.parseJavaCodeReferenceText(chameleon.getTreeParent().getPsi().getManager(), chars, 0, chars.length, SharedImplUtil.findCharTableByTree(chameleon), true);
}
public boolean isParsable(CharSequence buffer, final Project project) {return false;}
};
IElementType TYPE_TEXT = new ICodeFragmentElementType("TYPE_TEXT", StdLanguages.JAVA){
public ASTNode parseContents(ASTNode chameleon) {
final char[] chars = ((LeafElement)chameleon).textToCharArray();
return Parsing.parseTypeText(chameleon.getTreeParent().getPsi().getManager(), null, chars, 0, chars.length, 0, SharedImplUtil.findCharTableByTree(chameleon));
}
public boolean isParsable(CharSequence buffer, final Project project) {return false;}
};
}
| source/com/intellij/psi/impl/source/tree/JavaElementType.java | package com.intellij.psi.impl.source.tree;
import com.intellij.lang.ASTNode;
import com.intellij.lang.StdLanguages;
import com.intellij.lexer.Lexer;
import com.intellij.openapi.project.Project;
import com.intellij.psi.JavaTokenType;
import com.intellij.psi.PsiManager;
import com.intellij.psi.impl.source.parsing.JavaParsingContext;
import com.intellij.psi.impl.source.parsing.FileTextParsing;
import com.intellij.psi.impl.source.parsing.Parsing;
import com.intellij.psi.tree.IChameleonElementType;
import com.intellij.psi.tree.IElementType;
import com.intellij.psi.tree.IErrorCounterChameleonElementType;
import com.intellij.psi.tree.java.IJavaElementType;
import com.intellij.util.text.CharArrayUtil;
import com.intellij.util.CharTable;
public interface JavaElementType {
//chameleons
IElementType TYPE_PARAMETER = new IJavaElementType("TYPE_PARAMETER");
IElementType TYPE_PARAMETER_LIST = new IJavaElementType("TYPE_PARAMETER_LIST");
IElementType ERROR_ELEMENT = new IJavaElementType("ERROR_ELEMENT");
IElementType JAVA_CODE_REFERENCE = new IJavaElementType("JAVA_CODE_REFERENCE");
IElementType PACKAGE_STATEMENT = new IJavaElementType("PACKAGE_STATEMENT");
IElementType CLASS = new IJavaElementType("CLASS");
IElementType ANONYMOUS_CLASS = new IJavaElementType("ANONYMOUS_CLASS");
IElementType ENUM_CONSTANT_INITIALIZER = new IJavaElementType("ENUM_CONSTANT_INITIALIZER");
IElementType IMPORT_STATEMENT = new IJavaElementType("IMPORT_STATEMENT");
IElementType IMPORT_STATIC_STATEMENT = new IJavaElementType("IMPORT_STATIC_STATEMENT");
IElementType IMPORT_STATIC_REFERENCE = new IJavaElementType("IMPORT_STATIC_REFERENCE");
IElementType MODIFIER_LIST = new IJavaElementType("MODIFIER_LIST");
IElementType EXTENDS_LIST = new IJavaElementType("EXTENDS_LIST");
IElementType IMPLEMENTS_LIST = new IJavaElementType("IMPLEMENTS_LIST");
IElementType FIELD = new IJavaElementType("FIELD");
IElementType ENUM_CONSTANT = new IJavaElementType("ENUM_CONSTANT");
IElementType METHOD = new IJavaElementType("METHOD");
IElementType LOCAL_VARIABLE = new IJavaElementType("LOCAL_VARIABLE");
IElementType CLASS_INITIALIZER = new IJavaElementType("CLASS_INITIALIZER");
IElementType PARAMETER = new IJavaElementType("PARAMETER");
IElementType TYPE = new IJavaElementType("TYPE");
IElementType PARAMETER_LIST = new IJavaElementType("PARAMETER_LIST");
IElementType EXTENDS_BOUND_LIST = new IJavaElementType("EXTENDS_BOUND_LIST");
IElementType THROWS_LIST = new IJavaElementType("THROWS_LIST");
IElementType REFERENCE_PARAMETER_LIST = new IJavaElementType("REFERENCE_PARAMETER_LIST");
IElementType REFERENCE_EXPRESSION = new IJavaElementType("REFERENCE_EXPRESSION");
IElementType LITERAL_EXPRESSION = new IJavaElementType("LITERAL_EXPRESSION");
IElementType THIS_EXPRESSION = new IJavaElementType("THIS_EXPRESSION");
IElementType SUPER_EXPRESSION = new IJavaElementType("SUPER_EXPRESSION");
IElementType PARENTH_EXPRESSION = new IJavaElementType("PARENTH_EXPRESSION");
IElementType METHOD_CALL_EXPRESSION = new IJavaElementType("METHOD_CALL_EXPRESSION");
IElementType TYPE_CAST_EXPRESSION = new IJavaElementType("TYPE_CAST_EXPRESSION");
IElementType PREFIX_EXPRESSION = new IJavaElementType("PREFIX_EXPRESSION");
IElementType POSTFIX_EXPRESSION = new IJavaElementType("POSTFIX_EXPRESSION");
IElementType BINARY_EXPRESSION = new IJavaElementType("BINARY_EXPRESSION");
IElementType CONDITIONAL_EXPRESSION = new IJavaElementType("CONDITIONAL_EXPRESSION");
IElementType ASSIGNMENT_EXPRESSION = new IJavaElementType("ASSIGNMENT_EXPRESSION");
IElementType NEW_EXPRESSION = new IJavaElementType("NEW_EXPRESSION");
IElementType ARRAY_ACCESS_EXPRESSION = new IJavaElementType("ARRAY_ACCESS_EXPRESSION");
IElementType ARRAY_INITIALIZER_EXPRESSION = new IJavaElementType("ARRAY_INITIALIZER_EXPRESSION");
IElementType INSTANCE_OF_EXPRESSION = new IJavaElementType("INSTANCE_OF_EXPRESSION");
IElementType CLASS_OBJECT_ACCESS_EXPRESSION = new IJavaElementType("CLASS_OBJECT_ACCESS_EXPRESSION");
IElementType EMPTY_EXPRESSION = new IJavaElementType("EMPTY_EXPRESSION");
IElementType EXPRESSION_LIST = new IJavaElementType("EXPRESSION_LIST");
IElementType EMPTY_STATEMENT = new IJavaElementType("EMPTY_STATEMENT");
IElementType BLOCK_STATEMENT = new IJavaElementType("BLOCK_STATEMENT");
IElementType EXPRESSION_LIST_STATEMENT = new IJavaElementType("EXPRESSION_LIST_STATEMENT");
IElementType DECLARATION_STATEMENT = new IJavaElementType("DECLARATION_STATEMENT");
IElementType IF_STATEMENT = new IJavaElementType("IF_STATEMENT");
IElementType WHILE_STATEMENT = new IJavaElementType("WHILE_STATEMENT");
IElementType FOR_STATEMENT = new IJavaElementType("FOR_STATEMENT");
IElementType FOREACH_STATEMENT = new IJavaElementType("FOREACH_STATEMENT");
IElementType DO_WHILE_STATEMENT = new IJavaElementType("DO_WHILE_STATEMENT");
IElementType SWITCH_STATEMENT = new IJavaElementType("SWITCH_STATEMENT");
IElementType SWITCH_LABEL_STATEMENT = new IJavaElementType("SWITCH_LABEL_STATEMENT");
IElementType BREAK_STATEMENT = new IJavaElementType("BREAK_STATEMENT");
IElementType CONTINUE_STATEMENT = new IJavaElementType("CONTINUE_STATEMENT");
IElementType RETURN_STATEMENT = new IJavaElementType("RETURN_STATEMENT");
IElementType THROW_STATEMENT = new IJavaElementType("THROW_STATEMENT");
IElementType SYNCHRONIZED_STATEMENT = new IJavaElementType("SYNCHRONIZED_STATEMENT");
IElementType TRY_STATEMENT = new IJavaElementType("TRY_STATEMENT");
IElementType LABELED_STATEMENT = new IJavaElementType("LABELED_STATEMENT");
IElementType ASSERT_STATEMENT = new IJavaElementType("ASSERT_STATEMENT");
IElementType CATCH_SECTION = new IJavaElementType("CATCH_SECTION");
IElementType ANNOTATION_METHOD = new IJavaElementType("ANNOTATION_METHOD");
IElementType ANNOTATION_ARRAY_INITIALIZER = new IJavaElementType("ANNOTATION_ARRAY_INITIALIZER");
IElementType ANNOTATION = new IJavaElementType("ANNOTATION");
IElementType NAME_VALUE_PAIR = new IJavaElementType("NAME_VALUE_PAIR");
IElementType ANNOTATION_PARAMETER_LIST = new IJavaElementType("ANNOTATION_PARAMETER_LIST");
IElementType JAVA_FILE = new IChameleonElementType("JAVA_FILE_TEXT", StdLanguages.JAVA){
public ASTNode parseContents(ASTNode chameleon) {
final char[] chars = ((LeafElement)chameleon).textToCharArray();
final PsiManager manager = chameleon.getTreeParent().getPsi().getManager();
final Project project = manager.getProject();
return FileTextParsing.parseFileText(manager, getLanguage().getParserDefinition().createLexer(project),
chars, 0, chars.length, SharedImplUtil.findCharTableByTree(chameleon));
}
public boolean isParsable(CharSequence buffer, final Project project) {return true;}
};
IElementType IMPORT_LIST = new IChameleonElementType("IMPORT_LIST_TEXT", StdLanguages.JAVA){
public ASTNode parseContents(ASTNode chameleon) {
final char[] chars = ((LeafElement)chameleon).textToCharArray();
final PsiManager manager = chameleon.getTreeParent().getPsi().getManager();
final JavaParsingContext context = new JavaParsingContext(SharedImplUtil.findCharTableByTree(chameleon), manager.getEffectiveLanguageLevel());
return context.getImportsTextParsing().parseImportsText(manager, getLanguage().getParserDefinition().createLexer(manager.getProject()),
chars, 0, chars.length, ((LeafElement)chameleon).getState());
}
public boolean isParsable(CharSequence buffer, final Project project) {return false;}
};
IElementType CODE_BLOCK = new IErrorCounterChameleonElementType("CODE_BLOCK", StdLanguages.JAVA){
public ASTNode parseContents(ASTNode chameleon) {
final char[] chars = ((LeafElement)chameleon).textToCharArray();
final PsiManager manager = chameleon.getTreeParent().getPsi().getManager();
final CharTable table = SharedImplUtil.findCharTableByTree(chameleon);
JavaParsingContext context = new JavaParsingContext(table, manager.getEffectiveLanguageLevel());
return context.getStatementParsing().parseCodeBlockText(manager, getLanguage().getParserDefinition().createLexer(manager.getProject()),
chars, 0, chars.length, ((LeafElement)chameleon).getState()).getFirstChildNode();
}
public int getErrorsCount(CharSequence seq, Project project) {
final Lexer lexer = getLanguage().getParserDefinition().createLexer(project);
final char[] chars = CharArrayUtil.fromSequence(seq);
lexer.start(chars, 0, chars.length);
int balance = 0;
while(true){
IElementType type = lexer.getTokenType();
if (type == null) break;
if (type == JavaTokenType.LBRACE) {
balance++;
}
else if (type == JavaTokenType.RBRACE) {
balance--;
}
lexer.advance();
}
return balance;
}
};
IElementType EXPRESSION_STATEMENT = new IChameleonElementType("EXPRESSION_STATEMENT", StdLanguages.JAVA){
public ASTNode parseContents(ASTNode chameleon) {
final char[] chars = ((LeafElement)chameleon).textToCharArray();
final PsiManager manager = chameleon.getTreeParent().getPsi().getManager();
final JavaParsingContext context = new JavaParsingContext(SharedImplUtil.findCharTableByTree(chameleon), manager.getEffectiveLanguageLevel());
return context.getExpressionParsing().parseExpressionTextFragment(manager, chars, 0, chars.length, ((LeafElement)chameleon).getState());
}
public boolean isParsable(CharSequence buffer, final Project project) {return false;}
};
//The following are the children of code fragment
IElementType STATEMENTS = new ICodeFragmentElementType("STATEMENTS", StdLanguages.JAVA){
public ASTNode parseContents(ASTNode chameleon) {
final char[] chars = ((LeafElement)chameleon).textToCharArray();
final PsiManager manager = chameleon.getTreeParent().getPsi().getManager();
final CharTable table = SharedImplUtil.findCharTableByTree(chameleon);
JavaParsingContext context = new JavaParsingContext(table, manager.getEffectiveLanguageLevel());
return context.getStatementParsing().parseStatements(manager, getLanguage().getParserDefinition().createLexer(manager.getProject()), chars, 0, chars.length,
((LeafElement)chameleon).getState());
}
public boolean isParsable(CharSequence buffer, final Project project) {return false;}
};
IElementType EXPRESSION_TEXT = new ICodeFragmentElementType("EXPRESSION_TEXT", StdLanguages.JAVA){
public ASTNode parseContents(ASTNode chameleon) {
final char[] chars = ((LeafElement)chameleon).textToCharArray();
final PsiManager manager = chameleon.getTreeParent().getPsi().getManager();
final JavaParsingContext context = new JavaParsingContext(SharedImplUtil.findCharTableByTree(chameleon), manager.getEffectiveLanguageLevel());
return context.getExpressionParsing().parseExpressionTextFragment(manager, chars, 0, chars.length, ((LeafElement)chameleon).getState());
}
public boolean isParsable(CharSequence buffer, final Project project) {return false;}
};
IElementType REFERENCE_TEXT = new ICodeFragmentElementType("REFERENCE_TEXT", StdLanguages.JAVA){
public ASTNode parseContents(ASTNode chameleon) {
final char[] chars = ((LeafElement)chameleon).textToCharArray();
return Parsing.parseJavaCodeReferenceText(chameleon.getTreeParent().getPsi().getManager(), chars, 0, chars.length, SharedImplUtil.findCharTableByTree(chameleon), true);
}
public boolean isParsable(CharSequence buffer, final Project project) {return false;}
};
IElementType TYPE_TEXT = new ICodeFragmentElementType("TYPE_TEXT", StdLanguages.JAVA){
public ASTNode parseContents(ASTNode chameleon) {
final char[] chars = ((LeafElement)chameleon).textToCharArray();
return Parsing.parseTypeText(chameleon.getTreeParent().getPsi().getManager(), null, chars, 0, chars.length, 0, SharedImplUtil.findCharTableByTree(chameleon));
}
public boolean isParsable(CharSequence buffer, final Project project) {return false;}
};
}
| java reparse issue fixed
| source/com/intellij/psi/impl/source/tree/JavaElementType.java | java reparse issue fixed | <ide><path>ource/com/intellij/psi/impl/source/tree/JavaElementType.java
<ide> final Lexer lexer = getLanguage().getParserDefinition().createLexer(project);
<ide> final char[] chars = CharArrayUtil.fromSequence(seq);
<ide> lexer.start(chars, 0, chars.length);
<del> int balance = 0;
<add> if(lexer.getTokenType() != JavaTokenType.LBRACE) return FATAL_ERROR;
<add> lexer.advance();
<add> int balance = 1;
<add> IElementType type;
<ide> while(true){
<del> IElementType type = lexer.getTokenType();
<add> type = lexer.getTokenType();
<ide> if (type == null) break;
<add> if(balance == 0) return FATAL_ERROR;
<ide> if (type == JavaTokenType.LBRACE) {
<ide> balance++;
<ide> } |
|
Java | mit | 330f8f4a8e3dc9cd51d1ace37f2828f2b0f245b3 | 0 | dozedoff/commonj | /* Copyright (C) 2012 Nicholas Wright
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package file;
import java.io.BufferedInputStream;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
public class BinaryFileReader {
int blockLength = 8192;
ByteBuffer classBuffer;
byte[] c = new byte[blockLength];
public BinaryFileReader(){
classBuffer = ByteBuffer.allocate(31457280); //30mb
}
/**
* Set the Buffers initial capacity in bytes.
* @param buffersize size in bytes
*/
public BinaryFileReader(int buffersize){
classBuffer = ByteBuffer.allocate(buffersize);
}
public BinaryFileReader(int buffersize, int blocklength){
classBuffer = ByteBuffer.allocate(buffersize);
this.blockLength = blocklength;
}
public byte[] get(String path) throws Exception{
return get(new File(path));
}
public byte[] get(File path) throws IOException{
BufferedInputStream binary = null;
if(path.length() > classBuffer.capacity())
classBuffer = ByteBuffer.allocate((int)path.length());
FileInputStream fileStream = new FileInputStream(path);
binary = new BufferedInputStream(fileStream);
classBuffer.clear();
int count = 0;
while ((count=binary.read(c)) != -1){
classBuffer.put(c, 0, count);
}
classBuffer.flip();
byte[] varBuffer = new byte[classBuffer.limit()];
classBuffer.get(varBuffer);
fileStream.close();
binary.close();
return varBuffer;
}
public byte[] getViaDataInputStream(File path) throws IOException{
DataInputStream dis;
byte[] data = new byte[(int)path.length()];
FileInputStream fileStream = new FileInputStream(path);
dis = new DataInputStream(fileStream);
dis.readFully(data);
dis.close();
return data;
}
}
| src/file/BinaryFileReader.java | /* Copyright (C) 2012 Nicholas Wright
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package file;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
public class BinaryFileReader {
int blockLength = 8192;
ByteBuffer classBuffer;
byte[] c = new byte[blockLength];
public BinaryFileReader(){
classBuffer = ByteBuffer.allocate(31457280); //30mb
}
/**
* Set the Buffers initial capacity in bytes.
* @param buffersize size in bytes
*/
public BinaryFileReader(int buffersize){
classBuffer = ByteBuffer.allocate(buffersize);
}
public BinaryFileReader(int buffersize, int blocklength){
classBuffer = ByteBuffer.allocate(buffersize);
this.blockLength = blocklength;
}
public byte[] get(String path) throws Exception{
return get(new File(path));
}
public byte[] get(File path) throws IOException{
BufferedInputStream binary = null;
if(path.length() > classBuffer.capacity())
classBuffer = ByteBuffer.allocate((int)path.length());
FileInputStream fileStream = new FileInputStream(path);
binary = new BufferedInputStream(fileStream);
classBuffer.clear();
int count = 0;
while ((count=binary.read(c)) != -1){
classBuffer.put(c, 0, count);
}
classBuffer.flip();
byte[] varBuffer = new byte[classBuffer.limit()];
classBuffer.get(varBuffer);
fileStream.close();
binary.close();
return varBuffer;
}
}
| added different method for reading files | src/file/BinaryFileReader.java | added different method for reading files | <ide><path>rc/file/BinaryFileReader.java
<ide> package file;
<ide>
<ide> import java.io.BufferedInputStream;
<add>import java.io.DataInputStream;
<ide> import java.io.File;
<ide> import java.io.FileInputStream;
<ide> import java.io.IOException;
<ide>
<ide> return varBuffer;
<ide> }
<add>
<add> public byte[] getViaDataInputStream(File path) throws IOException{
<add>
<add> DataInputStream dis;
<add> byte[] data = new byte[(int)path.length()];
<add>
<add> FileInputStream fileStream = new FileInputStream(path);
<add> dis = new DataInputStream(fileStream);
<add>
<add> dis.readFully(data);
<add>
<add> dis.close();
<add>
<add> return data;
<add> }
<ide>
<ide> } |
|
Java | apache-2.0 | 8f410e3832ecd0635f472fa1b08e33ee4c97ca35 | 0 | liqinlong/L_Redmine,liqinlong/L_Redmine,liqinlong/L_Redmine | package liql.redmine;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import com.taskadapter.redmineapi.RedmineException;
import com.taskadapter.redmineapi.RedmineManager;
import com.taskadapter.redmineapi.bean.Issue;
import com.taskadapter.redmineapi.bean.Project;
import jxl.write.WriteException;
import liql.util.L_Excel;
import liql.util.L_LOG;
import liql.util.L_Util;
import nosubmit.L_Security;
public class L_GetIssue_Delay {
private static final String OUTDIR = L_Security.BASEDIR + "ǰѾissue" + File.separator;
public static void getCurrentDelayissues(RedmineManager mgr) {
try {
L_Util.mkdir(OUTDIR);
LinkedList<RedmineRowData> ALLINONE = new LinkedList<RedmineRowData>();
// list projects
List<Project> projects = mgr.getProjectManager().getProjects();
for (Project project : projects) {
if (L_Security.NOSCRIBE.contains(project.getId())) {
continue;// don't subcribe
}
LinkedList<RedmineRowData> rowsdata = new LinkedList<RedmineRowData>();
HashMap<String, String> param = new HashMap<String, String>();
param.put("project_id", String.valueOf(project.getId()));
// each project list issues
List<Issue> issues = mgr.getIssueManager().getIssues(param);
for (Issue issue : issues) {
// ѯųѹر&̱
// 4-̱
if (issue.getStatusId() == 5 || issue.getTracker().getId() == 4) {
continue;
}
if (null != issue.getDueDate()) {
long issueduedate = issue.getDueDate().getTime();// issueƻʱ
long curdate = System.currentTimeMillis();// ǰʱ
// if ״̬ѹر && ǰʱ>ƻʱ
if (issueduedate > curdate) {
continue;
}
}
rowsdata.add(new RedmineRowData(issue.getProject().getName(), issue.getId(), issue.getSubject(),
issue.getTracker().getName(), issue.getStatusName(), issue.getPriorityText(),
issue.getAuthor().toString(), issue.getAssigneeName(),
L_Util.fmt_YYYYMMDD(issue.getCreatedOn()), L_Util.fmt_YYYYMMDD(issue.getStartDate()),
L_Util.fmt_YYYYMMDD(issue.getUpdatedOn()), L_Util.fmt_YYYYMMDD(issue.getDueDate()),
issue.getDescription()));
}
L_LOG.OUT_Nece(project.getName() + "\t\t issue nums : " + rowsdata.size());
ALLINONE.addAll(rowsdata);
L_Excel.WriteExcel_Redmine(OUTDIR + "[" + project.getName() + "]_issues_delay(" + rowsdata.size() + ")"
+ L_Security.EXCELFIX, rowsdata);
rowsdata = null;
}
L_Excel.WriteExcel_Redmine(OUTDIR + "ALLINONE_issues_delay(" + ALLINONE.size() + ")" + L_Security.EXCELFIX,
ALLINONE);
L_LOG.OUT_Nece("all issue nums : " + ALLINONE.size());
} catch (RedmineException | WriteException | IOException e) {
e.printStackTrace();
}
}
}
| src/liql/redmine/L_GetIssue_Delay.java | package liql.redmine;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import com.taskadapter.redmineapi.RedmineException;
import com.taskadapter.redmineapi.RedmineManager;
import com.taskadapter.redmineapi.bean.Issue;
import com.taskadapter.redmineapi.bean.Project;
import jxl.write.WriteException;
import liql.util.L_Excel;
import liql.util.L_LOG;
import liql.util.L_Util;
import nosubmit.L_Security;
public class L_GetIssue_Delay {
private static final String OUTDIR = L_Security.BASEDIR + "ǰѾissue" + File.separator;
public static void getCurrentDelayissues(RedmineManager mgr) {
try {
L_Util.mkdir(OUTDIR);
LinkedList<RedmineRowData> ALLINONE = new LinkedList<RedmineRowData>();
// list projects
List<Project> projects = mgr.getProjectManager().getProjects();
for (Project project : projects) {
if (L_Security.NOSCRIBE.contains(project.getId())) {
continue;// don't subcribe
}
LinkedList<RedmineRowData> rowsdata = new LinkedList<RedmineRowData>();
HashMap<String, String> param = new HashMap<String, String>();
param.put("project_id", String.valueOf(project.getId()));
// each project list issues
List<Issue> issues = mgr.getIssueManager().getIssues(param);
for (Issue issue : issues) {
// ѯųѹر&̱
// 4-̱
if (issue.getStatusId() == 5 || issue.getTracker().getId() == 4) {
continue;
}
if (null != null) {
long issueduedate = issue.getDueDate().getTime();// issueƻʱ
long curdate = System.currentTimeMillis();// ǰʱ
// if ״̬ѹر && ǰʱ>ƻʱ
if (issueduedate > curdate) {
continue;
}
}
rowsdata.add(new RedmineRowData(issue.getProject().getName(), issue.getId(), issue.getSubject(),
issue.getTracker().getName(), issue.getStatusName(), issue.getPriorityText(),
issue.getAuthor().toString(), issue.getAssigneeName(),
L_Util.fmt_YYYYMMDD(issue.getCreatedOn()), L_Util.fmt_YYYYMMDD(issue.getStartDate()),
L_Util.fmt_YYYYMMDD(issue.getUpdatedOn()), L_Util.fmt_YYYYMMDD(issue.getDueDate()),
issue.getDescription()));
}
L_LOG.OUT_Nece(project.getName() + "\t\t issue nums : " + rowsdata.size());
ALLINONE.addAll(rowsdata);
L_Excel.WriteExcel_Redmine(OUTDIR + "[" + project.getName() + "]_issues_delay(" + rowsdata.size() + ")"
+ L_Security.EXCELFIX, rowsdata);
rowsdata = null;
}
L_Excel.WriteExcel_Redmine(OUTDIR + "ALLINONE_issues_delay(" + ALLINONE.size() + ")" + L_Security.EXCELFIX,
ALLINONE);
L_LOG.OUT_Nece("all issue nums : " + ALLINONE.size());
} catch (RedmineException | WriteException | IOException e) {
e.printStackTrace();
}
}
}
| 修复完成时间null的bug | src/liql/redmine/L_GetIssue_Delay.java | 修复完成时间null的bug | <ide><path>rc/liql/redmine/L_GetIssue_Delay.java
<ide> if (issue.getStatusId() == 5 || issue.getTracker().getId() == 4) {
<ide> continue;
<ide> }
<del> if (null != null) {
<add> if (null != issue.getDueDate()) {
<ide> long issueduedate = issue.getDueDate().getTime();// issueƻʱ
<ide> long curdate = System.currentTimeMillis();// ǰʱ
<ide> |
|
JavaScript | mit | af19d71d4818d86ec773f4b0047bdcc1e1645722 | 0 | dominictarr/assertions | var extended = require('./extended')
, elementary = require('./elementary')
, traverser = require('traverser')
, render = require('render')
, fail = require('./failure').fail
module.exports = {
every: every,
has: has,
apply: apply,
throws: throws,
path: path,
noop: noop,
atIndex: atIndex,
property: property
}
function property (actual, property, value, message){
function explain(err, template) {
throw fail(err).explain(
'property:'+template
, { actual: actual
, property: property
, path: [property]
, assertion: value
}
, message
)
}
if(!actual[property] && value == null)
//checks that property is defined on actual, even if it is undefined (but not deleted)
explain(new Error(), 'property: {actual:render}{path:path} must exist')
//if value is a function, assume it is an assertion... apply it to actual[property]
if('function' == typeof value) {
try { value(actual[property]) } catch (err) {
explain(err, 'property: ({actual:render}){path:path} must pass {assertion:function}')
}
} else if (value != null) //else if value is exiting, check it's equal to actual[property]
try { elementary.equal(actual[property], value) } catch (err) {
explain(err, 'property: ({actual:render}){path:path} must equal {assertion:function}')
}
//if you want to assert a value is null or undefined,
//use .property(name,it.equal(null|undefined))
}
function path (actual, expected, assertion, message) {
var current = actual
, soFar = []
if('string' == typeof expected) expected = [expected] //allow a singe key as a string
if('function' != typeof assertion) message = assertion, assertion = noop
for ( var i in expected) {
var key = expected[i]
current = current[key]
soFar.push(key)
if(!(typeof current !== 'undefined')) // check if there actually is a property
throw fail(new Error()).explain(
'path: ({actual:render}){soFar:path} must exist, (is undefined), expected path: {path:path}'
, { actual: actual, soFar: soFar, path:expected}
, message
)
}
try {
assertion(current)
} catch (err) {
throw fail(err).explain(
'path: expected ({actual:render}){path:path} to pass {assertion:function}'
, { actual: actual
, path: expected
, assertion: assertion
, current: current }
, message
)
}
return current
}
function apply (actual, assertion, message) {
//catch and wrap in message
try {
assertion (actual)
} catch (err) {
throw fail(err).explain('apply: {actual:render} did not pass {assertion:function}', {
actual: actual,
expected: assertion,
assertion: assertion
}, message)
}
}
function noop () {}
function throws (actual, assertion, message) {
if('string' == typeof assertion) message = assertion, assertion= noop
try {
actual()
} catch (err) {
try {
return apply (err, assertion, message)
} catch (f) {
throw f.explain(
'throws: {actual} threw an exception that did not pass {assertion:function}'
, {actual: actual, assertion: assertion}
, message
)
}
}
throw fail().explain('throws: {actual} did not throw', {actual: actual, expected: assertion}, message)
}
function every (array, assertion, message){
try{
extended.isArray(array)
}catch(err){
throw fail(err).explain('every: {actual:render} must be an Array')
}
for(var i in array){
try {
assertion.call(null,array[i])
} catch (err) {
throw fail(err).explain(
'every: every[{index}] (== {actual:render}) must pass {assertion:function}, \n ({index} out of {every.length} have passed)'
, { index: i
, every: array
, assertion: assertion
, actual: array[i]
}
, message
)
}
}
}
function has(obj, props, message) {
var pathTo = []
//traverser has lots of functions, so it needs a longer stack trace.
var orig = Error.stackTraceLimit
Error.stackTraceLimit = orig + 20
if('object' !== typeof props)
return extended.equal(obj, props)
try{
traverser(props, {leaf:leaf, branch: branch})
} catch (err){
err = fail(err).explain(
'has: ({actual:render}){path:path} must match {expected:render}){path:path}'
, { actual: obj
, expected: props
, path: pathTo
}
, message
)
Error.stackTraceLimit = orig
throw err
}
function leaf(p){
pathTo = p.path
var other = path(obj,p.path)
if('function' == typeof p.value){
p.value.call(p.value.parent,other)
}
else {
//since this is the leaf function, it cannot be an object.
elementary.equal(other,p.value)
}
}
function branch (p){
pathTo = p.path
var other = path(obj,p.path)
if('function' !== typeof p.value)
extended.complex(other)
p.each()
}
}
function atIndex (actual, relativeIndex, assertion, message) {
var index = relativeIndex < 0 ? actual.length + relativeIndex : relativeIndex
, minLength = Math.abs(relativeIndex)
;
function explain(err, template) {
throw fail(err).explain('atIndex: ' + template
, {actual: actual
, index: index
, relativeIndex: relativeIndex
, minLength: minLength
, assertion: assertion
}
, message)
}
if(!(actual))
explain(new Error(), '{actual:render} must not be null')
if(!(actual.length))
explain(new Error(), '{actual:render} must have length property')
if(!(actual.length > minLength))
explain(new Error(), '{actual:render}.length (== {actual.length}) must be greater than {minLength}')
if(!('function' == typeof assertion))
message = assertion, assertion == noop
try {
assertion(actual[index])
} catch (err) {
explain(err, '({actual:render})[{index}] must pass {assertion:function}')
}
}
/*
higher level assections that could be implemented:
* all(actual, assertions..., message) //all assertions must pass
* any(actual, assertions..., message) //at least one assertion must pass
//if index is negative, take index as length + index
refactor so that whereever it says 'assertion', if it's not a function : use equal.
*/
| higher.js | var extended = require('./extended')
, elementary = require('./elementary')
, traverser = require('traverser')
, render = require('render')
, fail = require('./failure').fail
module.exports = {
every: every,
has: has,
apply: apply,
throws: throws,
path: path,
noop: noop,
atIndex: atIndex,
property: property
}
function property (actual, property, value, message){
function explain(err, template) {
throw fail(err).explain(
'property:'+template
, { actual: actual
, property: property
, path: [property]
, assertion: value
}
, message
)
}
if(!actual[property] && value == null)
//checks that property is defined on actual, even if it is undefined (but not deleted)
explain(new Error(), 'property: {actual:render}{path:path} must exist')
//if value is a function, assume it is an assertion... apply it to actual[property]
if('function' == typeof value) {
try { value(actual[property]) } catch (err) {
explain(err, 'property: ({actual:render}){path:path} must pass {assertion:function}')
}
} else if (value != null) //else if value is exiting, check it's equal to actual[property]
try { elementary.equal(actual[property], value) } catch (err) {
explain(err, 'property: ({actual:render}){path:path} must equal {assertion:function}')
}
//if you want to assert a value is null or undefined,
//use .property(name,it.equal(null|undefined))
}
function path (actual, expected, assertion, message) {
var current = actual
, soFar = []
if('string' == typeof expected) expected = [expected] //allow a singe key as a string
if('function' != typeof assertion) message = assertion, assertion = noop
for ( var i in expected) {
var key = expected[i]
current = current[key]
soFar.push(key)
if(!(typeof current !== 'undefined')) // check if there actually is a property
throw fail(new Error()).explain(
'path: ({actual:render}){soFar:path} must exist, (is undefined), expected path: {path:path}'
, { actual: actual, soFar: soFar, path:expected}
, message
)
}
try {
assertion(current)
} catch (err) {
throw fail(err).explain(
'path: expected ({actual:render}){path:path} to pass {assertion:function}'
, { actual: actual
, path: expected
, assertion: assertion
, current: current }
, message
)
}
return current
}
function apply (actual, assertion, message) {
//catch and wrap in message
try {
assertion (actual)
} catch (err) {
throw fail(err).explain('apply: {actual:render} did not pass {assertion:function}', {
actual: actual,
expected: assertion,
assertion: assertion
}, message)
}
}
function noop () {}
function throws (actual, assertion, message) {
if('string' == typeof assertion) message = assertion, assertion= noop
try {
actual()
} catch (err) {
try {
return apply (err, assertion, message)
} catch (f) {
throw f.explain(
'throws: {actual} threw an exception that did not pass {assertion:function}'
, {actual: actual, assertion: assertion}
, message
)
}
}
throw fail().explain('throws: {actual} did not throw', {actual: actual, expected: assertion}, message)
}
function every (array, assertion, message){
try{
extended.isArray(array)
}catch(err){
throw fail(err).explain('every: {actual:render} must be an Array')
}
for(var i in array){
try {
assertion.call(null,array[i])
} catch (err) {
throw fail(err).explain(
'every: every[{index}] (== {actual:render}) must pass {assertion:function}, \n ({index} out of {every.length} have passed)'
, { index: i
, every: array
, assertion: assertion
, actual: array[i]
}
, message
)
}
}
}
function has(obj, props, message) {
var pathTo = []
//traverser has lots of functions, so it needs a longer stack trace.
var orig = Error.stackTraceLimit
Error.stackTraceLimit = orig + 20
if('object' !== typeof props)
return extended.equal(obj, props)
try{
traverser(props, {leaf:leaf, branch: branch})
} catch (err){
err = fail(err).explain(
'has: ({actual:render}){path:path} must match {expected:render}){path:path}'
, { actual: obj
, expected: props
, path: pathTo
}
, message
)
Error.stackTraceLimit = orig
throw err
}
function leaf(p){
pathTo = p.path
var other = path(obj,p.path)
if('function' == typeof p.value){
p.value.call(p.value.parent,other)
}
else {
//since this is the leaf function, it cannot be an object.
elementary.equal(other,p.value)
}
}
function branch (p){
pathTo = p.path
var other = path(obj,p.path)
if('function' !== typeof p.value)
extended.complex(other)
p.each()
}
}
function atIndex (actual, relativeIndex, assertion, message) {
var index = relativeIndex < 0 ? actual.length + relativeIndex : relativeIndex
, minLength = Math.abs(relativeIndex)
;
function explain(err, template) {
throw fail(err).explain('atIndex: ' + template
, {actual: actual
, index: index
, relativeIndex: relativeIndex
, minLength: minLength
, assertion: assertion
}
, message)
}
if(!(actual))
explain(new Error(), '{actual:render} must not be null')
if(!(actual.length))
explain(new Error(), '{actual:render} must have length property')
if(!(actual.length > minLength))
explain(new Error(), '{actual:render}.length (== {actual.length}) must be greater than {minLength}')
if(!('function' == typeof assertion))
message = assertion, assertion == noop
try {
assertion(actual[index])
} catch (err) {
explain(err, '({actual:render})[{index}] must pass {assertion:function}')
}
}
/*
higher level assections that could be implemented:
* all(actual, assertions..., message) //all assertions must pass
* any(actual, assertions..., message) //at least one assertion must pass
//if index is negative, take index as length + index
refactor so that whereever it says 'assertion', if it's not a function : use equal.
*/
| fix indentations
| higher.js | fix indentations | <ide><path>igher.js
<ide> , message
<ide> )
<ide> }
<del> return current
<add> return current
<ide> }
<ide>
<ide> function apply (actual, assertion, message) { |
|
JavaScript | mit | 2778d36b78f2e06db30ca2a2e8c4f0afbac6feed | 0 | LBAB-Humboldt/biomodelos_db_api,LBAB-Humboldt/biomodelos_db_api | import mongoose from 'mongoose';
const Schema = mongoose.Schema;
const ModelSchema = new Schema(
{
_id: { type: Schema.ObjectId, required: true },
taxID: { type: Number, required: true },
acceptedNameUsage: { type: String, required: true },
consensusMethod: {
type: String,
in: ['all', 'mean', 'median'],
required: true
},
modelingMethod: {
type: String,
required: true,
in: [
'Maxent',
'Bioclim',
'Convex hull',
'Expert map',
'Hybrid (Maxent + Expert opinion)',
'Hybrid (Bioclim + Expert opinion)',
'Hybrid (Maxent + Bioclim)'
]
},
modelLevel: { type: Number, in: [0, 1, 2, 3, 4] },
modelStatus: {
type: String,
in: ['Developing', 'pendingValidation', 'Valid'],
required: true
},
published: { type: Boolean, default: false },
customCitation: { type: String, default: null },
isActive: { type: Boolean, default: true },
modelID: { type: String, default: null, required: true },
recsUsed: { type: Number },
perfStatType: { type: String },
perfStatValue: { type: Number },
validationType: { type: String },
thresholdType: { type: String, in: [0, 10, 20, 30, 'Continuous'] },
modelAuthors: { type: String },
dd: { type: Number, min: 1, max: 31 },
mm: { type: Number, min: 1, max: 12 },
yyyy: { type: Number, min: 1800, max: 2100 },
statCoverLC2: { type: Number },
statCoverLC3: { type: Number },
statCoverLC4: { type: Number },
statCoverLC5: { type: Number },
statCoverLC6: { type: Number },
statCoverLC7: { type: Number },
statCoverLC8: { type: Number },
statCoverLC9: { type: Number },
statCoverLC10: { type: Number },
statCoverLC11: { type: Number },
statCoverLC12: { type: Number },
statCoverLC13: { type: Number },
statCoverLC14: { type: Number },
statCoverLC15: { type: Number },
statCoverLC16: { type: Number },
statCoverLC17: { type: Number },
statCoverLC18: { type: Number },
statCoverLC19: { type: Number },
statCoverLC20: { type: Number },
statCoverLC21: { type: Number },
statCoverLC22: { type: Number },
statCoverLC23: { type: Number },
statCoverLC24: { type: Number },
statCoverLC25: { type: Number },
statCoverLC26: { type: Number },
statCoverLC27: { type: Number },
statCoverLC28: { type: Number },
statCoverLC29: { type: Number },
statCoverLC30: { type: Number },
statCoverLC31: { type: Number },
statCoverLC32: { type: Number },
statCoverLC33: { type: Number },
statCoverLC34: { type: Number },
statCoverLC35: { type: Number },
statCoverLC36: { type: Number },
statCoverLC37: { type: Number },
statCoverLC38: { type: Number },
statCoverLC39: { type: Number },
statCoverLC40: { type: Number },
statCoverLC41: { type: Number },
statCoverLC42: { type: Number },
statCoverLC43: { type: Number },
statCoverLC44: { type: Number },
statCoverLC45: { type: Number },
statCoverLC46: { type: Number },
statCoverLC47: { type: Number },
statCoverLC48: { type: Number },
statCoverLC49: { type: Number },
statCoverLC50: { type: Number },
statCoverLC51: { type: Number },
statCoverLC52: { type: Number },
statCoverLC53: { type: Number },
statCoverLC54: { type: Number },
statCoverLC55: { type: Number },
statForestLoss00: { type: Number },
statForestLoss05: { type: Number },
statForestLoss10: { type: Number },
statForestLoss12: { type: Number },
statForestLoss90: { type: Number },
statFutureForest30c: { type: Number },
statFutureForest30d: { type: Number },
statFutureForest30h: { type: Number },
statRangeSize: { type: Number },
statModelEOO: { type: Number },
statRecsEOO: { type: Number },
statRepPA: { type: Number },
statRepPA1: { type: Number },
statRepPA2: { type: Number },
statRepPA3: { type: Number },
thumb: { type: String },
zip: { type: String },
png: { type: String },
methodFile: { type: String },
license: {
type: String,
in: ['by', 'by-sa', 'by-nc', 'by-nc-sa', 'cc-zero']
},
statForestLoss13: { type: Number },
statForestLoss14: { type: Number },
statForestLoss16: { type: Number },
modelSeason: {
type: String,
default: 'resident',
in: [
'resident',
'breeding season',
'non-breeding season',
'passage',
'seasonal occurrence uncertain'
]
},
modelOrigin: {
type: String,
default: 'native',
in: [
'resident',
'breeding season',
'non-breeding season',
'passage',
'seasonal occurrence uncertain'
]
},
modelGeoExtent: {
type: String,
default: 'national',
in: ['national', 'regional']
},
modelEpoch: {
type: String,
default: 'present',
in: ['present', 'past', 'future']
},
gsLayer: { type: String }
},
{
collection: 'models',
versionKey: false
}
);
export default mongoose.model('Model', ModelSchema, 'models');
| src/models/model.model.js | import mongoose from 'mongoose';
const Schema = mongoose.Schema;
const ModelSchema = new Schema(
{
_id: { type: Schema.ObjectId, required: true },
taxID: { type: Number, required: true },
acceptedNameUsage: { type: String, required: true },
consensusMethod: {
type: String,
in: ['all', 'mean', 'median'],
required: true
},
modelingMethod: {
type: String,
required: true,
in: [
'Maxent',
'Bioclim',
'Convex hull',
'Expert map',
'Hybrid (Maxent + Expert opinion)',
'Hybrid (Bioclim + Expert opinion)',
'Hybrid (Maxent + Bioclim)'
]
},
modelLevel: { type: Number, in: [0, 1, 2, 3, 4] },
modelStatus: {
type: String,
in: ['Developing', 'pendingValidation', 'Valid'],
required: true
},
published: { type: Boolean, default: false },
customCitation: { type: String, default: null },
isActive: { type: Boolean, default: true },
modelID: { type: String, default: null },
recsUsed: { type: Number },
perfStatType: { type: String },
perfStatValue: { type: Number },
validationType: { type: String },
thresholdType: { type: String, in: [0, 10, 20, 30, 'Continuous'] },
modelAuthors: { type: String },
dd: { type: Number, min: 1, max: 31 },
mm: { type: Number, min: 1, max: 12 },
yyyy: { type: Number, min: 1800, max: 2100 },
statCoverLC2: { type: Number },
statCoverLC3: { type: Number },
statCoverLC4: { type: Number },
statCoverLC5: { type: Number },
statCoverLC6: { type: Number },
statCoverLC7: { type: Number },
statCoverLC8: { type: Number },
statCoverLC9: { type: Number },
statCoverLC10: { type: Number },
statCoverLC11: { type: Number },
statCoverLC12: { type: Number },
statCoverLC13: { type: Number },
statCoverLC14: { type: Number },
statCoverLC15: { type: Number },
statCoverLC16: { type: Number },
statCoverLC17: { type: Number },
statCoverLC18: { type: Number },
statCoverLC19: { type: Number },
statCoverLC20: { type: Number },
statCoverLC21: { type: Number },
statCoverLC22: { type: Number },
statCoverLC23: { type: Number },
statCoverLC24: { type: Number },
statCoverLC25: { type: Number },
statCoverLC26: { type: Number },
statCoverLC27: { type: Number },
statCoverLC28: { type: Number },
statCoverLC29: { type: Number },
statCoverLC30: { type: Number },
statCoverLC31: { type: Number },
statCoverLC32: { type: Number },
statCoverLC33: { type: Number },
statCoverLC34: { type: Number },
statCoverLC35: { type: Number },
statCoverLC36: { type: Number },
statCoverLC37: { type: Number },
statCoverLC38: { type: Number },
statCoverLC39: { type: Number },
statCoverLC40: { type: Number },
statCoverLC41: { type: Number },
statCoverLC42: { type: Number },
statCoverLC43: { type: Number },
statCoverLC44: { type: Number },
statCoverLC45: { type: Number },
statCoverLC46: { type: Number },
statCoverLC47: { type: Number },
statCoverLC48: { type: Number },
statCoverLC49: { type: Number },
statCoverLC50: { type: Number },
statCoverLC51: { type: Number },
statCoverLC52: { type: Number },
statCoverLC53: { type: Number },
statCoverLC54: { type: Number },
statCoverLC55: { type: Number },
statForestLoss00: { type: Number },
statForestLoss05: { type: Number },
statForestLoss10: { type: Number },
statForestLoss12: { type: Number },
statForestLoss90: { type: Number },
statFutureForest30c: { type: Number },
statFutureForest30d: { type: Number },
statFutureForest30h: { type: Number },
statRangeSize: { type: Number },
statModelEOO: { type: Number },
statRecsEOO: { type: Number },
statRepPA: { type: Number },
statRepPA1: { type: Number },
statRepPA2: { type: Number },
statRepPA3: { type: Number },
thumb: { type: String },
zip: { type: String },
png: { type: String },
methodFile: { type: String },
license: {
type: String,
in: ['by', 'by-sa', 'by-nc', 'by-nc-sa', 'cc-zero']
},
statForestLoss13: { type: Number },
statForestLoss14: { type: Number },
statForestLoss16: { type: Number },
modelSeason: {
type: String,
default: 'resident',
in: [
'resident',
'breeding season',
'non-breeding season',
'passage',
'seasonal occurrence uncertain'
]
},
modelOrigin: {
type: String,
default: 'native',
in: [
'resident',
'breeding season',
'non-breeding season',
'passage',
'seasonal occurrence uncertain'
]
},
modelGeoExtent: {
type: String,
default: 'national',
in: ['national', 'regional']
},
modelEpoch: {
type: String,
default: 'present',
in: ['present', 'past', 'future']
},
gsLayer: { type: String }
},
{
collection: 'models',
versionKey: false
}
);
export default mongoose.model('Model', ModelSchema, 'models');
| make modelID filed required
| src/models/model.model.js | make modelID filed required | <ide><path>rc/models/model.model.js
<ide> published: { type: Boolean, default: false },
<ide> customCitation: { type: String, default: null },
<ide> isActive: { type: Boolean, default: true },
<del> modelID: { type: String, default: null },
<add> modelID: { type: String, default: null, required: true },
<ide> recsUsed: { type: Number },
<ide> perfStatType: { type: String },
<ide> perfStatValue: { type: Number }, |
|
Java | mit | c6fdb4db64e78d4c536e322cb5269f2632bf2bef | 0 | kotwgarnku/comets | package comets;
import javafx.geometry.Point3D;
public class Gravity {
public static final double GRAVITATIONAL_CONSTANT = 6.67384e-11;
public static final double MAX_GRAVITY_RANGE = 5e25;
public static Point3D calculateForce(SpaceObject someObject, SpaceObject otherObject) {
if(someObject.getPosition() == otherObject.getPosition())
return Point3D.ZERO;
Point3D accelerationVector = otherObject.getPosition().subtract(someObject.getPosition());
double distance = accelerationVector.magnitude();
if (distance > MAX_GRAVITY_RANGE)
return Point3D.ZERO;
return accelerationVector.multiply(otherObject.getMass() / Math.pow(distance, 3));
}
}
| src/main/java/comets/Gravity.java | package comets;
import javafx.geometry.Point3D;
public class Gravity implements Force {
public static final double GRAVITATIONAL_CONSTANT = 6.67384e-11;
public static final double MAX_GRAVITY_RANGE = 5e15;
@Override
public Point3D calculateAcceleration(Point3D thisObjectPos, Point3D otherObjectPos, double otherObjectsMass) {
if (thisObjectPos.equals(otherObjectPos))
return Point3D.ZERO;
Point3D accelerationVector = otherObjectPos.subtract(thisObjectPos);
double distance = accelerationVector.magnitude();
if (distance > MAX_GRAVITY_RANGE)
return Point3D.ZERO;
return accelerationVector.multiply(otherObjectsMass / Math.pow(distance, 3));
}
}
| Adjusted function.
| src/main/java/comets/Gravity.java | Adjusted function. | <ide><path>rc/main/java/comets/Gravity.java
<ide>
<ide> import javafx.geometry.Point3D;
<ide>
<del>public class Gravity implements Force {
<add>public class Gravity {
<ide>
<ide> public static final double GRAVITATIONAL_CONSTANT = 6.67384e-11;
<del> public static final double MAX_GRAVITY_RANGE = 5e15;
<add> public static final double MAX_GRAVITY_RANGE = 5e25;
<ide>
<del> @Override
<del> public Point3D calculateAcceleration(Point3D thisObjectPos, Point3D otherObjectPos, double otherObjectsMass) {
<del> if (thisObjectPos.equals(otherObjectPos))
<add> public static Point3D calculateForce(SpaceObject someObject, SpaceObject otherObject) {
<add> if(someObject.getPosition() == otherObject.getPosition())
<ide> return Point3D.ZERO;
<del> Point3D accelerationVector = otherObjectPos.subtract(thisObjectPos);
<add> Point3D accelerationVector = otherObject.getPosition().subtract(someObject.getPosition());
<ide> double distance = accelerationVector.magnitude();
<ide> if (distance > MAX_GRAVITY_RANGE)
<ide> return Point3D.ZERO;
<del> return accelerationVector.multiply(otherObjectsMass / Math.pow(distance, 3));
<add> return accelerationVector.multiply(otherObject.getMass() / Math.pow(distance, 3));
<ide> }
<ide> } |
|
Java | apache-2.0 | 026f93b410e2540fc1c6511bab38d3a7385143f4 | 0 | bboyfeiyu/RxJava,ypresto/RxJava,Siddartha07/RxJava,davidmoten/RxJava,ashwary/RxJava,msdgwzhy6/RxJava,Eagles2F/RxJava,ibaca/RxJava,androidgilbert/RxJava,xfumihiro/RxJava,pitatensai/RxJava,benjchristensen/RxJava,sunfei/RxJava,AttwellBrian/RxJava,Siddartha07/RxJava,suclike/RxJava,ronenhamias/RxJava,picnic106/RxJava,nurkiewicz/RxJava,YlJava110/RxJava,zhongdj/RxJava,stevegury/RxJava,A-w-K/RxJava,sanxieryu/RxJava,devagul93/RxJava,yuhuayi/RxJava,zjrstar/RxJava,rabbitcount/RxJava,tombujok/RxJava,lijunhuayc/RxJava,Shedings/RxJava,maugomez77/RxJava,stevegury/RxJava,klemzy/RxJava,jbripley/RxJava,Ryan800/RxJava,vqvu/RxJava,sposam/RxJava,picnic106/RxJava,eduardotrandafilov/RxJava,marcogarcia23/RxJava,randall-mo/RxJava,cloudbearings/RxJava,jacek-rzrz/RxJava,msdgwzhy6/RxJava,ibaca/RxJava,nvoron23/RxJava,ronenhamias/RxJava,klemzy/RxJava,xfumihiro/RxJava,wrightm/RxJava,A-w-K/RxJava,hyleung/RxJava,elijah513/RxJava,takecy/RxJava,frodoking/RxJava,duqiao/RxJava,elijah513/RxJava,eduardotrandafilov/RxJava,androidgilbert/RxJava,tombujok/RxJava,Ribeiro/RxJava,dromato/RxJava,markrietveld/RxJava,sposam/RxJava,frodoking/RxJava,runt18/RxJava,HuangWenhuan0/RxJava,KevinTCoughlin/RxJava,weikipeng/RxJava,lijunhuayc/RxJava,sunfei/RxJava,ashwary/RxJava,zjrstar/RxJava,sitexa/RxJava,sunfei/RxJava,jtulach/RxJava,artem-zinnatullin/RxJava,ppiech/RxJava,gjesse/RxJava,hzysoft/RxJava,akarnokd/RxJava,tilal6991/RxJava,zsxwing/RxJava,Godchin1990/RxJava,Godchin1990/RxJava,forsail/RxJava,TracyLu/RxJava,java02014/RxJava,wlrhnh-David/RxJava,b-cuts/RxJava,ReactiveX/RxJava,Ryan800/RxJava,cgpllx/RxJava,tilal6991/RxJava,davidmoten/RxJava,ruhkopf/RxJava,onepavel/RxJava,Siddartha07/RxJava,Shedings/RxJava,marcogarcia23/RxJava,nurkiewicz/RxJava,androidgilbert/RxJava,devagul93/RxJava,java02014/RxJava,A-w-K/RxJava,nkhuyu/RxJava,nkhuyu/RxJava,weikipeng/RxJava,tombujok/RxJava,wehjin/RxJava,jbripley/RxJava,Eagles2F/RxJava,AmberWhiteSky/RxJava,b-cuts/RxJava,fjg1989/RxJava,duqiao/RxJava,jacek-rzrz/RxJava,hzysoft/RxJava,spoon-bot/RxJava,fjg1989/RxJava,tilal6991/RxJava,shekarrex/RxJava,shekarrex/RxJava,fjg1989/RxJava,lncosie/RxJava,vqvu/RxJava,simonbasle/RxJava,akarnokd/RxJava,hzysoft/RxJava,ruhkopf/RxJava,cloudbearings/RxJava,wrightm/RxJava,sitexa/RxJava,YlJava110/RxJava,weikipeng/RxJava,Ribeiro/RxJava,androidyue/RxJava,Turbo87/RxJava,forsail/RxJava,forsail/RxJava,ronenhamias/RxJava,nvoron23/RxJava,aditya-chaturvedi/RxJava,ashwary/RxJava,nvoron23/RxJava,aditya-chaturvedi/RxJava,ChenWenHuan/RxJava,Godchin1990/RxJava,kuanghao/RxJava,yuhuayi/RxJava,maugomez77/RxJava,hyleung/RxJava,ypresto/RxJava,AttwellBrian/RxJava,java02014/RxJava,sposam/RxJava,shekarrex/RxJava,sanxieryu/RxJava,ChenWenHuan/RxJava,bboyfeiyu/RxJava,nurkiewicz/RxJava,devagul93/RxJava,elijah513/RxJava,TracyLu/RxJava,runt18/RxJava,southwolf/RxJava,zsxwing/RxJava,onepavel/RxJava,sitexa/RxJava,lncosie/RxJava,xfumihiro/RxJava,KevinTCoughlin/RxJava,eduardotrandafilov/RxJava,vqvu/RxJava,ReactiveX/RxJava,TracyLu/RxJava,onepavel/RxJava,Bobjoy/RxJava,zjrstar/RxJava,randall-mo/RxJava,runt18/RxJava,suclike/RxJava,marcogarcia23/RxJava,ibaca/RxJava,gjesse/RxJava,reactivex/rxjava,gjesse/RxJava,Ribeiro/RxJava,wlrhnh-David/RxJava,Turbo87/RxJava,ypresto/RxJava,NiteshKant/RxJava,ayushnvijay/RxJava,wlrhnh-David/RxJava,Bobjoy/RxJava,pitatensai/RxJava,Eagles2F/RxJava,markrietveld/RxJava,randall-mo/RxJava,srayhunter/RxJava,jbripley/RxJava,reactivex/rxjava,msdgwzhy6/RxJava,YlJava110/RxJava,hyarlagadda/RxJava,Turbo87/RxJava,srayhunter/RxJava,ruhkopf/RxJava,klemzy/RxJava,davidmoten/RxJava,nkhuyu/RxJava,ayushnvijay/RxJava,dromato/RxJava,kuanghao/RxJava,ChenWenHuan/RxJava,wehjin/RxJava,Shedings/RxJava,ppiech/RxJava,hyleung/RxJava,cloudbearings/RxJava,HuangWenhuan0/RxJava,picnic106/RxJava,zhongdj/RxJava,wrightm/RxJava,dromato/RxJava,stevegury/RxJava,southwolf/RxJava,NiteshKant/RxJava,rabbitcount/RxJava,suclike/RxJava,zsxwing/RxJava,ayushnvijay/RxJava,simonbasle/RxJava,takecy/RxJava,Ryan800/RxJava,spoon-bot/RxJava,jacek-rzrz/RxJava,pitatensai/RxJava,androidyue/RxJava,cgpllx/RxJava,androidyue/RxJava,AmberWhiteSky/RxJava,wehjin/RxJava,srayhunter/RxJava,aditya-chaturvedi/RxJava,maugomez77/RxJava,Bobjoy/RxJava,kuanghao/RxJava,frodoking/RxJava,hyarlagadda/RxJava,simonbasle/RxJava,KevinTCoughlin/RxJava,sanxieryu/RxJava,zhongdj/RxJava,takecy/RxJava,b-cuts/RxJava,lijunhuayc/RxJava,AmberWhiteSky/RxJava,hyarlagadda/RxJava,artem-zinnatullin/RxJava,yuhuayi/RxJava,jtulach/RxJava,HuangWenhuan0/RxJava,lncosie/RxJava,duqiao/RxJava,markrietveld/RxJava,southwolf/RxJava,cgpllx/RxJava,ppiech/RxJava,rabbitcount/RxJava | /**
* Copyright 2014 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package rx.internal.operators;
import java.util.concurrent.atomic.AtomicIntegerFieldUpdater;
import java.util.concurrent.atomic.AtomicLongFieldUpdater;
import rx.Observable.Operator;
import rx.Producer;
import rx.Scheduler;
import rx.Subscriber;
import rx.Subscription;
import rx.exceptions.MissingBackpressureException;
import rx.functions.Action0;
import rx.internal.util.RxRingBuffer;
import rx.internal.util.SynchronizedSubscription;
import rx.schedulers.ImmediateScheduler;
import rx.schedulers.TrampolineScheduler;
/**
* Delivers events on the specified {@code Scheduler} asynchronously via an unbounded buffer.
*
* <img width="640" src="https://github.com/ReactiveX/RxJava/wiki/images/rx-operators/observeOn.png" alt="">
*
* @param <T>
* the transmitted value type
*/
public final class OperatorObserveOn<T> implements Operator<T, T> {
private final Scheduler scheduler;
/**
* @param scheduler
*/
public OperatorObserveOn(Scheduler scheduler) {
this.scheduler = scheduler;
}
@Override
public Subscriber<? super T> call(Subscriber<? super T> child) {
if (scheduler instanceof ImmediateScheduler) {
// avoid overhead, execute directly
return child;
} else if (scheduler instanceof TrampolineScheduler) {
// avoid overhead, execute directly
return child;
} else {
return new ObserveOnSubscriber<T>(scheduler, child);
}
}
/** Observe through individual queue per observer. */
private static final class ObserveOnSubscriber<T> extends Subscriber<T> {
final Subscriber<? super T> child;
private final Scheduler.Worker recursiveScheduler;
private final ScheduledUnsubscribe scheduledUnsubscribe;
final NotificationLite<T> on = NotificationLite.instance();
private final RxRingBuffer queue = RxRingBuffer.getSpscInstance();
private boolean completed = false;
private boolean failure = false;
private volatile long requested = 0;
@SuppressWarnings("rawtypes")
static final AtomicLongFieldUpdater<ObserveOnSubscriber> REQUESTED = AtomicLongFieldUpdater.newUpdater(ObserveOnSubscriber.class, "requested");
volatile long counter;
@SuppressWarnings("rawtypes")
static final AtomicLongFieldUpdater<ObserveOnSubscriber> COUNTER_UPDATER = AtomicLongFieldUpdater.newUpdater(ObserveOnSubscriber.class, "counter");
// do NOT pass the Subscriber through to couple the subscription chain ... unsubscribing on the parent should
// not prevent anything downstream from consuming, which will happen if the Subscription is chained
public ObserveOnSubscriber(Scheduler scheduler, Subscriber<? super T> child) {
this.child = child;
this.recursiveScheduler = scheduler.createWorker();
this.scheduledUnsubscribe = new ScheduledUnsubscribe(recursiveScheduler, queue);
child.add(scheduledUnsubscribe);
child.setProducer(new Producer() {
@Override
public void request(long n) {
REQUESTED.getAndAdd(ObserveOnSubscriber.this, n);
schedule();
}
});
add(scheduledUnsubscribe);
child.add(recursiveScheduler);
child.add(this);
}
@Override
public void onStart() {
// signal that this is an async operator capable of receiving this many
request(RxRingBuffer.SIZE);
}
@Override
public void onNext(final T t) {
if (isUnsubscribed() || completed) {
return;
}
try {
queue.onNext(t);
} catch (MissingBackpressureException e) {
onError(e);
return;
}
schedule();
}
@Override
public void onCompleted() {
if (isUnsubscribed() || completed) {
return;
}
completed = true;
queue.onCompleted();
schedule();
}
@Override
public void onError(final Throwable e) {
if (isUnsubscribed() || completed) {
return;
}
// unsubscribe eagerly since time will pass before the scheduled onError results in an unsubscribe event
unsubscribe();
completed = true;
// mark failure so the polling thread will skip onNext still in the queue
failure = true;
queue.onError(e);
schedule();
}
protected void schedule() {
if (COUNTER_UPDATER.getAndIncrement(this) == 0) {
recursiveScheduler.schedule(new Action0() {
@Override
public void call() {
pollQueue();
}
});
}
}
private void pollQueue() {
int emitted = 0;
while (true) {
while (!scheduledUnsubscribe.isUnsubscribed()) {
if (REQUESTED.getAndDecrement(this) != 0) {
Object o = queue.poll();
if (o == null) {
// nothing in queue
REQUESTED.incrementAndGet(this);
break;
} else {
if (failure) {
// completed so we will skip onNext if they exist and only emit terminal events
if (on.isError(o)) {
System.out.println("Error: " + o);
// only emit error
on.accept(child, o);
}
} else {
if (!on.accept(child, o)) {
// non-terminal event so let's increment count
emitted++;
}
}
}
} else {
// we hit the end ... so increment back to 0 again
REQUESTED.incrementAndGet(this);
break;
}
}
long c = COUNTER_UPDATER.decrementAndGet(this);
if (c <= 0) {
// request the number of items that we emitted in this poll loop
if (emitted > 0) {
request(emitted);
}
break;
} else {
/*
* Set down to 1 and then iterate again.
* we lower it to 1 otherwise it could have grown very large while in the last poll loop
* and then we can end up looping all those times again here before existing even once we've drained
*/
COUNTER_UPDATER.set(this, 1);
// we now loop again, and if anything tries scheduling again after this it will increment and cause us to loop again after
}
}
}
}
static final class ScheduledUnsubscribe implements Subscription {
final Scheduler.Worker worker;
volatile int once;
static final AtomicIntegerFieldUpdater<ScheduledUnsubscribe> ONCE_UPDATER = AtomicIntegerFieldUpdater.newUpdater(ScheduledUnsubscribe.class, "once");
final RxRingBuffer queue;
volatile boolean unsubscribed = false;
public ScheduledUnsubscribe(Scheduler.Worker worker, RxRingBuffer queue) {
this.worker = worker;
this.queue = queue;
}
@Override
public boolean isUnsubscribed() {
return unsubscribed;
}
@Override
public void unsubscribe() {
if (ONCE_UPDATER.getAndSet(this, 1) == 0) {
worker.schedule(new Action0() {
@Override
public void call() {
worker.unsubscribe();
unsubscribed = true;
}
});
}
}
}
}
| src/main/java/rx/internal/operators/OperatorObserveOn.java | /**
* Copyright 2014 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package rx.internal.operators;
import java.util.concurrent.atomic.AtomicIntegerFieldUpdater;
import java.util.concurrent.atomic.AtomicLongFieldUpdater;
import rx.Observable.Operator;
import rx.Producer;
import rx.Scheduler;
import rx.Subscriber;
import rx.Subscription;
import rx.exceptions.MissingBackpressureException;
import rx.functions.Action0;
import rx.internal.util.RxRingBuffer;
import rx.internal.util.SynchronizedSubscription;
import rx.schedulers.ImmediateScheduler;
import rx.schedulers.TrampolineScheduler;
/**
* Delivers events on the specified {@code Scheduler} asynchronously via an unbounded buffer.
*
* <img width="640" src="https://github.com/ReactiveX/RxJava/wiki/images/rx-operators/observeOn.png" alt="">
*
* @param <T>
* the transmitted value type
*/
public final class OperatorObserveOn<T> implements Operator<T, T> {
private final Scheduler scheduler;
/**
* @param scheduler
*/
public OperatorObserveOn(Scheduler scheduler) {
this.scheduler = scheduler;
}
@Override
public Subscriber<? super T> call(Subscriber<? super T> child) {
if (scheduler instanceof ImmediateScheduler) {
// avoid overhead, execute directly
return child;
} else if (scheduler instanceof TrampolineScheduler) {
// avoid overhead, execute directly
return child;
} else {
return new ObserveOnSubscriber<T>(scheduler, child);
}
}
/** Observe through individual queue per observer. */
private static final class ObserveOnSubscriber<T> extends Subscriber<T> {
final Subscriber<? super T> child;
private final Scheduler.Worker recursiveScheduler;
private final ScheduledUnsubscribe scheduledUnsubscribe;
final NotificationLite<T> on = NotificationLite.instance();
private final RxRingBuffer queue = RxRingBuffer.getSpscInstance();
private boolean completed = false;
private volatile long requested = 0;
@SuppressWarnings("rawtypes")
static final AtomicLongFieldUpdater<ObserveOnSubscriber> REQUESTED = AtomicLongFieldUpdater.newUpdater(ObserveOnSubscriber.class, "requested");
volatile long counter;
@SuppressWarnings("rawtypes")
static final AtomicLongFieldUpdater<ObserveOnSubscriber> COUNTER_UPDATER = AtomicLongFieldUpdater.newUpdater(ObserveOnSubscriber.class, "counter");
// do NOT pass the Subscriber through to couple the subscription chain ... unsubscribing on the parent should
// not prevent anything downstream from consuming, which will happen if the Subscription is chained
public ObserveOnSubscriber(Scheduler scheduler, Subscriber<? super T> child) {
this.child = child;
this.recursiveScheduler = scheduler.createWorker();
this.scheduledUnsubscribe = new ScheduledUnsubscribe(recursiveScheduler, queue);
child.add(scheduledUnsubscribe);
child.setProducer(new Producer() {
@Override
public void request(long n) {
REQUESTED.getAndAdd(ObserveOnSubscriber.this, n);
schedule();
}
});
add(scheduledUnsubscribe);
child.add(recursiveScheduler);
child.add(this);
}
@Override
public void onStart() {
// signal that this is an async operator capable of receiving this many
request(RxRingBuffer.SIZE);
}
@Override
public void onNext(final T t) {
if (isUnsubscribed() || completed) {
return;
}
try {
queue.onNext(t);
} catch (MissingBackpressureException e) {
onError(e);
return;
}
schedule();
}
@Override
public void onCompleted() {
if (isUnsubscribed() || completed) {
return;
}
completed = true;
queue.onCompleted();
schedule();
}
@Override
public void onError(final Throwable e) {
if (isUnsubscribed() || completed) {
return;
}
completed = true;
queue.onError(e);
schedule();
}
protected void schedule() {
if (COUNTER_UPDATER.getAndIncrement(this) == 0) {
recursiveScheduler.schedule(new Action0() {
@Override
public void call() {
pollQueue();
}
});
}
}
private void pollQueue() {
int emitted = 0;
while (true) {
while (!scheduledUnsubscribe.isUnsubscribed()) {
if (REQUESTED.getAndDecrement(this) != 0) {
Object o = queue.poll();
if (o == null) {
// nothing in queue
REQUESTED.incrementAndGet(this);
break;
} else {
if (!on.accept(child, o)) {
// non-terminal event so let's increment count
emitted++;
}
}
} else {
// we hit the end ... so increment back to 0 again
REQUESTED.incrementAndGet(this);
break;
}
}
long c = COUNTER_UPDATER.decrementAndGet(this);
if (c <= 0) {
// request the number of items that we emitted in this poll loop
if (emitted > 0) {
request(emitted);
}
break;
} else {
/*
* Set down to 1 and then iterate again.
* we lower it to 1 otherwise it could have grown very large while in the last poll loop
* and then we can end up looping all those times again here before existing even once we've drained
*/
COUNTER_UPDATER.set(this, 1);
// we now loop again, and if anything tries scheduling again after this it will increment and cause us to loop again after
}
}
}
}
static final class ScheduledUnsubscribe implements Subscription {
final Scheduler.Worker worker;
volatile int once;
static final AtomicIntegerFieldUpdater<ScheduledUnsubscribe> ONCE_UPDATER = AtomicIntegerFieldUpdater.newUpdater(ScheduledUnsubscribe.class, "once");
final RxRingBuffer queue;
volatile boolean unsubscribed = false;
public ScheduledUnsubscribe(Scheduler.Worker worker, RxRingBuffer queue) {
this.worker = worker;
this.queue = queue;
}
@Override
public boolean isUnsubscribed() {
return unsubscribed;
}
@Override
public void unsubscribe() {
if (ONCE_UPDATER.getAndSet(this, 1) == 0) {
worker.schedule(new Action0() {
@Override
public void call() {
worker.unsubscribe();
unsubscribed = true;
}
});
}
}
}
}
| Unsubscribe eagerly and drop queued onNext to emit onError
The queue will be drained to find and emit the onError.
| src/main/java/rx/internal/operators/OperatorObserveOn.java | Unsubscribe eagerly and drop queued onNext to emit onError | <ide><path>rc/main/java/rx/internal/operators/OperatorObserveOn.java
<ide>
<ide> private final RxRingBuffer queue = RxRingBuffer.getSpscInstance();
<ide> private boolean completed = false;
<add> private boolean failure = false;
<ide>
<ide> private volatile long requested = 0;
<ide> @SuppressWarnings("rawtypes")
<ide> if (isUnsubscribed() || completed) {
<ide> return;
<ide> }
<add> // unsubscribe eagerly since time will pass before the scheduled onError results in an unsubscribe event
<add> unsubscribe();
<ide> completed = true;
<add> // mark failure so the polling thread will skip onNext still in the queue
<add> failure = true;
<ide> queue.onError(e);
<ide> schedule();
<ide> }
<ide> REQUESTED.incrementAndGet(this);
<ide> break;
<ide> } else {
<del> if (!on.accept(child, o)) {
<del> // non-terminal event so let's increment count
<del> emitted++;
<add> if (failure) {
<add> // completed so we will skip onNext if they exist and only emit terminal events
<add> if (on.isError(o)) {
<add> System.out.println("Error: " + o);
<add> // only emit error
<add> on.accept(child, o);
<add> }
<add> } else {
<add> if (!on.accept(child, o)) {
<add> // non-terminal event so let's increment count
<add> emitted++;
<add> }
<ide> }
<ide> }
<ide> } else { |
|
Java | apache-2.0 | 9d9b3434ead600ce6146d8e72559f90b88f17805 | 0 | sdeleuze/reactor-core,sdeleuze/reactor-core,reactor/reactor-core,sdeleuze/reactor-core,sdeleuze/reactor-core | /*
* Copyright (c) 2011-2016 Pivotal Software Inc, All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package reactor.core.publisher;
import java.time.Duration;
import java.util.Optional;
import java.util.concurrent.Callable;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Future;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicLong;
import java.util.function.BiConsumer;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.LongConsumer;
import java.util.function.Predicate;
import java.util.function.Supplier;
import java.util.logging.Level;
import java.util.stream.LongStream;
import org.reactivestreams.Publisher;
import org.reactivestreams.Subscriber;
import org.reactivestreams.Subscription;
import reactor.core.flow.Fuseable;
import reactor.core.queue.QueueSupplier;
import reactor.core.scheduler.Scheduler;
import reactor.core.state.Backpressurable;
import reactor.core.state.Completable;
import reactor.core.state.Introspectable;
import reactor.core.subscriber.LambdaSubscriber;
import reactor.core.scheduler.Timer;
import reactor.core.tuple.Tuple;
import reactor.core.tuple.Tuple2;
import reactor.core.tuple.Tuple3;
import reactor.core.tuple.Tuple4;
import reactor.core.tuple.Tuple5;
import reactor.core.tuple.Tuple6;
import reactor.core.util.Assert;
import reactor.core.util.Logger;
import reactor.core.util.PlatformDependent;
import reactor.core.util.ReactiveStateUtils;
/**
* A Reactive Streams {@link Publisher} with basic rx operators that completes successfully by emitting an element, or
* with an error.
*
* <p>
* <img width="640" src="https://raw.githubusercontent.com/reactor/projectreactor.io/master/src/main/static/assets/img/marble/mono.png" alt="">
* <p>
*
* <p>The rx operators will offer aliases for input {@link Mono} type to preserve the "at most one"
* property of the resulting {@link Mono}. For instance {@link Mono#flatMap flatMap} returns a {@link Flux} with
* possibly
* more than 1 emission. Its alternative enforcing {@link Mono} input is {@link Mono#then then}.
*
* <p>{@code Mono<Void>} should be used for {@link Publisher} that just completes without any value.
*
* <p>It is intended to be used in implementations and return types, input parameters should keep using raw {@link
* Publisher} as much as possible.
*
* @param <T> the type of the single value of this class
*
* @author Sebastien Deleuze
* @author Stephane Maldini
* @see Flux
* @since 2.5
*/
public abstract class Mono<T> implements Publisher<T>, Backpressurable, Introspectable,
Completable {
static final Mono<?> NEVER = MonoSource.from(FluxNever.instance());
// ==============================================================================================================
// Static Generators
// ==============================================================================================================
/**
* Pick the first result coming from any of the given monos and populate a new {@literal Mono}.
*
* <p>
* <img class="marble" src="https://raw.githubusercontent.com/reactor/projectreactor.io/master/src/main/static/assets/img/marble/any.png" alt="">
* <p>
* @param monos The deferred monos to use.
* @param <T> The type of the function result.
*
* @return a {@link Mono}.
*/
@SafeVarargs
@SuppressWarnings("varargs")
public static <T> Mono<T> any(Mono<? extends T>... monos) {
return MonoSource.wrap(new FluxAmb<>(monos));
}
/**
* Pick the first result coming from any of the given monos and populate a new {@literal Mono}.
*
* <p>
* <img class="marble" src="https://raw.githubusercontent.com/reactor/projectreactor.io/master/src/main/static/assets/img/marble/any.png" alt="">
* <p>
* @param monos The monos to use.
* @param <T> The type of the function result.
*
* @return a {@link Mono}.
*/
public static <T> Mono<T> any(Iterable<? extends Mono<? extends T>> monos) {
return MonoSource.wrap(new FluxAmb<>(monos));
}
/**
* Create a {@link Mono} provider that will {@link Supplier#get supply} a target {@link Mono} to subscribe to for
* each {@link Subscriber} downstream.
*
* <p>
* <img class="marble" src="https://raw.githubusercontent.com/reactor/projectreactor.io/master/src/main/static/assets/img/marble/defer1.png" alt="">
* <p>
* @param supplier a {@link Mono} factory
*
* @param <T> the element type of the returned Mono instance
*
* @return a new {@link Mono} factory
*/
public static <T> Mono<T> defer(Supplier<? extends Mono<? extends T>> supplier) {
return new MonoDefer<>(supplier);
}
/**
* Create a Mono which delays an onNext signal of {@code duration} milliseconds and complete.
* If the demand cannot be produced in time, an onError will be signalled instead.
*
* <p>
* <img class="marble" src="https://raw.githubusercontent.com/reactor/projectreactor.io/master/src/main/static/assets/img/marble/delay.png" alt="">
* <p>
* @param duration the duration in milliseconds of the delay
*
* @return a new {@link Mono}
*/
public static Mono<Long> delay(long duration) {
return delay(duration, Timer.global());
}
/**
* Create a Mono which delays an onNext signal of {@code duration} of given unit and complete on the global timer.
* If the demand cannot be produced in time, an onError will be signalled instead.
*
* <p>
* <img class="marble" src="https://raw.githubusercontent.com/reactor/projectreactor.io/master/src/main/static/assets/img/marble/delay.png" alt="">
* <p>
* @param duration the duration of the delay
*
* @return a new {@link Mono}
*/
public static Mono<Long> delay(Duration duration) {
return delay(duration.toMillis());
}
/**
* Create a Mono which delays an onNext signal of {@code duration} milliseconds and complete.
* If the demand cannot be produced in time, an onError will be signalled instead.
*
* <p>
* <img class="marble" src="https://raw.githubusercontent.com/reactor/projectreactor.io/master/src/main/static/assets/img/marble/delay.png" alt="">
* <p>
* @param duration the duration in milliseconds of the delay
* @param timer the timer
*
* @return a new {@link Mono}
*/
public static Mono<Long> delay(long duration, Timer timer) {
Assert.isTrue(duration >= timer.period(), "The delay " + duration + " cannot be less than the timer resolution " +
"" + timer.period());
return new MonoDelay(timer, duration);
}
/**
* Create a Mono which delays an onNext signal of {@code duration} and complete.
* If the demand cannot be produced in time, an onError will be signalled instead.
*
* <p>
* <img class="marble" src="https://raw.githubusercontent.com/reactor/projectreactor.io/master/src/main/static/assets/img/marble/delay.png" alt="">
* <p>
* @param duration the duration of the delay
* @param timer the timer
*
* @return a new {@link Mono}
*/
public static Mono<Long> delay(Duration duration, Timer timer) {
return delay(duration.toMillis(), timer);
}
/**
* Create a {@link Mono} that completes without emitting any item.
*
* <p>
* <img class="marble" src="https://raw.githubusercontent.com/reactor/projectreactor.io/master/src/main/static/assets/img/marble/empty.png" alt="">
* <p>
* @param <T> the reified {@link Subscriber} type
*
* @return a completed {@link Mono}
*/
@SuppressWarnings("unchecked")
public static <T> Mono<T> empty() {
return (Mono<T>) MonoEmpty.instance();
}
/**
* Create a new {@link Mono} that ignores onNext (dropping them) and only react on Completion signal.
*
* <p>
* <img class="marble" src="https://raw.githubusercontent.com/reactor/projectreactor.io/master/src/main/static/assets/img/marble/after.png" alt="">
* <p>
* @param source the {@link Publisher to ignore}
* @param <T> the reified {@link Publisher} type
*
* @return a new completable {@link Mono}.
*/
@SuppressWarnings("unchecked")
public static <T> Mono<Void> empty(Publisher<T> source) {
return (Mono<Void>)new MonoIgnoreElements<>(source);
}
/**
* Create a {@link Mono} that completes with the specified error immediately after onSubscribe.
*
* <p>
* <img class="marble" src="https://raw.githubusercontent.com/reactor/projectreactor.io/master/src/main/static/assets/img/marble/error.png" alt="">
* <p>
* @param error the onError signal
* @param <T> the reified {@link Subscriber} type
*
* @return a failed {@link Mono}
*/
public static <T> Mono<T> error(Throwable error) {
return new MonoError<>(error);
}
/**
* Expose the specified {@link Publisher} with the {@link Mono} API, and ensure it will emit 0 or 1 item.
*
* <p>
* <img class="marble" src="https://raw.githubusercontent.com/reactor/projectreactor.io/master/src/main/static/assets/img/marble/from1.png" alt="">
* <p>
* @param source the {@link Publisher} source
* @param <T> the source type
*
* @return the next item emitted as a {@link Mono}
*/
@SuppressWarnings("unchecked")
public static <T> Mono<T> from(Publisher<? extends T> source) {
if (source == null) {
return empty();
}
if (source instanceof Mono) {
return (Mono<T>) source;
}
return new MonoNext<>(source);
}
/**
* Create a {@link Mono} producing the value for the {@link Mono} using the given supplier.
*
* <p>
* <img class="marble" src="https://raw.githubusercontent.com/reactor/projectreactor.io/master/src/main/static/assets/img/marble/fromcallable.png" alt="">
* <p>
* @param supplier {@link Supplier} that will produce the value
* @param <T> type of the expected value
*
* @return A {@link Mono}.
*/
public static <T> Mono<T> fromCallable(Callable<? extends T> supplier) {
return new MonoCallable<>(supplier);
}
/**
* Create a {@link Mono} producing the value for the {@link Mono} using the given {@link CompletableFuture}.
*
* <p>
* <img class="marble" src="https://raw.githubusercontent.com/reactor/projectreactor.io/master/src/main/static/assets/img/marble/fromcompletablefuture.png" alt="">
* <p>
* @param completableFuture {@link CompletableFuture} that will produce the value
* @param <T> type of the expected value
*
* @return A {@link Mono}.
*/
public static <T> Mono<T> fromCompletableFuture(CompletableFuture<? extends T> completableFuture) {
return new MonoCompletableFuture<>(completableFuture);
}
/**
* Build a {@link Mono} that will only emit the result of the future and then complete.
* The future will be polled for an unbounded amount of time on request().
*
* <p>
* <img class="marble" src="https://raw.githubusercontent.com/reactor/projectreactor.io/master/src/main/static/assets/img/marble/fromfuture.png" alt="">
*
* @param future the future to poll value from
* @param <T> the value type of the Future and the retuned Mono instance
* @return a new {@link Mono}
*/
public static <T> Mono<T> fromFuture(Future<? extends T> future) {
return new MonoFuture<T>(future);
}
/**
* Build a {@link Mono} that will only emit the result of the future and then complete.
* The future will be polled for a given amount of time on request() then onError if failed to return.
*
* <p>
* <img class="marble" src="https://raw.githubusercontent.com/reactor/projectreactor.io/master/src/main/static/assets/img/marble/fromfuture.png" alt="">
*
* @param <T> the value type of the Future and the retuned Mono instance
* @param future the future to poll value from
* @param timeout the timeout in milliseconds
* @return a new {@link Mono}
*/
public static <T> Mono<T> fromFuture(Future<? extends T> future, long timeout) {
return new MonoFuture<>(future, timeout);
}
/**
* Build a {@link Mono} that will only emit the result of the future and then complete.
* The future will be polled for a given amount of time on request() then onError if failed to return.
*
* <p>
* <img class="marble" src="https://raw.githubusercontent.com/reactor/projectreactor.io/master/src/main/static/assets/img/marble/fromfuture.png" alt="">
*
* @param future the future to poll value from
* @param duration the duration to wait for the result of the future before failing with onError
* @param <T> the value type of the Future and the retuned Mono instance
* @return a new {@link Mono}
*/
public static <T> Mono<T> fromFuture(Future<? extends T> future, Duration duration) {
return fromFuture(future, duration.toMillis());
}
/**
* Create a {@link Mono} only producing a completion signal after using the given
* runnable.
*
* <p>
* <img class="marble" src="https://raw.githubusercontent.com/reactor/projectreactor.io/master/src/main/static/assets/img/marble/fromrunnable.png" alt="">
* <p>
* @param runnable {@link Runnable} that will callback the completion signal
*
* @return A {@link Mono}.
*/
public static Mono<Void> fromRunnable(Runnable runnable) {
return MonoSource.wrap(new FluxPeek<>(MonoEmpty.instance(), null, null, null, runnable, null, null,
null));
}
/**
* Create a new {@link Mono} that ignores onNext (dropping them) and only react on Completion signal.
*
* <p>
* <img class="marble" src="https://raw.githubusercontent.com/reactor/projectreactor.io/master/src/main/static/assets/img/marble/ignoreelements.png" alt="">
* <p>
* @param source the {@link Publisher to ignore}
* @param <T> the source type of the ignored data
*
* @return a new completable {@link Mono}.
*/
public static <T> Mono<T> ignoreElements(Publisher<T> source) {
return new MonoIgnoreElements<>(source);
}
/**
* Create a new {@link Mono} that emits the specified item.
*
* <p>
* <img class="marble" src="https://raw.githubusercontent.com/reactor/projectreactor.io/master/src/main/static/assets/img/marble/just.png" alt="">
* <p>
* @param data the only item to onNext
* @param <T> the type of the produced item
*
* @return a {@link Mono}.
*/
public static <T> Mono<T> just(T data) {
return new MonoJust<>(data);
}
/**
* Create a new {@link Mono} that emits the specified item if {@link Optional#isPresent()} otherwise only emits
* onComplete.
*
* <p>
* <img class="marble" src="https://raw.githubusercontent.com/reactor/projectreactor.io/master/src/main/static/assets/img/marble/justorempty.png" alt="">
* <p>
* @param data the {@link Optional} item to onNext or onComplete if not present
* @param <T> the type of the produced item
*
* @return a {@link Mono}.
*/
public static <T> Mono<T> justOrEmpty(Optional<? extends T> data) {
return data != null && data.isPresent() ? just(data.get()) : empty();
}
/**
* Create a new {@link Mono} that emits the specified item if non null otherwise only emits
* onComplete.
*
* <p>
* <img class="marble" src="https://raw.githubusercontent.com/reactor/projectreactor.io/master/src/main/static/assets/img/marble/justorempty.png" alt="">
* <p>
* @param data the item to onNext or onComplete if null
* @param <T> the type of the produced item
*
* @return a {@link Mono}.
*/
public static <T> Mono<T> justOrEmpty(T data) {
return data != null ? just(data) : empty();
}
/**
* Return a {@link Mono} that will never signal any data, error or completion signal.
* <p>
* <img class="marble" src="https://raw.githubusercontent.com/reactor/projectreactor.io/master/src/main/static/assets/img/marble/never.png" alt="">
* <p>
* @param <T> the {@link Subscriber} type target
*
* @return a never completing {@link Mono}
*/
@SuppressWarnings("unchecked")
public static <T> Mono<T> never() {
return (Mono<T>)NEVER;
}
/**
* Merge given monos into a new a {@literal Mono} that will be fulfilled when all of the given {@literal Mono Monos}
* have been fulfilled.
*
* <p>
* <img class="marble" src="https://raw.githubusercontent.com/reactor/projectreactor.io/master/src/main/static/assets/img/marble/whent.png" alt="">
* <p>
* @param p1 The first upstream {@link Publisher} to subscribe to.
* @param p2 The second upstream {@link Publisher} to subscribe to.
* @param <T1> type of the value from source1
* @param <T2> type of the value from source2
*
* @return a {@link Mono}.
*/
public static <T1, T2> Mono<Tuple2<T1, T2>> when(Mono<? extends T1> p1, Mono<? extends T2> p2) {
return when(Tuple.fn2(), p1, p2);
}
/**
* Merge given monos into a new a {@literal Mono} that will be fulfilled when all of the given {@literal Mono Monos}
* have been fulfilled.
*
* <p>
* <img class="marble" src="https://raw.githubusercontent.com/reactor/projectreactor.io/master/src/main/static/assets/img/marble/whent.png" alt="">
* <p>
* @param p1 The first upstream {@link Publisher} to subscribe to.
* @param p2 The second upstream {@link Publisher} to subscribe to.
* @param p3 The third upstream {@link Publisher} to subscribe to.
* @param <T1> type of the value from source1
* @param <T2> type of the value from source2
* @param <T3> type of the value from source3
*
* @return a {@link Mono}.
*/
public static <T1, T2, T3> Mono<Tuple3<T1, T2, T3>> when(Mono<? extends T1> p1, Mono<? extends T2> p2, Mono<? extends T3> p3) {
return when(Tuple.fn3(), p1, p2, p3);
}
/**
* Merge given monos into a new a {@literal Mono} that will be fulfilled when all of the given {@literal Mono Monos}
* have been fulfilled.
*
* <p>
* <img class="marble" src="https://raw.githubusercontent.com/reactor/projectreactor.io/master/src/main/static/assets/img/marble/whent.png" alt="">
* <p>
* @param p1 The first upstream {@link Publisher} to subscribe to.
* @param p2 The second upstream {@link Publisher} to subscribe to.
* @param p3 The third upstream {@link Publisher} to subscribe to.
* @param p4 The fourth upstream {@link Publisher} to subscribe to.
* @param <T1> type of the value from source1
* @param <T2> type of the value from source2
* @param <T3> type of the value from source3
* @param <T4> type of the value from source4
*
* @return a {@link Mono}.
*/
public static <T1, T2, T3, T4> Mono<Tuple4<T1, T2, T3, T4>> when(Mono<? extends T1> p1,
Mono<? extends T2> p2,
Mono<? extends T3> p3,
Mono<? extends T4> p4) {
return when(Tuple.fn4(), p1, p2, p3, p4);
}
/**
* Merge given monos into a new a {@literal Mono} that will be fulfilled when all of the given {@literal Mono Monos}
* have been fulfilled.
*
* <p>
* <img class="marble" src="https://raw.githubusercontent.com/reactor/projectreactor.io/master/src/main/static/assets/img/marble/whent.png" alt="">
* <p>
* @param p1 The first upstream {@link Publisher} to subscribe to.
* @param p2 The second upstream {@link Publisher} to subscribe to.
* @param p3 The third upstream {@link Publisher} to subscribe to.
* @param p4 The fourth upstream {@link Publisher} to subscribe to.
* @param p5 The fifth upstream {@link Publisher} to subscribe to.
* @param <T1> type of the value from source1
* @param <T2> type of the value from source2
* @param <T3> type of the value from source3
* @param <T4> type of the value from source4
* @param <T5> type of the value from source5
*
* @return a {@link Mono}.
*/
public static <T1, T2, T3, T4, T5> Mono<Tuple5<T1, T2, T3, T4, T5>> when(Mono<? extends T1> p1,
Mono<? extends T2> p2,
Mono<? extends T3> p3,
Mono<? extends T4> p4,
Mono<? extends T5> p5) {
return when(Tuple.fn5(), p1, p2, p3, p4, p5);
}
/**
* Merge given monos into a new a {@literal Mono} that will be fulfilled when all of the given {@literal Mono Monos}
* have been fulfilled.
*
* <p>
* <img class="marble" src="https://raw.githubusercontent.com/reactor/projectreactor.io/master/src/main/static/assets/img/marble/whent.png" alt="">
* <p>
* @param p1 The first upstream {@link Publisher} to subscribe to.
* @param p2 The second upstream {@link Publisher} to subscribe to.
* @param p3 The third upstream {@link Publisher} to subscribe to.
* @param p4 The fourth upstream {@link Publisher} to subscribe to.
* @param p5 The fifth upstream {@link Publisher} to subscribe to.
* @param p6 The sixth upstream {@link Publisher} to subscribe to.
* @param <T1> type of the value from source1
* @param <T2> type of the value from source2
* @param <T3> type of the value from source3
* @param <T4> type of the value from source4
* @param <T5> type of the value from source5
* @param <T6> type of the value from source6
*
* @return a {@link Mono}.
*/
public static <T1, T2, T3, T4, T5, T6> Mono<Tuple6<T1, T2, T3, T4, T5, T6>> when(Mono<? extends T1> p1,
Mono<? extends T2> p2,
Mono<? extends T3> p3,
Mono<? extends T4> p4,
Mono<? extends T5> p5,
Mono<? extends T6> p6) {
return when(Tuple.fn6(), p1, p2, p3, p4, p5, p6);
}
/**
* Aggregate given monos into a new a {@literal Mono} that will be fulfilled when all of the given {@literal Mono
* Monos} have been fulfilled. If any Mono terminates without value, the returned sequence will be terminated immediately and pending results cancelled.
*
* <p>
* <img class="marble" src="https://raw.githubusercontent.com/reactor/projectreactor.io/master/src/main/static/assets/img/marble/whent.png" alt="">
* <p>
* @param monos The monos to use.
* @param <T> The type of the function result.
*
* @return a {@link Mono}.
*/
@SafeVarargs
@SuppressWarnings({"unchecked","varargs"})
private static <T> Mono<T[]> when(Mono<? extends T>... monos) {
return when(array -> (T[])array, monos);
}
/**
* Aggregate given monos into a new a {@literal Mono} that will be fulfilled when all of the given {@literal Mono
* Monos} have been fulfilled. If any Mono terminates without value, the returned sequence will be terminated immediately and pending results cancelled.
*
* <p>
* <img class="marble" src="https://raw.githubusercontent.com/reactor/projectreactor.io/master/src/main/static/assets/img/marble/when.png" alt="">
* <p>
* @param combinator the combinator {@link Function}
* @param monos The monos to use.
* @param <T> The super incoming type
* @param <V> The type of the function result.
*
* @return a {@link Mono}.
*/
@SafeVarargs
@SuppressWarnings({"varargs", "unchecked"})
private static <T, V> Mono<V> when(Function<? super Object[], ? extends V> combinator, Mono<? extends T>... monos) {
return MonoSource.wrap(new FluxZip<>(monos, combinator, QueueSupplier.one(), 1));
}
/**
* Aggregate given monos into a new a {@literal Mono} that will be fulfilled when all of the given {@literal Mono
* Monos} have been fulfilled. If any Mono terminates without value, the returned sequence will be terminated immediately and pending results cancelled.
*
* <p>
* <img class="marble" src="https://raw.githubusercontent.com/reactor/projectreactor.io/master/src/main/static/assets/img/marble/whent.png" alt="">
* <p>
*
* @param monos The monos to use.
* @param <T> The type of the function result.
*
* @return a {@link Mono}.
*/
@SuppressWarnings("unchecked")
public static <T> Mono<T[]> when(final Iterable<? extends Mono<? extends T>> monos) {
return when(array -> (T[])array, monos);
}
/**
* Aggregate given monos into a new a {@literal Mono} that will be fulfilled when all of the given {@literal Mono
* Monos} have been fulfilled. If any Mono terminates without value, the returned sequence will be terminated immediately and pending results cancelled.
*
* <p>
* <img class="marble" src="https://raw.githubusercontent.com/reactor/projectreactor.io/master/src/main/static/assets/img/marble/when.png" alt="">
* <p>
*
* @param combinator the combinator {@link Function}
* @param monos The monos to use.
* @param <T> The type of the function result.
* @param <V> The result type
*
* @return a {@link Mono}.
*/
@SuppressWarnings("unchecked")
public static <T, V> Mono<V> when(final Function<? super Object[], ? extends V> combinator, final Iterable<?
extends Mono<? extends T>> monos) {
return MonoSource.wrap(new FluxZip<>(monos, combinator, QueueSupplier.one(), 1));
}
// ==============================================================================================================
// Operators
// ==============================================================================================================
protected Mono() {
}
/**
* Transform this {@link Mono} into a target {@link Publisher}
*
* {@code mono.as(Flux::from).subscribe(Subscribers.unbounded()) }
*
* @param transformer the {@link Function} applying this {@link Mono}
* @param <P> the returned {@link Publisher} output
* @param <V> the element type of the returned Publisher
*
* @return the transformed {@link Mono}
*/
public final <V, P extends Publisher<V>> P as(Function<? super Mono<T>, P> transformer) {
return transformer.apply(this);
}
/**
* Combine the result from this mono and another into a {@link Tuple2}.
*
* <p>
* <img class="marble" src="https://raw.githubusercontent.com/reactor/projectreactor.io/master/src/main/static/assets/img/marble/and.png" alt="">
* <p>
* @param other the {@link Mono} to combine with
* @param <T2> the element type of the other Mono instance
*
* @return a new combined Mono
* @see #when
*/
public final <T2> Mono<Tuple2<T, T2>> and(Mono<? extends T2> other) {
return when(this, other);
}
/**
* Return a {@code Mono<Void>} which only listens for complete and error signals from this {@link Mono} completes.
*
* <p>
* <img class="marble" src="https://raw.githubusercontent.com/reactor/projectreactor.io/master/src/main/static/assets/img/marble/after1.png" alt="">
* <p>
* @return a {@link Mono} igoring its payload (actively dropping)
*/
public final Mono<Void> after() {
return empty(this);
}
/**
* Transform the terminal signal (error or completion) into {@code Mono<V>} that will emit at most one result in the
* returned {@link Mono}.
*
* <p>
* <img class="marble" src="https://raw.githubusercontent.com/reactor/projectreactor.io/master/src/main/static/assets/img/marble/afters1.png" alt="">
*
* @param other a {@link Mono} to emit from after termination
* @param <V> the element type of the supplied Mono
*
* @return a new {@link Mono} that emits from the supplied {@link Mono}
*/
public final <V> Mono<V> after(Mono<V> other) {
return after(() -> other);
}
/**
* Transform the terminal signal (error or completion) into {@code Mono<V>} that will emit at most one result in the
* returned {@link Mono}.
*
* <p>
* <img class="marble" src="https://raw.githubusercontent.com/reactor/projectreactor.io/master/src/main/static/assets/img/marble/afters1.png" alt="">
*
* @param sourceSupplier a {@link Supplier} of {@link Mono} to emit from after termination
* @param <V> the element type of the supplied Mono
*
* @return a new {@link Mono} that emits from the supplied {@link Mono}
*/
public final <V> Mono<V> after(final Supplier<? extends Mono<V>> sourceSupplier) {
return MonoSource.wrap(after().flatMap(null, null, sourceSupplier));
}
/**
* Transform the terminal signal (error or completion) into {@code Mono<V>} that will emit at most one result in the
* returned {@link Mono}.
*
* <p>
* <img class="marble" src="https://raw.githubusercontent.com/reactor/projectreactor.io/master/src/main/static/assets/img/marble/afters1.png" alt="">
*
* @param <V> the element type of the supplied Mono
* @param sourceSupplier a {@link Supplier} of {@link Mono} to emit from after termination
*
* @return a new {@link Mono} that emits from the supplied {@link Mono}
*/
public final <V> Mono<V> afterSuccessOrError(final Supplier<? extends Mono<V>> sourceSupplier) {
return MonoSource.wrap(after().flatMap(null,
throwable -> Flux.concat(sourceSupplier.get(), Mono .error(throwable)),
sourceSupplier));
}
/**
* Cast the current {@link Mono} produced type into a target produced type.
*
* <p>
* <img class="marble" src="https://raw.githubusercontent.com/reactor/projectreactor.io/master/src/main/static/assets/img/marble/cast1.png" alt="">
*
* @param <E> the {@link Mono} output type
* @param stream the target type to cast to
*
* @return a casted {@link Mono}
*/
@SuppressWarnings("unchecked")
public final <E> Mono<E> cast(Class<E> stream) {
return (Mono<E>) this;
}
/**
* Turn this {@link Mono} into a hot source and cache last emitted signals for further {@link Subscriber}.
* Completion and Error will also be replayed.
* <p>
* <img width="500" src="https://raw.githubusercontent.com/reactor/projectreactor.io/master/src/main/static/assets/img/marble/cache1.png"
* alt="">
*
* @return a replaying {@link Mono}
*/
public final Mono<T> cache() {
return new MonoProcessor<>(this);
}
/**
* Subscribe a {@link Consumer} to this {@link Mono} that will consume all the
* sequence.
* <p>
* For a passive version that observe and forward incoming data see {@link #doOnSuccess(Consumer)} and
* {@link #doOnError(java.util.function.Consumer)}.
*
* <p>
* <img class="marble" src="https://raw.githubusercontent.com/reactor/projectreactor.io/master/src/main/static/assets/img/marble/consume1.png" alt="">
*
* @param consumer the consumer to invoke on each value
*
* @return a new {@link Runnable} to dispose the {@link Subscription}
*/
public final Runnable consume(Consumer<? super T> consumer) {
return consume(consumer, null, null);
}
/**
* Subscribe {@link Consumer} to this {@link Mono} that will consume all the
* sequence.
* <p>
* For a passive version that observe and forward incoming data see {@link #doOnSuccess(Consumer)} and
* {@link #doOnError(java.util.function.Consumer)}.
*
* <p>
* <img class="marble" src="https://raw.githubusercontent.com/reactor/projectreactor.io/master/src/main/static/assets/img/marble/consumeerror1.png" alt="">
*
* @param consumer the consumer to invoke on each next signal
* @param errorConsumer the consumer to invoke on error signal
*
* @return a new {@link Runnable} to dispose the {@link Subscription}
*/
public final Runnable consume(Consumer<? super T> consumer, Consumer<? super Throwable> errorConsumer) {
return consume(consumer, errorConsumer, null);
}
/**
* Subscribe {@link Consumer} to this {@link Mono} that will consume all the
* sequence.
* <p>
* For a passive version that observe and forward incoming data see {@link #doOnSuccess(Consumer)} and
* {@link #doOnError(java.util.function.Consumer)}.
*
* <p>
* <img class="marble" src="https://raw.githubusercontent.com/reactor/projectreactor.io/master/src/main/static/assets/img/marble/consumecomplete1.png" alt="">
*
* @param consumer the consumer to invoke on each value
* @param errorConsumer the consumer to invoke on error signal
* @param completeConsumer the consumer to invoke on complete signal
*
* @return a new {@link Runnable} to dispose the {@link Subscription}
*/
public final Runnable consume(Consumer<? super T> consumer,
Consumer<? super Throwable> errorConsumer,
Runnable completeConsumer) {
return subscribeWith(new LambdaSubscriber<>(consumer, errorConsumer, completeConsumer));
}
/**
* Concatenate emissions of this {@link Mono} with the provided {@link Publisher} (no interleave).
* <p>
* <img class="marble" src="https://raw.githubusercontent.com/reactor/projectreactor.io/master/src/main/static/assets/img/marble/concat.png" alt="">
*
* @param other the {@link Publisher} sequence to concat after this {@link Flux}
*
* @return a concatenated {@link Flux}
*/
@SuppressWarnings("unchecked")
public final Flux<T> concatWith(Publisher<? extends T> other) {
return new FluxConcatArray<>(this, other);
}
/**
* Introspect this Mono graph
*
* @return {@literal ReactiveStateUtils.Graph} representation of a publisher graph
*/
public final ReactiveStateUtils.Graph debug() {
return ReactiveStateUtils.scan(this);
}
/**
* Provide a default unique value if this mono is completed without any data
*
* <p>
* <img class="marble" src="https://raw.githubusercontent.com/reactor/projectreactor.io/master/src/main/static/assets/img/marble/defaultifempty.png" alt="">
* <p>
* @param defaultV the alternate value if this sequence is empty
*
* @return a new {@link Mono}
*
* @see Flux#defaultIfEmpty(Object)
*/
public final Mono<T> defaultIfEmpty(T defaultV) {
return MonoSource.wrap(new FluxDefaultIfEmpty<T>(this, defaultV));
}
/**
* Delay the {@link Mono#subscribe(Subscriber) subscription} to this {@link Mono} source until the given
* period elapses.
*
* <p>
* <img class="marble" src="https://raw.githubusercontent.com/reactor/projectreactor.io/master/src/main/static/assets/img/marble/delaysubscription1.png" alt="">
*
* @param delay period in seconds before subscribing this {@link Mono}
*
* @return a delayed {@link Mono}
*
*/
public final Mono<T> delaySubscription(long delay) {
return delaySubscription(Duration.ofSeconds(delay));
}
/**
* Delay the {@link Mono#subscribe(Subscriber) subscription} to this {@link Mono} source until the given
* period elapses.
*
* <p>
* <img class="marble" src="https://raw.githubusercontent.com/reactor/projectreactor.io/master/src/main/static/assets/img/marble/delaysubscription1.png" alt="">
*
* @param delay duration before subscribing this {@link Mono}
*
* @return a delayed {@link Mono}
*
*/
public final Mono<T> delaySubscription(Duration delay) {
return delaySubscription(Mono.delay(delay));
}
/**
* Delay the subscription to this {@link Mono} until another {@link Publisher}
* signals a value or completes.
*
* <p>
* <img class="marble" src="https://raw.githubusercontent.com/reactor/projectreactor.io/master/src/main/static/assets/img/marble/delaysubscriptionp1.png" alt="">
*
* @param subscriptionDelay a
* {@link Publisher} to signal by next or complete this {@link Mono#subscribe(Subscriber)}
* @param <U> the other source type
*
* @return a delayed {@link Mono}
*
*/
public final <U> Mono<T> delaySubscription(Publisher<U> subscriptionDelay) {
return MonoSource.wrap(new FluxDelaySubscription<>(this, subscriptionDelay));
}
/**
* A "phantom-operator" working only if this
* {@link Mono} is a emits onNext, onError or onComplete {@link Signal}. The relative {@link Subscriber}
* callback will be invoked, error {@link Signal} will trigger onError and complete {@link Signal} will trigger
* onComplete.
*
* <p>
* <img class="marble" src="https://raw.githubusercontent.com/reactor/projectreactor.io/master/src/main/static/assets/img/marble/dematerialize1.png" alt="">
* @param <X> the dematerialized type
*
* @return a dematerialized {@link Mono}
*/
@SuppressWarnings("unchecked")
public final <X> Mono<X> dematerialize() {
Mono<Signal<X>> thiz = (Mono<Signal<X>>) this;
return MonoSource.wrap(new FluxDematerialize<>(thiz));
}
/**
* Run onNext, onComplete and onError on a supplied {@link Function} worker like {@link SchedulerGroup}.
*
* <p>
* <img class="marble" src="https://raw.githubusercontent.com/reactor/projectreactor.io/master/src/main/static/assets/img/marble/dispatchon1.png" alt="">
* <p> <p>
* Typically used for fast publisher, slow consumer(s) scenarios.
* It naturally combines with {@link SchedulerGroup#single} and {@link SchedulerGroup#async} which implement
* fast async event loops.
*
* {@code mono.dispatchOn(WorkQueueProcessor.create()).subscribe(Subscribers.unbounded()) }
*
* @param scheduler a checked {@link reactor.core.scheduler.Scheduler.Worker} factory
*
* @return an asynchronous {@link Mono}
*/
@SuppressWarnings("unchecked")
public final Mono<T> dispatchOn(Scheduler scheduler) {
if (this instanceof Fuseable.ScalarSupplier) {
T value = get();
return MonoSource.wrap(new FluxSubscribeOnValue<>(value, scheduler, true));
}
return MonoSource.wrap(new FluxDispatchOn(this, scheduler, false, 1, QueueSupplier.<T>one()));
}
/**
* Triggered after the {@link Mono} terminates, either by completing downstream successfully or with an error.
* The arguments will be null depending on success, success with data and error:
* <ul>
* <li>null, null : completed without data</li>
* <li>T, null : completed with data</li>
* <li>null, Throwable : failed with/without data</li>
* </ul>
*
* <p>
* <img class="marble" src="https://raw.githubusercontent.com/reactor/projectreactor.io/master/src/main/static/assets/img/marble/doafterterminate1.png" alt="">
* <p>
* @param afterTerminate the callback to call after {@link Subscriber#onNext}, {@link Subscriber#onComplete} without preceding {@link Subscriber#onNext} or {@link Subscriber#onError}
*
* @return a new {@link Mono}
*/
public final Mono<T> doAfterTerminate(BiConsumer<? super T, Throwable> afterTerminate) {
return new MonoSuccess<>(this, null, null, afterTerminate);
}
/**
* Triggered when the {@link Mono} is cancelled.
*
*
* <p>
* <img class="marble" src="https://raw.githubusercontent.com/reactor/projectreactor.io/master/src/main/static/assets/img/marble/dooncancel.png" alt="">
* <p>
* @param onCancel the callback to call on {@link Subscription#cancel()}
*
* @return a new {@link Mono}
*/
public final Mono<T> doOnCancel(Runnable onCancel) {
if (this instanceof Fuseable) {
return MonoSource.wrap(new FluxPeekFuseable<>(this, null, null, null, null, null, null, onCancel));
}
return MonoSource.wrap(new FluxPeek<>(this, null, null, null, null, null, null, onCancel));
}
/**
* Triggered when the {@link Mono} completes successfully.
*
* <ul>
* <li>null : completed without data</li>
* <li>T: completed with data</li>
* </ul>
*
* <p>
* <img class="marble" src="https://raw.githubusercontent.com/reactor/projectreactor.io/master/src/main/static/assets/img/marble/doonsuccess.png" alt="">
* <p>
* @param onSuccess the callback to call on
* {@link Subscriber#onNext} or {@link Subscriber#onComplete} without preceding {@link Subscriber#onNext}
*
* @return a new {@link Mono}
*/
public final Mono<T> doOnSuccess(Consumer<? super T> onSuccess) {
return new MonoSuccess<>(this, onSuccess, null, null);
}
/**
* Triggered when the {@link Mono} completes with an error.
*
* <p>
* <img class="marble" src="https://raw.githubusercontent.com/reactor/projectreactor.io/master/src/main/static/assets/img/marble/doonerror1.png" alt="">
* <p>
* @param onError the error callback to call on {@link Subscriber#onError(Throwable)}
*
* @return a new {@link Mono}
*/
public final Mono<T> doOnError(Consumer<? super Throwable> onError) {
if (this instanceof Fuseable) {
return MonoSource.wrap(new FluxPeekFuseable<>(this, null, null, onError, null, null, null, null));
}
return MonoSource.wrap(new FluxPeek<>(this, null, null, onError, null, null, null, null));
}
/**
* Attach a {@link LongConsumer} to this {@link Mono} that will observe any request to this {@link Mono}.
*
* <p>
* <img class="marble" src="https://raw.githubusercontent.com/reactor/projectreactor.io/master/src/main/static/assets/img/marble/doonrequest1.png" alt="">
*
* @param consumer the consumer to invoke on each request
*
* @return an observed {@link Mono}
*/
public final Mono<T> doOnRequest(final LongConsumer consumer) {
if (this instanceof Fuseable) {
return MonoSource.wrap(new FluxPeekFuseable<>(this, null, null, null, null, null, consumer, null));
}
return MonoSource.wrap(new FluxPeek<>(this, null, null, null, null, null, consumer, null));
}
/**
* Triggered when the {@link Mono} is subscribed.
*
* <p>
* <img class="marble" src="https://raw.githubusercontent.com/reactor/projectreactor.io/master/src/main/static/assets/img/marble/doonsubscribe.png" alt="">
* <p>
* @param onSubscribe the callback to call on {@link Subscriber#onSubscribe(Subscription)}
*
* @return a new {@link Mono}
*/
public final Mono<T> doOnSubscribe(Consumer<? super Subscription> onSubscribe) {
if (this instanceof Fuseable) {
return MonoSource.wrap(new FluxPeekFuseable<>(this, onSubscribe, null, null, null, null, null, null));
}
return MonoSource.wrap(new FluxPeek<>(this, onSubscribe, null, null, null, null, null, null));
}
/**
* Triggered when the {@link Mono} terminates, either by completing successfully or with an error.
*
* <ul>
* <li>null, null : completing without data</li>
* <li>T, null : completing with data</li>
* <li>null, Throwable : failing with/without data</li>
* </ul>
*
* <p>
* <img class="marble" src="https://raw.githubusercontent.com/reactor/projectreactor.io/master/src/main/static/assets/img/marble/doonterminate1.png" alt="">
* <p>
* @param onTerminate the callback to call {@link Subscriber#onNext}, {@link Subscriber#onComplete} without preceding {@link Subscriber#onNext} or {@link Subscriber#onError}
*
* @return a new {@link Mono}
*/
public final Mono<T> doOnTerminate(BiConsumer<? super T, Throwable> onTerminate) {
return new MonoSuccess<>(this, null, onTerminate, null);
}
/**
* Map this {@link Mono} sequence into {@link reactor.core.tuple.Tuple2} of T1 {@link Long} timemillis and T2
* {@link T} associated data. The timemillis corresponds to the elapsed time between the subscribe and the first
* next signal.
*
* <p>
* <img class="marble" src="https://raw.githubusercontent.com/reactor/projectreactor.io/master/src/main/static/assets/img/marble/elapsed1.png" alt="">
*
* @return a transforming {@link Mono} that emits a tuple of time elapsed in milliseconds and matching data
*/
public final Mono<Tuple2<Long, T>> elapsed() {
return MonoSource.wrap(new FluxElapsed<>(this));
}
/**
* Transform the items emitted by a {@link Publisher} into Publishers, then flatten the emissions from those by
* merging them into a single {@link Flux}, so that they may interleave.
*
* <p>
* <img class="marble" src="https://raw.githubusercontent.com/reactor/projectreactor.io/master/src/main/static/assets/img/marble/flatmap1.png" alt="">
* <p>
* @param mapper the
* {@link Function} to produce a sequence of R from the the eventual passed {@link Subscriber#onNext}
* @param <R> the merged sequence type
*
* @return a new {@link Flux} as the sequence is not guaranteed to be single at most
*/
public final <R> Flux<R> flatMap(Function<? super T, ? extends Publisher<? extends R>> mapper) {
return flatMap(mapper, PlatformDependent.SMALL_BUFFER_SIZE);
}
/**
* Transform the items emitted by a {@link Publisher} into Publishers, then flatten the emissions from those by
* merging them into a single {@link Flux}, so that they may interleave.
*
* <p>
* <img class="marble" src="https://raw.githubusercontent.com/reactor/projectreactor.io/master/src/main/static/assets/img/marble/flatmap1.png" alt="">
* <p>
* @param mapper the
* {@link Function} to produce a sequence of R from the the eventual passed {@link Subscriber#onNext}
* @param prefetch the inner source request size
* @param <R> the merged sequence type
*
* @return a new {@link Flux} as the sequence is not guaranteed to be single at most
*/
public final <R> Flux<R> flatMap(Function<? super T, ? extends Publisher<? extends R>> mapper, int prefetch) {
return new FluxFlatMap<>(
this,
mapper,
false,
Integer.MAX_VALUE,
QueueSupplier.one(),
prefetch,
QueueSupplier.get(prefetch)
);
}
/**
* Transform the signals emitted by this {@link Flux} into Publishers, then flatten the emissions from those by
* merging them into a single {@link Flux}, so that they may interleave.
*
* <p>
* <img class="marble" src="https://raw.githubusercontent.com/reactor/projectreactor.io/master/src/main/static/assets/img/marble/flatmaps1.png" alt="">
* <p>
* @param mapperOnNext the {@link Function} to call on next data and returning a sequence to merge
* @param mapperOnError the {@link Function} to call on error signal and returning a sequence to merge
* @param mapperOnComplete the {@link Function} to call on complete signal and returning a sequence to merge
* @param <R> the type of the produced merged sequence
*
* @return a new {@link Flux} as the sequence is not guaranteed to be single at most
*
* @see Flux#flatMap(Function, Function, Supplier)
*/
@SuppressWarnings("unchecked")
public final <R> Flux<R> flatMap(Function<? super T, ? extends Publisher<? extends R>> mapperOnNext,
Function<Throwable, ? extends Publisher<? extends R>> mapperOnError,
Supplier<? extends Publisher<? extends R>> mapperOnComplete) {
return new FluxFlatMap<>(
new FluxMapSignal<>(this, mapperOnNext, mapperOnError, mapperOnComplete),
Function.identity(),
false,
Integer.MAX_VALUE,
QueueSupplier.xs(),
PlatformDependent.XS_BUFFER_SIZE,
QueueSupplier.xs()
);
}
/**
* Convert this {@link Mono} to a {@link Flux}
*
* @return a {@link Flux} variant of this {@link Mono}
*/
public final Flux<T> flux() {
return FluxSource.wrap(this);
}
/**
* Block until a next signal is received, will return null if onComplete, T if onNext, throw a
* {@literal Exceptions.DownstreamException} if checked error or origin RuntimeException if unchecked.
* If the default timeout {@literal PlatformDependent#DEFAULT_TIMEOUT} has elapsed, a CancelException will be thrown.
*
* <p>
* <img class="marble" src="https://raw.githubusercontent.com/reactor/projectreactor.io/master/src/main/static/assets/img/marble/get.png" alt="">
* <p>
*
* @return T the result
*/
public T get() {
return get(PlatformDependent.DEFAULT_TIMEOUT);
}
/**
* Block until a next signal is received, will return null if onComplete, T if onNext, throw a
* {@literal Exceptions.DownstreamException} if checked error or origin RuntimeException if unchecked.
* If the default timeout {@literal PlatformDependent#DEFAULT_TIMEOUT} has elapsed, a CancelException will be thrown.
*
* Note that each get() will subscribe a new single (MonoResult) subscriber, in other words, the result might
* miss signal from hot publishers.
*
* <p>
* <img class="marble" src="https://raw.githubusercontent.com/reactor/projectreactor.io/master/src/main/static/assets/img/marble/get.png" alt="">
* <p>
*
* @param timeout maximum time period to wait for in milliseconds before raising a {@literal reactor.core.util.Exceptions.CancelException}
*
* @return T the result
*/
public T get(long timeout) {
if(this instanceof Supplier){
return get();
}
return subscribe().get(timeout);
}
/**
* Block until a next signal is received, will return null if onComplete, T if onNext, throw a
* {@literal Exceptions.DownstreamException} if checked error or origin RuntimeException if unchecked.
* If the default timeout {@literal PlatformDependent#DEFAULT_TIMEOUT} has elapsed, a CancelException will be thrown.
*
* Note that each get() will subscribe a new single (MonoResult) subscriber, in other words, the result might
* miss signal from hot publishers.
*
* <p>
* <img class="marble" src="https://raw.githubusercontent.com/reactor/projectreactor.io/master/src/main/static/assets/img/marble/get.png" alt="">
* <p>
*
* @param timeout maximum time period to wait for before raising a {@literal reactor.core.util.Exceptions.CancelException}
*
* @return T the result
*/
public T get(Duration timeout) {
return get(timeout.toMillis());
}
@Override
public final long getCapacity() {
return 1L;
}
@Override
public int getMode() {
return FACTORY;
}
@Override
public String getName() {
return getClass().getSimpleName()
.replace(Mono.class.getSimpleName(), "");
}
/**
* Emit a single boolean true if this {@link Mono} has an element.
*
* <p>
* <img class="marble" src="https://raw.githubusercontent.com/reactor/projectreactor.io/master/src/main/static/assets/img/marble/haselement.png" alt="">
*
* @return a new {@link Mono} with <code>true</code> if a value is emitted and <code>false</code>
* otherwise
*/
public final Mono<Boolean> hasElement() {
return new MonoHasElements<>(this);
}
/**
* Ignores onNext signal (dropping it) and only reacts on termination.
*
* <p>
* <img class="marble" src="https://raw.githubusercontent.com/reactor/projectreactor.io/master/src/main/static/assets/img/marble/ignoreelement.png" alt="">
* <p>
*
* @return a new completable {@link Mono}.
*/
public final Mono<T> ignoreElement() {
return ignoreElements(this);
}
/**
* Create a {@link Mono} intercepting all source signals with the returned Subscriber that might choose to pass them
* alone to the provided Subscriber (given to the returned {@code subscribe(Subscriber)}.
*
* <p>
* <img class="marble" src="https://raw.githubusercontent.com/reactor/projectreactor.io/master/src/main/static/assets/img/marble/lift1.png" alt="">
* <p>
* @param lifter the function accepting the target {@link Subscriber} and returning the {@link Subscriber}
* exposed this sequence
* @param <V> the output type
* @return a new lifted {@link Mono}
*
* @see Flux#lift
*/
public final <V> Mono<V> lift(Function<Subscriber<? super V>, Subscriber<? super T>> lifter) {
return new FluxLift.MonoLift<>(this, lifter);
}
/**
* Observe all Reactive Streams signals and use {@link Logger} support to handle trace implementation. Default will
* use {@link Level#INFO} and java.util.logging. If SLF4J is available, it will be used instead.
*
* Options allow fine grained filtering of the traced signal, for instance to only capture onNext and onError:
* <pre>
* mono.log("category", Level.INFO, Logger.ON_NEXT | LOGGER.ON_ERROR)
* <p>
* <img class="marble" src="https://raw.githubusercontent.com/reactor/projectreactor.io/master/src/main/static/assets/img/marble/log1.png" alt="">
* <p>
*
* @return a new {@link Mono}
*
* @see Flux#log()
*/
public final Mono<T> log() {
return log(null, Level.INFO, Logger.ALL);
}
/**
* Observe all Reactive Streams signals and use {@link Logger} support to handle trace implementation. Default will
* use {@link Level#INFO} and java.util.logging. If SLF4J is available, it will be used instead.
*
* Options allow fine grained filtering of the traced signal, for instance to only capture onNext and onError:
* <pre>
* mono.log("category", Level.INFO, Logger.ON_NEXT | LOGGER.ON_ERROR)
* <p>
* <img class="marble" src="https://raw.githubusercontent.com/reactor/projectreactor.io/master/src/main/static/assets/img/marble/log1.png" alt="">
* <p>
* @param category to be mapped into logger configuration (e.g. org.springframework.reactor).
*
* @return a new {@link Mono}
*/
public final Mono<T> log(String category) {
return log(category, Level.INFO, Logger.ALL);
}
/**
* Observe all Reactive Streams signals and use {@link Logger} support to handle trace implementation. Default will
* use the passed {@link Level} and java.util.logging. If SLF4J is available, it will be used instead.
*
* Options allow fine grained filtering of the traced signal, for instance to only capture onNext and onError:
* <pre>
* mono.log("category", Level.INFO, Logger.ON_NEXT | LOGGER.ON_ERROR)
* <p>
* <img class="marble" src="https://raw.githubusercontent.com/reactor/projectreactor.io/master/src/main/static/assets/img/marble/log1.png" alt="">
* <p>
* @param category to be mapped into logger configuration (e.g. org.springframework.reactor).
* @param level the level to enforce for this tracing Flux
*
* @return a new {@link Mono}
*/
public final Mono<T> log(String category, Level level) {
return log(category, level, Logger.ALL);
}
/**
* Observe Reactive Streams signals matching the passed flags {@code options} and use {@link Logger} support to
* handle trace
* implementation. Default will
* use the passed {@link Level} and java.util.logging. If SLF4J is available, it will be used instead.
*
* Options allow fine grained filtering of the traced signal, for instance to only capture onNext and onError:
* <pre>
* mono.log("category", Level.INFO, Logger.ON_NEXT | LOGGER.ON_ERROR)
* <p>
* <img class="marble" src="https://raw.githubusercontent.com/reactor/projectreactor.io/master/src/main/static/assets/img/marble/log1.png" alt="">
* <p>
* @param category to be mapped into logger configuration (e.g. org.springframework.reactor).
* @param level the level to enforce for this tracing Flux
* @param options a flag option that can be mapped with {@link Logger#ON_NEXT} etc.
*
* @return a new {@link Mono}
*
*/
public final Mono<T> log(String category, Level level, int options) {
return MonoSource.wrap(new FluxLog<>(this, category, level, options));
}
/**
* Transform the item emitted by this {@link Mono} by applying a function to item emitted.
*
* <p>
* <img class="marble" src="https://raw.githubusercontent.com/reactor/projectreactor.io/master/src/main/static/assets/img/marble/map1.png" alt="">
* <p>
* @param mapper the transforming function
* @param <R> the transformed type
*
* @return a new {@link Mono}
*/
public final <R> Mono<R> map(Function<? super T, ? extends R> mapper) {
if (this instanceof Fuseable) {
return MonoSource.wrap(new FluxMapFuseable<>(this, mapper));
}
return MonoSource.wrap(new FluxMap<>(this, mapper));
}
/**
* Transform the incoming onNext, onError and onComplete signals into {@link Signal}.
* Since the error is materialized as a {@code Signal}, the propagation will be stopped and onComplete will be
* emitted. Complete signal will first emit a {@code Signal.complete()} and then effectively complete the flux.
*
* <p>
* <img class="marble" src="https://raw.githubusercontent.com/reactor/projectreactor.io/master/src/main/static/assets/img/marble/materialize1.png" alt="">
*
* @return a {@link Mono} of materialized {@link Signal}
*/
public final Mono<Signal<T>> materialize() {
return new FluxMaterialize<>(this).next();
}
/**
* Merge emissions of this {@link Mono} with the provided {@link Publisher}.
*
* <p>
* <img class="marble" src="https://raw.githubusercontent.com/reactor/projectreactor.io/master/src/main/static/assets/img/marble/merge1.png" alt="">
* <p>
* @param other the other {@link Publisher} to merge with
*
* @return a new {@link Flux} as the sequence is not guaranteed to be at most 1
*/
@SuppressWarnings("unchecked")
public final Flux<T> mergeWith(Publisher<? extends T> other) {
return Flux.merge(this, other);
}
/**
* Emit the current instance of the {@link Mono}.
*
* <p>
* <img class="marble" src="https://raw.githubusercontent.com/reactor/projectreactor.io/master/src/main/static/assets/img/marble/nest1.png" alt="">
*
* @return a new {@link Mono} whose value will be the current {@link Mono}
*/
public final Mono<Mono<T>> nest() {
return just(this);
}
/**
* Emit the any of the result from this mono or from the given mono
*
* <p>
* <img class="marble" src="https://raw.githubusercontent.com/reactor/projectreactor.io/master/src/main/static/assets/img/marble/or.png" alt="">
* <p>
* @param other the racing other {@link Mono} to compete with for the result
*
* @return a new {@link Mono}
* @see #any
*/
public final Mono<T> or(Mono<? extends T> other) {
return any(this, other);
}
/**
* Subscribe to a returned fallback publisher when any error occurs.
*
* <p>
* <img class="marble" src="https://raw.githubusercontent.com/reactor/projectreactor.io/master/src/main/static/assets/img/marble/otherwise.png" alt="">
* <p>
* @param fallback the function to map an alternative {@link Mono}
*
* @return an alternating {@link Mono} on source onError
*
* @see Flux#onErrorResumeWith
*/
public final Mono<T> otherwise(Function<Throwable, ? extends Mono<? extends T>> fallback) {
return MonoSource.wrap(new FluxResume<>(this, fallback));
}
/**
* Provide an alternative {@link Mono} if this mono is completed without data
*
* <p>
* <img class="marble" src="https://raw.githubusercontent.com/reactor/projectreactor.io/master/src/main/static/assets/img/marble/otherwiseempty.png" alt="">
* <p>
* @param alternate the alternate mono if this mono is empty
*
* @return an alternating {@link Mono} on source onComplete without elements
* @see Flux#switchIfEmpty
*/
public final Mono<T> otherwiseIfEmpty(Mono<? extends T> alternate) {
return MonoSource.wrap(new FluxSwitchIfEmpty<>(this, alternate));
}
/**
* Subscribe to a returned fallback value when any error occurs.
*
* <p>
* <img class="marble" src="https://raw.githubusercontent.com/reactor/projectreactor.io/master/src/main/static/assets/img/marble/otherwisejust.png" alt="">
* <p>
* @param fallback the value to emit if an error occurs
*
* @return a new {@link Mono}
*
* @see Flux#onErrorReturn
*/
public final Mono<T> otherwiseJust(final T fallback) {
return otherwise(throwable -> just(fallback));
}
/**
* Run the requests to this Publisher {@link Mono} on a given worker thread like {@link SchedulerGroup}.
* <p>
* {@code mono.subscribeOn(SchedulerGroup.io()).subscribe(Subscribers.unbounded()) }
*
* <p>
* <img class="marble" src="https://raw.githubusercontent.com/reactor/projectreactor.io/master/src/main/static/assets/img/marble/subscribeon1.png" alt="">
* <p>
* @param scheduler a checked {@link reactor.core.scheduler.Scheduler.Worker} factory
*
* @return a new asynchronous {@link Mono}
*/
public final Mono<T> subscribeOn(Scheduler scheduler) {
return MonoSource.wrap(new FluxSubscribeOn<>(this, scheduler));
}
/**
* Repeatedly subscribe to this {@link Mono} until there is an onNext signal when a companion sequence signals a
* number of emitted elements.
* <p>If the companion sequence signals when this {@link Mono} is active, the repeat
* attempt is suppressed and any terminal signal will terminate this {@link Flux} with the same signal immediately.
*
* <p>
* <img class="marble" src="https://raw.githubusercontent.com/reactor/projectreactor.io/master/src/main/static/assets/img/marble/repeatwhenempty.png" alt="">
*
* @param repeatFactory the
* {@link Function} providing a {@link Flux} signalling the current number of repeat on onComplete and returning a {@link Publisher} companion.
*
* @return an eventually repeated {@link Mono} on onComplete when the companion {@link Publisher} produces an
* onNext signal
*
*/
public final Mono<T> repeatWhenEmpty(Function<Flux<Long>, ? extends Publisher<?>> repeatFactory) {
return repeatWhenEmpty(Integer.MAX_VALUE, repeatFactory);
}
/**
* Repeatedly subscribe to this {@link Mono} until there is an onNext signal when a companion sequence signals a
* number of emitted elements.
* <p>If the companion sequence signals when this {@link Mono} is active, the repeat
* attempt is suppressed and any terminal signal will terminate this {@link Flux} with the same signal immediately.
* <p>Emits an {@link IllegalStateException} if the max repeat is exceeded and different from {@code Integer.MAX_VALUE}.
*
* <p>
* <img class="marble" src="https://raw.githubusercontent.com/reactor/projectreactor.io/master/src/main/static/assets/img/marble/repeatwhen1.png" alt="">
*
* @param maxRepeat the maximum repeat number of time (infinite if {@code Integer.MAX_VALUE})
* @param repeatFactory the
* {@link Function} providing a {@link Flux} signalling the current repeat index from 0 on onComplete and returning a {@link Publisher} companion.
*
* @return an eventually repeated {@link Mono} on onComplete when the companion {@link Publisher} produces an
* onNext signal
*
*/
public final Mono<T> repeatWhenEmpty(int maxRepeat, Function<Flux<Long>, ? extends Publisher<?>> repeatFactory) {
return Mono.defer(() -> {
Flux<Long> iterations;
if(maxRepeat == Integer.MAX_VALUE) {
AtomicLong counter = new AtomicLong();
iterations = Flux
.generate((range, subscriber) -> LongStream
.range(0, range)
.forEach(l -> subscriber.onNext(counter.getAndIncrement())));
} else {
iterations = Flux
.range(0, maxRepeat)
.map(Integer::longValue)
.concatWith(Flux.error(new IllegalStateException("Exceeded maximum number of repeats"), true));
}
AtomicBoolean nonEmpty = new AtomicBoolean();
return Flux
.from(this
.doOnSuccess(e -> nonEmpty.lazySet(e != null)))
.repeatWhen(o -> repeatFactory
.apply(o
.takeWhile(e -> !nonEmpty.get())
.zipWith(iterations, 1, (c, i) -> i)))
.single();
});
}
/**
* Re-subscribes to this {@link Mono} sequence if it signals any error
* either indefinitely.
* <p>
* The times == Long.MAX_VALUE is treated as infinite retry.
*
* <p>
* <img class="marble" src="https://raw.githubusercontent.com/reactor/projectreactor.io/master/src/main/static/assets/img/marble/retry1.png" alt="">
*
* @return a re-subscribing {@link Mono} on onError
*/
public final Mono<T> retry() {
return retry(Long.MAX_VALUE);
}
/**
* Re-subscribes to this {@link Mono} sequence if it signals any error
* either indefinitely or a fixed number of times.
* <p>
* The times == Long.MAX_VALUE is treated as infinite retry.
*
* <p>
* <img class="marble" src="https://raw.githubusercontent.com/reactor/projectreactor.io/master/src/main/static/assets/img/marble/retryn1.png" alt="">
*
* @param numRetries the number of times to tolerate an error
*
* @return a re-subscribing {@link Mono} on onError up to the specified number of retries.
*
*/
public final Mono<T> retry(long numRetries) {
return MonoSource.wrap(new FluxRetry<T>(this, numRetries));
}
/**
* Re-subscribes to this {@link Mono} sequence if it signals any error
* and the given {@link Predicate} matches otherwise push the error downstream.
*
* <p>
* <img class="marble" src="https://raw.githubusercontent.com/reactor/projectreactor.io/master/src/main/static/assets/img/marble/retryb1.png" alt="">
*
* @param retryMatcher the predicate to evaluate if retry should occur based on a given error signal
*
* @return a re-subscribing {@link Mono} on onError if the predicates matches.
*/
public final Mono<T> retry(Predicate<Throwable> retryMatcher) {
return retryWhen(v -> v.filter(retryMatcher));
}
/**
* Re-subscribes to this {@link Mono} sequence up to the specified number of retries if it signals any
* error and the given {@link Predicate} matches otherwise push the error downstream.
*
* <p>
* <img class="marble" src="https://raw.githubusercontent.com/reactor/projectreactor.io/master/src/main/static/assets/img/marble/retrynb1.png" alt="">
*
* @param numRetries the number of times to tolerate an error
* @param retryMatcher the predicate to evaluate if retry should occur based on a given error signal
*
* @return a re-subscribing {@link Mono} on onError up to the specified number of retries and if the predicate
* matches.
*
*/
public final Mono<T> retry(long numRetries, Predicate<Throwable> retryMatcher) {
return retry(Flux.countingPredicate(retryMatcher, numRetries));
}
/**
* Retries this {@link Mono} when a companion sequence signals
* an item in response to this {@link Mono} error signal
* <p>If the companion sequence signals when the {@link Mono} is active, the retry
* attempt is suppressed and any terminal signal will terminate the {@link Mono} source with the same signal
* immediately.
*
* <p>
* <img class="marble" src="https://raw.githubusercontent.com/reactor/projectreactor.io/master/src/main/static/assets/img/marble/retrywhen1.png" alt="">
*
* @param whenFactory the {@link Function} providing a {@link Flux} signalling any error from the source sequence and returning a {@link Publisher} companion.
*
* @return a re-subscribing {@link Mono} on onError when the companion {@link Publisher} produces an
* onNext signal
*/
public final Mono<T> retryWhen(Function<Flux<Throwable>, ? extends Publisher<?>> whenFactory) {
return MonoSource.wrap(new FluxRetryWhen<T>(this, whenFactory));
}
/**
* Start the chain and request unbounded demand.
*
* <p>
* <img width="500" src="https://raw.githubusercontent.com/reactor/projectreactor.io/master/src/main/static/assets/img/marble/unbounded1.png" alt="">
* <p>
*
* @return a {@link Runnable} task to execute to dispose and cancel the underlying {@link Subscription}
*/
public final MonoProcessor<T> subscribe() {
MonoProcessor<T> s;
if(this instanceof MonoProcessor){
s = (MonoProcessor<T>)this;
}
else{
s = new MonoProcessor<>(this);
}
s.connect();
return s;
}
/**
* Subscribe the {@link Mono} with the givne {@link Subscriber} and return it.
*
* @param subscriber the {@link Subscriber} to subscribe
* @param <E> the reified type of the {@link Subscriber} for chaining
*
* @return the passed {@link Subscriber} after subscribing it to this {@link Mono}
*/
public final <E extends Subscriber<? super T>> E subscribeWith(E subscriber) {
subscribe(subscriber);
return subscriber;
}
/**
* Convert the value of {@link Mono} to another {@link Mono} possibly with another value type.
*
* <p>
* <img class="marble" src="https://raw.githubusercontent.com/reactor/projectreactor.io/master/src/main/static/assets/img/marble/then.png" alt="">
* <p>
* @param transformer the function to dynamically bind a new {@link Mono}
* @param <R> the result type bound
*
* @return a new {@link Mono} containing the merged values
*/
public final <R> Mono<R> then(Function<? super T, ? extends Mono<? extends R>> transformer) {
return MonoSource.wrap(flatMap(transformer));
}
/**
* Assign the given {@link Function} to transform the incoming value {@code T} into n {@code Mono<? extends T1>} and pass
* the result as a combined {@code Tuple}.
*
* <p>
* <img class="marble" src="https://raw.githubusercontent.com/reactor/projectreactor.io/master/src/main/static/assets/img/marble/thenn.png" alt="">
* <p>
* @param fn1 the transformation function
* @param fn2 the transformation function
* @param <T1> the type of the return value of the transformation function
* @param <T2> the type of the return value of the transformation function
*
* @return a new {@link Mono} containing the combined values
*/
public final <T1, T2> Mono<Tuple2<T1, T2>> then(
final Function<? super T, ? extends Mono<? extends T1>> fn1,
final Function<? super T, ? extends Mono<? extends T2>> fn2) {
return then(o -> when(fn1.apply(o), fn2.apply(o)));
}
/**
* Assign the given {@link Function} to transform the incoming value {@code T} into n {@code Mono<? extends T1>} and pass
* the result as a combined {@code Tuple}.
*
* <p>
* <img class="marble" src="https://raw.githubusercontent.com/reactor/projectreactor.io/master/src/main/static/assets/img/marble/thenn.png" alt="">
* <p>
* @param fn1 the transformation function
* @param fn2 the transformation function
* @param fn3 the transformation function
* @param <T1> the type of the return value of the transformation function
* @param <T2> the type of the return value of the transformation function
* @param <T3> the type of the return value of the transformation function
*
* @return a new {@link Mono} containing the combined values
*/
public final <T1, T2, T3> Mono<Tuple3<T1, T2, T3>> then(
final Function<? super T, ? extends Mono<? extends T1>> fn1,
final Function<? super T, ? extends Mono<? extends T2>> fn2,
final Function<? super T, ? extends Mono<? extends T3>> fn3) {
return then(o -> when(fn1.apply(o), fn2.apply(o), fn3.apply(o)));
}
/**
* Assign the given {@link Function} to transform the incoming value {@code T} into n {@code Mono<? extends T1>} and pass
* the result as a combined {@code Tuple}.
*
* <p>
* <img class="marble" src="https://raw.githubusercontent.com/reactor/projectreactor.io/master/src/main/static/assets/img/marble/thenn.png" alt="">
* <p>
* @param fn1 the transformation function
* @param fn2 the transformation function
* @param fn3 the transformation function
* @param fn4 the transformation function
* @param <T1> the type of the return value of the transformation function
* @param <T2> the type of the return value of the transformation function
* @param <T3> the type of the return value of the transformation function
* @param <T4> the type of the return value of the transformation function
*
* @return a new {@link Mono} containing the combined values
*
* @since 2.5
*/
public final <T1, T2, T3, T4> Mono<Tuple4<T1, T2, T3, T4>> then(
final Function<? super T, ? extends Mono<? extends T1>> fn1,
final Function<? super T, ? extends Mono<? extends T2>> fn2,
final Function<? super T, ? extends Mono<? extends T3>> fn3,
final Function<? super T, ? extends Mono<? extends T4>> fn4) {
return then(o -> when(fn1.apply(o), fn2.apply(o), fn3.apply(o), fn4.apply(o)));
}
/**
* Assign the given {@link Function} to transform the incoming value {@code T} into n {@code Mono<? extends T1>} and pass
* the result as a combined {@code Tuple}.
*
* <p>
* <img class="marble" src="https://raw.githubusercontent.com/reactor/projectreactor.io/master/src/main/static/assets/img/marble/thenn.png" alt="">
* <p>
* @param fn1 the transformation function
* @param fn2 the transformation function
* @param fn3 the transformation function
* @param fn4 the transformation function
* @param fn5 the transformation function
* @param <T1> the type of the return value of the transformation function
* @param <T2> the type of the return value of the transformation function
* @param <T3> the type of the return value of the transformation function
* @param <T4> the type of the return value of the transformation function
* @param <T5> the type of the return value of the transformation function
*
* @return a new {@link Mono} containing the combined values
*
*/
public final <T1, T2, T3, T4, T5> Mono<Tuple5<T1, T2, T3, T4, T5>> then(
final Function<? super T, ? extends Mono<? extends T1>> fn1,
final Function<? super T, ? extends Mono<? extends T2>> fn2,
final Function<? super T, ? extends Mono<? extends T3>> fn3,
final Function<? super T, ? extends Mono<? extends T4>> fn4,
final Function<? super T, ? extends Mono<? extends T5>> fn5) {
return then(o -> when(fn1.apply(o), fn2.apply(o), fn3.apply(o), fn4.apply(o), fn5.apply(o)));
}
/**
* Assign the given {@link Function} to transform the incoming value {@code T} into n {@code Mono<? extends T1>} and pass
* the result as a combined {@code Tuple}.
*
* <p>
* <img class="marble" src="https://raw.githubusercontent.com/reactor/projectreactor.io/master/src/main/static/assets/img/marble/thenn.png" alt="">
* <p>
* @param fn1 the transformation function
* @param fn2 the transformation function
* @param fn3 the transformation function
* @param fn4 the transformation function
* @param fn5 the transformation function
* @param fn6 the transformation function
* @param <T1> the type of the return value of the transformation function
* @param <T2> the type of the return value of the transformation function
* @param <T3> the type of the return value of the transformation function
* @param <T4> the type of the return value of the transformation function
* @param <T5> the type of the return value of the transformation function
* @param <T6> the type of the return value of the transformation function
*
* @return a new {@link Mono} containing the combined values
*
*/
public final <T1, T2, T3, T4, T5, T6> Mono<Tuple6<T1, T2, T3, T4, T5, T6>> then(
final Function<? super T, ? extends Mono<? extends T1>> fn1,
final Function<? super T, ? extends Mono<? extends T2>> fn2,
final Function<? super T, ? extends Mono<? extends T3>> fn3,
final Function<? super T, ? extends Mono<? extends T4>> fn4,
final Function<? super T, ? extends Mono<? extends T5>> fn5,
final Function<? super T, ? extends Mono<? extends T6>> fn6) {
return then(o -> when(fn1.apply(o), fn2.apply(o), fn3.apply(o), fn4.apply(o), fn5.apply(o), fn6.apply(o)));
}
/**
* Signal a {@link java.util.concurrent.TimeoutException} error in case an item doesn't arrive before the given period.
*
* <p>
* <img class="marble" src="https://raw.githubusercontent.com/reactor/projectreactor.io/master/src/main/static/assets/img/marble/timeouttime1.png" alt="">
*
* @param timeout the timeout before the onNext signal from this {@link Mono}
*
* @return an expirable {@link Mono}
*/
public final Mono<T> timeout(long timeout) {
return timeout(Duration.ofMillis(timeout), null);
}
/**
* Signal a {@link java.util.concurrent.TimeoutException} in case an item doesn't arrive before the given period.
*
* <p>
* <img class="marble" src="https://raw.githubusercontent.com/reactor/projectreactor.io/master/src/main/static/assets/img/marble/timeouttime1.png" alt="">
*
* @param timeout the timeout before the onNext signal from this {@link Mono}
*
* @return an expirable {@link Mono}
*/
public final Mono<T> timeout(Duration timeout) {
return timeout(timeout, null);
}
/**
* Switch to a fallback {@link Mono} in case an item doesn't arrive before the given period.
*
* <p> If the given {@link Publisher} is null, signal a {@link java.util.concurrent.TimeoutException}.
*
* <p>
* <img class="marble" src="https://raw.githubusercontent.com/reactor/projectreactor.io/master/src/main/static/assets/img/marble/timeouttimefallback1.png" alt="">
*
* @param timeout the timeout before the onNext signal from this {@link Mono}
* @param fallback the fallback {@link Mono} to subscribe when a timeout occurs
*
* @return an expirable {@link Mono} with a fallback {@link Mono}
*/
public final Mono<T> timeout(Duration timeout, Mono<? extends T> fallback) {
final Mono<Long> _timer = Mono.delay(timeout).otherwiseJust(0L);
final Function<T, Publisher<Long>> rest = o -> never();
if(fallback == null) {
return MonoSource.wrap(new FluxTimeout<>(this, _timer, rest));
}
return MonoSource.wrap(new FluxTimeout<>(this, _timer, rest, fallback));
}
/**
* Signal a {@link java.util.concurrent.TimeoutException} in case the item from this {@link Mono} has
* not been emitted before the given {@link Publisher} emits.
*
* <p>
* <img class="marble" src="https://raw.githubusercontent.com/reactor/projectreactor.io/master/src/main/static/assets/img/marble/timeoutp1.png" alt="">
*
* @param firstTimeout the timeout {@link Publisher} that must not emit before the first signal from this {@link Flux}
* @param <U> the element type of the timeout Publisher
*
* @return an expirable {@link Mono} if the first item does not come before a {@link Publisher} signal
*
*/
public final <U> Mono<T> timeout(Publisher<U> firstTimeout) {
return MonoSource.wrap(new FluxTimeout<>(this, firstTimeout, t -> never()));
}
/**
* Switch to a fallback {@link Publisher} in case the item from this {@link Mono} has
* not been emitted before the given {@link Publisher} emits. The following items will be individually timed via
* the factory provided {@link Publisher}.
*
* <p>
* <img class="marble" src="https://raw.githubusercontent.com/reactor/projectreactor.io/master/src/main/static/assets/img/marble/timeoutfallbackp1.png" alt="">
*
* @param firstTimeout the timeout
* {@link Publisher} that must not emit before the first signal from this {@link Mono}
* @param fallback the fallback {@link Publisher} to subscribe when a timeout occurs
* @param <U> the element type of the timeout Publisher
*
* @return a first then per-item expirable {@link Mono} with a fallback {@link Publisher}
*
*/
public final <U> Mono<T> timeout(Publisher<U> firstTimeout, Mono<? extends T> fallback) {
return MonoSource.wrap(new FluxTimeout<>(this, firstTimeout, t -> never(), fallback));
}
/**
* Emit a {@link reactor.core.tuple.Tuple2} pair of T1 {@link Long} current system time in
* millis and T2 {@link T} associated data for the eventual item from this {@link Mono}
*
* <p>
* <img class="marble" src="https://raw.githubusercontent.com/reactor/projectreactor.io/master/src/main/static/assets/img/marble/timestamp1.png" alt="">
*
* @return a timestamped {@link Mono}
*/
@SuppressWarnings("unchecked")
public final Mono<Tuple2<Long, T>> timestamp() {
return map(Flux.TIMESTAMP_OPERATOR);
}
/**
* Transform this {@link Mono} into a {@link CompletableFuture} completing on onNext or onComplete and failing on
* onError.
*
* <p>
* <img class="marble" src="https://raw.githubusercontent.com/reactor/projectreactor.io/master/src/main/static/assets/img/marble/tocompletablefuture.png" alt="">
* <p>
*
* @return a {@link CompletableFuture}
*/
public final CompletableFuture<T> toCompletableFuture() {
return subscribeWith(new MonoToCompletableFuture<>());
}
/**
* Test the result if any of this {@link Mono} and replay it if predicate returns true.
* Otherwise complete without value.
*
* <p>
* <img class="marble" src="https://raw.githubusercontent.com/reactor/projectreactor.io/master/src/main/static/assets/img/marble/where.png" alt="">
* <p>
* @param tester the predicate to evaluate
*
* @return a filtered {@link Mono}
*/
public final Mono<T> where(final Predicate<? super T> tester) {
if (this instanceof Fuseable) {
return MonoSource.wrap(new FluxFilterFuseable<>(this, tester));
}
return MonoSource.wrap(new FluxFilter<>(this, tester));
}
}
| src/main/java/reactor/core/publisher/Mono.java | /*
* Copyright (c) 2011-2016 Pivotal Software Inc, All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package reactor.core.publisher;
import java.time.Duration;
import java.util.Optional;
import java.util.concurrent.Callable;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Future;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicLong;
import java.util.function.BiConsumer;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.LongConsumer;
import java.util.function.Predicate;
import java.util.function.Supplier;
import java.util.logging.Level;
import java.util.stream.LongStream;
import org.reactivestreams.Publisher;
import org.reactivestreams.Subscriber;
import org.reactivestreams.Subscription;
import reactor.core.flow.Fuseable;
import reactor.core.queue.QueueSupplier;
import reactor.core.scheduler.Scheduler;
import reactor.core.state.Backpressurable;
import reactor.core.state.Completable;
import reactor.core.state.Introspectable;
import reactor.core.subscriber.LambdaSubscriber;
import reactor.core.scheduler.Timer;
import reactor.core.tuple.Tuple;
import reactor.core.tuple.Tuple2;
import reactor.core.tuple.Tuple3;
import reactor.core.tuple.Tuple4;
import reactor.core.tuple.Tuple5;
import reactor.core.tuple.Tuple6;
import reactor.core.util.Assert;
import reactor.core.util.Logger;
import reactor.core.util.PlatformDependent;
import reactor.core.util.ReactiveStateUtils;
/**
* A Reactive Streams {@link Publisher} with basic rx operators that completes successfully by emitting an element, or
* with an error.
*
* <p>
* <img width="640" src="https://raw.githubusercontent.com/reactor/projectreactor.io/master/src/main/static/assets/img/marble/mono.png" alt="">
* <p>
*
* <p>The rx operators will offer aliases for input {@link Mono} type to preserve the "at most one"
* property of the resulting {@link Mono}. For instance {@link Mono#flatMap flatMap} returns a {@link Flux} with
* possibly
* more than 1 emission. Its alternative enforcing {@link Mono} input is {@link Mono#then then}.
*
* <p>{@code Mono<Void>} should be used for {@link Publisher} that just completes without any value.
*
* <p>It is intended to be used in implementations and return types, input parameters should keep using raw {@link
* Publisher} as much as possible.
*
* @param <T> the type of the single value of this class
*
* @author Sebastien Deleuze
* @author Stephane Maldini
* @see Flux
* @since 2.5
*/
public abstract class Mono<T> implements Publisher<T>, Backpressurable, Introspectable,
Completable {
static final Mono<?> NEVER = MonoSource.from(FluxNever.instance());
// ==============================================================================================================
// Static Generators
// ==============================================================================================================
/**
* Pick the first result coming from any of the given monos and populate a new {@literal Mono}.
*
* <p>
* <img class="marble" src="https://raw.githubusercontent.com/reactor/projectreactor.io/master/src/main/static/assets/img/marble/any.png" alt="">
* <p>
* @param monos The deferred monos to use.
* @param <T> The type of the function result.
*
* @return a {@link Mono}.
*/
@SafeVarargs
@SuppressWarnings("varargs")
public static <T> Mono<T> any(Mono<? extends T>... monos) {
return MonoSource.wrap(new FluxAmb<>(monos));
}
/**
* Pick the first result coming from any of the given monos and populate a new {@literal Mono}.
*
* <p>
* <img class="marble" src="https://raw.githubusercontent.com/reactor/projectreactor.io/master/src/main/static/assets/img/marble/any.png" alt="">
* <p>
* @param monos The monos to use.
* @param <T> The type of the function result.
*
* @return a {@link Mono}.
*/
public static <T> Mono<T> any(Iterable<? extends Mono<? extends T>> monos) {
return MonoSource.wrap(new FluxAmb<>(monos));
}
/**
* Create a {@link Mono} provider that will {@link Supplier#get supply} a target {@link Mono} to subscribe to for
* each {@link Subscriber} downstream.
*
* <p>
* <img class="marble" src="https://raw.githubusercontent.com/reactor/projectreactor.io/master/src/main/static/assets/img/marble/defer1.png" alt="">
* <p>
* @param supplier a {@link Mono} factory
*
* @param <T> the element type of the returned Mono instance
*
* @return a new {@link Mono} factory
*/
public static <T> Mono<T> defer(Supplier<? extends Mono<? extends T>> supplier) {
return new MonoDefer<>(supplier);
}
/**
* Create a Mono which delays an onNext signal of {@code duration} milliseconds and complete.
* If the demand cannot be produced in time, an onError will be signalled instead.
*
* <p>
* <img class="marble" src="https://raw.githubusercontent.com/reactor/projectreactor.io/master/src/main/static/assets/img/marble/delay.png" alt="">
* <p>
* @param duration the duration in milliseconds of the delay
*
* @return a new {@link Mono}
*/
public static Mono<Long> delay(long duration) {
return delay(duration, Timer.global());
}
/**
* Create a Mono which delays an onNext signal of {@code duration} of given unit and complete on the global timer.
* If the demand cannot be produced in time, an onError will be signalled instead.
*
* <p>
* <img class="marble" src="https://raw.githubusercontent.com/reactor/projectreactor.io/master/src/main/static/assets/img/marble/delay.png" alt="">
* <p>
* @param duration the duration of the delay
*
* @return a new {@link Mono}
*/
public static Mono<Long> delay(Duration duration) {
return delay(duration.toMillis());
}
/**
* Create a Mono which delays an onNext signal of {@code duration} milliseconds and complete.
* If the demand cannot be produced in time, an onError will be signalled instead.
*
* <p>
* <img class="marble" src="https://raw.githubusercontent.com/reactor/projectreactor.io/master/src/main/static/assets/img/marble/delay.png" alt="">
* <p>
* @param duration the duration in milliseconds of the delay
* @param timer the timer
*
* @return a new {@link Mono}
*/
public static Mono<Long> delay(long duration, Timer timer) {
Assert.isTrue(duration >= timer.period(), "The delay " + duration + " cannot be less than the timer resolution " +
"" + timer.period());
return new MonoDelay(timer, duration);
}
/**
* Create a Mono which delays an onNext signal of {@code duration} and complete.
* If the demand cannot be produced in time, an onError will be signalled instead.
*
* <p>
* <img class="marble" src="https://raw.githubusercontent.com/reactor/projectreactor.io/master/src/main/static/assets/img/marble/delay.png" alt="">
* <p>
* @param duration the duration of the delay
* @param timer the timer
*
* @return a new {@link Mono}
*/
public static Mono<Long> delay(Duration duration, Timer timer) {
return delay(duration.toMillis(), timer);
}
/**
* Create a {@link Mono} that completes without emitting any item.
*
* <p>
* <img class="marble" src="https://raw.githubusercontent.com/reactor/projectreactor.io/master/src/main/static/assets/img/marble/empty.png" alt="">
* <p>
* @param <T> the reified {@link Subscriber} type
*
* @return a completed {@link Mono}
*/
@SuppressWarnings("unchecked")
public static <T> Mono<T> empty() {
return (Mono<T>) MonoEmpty.instance();
}
/**
* Create a new {@link Mono} that ignores onNext (dropping them) and only react on Completion signal.
*
* <p>
* <img class="marble" src="https://raw.githubusercontent.com/reactor/projectreactor.io/master/src/main/static/assets/img/marble/after.png" alt="">
* <p>
* @param source the {@link Publisher to ignore}
* @param <T> the reified {@link Publisher} type
*
* @return a new completable {@link Mono}.
*/
@SuppressWarnings("unchecked")
public static <T> Mono<Void> empty(Publisher<T> source) {
return (Mono<Void>)new MonoIgnoreElements<>(source);
}
/**
* Create a {@link Mono} that completes with the specified error immediately after onSubscribe.
*
* <p>
* <img class="marble" src="https://raw.githubusercontent.com/reactor/projectreactor.io/master/src/main/static/assets/img/marble/error.png" alt="">
* <p>
* @param error the onError signal
* @param <T> the reified {@link Subscriber} type
*
* @return a failed {@link Mono}
*/
public static <T> Mono<T> error(Throwable error) {
return new MonoError<>(error);
}
/**
* Expose the specified {@link Publisher} with the {@link Mono} API, and ensure it will emit 0 or 1 item.
*
* <p>
* <img class="marble" src="https://raw.githubusercontent.com/reactor/projectreactor.io/master/src/main/static/assets/img/marble/from1.png" alt="">
* <p>
* @param source the {@link Publisher} source
* @param <T> the source type
*
* @return the next item emitted as a {@link Mono}
*/
@SuppressWarnings("unchecked")
public static <T> Mono<T> from(Publisher<? extends T> source) {
if (source == null) {
return empty();
}
if (source instanceof Mono) {
return (Mono<T>) source;
}
return new MonoNext<>(source);
}
/**
* Create a {@link Mono} producing the value for the {@link Mono} using the given supplier.
*
* <p>
* <img class="marble" src="https://raw.githubusercontent.com/reactor/projectreactor.io/master/src/main/static/assets/img/marble/fromcallable.png" alt="">
* <p>
* @param supplier {@link Supplier} that will produce the value
* @param <T> type of the expected value
*
* @return A {@link Mono}.
*/
public static <T> Mono<T> fromCallable(Callable<? extends T> supplier) {
return new MonoCallable<>(supplier);
}
/**
* Create a {@link Mono} producing the value for the {@link Mono} using the given {@link CompletableFuture}.
*
* <p>
* <img class="marble" src="https://raw.githubusercontent.com/reactor/projectreactor.io/master/src/main/static/assets/img/marble/fromcompletablefuture.png" alt="">
* <p>
* @param completableFuture {@link CompletableFuture} that will produce the value
* @param <T> type of the expected value
*
* @return A {@link Mono}.
*/
public static <T> Mono<T> fromCompletableFuture(CompletableFuture<? extends T> completableFuture) {
return new MonoCompletableFuture<>(completableFuture);
}
/**
* Build a {@link Mono} that will only emit the result of the future and then complete.
* The future will be polled for an unbounded amount of time on request().
*
* <p>
* <img class="marble" src="https://raw.githubusercontent.com/reactor/projectreactor.io/master/src/main/static/assets/img/marble/fromfuture.png" alt="">
*
* @param future the future to poll value from
* @param <T> the value type of the Future and the retuned Mono instance
* @return a new {@link Mono}
*/
public static <T> Mono<T> fromFuture(Future<? extends T> future) {
return new MonoFuture<T>(future);
}
/**
* Build a {@link Mono} that will only emit the result of the future and then complete.
* The future will be polled for a given amount of time on request() then onError if failed to return.
*
* <p>
* <img class="marble" src="https://raw.githubusercontent.com/reactor/projectreactor.io/master/src/main/static/assets/img/marble/fromfuture.png" alt="">
*
* @param <T> the value type of the Future and the retuned Mono instance
* @param future the future to poll value from
* @param timeout the timeout in milliseconds
* @return a new {@link Mono}
*/
public static <T> Mono<T> fromFuture(Future<? extends T> future, long timeout) {
return new MonoFuture<>(future, timeout);
}
/**
* Build a {@link Mono} that will only emit the result of the future and then complete.
* The future will be polled for a given amount of time on request() then onError if failed to return.
*
* <p>
* <img class="marble" src="https://raw.githubusercontent.com/reactor/projectreactor.io/master/src/main/static/assets/img/marble/fromfuture.png" alt="">
*
* @param future the future to poll value from
* @param duration the duration to wait for the result of the future before failing with onError
* @param <T> the value type of the Future and the retuned Mono instance
* @return a new {@link Mono}
*/
public static <T> Mono<T> fromFuture(Future<? extends T> future, Duration duration) {
return fromFuture(future, duration.toMillis());
}
/**
* Create a {@link Mono} only producing a completion signal after using the given
* runnable.
*
* <p>
* <img class="marble" src="https://raw.githubusercontent.com/reactor/projectreactor.io/master/src/main/static/assets/img/marble/fromrunnable.png" alt="">
* <p>
* @param runnable {@link Runnable} that will callback the completion signal
*
* @return A {@link Mono}.
*/
public static Mono<Void> fromRunnable(Runnable runnable) {
return MonoSource.wrap(new FluxPeek<>(MonoEmpty.instance(), null, null, null, runnable, null, null,
null));
}
/**
* Create a new {@link Mono} that ignores onNext (dropping them) and only react on Completion signal.
*
* <p>
* <img class="marble" src="https://raw.githubusercontent.com/reactor/projectreactor.io/master/src/main/static/assets/img/marble/ignoreelements.png" alt="">
* <p>
* @param source the {@link Publisher to ignore}
* @param <T> the source type of the ignored data
*
* @return a new completable {@link Mono}.
*/
public static <T> Mono<T> ignoreElements(Publisher<T> source) {
return new MonoIgnoreElements<>(source);
}
/**
* Create a new {@link Mono} that emits the specified item.
*
* <p>
* <img class="marble" src="https://raw.githubusercontent.com/reactor/projectreactor.io/master/src/main/static/assets/img/marble/just.png" alt="">
* <p>
* @param data the only item to onNext
* @param <T> the type of the produced item
*
* @return a {@link Mono}.
*/
public static <T> Mono<T> just(T data) {
return new MonoJust<>(data);
}
/**
* Create a new {@link Mono} that emits the specified item if {@link Optional#isPresent()} otherwise only emits
* onComplete.
*
* <p>
* <img class="marble" src="https://raw.githubusercontent.com/reactor/projectreactor.io/master/src/main/static/assets/img/marble/justorempty.png" alt="">
* <p>
* @param data the {@link Optional} item to onNext or onComplete if not present
* @param <T> the type of the produced item
*
* @return a {@link Mono}.
*/
public static <T> Mono<T> justOrEmpty(Optional<? extends T> data) {
return data != null && data.isPresent() ? just(data.get()) : empty();
}
/**
* Create a new {@link Mono} that emits the specified item if non null otherwise only emits
* onComplete.
*
* <p>
* <img class="marble" src="https://raw.githubusercontent.com/reactor/projectreactor.io/master/src/main/static/assets/img/marble/justorempty.png" alt="">
* <p>
* @param data the item to onNext or onComplete if null
* @param <T> the type of the produced item
*
* @return a {@link Mono}.
*/
public static <T> Mono<T> justOrEmpty(T data) {
return data != null ? just(data) : empty();
}
/**
* Return a {@link Mono} that will never signal any data, error or completion signal.
* <p>
* <img class="marble" src="https://raw.githubusercontent.com/reactor/projectreactor.io/master/src/main/static/assets/img/marble/never.png" alt="">
* <p>
* @param <T> the {@link Subscriber} type target
*
* @return a never completing {@link Mono}
*/
@SuppressWarnings("unchecked")
public static <T> Mono<T> never() {
return (Mono<T>)NEVER;
}
/**
* Merge given monos into a new a {@literal Mono} that will be fulfilled when all of the given {@literal Mono Monos}
* have been fulfilled.
*
* <p>
* <img class="marble" src="https://raw.githubusercontent.com/reactor/projectreactor.io/master/src/main/static/assets/img/marble/whent.png" alt="">
* <p>
* @param p1 The first upstream {@link Publisher} to subscribe to.
* @param p2 The second upstream {@link Publisher} to subscribe to.
* @param <T1> type of the value from source1
* @param <T2> type of the value from source2
*
* @return a {@link Mono}.
*/
public static <T1, T2> Mono<Tuple2<T1, T2>> when(Mono<? extends T1> p1, Mono<? extends T2> p2) {
return when(Tuple.fn2(), p1, p2);
}
/**
* Merge given monos into a new a {@literal Mono} that will be fulfilled when all of the given {@literal Mono Monos}
* have been fulfilled.
*
* <p>
* <img class="marble" src="https://raw.githubusercontent.com/reactor/projectreactor.io/master/src/main/static/assets/img/marble/whent.png" alt="">
* <p>
* @param p1 The first upstream {@link Publisher} to subscribe to.
* @param p2 The second upstream {@link Publisher} to subscribe to.
* @param p3 The third upstream {@link Publisher} to subscribe to.
* @param <T1> type of the value from source1
* @param <T2> type of the value from source2
* @param <T3> type of the value from source3
*
* @return a {@link Mono}.
*/
public static <T1, T2, T3> Mono<Tuple3<T1, T2, T3>> when(Mono<? extends T1> p1, Mono<? extends T2> p2, Mono<? extends T3> p3) {
return when(Tuple.fn3(), p1, p2, p3);
}
/**
* Merge given monos into a new a {@literal Mono} that will be fulfilled when all of the given {@literal Mono Monos}
* have been fulfilled.
*
* <p>
* <img class="marble" src="https://raw.githubusercontent.com/reactor/projectreactor.io/master/src/main/static/assets/img/marble/whent.png" alt="">
* <p>
* @param p1 The first upstream {@link Publisher} to subscribe to.
* @param p2 The second upstream {@link Publisher} to subscribe to.
* @param p3 The third upstream {@link Publisher} to subscribe to.
* @param p4 The fourth upstream {@link Publisher} to subscribe to.
* @param <T1> type of the value from source1
* @param <T2> type of the value from source2
* @param <T3> type of the value from source3
* @param <T4> type of the value from source4
*
* @return a {@link Mono}.
*/
public static <T1, T2, T3, T4> Mono<Tuple4<T1, T2, T3, T4>> when(Mono<? extends T1> p1,
Mono<? extends T2> p2,
Mono<? extends T3> p3,
Mono<? extends T4> p4) {
return when(Tuple.fn4(), p1, p2, p3, p4);
}
/**
* Merge given monos into a new a {@literal Mono} that will be fulfilled when all of the given {@literal Mono Monos}
* have been fulfilled.
*
* <p>
* <img class="marble" src="https://raw.githubusercontent.com/reactor/projectreactor.io/master/src/main/static/assets/img/marble/whent.png" alt="">
* <p>
* @param p1 The first upstream {@link Publisher} to subscribe to.
* @param p2 The second upstream {@link Publisher} to subscribe to.
* @param p3 The third upstream {@link Publisher} to subscribe to.
* @param p4 The fourth upstream {@link Publisher} to subscribe to.
* @param p5 The fifth upstream {@link Publisher} to subscribe to.
* @param <T1> type of the value from source1
* @param <T2> type of the value from source2
* @param <T3> type of the value from source3
* @param <T4> type of the value from source4
* @param <T5> type of the value from source5
*
* @return a {@link Mono}.
*/
public static <T1, T2, T3, T4, T5> Mono<Tuple5<T1, T2, T3, T4, T5>> when(Mono<? extends T1> p1,
Mono<? extends T2> p2,
Mono<? extends T3> p3,
Mono<? extends T4> p4,
Mono<? extends T5> p5) {
return when(Tuple.fn5(), p1, p2, p3, p4, p5);
}
/**
* Merge given monos into a new a {@literal Mono} that will be fulfilled when all of the given {@literal Mono Monos}
* have been fulfilled.
*
* <p>
* <img class="marble" src="https://raw.githubusercontent.com/reactor/projectreactor.io/master/src/main/static/assets/img/marble/whent.png" alt="">
* <p>
* @param p1 The first upstream {@link Publisher} to subscribe to.
* @param p2 The second upstream {@link Publisher} to subscribe to.
* @param p3 The third upstream {@link Publisher} to subscribe to.
* @param p4 The fourth upstream {@link Publisher} to subscribe to.
* @param p5 The fifth upstream {@link Publisher} to subscribe to.
* @param p6 The sixth upstream {@link Publisher} to subscribe to.
* @param <T1> type of the value from source1
* @param <T2> type of the value from source2
* @param <T3> type of the value from source3
* @param <T4> type of the value from source4
* @param <T5> type of the value from source5
* @param <T6> type of the value from source6
*
* @return a {@link Mono}.
*/
public static <T1, T2, T3, T4, T5, T6> Mono<Tuple6<T1, T2, T3, T4, T5, T6>> when(Mono<? extends T1> p1,
Mono<? extends T2> p2,
Mono<? extends T3> p3,
Mono<? extends T4> p4,
Mono<? extends T5> p5,
Mono<? extends T6> p6) {
return when(Tuple.fn6(), p1, p2, p3, p4, p5, p6);
}
/**
* Aggregate given monos into a new a {@literal Mono} that will be fulfilled when all of the given {@literal Mono
* Monos} have been fulfilled. If any Mono terminates without value, the returned sequence will be terminated immediately and pending results cancelled.
*
* <p>
* <img class="marble" src="https://raw.githubusercontent.com/reactor/projectreactor.io/master/src/main/static/assets/img/marble/whent.png" alt="">
* <p>
* @param monos The monos to use.
* @param <T> The type of the function result.
*
* @return a {@link Mono}.
*/
@SafeVarargs
@SuppressWarnings({"unchecked","varargs"})
private static <T> Mono<T[]> when(Mono<? extends T>... monos) {
return when(array -> (T[])array, monos);
}
/**
* Aggregate given monos into a new a {@literal Mono} that will be fulfilled when all of the given {@literal Mono
* Monos} have been fulfilled. If any Mono terminates without value, the returned sequence will be terminated immediately and pending results cancelled.
*
* <p>
* <img class="marble" src="https://raw.githubusercontent.com/reactor/projectreactor.io/master/src/main/static/assets/img/marble/when.png" alt="">
* <p>
* @param combinator the combinator {@link Function}
* @param monos The monos to use.
* @param <T> The super incoming type
* @param <V> The type of the function result.
*
* @return a {@link Mono}.
*/
@SafeVarargs
@SuppressWarnings({"varargs", "unchecked"})
private static <T, V> Mono<V> when(Function<? super Object[], ? extends V> combinator, Mono<? extends T>... monos) {
return MonoSource.wrap(new FluxZip<>(monos, combinator, QueueSupplier.one(), 1));
}
/**
* Aggregate given monos into a new a {@literal Mono} that will be fulfilled when all of the given {@literal Mono
* Monos} have been fulfilled. If any Mono terminates without value, the returned sequence will be terminated immediately and pending results cancelled.
*
* <p>
* <img class="marble" src="https://raw.githubusercontent.com/reactor/projectreactor.io/master/src/main/static/assets/img/marble/whent.png" alt="">
* <p>
*
* @param monos The monos to use.
* @param <T> The type of the function result.
*
* @return a {@link Mono}.
*/
@SuppressWarnings("unchecked")
public static <T> Mono<T[]> when(final Iterable<? extends Mono<? extends T>> monos) {
return when(array -> (T[])array, monos);
}
/**
* Aggregate given monos into a new a {@literal Mono} that will be fulfilled when all of the given {@literal Mono
* Monos} have been fulfilled. If any Mono terminates without value, the returned sequence will be terminated immediately and pending results cancelled.
*
* <p>
* <img class="marble" src="https://raw.githubusercontent.com/reactor/projectreactor.io/master/src/main/static/assets/img/marble/when.png" alt="">
* <p>
*
* @param combinator the combinator {@link Function}
* @param monos The monos to use.
* @param <T> The type of the function result.
* @param <V> The result type
*
* @return a {@link Mono}.
*/
@SuppressWarnings("unchecked")
public static <T, V> Mono<V> when(final Function<? super Object[], ? extends V> combinator, final Iterable<?
extends Mono<? extends T>> monos) {
return MonoSource.wrap(new FluxZip<>(monos, combinator, QueueSupplier.one(), 1));
}
// ==============================================================================================================
// Operators
// ==============================================================================================================
protected Mono() {
}
/**
* Transform this {@link Mono} into a target {@link Publisher}
*
* {@code mono.as(Flux::from).subscribe(Subscribers.unbounded()) }
*
* @param transformer the {@link Function} applying this {@link Mono}
* @param <P> the returned {@link Publisher} output
* @param <V> the element type of the returned Publisher
*
* @return the transformed {@link Mono}
*/
public final <V, P extends Publisher<V>> P as(Function<? super Mono<T>, P> transformer) {
return transformer.apply(this);
}
/**
* Combine the result from this mono and another into a {@link Tuple2}.
*
* <p>
* <img class="marble" src="https://raw.githubusercontent.com/reactor/projectreactor.io/master/src/main/static/assets/img/marble/and.png" alt="">
* <p>
* @param other the {@link Mono} to combine with
* @param <T2> the element type of the other Mono instance
*
* @return a new combined Mono
* @see #when
*/
public final <T2> Mono<Tuple2<T, T2>> and(Mono<? extends T2> other) {
return when(this, other);
}
/**
* Return a {@code Mono<Void>} which only listens for complete and error signals from this {@link Mono} completes.
*
* <p>
* <img class="marble" src="https://raw.githubusercontent.com/reactor/projectreactor.io/master/src/main/static/assets/img/marble/after1.png" alt="">
* <p>
* @return a {@link Mono} igoring its payload (actively dropping)
*/
public final Mono<Void> after() {
return empty(this);
}
/**
* Transform the terminal signal (error or completion) into {@code Mono<V>} that will emit at most one result in the
* returned {@link Mono}.
*
* <p>
* <img class="marble" src="https://raw.githubusercontent.com/reactor/projectreactor.io/master/src/main/static/assets/img/marble/afters1.png" alt="">
*
* @param other a {@link Mono} to emit from after termination
* @param <V> the element type of the supplied Mono
*
* @return a new {@link Mono} that emits from the supplied {@link Mono}
*/
public final <V> Mono<V> after(Mono<V> other) {
return after(() -> other);
}
/**
* Transform the terminal signal (error or completion) into {@code Mono<V>} that will emit at most one result in the
* returned {@link Mono}.
*
* <p>
* <img class="marble" src="https://raw.githubusercontent.com/reactor/projectreactor.io/master/src/main/static/assets/img/marble/afters1.png" alt="">
*
* @param sourceSupplier a {@link Supplier} of {@link Mono} to emit from after termination
* @param <V> the element type of the supplied Mono
*
* @return a new {@link Mono} that emits from the supplied {@link Mono}
*/
public final <V> Mono<V> after(final Supplier<? extends Mono<V>> sourceSupplier) {
return MonoSource.wrap(after().flatMap(null, null, sourceSupplier));
}
/**
* Transform the terminal signal (error or completion) into {@code Mono<V>} that will emit at most one result in the
* returned {@link Mono}.
*
* <p>
* <img class="marble" src="https://raw.githubusercontent.com/reactor/projectreactor.io/master/src/main/static/assets/img/marble/afters1.png" alt="">
*
* @param <V> the element type of the supplied Mono
* @param sourceSupplier a {@link Supplier} of {@link Mono} to emit from after termination
*
* @return a new {@link Mono} that emits from the supplied {@link Mono}
*/
public final <V> Mono<V> afterSuccessOrError(final Supplier<? extends Mono<V>> sourceSupplier) {
return MonoSource.wrap(after().flatMap(null,
throwable -> Flux.concat(sourceSupplier.get(), Mono .error(throwable)),
sourceSupplier));
}
/**
* Cast the current {@link Mono} produced type into a target produced type.
*
* <p>
* <img class="marble" src="https://raw.githubusercontent.com/reactor/projectreactor.io/master/src/main/static/assets/img/marble/cast1.png" alt="">
*
* @param <E> the {@link Mono} output type
* @param stream the target type to cast to
*
* @return a casted {@link Mono}
*/
@SuppressWarnings("unchecked")
public final <E> Mono<E> cast(Class<E> stream) {
return (Mono<E>) this;
}
/**
* Turn this {@link Mono} into a hot source and cache last emitted signals for further {@link Subscriber}.
* Completion and Error will also be replayed.
* <p>
* <img width="500" src="https://raw.githubusercontent.com/reactor/projectreactor.io/master/src/main/static/assets/img/marble/cache1.png"
* alt="">
*
* @return a replaying {@link Mono}
*/
public final Mono<T> cache() {
return new MonoProcessor<>(this);
}
/**
* Subscribe a {@link Consumer} to this {@link Mono} that will consume all the
* sequence.
* <p>
* For a passive version that observe and forward incoming data see {@link #doOnSuccess(Consumer)} and
* {@link #doOnError(java.util.function.Consumer)}.
*
* <p>
* <img class="marble" src="https://raw.githubusercontent.com/reactor/projectreactor.io/master/src/main/static/assets/img/marble/consume1.png" alt="">
*
* @param consumer the consumer to invoke on each value
*
* @return a new {@link Runnable} to dispose the {@link Subscription}
*/
public final Runnable consume(Consumer<? super T> consumer) {
return consume(consumer, null, null);
}
/**
* Subscribe {@link Consumer} to this {@link Mono} that will consume all the
* sequence.
* <p>
* For a passive version that observe and forward incoming data see {@link #doOnSuccess(Consumer)} and
* {@link #doOnError(java.util.function.Consumer)}.
*
* <p>
* <img class="marble" src="https://raw.githubusercontent.com/reactor/projectreactor.io/master/src/main/static/assets/img/marble/consumeerror1.png" alt="">
*
* @param consumer the consumer to invoke on each next signal
* @param errorConsumer the consumer to invoke on error signal
*
* @return a new {@link Runnable} to dispose the {@link Subscription}
*/
public final Runnable consume(Consumer<? super T> consumer, Consumer<? super Throwable> errorConsumer) {
return consume(consumer, errorConsumer, null);
}
/**
* Subscribe {@link Consumer} to this {@link Mono} that will consume all the
* sequence.
* <p>
* For a passive version that observe and forward incoming data see {@link #doOnSuccess(Consumer)} and
* {@link #doOnError(java.util.function.Consumer)}.
*
* <p>
* <img class="marble" src="https://raw.githubusercontent.com/reactor/projectreactor.io/master/src/main/static/assets/img/marble/consumecomplete1.png" alt="">
*
* @param consumer the consumer to invoke on each value
* @param errorConsumer the consumer to invoke on error signal
* @param completeConsumer the consumer to invoke on complete signal
*
* @return a new {@link Runnable} to dispose the {@link Subscription}
*/
public final Runnable consume(Consumer<? super T> consumer,
Consumer<? super Throwable> errorConsumer,
Runnable completeConsumer) {
return subscribeWith(new LambdaSubscriber<>(consumer, errorConsumer, completeConsumer));
}
/**
* Introspect this Mono graph
*
* @return {@literal ReactiveStateUtils.Graph} representation of a publisher graph
*/
public final ReactiveStateUtils.Graph debug() {
return ReactiveStateUtils.scan(this);
}
/**
* Provide a default unique value if this mono is completed without any data
*
* <p>
* <img class="marble" src="https://raw.githubusercontent.com/reactor/projectreactor.io/master/src/main/static/assets/img/marble/defaultifempty.png" alt="">
* <p>
* @param defaultV the alternate value if this sequence is empty
*
* @return a new {@link Mono}
*
* @see Flux#defaultIfEmpty(Object)
*/
public final Mono<T> defaultIfEmpty(T defaultV) {
return MonoSource.wrap(new FluxDefaultIfEmpty<T>(this, defaultV));
}
/**
* Delay the {@link Mono#subscribe(Subscriber) subscription} to this {@link Mono} source until the given
* period elapses.
*
* <p>
* <img class="marble" src="https://raw.githubusercontent.com/reactor/projectreactor.io/master/src/main/static/assets/img/marble/delaysubscription1.png" alt="">
*
* @param delay period in seconds before subscribing this {@link Mono}
*
* @return a delayed {@link Mono}
*
*/
public final Mono<T> delaySubscription(long delay) {
return delaySubscription(Duration.ofSeconds(delay));
}
/**
* Delay the {@link Mono#subscribe(Subscriber) subscription} to this {@link Mono} source until the given
* period elapses.
*
* <p>
* <img class="marble" src="https://raw.githubusercontent.com/reactor/projectreactor.io/master/src/main/static/assets/img/marble/delaysubscription1.png" alt="">
*
* @param delay duration before subscribing this {@link Mono}
*
* @return a delayed {@link Mono}
*
*/
public final Mono<T> delaySubscription(Duration delay) {
return delaySubscription(Mono.delay(delay));
}
/**
* Delay the subscription to this {@link Mono} until another {@link Publisher}
* signals a value or completes.
*
* <p>
* <img class="marble" src="https://raw.githubusercontent.com/reactor/projectreactor.io/master/src/main/static/assets/img/marble/delaysubscriptionp1.png" alt="">
*
* @param subscriptionDelay a
* {@link Publisher} to signal by next or complete this {@link Mono#subscribe(Subscriber)}
* @param <U> the other source type
*
* @return a delayed {@link Mono}
*
*/
public final <U> Mono<T> delaySubscription(Publisher<U> subscriptionDelay) {
return MonoSource.wrap(new FluxDelaySubscription<>(this, subscriptionDelay));
}
/**
* A "phantom-operator" working only if this
* {@link Mono} is a emits onNext, onError or onComplete {@link Signal}. The relative {@link Subscriber}
* callback will be invoked, error {@link Signal} will trigger onError and complete {@link Signal} will trigger
* onComplete.
*
* <p>
* <img class="marble" src="https://raw.githubusercontent.com/reactor/projectreactor.io/master/src/main/static/assets/img/marble/dematerialize1.png" alt="">
* @param <X> the dematerialized type
*
* @return a dematerialized {@link Mono}
*/
@SuppressWarnings("unchecked")
public final <X> Mono<X> dematerialize() {
Mono<Signal<X>> thiz = (Mono<Signal<X>>) this;
return MonoSource.wrap(new FluxDematerialize<>(thiz));
}
/**
* Run onNext, onComplete and onError on a supplied {@link Function} worker like {@link SchedulerGroup}.
*
* <p>
* <img class="marble" src="https://raw.githubusercontent.com/reactor/projectreactor.io/master/src/main/static/assets/img/marble/dispatchon1.png" alt="">
* <p> <p>
* Typically used for fast publisher, slow consumer(s) scenarios.
* It naturally combines with {@link SchedulerGroup#single} and {@link SchedulerGroup#async} which implement
* fast async event loops.
*
* {@code mono.dispatchOn(WorkQueueProcessor.create()).subscribe(Subscribers.unbounded()) }
*
* @param scheduler a checked {@link reactor.core.scheduler.Scheduler.Worker} factory
*
* @return an asynchronous {@link Mono}
*/
@SuppressWarnings("unchecked")
public final Mono<T> dispatchOn(Scheduler scheduler) {
if (this instanceof Fuseable.ScalarSupplier) {
T value = get();
return MonoSource.wrap(new FluxSubscribeOnValue<>(value, scheduler, true));
}
return MonoSource.wrap(new FluxDispatchOn(this, scheduler, false, 1, QueueSupplier.<T>one()));
}
/**
* Triggered after the {@link Mono} terminates, either by completing downstream successfully or with an error.
* The arguments will be null depending on success, success with data and error:
* <ul>
* <li>null, null : completed without data</li>
* <li>T, null : completed with data</li>
* <li>null, Throwable : failed with/without data</li>
* </ul>
*
* <p>
* <img class="marble" src="https://raw.githubusercontent.com/reactor/projectreactor.io/master/src/main/static/assets/img/marble/doafterterminate1.png" alt="">
* <p>
* @param afterTerminate the callback to call after {@link Subscriber#onNext}, {@link Subscriber#onComplete} without preceding {@link Subscriber#onNext} or {@link Subscriber#onError}
*
* @return a new {@link Mono}
*/
public final Mono<T> doAfterTerminate(BiConsumer<? super T, Throwable> afterTerminate) {
return new MonoSuccess<>(this, null, null, afterTerminate);
}
/**
* Triggered when the {@link Mono} is cancelled.
*
*
* <p>
* <img class="marble" src="https://raw.githubusercontent.com/reactor/projectreactor.io/master/src/main/static/assets/img/marble/dooncancel.png" alt="">
* <p>
* @param onCancel the callback to call on {@link Subscription#cancel()}
*
* @return a new {@link Mono}
*/
public final Mono<T> doOnCancel(Runnable onCancel) {
if (this instanceof Fuseable) {
return MonoSource.wrap(new FluxPeekFuseable<>(this, null, null, null, null, null, null, onCancel));
}
return MonoSource.wrap(new FluxPeek<>(this, null, null, null, null, null, null, onCancel));
}
/**
* Triggered when the {@link Mono} completes successfully.
*
* <ul>
* <li>null : completed without data</li>
* <li>T: completed with data</li>
* </ul>
*
* <p>
* <img class="marble" src="https://raw.githubusercontent.com/reactor/projectreactor.io/master/src/main/static/assets/img/marble/doonsuccess.png" alt="">
* <p>
* @param onSuccess the callback to call on
* {@link Subscriber#onNext} or {@link Subscriber#onComplete} without preceding {@link Subscriber#onNext}
*
* @return a new {@link Mono}
*/
public final Mono<T> doOnSuccess(Consumer<? super T> onSuccess) {
return new MonoSuccess<>(this, onSuccess, null, null);
}
/**
* Triggered when the {@link Mono} completes with an error.
*
* <p>
* <img class="marble" src="https://raw.githubusercontent.com/reactor/projectreactor.io/master/src/main/static/assets/img/marble/doonerror1.png" alt="">
* <p>
* @param onError the error callback to call on {@link Subscriber#onError(Throwable)}
*
* @return a new {@link Mono}
*/
public final Mono<T> doOnError(Consumer<? super Throwable> onError) {
if (this instanceof Fuseable) {
return MonoSource.wrap(new FluxPeekFuseable<>(this, null, null, onError, null, null, null, null));
}
return MonoSource.wrap(new FluxPeek<>(this, null, null, onError, null, null, null, null));
}
/**
* Attach a {@link LongConsumer} to this {@link Mono} that will observe any request to this {@link Mono}.
*
* <p>
* <img class="marble" src="https://raw.githubusercontent.com/reactor/projectreactor.io/master/src/main/static/assets/img/marble/doonrequest1.png" alt="">
*
* @param consumer the consumer to invoke on each request
*
* @return an observed {@link Mono}
*/
public final Mono<T> doOnRequest(final LongConsumer consumer) {
if (this instanceof Fuseable) {
return MonoSource.wrap(new FluxPeekFuseable<>(this, null, null, null, null, null, consumer, null));
}
return MonoSource.wrap(new FluxPeek<>(this, null, null, null, null, null, consumer, null));
}
/**
* Triggered when the {@link Mono} is subscribed.
*
* <p>
* <img class="marble" src="https://raw.githubusercontent.com/reactor/projectreactor.io/master/src/main/static/assets/img/marble/doonsubscribe.png" alt="">
* <p>
* @param onSubscribe the callback to call on {@link Subscriber#onSubscribe(Subscription)}
*
* @return a new {@link Mono}
*/
public final Mono<T> doOnSubscribe(Consumer<? super Subscription> onSubscribe) {
if (this instanceof Fuseable) {
return MonoSource.wrap(new FluxPeekFuseable<>(this, onSubscribe, null, null, null, null, null, null));
}
return MonoSource.wrap(new FluxPeek<>(this, onSubscribe, null, null, null, null, null, null));
}
/**
* Triggered when the {@link Mono} terminates, either by completing successfully or with an error.
*
* <ul>
* <li>null, null : completing without data</li>
* <li>T, null : completing with data</li>
* <li>null, Throwable : failing with/without data</li>
* </ul>
*
* <p>
* <img class="marble" src="https://raw.githubusercontent.com/reactor/projectreactor.io/master/src/main/static/assets/img/marble/doonterminate1.png" alt="">
* <p>
* @param onTerminate the callback to call {@link Subscriber#onNext}, {@link Subscriber#onComplete} without preceding {@link Subscriber#onNext} or {@link Subscriber#onError}
*
* @return a new {@link Mono}
*/
public final Mono<T> doOnTerminate(BiConsumer<? super T, Throwable> onTerminate) {
return new MonoSuccess<>(this, null, onTerminate, null);
}
/**
* Map this {@link Mono} sequence into {@link reactor.core.tuple.Tuple2} of T1 {@link Long} timemillis and T2
* {@link T} associated data. The timemillis corresponds to the elapsed time between the subscribe and the first
* next signal.
*
* <p>
* <img class="marble" src="https://raw.githubusercontent.com/reactor/projectreactor.io/master/src/main/static/assets/img/marble/elapsed1.png" alt="">
*
* @return a transforming {@link Mono} that emits a tuple of time elapsed in milliseconds and matching data
*/
public final Mono<Tuple2<Long, T>> elapsed() {
return MonoSource.wrap(new FluxElapsed<>(this));
}
/**
* Transform the items emitted by a {@link Publisher} into Publishers, then flatten the emissions from those by
* merging them into a single {@link Flux}, so that they may interleave.
*
* <p>
* <img class="marble" src="https://raw.githubusercontent.com/reactor/projectreactor.io/master/src/main/static/assets/img/marble/flatmap1.png" alt="">
* <p>
* @param mapper the
* {@link Function} to produce a sequence of R from the the eventual passed {@link Subscriber#onNext}
* @param <R> the merged sequence type
*
* @return a new {@link Flux} as the sequence is not guaranteed to be single at most
*/
public final <R> Flux<R> flatMap(Function<? super T, ? extends Publisher<? extends R>> mapper) {
return flatMap(mapper, PlatformDependent.SMALL_BUFFER_SIZE);
}
/**
* Transform the items emitted by a {@link Publisher} into Publishers, then flatten the emissions from those by
* merging them into a single {@link Flux}, so that they may interleave.
*
* <p>
* <img class="marble" src="https://raw.githubusercontent.com/reactor/projectreactor.io/master/src/main/static/assets/img/marble/flatmap1.png" alt="">
* <p>
* @param mapper the
* {@link Function} to produce a sequence of R from the the eventual passed {@link Subscriber#onNext}
* @param prefetch the inner source request size
* @param <R> the merged sequence type
*
* @return a new {@link Flux} as the sequence is not guaranteed to be single at most
*/
public final <R> Flux<R> flatMap(Function<? super T, ? extends Publisher<? extends R>> mapper, int prefetch) {
return new FluxFlatMap<>(
this,
mapper,
false,
Integer.MAX_VALUE,
QueueSupplier.one(),
prefetch,
QueueSupplier.get(prefetch)
);
}
/**
* Transform the signals emitted by this {@link Flux} into Publishers, then flatten the emissions from those by
* merging them into a single {@link Flux}, so that they may interleave.
*
* <p>
* <img class="marble" src="https://raw.githubusercontent.com/reactor/projectreactor.io/master/src/main/static/assets/img/marble/flatmaps1.png" alt="">
* <p>
* @param mapperOnNext the {@link Function} to call on next data and returning a sequence to merge
* @param mapperOnError the {@link Function} to call on error signal and returning a sequence to merge
* @param mapperOnComplete the {@link Function} to call on complete signal and returning a sequence to merge
* @param <R> the type of the produced merged sequence
*
* @return a new {@link Flux} as the sequence is not guaranteed to be single at most
*
* @see Flux#flatMap(Function, Function, Supplier)
*/
@SuppressWarnings("unchecked")
public final <R> Flux<R> flatMap(Function<? super T, ? extends Publisher<? extends R>> mapperOnNext,
Function<Throwable, ? extends Publisher<? extends R>> mapperOnError,
Supplier<? extends Publisher<? extends R>> mapperOnComplete) {
return new FluxFlatMap<>(
new FluxMapSignal<>(this, mapperOnNext, mapperOnError, mapperOnComplete),
Function.identity(),
false,
Integer.MAX_VALUE,
QueueSupplier.xs(),
PlatformDependent.XS_BUFFER_SIZE,
QueueSupplier.xs()
);
}
/**
* Convert this {@link Mono} to a {@link Flux}
*
* @return a {@link Flux} variant of this {@link Mono}
*/
public final Flux<T> flux() {
return FluxSource.wrap(this);
}
/**
* Block until a next signal is received, will return null if onComplete, T if onNext, throw a
* {@literal Exceptions.DownstreamException} if checked error or origin RuntimeException if unchecked.
* If the default timeout {@literal PlatformDependent#DEFAULT_TIMEOUT} has elapsed, a CancelException will be thrown.
*
* <p>
* <img class="marble" src="https://raw.githubusercontent.com/reactor/projectreactor.io/master/src/main/static/assets/img/marble/get.png" alt="">
* <p>
*
* @return T the result
*/
public T get() {
return get(PlatformDependent.DEFAULT_TIMEOUT);
}
/**
* Block until a next signal is received, will return null if onComplete, T if onNext, throw a
* {@literal Exceptions.DownstreamException} if checked error or origin RuntimeException if unchecked.
* If the default timeout {@literal PlatformDependent#DEFAULT_TIMEOUT} has elapsed, a CancelException will be thrown.
*
* Note that each get() will subscribe a new single (MonoResult) subscriber, in other words, the result might
* miss signal from hot publishers.
*
* <p>
* <img class="marble" src="https://raw.githubusercontent.com/reactor/projectreactor.io/master/src/main/static/assets/img/marble/get.png" alt="">
* <p>
*
* @param timeout maximum time period to wait for in milliseconds before raising a {@literal reactor.core.util.Exceptions.CancelException}
*
* @return T the result
*/
public T get(long timeout) {
if(this instanceof Supplier){
return get();
}
return subscribe().get(timeout);
}
/**
* Block until a next signal is received, will return null if onComplete, T if onNext, throw a
* {@literal Exceptions.DownstreamException} if checked error or origin RuntimeException if unchecked.
* If the default timeout {@literal PlatformDependent#DEFAULT_TIMEOUT} has elapsed, a CancelException will be thrown.
*
* Note that each get() will subscribe a new single (MonoResult) subscriber, in other words, the result might
* miss signal from hot publishers.
*
* <p>
* <img class="marble" src="https://raw.githubusercontent.com/reactor/projectreactor.io/master/src/main/static/assets/img/marble/get.png" alt="">
* <p>
*
* @param timeout maximum time period to wait for before raising a {@literal reactor.core.util.Exceptions.CancelException}
*
* @return T the result
*/
public T get(Duration timeout) {
return get(timeout.toMillis());
}
@Override
public final long getCapacity() {
return 1L;
}
@Override
public int getMode() {
return FACTORY;
}
@Override
public String getName() {
return getClass().getSimpleName()
.replace(Mono.class.getSimpleName(), "");
}
/**
* Emit a single boolean true if this {@link Mono} has an element.
*
* <p>
* <img class="marble" src="https://raw.githubusercontent.com/reactor/projectreactor.io/master/src/main/static/assets/img/marble/haselement.png" alt="">
*
* @return a new {@link Mono} with <code>true</code> if a value is emitted and <code>false</code>
* otherwise
*/
public final Mono<Boolean> hasElement() {
return new MonoHasElements<>(this);
}
/**
* Ignores onNext signal (dropping it) and only reacts on termination.
*
* <p>
* <img class="marble" src="https://raw.githubusercontent.com/reactor/projectreactor.io/master/src/main/static/assets/img/marble/ignoreelement.png" alt="">
* <p>
*
* @return a new completable {@link Mono}.
*/
public final Mono<T> ignoreElement() {
return ignoreElements(this);
}
/**
* Create a {@link Mono} intercepting all source signals with the returned Subscriber that might choose to pass them
* alone to the provided Subscriber (given to the returned {@code subscribe(Subscriber)}.
*
* <p>
* <img class="marble" src="https://raw.githubusercontent.com/reactor/projectreactor.io/master/src/main/static/assets/img/marble/lift1.png" alt="">
* <p>
* @param lifter the function accepting the target {@link Subscriber} and returning the {@link Subscriber}
* exposed this sequence
* @param <V> the output type
* @return a new lifted {@link Mono}
*
* @see Flux#lift
*/
public final <V> Mono<V> lift(Function<Subscriber<? super V>, Subscriber<? super T>> lifter) {
return new FluxLift.MonoLift<>(this, lifter);
}
/**
* Observe all Reactive Streams signals and use {@link Logger} support to handle trace implementation. Default will
* use {@link Level#INFO} and java.util.logging. If SLF4J is available, it will be used instead.
*
* Options allow fine grained filtering of the traced signal, for instance to only capture onNext and onError:
* <pre>
* mono.log("category", Level.INFO, Logger.ON_NEXT | LOGGER.ON_ERROR)
* <p>
* <img class="marble" src="https://raw.githubusercontent.com/reactor/projectreactor.io/master/src/main/static/assets/img/marble/log1.png" alt="">
* <p>
*
* @return a new {@link Mono}
*
* @see Flux#log()
*/
public final Mono<T> log() {
return log(null, Level.INFO, Logger.ALL);
}
/**
* Observe all Reactive Streams signals and use {@link Logger} support to handle trace implementation. Default will
* use {@link Level#INFO} and java.util.logging. If SLF4J is available, it will be used instead.
*
* Options allow fine grained filtering of the traced signal, for instance to only capture onNext and onError:
* <pre>
* mono.log("category", Level.INFO, Logger.ON_NEXT | LOGGER.ON_ERROR)
* <p>
* <img class="marble" src="https://raw.githubusercontent.com/reactor/projectreactor.io/master/src/main/static/assets/img/marble/log1.png" alt="">
* <p>
* @param category to be mapped into logger configuration (e.g. org.springframework.reactor).
*
* @return a new {@link Mono}
*/
public final Mono<T> log(String category) {
return log(category, Level.INFO, Logger.ALL);
}
/**
* Observe all Reactive Streams signals and use {@link Logger} support to handle trace implementation. Default will
* use the passed {@link Level} and java.util.logging. If SLF4J is available, it will be used instead.
*
* Options allow fine grained filtering of the traced signal, for instance to only capture onNext and onError:
* <pre>
* mono.log("category", Level.INFO, Logger.ON_NEXT | LOGGER.ON_ERROR)
* <p>
* <img class="marble" src="https://raw.githubusercontent.com/reactor/projectreactor.io/master/src/main/static/assets/img/marble/log1.png" alt="">
* <p>
* @param category to be mapped into logger configuration (e.g. org.springframework.reactor).
* @param level the level to enforce for this tracing Flux
*
* @return a new {@link Mono}
*/
public final Mono<T> log(String category, Level level) {
return log(category, level, Logger.ALL);
}
/**
* Observe Reactive Streams signals matching the passed flags {@code options} and use {@link Logger} support to
* handle trace
* implementation. Default will
* use the passed {@link Level} and java.util.logging. If SLF4J is available, it will be used instead.
*
* Options allow fine grained filtering of the traced signal, for instance to only capture onNext and onError:
* <pre>
* mono.log("category", Level.INFO, Logger.ON_NEXT | LOGGER.ON_ERROR)
* <p>
* <img class="marble" src="https://raw.githubusercontent.com/reactor/projectreactor.io/master/src/main/static/assets/img/marble/log1.png" alt="">
* <p>
* @param category to be mapped into logger configuration (e.g. org.springframework.reactor).
* @param level the level to enforce for this tracing Flux
* @param options a flag option that can be mapped with {@link Logger#ON_NEXT} etc.
*
* @return a new {@link Mono}
*
*/
public final Mono<T> log(String category, Level level, int options) {
return MonoSource.wrap(new FluxLog<>(this, category, level, options));
}
/**
* Transform the item emitted by this {@link Mono} by applying a function to item emitted.
*
* <p>
* <img class="marble" src="https://raw.githubusercontent.com/reactor/projectreactor.io/master/src/main/static/assets/img/marble/map1.png" alt="">
* <p>
* @param mapper the transforming function
* @param <R> the transformed type
*
* @return a new {@link Mono}
*/
public final <R> Mono<R> map(Function<? super T, ? extends R> mapper) {
if (this instanceof Fuseable) {
return MonoSource.wrap(new FluxMapFuseable<>(this, mapper));
}
return MonoSource.wrap(new FluxMap<>(this, mapper));
}
/**
* Transform the incoming onNext, onError and onComplete signals into {@link Signal}.
* Since the error is materialized as a {@code Signal}, the propagation will be stopped and onComplete will be
* emitted. Complete signal will first emit a {@code Signal.complete()} and then effectively complete the flux.
*
* <p>
* <img class="marble" src="https://raw.githubusercontent.com/reactor/projectreactor.io/master/src/main/static/assets/img/marble/materialize1.png" alt="">
*
* @return a {@link Mono} of materialized {@link Signal}
*/
public final Mono<Signal<T>> materialize() {
return new FluxMaterialize<>(this).next();
}
/**
* Merge emissions of this {@link Mono} with the provided {@link Publisher}.
*
* <p>
* <img class="marble" src="https://raw.githubusercontent.com/reactor/projectreactor.io/master/src/main/static/assets/img/marble/merge1.png" alt="">
* <p>
* @param other the other {@link Publisher} to merge with
*
* @return a new {@link Flux} as the sequence is not guaranteed to be at most 1
*/
@SuppressWarnings("unchecked")
public final Flux<T> mergeWith(Publisher<? extends T> other) {
return Flux.merge(this, other);
}
/**
* Emit the current instance of the {@link Mono}.
*
* <p>
* <img class="marble" src="https://raw.githubusercontent.com/reactor/projectreactor.io/master/src/main/static/assets/img/marble/nest1.png" alt="">
*
* @return a new {@link Mono} whose value will be the current {@link Mono}
*/
public final Mono<Mono<T>> nest() {
return just(this);
}
/**
* Emit the any of the result from this mono or from the given mono
*
* <p>
* <img class="marble" src="https://raw.githubusercontent.com/reactor/projectreactor.io/master/src/main/static/assets/img/marble/or.png" alt="">
* <p>
* @param other the racing other {@link Mono} to compete with for the result
*
* @return a new {@link Mono}
* @see #any
*/
public final Mono<T> or(Mono<? extends T> other) {
return any(this, other);
}
/**
* Subscribe to a returned fallback publisher when any error occurs.
*
* <p>
* <img class="marble" src="https://raw.githubusercontent.com/reactor/projectreactor.io/master/src/main/static/assets/img/marble/otherwise.png" alt="">
* <p>
* @param fallback the function to map an alternative {@link Mono}
*
* @return an alternating {@link Mono} on source onError
*
* @see Flux#onErrorResumeWith
*/
public final Mono<T> otherwise(Function<Throwable, ? extends Mono<? extends T>> fallback) {
return MonoSource.wrap(new FluxResume<>(this, fallback));
}
/**
* Provide an alternative {@link Mono} if this mono is completed without data
*
* <p>
* <img class="marble" src="https://raw.githubusercontent.com/reactor/projectreactor.io/master/src/main/static/assets/img/marble/otherwiseempty.png" alt="">
* <p>
* @param alternate the alternate mono if this mono is empty
*
* @return an alternating {@link Mono} on source onComplete without elements
* @see Flux#switchIfEmpty
*/
public final Mono<T> otherwiseIfEmpty(Mono<? extends T> alternate) {
return MonoSource.wrap(new FluxSwitchIfEmpty<>(this, alternate));
}
/**
* Subscribe to a returned fallback value when any error occurs.
*
* <p>
* <img class="marble" src="https://raw.githubusercontent.com/reactor/projectreactor.io/master/src/main/static/assets/img/marble/otherwisejust.png" alt="">
* <p>
* @param fallback the value to emit if an error occurs
*
* @return a new {@link Mono}
*
* @see Flux#onErrorReturn
*/
public final Mono<T> otherwiseJust(final T fallback) {
return otherwise(throwable -> just(fallback));
}
/**
* Run the requests to this Publisher {@link Mono} on a given worker thread like {@link SchedulerGroup}.
* <p>
* {@code mono.subscribeOn(SchedulerGroup.io()).subscribe(Subscribers.unbounded()) }
*
* <p>
* <img class="marble" src="https://raw.githubusercontent.com/reactor/projectreactor.io/master/src/main/static/assets/img/marble/subscribeon1.png" alt="">
* <p>
* @param scheduler a checked {@link reactor.core.scheduler.Scheduler.Worker} factory
*
* @return a new asynchronous {@link Mono}
*/
public final Mono<T> subscribeOn(Scheduler scheduler) {
return MonoSource.wrap(new FluxSubscribeOn<>(this, scheduler));
}
/**
* Repeatedly subscribe to this {@link Mono} until there is an onNext signal when a companion sequence signals a
* number of emitted elements.
* <p>If the companion sequence signals when this {@link Mono} is active, the repeat
* attempt is suppressed and any terminal signal will terminate this {@link Flux} with the same signal immediately.
*
* <p>
* <img class="marble" src="https://raw.githubusercontent.com/reactor/projectreactor.io/master/src/main/static/assets/img/marble/repeatwhenempty.png" alt="">
*
* @param repeatFactory the
* {@link Function} providing a {@link Flux} signalling the current number of repeat on onComplete and returning a {@link Publisher} companion.
*
* @return an eventually repeated {@link Mono} on onComplete when the companion {@link Publisher} produces an
* onNext signal
*
*/
public final Mono<T> repeatWhenEmpty(Function<Flux<Long>, ? extends Publisher<?>> repeatFactory) {
return repeatWhenEmpty(Integer.MAX_VALUE, repeatFactory);
}
/**
* Repeatedly subscribe to this {@link Mono} until there is an onNext signal when a companion sequence signals a
* number of emitted elements.
* <p>If the companion sequence signals when this {@link Mono} is active, the repeat
* attempt is suppressed and any terminal signal will terminate this {@link Flux} with the same signal immediately.
* <p>Emits an {@link IllegalStateException} if the max repeat is exceeded and different from {@code Integer.MAX_VALUE}.
*
* <p>
* <img class="marble" src="https://raw.githubusercontent.com/reactor/projectreactor.io/master/src/main/static/assets/img/marble/repeatwhen1.png" alt="">
*
* @param maxRepeat the maximum repeat number of time (infinite if {@code Integer.MAX_VALUE})
* @param repeatFactory the
* {@link Function} providing a {@link Flux} signalling the current repeat index from 0 on onComplete and returning a {@link Publisher} companion.
*
* @return an eventually repeated {@link Mono} on onComplete when the companion {@link Publisher} produces an
* onNext signal
*
*/
public final Mono<T> repeatWhenEmpty(int maxRepeat, Function<Flux<Long>, ? extends Publisher<?>> repeatFactory) {
return Mono.defer(() -> {
Flux<Long> iterations;
if(maxRepeat == Integer.MAX_VALUE) {
AtomicLong counter = new AtomicLong();
iterations = Flux
.generate((range, subscriber) -> LongStream
.range(0, range)
.forEach(l -> subscriber.onNext(counter.getAndIncrement())));
} else {
iterations = Flux
.range(0, maxRepeat)
.map(Integer::longValue)
.concatWith(Flux.error(new IllegalStateException("Exceeded maximum number of repeats"), true));
}
AtomicBoolean nonEmpty = new AtomicBoolean();
return Flux
.from(this
.doOnSuccess(e -> nonEmpty.lazySet(e != null)))
.repeatWhen(o -> repeatFactory
.apply(o
.takeWhile(e -> !nonEmpty.get())
.zipWith(iterations, 1, (c, i) -> i)))
.single();
});
}
/**
* Re-subscribes to this {@link Mono} sequence if it signals any error
* either indefinitely.
* <p>
* The times == Long.MAX_VALUE is treated as infinite retry.
*
* <p>
* <img class="marble" src="https://raw.githubusercontent.com/reactor/projectreactor.io/master/src/main/static/assets/img/marble/retry1.png" alt="">
*
* @return a re-subscribing {@link Mono} on onError
*/
public final Mono<T> retry() {
return retry(Long.MAX_VALUE);
}
/**
* Re-subscribes to this {@link Mono} sequence if it signals any error
* either indefinitely or a fixed number of times.
* <p>
* The times == Long.MAX_VALUE is treated as infinite retry.
*
* <p>
* <img class="marble" src="https://raw.githubusercontent.com/reactor/projectreactor.io/master/src/main/static/assets/img/marble/retryn1.png" alt="">
*
* @param numRetries the number of times to tolerate an error
*
* @return a re-subscribing {@link Mono} on onError up to the specified number of retries.
*
*/
public final Mono<T> retry(long numRetries) {
return MonoSource.wrap(new FluxRetry<T>(this, numRetries));
}
/**
* Re-subscribes to this {@link Mono} sequence if it signals any error
* and the given {@link Predicate} matches otherwise push the error downstream.
*
* <p>
* <img class="marble" src="https://raw.githubusercontent.com/reactor/projectreactor.io/master/src/main/static/assets/img/marble/retryb1.png" alt="">
*
* @param retryMatcher the predicate to evaluate if retry should occur based on a given error signal
*
* @return a re-subscribing {@link Mono} on onError if the predicates matches.
*/
public final Mono<T> retry(Predicate<Throwable> retryMatcher) {
return retryWhen(v -> v.filter(retryMatcher));
}
/**
* Re-subscribes to this {@link Mono} sequence up to the specified number of retries if it signals any
* error and the given {@link Predicate} matches otherwise push the error downstream.
*
* <p>
* <img class="marble" src="https://raw.githubusercontent.com/reactor/projectreactor.io/master/src/main/static/assets/img/marble/retrynb1.png" alt="">
*
* @param numRetries the number of times to tolerate an error
* @param retryMatcher the predicate to evaluate if retry should occur based on a given error signal
*
* @return a re-subscribing {@link Mono} on onError up to the specified number of retries and if the predicate
* matches.
*
*/
public final Mono<T> retry(long numRetries, Predicate<Throwable> retryMatcher) {
return retry(Flux.countingPredicate(retryMatcher, numRetries));
}
/**
* Retries this {@link Mono} when a companion sequence signals
* an item in response to this {@link Mono} error signal
* <p>If the companion sequence signals when the {@link Mono} is active, the retry
* attempt is suppressed and any terminal signal will terminate the {@link Mono} source with the same signal
* immediately.
*
* <p>
* <img class="marble" src="https://raw.githubusercontent.com/reactor/projectreactor.io/master/src/main/static/assets/img/marble/retrywhen1.png" alt="">
*
* @param whenFactory the {@link Function} providing a {@link Flux} signalling any error from the source sequence and returning a {@link Publisher} companion.
*
* @return a re-subscribing {@link Mono} on onError when the companion {@link Publisher} produces an
* onNext signal
*/
public final Mono<T> retryWhen(Function<Flux<Throwable>, ? extends Publisher<?>> whenFactory) {
return MonoSource.wrap(new FluxRetryWhen<T>(this, whenFactory));
}
/**
* Start the chain and request unbounded demand.
*
* <p>
* <img width="500" src="https://raw.githubusercontent.com/reactor/projectreactor.io/master/src/main/static/assets/img/marble/unbounded1.png" alt="">
* <p>
*
* @return a {@link Runnable} task to execute to dispose and cancel the underlying {@link Subscription}
*/
public final MonoProcessor<T> subscribe() {
MonoProcessor<T> s;
if(this instanceof MonoProcessor){
s = (MonoProcessor<T>)this;
}
else{
s = new MonoProcessor<>(this);
}
s.connect();
return s;
}
/**
* Subscribe the {@link Mono} with the givne {@link Subscriber} and return it.
*
* @param subscriber the {@link Subscriber} to subscribe
* @param <E> the reified type of the {@link Subscriber} for chaining
*
* @return the passed {@link Subscriber} after subscribing it to this {@link Mono}
*/
public final <E extends Subscriber<? super T>> E subscribeWith(E subscriber) {
subscribe(subscriber);
return subscriber;
}
/**
* Convert the value of {@link Mono} to another {@link Mono} possibly with another value type.
*
* <p>
* <img class="marble" src="https://raw.githubusercontent.com/reactor/projectreactor.io/master/src/main/static/assets/img/marble/then.png" alt="">
* <p>
* @param transformer the function to dynamically bind a new {@link Mono}
* @param <R> the result type bound
*
* @return a new {@link Mono} containing the merged values
*/
public final <R> Mono<R> then(Function<? super T, ? extends Mono<? extends R>> transformer) {
return MonoSource.wrap(flatMap(transformer));
}
/**
* Assign the given {@link Function} to transform the incoming value {@code T} into n {@code Mono<? extends T1>} and pass
* the result as a combined {@code Tuple}.
*
* <p>
* <img class="marble" src="https://raw.githubusercontent.com/reactor/projectreactor.io/master/src/main/static/assets/img/marble/thenn.png" alt="">
* <p>
* @param fn1 the transformation function
* @param fn2 the transformation function
* @param <T1> the type of the return value of the transformation function
* @param <T2> the type of the return value of the transformation function
*
* @return a new {@link Mono} containing the combined values
*/
public final <T1, T2> Mono<Tuple2<T1, T2>> then(
final Function<? super T, ? extends Mono<? extends T1>> fn1,
final Function<? super T, ? extends Mono<? extends T2>> fn2) {
return then(o -> when(fn1.apply(o), fn2.apply(o)));
}
/**
* Assign the given {@link Function} to transform the incoming value {@code T} into n {@code Mono<? extends T1>} and pass
* the result as a combined {@code Tuple}.
*
* <p>
* <img class="marble" src="https://raw.githubusercontent.com/reactor/projectreactor.io/master/src/main/static/assets/img/marble/thenn.png" alt="">
* <p>
* @param fn1 the transformation function
* @param fn2 the transformation function
* @param fn3 the transformation function
* @param <T1> the type of the return value of the transformation function
* @param <T2> the type of the return value of the transformation function
* @param <T3> the type of the return value of the transformation function
*
* @return a new {@link Mono} containing the combined values
*/
public final <T1, T2, T3> Mono<Tuple3<T1, T2, T3>> then(
final Function<? super T, ? extends Mono<? extends T1>> fn1,
final Function<? super T, ? extends Mono<? extends T2>> fn2,
final Function<? super T, ? extends Mono<? extends T3>> fn3) {
return then(o -> when(fn1.apply(o), fn2.apply(o), fn3.apply(o)));
}
/**
* Assign the given {@link Function} to transform the incoming value {@code T} into n {@code Mono<? extends T1>} and pass
* the result as a combined {@code Tuple}.
*
* <p>
* <img class="marble" src="https://raw.githubusercontent.com/reactor/projectreactor.io/master/src/main/static/assets/img/marble/thenn.png" alt="">
* <p>
* @param fn1 the transformation function
* @param fn2 the transformation function
* @param fn3 the transformation function
* @param fn4 the transformation function
* @param <T1> the type of the return value of the transformation function
* @param <T2> the type of the return value of the transformation function
* @param <T3> the type of the return value of the transformation function
* @param <T4> the type of the return value of the transformation function
*
* @return a new {@link Mono} containing the combined values
*
* @since 2.5
*/
public final <T1, T2, T3, T4> Mono<Tuple4<T1, T2, T3, T4>> then(
final Function<? super T, ? extends Mono<? extends T1>> fn1,
final Function<? super T, ? extends Mono<? extends T2>> fn2,
final Function<? super T, ? extends Mono<? extends T3>> fn3,
final Function<? super T, ? extends Mono<? extends T4>> fn4) {
return then(o -> when(fn1.apply(o), fn2.apply(o), fn3.apply(o), fn4.apply(o)));
}
/**
* Assign the given {@link Function} to transform the incoming value {@code T} into n {@code Mono<? extends T1>} and pass
* the result as a combined {@code Tuple}.
*
* <p>
* <img class="marble" src="https://raw.githubusercontent.com/reactor/projectreactor.io/master/src/main/static/assets/img/marble/thenn.png" alt="">
* <p>
* @param fn1 the transformation function
* @param fn2 the transformation function
* @param fn3 the transformation function
* @param fn4 the transformation function
* @param fn5 the transformation function
* @param <T1> the type of the return value of the transformation function
* @param <T2> the type of the return value of the transformation function
* @param <T3> the type of the return value of the transformation function
* @param <T4> the type of the return value of the transformation function
* @param <T5> the type of the return value of the transformation function
*
* @return a new {@link Mono} containing the combined values
*
*/
public final <T1, T2, T3, T4, T5> Mono<Tuple5<T1, T2, T3, T4, T5>> then(
final Function<? super T, ? extends Mono<? extends T1>> fn1,
final Function<? super T, ? extends Mono<? extends T2>> fn2,
final Function<? super T, ? extends Mono<? extends T3>> fn3,
final Function<? super T, ? extends Mono<? extends T4>> fn4,
final Function<? super T, ? extends Mono<? extends T5>> fn5) {
return then(o -> when(fn1.apply(o), fn2.apply(o), fn3.apply(o), fn4.apply(o), fn5.apply(o)));
}
/**
* Assign the given {@link Function} to transform the incoming value {@code T} into n {@code Mono<? extends T1>} and pass
* the result as a combined {@code Tuple}.
*
* <p>
* <img class="marble" src="https://raw.githubusercontent.com/reactor/projectreactor.io/master/src/main/static/assets/img/marble/thenn.png" alt="">
* <p>
* @param fn1 the transformation function
* @param fn2 the transformation function
* @param fn3 the transformation function
* @param fn4 the transformation function
* @param fn5 the transformation function
* @param fn6 the transformation function
* @param <T1> the type of the return value of the transformation function
* @param <T2> the type of the return value of the transformation function
* @param <T3> the type of the return value of the transformation function
* @param <T4> the type of the return value of the transformation function
* @param <T5> the type of the return value of the transformation function
* @param <T6> the type of the return value of the transformation function
*
* @return a new {@link Mono} containing the combined values
*
*/
public final <T1, T2, T3, T4, T5, T6> Mono<Tuple6<T1, T2, T3, T4, T5, T6>> then(
final Function<? super T, ? extends Mono<? extends T1>> fn1,
final Function<? super T, ? extends Mono<? extends T2>> fn2,
final Function<? super T, ? extends Mono<? extends T3>> fn3,
final Function<? super T, ? extends Mono<? extends T4>> fn4,
final Function<? super T, ? extends Mono<? extends T5>> fn5,
final Function<? super T, ? extends Mono<? extends T6>> fn6) {
return then(o -> when(fn1.apply(o), fn2.apply(o), fn3.apply(o), fn4.apply(o), fn5.apply(o), fn6.apply(o)));
}
/**
* Signal a {@link java.util.concurrent.TimeoutException} error in case an item doesn't arrive before the given period.
*
* <p>
* <img class="marble" src="https://raw.githubusercontent.com/reactor/projectreactor.io/master/src/main/static/assets/img/marble/timeouttime1.png" alt="">
*
* @param timeout the timeout before the onNext signal from this {@link Mono}
*
* @return an expirable {@link Mono}
*/
public final Mono<T> timeout(long timeout) {
return timeout(Duration.ofMillis(timeout), null);
}
/**
* Signal a {@link java.util.concurrent.TimeoutException} in case an item doesn't arrive before the given period.
*
* <p>
* <img class="marble" src="https://raw.githubusercontent.com/reactor/projectreactor.io/master/src/main/static/assets/img/marble/timeouttime1.png" alt="">
*
* @param timeout the timeout before the onNext signal from this {@link Mono}
*
* @return an expirable {@link Mono}
*/
public final Mono<T> timeout(Duration timeout) {
return timeout(timeout, null);
}
/**
* Switch to a fallback {@link Mono} in case an item doesn't arrive before the given period.
*
* <p> If the given {@link Publisher} is null, signal a {@link java.util.concurrent.TimeoutException}.
*
* <p>
* <img class="marble" src="https://raw.githubusercontent.com/reactor/projectreactor.io/master/src/main/static/assets/img/marble/timeouttimefallback1.png" alt="">
*
* @param timeout the timeout before the onNext signal from this {@link Mono}
* @param fallback the fallback {@link Mono} to subscribe when a timeout occurs
*
* @return an expirable {@link Mono} with a fallback {@link Mono}
*/
public final Mono<T> timeout(Duration timeout, Mono<? extends T> fallback) {
final Mono<Long> _timer = Mono.delay(timeout).otherwiseJust(0L);
final Function<T, Publisher<Long>> rest = o -> never();
if(fallback == null) {
return MonoSource.wrap(new FluxTimeout<>(this, _timer, rest));
}
return MonoSource.wrap(new FluxTimeout<>(this, _timer, rest, fallback));
}
/**
* Signal a {@link java.util.concurrent.TimeoutException} in case the item from this {@link Mono} has
* not been emitted before the given {@link Publisher} emits.
*
* <p>
* <img class="marble" src="https://raw.githubusercontent.com/reactor/projectreactor.io/master/src/main/static/assets/img/marble/timeoutp1.png" alt="">
*
* @param firstTimeout the timeout {@link Publisher} that must not emit before the first signal from this {@link Flux}
* @param <U> the element type of the timeout Publisher
*
* @return an expirable {@link Mono} if the first item does not come before a {@link Publisher} signal
*
*/
public final <U> Mono<T> timeout(Publisher<U> firstTimeout) {
return MonoSource.wrap(new FluxTimeout<>(this, firstTimeout, t -> never()));
}
/**
* Switch to a fallback {@link Publisher} in case the item from this {@link Mono} has
* not been emitted before the given {@link Publisher} emits. The following items will be individually timed via
* the factory provided {@link Publisher}.
*
* <p>
* <img class="marble" src="https://raw.githubusercontent.com/reactor/projectreactor.io/master/src/main/static/assets/img/marble/timeoutfallbackp1.png" alt="">
*
* @param firstTimeout the timeout
* {@link Publisher} that must not emit before the first signal from this {@link Mono}
* @param fallback the fallback {@link Publisher} to subscribe when a timeout occurs
* @param <U> the element type of the timeout Publisher
*
* @return a first then per-item expirable {@link Mono} with a fallback {@link Publisher}
*
*/
public final <U> Mono<T> timeout(Publisher<U> firstTimeout, Mono<? extends T> fallback) {
return MonoSource.wrap(new FluxTimeout<>(this, firstTimeout, t -> never(), fallback));
}
/**
* Emit a {@link reactor.core.tuple.Tuple2} pair of T1 {@link Long} current system time in
* millis and T2 {@link T} associated data for the eventual item from this {@link Mono}
*
* <p>
* <img class="marble" src="https://raw.githubusercontent.com/reactor/projectreactor.io/master/src/main/static/assets/img/marble/timestamp1.png" alt="">
*
* @return a timestamped {@link Mono}
*/
@SuppressWarnings("unchecked")
public final Mono<Tuple2<Long, T>> timestamp() {
return map(Flux.TIMESTAMP_OPERATOR);
}
/**
* Transform this {@link Mono} into a {@link CompletableFuture} completing on onNext or onComplete and failing on
* onError.
*
* <p>
* <img class="marble" src="https://raw.githubusercontent.com/reactor/projectreactor.io/master/src/main/static/assets/img/marble/tocompletablefuture.png" alt="">
* <p>
*
* @return a {@link CompletableFuture}
*/
public final CompletableFuture<T> toCompletableFuture() {
return subscribeWith(new MonoToCompletableFuture<>());
}
/**
* Test the result if any of this {@link Mono} and replay it if predicate returns true.
* Otherwise complete without value.
*
* <p>
* <img class="marble" src="https://raw.githubusercontent.com/reactor/projectreactor.io/master/src/main/static/assets/img/marble/where.png" alt="">
* <p>
* @param tester the predicate to evaluate
*
* @return a filtered {@link Mono}
*/
public final Mono<T> where(final Predicate<? super T> tester) {
if (this instanceof Fuseable) {
return MonoSource.wrap(new FluxFilterFuseable<>(this, tester));
}
return MonoSource.wrap(new FluxFilter<>(this, tester));
}
}
| fix #59
| src/main/java/reactor/core/publisher/Mono.java | fix #59 | <ide><path>rc/main/java/reactor/core/publisher/Mono.java
<ide> }
<ide>
<ide> /**
<add> * Concatenate emissions of this {@link Mono} with the provided {@link Publisher} (no interleave).
<add> * <p>
<add> * <img class="marble" src="https://raw.githubusercontent.com/reactor/projectreactor.io/master/src/main/static/assets/img/marble/concat.png" alt="">
<add> *
<add> * @param other the {@link Publisher} sequence to concat after this {@link Flux}
<add> *
<add> * @return a concatenated {@link Flux}
<add> */
<add> @SuppressWarnings("unchecked")
<add> public final Flux<T> concatWith(Publisher<? extends T> other) {
<add> return new FluxConcatArray<>(this, other);
<add> }
<add>
<add> /**
<ide> * Introspect this Mono graph
<ide> *
<ide> * @return {@literal ReactiveStateUtils.Graph} representation of a publisher graph |
|
Java | apache-2.0 | aa79c51f548f88b7f0e4e732f532870023c3e76f | 0 | jackygurui/redisson,zhoffice/redisson,redisson/redisson,mrniko/redisson | /**
* Copyright 2016 Nikita Koksharov
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.redisson.config;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.Reader;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.net.URI;
import java.net.URL;
import java.util.List;
import org.redisson.api.RedissonNodeInitializer;
import org.redisson.client.codec.Codec;
import org.redisson.cluster.ClusterConnectionManager;
import org.redisson.codec.CodecProvider;
import org.redisson.connection.ConnectionManager;
import org.redisson.connection.ElasticacheConnectionManager;
import org.redisson.connection.MasterSlaveConnectionManager;
import org.redisson.connection.ReplicatedConnectionManager;
import org.redisson.connection.SentinelConnectionManager;
import org.redisson.connection.SingleConnectionManager;
import org.redisson.connection.balancer.LoadBalancer;
import org.redisson.liveobject.provider.ResolverProvider;
import com.fasterxml.jackson.annotation.JsonFilter;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ser.FilterProvider;
import com.fasterxml.jackson.databind.ser.impl.SimpleBeanPropertyFilter;
import com.fasterxml.jackson.databind.ser.impl.SimpleFilterProvider;
import com.fasterxml.jackson.databind.type.TypeFactory;
import com.fasterxml.jackson.dataformat.yaml.YAMLFactory;
/**
*
* @author Nikita Koksharov
*
*/
public class ConfigSupport {
@JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, property = "class")
@JsonFilter("classFilter")
public static class ClassMixIn {
}
public abstract static class SingleSeverConfigMixIn {
@JsonProperty
List<URI> address;
@JsonIgnore
abstract SingleServerConfig setAddress(String address);
@JsonIgnore
abstract URI getAddress();
@JsonIgnore
abstract void setAddress(URI address);
}
public abstract static class MasterSlaveServersConfigMixIn {
@JsonProperty
List<URI> masterAddress;
@JsonIgnore
abstract MasterSlaveServersConfig setMasterAddress(String masterAddress);
@JsonIgnore
abstract URI getMasterAddress();
@JsonIgnore
abstract void setMasterAddress(URI masterAddress);
}
@JsonIgnoreProperties("clusterConfig")
public static class ConfigMixIn {
@JsonProperty
SentinelServersConfig sentinelServersConfig;
@JsonProperty
MasterSlaveServersConfig masterSlaveServersConfig;
@JsonProperty
SingleServerConfig singleServerConfig;
@JsonProperty
ClusterServersConfig clusterServersConfig;
@JsonProperty
ElasticacheServersConfig elasticacheServersConfig;
@JsonProperty
ReplicatedServersConfig replicatedServersConfig;
}
private ObjectMapper jsonMapper = createMapper(null, null);
private ObjectMapper yamlMapper = createMapper(new YAMLFactory(), null);
private void patchUriObject() throws IOException {
patchUriField("lowMask", "L_DASH");
patchUriField("highMask", "H_DASH");
}
private void patchUriField(String methodName, String fieldName)
throws IOException {
try {
Method lowMask = URI.class.getDeclaredMethod(methodName, String.class);
lowMask.setAccessible(true);
Long lowMaskValue = (Long) lowMask.invoke(null, "-_");
Field lowDash = URI.class.getDeclaredField(fieldName);
Field modifiers = Field.class.getDeclaredField("modifiers");
modifiers.setAccessible(true);
modifiers.setInt(lowDash, lowDash.getModifiers() & ~Modifier.FINAL);
lowDash.setAccessible(true);
lowDash.setLong(null, lowMaskValue);
} catch (Exception e) {
throw new IOException(e);
}
}
public <T> T fromJSON(String content, Class<T> configType) throws IOException {
patchUriObject();
return jsonMapper.readValue(content, configType);
}
public <T> T fromJSON(File file, Class<T> configType) throws IOException {
patchUriObject();
return fromJSON(file, configType, null);
}
public <T> T fromJSON(File file, Class<T> configType, ClassLoader classLoader) throws IOException {
patchUriObject();
jsonMapper = createMapper(null, classLoader);
return jsonMapper.readValue(file, configType);
}
public <T> T fromJSON(URL url, Class<T> configType) throws IOException {
patchUriObject();
return jsonMapper.readValue(url, configType);
}
public <T> T fromJSON(Reader reader, Class<T> configType) throws IOException {
patchUriObject();
return jsonMapper.readValue(reader, configType);
}
public <T> T fromJSON(InputStream inputStream, Class<T> configType) throws IOException {
patchUriObject();
return jsonMapper.readValue(inputStream, configType);
}
public String toJSON(Config config) throws IOException {
patchUriObject();
return jsonMapper.writeValueAsString(config);
}
public <T> T fromYAML(String content, Class<T> configType) throws IOException {
patchUriObject();
return yamlMapper.readValue(content, configType);
}
public <T> T fromYAML(File file, Class<T> configType) throws IOException {
patchUriObject();
return yamlMapper.readValue(file, configType);
}
public <T> T fromYAML(File file, Class<T> configType, ClassLoader classLoader) throws IOException {
patchUriObject();
yamlMapper = createMapper(new YAMLFactory(), classLoader);
return yamlMapper.readValue(file, configType);
}
public <T> T fromYAML(URL url, Class<T> configType) throws IOException {
patchUriObject();
return yamlMapper.readValue(url, configType);
}
public <T> T fromYAML(Reader reader, Class<T> configType) throws IOException {
patchUriObject();
return yamlMapper.readValue(reader, configType);
}
public <T> T fromYAML(InputStream inputStream, Class<T> configType) throws IOException {
patchUriObject();
return yamlMapper.readValue(inputStream, configType);
}
public String toYAML(Config config) throws IOException {
patchUriObject();
return yamlMapper.writeValueAsString(config);
}
public static ConnectionManager createConnectionManager(Config configCopy) {
if (configCopy.getMasterSlaveServersConfig() != null) {
validate(configCopy.getMasterSlaveServersConfig());
return new MasterSlaveConnectionManager(configCopy.getMasterSlaveServersConfig(), configCopy);
} else if (configCopy.getSingleServerConfig() != null) {
validate(configCopy.getSingleServerConfig());
return new SingleConnectionManager(configCopy.getSingleServerConfig(), configCopy);
} else if (configCopy.getSentinelServersConfig() != null) {
validate(configCopy.getSentinelServersConfig());
return new SentinelConnectionManager(configCopy.getSentinelServersConfig(), configCopy);
} else if (configCopy.getClusterServersConfig() != null) {
validate(configCopy.getClusterServersConfig());
return new ClusterConnectionManager(configCopy.getClusterServersConfig(), configCopy);
} else if (configCopy.getElasticacheServersConfig() != null) {
validate(configCopy.getElasticacheServersConfig());
return new ElasticacheConnectionManager(configCopy.getElasticacheServersConfig(), configCopy);
} else if (configCopy.getReplicatedServersConfig() != null) {
validate(configCopy.getReplicatedServersConfig());
return new ReplicatedConnectionManager(configCopy.getReplicatedServersConfig(), configCopy);
} else if (configCopy.getConnectionManager() != null) {
return configCopy.getConnectionManager();
}else {
throw new IllegalArgumentException("server(s) address(es) not defined!");
}
}
private static void validate(SingleServerConfig config) {
if (config.getConnectionPoolSize() < config.getConnectionMinimumIdleSize()) {
throw new IllegalArgumentException("connectionPoolSize can't be lower than connectionMinimumIdleSize");
}
}
private static void validate(BaseMasterSlaveServersConfig<?> config) {
if (config.getSlaveConnectionPoolSize() < config.getSlaveConnectionMinimumIdleSize()) {
throw new IllegalArgumentException("slaveConnectionPoolSize can't be lower than slaveConnectionMinimumIdleSize");
}
if (config.getMasterConnectionPoolSize() < config.getMasterConnectionMinimumIdleSize()) {
throw new IllegalArgumentException("masterConnectionPoolSize can't be lower than masterConnectionMinimumIdleSize");
}
if (config.getSubscriptionConnectionPoolSize() < config.getSubscriptionConnectionMinimumIdleSize()) {
throw new IllegalArgumentException("slaveSubscriptionConnectionMinimumIdleSize can't be lower than slaveSubscriptionConnectionPoolSize");
}
}
private ObjectMapper createMapper(JsonFactory mapping, ClassLoader classLoader) {
ObjectMapper mapper = new ObjectMapper(mapping);
mapper.addMixIn(MasterSlaveServersConfig.class, MasterSlaveServersConfigMixIn.class);
mapper.addMixIn(SingleServerConfig.class, SingleSeverConfigMixIn.class);
mapper.addMixIn(Config.class, ConfigMixIn.class);
mapper.addMixIn(CodecProvider.class, ClassMixIn.class);
mapper.addMixIn(ResolverProvider.class, ClassMixIn.class);
mapper.addMixIn(Codec.class, ClassMixIn.class);
mapper.addMixIn(RedissonNodeInitializer.class, ClassMixIn.class);
mapper.addMixIn(LoadBalancer.class, ClassMixIn.class);
FilterProvider filterProvider = new SimpleFilterProvider()
.addFilter("classFilter", SimpleBeanPropertyFilter.filterOutAllExcept());
mapper.setFilterProvider(filterProvider);
mapper.setSerializationInclusion(Include.NON_NULL);
if (classLoader != null) {
TypeFactory tf = TypeFactory.defaultInstance()
.withClassLoader(classLoader);
mapper.setTypeFactory(tf);
}
return mapper;
}
}
| redisson/src/main/java/org/redisson/config/ConfigSupport.java | /**
* Copyright 2016 Nikita Koksharov
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.redisson.config;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.Reader;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.net.URI;
import java.net.URL;
import java.util.List;
import org.redisson.api.RedissonNodeInitializer;
import org.redisson.client.codec.Codec;
import org.redisson.cluster.ClusterConnectionManager;
import org.redisson.codec.CodecProvider;
import org.redisson.connection.ConnectionManager;
import org.redisson.connection.ElasticacheConnectionManager;
import org.redisson.connection.MasterSlaveConnectionManager;
import org.redisson.connection.ReplicatedConnectionManager;
import org.redisson.connection.SentinelConnectionManager;
import org.redisson.connection.SingleConnectionManager;
import org.redisson.connection.balancer.LoadBalancer;
import org.redisson.liveobject.provider.ResolverProvider;
import com.fasterxml.jackson.annotation.JsonFilter;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ser.FilterProvider;
import com.fasterxml.jackson.databind.ser.impl.SimpleBeanPropertyFilter;
import com.fasterxml.jackson.databind.ser.impl.SimpleFilterProvider;
import com.fasterxml.jackson.databind.type.TypeFactory;
import com.fasterxml.jackson.dataformat.yaml.YAMLFactory;
/**
*
* @author Nikita Koksharov
*
*/
public class ConfigSupport {
@JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, property = "class")
@JsonFilter("classFilter")
public static class ClassMixIn {
}
public abstract static class SingleSeverConfigMixIn {
@JsonProperty
List<URI> address;
@JsonIgnore
abstract SingleServerConfig setAddress(String address);
@JsonIgnore
abstract URI getAddress();
@JsonIgnore
abstract void setAddress(URI address);
}
public abstract static class MasterSlaveServersConfigMixIn {
@JsonProperty
List<URI> masterAddress;
@JsonIgnore
abstract MasterSlaveServersConfig setMasterAddress(String masterAddress);
@JsonIgnore
abstract URI getMasterAddress();
@JsonIgnore
abstract void setMasterAddress(URI masterAddress);
}
@JsonIgnoreProperties("clusterConfig")
public static class ConfigMixIn {
@JsonProperty
SentinelServersConfig sentinelServersConfig;
@JsonProperty
MasterSlaveServersConfig masterSlaveServersConfig;
@JsonProperty
SingleServerConfig singleServerConfig;
@JsonProperty
ClusterServersConfig clusterServersConfig;
@JsonProperty
ElasticacheServersConfig elasticacheServersConfig;
@JsonProperty
ReplicatedServersConfig replicatedServersConfig;
}
private ObjectMapper jsonMapper = createMapper(null, null);
private ObjectMapper yamlMapper = createMapper(new YAMLFactory(), null);
private void patchUriObject() throws IOException {
patchUriField("lowMask", "L_DASH");
patchUriField("highMask", "H_DASH");
}
private void patchUriField(String methodName, String fieldName)
throws IOException {
try {
Method lowMask = URI.class.getDeclaredMethod(methodName, String.class);
lowMask.setAccessible(true);
long lowMaskValue = (long) lowMask.invoke(null, "-_");
Field lowDash = URI.class.getDeclaredField(fieldName);
Field modifiers = Field.class.getDeclaredField("modifiers");
modifiers.setAccessible(true);
modifiers.setInt(lowDash, lowDash.getModifiers() & ~Modifier.FINAL);
lowDash.setAccessible(true);
lowDash.setLong(null, lowMaskValue);
} catch (Exception e) {
throw new IOException(e);
}
}
public <T> T fromJSON(String content, Class<T> configType) throws IOException {
patchUriObject();
return jsonMapper.readValue(content, configType);
}
public <T> T fromJSON(File file, Class<T> configType) throws IOException {
patchUriObject();
return fromJSON(file, configType, null);
}
public <T> T fromJSON(File file, Class<T> configType, ClassLoader classLoader) throws IOException {
patchUriObject();
jsonMapper = createMapper(null, classLoader);
return jsonMapper.readValue(file, configType);
}
public <T> T fromJSON(URL url, Class<T> configType) throws IOException {
patchUriObject();
return jsonMapper.readValue(url, configType);
}
public <T> T fromJSON(Reader reader, Class<T> configType) throws IOException {
patchUriObject();
return jsonMapper.readValue(reader, configType);
}
public <T> T fromJSON(InputStream inputStream, Class<T> configType) throws IOException {
patchUriObject();
return jsonMapper.readValue(inputStream, configType);
}
public String toJSON(Config config) throws IOException {
patchUriObject();
return jsonMapper.writeValueAsString(config);
}
public <T> T fromYAML(String content, Class<T> configType) throws IOException {
patchUriObject();
return yamlMapper.readValue(content, configType);
}
public <T> T fromYAML(File file, Class<T> configType) throws IOException {
patchUriObject();
return yamlMapper.readValue(file, configType);
}
public <T> T fromYAML(File file, Class<T> configType, ClassLoader classLoader) throws IOException {
patchUriObject();
yamlMapper = createMapper(new YAMLFactory(), classLoader);
return yamlMapper.readValue(file, configType);
}
public <T> T fromYAML(URL url, Class<T> configType) throws IOException {
patchUriObject();
return yamlMapper.readValue(url, configType);
}
public <T> T fromYAML(Reader reader, Class<T> configType) throws IOException {
patchUriObject();
return yamlMapper.readValue(reader, configType);
}
public <T> T fromYAML(InputStream inputStream, Class<T> configType) throws IOException {
patchUriObject();
return yamlMapper.readValue(inputStream, configType);
}
public String toYAML(Config config) throws IOException {
patchUriObject();
return yamlMapper.writeValueAsString(config);
}
public static ConnectionManager createConnectionManager(Config configCopy) {
if (configCopy.getMasterSlaveServersConfig() != null) {
validate(configCopy.getMasterSlaveServersConfig());
return new MasterSlaveConnectionManager(configCopy.getMasterSlaveServersConfig(), configCopy);
} else if (configCopy.getSingleServerConfig() != null) {
validate(configCopy.getSingleServerConfig());
return new SingleConnectionManager(configCopy.getSingleServerConfig(), configCopy);
} else if (configCopy.getSentinelServersConfig() != null) {
validate(configCopy.getSentinelServersConfig());
return new SentinelConnectionManager(configCopy.getSentinelServersConfig(), configCopy);
} else if (configCopy.getClusterServersConfig() != null) {
validate(configCopy.getClusterServersConfig());
return new ClusterConnectionManager(configCopy.getClusterServersConfig(), configCopy);
} else if (configCopy.getElasticacheServersConfig() != null) {
validate(configCopy.getElasticacheServersConfig());
return new ElasticacheConnectionManager(configCopy.getElasticacheServersConfig(), configCopy);
} else if (configCopy.getReplicatedServersConfig() != null) {
validate(configCopy.getReplicatedServersConfig());
return new ReplicatedConnectionManager(configCopy.getReplicatedServersConfig(), configCopy);
} else if (configCopy.getConnectionManager() != null) {
return configCopy.getConnectionManager();
}else {
throw new IllegalArgumentException("server(s) address(es) not defined!");
}
}
private static void validate(SingleServerConfig config) {
if (config.getConnectionPoolSize() < config.getConnectionMinimumIdleSize()) {
throw new IllegalArgumentException("connectionPoolSize can't be lower than connectionMinimumIdleSize");
}
}
private static void validate(BaseMasterSlaveServersConfig<?> config) {
if (config.getSlaveConnectionPoolSize() < config.getSlaveConnectionMinimumIdleSize()) {
throw new IllegalArgumentException("slaveConnectionPoolSize can't be lower than slaveConnectionMinimumIdleSize");
}
if (config.getMasterConnectionPoolSize() < config.getMasterConnectionMinimumIdleSize()) {
throw new IllegalArgumentException("masterConnectionPoolSize can't be lower than masterConnectionMinimumIdleSize");
}
if (config.getSubscriptionConnectionPoolSize() < config.getSubscriptionConnectionMinimumIdleSize()) {
throw new IllegalArgumentException("slaveSubscriptionConnectionMinimumIdleSize can't be lower than slaveSubscriptionConnectionPoolSize");
}
}
private ObjectMapper createMapper(JsonFactory mapping, ClassLoader classLoader) {
ObjectMapper mapper = new ObjectMapper(mapping);
mapper.addMixIn(MasterSlaveServersConfig.class, MasterSlaveServersConfigMixIn.class);
mapper.addMixIn(SingleServerConfig.class, SingleSeverConfigMixIn.class);
mapper.addMixIn(Config.class, ConfigMixIn.class);
mapper.addMixIn(CodecProvider.class, ClassMixIn.class);
mapper.addMixIn(ResolverProvider.class, ClassMixIn.class);
mapper.addMixIn(Codec.class, ClassMixIn.class);
mapper.addMixIn(RedissonNodeInitializer.class, ClassMixIn.class);
mapper.addMixIn(LoadBalancer.class, ClassMixIn.class);
FilterProvider filterProvider = new SimpleFilterProvider()
.addFilter("classFilter", SimpleBeanPropertyFilter.filterOutAllExcept());
mapper.setFilterProvider(filterProvider);
mapper.setSerializationInclusion(Include.NON_NULL);
if (classLoader != null) {
TypeFactory tf = TypeFactory.defaultInstance()
.withClassLoader(classLoader);
mapper.setTypeFactory(tf);
}
return mapper;
}
}
| compilation fixed
| redisson/src/main/java/org/redisson/config/ConfigSupport.java | compilation fixed | <ide><path>edisson/src/main/java/org/redisson/config/ConfigSupport.java
<ide> try {
<ide> Method lowMask = URI.class.getDeclaredMethod(methodName, String.class);
<ide> lowMask.setAccessible(true);
<del> long lowMaskValue = (long) lowMask.invoke(null, "-_");
<add> Long lowMaskValue = (Long) lowMask.invoke(null, "-_");
<ide>
<ide> Field lowDash = URI.class.getDeclaredField(fieldName);
<ide> |
|
Java | mit | 9392458c5d9608baa03be1dc84ad54c42b5caa2c | 0 | remigourdon/sound-editors | package framework;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.SourceDataLine;
import java.util.Map;
import java.util.HashMap;
import java.util.ArrayList;
import framework.Sound;
/**
* Manage a list of Sound objects.
*
* This class provides methods to play, pause and mix different sounds.
*/
public class Player {
public Player() {
final AudioFormat af = new AudioFormat(
SAMPLE_RATE, BITS_PER_SAMPLE, 1, true, true);
try {
line = AudioSystem.getSourceDataLine(af);
line.open();
} catch(Exception e) {
e.printStackTrace();
}
playlist = new HashMap<Sound, Boolean>();
}
/**
* Add the specified Sound to the playlist.
* @param s the sound to be added
*/
public void addSound(Sound s) {
playlist.put(s, true);
}
/**
* Remove the specified Sound from the playlist.
* @param s the Sound to be removed
*/
public void removeSound(Sound s) {
playlist.remove(s);
}
/**
* Toggle a Sound inside the playlist.
*
* If its value is true, it is added to the mix.
* If its value is false, it is muted.
* @param s the Sound to be toggled
*/
public void toggleSound(Sound s) {
if(playlist.get(s) != null)
playlist.put(s, !playlist.get(s));
}
/**
* Mix the Sound objects contains in the list.
* @param l the list of Sound objects to be mixed
* @return the byte array containing the mix
*/
public byte[] mix(ArrayList<Sound> l) {
int maxDuration = 0;
for(Sound s : l) {
if(s.getDuration() > maxDuration)
maxDuration = s.getDuration();
}
byte[] result = new byte[maxDuration * SAMPLE_RATE];
for(int i = 0; i < result.length; i++) {
ArrayList<Sound> done = new ArrayList<Sound>();
for(Sound s : l) {
result[i] = (byte)(s.getData()[i] + result[i]);
if(i + 1 >= s.getData().length)
done.add(s);
}
l.removeAll(done);
}
return result;
}
/**
* Play all the Sound objects which are not muted.
*/
public void play() {
ArrayList<Sound> selection = new ArrayList<Sound>();
for(Map.Entry<Sound, Boolean> entry : playlist.entrySet()) {
if(entry.getValue())
selection.add(entry.getKey());
}
byte[] theMix = mix(selection);
line.start();
line.write(theMix, 0, theMix.length);
line.stop();
line.drain();
}
private SourceDataLine line;
private HashMap<Sound, Boolean> playlist;
// Constants
private final int SAMPLE_RATE = 44100; // CD quality audio
private final int BITS_PER_SAMPLE = 16;
} | framework/Player.java | package framework;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.SourceDataLine;
import java.util.Map;
import java.util.HashMap;
import java.util.ArrayList;
import framework.Sound;
/**
* Manage a list of Sound objects.
*
* This class provides methods to play, pause and mix different sounds.
*/
public class Player {
public Player() {
final AudioFormat af = new AudioFormat(
SAMPLE_RATE, BITS_PER_SAMPLE, 1, true, true);
try {
line = AudioSystem.getSourceDataLine(af);
line.open();
} catch(Exception e) {
e.printStackTrace();
}
playlist = new HashMap<Sound, Boolean>();
}
/**
* Add the specified Sound to the playlist.
* @param s the sound to be added
*/
public void addSound(Sound s) {
playlist.put(s, true);
}
/**
* Remove the specified Sound from the playlist.
* @param s the Sound to be removed
*/
public void removeSound(Sound s) {
playlist.remove(s);
}
/**
* Toggle a Sound inside the playlist.
*
* If its value is true, it is added to the mix.
* If its value is false, it is muted.
* @param s the Sound to be toggled
*/
public void toggleSound(Sound s) {
if(playlist.get(s) != null)
playlist.put(s, !playlist.get(s));
}
/**
* Mix the Sound objects contains in the list.
* @param l the list of Sound objects to be mixed
* @return the byte array containing the mix
*/
public byte[] mix(ArrayList<Sound> l) {
int maxDuration = 0;
for(Sound s : l) {
if(s.getDuration() > maxDuration)
maxDuration = s.getDuration();
}
byte[] result = new byte[maxDuration * SAMPLE_RATE];
for(int i = 0; i < result.length; i++) {
ArrayList<Sound> done = new ArrayList<Sound>();
for(Sound s : l) {
result[i] = (byte)(s.getData()[i] + result[i]);
if(i + 1 >= s.getData().length)
done.add(s);
}
l.removeAll(done);
}
return result;
}
/**
* Play all the Sound objects which are not muted.
*/
public void play() {
ArrayList<Sound> selection = new ArrayList<Sound>();
for(Map.Entry<Sound, Boolean> entry : playlist.entrySet()) {
if(entry.getValue())
selection.add(entry.getKey());
}
byte[] theMix = mix(selection);
line.write(theMix, 0, theMix.length);
}
private SourceDataLine line;
private HashMap<Sound, Boolean> playlist;
// Constants
private final int SAMPLE_RATE = 44100; // CD quality audio
private final int BITS_PER_SAMPLE = 16;
} | Add code to start the audio line, stop it and drain it.
| framework/Player.java | Add code to start the audio line, stop it and drain it. | <ide><path>ramework/Player.java
<ide> }
<ide>
<ide> byte[] theMix = mix(selection);
<add> line.start();
<ide> line.write(theMix, 0, theMix.length);
<add> line.stop();
<add> line.drain();
<ide> }
<ide>
<ide> private SourceDataLine line; |
|
Java | mit | error: pathspec 'LARDTestTest/src/ca/ualberta/lard/test/NewEditCommentActivityTests.java' did not match any file(s) known to git
| 173d001bd346bda9a8237bb70a9c1391ba985577 | 1 | CMPUT301W14T06/LARD | package ca.ualberta.lard.test;
import ca.ualberta.lard.NewEditCommentActivity;
import android.test.ActivityInstrumentationTestCase2;
/**
* JUnit tests for NewCommentActivity. Tests that the correct parent id is received. Also
* tests user interaction with the UI (attaching a picture, changing location, inputting
* text for the comment).
*/
public class NewEditCommentActivityTests extends ActivityInstrumentationTestCase2<NewEditCommentActivity> {
public NewEditCommentActivityTests() {
super(NewEditCommentActivity.class);
}
/*public void testParentIDExists() {
Intent intent = new Intent();
String value = "Test";
intent.putExtra(NewCommentActivity.PARENT_STRING, value);
setActivityIntent(intent);
NewCommentActivity activity = getActivity();
assertEquals("NewCommentActivity should get the value from intent", value, activity, activity.getPid());
}
public void testParentIDNotExists() {
Intent intent = new Intent();
setActivityIntent(intent);
NewCommentActivity activity = getActivity();
assertEquals("NewCommentActivity should get the value from intent", null, activity.getPid());
}
public void testPictureDefault() {
Intent intent = new Intent();
setActivityIntent(intent);
NewCommentActivity activity = getActivity();
assertTrue("NewCommentActivity should by default have no picture", activity.getPicture().isNull());
}
public void testGeoLocationDefault() {
Intent intent = new Intent();
setActivityIntent(intent);
NewCommentActivity activity = getActivity();
GeoLocation loc = new GeoLocation(activity);
assertEquals("NewCommentActivity should by default have a default location", loc.getLatitude(), activity.getGeoLocation().getLatitude());
assertEquals("NewCommentActivity should by default have a default location", loc.getLongitude(), activity.getGeoLocation().getLongitude());
}*/
}
/*package ca.ualberta.lard.test;
import android.content.Context;
import android.content.Intent;
import android.test.ActivityInstrumentationTestCase2;
import ca.ualberta.lard.EditCommentActivity;
import ca.ualberta.lard.model.Comment;
public class EditCommentActivityTests extends ActivityInstrumentationTestCase2<EditCommentActivity> {
private Comment comment;
private String id;
private EditCommentActivity activity;
private Intent intent;
public EditCommentActivityTests() {
super(EditCommentActivity.class);
}
protected void setUp() throws Exception {
super.setUp();
Context context = this.getInstrumentation().getTargetContext().getApplicationContext();
comment = new Comment("This is a comment.", context);
id = comment.getId();
// Pass the activity the id
intent = new Intent();
intent.putExtra(EditCommentActivity.EXTRA_COMMENT_ID, id);
setActivityIntent(intent);
activity = getActivity();
}
protected void tearDown() throws Exception {
super.tearDown();
comment = null;
id = null;
intent = null;
activity = null;
}
*//**
* Tests that when the activity is started, a comment id is received.
*//*
public void testReceiveId() {
String passedId = (String)activity.getIntent().getStringExtra(EditCommentActivity.EXTRA_COMMENT_ID);
assertEquals("Should receive an id from the intent.", id, passedId);
}
*//**
* Tests that when the user changes the comment author, the comment author
* is updated. Changing to an empty author should update the author to Anonymous.
*//*
public void testChangeAuthor() {
fail();
}
*//**
* Tests that when the user changes the comment body text, the body text is
* updated. Changing to an empty body text should update the text to say
* [Comment Text Removed].
*//*
public void testChangeBodyText() {
fail();
}
*//**
* Tests that when the user attaches a new picture, the picture is updated.
* Removing a picture should display "Picture removed".
*//*
public void testChangePicture() {
fail();
}
*//**
* Tests that when the user changes the location, LocationSelectionsActivity is opened
* and that location is updated.
*//*
public void testChangeLocation() {
fail();
}
}*/
| LARDTestTest/src/ca/ualberta/lard/test/NewEditCommentActivityTests.java | lots of small formatting changes were made
| LARDTestTest/src/ca/ualberta/lard/test/NewEditCommentActivityTests.java | lots of small formatting changes were made | <ide><path>ARDTestTest/src/ca/ualberta/lard/test/NewEditCommentActivityTests.java
<add>package ca.ualberta.lard.test;
<add>
<add>import ca.ualberta.lard.NewEditCommentActivity;
<add>import android.test.ActivityInstrumentationTestCase2;
<add>
<add>/**
<add> * JUnit tests for NewCommentActivity. Tests that the correct parent id is received. Also
<add> * tests user interaction with the UI (attaching a picture, changing location, inputting
<add> * text for the comment).
<add> */
<add>
<add>public class NewEditCommentActivityTests extends ActivityInstrumentationTestCase2<NewEditCommentActivity> {
<add>
<add> public NewEditCommentActivityTests() {
<add> super(NewEditCommentActivity.class);
<add> }
<add>
<add> /*public void testParentIDExists() {
<add> Intent intent = new Intent();
<add> String value = "Test";
<add> intent.putExtra(NewCommentActivity.PARENT_STRING, value);
<add> setActivityIntent(intent);
<add> NewCommentActivity activity = getActivity();
<add> assertEquals("NewCommentActivity should get the value from intent", value, activity, activity.getPid());
<add> }
<add>
<add> public void testParentIDNotExists() {
<add> Intent intent = new Intent();
<add> setActivityIntent(intent);
<add> NewCommentActivity activity = getActivity();
<add> assertEquals("NewCommentActivity should get the value from intent", null, activity.getPid());
<add> }
<add>
<add> public void testPictureDefault() {
<add> Intent intent = new Intent();
<add> setActivityIntent(intent);
<add> NewCommentActivity activity = getActivity();
<add> assertTrue("NewCommentActivity should by default have no picture", activity.getPicture().isNull());
<add> }
<add>
<add> public void testGeoLocationDefault() {
<add> Intent intent = new Intent();
<add> setActivityIntent(intent);
<add> NewCommentActivity activity = getActivity();
<add> GeoLocation loc = new GeoLocation(activity);
<add> assertEquals("NewCommentActivity should by default have a default location", loc.getLatitude(), activity.getGeoLocation().getLatitude());
<add> assertEquals("NewCommentActivity should by default have a default location", loc.getLongitude(), activity.getGeoLocation().getLongitude());
<add> }*/
<add>
<add>}
<add>
<add>/*package ca.ualberta.lard.test;
<add>
<add>import android.content.Context;
<add>import android.content.Intent;
<add>import android.test.ActivityInstrumentationTestCase2;
<add>import ca.ualberta.lard.EditCommentActivity;
<add>import ca.ualberta.lard.model.Comment;
<add>
<add>public class EditCommentActivityTests extends ActivityInstrumentationTestCase2<EditCommentActivity> {
<add> private Comment comment;
<add> private String id;
<add> private EditCommentActivity activity;
<add> private Intent intent;
<add>
<add> public EditCommentActivityTests() {
<add> super(EditCommentActivity.class);
<add> }
<add>
<add> protected void setUp() throws Exception {
<add> super.setUp();
<add> Context context = this.getInstrumentation().getTargetContext().getApplicationContext();
<add> comment = new Comment("This is a comment.", context);
<add> id = comment.getId();
<add>
<add> // Pass the activity the id
<add> intent = new Intent();
<add> intent.putExtra(EditCommentActivity.EXTRA_COMMENT_ID, id);
<add>
<add> setActivityIntent(intent);
<add> activity = getActivity();
<add> }
<add>
<add> protected void tearDown() throws Exception {
<add> super.tearDown();
<add> comment = null;
<add> id = null;
<add> intent = null;
<add> activity = null;
<add> }
<add>
<add> *//**
<add> * Tests that when the activity is started, a comment id is received.
<add> *//*
<add> public void testReceiveId() {
<add> String passedId = (String)activity.getIntent().getStringExtra(EditCommentActivity.EXTRA_COMMENT_ID);
<add> assertEquals("Should receive an id from the intent.", id, passedId);
<add> }
<add>
<add> *//**
<add> * Tests that when the user changes the comment author, the comment author
<add> * is updated. Changing to an empty author should update the author to Anonymous.
<add> *//*
<add> public void testChangeAuthor() {
<add> fail();
<add> }
<add>
<add> *//**
<add> * Tests that when the user changes the comment body text, the body text is
<add> * updated. Changing to an empty body text should update the text to say
<add> * [Comment Text Removed].
<add> *//*
<add> public void testChangeBodyText() {
<add> fail();
<add> }
<add>
<add> *//**
<add> * Tests that when the user attaches a new picture, the picture is updated.
<add> * Removing a picture should display "Picture removed".
<add> *//*
<add> public void testChangePicture() {
<add> fail();
<add> }
<add>
<add> *//**
<add> * Tests that when the user changes the location, LocationSelectionsActivity is opened
<add> * and that location is updated.
<add> *//*
<add> public void testChangeLocation() {
<add> fail();
<add> }
<add>}*/ |
|
Java | mit | b1ddafa1d1218472eae1509fd0e47c549a7fe7a6 | 0 | gems-uff/dyevc,gems-uff/dyevc | package br.uff.ic.dyevc.monitor;
//~--- non-JDK imports --------------------------------------------------------
import br.uff.ic.dyevc.application.IConstants;
import br.uff.ic.dyevc.exception.DyeVCException;
import br.uff.ic.dyevc.exception.MonitorException;
import br.uff.ic.dyevc.exception.RepositoryReferencedException;
import br.uff.ic.dyevc.exception.ServiceException;
import br.uff.ic.dyevc.gui.core.MessageManager;
import br.uff.ic.dyevc.model.CommitInfo;
import br.uff.ic.dyevc.model.MonitoredRepositories;
import br.uff.ic.dyevc.model.MonitoredRepository;
import br.uff.ic.dyevc.model.topology.CommitFilter;
import br.uff.ic.dyevc.model.topology.RepositoryInfo;
import br.uff.ic.dyevc.model.topology.Topology;
import br.uff.ic.dyevc.persistence.CommitDAO;
import br.uff.ic.dyevc.persistence.TopologyDAO;
import br.uff.ic.dyevc.tools.vcs.git.GitCommitTools;
import br.uff.ic.dyevc.utils.RepositoryConverter;
import br.uff.ic.dyevc.utils.SystemUtils;
import org.apache.commons.collections15.CollectionUtils;
import org.eclipse.jgit.transport.URIish;
import org.slf4j.LoggerFactory;
//~--- JDK imports ------------------------------------------------------------
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectInputStream;
import java.io.ObjectOutput;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
/**
* This class updates the topology.
*
* @author Cristiano
*/
public class TopologyUpdater {
private final TopologyDAO topologyDAO;
private final CommitDAO commitDAO;
private Topology topology;
private final MonitoredRepositories monitoredRepositories;
private RepositoryConverter converter;
private MonitoredRepository repositoryToUpdate;
private GitCommitTools tools;
/**
* Creates a new object of this type.
*/
public TopologyUpdater() {
LoggerFactory.getLogger(TopologyUpdater.class).trace("Constructor -> Entry.");
topologyDAO = new TopologyDAO();
commitDAO = new CommitDAO();
this.monitoredRepositories = MonitoredRepositories.getInstance();
LoggerFactory.getLogger(TopologyUpdater.class).trace("Constructor -> Exit.");
}
/**
* Updates the topology.
*
* @param repositoryToUpdate the repository to be updated
*/
public void update(MonitoredRepository repositoryToUpdate) {
LoggerFactory.getLogger(TopologyUpdater.class).trace("Topology updater is running.");
if (!repositoryToUpdate.hasSystemName()) {
MessageManager.getInstance().addMessage("Repository <" + repositoryToUpdate.getName() + "> with id <"
+ repositoryToUpdate.getId()
+ "> has no system name configured and will not be added to the topology.");
return;
}
this.repositoryToUpdate = repositoryToUpdate;
this.converter = new RepositoryConverter(repositoryToUpdate);
MessageManager.getInstance().addMessage("Updating topology for repository <" + repositoryToUpdate.getId()
+ "> with id <" + repositoryToUpdate.getName() + ">");
updateRepositoryTopology();
updateCommitTopology();
MessageManager.getInstance().addMessage("Finished update topology for repository <"
+ repositoryToUpdate.getId() + "> with id <" + repositoryToUpdate.getName() + ">");
LoggerFactory.getLogger(TopologyUpdater.class).trace("Topology updater finished running.");
}
/**
* Updates the topology for the specified repository in the database, including any new referenced repositories that
* do not yet exist and refreshes local topology cache.
*
* @see RepositoryConverter
*/
private void updateRepositoryTopology() {
LoggerFactory.getLogger(TopologyUpdater.class).trace("updateRepositoryTopology -> Entry.");
String systemName = repositoryToUpdate.getSystemName();
// TODO implement lock mechanism
try {
topology = topologyDAO.readTopologyForSystem(systemName);
RepositoryInfo localRepositoryInfo = converter.toRepositoryInfo();
RepositoryInfo remoteRepositoryInfo = topology.getRepositoryInfo(systemName, localRepositoryInfo.getId());
/*
* changedLocally is used to flag any changes to repository info. If any changes were detected by the end of the
* method, then the repository is updated in database. It is initialized with true if the repository info
* does not exist in the database.
*/
boolean changedLocally = remoteRepositoryInfo == null;
if (!changedLocally) {
// localRepositoryInfo already exists in the topology, then gets the list of hosts that monitor it
localRepositoryInfo.setMonitoredBy(remoteRepositoryInfo.getMonitoredBy());
} else {
localRepositoryInfo.addMonitoredBy(SystemUtils.getLocalHostname());
}
if (!changedLocally) {
// check whether this computer must be added or removed from the monitoredby list.
Set<String> monitoredBy = localRepositoryInfo.getMonitoredBy();
String hostname = SystemUtils.getLocalHostname();
if (repositoryToUpdate.isMarkedForDeletion()) {
changedLocally |= monitoredBy.remove(hostname);
} else {
changedLocally |= monitoredBy.add(hostname);
}
}
if (!changedLocally) {
// Checks if the pullsFrom list must be updated
Collection<String> insertedPullsFrom = CollectionUtils.subtract(localRepositoryInfo.getPullsFrom(),
remoteRepositoryInfo.getPullsFrom());
Collection<String> removedPullsFrom = CollectionUtils.subtract(remoteRepositoryInfo.getPullsFrom(),
localRepositoryInfo.getPullsFrom());
changedLocally |= !insertedPullsFrom.isEmpty();
changedLocally |= !removedPullsFrom.isEmpty();
}
if (!changedLocally) {
// Checks if the pushesTo list must be updated
Collection<String> insertedPushesTo = CollectionUtils.subtract(localRepositoryInfo.getPushesTo(),
remoteRepositoryInfo.getPushesTo());
Collection<String> removedPushesTo = CollectionUtils.subtract(remoteRepositoryInfo.getPushesTo(),
localRepositoryInfo.getPushesTo());
changedLocally |= !insertedPushesTo.isEmpty();
changedLocally |= !removedPushesTo.isEmpty();
}
if (changedLocally) {
Date lastChanged = topologyDAO.upsertRepository(converter.toRepositoryInfo());
topologyDAO.upsertRepositories(converter.getRelatedNewList());
repositoryToUpdate.setLastChanged(lastChanged);
topology = topologyDAO.readTopologyForSystem(repositoryToUpdate.getSystemName());
}
} catch (DyeVCException dex) {
MessageManager.getInstance().addMessage("Error updating repository<" + repositoryToUpdate.getName()
+ "> with id<" + repositoryToUpdate.getId() + ">\n\t" + dex.getMessage());
} catch (RuntimeException re) {
MessageManager.getInstance().addMessage("Error updating repository<" + repositoryToUpdate.getName()
+ "> with id<" + repositoryToUpdate.getId() + ">\n\t" + re.getMessage());
LoggerFactory.getLogger(TopologyUpdater.class).error("Error during topology update.", re);
}
LoggerFactory.getLogger(TopologyUpdater.class).trace("updateRepositoryTopology -> Exit.");
}
/**
* Updates the topology for the specified repository sending any new commits found both to the repository and to
* referenced repositories.
*/
private void updateCommitTopology() {
LoggerFactory.getLogger(TopologyUpdater.class).trace("updateCommitTopology -> Entry.");
try {
// TODO implement lock mechanism
// Retrieves previous snapshot from disk
ArrayList<CommitInfo> previousSnapshot = retrieveSnapshot();
// Retrieves current snapshot from repository
tools = GitCommitTools.getInstance(repositoryToUpdate, true);
ArrayList<CommitInfo> currentSnapshot = (ArrayList)tools.getCommitInfos();
// Identifies new local commits since previous snapshot
ArrayList<CommitInfo> newCommits = new ArrayList<CommitInfo>(currentSnapshot);
if (previousSnapshot != null) {
newCommits = (ArrayList)CollectionUtils.subtract(currentSnapshot, previousSnapshot);
}
// Identifies commits that are potentially not synchronized in the database, before inserting new commits
boolean dbIsEmpty = checkIfDbIsEmpty();
Set<CommitInfo> commitsNotFoundInSomeReps = new HashSet<CommitInfo>();
if (!dbIsEmpty) {
commitsNotFoundInSomeReps = getCommitsNotFoundInSomeReps();
}
// Insert commits into the database
ArrayList<CommitInfo> commitsToInsert = getCommitsToInsert(newCommits, dbIsEmpty);
if (!commitsToInsert.isEmpty()) {
insertCommits(commitsToInsert);
}
// Identifies commits that were deleted since previous snapshot
ArrayList<CommitInfo> commitsToDelete = new ArrayList<CommitInfo>();
if (previousSnapshot != null) {
commitsToDelete = (ArrayList<CommitInfo>)CollectionUtils.subtract(previousSnapshot, currentSnapshot);
}
// delete commits from database
if (!commitsToDelete.isEmpty()) {
deleteCommits(commitsToDelete);
}
// save current snapshot to disk
saveSnapshot(currentSnapshot);
// updates commits in the database (those that were not deleted)
ArrayList<CommitInfo> commitsToUpdate = (ArrayList)CollectionUtils.subtract(commitsNotFoundInSomeReps,
commitsToDelete);
if (!commitsToUpdate.isEmpty()) {
updateCommits(commitsToUpdate);
}
// removes orphaned commits (those that remained with an empty foundIn list.
commitDAO.deleteOrphanedCommits(repositoryToUpdate.getSystemName());
} catch (DyeVCException dex) {
MessageManager.getInstance().addMessage("Error updating commits from repository <"
+ repositoryToUpdate.getName() + "> with id<" + repositoryToUpdate.getId() + ">\n\t"
+ dex.getMessage());
} catch (RuntimeException re) {
MessageManager.getInstance().addMessage("Error updating commits from repository <"
+ repositoryToUpdate.getName() + "> with id<" + repositoryToUpdate.getId() + ">\n\t"
+ re.getMessage());
LoggerFactory.getLogger(TopologyUpdater.class).error("Error during topology update.", re);
}
LoggerFactory.getLogger(TopologyUpdater.class).trace("updateCommitTopology -> Exit.");
}
/**
* Verifies if the local monitored repositories marked for deletion are referenced in the topology. If not, delete
* them.
*
* @throws DyeVCException
*/
void verifyDeletedRepositories() throws DyeVCException {
LoggerFactory.getLogger(TopologyUpdater.class).trace("verifyDeletedRepositories -> Entry.");
for (Iterator<MonitoredRepository> it =
MonitoredRepositories.getMarkedForDeletion().iterator(); it.hasNext(); ) {
MonitoredRepository monitoredRepository = it.next();
if (!monitoredRepository.hasSystemName()) {
MessageManager.getInstance().addMessage("Repository <" + monitoredRepository.getName() + "> with id <"
+ monitoredRepository.getId()
+ "> has no system name configured and will not be added to the topology.");
continue;
}
try {
monitoredRepositories.removeMarkedForDeletion(monitoredRepository);
} catch (RepositoryReferencedException rre) {
StringBuilder message = new StringBuilder();
message.append("Repository <").append(monitoredRepository.getName()).append("> with id <").append(
monitoredRepository.getId()).append(
"> could not be deleted because it is still referenced by the following clone(s): ");
for (RepositoryInfo info : rre.getRelatedRepositories()) {
message.append("\n<").append(info.getCloneName()).append(">, id: <").append(info.getId()).append(
">, located at host <").append(info.getHostName()).append(">");
}
LoggerFactory.getLogger(TopologyUpdater.class).warn(message.toString());
} catch (RuntimeException re) {
StringBuilder message = new StringBuilder();
message.append("Repository <").append(monitoredRepository.getName()).append("> with id <").append(
monitoredRepository.getId()).append("> could not be deleted due to the following error: ").append(
re.getMessage());
LoggerFactory.getLogger(TopologyUpdater.class).warn(message.toString(), re);
}
}
LoggerFactory.getLogger(TopologyUpdater.class).trace("verifyDeletedRepositories -> Exit.");
}
/**
* Retrieves the previous snapshot of commit infos from disk. If there was no previous snapshot saved, then returns
* null.
*
* @return the saved snapshot of commit infos (null if no previous snapshot found).
* @throws DyeVCException
*/
private ArrayList<CommitInfo> retrieveSnapshot() throws DyeVCException {
LoggerFactory.getLogger(TopologyUpdater.class).trace("retrieveSnapshot -> Entry.");
ObjectInput input = null;
String snapshotPath;
ArrayList<CommitInfo> recoveredCommits = null;
try {
snapshotPath = repositoryToUpdate.getWorkingCloneConnection().getPath() + IConstants.DIR_SEPARATOR
+ "snapshot.ser";
input = new ObjectInputStream(new BufferedInputStream(new FileInputStream(snapshotPath)));
// deserialize the List
recoveredCommits = (ArrayList<CommitInfo>)input.readObject();
} catch (FileNotFoundException ex) {
// do nothing. There is no previous snapshot, so will return null.
} catch (ClassNotFoundException ex) {
throw new MonitorException(ex);
} catch (IOException ex) {
throw new MonitorException(ex);
} finally {
try {
if (input != null) {
input.close();
}
} catch (IOException ex) {
LoggerFactory.getLogger(TopologyUpdater.class).warn("Error closing snapshot stream.", ex);
}
}
LoggerFactory.getLogger(TopologyUpdater.class).trace("retrieveSnapshot -> Exit.");
return recoveredCommits;
}
/**
* Saves a snapshot with the specified list of commit infos to disk
*
* @param commitInfos the list of commit infos to be saved
* @throws DyeVCException
*/
private void saveSnapshot(ArrayList<CommitInfo> commitInfos) throws DyeVCException {
LoggerFactory.getLogger(TopologyUpdater.class).trace("saveSnapshot -> Entry.");
ObjectOutput output = null;
String snapshotPath;
try {
snapshotPath = repositoryToUpdate.getWorkingCloneConnection().getPath() + IConstants.DIR_SEPARATOR
+ "snapshot.ser";
output = new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream(snapshotPath)));
output.writeObject(commitInfos);
} catch (IOException ex) {
throw new MonitorException(ex);
} finally {
try {
if (output != null) {
output.close();
}
} catch (IOException ex) {
LoggerFactory.getLogger(TopologyUpdater.class).warn("Error closing snapshot stream.", ex);
}
}
LoggerFactory.getLogger(TopologyUpdater.class).trace("saveSnapshot -> Exit.");
}
/**
* Retrieves from the database the number of existing commits for the system that the repository being updated
* belongs to and returns true if this number is not 0.
*
* @return true if there is any commit in the database
* @throws ServiceException
*/
private boolean checkIfDbIsEmpty() throws ServiceException {
LoggerFactory.getLogger(TopologyUpdater.class).trace("countCommitsInDatabase -> Entry.");
CommitFilter filter = new CommitFilter();
filter.setSystemName(repositoryToUpdate.getSystemName());
int commitCount = commitDAO.countCommitsByQuery(filter);
LoggerFactory.getLogger(TopologyUpdater.class).trace("countCommitsInDatabase -> Exit.");
return commitCount == 0;
}
/**
* Retrieves from the database the list of commits that were not found in repositories related to the repository
* being updated. If at least one related repository was not listed in the commits foundIn list, then the commit is
* retrieved
*
* @return The list of commits that were not found in some of the related repositories
*/
private Set<CommitInfo> getCommitsNotFoundInSomeReps() throws DyeVCException {
LoggerFactory.getLogger(TopologyUpdater.class).trace("getCommitsNotFoundInSomeReps -> Entry.");
Set<String> repositoryIds = new HashSet<String>();
RepositoryInfo info = converter.toRepositoryInfo();
repositoryIds.add(repositoryToUpdate.getId());
repositoryIds.addAll(info.getPullsFrom());
repositoryIds.addAll(info.getPushesTo());
Set<CommitInfo> commitsNotFound = commitDAO.getCommitsNotFoundInRepositories(repositoryIds,
info.getSystemName(), false);
LoggerFactory.getLogger(TopologyUpdater.class).trace("getCommitsNotFoundInSomeReps -> Exit.");
return commitsNotFound;
}
/**
* Verifies which of the snapshot's new commits already exist in the database, and return only those that do not
* exist, this is, those that must be inserted into the database
*
* @param newCommits New commits found in the current repository snapshot
* @param dbIsEmpty Indicates if database is empty for the system this repository belongs to.
* @return the list of commits that do not exist in the database yet
* @throws DyeVCException
*/
private ArrayList<CommitInfo> getCommitsToInsert(ArrayList<CommitInfo> newCommits, boolean dbIsEmpty)
throws DyeVCException {
LoggerFactory.getLogger(TopologyUpdater.class).trace("getCommitsToInsert -> Entry.");
ArrayList<CommitInfo> commitsToInsert = new ArrayList(newCommits);
if (newCommits != null) {
if (!dbIsEmpty) {
// Check db only if it is not empty, otherwise all commits in newCommits have to be inserted.
Set<CommitInfo> newCommitsInDatabase = commitDAO.getCommitsByHashes(newCommits,
converter.toRepositoryInfo().getSystemName());
commitsToInsert = (ArrayList<CommitInfo>)CollectionUtils.subtract(newCommits, newCommitsInDatabase);
}
} else {
// if newCommits is null, return an empty list (no commits to insert)
commitsToInsert = new ArrayList<CommitInfo>();
}
LoggerFactory.getLogger(TopologyUpdater.class).trace("getCommitsToInsert -> Exit.");
return commitsToInsert;
}
/**
* Converts a set of URIishes into a set of repository ids.
*
* @param aheadSet the set of uriishes to be converted.
* @return the set of uriishes converted into a set of repository ids.
* @throws DyeVCException
*/
private Set<String> convertURIishesToRepIds(final Set<URIish> aheadSet) throws DyeVCException {
LoggerFactory.getLogger(TopologyUpdater.class).trace("convertURIishesToRepIds -> Entry.");
Set<String> aheadRepIds = new HashSet<String>(aheadSet.size());
for (URIish uriish : aheadSet) {
String repId = converter.mapUriToRepositoryId(uriish);
if (repId != null) {
aheadRepIds.add(repId);
}
}
LoggerFactory.getLogger(TopologyUpdater.class).trace("convertURIishesToRepIds -> Exit.");
return aheadRepIds;
}
/**
* Insert new commits into the database. Prior to the insertion, update each commit with the list of repositories
* where they are known to be found.
*
* @param commitsToInsert the list of commits to be inserted
*/
private void insertCommits(ArrayList<CommitInfo> commitsToInsert) throws DyeVCException {
LoggerFactory.getLogger(TopologyUpdater.class).trace("insertCommits -> Entry.");
commitsToInsert = updateWhereExists(commitsToInsert);
commitDAO.insertCommits(commitsToInsert);
LoggerFactory.getLogger(TopologyUpdater.class).trace("insertCommits -> Exit.");
}
/**
* Updates commits into the database. Prior to the update, update each commit with the list of repositories where
* they are known to be found. If the list of repositories has not changed since last run, then do not update the
* commit. updateableCommits commitsToUpdate the list of commits to be updated
*/
private void updateCommits(ArrayList<CommitInfo> commitsToUpdate) throws DyeVCException {
LoggerFactory.getLogger(TopologyUpdater.class).trace("updateCommits -> Entry.");
commitsToUpdate = updateWhereExists(commitsToUpdate);
// Populates a map with groups of commits that should be updated with new repositories where they can now be found
Map<String, List<CommitInfo>> commitsToUpdateByRepository = new TreeMap<String, List<CommitInfo>>();
for (CommitInfo ci : commitsToUpdate) {
Collection<String> newRepIds = CollectionUtils.subtract(ci.getFoundIn(), ci.getPreviousFoundIn());
if (!newRepIds.isEmpty()) {
// if collection of found repositories for the commits has changed, then include the commit to be updated for
// new repository id can now be found.
for (String repId : newRepIds) {
List<CommitInfo> cisToUpdate = commitsToUpdateByRepository.get(repId);
if (cisToUpdate == null) {
cisToUpdate = new ArrayList<CommitInfo>();
commitsToUpdateByRepository.put(repId, cisToUpdate);
}
cisToUpdate.add(ci);
}
}
}
for (String repId : commitsToUpdateByRepository.keySet()) {
commitDAO.updateCommitsWithNewRepository(commitsToUpdateByRepository.get(repId), repId);
}
LoggerFactory.getLogger(TopologyUpdater.class).trace("updateCommits -> Exit.");
}
/**
* Delete the specified list of commits from the database.
*
* @param commitsToDelete the list of commits to be deleted.
*/
private void deleteCommits(ArrayList<CommitInfo> commitsToDelete) throws ServiceException {
commitDAO.deleteCommits(commitsToDelete, repositoryToUpdate.getSystemName());
}
/**
* Updates each commit in the specified list with the list of repositories where they are known to be found. This is
* done checking the repository status for each non-synchronized branch.
*
* @param commitList
* @return
*/
private ArrayList<CommitInfo> updateWhereExists(ArrayList<CommitInfo> commitList) throws DyeVCException {
LoggerFactory.getLogger(TopologyUpdater.class).trace("updateWhereExists -> Entry.");
for (CommitInfo ci : commitList) {
ci.setPreviousFoundIn(new HashSet<String>(ci.getFoundIn()));
Set<URIish> aheadSet = repositoryToUpdate.getRepStatus().getAheadRepsForCommit(ci.getHash());
Set<URIish> behindSet = repositoryToUpdate.getRepStatus().getBehindRepsForCommit(ci.getHash());
if (aheadSet.isEmpty() && behindSet.isEmpty()) {
if (tools.getCommitInfoMap().containsKey(ci.getHash())) {
// If the commit is neither ahead nor behind any related repository, and exists locally,
// then it exists in all related repositories
ci.addAllToFoundIn(converter.toRepositoryInfo().getPullsFrom());
ci.addAllToFoundIn(converter.toRepositoryInfo().getPushesTo());
ci.addFoundIn(repositoryToUpdate.getId());
}
continue;
}
if (!behindSet.isEmpty()) {
// Commit is behind, so it does not exist locally and exists in all repositories in behindSet.
Set<String> behindRepIds = convertURIishesToRepIds(behindSet);
ci.addAllToFoundIn(behindRepIds);
}
if (!aheadSet.isEmpty()) {
// Commit is ahead, so it exists locally and in all repositories that DO NOT have an ahead list containing it.
Set<String> aheadRepIds = convertURIishesToRepIds(aheadSet);
Collection<String> notAheadRepIds =
CollectionUtils.subtract(converter.toRepositoryInfo().getPushesTo(), aheadRepIds);
ci.addAllToFoundIn(notAheadRepIds);
ci.addFoundIn(repositoryToUpdate.getId());
}
}
LoggerFactory.getLogger(TopologyUpdater.class).trace("updateWhereExists -> Exit.");
return commitList;
}
}
| DyeVC/src/main/java/br/uff/ic/dyevc/monitor/TopologyUpdater.java | package br.uff.ic.dyevc.monitor;
//~--- non-JDK imports --------------------------------------------------------
import br.uff.ic.dyevc.application.IConstants;
import br.uff.ic.dyevc.exception.DyeVCException;
import br.uff.ic.dyevc.exception.MonitorException;
import br.uff.ic.dyevc.exception.RepositoryReferencedException;
import br.uff.ic.dyevc.exception.ServiceException;
import br.uff.ic.dyevc.gui.core.MessageManager;
import br.uff.ic.dyevc.model.CommitInfo;
import br.uff.ic.dyevc.model.MonitoredRepositories;
import br.uff.ic.dyevc.model.MonitoredRepository;
import br.uff.ic.dyevc.model.topology.CommitFilter;
import br.uff.ic.dyevc.model.topology.RepositoryInfo;
import br.uff.ic.dyevc.model.topology.Topology;
import br.uff.ic.dyevc.persistence.CommitDAO;
import br.uff.ic.dyevc.persistence.TopologyDAO;
import br.uff.ic.dyevc.tools.vcs.git.GitCommitTools;
import br.uff.ic.dyevc.utils.RepositoryConverter;
import br.uff.ic.dyevc.utils.SystemUtils;
import org.apache.commons.collections15.CollectionUtils;
import org.eclipse.jgit.transport.URIish;
import org.slf4j.LoggerFactory;
//~--- JDK imports ------------------------------------------------------------
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectInputStream;
import java.io.ObjectOutput;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
/**
* This class updates the topology.
*
* @author Cristiano
*/
public class TopologyUpdater {
private final TopologyDAO topologyDAO;
private final CommitDAO commitDAO;
private Topology topology;
private final MonitoredRepositories monitoredRepositories;
private RepositoryConverter converter;
private MonitoredRepository repositoryToUpdate;
private GitCommitTools tools;
/**
* Creates a new object of this type.
*/
public TopologyUpdater() {
LoggerFactory.getLogger(TopologyUpdater.class).trace("Constructor -> Entry.");
topologyDAO = new TopologyDAO();
commitDAO = new CommitDAO();
this.monitoredRepositories = MonitoredRepositories.getInstance();
LoggerFactory.getLogger(TopologyUpdater.class).trace("Constructor -> Exit.");
}
/**
* Updates the topology.
*
* @param repositoryToUpdate the repository to be updated
*/
public void update(MonitoredRepository repositoryToUpdate) {
LoggerFactory.getLogger(TopologyUpdater.class).trace("Topology updater is running.");
if (!repositoryToUpdate.hasSystemName()) {
MessageManager.getInstance().addMessage("Repository <" + repositoryToUpdate.getName() + "> with id <"
+ repositoryToUpdate.getId()
+ "> has no system name configured and will not be added to the topology.");
return;
}
this.repositoryToUpdate = repositoryToUpdate;
this.converter = new RepositoryConverter(repositoryToUpdate);
MessageManager.getInstance().addMessage("Updating topology for repository <" + repositoryToUpdate.getId()
+ "> with id <" + repositoryToUpdate.getName() + ">");
updateRepositoryTopology();
updateCommitTopology();
MessageManager.getInstance().addMessage("Finished update topology for repository <"
+ repositoryToUpdate.getId() + "> with id <" + repositoryToUpdate.getName() + ">");
LoggerFactory.getLogger(TopologyUpdater.class).trace("Topology updater finished running.");
}
/**
* Updates the topology for the specified repository in the database, including any new referenced repositories that
* do not yet exist and refreshes local topology cache.
*
* @see RepositoryConverter
*/
private void updateRepositoryTopology() {
LoggerFactory.getLogger(TopologyUpdater.class).trace("updateRepositoryTopology -> Entry.");
String systemName = repositoryToUpdate.getSystemName();
try {
topology = topologyDAO.readTopologyForSystem(systemName);
RepositoryInfo localRepositoryInfo = converter.toRepositoryInfo();
RepositoryInfo remoteRepositoryInfo = topology.getRepositoryInfo(systemName, localRepositoryInfo.getId());
/*
* changedLocally is used to flag any changes to repository info. If any changes were done at the end of the
* method, then the repository is updated in database. It is initialized with true if the repository info
* does not exist in the database.
*/
boolean changedLocally = remoteRepositoryInfo == null;
if (!changedLocally) {
// localRepositoryInfo already exists in the topology, then gets the list of hosts that monitor it
localRepositoryInfo.setMonitoredBy(remoteRepositoryInfo.getMonitoredBy());
} else {
localRepositoryInfo.addMonitoredBy(SystemUtils.getLocalHostname());
}
if (!changedLocally) {
// check whether this computer must be added or removed from the monitoredby list.
Set<String> monitoredBy = localRepositoryInfo.getMonitoredBy();
String hostname = SystemUtils.getLocalHostname();
if (repositoryToUpdate.isMarkedForDeletion()) {
changedLocally |= monitoredBy.remove(hostname);
} else {
changedLocally |= monitoredBy.add(hostname);
}
}
if (!changedLocally) {
// Checks if the pullsFrom list must be updated
Collection<String> insertedPullsFrom = CollectionUtils.subtract(localRepositoryInfo.getPullsFrom(),
remoteRepositoryInfo.getPullsFrom());
Collection<String> removedPullsFrom = CollectionUtils.subtract(remoteRepositoryInfo.getPullsFrom(),
localRepositoryInfo.getPullsFrom());
changedLocally |= !insertedPullsFrom.isEmpty();
changedLocally |= !removedPullsFrom.isEmpty();
}
if (!changedLocally) {
// Checks if the pushesTo list must be updated
Collection<String> insertedPushesTo = CollectionUtils.subtract(localRepositoryInfo.getPushesTo(),
remoteRepositoryInfo.getPushesTo());
Collection<String> removedPushesTo = CollectionUtils.subtract(remoteRepositoryInfo.getPushesTo(),
localRepositoryInfo.getPushesTo());
changedLocally |= !insertedPushesTo.isEmpty();
changedLocally |= !removedPushesTo.isEmpty();
}
if (changedLocally) {
Date lastChanged = topologyDAO.upsertRepository(converter.toRepositoryInfo());
topologyDAO.upsertRepositories(converter.getRelatedNewList());
repositoryToUpdate.setLastChanged(lastChanged);
topology = topologyDAO.readTopologyForSystem(repositoryToUpdate.getSystemName());
}
} catch (DyeVCException dex) {
MessageManager.getInstance().addMessage("Error updating repository<" + repositoryToUpdate.getName()
+ "> with id<" + repositoryToUpdate.getId() + ">\n\t" + dex.getMessage());
} catch (RuntimeException re) {
MessageManager.getInstance().addMessage("Error updating repository<" + repositoryToUpdate.getName()
+ "> with id<" + repositoryToUpdate.getId() + ">\n\t" + re.getMessage());
LoggerFactory.getLogger(TopologyUpdater.class).error("Error during topology update.", re);
}
LoggerFactory.getLogger(TopologyUpdater.class).trace("updateRepositoryTopology -> Exit.");
}
/**
* Updates the topology for the specified repository sending any new commits found both to the repository and to
* referenced repositories.
*/
private void updateCommitTopology() {
LoggerFactory.getLogger(TopologyUpdater.class).trace("updateCommitTopology -> Entry.");
try {
// TODO implement lock mechanism
// Retrieves previous snapshot from disk
ArrayList<CommitInfo> previousSnapshot = retrieveSnapshot();
// Retrieves current snapshot from repository
tools = GitCommitTools.getInstance(repositoryToUpdate, true);
ArrayList<CommitInfo> currentSnapshot = (ArrayList)tools.getCommitInfos();
// Identifies new local commits since previous snapshot
ArrayList<CommitInfo> newCommits = currentSnapshot;
if (previousSnapshot != null) {
newCommits = (ArrayList)CollectionUtils.subtract(currentSnapshot, previousSnapshot);
}
// Identifies commits that were deleted since previous snapshot
ArrayList<CommitInfo> commitsToDelete = new ArrayList<CommitInfo>();
if (previousSnapshot != null) {
commitsToDelete = (ArrayList<CommitInfo>)CollectionUtils.subtract(previousSnapshot, currentSnapshot);
}
// Identifies commits that are potentially not synchronized in the database
int commitCount = countCommitsInDatabase();
Set<CommitInfo> commitsNotFoundInSomeReps = new HashSet<CommitInfo>();
if (commitCount > 0) {
commitsNotFoundInSomeReps = getCommitsNotFoundInSomeReps();
}
// Insert commits into the database
ArrayList<CommitInfo> commitsToInsert = getCommitsToInsert(newCommits);
// uncomment this later
if (!commitsToInsert.isEmpty()) {
insertCommits(commitsToInsert);
}
// delete commits from database
// uncomment this later
if (!commitsToDelete.isEmpty()) {
deleteCommits(commitsToDelete);
}
// save current snapshot to disk
// uncomment this later
saveSnapshot(currentSnapshot);
// updated commits in the database (those that were not deleted)
ArrayList<CommitInfo> updateableCommits = (ArrayList)CollectionUtils.subtract(commitsNotFoundInSomeReps,
commitsToDelete);
if (!updateableCommits.isEmpty()) {
updateCommits(updateableCommits);
}
commitDAO.deleteOrphanedCommits(repositoryToUpdate.getSystemName());
} catch (DyeVCException dex) {
MessageManager.getInstance().addMessage("Error updating commits from repository <"
+ repositoryToUpdate.getName() + "> with id<" + repositoryToUpdate.getId() + ">\n\t"
+ dex.getMessage());
} catch (RuntimeException re) {
MessageManager.getInstance().addMessage("Error updating commits from repository <"
+ repositoryToUpdate.getName() + "> with id<" + repositoryToUpdate.getId() + ">\n\t"
+ re.getMessage());
LoggerFactory.getLogger(TopologyUpdater.class).error("Error during topology update.", re);
}
LoggerFactory.getLogger(TopologyUpdater.class).trace("updateCommitTopology -> Exit.");
}
/**
* Verifies if the local monitored repositories marked for deletion are referenced in the topology. If not, delete
* them.
*
* @throws DyeVCException
*/
void verifyDeletedRepositories() throws DyeVCException {
LoggerFactory.getLogger(TopologyUpdater.class).trace("verifyDeletedRepositories -> Entry.");
for (Iterator<MonitoredRepository> it =
MonitoredRepositories.getMarkedForDeletion().iterator(); it.hasNext(); ) {
MonitoredRepository monitoredRepository = it.next();
if (!monitoredRepository.hasSystemName()) {
MessageManager.getInstance().addMessage("Repository <" + monitoredRepository.getName() + "> with id <"
+ monitoredRepository.getId()
+ "> has no system name configured and will not be added to the topology.");
continue;
}
try {
monitoredRepositories.removeMarkedForDeletion(monitoredRepository);
} catch (RepositoryReferencedException rre) {
StringBuilder message = new StringBuilder();
message.append("Repository <").append(monitoredRepository.getName()).append("> with id <").append(
monitoredRepository.getId()).append(
"> could not be deleted because it is still referenced by the following clone(s): ");
for (RepositoryInfo info : rre.getRelatedRepositories()) {
message.append("\n<").append(info.getCloneName()).append(">, id: <").append(info.getId()).append(
">, located at host <").append(info.getHostName()).append(">");
}
LoggerFactory.getLogger(TopologyUpdater.class).warn(message.toString());
} catch (RuntimeException re) {
StringBuilder message = new StringBuilder();
message.append("Repository <").append(monitoredRepository.getName()).append("> with id <").append(
monitoredRepository.getId()).append("> could not be deleted due to the following error: ").append(
re.getMessage());
LoggerFactory.getLogger(TopologyUpdater.class).warn(message.toString(), re);
}
}
LoggerFactory.getLogger(TopologyUpdater.class).trace("verifyDeletedRepositories -> Exit.");
}
/**
* Retrieves the previous snapshot of commit infos from disk. If there was no previous snapshot saved, then returns
* null.
*
* @return the saved snapshot of commit infos (null if no previous snapshot found).
* @throws DyeVCException
*/
private ArrayList<CommitInfo> retrieveSnapshot() throws DyeVCException {
LoggerFactory.getLogger(TopologyUpdater.class).trace("retrieveSnapshot -> Entry.");
ObjectInput input = null;
String snapshotPath;
ArrayList<CommitInfo> recoveredCommits = null;
try {
snapshotPath = repositoryToUpdate.getWorkingCloneConnection().getPath() + IConstants.DIR_SEPARATOR
+ "snapshot.ser";
input = new ObjectInputStream(new BufferedInputStream(new FileInputStream(snapshotPath)));
// deserialize the List
recoveredCommits = (ArrayList<CommitInfo>)input.readObject();
} catch (FileNotFoundException ex) {
// do nothing. There is no previous snapshot, so will return null.
} catch (ClassNotFoundException ex) {
throw new MonitorException(ex);
} catch (IOException ex) {
throw new MonitorException(ex);
} finally {
try {
if (input != null) {
input.close();
}
} catch (IOException ex) {
LoggerFactory.getLogger(TopologyUpdater.class).warn("Error closing snapshot stream.", ex);
}
}
LoggerFactory.getLogger(TopologyUpdater.class).trace("retrieveSnapshot -> Exit.");
return recoveredCommits;
}
/**
* Saves a snapshot with the specified list of commit infos to disk
*
* @param commitInfos the list of commit infos to be saved
* @throws DyeVCException
*/
private void saveSnapshot(ArrayList<CommitInfo> commitInfos) throws DyeVCException {
LoggerFactory.getLogger(TopologyUpdater.class).trace("saveSnapshot -> Entry.");
ObjectOutput output = null;
String snapshotPath;
try {
snapshotPath = repositoryToUpdate.getWorkingCloneConnection().getPath() + IConstants.DIR_SEPARATOR
+ "snapshot.ser";
output = new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream(snapshotPath)));
output.writeObject(commitInfos);
} catch (IOException ex) {
throw new MonitorException(ex);
} finally {
try {
if (output != null) {
output.close();
}
} catch (IOException ex) {
LoggerFactory.getLogger(TopologyUpdater.class).warn("Error closing snapshot stream.", ex);
}
}
LoggerFactory.getLogger(TopologyUpdater.class).trace("saveSnapshot -> Exit.");
}
/**
* Retrieves from the database the number of existing commits for the system that the repository being updated
* belongs to
*
* @return the number of existing commits for the system that the repository being updated belongs to
* @throws ServiceException
*/
private int countCommitsInDatabase() throws ServiceException {
LoggerFactory.getLogger(TopologyUpdater.class).trace("countCommitsInDatabase -> Entry.");
CommitFilter filter = new CommitFilter();
filter.setSystemName(repositoryToUpdate.getSystemName());
LoggerFactory.getLogger(TopologyUpdater.class).trace("countCommitsInDatabase -> Exit.");
return commitDAO.countCommitsByQuery(filter);
}
/**
* Retrieves from the database the list of commits that were not found in repositories related to the repository
* being updated. If at least one related repository was not listed in the commits foundIn list, then the commit is
* retrieved
*
* @return The list of commits that were not found in some of the related repositories
*/
private Set<CommitInfo> getCommitsNotFoundInSomeReps() throws DyeVCException {
LoggerFactory.getLogger(TopologyUpdater.class).trace("getCommitsNotFoundInSomeReps -> Entry.");
Set<String> repositoryIds = new HashSet<String>();
RepositoryInfo info = converter.toRepositoryInfo();
repositoryIds.add(repositoryToUpdate.getId());
repositoryIds.addAll(info.getPullsFrom());
repositoryIds.addAll(info.getPushesTo());
Set<CommitInfo> commitsNotFound = commitDAO.getCommitsNotFoundInRepositories(repositoryIds,
info.getSystemName(), false);
LoggerFactory.getLogger(TopologyUpdater.class).trace("getCommitsNotFoundInSomeReps -> Exit.");
return commitsNotFound;
}
/**
* Verifies which of the snapshot's new commits already exist in the database, and return only those that do not
* exist, this is, those that must be inserted into the database
*
* @param newCommits New commits found in the current repository snapshot
* @return the list of commits that do not exist in the database yet
* @throws DyeVCException
*/
private ArrayList<CommitInfo> getCommitsToInsert(ArrayList<CommitInfo> newCommits) throws DyeVCException {
LoggerFactory.getLogger(TopologyUpdater.class).trace("getCommitsToInsert -> Entry.");
ArrayList<CommitInfo> commitsToInsert = newCommits;
if (newCommits != null) {
Set<CommitInfo> newCommitsInDatabase = commitDAO.getCommitsByHashes(newCommits,
converter.toRepositoryInfo().getSystemName());
commitsToInsert = (ArrayList<CommitInfo>)CollectionUtils.subtract(newCommits, newCommitsInDatabase);
} else {
commitsToInsert = new ArrayList<CommitInfo>();
}
LoggerFactory.getLogger(TopologyUpdater.class).trace("getCommitsToInsert -> Exit.");
return commitsToInsert;
}
/**
* Converts a set of URIishes into a set of repository ids.
*
* @param aheadSet the set of uriishes to be converted.
* @return the set of uriishes converted into a set of repository ids.
* @throws DyeVCException
*/
private Set<String> convertURIishesToRepIds(final Set<URIish> aheadSet) throws DyeVCException {
LoggerFactory.getLogger(TopologyUpdater.class).trace("convertURIishesToRepIds -> Entry.");
Set<String> aheadRepIds = new HashSet<String>(aheadSet.size());
for (URIish uriish : aheadSet) {
String repId = converter.mapUriToRepositoryId(uriish);
if (repId != null) {
aheadRepIds.add(repId);
}
}
LoggerFactory.getLogger(TopologyUpdater.class).trace("convertURIishesToRepIds -> Exit.");
return aheadRepIds;
}
/**
* Insert new commits into the database. Prior to the insertion, update each commit with the list of repositories
* where they are known to be found.
*
* @param commitsToInsert the list of commits to be inserted
*/
private void insertCommits(ArrayList<CommitInfo> commitsToInsert) throws DyeVCException {
LoggerFactory.getLogger(TopologyUpdater.class).trace("insertCommits -> Entry.");
commitsToInsert = updateWhereExists(commitsToInsert);
commitDAO.insertCommits(commitsToInsert);
LoggerFactory.getLogger(TopologyUpdater.class).trace("insertCommits -> Exit.");
}
/**
* Updates commits into the database. Prior to the update, update each commit with the list of repositories where
* they are known to be found. If the list of repositories has not changed since last run, then do not update the
* commit. updateableCommits commitsToUpdate the list of commits to be updated
*/
private void updateCommits(ArrayList<CommitInfo> updateableCommits) throws DyeVCException {
LoggerFactory.getLogger(TopologyUpdater.class).trace("updateCommits -> Entry.");
updateableCommits = updateWhereExists(updateableCommits);
ArrayList<CommitInfo> commitsToUpdate = new ArrayList<CommitInfo>();
// Populates a map with groups of commits that should be updated with new repositories where they can now be found
Map<String, List<CommitInfo>> commitsToUpdateByRepository = new TreeMap<String, List<CommitInfo>>();
for (CommitInfo ci : updateableCommits) {
Collection<String> newRepIds = CollectionUtils.subtract(ci.getFoundIn(), ci.getPreviousFoundIn());
if (!newRepIds.isEmpty()) {
// if collection of found repositories for the commits has changed, then include the commit to be updated for
// new repository id can now be found.
for (String repId : newRepIds) {
List<CommitInfo> cisToUpdate = commitsToUpdateByRepository.get(repId);
if (cisToUpdate == null) {
cisToUpdate = new ArrayList<CommitInfo>();
commitsToUpdateByRepository.put(repId, cisToUpdate);
}
cisToUpdate.add(ci);
}
}
}
for (String repId : commitsToUpdateByRepository.keySet()) {
commitDAO.updateCommitsWithNewRepository(commitsToUpdateByRepository.get(repId), repId);
}
LoggerFactory.getLogger(TopologyUpdater.class).trace("updateCommits -> Exit.");
}
/**
* Delete the specified list of commits from the database.
*
* @param commitsToDelete the list of commits to be deleted.
*/
private void deleteCommits(ArrayList<CommitInfo> commitsToDelete) throws ServiceException {
commitDAO.deleteCommits(commitsToDelete, repositoryToUpdate.getSystemName());
}
/**
* Updates each commit in the specified list with the list of repositories where they are known to be found. This is
* done checking the repository status for each non-synchronized branch.
*
* @param commitList
* @return
*/
private ArrayList<CommitInfo> updateWhereExists(ArrayList<CommitInfo> commitList) throws DyeVCException {
LoggerFactory.getLogger(TopologyUpdater.class).trace("updateWhereExists -> Entry.");
for (CommitInfo ci : commitList) {
ci.setPreviousFoundIn(new HashSet<String>(ci.getFoundIn()));
Set<URIish> aheadSet = repositoryToUpdate.getRepStatus().getAheadRepsForCommit(ci.getHash());
Set<URIish> behindSet = repositoryToUpdate.getRepStatus().getBehindRepsForCommit(ci.getHash());
if (aheadSet.isEmpty() && behindSet.isEmpty()) {
if (tools.getCommitInfoMap().containsKey(ci.getHash())) {
// If the commit is neither ahead nor behind any related repository, and exists locally,
// then it exists in all related repositories
ci.addAllToFoundIn(converter.toRepositoryInfo().getPullsFrom());
ci.addAllToFoundIn(converter.toRepositoryInfo().getPushesTo());
ci.addFoundIn(repositoryToUpdate.getId());
}
}
if (!behindSet.isEmpty()) {
// Commit is behind, so it does not exist locally and exists in all repositories in behindSet.
Set<String> behindRepIds = convertURIishesToRepIds(behindSet);
ci.addAllToFoundIn(behindRepIds);
}
if (!aheadSet.isEmpty()) {
// Commit is ahead, so it exists locally and in all repositories that DO NOT have an ahead list containing it.
Set<String> aheadRepIds = convertURIishesToRepIds(aheadSet);
Collection<String> notAheadRepIds =
CollectionUtils.subtract(converter.toRepositoryInfo().getPushesTo(), aheadRepIds);
ci.addAllToFoundIn(notAheadRepIds);
ci.addFoundIn(repositoryToUpdate.getId());
}
}
LoggerFactory.getLogger(TopologyUpdater.class).trace("updateWhereExists -> Exit.");
return commitList;
}
}
| Refactoring methods and comments related to #70. | DyeVC/src/main/java/br/uff/ic/dyevc/monitor/TopologyUpdater.java | Refactoring methods and comments related to #70. | <ide><path>yeVC/src/main/java/br/uff/ic/dyevc/monitor/TopologyUpdater.java
<ide> LoggerFactory.getLogger(TopologyUpdater.class).trace("updateRepositoryTopology -> Entry.");
<ide> String systemName = repositoryToUpdate.getSystemName();
<ide>
<add> // TODO implement lock mechanism
<ide> try {
<ide> topology = topologyDAO.readTopologyForSystem(systemName);
<ide>
<ide> RepositoryInfo remoteRepositoryInfo = topology.getRepositoryInfo(systemName, localRepositoryInfo.getId());
<ide>
<ide> /*
<del> * changedLocally is used to flag any changes to repository info. If any changes were done at the end of the
<add> * changedLocally is used to flag any changes to repository info. If any changes were detected by the end of the
<ide> * method, then the repository is updated in database. It is initialized with true if the repository info
<ide> * does not exist in the database.
<ide> */
<ide> ArrayList<CommitInfo> currentSnapshot = (ArrayList)tools.getCommitInfos();
<ide>
<ide> // Identifies new local commits since previous snapshot
<del> ArrayList<CommitInfo> newCommits = currentSnapshot;
<add> ArrayList<CommitInfo> newCommits = new ArrayList<CommitInfo>(currentSnapshot);
<ide> if (previousSnapshot != null) {
<ide> newCommits = (ArrayList)CollectionUtils.subtract(currentSnapshot, previousSnapshot);
<add> }
<add>
<add> // Identifies commits that are potentially not synchronized in the database, before inserting new commits
<add> boolean dbIsEmpty = checkIfDbIsEmpty();
<add> Set<CommitInfo> commitsNotFoundInSomeReps = new HashSet<CommitInfo>();
<add> if (!dbIsEmpty) {
<add> commitsNotFoundInSomeReps = getCommitsNotFoundInSomeReps();
<add> }
<add>
<add> // Insert commits into the database
<add> ArrayList<CommitInfo> commitsToInsert = getCommitsToInsert(newCommits, dbIsEmpty);
<add> if (!commitsToInsert.isEmpty()) {
<add> insertCommits(commitsToInsert);
<ide> }
<ide>
<ide> // Identifies commits that were deleted since previous snapshot
<ide> commitsToDelete = (ArrayList<CommitInfo>)CollectionUtils.subtract(previousSnapshot, currentSnapshot);
<ide> }
<ide>
<del> // Identifies commits that are potentially not synchronized in the database
<del> int commitCount = countCommitsInDatabase();
<del> Set<CommitInfo> commitsNotFoundInSomeReps = new HashSet<CommitInfo>();
<del> if (commitCount > 0) {
<del> commitsNotFoundInSomeReps = getCommitsNotFoundInSomeReps();
<del> }
<del>
<del> // Insert commits into the database
<del> ArrayList<CommitInfo> commitsToInsert = getCommitsToInsert(newCommits);
<del> // uncomment this later
<del> if (!commitsToInsert.isEmpty()) {
<del> insertCommits(commitsToInsert);
<del> }
<del>
<ide> // delete commits from database
<del> // uncomment this later
<ide> if (!commitsToDelete.isEmpty()) {
<ide> deleteCommits(commitsToDelete);
<ide> }
<ide>
<ide> // save current snapshot to disk
<del> // uncomment this later
<ide> saveSnapshot(currentSnapshot);
<ide>
<del> // updated commits in the database (those that were not deleted)
<del> ArrayList<CommitInfo> updateableCommits = (ArrayList)CollectionUtils.subtract(commitsNotFoundInSomeReps,
<del> commitsToDelete);
<del> if (!updateableCommits.isEmpty()) {
<del> updateCommits(updateableCommits);
<del> }
<del>
<add> // updates commits in the database (those that were not deleted)
<add> ArrayList<CommitInfo> commitsToUpdate = (ArrayList)CollectionUtils.subtract(commitsNotFoundInSomeReps,
<add> commitsToDelete);
<add> if (!commitsToUpdate.isEmpty()) {
<add> updateCommits(commitsToUpdate);
<add> }
<add>
<add> // removes orphaned commits (those that remained with an empty foundIn list.
<ide> commitDAO.deleteOrphanedCommits(repositoryToUpdate.getSystemName());
<ide> } catch (DyeVCException dex) {
<ide> MessageManager.getInstance().addMessage("Error updating commits from repository <"
<ide>
<ide> /**
<ide> * Retrieves from the database the number of existing commits for the system that the repository being updated
<del> * belongs to
<del> *
<del> * @return the number of existing commits for the system that the repository being updated belongs to
<add> * belongs to and returns true if this number is not 0.
<add> *
<add> * @return true if there is any commit in the database
<ide> * @throws ServiceException
<ide> */
<del> private int countCommitsInDatabase() throws ServiceException {
<add> private boolean checkIfDbIsEmpty() throws ServiceException {
<ide> LoggerFactory.getLogger(TopologyUpdater.class).trace("countCommitsInDatabase -> Entry.");
<add>
<ide> CommitFilter filter = new CommitFilter();
<ide> filter.setSystemName(repositoryToUpdate.getSystemName());
<add> int commitCount = commitDAO.countCommitsByQuery(filter);
<ide>
<ide> LoggerFactory.getLogger(TopologyUpdater.class).trace("countCommitsInDatabase -> Exit.");
<ide>
<del> return commitDAO.countCommitsByQuery(filter);
<add> return commitCount == 0;
<ide> }
<ide>
<ide> /**
<ide> * exist, this is, those that must be inserted into the database
<ide> *
<ide> * @param newCommits New commits found in the current repository snapshot
<add> * @param dbIsEmpty Indicates if database is empty for the system this repository belongs to.
<ide> * @return the list of commits that do not exist in the database yet
<ide> * @throws DyeVCException
<ide> */
<del> private ArrayList<CommitInfo> getCommitsToInsert(ArrayList<CommitInfo> newCommits) throws DyeVCException {
<add> private ArrayList<CommitInfo> getCommitsToInsert(ArrayList<CommitInfo> newCommits, boolean dbIsEmpty)
<add> throws DyeVCException {
<ide> LoggerFactory.getLogger(TopologyUpdater.class).trace("getCommitsToInsert -> Entry.");
<del> ArrayList<CommitInfo> commitsToInsert = newCommits;
<add> ArrayList<CommitInfo> commitsToInsert = new ArrayList(newCommits);
<ide>
<ide> if (newCommits != null) {
<del> Set<CommitInfo> newCommitsInDatabase = commitDAO.getCommitsByHashes(newCommits,
<del> converter.toRepositoryInfo().getSystemName());
<del> commitsToInsert = (ArrayList<CommitInfo>)CollectionUtils.subtract(newCommits, newCommitsInDatabase);
<add> if (!dbIsEmpty) {
<add> // Check db only if it is not empty, otherwise all commits in newCommits have to be inserted.
<add> Set<CommitInfo> newCommitsInDatabase = commitDAO.getCommitsByHashes(newCommits,
<add> converter.toRepositoryInfo().getSystemName());
<add> commitsToInsert = (ArrayList<CommitInfo>)CollectionUtils.subtract(newCommits, newCommitsInDatabase);
<add> }
<ide> } else {
<add> // if newCommits is null, return an empty list (no commits to insert)
<ide> commitsToInsert = new ArrayList<CommitInfo>();
<ide> }
<ide>
<ide> * they are known to be found. If the list of repositories has not changed since last run, then do not update the
<ide> * commit. updateableCommits commitsToUpdate the list of commits to be updated
<ide> */
<del> private void updateCommits(ArrayList<CommitInfo> updateableCommits) throws DyeVCException {
<add> private void updateCommits(ArrayList<CommitInfo> commitsToUpdate) throws DyeVCException {
<ide> LoggerFactory.getLogger(TopologyUpdater.class).trace("updateCommits -> Entry.");
<ide>
<del> updateableCommits = updateWhereExists(updateableCommits);
<del> ArrayList<CommitInfo> commitsToUpdate = new ArrayList<CommitInfo>();
<add> commitsToUpdate = updateWhereExists(commitsToUpdate);
<ide>
<ide> // Populates a map with groups of commits that should be updated with new repositories where they can now be found
<ide> Map<String, List<CommitInfo>> commitsToUpdateByRepository = new TreeMap<String, List<CommitInfo>>();
<del> for (CommitInfo ci : updateableCommits) {
<add> for (CommitInfo ci : commitsToUpdate) {
<ide> Collection<String> newRepIds = CollectionUtils.subtract(ci.getFoundIn(), ci.getPreviousFoundIn());
<ide> if (!newRepIds.isEmpty()) {
<ide> // if collection of found repositories for the commits has changed, then include the commit to be updated for
<ide> ci.addAllToFoundIn(converter.toRepositoryInfo().getPushesTo());
<ide> ci.addFoundIn(repositoryToUpdate.getId());
<ide> }
<add>
<add> continue;
<ide> }
<ide>
<ide> if (!behindSet.isEmpty()) { |
|
JavaScript | agpl-3.0 | 1f8aa6af5103d1b2fc0c3fac50771c5d96d9a796 | 0 | duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test | 54c0ecee-2e63-11e5-9284-b827eb9e62be | helloWorld.js | 54bb78e0-2e63-11e5-9284-b827eb9e62be | 54c0ecee-2e63-11e5-9284-b827eb9e62be | helloWorld.js | 54c0ecee-2e63-11e5-9284-b827eb9e62be | <ide><path>elloWorld.js
<del>54bb78e0-2e63-11e5-9284-b827eb9e62be
<add>54c0ecee-2e63-11e5-9284-b827eb9e62be |
|
Java | apache-2.0 | 84830e4a5231fb5b8b19b056ac8cb69e8d188db0 | 0 | semonte/intellij-community,wreckJ/intellij-community,holmes/intellij-community,fengbaicanhe/intellij-community,muntasirsyed/intellij-community,pwoodworth/intellij-community,ThiagoGarciaAlves/intellij-community,ahb0327/intellij-community,akosyakov/intellij-community,supersven/intellij-community,fitermay/intellij-community,hurricup/intellij-community,ryano144/intellij-community,supersven/intellij-community,signed/intellij-community,MER-GROUP/intellij-community,vladmm/intellij-community,dslomov/intellij-community,ahb0327/intellij-community,vladmm/intellij-community,kool79/intellij-community,Distrotech/intellij-community,diorcety/intellij-community,Distrotech/intellij-community,diorcety/intellij-community,SerCeMan/intellij-community,ol-loginov/intellij-community,da1z/intellij-community,salguarnieri/intellij-community,Distrotech/intellij-community,ol-loginov/intellij-community,ibinti/intellij-community,ryano144/intellij-community,caot/intellij-community,idea4bsd/idea4bsd,michaelgallacher/intellij-community,salguarnieri/intellij-community,da1z/intellij-community,wreckJ/intellij-community,xfournet/intellij-community,salguarnieri/intellij-community,ftomassetti/intellij-community,amith01994/intellij-community,adedayo/intellij-community,vladmm/intellij-community,kdwink/intellij-community,nicolargo/intellij-community,muntasirsyed/intellij-community,amith01994/intellij-community,blademainer/intellij-community,nicolargo/intellij-community,semonte/intellij-community,muntasirsyed/intellij-community,ryano144/intellij-community,mglukhikh/intellij-community,holmes/intellij-community,fitermay/intellij-community,diorcety/intellij-community,adedayo/intellij-community,SerCeMan/intellij-community,Lekanich/intellij-community,asedunov/intellij-community,vvv1559/intellij-community,ernestp/consulo,salguarnieri/intellij-community,Distrotech/intellij-community,jexp/idea2,akosyakov/intellij-community,orekyuu/intellij-community,ThiagoGarciaAlves/intellij-community,caot/intellij-community,Distrotech/intellij-community,supersven/intellij-community,semonte/intellij-community,izonder/intellij-community,FHannes/intellij-community,signed/intellij-community,fengbaicanhe/intellij-community,xfournet/intellij-community,nicolargo/intellij-community,apixandru/intellij-community,supersven/intellij-community,ThiagoGarciaAlves/intellij-community,FHannes/intellij-community,vvv1559/intellij-community,fitermay/intellij-community,suncycheng/intellij-community,retomerz/intellij-community,allotria/intellij-community,orekyuu/intellij-community,ivan-fedorov/intellij-community,consulo/consulo,da1z/intellij-community,kdwink/intellij-community,ryano144/intellij-community,semonte/intellij-community,nicolargo/intellij-community,fitermay/intellij-community,idea4bsd/idea4bsd,fengbaicanhe/intellij-community,clumsy/intellij-community,tmpgit/intellij-community,vladmm/intellij-community,blademainer/intellij-community,suncycheng/intellij-community,apixandru/intellij-community,jagguli/intellij-community,jagguli/intellij-community,asedunov/intellij-community,kdwink/intellij-community,fitermay/intellij-community,retomerz/intellij-community,allotria/intellij-community,adedayo/intellij-community,asedunov/intellij-community,xfournet/intellij-community,akosyakov/intellij-community,ibinti/intellij-community,wreckJ/intellij-community,holmes/intellij-community,jagguli/intellij-community,blademainer/intellij-community,diorcety/intellij-community,ivan-fedorov/intellij-community,muntasirsyed/intellij-community,ibinti/intellij-community,gnuhub/intellij-community,vladmm/intellij-community,TangHao1987/intellij-community,hurricup/intellij-community,orekyuu/intellij-community,petteyg/intellij-community,ThiagoGarciaAlves/intellij-community,robovm/robovm-studio,ftomassetti/intellij-community,slisson/intellij-community,diorcety/intellij-community,retomerz/intellij-community,caot/intellij-community,kool79/intellij-community,holmes/intellij-community,fnouama/intellij-community,signed/intellij-community,Distrotech/intellij-community,alphafoobar/intellij-community,vvv1559/intellij-community,lucafavatella/intellij-community,alphafoobar/intellij-community,clumsy/intellij-community,nicolargo/intellij-community,gnuhub/intellij-community,ol-loginov/intellij-community,samthor/intellij-community,muntasirsyed/intellij-community,slisson/intellij-community,fitermay/intellij-community,caot/intellij-community,izonder/intellij-community,kdwink/intellij-community,samthor/intellij-community,jagguli/intellij-community,hurricup/intellij-community,lucafavatella/intellij-community,apixandru/intellij-community,mglukhikh/intellij-community,pwoodworth/intellij-community,ivan-fedorov/intellij-community,da1z/intellij-community,idea4bsd/idea4bsd,consulo/consulo,kool79/intellij-community,signed/intellij-community,fnouama/intellij-community,nicolargo/intellij-community,apixandru/intellij-community,da1z/intellij-community,supersven/intellij-community,ahb0327/intellij-community,vladmm/intellij-community,adedayo/intellij-community,kool79/intellij-community,amith01994/intellij-community,ol-loginov/intellij-community,diorcety/intellij-community,caot/intellij-community,michaelgallacher/intellij-community,Lekanich/intellij-community,signed/intellij-community,fengbaicanhe/intellij-community,mglukhikh/intellij-community,supersven/intellij-community,michaelgallacher/intellij-community,ibinti/intellij-community,salguarnieri/intellij-community,ol-loginov/intellij-community,fengbaicanhe/intellij-community,akosyakov/intellij-community,pwoodworth/intellij-community,ryano144/intellij-community,slisson/intellij-community,ivan-fedorov/intellij-community,gnuhub/intellij-community,MichaelNedzelsky/intellij-community,SerCeMan/intellij-community,diorcety/intellij-community,izonder/intellij-community,akosyakov/intellij-community,hurricup/intellij-community,petteyg/intellij-community,caot/intellij-community,orekyuu/intellij-community,lucafavatella/intellij-community,michaelgallacher/intellij-community,signed/intellij-community,amith01994/intellij-community,nicolargo/intellij-community,blademainer/intellij-community,tmpgit/intellij-community,robovm/robovm-studio,petteyg/intellij-community,allotria/intellij-community,joewalnes/idea-community,MER-GROUP/intellij-community,youdonghai/intellij-community,ibinti/intellij-community,nicolargo/intellij-community,joewalnes/idea-community,semonte/intellij-community,muntasirsyed/intellij-community,MichaelNedzelsky/intellij-community,kdwink/intellij-community,signed/intellij-community,MER-GROUP/intellij-community,ibinti/intellij-community,alphafoobar/intellij-community,petteyg/intellij-community,samthor/intellij-community,fengbaicanhe/intellij-community,TangHao1987/intellij-community,holmes/intellij-community,kool79/intellij-community,suncycheng/intellij-community,MichaelNedzelsky/intellij-community,xfournet/intellij-community,ibinti/intellij-community,orekyuu/intellij-community,wreckJ/intellij-community,SerCeMan/intellij-community,FHannes/intellij-community,Distrotech/intellij-community,fitermay/intellij-community,salguarnieri/intellij-community,ThiagoGarciaAlves/intellij-community,youdonghai/intellij-community,amith01994/intellij-community,FHannes/intellij-community,xfournet/intellij-community,slisson/intellij-community,wreckJ/intellij-community,FHannes/intellij-community,signed/intellij-community,SerCeMan/intellij-community,da1z/intellij-community,semonte/intellij-community,michaelgallacher/intellij-community,MER-GROUP/intellij-community,clumsy/intellij-community,izonder/intellij-community,diorcety/intellij-community,caot/intellij-community,michaelgallacher/intellij-community,ahb0327/intellij-community,FHannes/intellij-community,lucafavatella/intellij-community,diorcety/intellij-community,caot/intellij-community,samthor/intellij-community,MichaelNedzelsky/intellij-community,FHannes/intellij-community,lucafavatella/intellij-community,hurricup/intellij-community,fnouama/intellij-community,joewalnes/idea-community,fnouama/intellij-community,jexp/idea2,izonder/intellij-community,supersven/intellij-community,fnouama/intellij-community,holmes/intellij-community,ryano144/intellij-community,lucafavatella/intellij-community,TangHao1987/intellij-community,ibinti/intellij-community,youdonghai/intellij-community,TangHao1987/intellij-community,petteyg/intellij-community,ftomassetti/intellij-community,MER-GROUP/intellij-community,holmes/intellij-community,kdwink/intellij-community,TangHao1987/intellij-community,akosyakov/intellij-community,suncycheng/intellij-community,vladmm/intellij-community,kdwink/intellij-community,SerCeMan/intellij-community,michaelgallacher/intellij-community,ftomassetti/intellij-community,alphafoobar/intellij-community,supersven/intellij-community,allotria/intellij-community,supersven/intellij-community,jagguli/intellij-community,nicolargo/intellij-community,amith01994/intellij-community,izonder/intellij-community,fitermay/intellij-community,ftomassetti/intellij-community,ThiagoGarciaAlves/intellij-community,michaelgallacher/intellij-community,semonte/intellij-community,da1z/intellij-community,adedayo/intellij-community,mglukhikh/intellij-community,michaelgallacher/intellij-community,mglukhikh/intellij-community,robovm/robovm-studio,jagguli/intellij-community,retomerz/intellij-community,ibinti/intellij-community,retomerz/intellij-community,allotria/intellij-community,ernestp/consulo,salguarnieri/intellij-community,ernestp/consulo,kool79/intellij-community,semonte/intellij-community,orekyuu/intellij-community,vvv1559/intellij-community,salguarnieri/intellij-community,jagguli/intellij-community,clumsy/intellij-community,consulo/consulo,robovm/robovm-studio,hurricup/intellij-community,wreckJ/intellij-community,akosyakov/intellij-community,diorcety/intellij-community,ahb0327/intellij-community,jexp/idea2,orekyuu/intellij-community,ryano144/intellij-community,slisson/intellij-community,orekyuu/intellij-community,asedunov/intellij-community,Lekanich/intellij-community,idea4bsd/idea4bsd,slisson/intellij-community,apixandru/intellij-community,signed/intellij-community,ol-loginov/intellij-community,joewalnes/idea-community,adedayo/intellij-community,clumsy/intellij-community,vladmm/intellij-community,clumsy/intellij-community,robovm/robovm-studio,MER-GROUP/intellij-community,vvv1559/intellij-community,lucafavatella/intellij-community,da1z/intellij-community,apixandru/intellij-community,joewalnes/idea-community,MichaelNedzelsky/intellij-community,adedayo/intellij-community,clumsy/intellij-community,muntasirsyed/intellij-community,slisson/intellij-community,ahb0327/intellij-community,signed/intellij-community,semonte/intellij-community,pwoodworth/intellij-community,semonte/intellij-community,ivan-fedorov/intellij-community,adedayo/intellij-community,samthor/intellij-community,orekyuu/intellij-community,vvv1559/intellij-community,izonder/intellij-community,caot/intellij-community,TangHao1987/intellij-community,ibinti/intellij-community,wreckJ/intellij-community,wreckJ/intellij-community,akosyakov/intellij-community,suncycheng/intellij-community,Lekanich/intellij-community,allotria/intellij-community,fitermay/intellij-community,samthor/intellij-community,SerCeMan/intellij-community,mglukhikh/intellij-community,alphafoobar/intellij-community,fengbaicanhe/intellij-community,kdwink/intellij-community,MichaelNedzelsky/intellij-community,amith01994/intellij-community,amith01994/intellij-community,clumsy/intellij-community,da1z/intellij-community,holmes/intellij-community,Lekanich/intellij-community,idea4bsd/idea4bsd,MichaelNedzelsky/intellij-community,idea4bsd/idea4bsd,dslomov/intellij-community,mglukhikh/intellij-community,nicolargo/intellij-community,kool79/intellij-community,ol-loginov/intellij-community,petteyg/intellij-community,fnouama/intellij-community,signed/intellij-community,alphafoobar/intellij-community,Lekanich/intellij-community,consulo/consulo,TangHao1987/intellij-community,robovm/robovm-studio,ryano144/intellij-community,SerCeMan/intellij-community,apixandru/intellij-community,vvv1559/intellij-community,salguarnieri/intellij-community,izonder/intellij-community,dslomov/intellij-community,kool79/intellij-community,da1z/intellij-community,tmpgit/intellij-community,MichaelNedzelsky/intellij-community,tmpgit/intellij-community,SerCeMan/intellij-community,supersven/intellij-community,dslomov/intellij-community,allotria/intellij-community,fnouama/intellij-community,blademainer/intellij-community,kool79/intellij-community,idea4bsd/idea4bsd,ernestp/consulo,MichaelNedzelsky/intellij-community,supersven/intellij-community,kool79/intellij-community,salguarnieri/intellij-community,orekyuu/intellij-community,apixandru/intellij-community,suncycheng/intellij-community,FHannes/intellij-community,amith01994/intellij-community,ThiagoGarciaAlves/intellij-community,dslomov/intellij-community,apixandru/intellij-community,nicolargo/intellij-community,youdonghai/intellij-community,pwoodworth/intellij-community,ivan-fedorov/intellij-community,pwoodworth/intellij-community,ftomassetti/intellij-community,SerCeMan/intellij-community,holmes/intellij-community,xfournet/intellij-community,blademainer/intellij-community,tmpgit/intellij-community,ivan-fedorov/intellij-community,clumsy/intellij-community,caot/intellij-community,petteyg/intellij-community,fnouama/intellij-community,blademainer/intellij-community,lucafavatella/intellij-community,jagguli/intellij-community,idea4bsd/idea4bsd,mglukhikh/intellij-community,ol-loginov/intellij-community,slisson/intellij-community,hurricup/intellij-community,apixandru/intellij-community,vvv1559/intellij-community,alphafoobar/intellij-community,da1z/intellij-community,samthor/intellij-community,suncycheng/intellij-community,samthor/intellij-community,mglukhikh/intellij-community,ol-loginov/intellij-community,retomerz/intellij-community,youdonghai/intellij-community,michaelgallacher/intellij-community,xfournet/intellij-community,ol-loginov/intellij-community,adedayo/intellij-community,fnouama/intellij-community,jexp/idea2,holmes/intellij-community,semonte/intellij-community,da1z/intellij-community,vvv1559/intellij-community,samthor/intellij-community,MER-GROUP/intellij-community,signed/intellij-community,asedunov/intellij-community,jexp/idea2,youdonghai/intellij-community,supersven/intellij-community,youdonghai/intellij-community,vladmm/intellij-community,idea4bsd/idea4bsd,ryano144/intellij-community,ibinti/intellij-community,MER-GROUP/intellij-community,petteyg/intellij-community,kool79/intellij-community,tmpgit/intellij-community,ftomassetti/intellij-community,blademainer/intellij-community,dslomov/intellij-community,blademainer/intellij-community,da1z/intellij-community,ernestp/consulo,apixandru/intellij-community,clumsy/intellij-community,suncycheng/intellij-community,fnouama/intellij-community,apixandru/intellij-community,dslomov/intellij-community,robovm/robovm-studio,FHannes/intellij-community,izonder/intellij-community,ahb0327/intellij-community,alphafoobar/intellij-community,ivan-fedorov/intellij-community,jagguli/intellij-community,diorcety/intellij-community,salguarnieri/intellij-community,youdonghai/intellij-community,vvv1559/intellij-community,MichaelNedzelsky/intellij-community,gnuhub/intellij-community,ibinti/intellij-community,lucafavatella/intellij-community,kdwink/intellij-community,MichaelNedzelsky/intellij-community,tmpgit/intellij-community,TangHao1987/intellij-community,mglukhikh/intellij-community,muntasirsyed/intellij-community,wreckJ/intellij-community,joewalnes/idea-community,robovm/robovm-studio,pwoodworth/intellij-community,xfournet/intellij-community,petteyg/intellij-community,dslomov/intellij-community,gnuhub/intellij-community,idea4bsd/idea4bsd,idea4bsd/idea4bsd,youdonghai/intellij-community,hurricup/intellij-community,gnuhub/intellij-community,izonder/intellij-community,consulo/consulo,xfournet/intellij-community,asedunov/intellij-community,gnuhub/intellij-community,youdonghai/intellij-community,petteyg/intellij-community,lucafavatella/intellij-community,hurricup/intellij-community,ThiagoGarciaAlves/intellij-community,dslomov/intellij-community,asedunov/intellij-community,diorcety/intellij-community,tmpgit/intellij-community,tmpgit/intellij-community,michaelgallacher/intellij-community,tmpgit/intellij-community,amith01994/intellij-community,ol-loginov/intellij-community,vvv1559/intellij-community,holmes/intellij-community,pwoodworth/intellij-community,orekyuu/intellij-community,fitermay/intellij-community,youdonghai/intellij-community,ThiagoGarciaAlves/intellij-community,retomerz/intellij-community,robovm/robovm-studio,vladmm/intellij-community,Lekanich/intellij-community,michaelgallacher/intellij-community,youdonghai/intellij-community,vvv1559/intellij-community,asedunov/intellij-community,muntasirsyed/intellij-community,consulo/consulo,ernestp/consulo,TangHao1987/intellij-community,ftomassetti/intellij-community,clumsy/intellij-community,allotria/intellij-community,suncycheng/intellij-community,alphafoobar/intellij-community,dslomov/intellij-community,muntasirsyed/intellij-community,ivan-fedorov/intellij-community,idea4bsd/idea4bsd,alphafoobar/intellij-community,caot/intellij-community,suncycheng/intellij-community,salguarnieri/intellij-community,suncycheng/intellij-community,wreckJ/intellij-community,hurricup/intellij-community,asedunov/intellij-community,ahb0327/intellij-community,Lekanich/intellij-community,SerCeMan/intellij-community,joewalnes/idea-community,youdonghai/intellij-community,ThiagoGarciaAlves/intellij-community,fitermay/intellij-community,robovm/robovm-studio,FHannes/intellij-community,xfournet/intellij-community,asedunov/intellij-community,alphafoobar/intellij-community,fnouama/intellij-community,allotria/intellij-community,semonte/intellij-community,signed/intellij-community,fengbaicanhe/intellij-community,ThiagoGarciaAlves/intellij-community,Lekanich/intellij-community,pwoodworth/intellij-community,kool79/intellij-community,fengbaicanhe/intellij-community,petteyg/intellij-community,ftomassetti/intellij-community,lucafavatella/intellij-community,asedunov/intellij-community,ftomassetti/intellij-community,Distrotech/intellij-community,robovm/robovm-studio,kdwink/intellij-community,adedayo/intellij-community,ftomassetti/intellij-community,asedunov/intellij-community,samthor/intellij-community,allotria/intellij-community,ivan-fedorov/intellij-community,samthor/intellij-community,retomerz/intellij-community,retomerz/intellij-community,hurricup/intellij-community,akosyakov/intellij-community,ahb0327/intellij-community,allotria/intellij-community,izonder/intellij-community,apixandru/intellij-community,tmpgit/intellij-community,izonder/intellij-community,retomerz/intellij-community,ryano144/intellij-community,fnouama/intellij-community,samthor/intellij-community,MER-GROUP/intellij-community,FHannes/intellij-community,petteyg/intellij-community,ibinti/intellij-community,gnuhub/intellij-community,adedayo/intellij-community,FHannes/intellij-community,suncycheng/intellij-community,lucafavatella/intellij-community,wreckJ/intellij-community,ivan-fedorov/intellij-community,joewalnes/idea-community,mglukhikh/intellij-community,SerCeMan/intellij-community,dslomov/intellij-community,apixandru/intellij-community,lucafavatella/intellij-community,hurricup/intellij-community,jexp/idea2,alphafoobar/intellij-community,muntasirsyed/intellij-community,clumsy/intellij-community,tmpgit/intellij-community,akosyakov/intellij-community,jagguli/intellij-community,gnuhub/intellij-community,dslomov/intellij-community,holmes/intellij-community,pwoodworth/intellij-community,ThiagoGarciaAlves/intellij-community,jexp/idea2,robovm/robovm-studio,mglukhikh/intellij-community,slisson/intellij-community,retomerz/intellij-community,muntasirsyed/intellij-community,allotria/intellij-community,gnuhub/intellij-community,blademainer/intellij-community,gnuhub/intellij-community,Lekanich/intellij-community,retomerz/intellij-community,xfournet/intellij-community,wreckJ/intellij-community,semonte/intellij-community,jexp/idea2,jagguli/intellij-community,mglukhikh/intellij-community,ryano144/intellij-community,blademainer/intellij-community,vladmm/intellij-community,gnuhub/intellij-community,pwoodworth/intellij-community,ol-loginov/intellij-community,blademainer/intellij-community,caot/intellij-community,ahb0327/intellij-community,MER-GROUP/intellij-community,nicolargo/intellij-community,fengbaicanhe/intellij-community,slisson/intellij-community,akosyakov/intellij-community,Lekanich/intellij-community,orekyuu/intellij-community,ahb0327/intellij-community,MER-GROUP/intellij-community,idea4bsd/idea4bsd,allotria/intellij-community,MER-GROUP/intellij-community,vladmm/intellij-community,fengbaicanhe/intellij-community,Distrotech/intellij-community,akosyakov/intellij-community,slisson/intellij-community,xfournet/intellij-community,Distrotech/intellij-community,Distrotech/intellij-community,joewalnes/idea-community,xfournet/intellij-community,ahb0327/intellij-community,Lekanich/intellij-community,amith01994/intellij-community,fengbaicanhe/intellij-community,fitermay/intellij-community,vvv1559/intellij-community,FHannes/intellij-community,retomerz/intellij-community,jagguli/intellij-community,fitermay/intellij-community,Distrotech/intellij-community,TangHao1987/intellij-community,kdwink/intellij-community,adedayo/intellij-community,ftomassetti/intellij-community,ivan-fedorov/intellij-community,hurricup/intellij-community,MichaelNedzelsky/intellij-community,TangHao1987/intellij-community,ryano144/intellij-community,pwoodworth/intellij-community,amith01994/intellij-community,TangHao1987/intellij-community,slisson/intellij-community,kdwink/intellij-community,asedunov/intellij-community | package com.intellij.testFramework;
import com.intellij.execution.process.OSProcessHandler;
import com.intellij.execution.process.ProcessAdapter;
import com.intellij.execution.process.ProcessEvent;
import com.intellij.execution.process.ProcessOutputTypes;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.command.CommandProcessor;
import com.intellij.openapi.components.ProjectComponent;
import com.intellij.openapi.diff.LineTokenizer;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Key;
import com.intellij.openapi.util.Ref;
import com.intellij.openapi.vcs.AbstractVcs;
import com.intellij.openapi.vcs.ProjectLevelVcsManager;
import com.intellij.openapi.vcs.VcsConfiguration;
import com.intellij.openapi.vcs.VcsShowConfirmationOption;
import com.intellij.openapi.vcs.changes.ChangeListManager;
import com.intellij.openapi.vcs.changes.VcsDirtyScope;
import com.intellij.openapi.vcs.changes.VcsDirtyScopeManager;
import com.intellij.openapi.vfs.CharsetToolkit;
import com.intellij.openapi.vfs.LocalFileSystem;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.testFramework.builders.JavaModuleFixtureBuilder;
import com.intellij.testFramework.fixtures.IdeaProjectTestFixture;
import com.intellij.testFramework.fixtures.IdeaTestFixtureFactory;
import com.intellij.testFramework.fixtures.TestFixtureBuilder;
import org.jetbrains.annotations.Nullable;
import org.junit.Assert;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/**
* @author yole
*/
public class AbstractVcsTestCase {
protected Project myProject;
protected VirtualFile myWorkingCopyDir;
protected File myClientBinaryPath;
protected IdeaProjectTestFixture myProjectFixture;
protected RunResult runClient(String exeName, @Nullable String stdin, @Nullable final File workingDir, String[] commandLine) throws IOException {
final List<String> arguments = new ArrayList<String>();
arguments.add(new File(myClientBinaryPath, exeName).toString());
Collections.addAll(arguments, commandLine);
final ProcessBuilder builder = new ProcessBuilder().command(arguments);
if (workingDir != null) {
builder.directory(workingDir);
}
Process clientProcess = builder.start();
final RunResult result = new RunResult();
if (stdin != null) {
OutputStream outputStream = clientProcess.getOutputStream();
try {
byte[] bytes = stdin.getBytes();
outputStream.write(bytes);
}
finally {
outputStream.close();
}
}
OSProcessHandler handler = new OSProcessHandler(clientProcess, "") {
public Charset getCharset() {
return CharsetToolkit.getDefaultSystemCharset();
}
};
handler.addProcessListener(new ProcessAdapter() {
public void onTextAvailable(final ProcessEvent event, final Key outputType) {
if (outputType == ProcessOutputTypes.STDOUT) {
result.stdOut += event.getText();
}
else if (outputType == ProcessOutputTypes.STDERR) {
result.stdErr += event.getText();
}
}
});
handler.startNotify();
handler.waitFor();
result.exitCode = clientProcess.exitValue();
return result;
}
protected void initProject(final File clientRoot) throws Exception {
final TestFixtureBuilder<IdeaProjectTestFixture> testFixtureBuilder = IdeaTestFixtureFactory.getFixtureFactory().createFixtureBuilder();
myProjectFixture = testFixtureBuilder.getFixture();
testFixtureBuilder.addModule(JavaModuleFixtureBuilder.class).addContentRoot(clientRoot.toString());
myProjectFixture.setUp();
myProject = myProjectFixture.getProject();
((ProjectComponent) ChangeListManager.getInstance(myProject)).projectOpened();
((ProjectComponent) VcsDirtyScopeManager.getInstance(myProject)).projectOpened();
ApplicationManager.getApplication().runWriteAction(new Runnable() {
public void run() {
myWorkingCopyDir = LocalFileSystem.getInstance().refreshAndFindFileByIoFile(clientRoot);
assert myWorkingCopyDir != null;
}
});
}
protected void activateVCS(final String vcsName) {
ProjectLevelVcsManager vcsManager = ProjectLevelVcsManager.getInstance(myProject);
vcsManager.setDirectoryMapping(myWorkingCopyDir.getPath(), vcsName);
vcsManager.updateActiveVcss();
AbstractVcs vcs = vcsManager.findVcsByName(vcsName);
Assert.assertEquals(1, vcsManager.getRootsUnderVcs(vcs).length);
}
protected VirtualFile createFileInCommand(final String name, @Nullable final String content) {
final Ref<VirtualFile> result = new Ref<VirtualFile>();
CommandProcessor.getInstance().executeCommand(myProject, new Runnable() {
public void run() {
try {
VirtualFile file = myWorkingCopyDir.createChildData(this, name);
if (content != null) {
file.setBinaryContent(CharsetToolkit.getUtf8Bytes(content));
}
result.set(file);
}
catch (IOException e) {
throw new RuntimeException(e);
}
}
}, "", null);
return result.get();
}
protected void tearDownProject() throws Exception {
if (myProject != null) {
((ProjectComponent) VcsDirtyScopeManager.getInstance(myProject)).projectClosed();
((ProjectComponent) ChangeListManager.getInstance(myProject)).projectClosed();
((ProjectComponent) ProjectLevelVcsManager.getInstance(myProject)).projectClosed();
myProject = null;
}
if (myProjectFixture != null) {
myProjectFixture.tearDown();
myProjectFixture = null;
}
}
protected void enableSilentOperation(final String vcsName, final VcsConfiguration.StandardConfirmation op) {
ProjectLevelVcsManager vcsManager = ProjectLevelVcsManager.getInstance(myProject);
final AbstractVcs vcs = vcsManager.findVcsByName(vcsName);
VcsShowConfirmationOption option = vcsManager.getStandardConfirmation(op, vcs);
option.setValue(VcsShowConfirmationOption.Value.DO_ACTION_SILENTLY);
}
protected void verify(final RunResult runResult) {
Assert.assertEquals(runResult.stdErr, 0, runResult.exitCode);
}
protected void verify(final RunResult runResult, final String... stdoutLines) {
verify(runResult);
final String[] lines = new LineTokenizer(runResult.stdOut).execute();
Assert.assertEquals(stdoutLines.length, lines.length);
for(int i=0; i<stdoutLines.length; i++) {
Assert.assertEquals(stdoutLines [i], compressWhitespace(lines [i]));
}
}
private String compressWhitespace(String line) {
while(line.indexOf(" ") > 0) {
line = line.replace(" ", " ");
}
return line.trim();
}
protected VcsDirtyScope getAllDirtyScope() {
VcsDirtyScopeManager dirtyScopeManager = VcsDirtyScopeManager.getInstance(myProject);
dirtyScopeManager.markEverythingDirty();
List<VcsDirtyScope> scopes = dirtyScopeManager.retrieveScopes();
Assert.assertEquals(1, scopes.size());
return scopes.get(0);
}
protected void renameFileInCommand(final VirtualFile fileToAdd, final String newName) {
CommandProcessor.getInstance().executeCommand(myProject, new Runnable() {
public void run() {
try {
fileToAdd.rename(this, newName);
}
catch (IOException e) {
throw new RuntimeException(e);
}
}
}, "", null);
}
protected class RunResult {
public int exitCode = -1;
public String stdOut = "";
public String stdErr = "";
}
} | openapi/src/com/intellij/testFramework/AbstractVcsTestCase.java | package com.intellij.testFramework;
import com.intellij.execution.process.OSProcessHandler;
import com.intellij.execution.process.ProcessAdapter;
import com.intellij.execution.process.ProcessEvent;
import com.intellij.execution.process.ProcessOutputTypes;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.command.CommandProcessor;
import com.intellij.openapi.components.ProjectComponent;
import com.intellij.openapi.diff.LineTokenizer;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Key;
import com.intellij.openapi.util.Ref;
import com.intellij.openapi.vcs.AbstractVcs;
import com.intellij.openapi.vcs.ProjectLevelVcsManager;
import com.intellij.openapi.vcs.VcsConfiguration;
import com.intellij.openapi.vcs.VcsShowConfirmationOption;
import com.intellij.openapi.vcs.changes.ChangeListManager;
import com.intellij.openapi.vcs.changes.VcsDirtyScope;
import com.intellij.openapi.vcs.changes.VcsDirtyScopeManager;
import com.intellij.openapi.vfs.CharsetToolkit;
import com.intellij.openapi.vfs.LocalFileSystem;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.testFramework.builders.JavaModuleFixtureBuilder;
import com.intellij.testFramework.fixtures.IdeaProjectTestFixture;
import com.intellij.testFramework.fixtures.IdeaTestFixtureFactory;
import com.intellij.testFramework.fixtures.TestFixtureBuilder;
import org.jetbrains.annotations.Nullable;
import org.junit.Assert;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* @author yole
*/
public class AbstractVcsTestCase {
protected Project myProject;
protected VirtualFile myWorkingCopyDir;
protected File myClientBinaryPath;
protected IdeaProjectTestFixture myProjectFixture;
protected RunResult runClient(String exeName, @Nullable String stdin, @Nullable final File workingDir, String[] commandLine) throws IOException {
final List<String> arguments = new ArrayList<String>();
arguments.add(new File(myClientBinaryPath, exeName).toString());
Collections.addAll(arguments, commandLine);
final ProcessBuilder builder = new ProcessBuilder().command(arguments);
if (workingDir != null) {
builder.directory(workingDir);
}
Process clientProcess = builder.start();
final RunResult result = new RunResult();
if (stdin != null) {
OutputStream outputStream = clientProcess.getOutputStream();
try {
byte[] bytes = stdin.getBytes();
outputStream.write(bytes);
}
finally {
outputStream.close();
}
}
OSProcessHandler handler = new OSProcessHandler(clientProcess, "") {
public Charset getCharset() {
return CharsetToolkit.getDefaultSystemCharset();
}
};
handler.addProcessListener(new ProcessAdapter() {
public void onTextAvailable(final ProcessEvent event, final Key outputType) {
if (outputType == ProcessOutputTypes.STDOUT) {
result.stdOut += event.getText();
}
else if (outputType == ProcessOutputTypes.STDERR) {
result.stdErr += event.getText();
}
}
});
handler.startNotify();
handler.waitFor();
result.exitCode = clientProcess.exitValue();
return result;
}
protected void initProject(final File clientRoot) throws Exception {
final TestFixtureBuilder<IdeaProjectTestFixture> testFixtureBuilder = IdeaTestFixtureFactory.getFixtureFactory().createFixtureBuilder();
myProjectFixture = testFixtureBuilder.getFixture();
testFixtureBuilder.addModule(JavaModuleFixtureBuilder.class).addContentRoot(clientRoot.toString());
myProjectFixture.setUp();
myProject = myProjectFixture.getProject();
((ProjectComponent) ChangeListManager.getInstance(myProject)).projectOpened();
((ProjectComponent) VcsDirtyScopeManager.getInstance(myProject)).projectOpened();
ApplicationManager.getApplication().runWriteAction(new Runnable() {
public void run() {
myWorkingCopyDir = LocalFileSystem.getInstance().refreshAndFindFileByIoFile(clientRoot);
assert myWorkingCopyDir != null;
}
});
}
protected void activateVCS(final String vcsName) {
ProjectLevelVcsManager vcsManager = ProjectLevelVcsManager.getInstance(myProject);
vcsManager.setDirectoryMapping(myWorkingCopyDir.getPath(), vcsName);
vcsManager.updateActiveVcss();
AbstractVcs vcs = vcsManager.findVcsByName(vcsName);
Assert.assertEquals(1, vcsManager.getRootsUnderVcs(vcs).length);
}
protected VirtualFile createFileInCommand(final String name, @Nullable final String content) {
final Ref<VirtualFile> result = new Ref<VirtualFile>();
CommandProcessor.getInstance().executeCommand(myProject, new Runnable() {
public void run() {
try {
VirtualFile file = myWorkingCopyDir.createChildData(this, name);
if (content != null) {
file.setBinaryContent(CharsetToolkit.getUtf8Bytes(content));
}
result.set(file);
}
catch (IOException e) {
throw new RuntimeException(e);
}
}
}, "", null);
return result.get();
}
protected void tearDownProject() throws Exception {
if (myProject != null) {
((ProjectComponent) VcsDirtyScopeManager.getInstance(myProject)).projectClosed();
((ProjectComponent) ChangeListManager.getInstance(myProject)).projectClosed();
((ProjectComponent) ProjectLevelVcsManager.getInstance(myProject)).projectClosed();
myProject = null;
}
if (myProjectFixture != null) {
myProjectFixture.tearDown();
myProjectFixture = null;
}
}
protected void enableSilentOperation(final String vcsName, final VcsConfiguration.StandardConfirmation op) {
ProjectLevelVcsManager vcsManager = ProjectLevelVcsManager.getInstance(myProject);
final AbstractVcs vcs = vcsManager.findVcsByName(vcsName);
VcsShowConfirmationOption option = vcsManager.getStandardConfirmation(op, vcs);
option.setValue(VcsShowConfirmationOption.Value.DO_ACTION_SILENTLY);
}
protected void verify(final RunResult runResult) {
Assert.assertEquals(runResult.stdErr, 0, runResult.exitCode);
}
protected void verify(final RunResult runResult, final String... stdoutLines) {
verify(runResult);
final String[] lines = new LineTokenizer(runResult.stdOut).execute();
for(int i=0; i<stdoutLines.length; i++) {
final Pattern pattern = Pattern.compile(stdoutLines [i]);
final Matcher matcher = pattern.matcher(lines [i].trim());
Assert.assertTrue(lines [i], matcher.find());
}
}
protected VcsDirtyScope getAllDirtyScope() {
VcsDirtyScopeManager dirtyScopeManager = VcsDirtyScopeManager.getInstance(myProject);
dirtyScopeManager.markEverythingDirty();
List<VcsDirtyScope> scopes = dirtyScopeManager.retrieveScopes();
Assert.assertEquals(1, scopes.size());
return scopes.get(0);
}
protected void renameFileInCommand(final VirtualFile fileToAdd, final String newName) {
CommandProcessor.getInstance().executeCommand(myProject, new Runnable() {
public void run() {
try {
fileToAdd.rename(this, newName);
}
catch (IOException e) {
throw new RuntimeException(e);
}
}
}, "", null);
}
protected class RunResult {
public int exitCode = -1;
public String stdOut = "";
public String stdErr = "";
}
} | test that fails: rename with replace
| openapi/src/com/intellij/testFramework/AbstractVcsTestCase.java | test that fails: rename with replace | <ide><path>penapi/src/com/intellij/testFramework/AbstractVcsTestCase.java
<ide> import java.util.ArrayList;
<ide> import java.util.Collections;
<ide> import java.util.List;
<del>import java.util.regex.Matcher;
<del>import java.util.regex.Pattern;
<ide>
<ide> /**
<ide> * @author yole
<ide> protected void verify(final RunResult runResult, final String... stdoutLines) {
<ide> verify(runResult);
<ide> final String[] lines = new LineTokenizer(runResult.stdOut).execute();
<add> Assert.assertEquals(stdoutLines.length, lines.length);
<ide> for(int i=0; i<stdoutLines.length; i++) {
<del> final Pattern pattern = Pattern.compile(stdoutLines [i]);
<del> final Matcher matcher = pattern.matcher(lines [i].trim());
<del> Assert.assertTrue(lines [i], matcher.find());
<del> }
<add> Assert.assertEquals(stdoutLines [i], compressWhitespace(lines [i]));
<add> }
<add> }
<add>
<add> private String compressWhitespace(String line) {
<add> while(line.indexOf(" ") > 0) {
<add> line = line.replace(" ", " ");
<add> }
<add> return line.trim();
<ide> }
<ide>
<ide> protected VcsDirtyScope getAllDirtyScope() { |
|
Java | mit | 2477dd4702f905ea040b558ee0b355b493d354cc | 0 | iimog/bcgTree,iimog/bcgTree,iimog/bcgTree,iimog/bcgTree,iimog/bcgTree | package bcgTree.gui;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.TextArea;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.awt.image.BufferedImage;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.TreeMap;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JProgressBar;
import javax.swing.JScrollPane;
import javax.swing.JSpinner;
import javax.swing.JTextField;
import javax.swing.SpinnerNumberModel;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.UIManager.LookAndFeelInfo;
public class BcgTree extends JFrame {
private static final long serialVersionUID = 1L;
public static final String VERSION = "1.0.10";
private static final int DEFAULT_TEXTFIELD_COLUMNS = 30;
public static void main(String[] args) {
BcgTree mainWindow = new BcgTree();
mainWindow.pack();
mainWindow.setVisible(true);
}
private Map<String, File> proteomes;
private Map<String, File> genomes;
private String outdir;
private String hmmsearch_bin = "";
private String muscle_bin = "";
private String gblocks_bin = "";
private String raxml_bin = "";
private String prodigal_bin = "";
private TextArea logTextArea;
private JPanel proteomesPanel;
private Map<JTextField, String> proteomeTextFields;
private JTextField outdirTextField;
private JProgressBar progressBar;
private BcgTree self;
private JButton runButton;
private JPanel settingsPanel;
private Map<String, JTextField> programPaths = new HashMap<String, JTextField>();
private JPanel checkProgramsPanel;
private JSpinner bootstrapSpinner;
private JSpinner threadsSpinner;
private JTextField randomSeedXTextField;
private JTextField randomSeedPTextField;
private JTextField hmmfileTextField;
private JSpinner minProteomesSpinner;
private JCheckBox allProteomesCheckbox;
private JTextField raxmlAaSubstitutionModelTextField;
private JTextField raxmlArgsTextField;
private JPanel genomesPanel;
public BcgTree() {
self = this;
proteomes = new TreeMap<String, File>();
genomes = new TreeMap<String, File>();
outdir = System.getProperty("user.home") + "/bcgTree";
loadGlobalSettings();
initGUI();
}
public void initGUI() {
// Basic settings
this.setTitle("bcgTree " + VERSION);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setLayout(new BorderLayout());
// Set look and file
try {
for (LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (Exception e) {
// If Nimbus is not available, you can set the GUI to another look and feel.
}
// Add central panel (split in parameter section and log/output section)
JPanel mainPanel = new JPanel();
mainPanel.setLayout(new GridLayout(1, 2));
this.add(mainPanel, BorderLayout.CENTER);
settingsPanel = new JPanel();
JScrollPane settingsScrollPane = new JScrollPane(settingsPanel);
settingsPanel.setLayout(new GridBagLayout());
mainPanel.add(settingsScrollPane);
JPanel logPanel = new JPanel();
logPanel.setLayout(new BorderLayout());
mainPanel.add(logPanel);
// Add Elements to settingsPanel
// proteome settings
JPanel proteomesPane = new JPanel();
Accordion proteomeAccordion = new Accordion("Add proteomes (peptide fasta)", proteomesPane);
GridBagConstraints c = new GridBagConstraints();
c.fill = GridBagConstraints.HORIZONTAL;
c.gridx = 0;
c.gridy = 0;
settingsPanel.add(proteomeAccordion, c);
JButton proteomesAddButton = new JButton("+");
proteomesAddButton.addActionListener(proteomeAddActionListener);
proteomesPane.add(proteomesAddButton);
proteomesPanel = new JPanel();
proteomesPanel.setLayout(new GridBagLayout());
proteomesPane.add(proteomesPanel);
// genome settings
JPanel genomePane = new JPanel();
Accordion genomeAccordion = new Accordion("Add genomes (nucleotide fasta, will be translated)", genomePane);
c = new GridBagConstraints();
c.fill = GridBagConstraints.HORIZONTAL;
c.gridx = 0;
c.gridy = 1;
settingsPanel.add(genomeAccordion, c);
JButton genomeAddButton = new JButton("+");
genomeAddButton.addActionListener(genomeAddActionListener);
genomePane.add(genomeAddButton);
genomesPanel = new JPanel();
genomesPanel.setLayout(new GridBagLayout());
genomePane.add(genomesPanel);
// outputdir settings
JPanel outdirPane = new JPanel();
JLabel outdirLabel = new JLabel("Output directory:");
outdirPane.add(outdirLabel);
outdirTextField = new JTextField(outdir, DEFAULT_TEXTFIELD_COLUMNS);
outdirPane.add(outdirTextField);
JButton outdirChooseButton = new JButton("choose");
outdirChooseButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
openOutdirChooseDialog();
}
});
outdirPane.add(outdirChooseButton);
Accordion outdirAccordion = new Accordion("Set output directory", outdirPane);
c = new GridBagConstraints();
c.fill = GridBagConstraints.HORIZONTAL;
c.gridx = 0;
c.gridy = 2;
settingsPanel.add(outdirAccordion, c);
// Add check programms
JPanel checkProgramsMainPanel = new JPanel(new BorderLayout());
checkProgramsPanel = new JPanel(new GridBagLayout());
checkProgramsMainPanel.add(checkProgramsPanel, BorderLayout.CENTER);
addCheckProgramPanel("hmmsearch", hmmsearch_bin, "hmmsearch-bin", 0);
addCheckProgramPanel("muscle", muscle_bin, "muscle-bin", 1);
addCheckProgramPanel("Gblocks", gblocks_bin, "gblocks-bin", 2);
addCheckProgramPanel("RAxML", raxml_bin, "raxml-bin", 3);
addCheckProgramPanel("prodigal", prodigal_bin, "prodigal-bin", 4);
JPanel checkProgramsButtonPanel = new JPanel(new GridLayout(1, 2));
JButton checkProgramsButton = new JButton("check");
checkProgramsButton.addActionListener(checkProgramsActionListener);
checkProgramsButtonPanel.add(checkProgramsButton);
JButton saveProgramsButton = new JButton("save");
saveProgramsButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
saveGlobalSettings();
}
});
checkProgramsButtonPanel.add(saveProgramsButton);
checkProgramsMainPanel.add(checkProgramsButtonPanel, BorderLayout.SOUTH);
Accordion checkProgramsAccordion = new Accordion("Check external programs", checkProgramsMainPanel);
c = new GridBagConstraints();
c.fill = GridBagConstraints.HORIZONTAL;
c.gridx = 0;
c.gridy = 3;
settingsPanel.add(checkProgramsAccordion, c);
// Add check programms
Accordion advancedSettingsAccordion = new Accordion("Advanced settings", getAdvancedSettingsPanel());
c = new GridBagConstraints();
c.fill = GridBagConstraints.HORIZONTAL;
c.gridx = 0;
c.gridy = 4;
settingsPanel.add(advancedSettingsAccordion, c);
// Add "Run" button
runButton = new JButton("Run");
c = new GridBagConstraints();
c.anchor = GridBagConstraints.CENTER;
c.gridx = 0;
c.gridy = 5;
settingsPanel.add(runButton, c);
runButton.addActionListener(runActionListener);
// Add bcgTree logo
try {
BufferedImage logo = ImageIO.read(getClass().getResource("/bcgTree.png"));
JLabel picLabel = new JLabel(new ImageIcon(logo));
logPanel.add(picLabel, BorderLayout.NORTH);
} catch (IOException e1) {
e1.printStackTrace();
}
// Add log textarea
logTextArea = new TextArea();
logTextArea.setEditable(false);
logPanel.add(logTextArea, BorderLayout.CENTER);
// Add progressBar
progressBar = new JProgressBar(0, 100);
logPanel.add(progressBar, BorderLayout.SOUTH);
// final adjustments
SwingUtilities.updateComponentTreeUI(this);
this.pack();
}
private JPanel getAdvancedSettingsPanel() {
JPanel advancedSettingsPanel = new JPanel(new GridLayout(9, 2));
advancedSettingsPanel.add(new JLabel("--bootstraps"));
bootstrapSpinner = new JSpinner(new SpinnerNumberModel(10, 1, 1000, 1));
advancedSettingsPanel.add(bootstrapSpinner);
advancedSettingsPanel.add(new JLabel("--threads"));
threadsSpinner = new JSpinner(new SpinnerNumberModel(2, 1, 80, 1));
advancedSettingsPanel.add(threadsSpinner);
advancedSettingsPanel.add(new JLabel("--raxml-x-rapidBootstrapRandomNumberSeed"));
randomSeedXTextField = new JTextField("", DEFAULT_TEXTFIELD_COLUMNS);
advancedSettingsPanel.add(randomSeedXTextField);
advancedSettingsPanel.add(new JLabel("--raxml-p-parsimonyRandomSeed"));
randomSeedPTextField = new JTextField("", DEFAULT_TEXTFIELD_COLUMNS);
advancedSettingsPanel.add(randomSeedPTextField);
advancedSettingsPanel.add(new JLabel("--raxml-aa-substitution-model"));
raxmlAaSubstitutionModelTextField = new JTextField("AUTO", DEFAULT_TEXTFIELD_COLUMNS);
advancedSettingsPanel.add(raxmlAaSubstitutionModelTextField);
advancedSettingsPanel.add(new JLabel("--raxml-args"));
raxmlArgsTextField = new JTextField("", DEFAULT_TEXTFIELD_COLUMNS);
advancedSettingsPanel.add(raxmlArgsTextField);
advancedSettingsPanel.add(new JLabel("--hmmfile"));
hmmfileTextField = new JTextField(System.getProperty("user.dir") + "/../data/essential.hmm",
DEFAULT_TEXTFIELD_COLUMNS);
advancedSettingsPanel.add(hmmfileTextField);
advancedSettingsPanel.add(new JLabel("--min-proteomes"));
minProteomesSpinner = new JSpinner(new SpinnerNumberModel(2, 1, 10000, 1));
advancedSettingsPanel.add(minProteomesSpinner);
advancedSettingsPanel.add(new JLabel("--all-proteomes"));
allProteomesCheckbox = new JCheckBox();
allProteomesCheckbox.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
minProteomesSpinner.setEnabled(!allProteomesCheckbox.isSelected());
}
});
advancedSettingsPanel.add(allProteomesCheckbox);
return advancedSettingsPanel;
}
protected void openOutdirChooseDialog() {
JFileChooser chooser = new JFileChooser();
chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
int exitOption = chooser.showOpenDialog(this);
if (exitOption == JFileChooser.APPROVE_OPTION) {
outdir = chooser.getSelectedFile().getAbsolutePath();
outdirTextField.setText(outdir);
}
}
ActionListener runActionListener = new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// Clear Textfield
logTextArea.setText("");
logTextArea.setForeground(Color.BLACK);
// Apply changes to proteome names
renameProteomes();
// create outdir and write options file there:
outdir = outdirTextField.getText();
new File(outdir).mkdirs();
PrintWriter writer;
try {
writer = new PrintWriter(outdir + "/options.txt", "UTF-8");
writer.println("--outdir=\"" + outdir + "\"");
writer.println("--bootstraps=" + bootstrapSpinner.getValue());
writer.println("--threads=" + threadsSpinner.getValue());
writer.println("--hmmfile=\"" + hmmfileTextField.getText() + "\"");
if (allProteomesCheckbox.isSelected()) {
writer.println("--all-proteomes");
} else {
writer.println("--min-proteomes=" + minProteomesSpinner.getValue());
}
String pSeed = randomSeedPTextField.getText();
if (!pSeed.equals("")) {
writer.println("--raxml-p-parsimonyRandomSeed=" + pSeed);
}
String xSeed = randomSeedXTextField.getText();
if (!xSeed.equals("")) {
writer.println("--raxml-x-rapidBootstrapRandomNumberSeed=" + xSeed);
}
String raxmlAaSubstitutionModel = raxmlAaSubstitutionModelTextField.getText();
if (!raxmlAaSubstitutionModel.equals("")) {
writer.println("--raxml-aa-substitution-model=\"" + raxmlAaSubstitutionModel
+ "\"");
}
String raxmlArgs = raxmlArgsTextField.getText();
if (!raxmlArgs.equals("")) {
writer.println("--raxml-args=\"" + raxmlArgs + "\"");
}
for (String p : programPaths.keySet()) {
String path = programPaths.get(p).getText();
if (!path.equals("")) {
writer.println("--" + p + "=" + programPaths.get(p).getText());
}
}
for (Map.Entry<String, File> entry : proteomes.entrySet()) {
writer.println("--proteome " + entry.getKey() + "=" + "\""
+ entry.getValue().getAbsolutePath() + "\"");
}
for (Map.Entry<String, File> entry : genomes.entrySet()) {
writer.println("--genome " + entry.getKey() + "=" + "\""
+ entry.getValue().getAbsolutePath() + "\"");
}
writer.close();
} catch (FileNotFoundException | UnsupportedEncodingException e2) {
e2.printStackTrace();
}
try {
Process proc = Runtime.getRuntime().exec("perl " + System.getProperty("user.dir")
+ "/../bin/bcgTree.pl @" + outdir + "/options.txt");
// collect stderr
StreamGobbler errorGobbler = new StreamGobbler(proc.getErrorStream(), "ERROR");
// collect stdout
StreamGobbler outputGobbler = new StreamGobbler(proc.getInputStream(), "OUTPUT");
// start gobblers
errorGobbler.start();
outputGobbler.start();
PostProcessWorker postProcessWorker = new PostProcessWorker(proc);
postProcessWorker.start();
progressBar.setIndeterminate(true);
runButton.setEnabled(false);
} catch (Exception e1) {
e1.printStackTrace();
}
}
};
ActionListener checkProgramsActionListener = new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// Clear Textfield
logTextArea.setText(
"WARNING: It is only checked whether the paths of each program point to an executable file.\nIt is not checked whether it is the correct program.\n\n");
logTextArea.setForeground(Color.BLACK);
try {
String callBcgTree = "perl " + System.getProperty("user.dir")
+ "/../bin/bcgTree.pl --check-external-programs";
for (String p : programPaths.keySet()) {
String path = programPaths.get(p).getText();
if (!path.equals("")) {
callBcgTree += " --" + p + "=" + programPaths.get(p).getText();
}
}
logTextArea.append(callBcgTree + "\n");
Process proc = Runtime.getRuntime().exec(callBcgTree);
// collect stderr
StreamGobbler errorGobbler = new StreamGobbler(proc.getErrorStream(), "ERROR");
// collect stdout
StreamGobbler outputGobbler = new StreamGobbler(proc.getInputStream(), "OUTPUT");
// start gobblers
errorGobbler.start();
outputGobbler.start();
PostCheckWorker postCheckWorker = new PostCheckWorker(proc);
postCheckWorker.start();
} catch (Exception e1) {
e1.printStackTrace();
}
}
};
ActionListener proteomeAddActionListener = new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
proteomeAddAction();
}
};
ActionListener genomeAddActionListener = new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
genomeAddAction();
}
};
private HashMap<JTextField, String> genomeTextFields;
public void proteomeAddAction() {
JFileChooser chooser = new JFileChooser();
chooser.setMultiSelectionEnabled(true);
int exitOption = chooser.showOpenDialog(this);
if (exitOption != JFileChooser.APPROVE_OPTION) {
return;
}
File[] files = chooser.getSelectedFiles();
for (int i = 0; i < files.length; i++) {
String name = files[i].getName().replace(" ", "_");
String path = files[i].getAbsolutePath();
// avoid name collisions (does not matter if name and path are identical)
if (proteomes.get(name) != null && !proteomes.get(name).getAbsolutePath().equals(path)) {
int suffix = 1;
while (proteomes.get(name + "_" + suffix) != null
&& !proteomes.get(name + "_" + suffix).getAbsolutePath().equals(path)) {
suffix++;
}
name = name + "_" + suffix;
}
proteomes.put(name, files[i]);
}
updateProteomePanel();
}
public void genomeAddAction() {
JFileChooser chooser = new JFileChooser();
chooser.setMultiSelectionEnabled(true);
int exitOption = chooser.showOpenDialog(this);
if (exitOption != JFileChooser.APPROVE_OPTION) {
return;
}
File[] files = chooser.getSelectedFiles();
for (int i = 0; i < files.length; i++) {
String name = files[i].getName().replace(" ", "_");
String path = files[i].getAbsolutePath();
// avoid name collisions (does not matter if name and path are identical)
if (genomes.get(name) != null && !genomes.get(name).getAbsolutePath().equals(path)) {
int suffix = 1;
while (genomes.get(name + "_" + suffix) != null
&& !genomes.get(name + "_" + suffix).getAbsolutePath().equals(path)) {
suffix++;
}
name = name + "_" + suffix;
}
genomes.put(name, files[i]);
}
updateGenomePanel();
}
private void addCheckProgramPanel(String name, String currentPath, String commandLineOption, int row) {
JLabel checkProgramLabel = new JLabel(name);
GridBagConstraints c = new GridBagConstraints();
c.gridx = 0;
c.gridy = row;
checkProgramsPanel.add(checkProgramLabel, c);
JTextField checkProgramTextField = new JTextField(currentPath, DEFAULT_TEXTFIELD_COLUMNS);
programPaths.put(commandLineOption, checkProgramTextField);
c = new GridBagConstraints();
c.fill = GridBagConstraints.HORIZONTAL;
c.ipadx = 100;
c.gridx = 1;
c.gridy = row;
checkProgramsPanel.add(checkProgramTextField, c);
JButton outdirChooseButton = new JButton("choose");
outdirChooseButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
String newPath = openProgramChooseDialog();
if (newPath != null) {
checkProgramTextField.setText(newPath);
}
}
});
c = new GridBagConstraints();
c.gridx = 2;
c.gridy = row;
checkProgramsPanel.add(outdirChooseButton, c);
}
protected String openProgramChooseDialog() {
JFileChooser chooser = new JFileChooser();
chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
int exitOption = chooser.showOpenDialog(this);
if (exitOption == JFileChooser.APPROVE_OPTION) {
return chooser.getSelectedFile().getAbsolutePath();
}
return null;
}
public void removeProteome(String name) {
proteomes.remove(name);
renameProteomes();
updateProteomePanel();
}
public void removeGenome(String name) {
genomes.remove(name);
renameGenomes();
updateGenomePanel();
}
public void renameGenomes() {
TreeMap<String, File> newGenomes = new TreeMap<String, File>();
for (Map.Entry<JTextField, String> entry : genomeTextFields.entrySet()) {
if (genomes.containsKey(entry.getValue())) {
newGenomes.put(entry.getKey().getText(), genomes.get(entry.getValue()));
}
}
genomes = newGenomes;
}
public void renameProteomes() {
TreeMap<String, File> newProteomes = new TreeMap<String, File>();
for (Map.Entry<JTextField, String> entry : proteomeTextFields.entrySet()) {
if (proteomes.containsKey(entry.getValue())) {
newProteomes.put(entry.getKey().getText(), proteomes.get(entry.getValue()));
}
}
proteomes = newProteomes;
}
public void updateProteomePanel() {
proteomesPanel.removeAll();
proteomeTextFields = new HashMap<JTextField, String>();
int row = 0;
for (Map.Entry<String, File> entry : proteomes.entrySet()) {
JButton removeButton = new JButton("-");
removeButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
removeProteome(entry.getKey());
}
});
GridBagConstraints c = new GridBagConstraints();
c.gridx = 0;
c.gridy = row;
proteomesPanel.add(removeButton, c);
JTextField proteomeNameTextField = new JTextField(entry.getKey(), DEFAULT_TEXTFIELD_COLUMNS);
proteomeNameTextField.addFocusListener(new FocusListener() {
@Override
public void focusLost(FocusEvent e) {
if (e.isTemporary()) {
return;
}
if (proteomeNameTextField.getText().contains(" ")) {
proteomeNameTextField.setText(
proteomeNameTextField.getText().replace(" ", "_"));
showSpaceInNameWarningDialog();
}
checkDuplicateNames();
}
@Override
public void focusGained(FocusEvent e) {
}
});
proteomeTextFields.put(proteomeNameTextField, entry.getKey());
c = new GridBagConstraints();
c.fill = GridBagConstraints.HORIZONTAL;
c.gridx = 1;
c.gridy = row;
proteomesPanel.add(proteomeNameTextField, c);
JLabel proteomePathLabel = new JLabel(entry.getValue().getAbsolutePath());
c = new GridBagConstraints();
c.fill = GridBagConstraints.HORIZONTAL;
c.gridx = 2;
c.gridy = row;
proteomesPanel.add(proteomePathLabel, c);
row++;
}
this.revalidate();
this.repaint();
}
public void updateGenomePanel() {
genomesPanel.removeAll();
genomeTextFields = new HashMap<JTextField, String>();
int row = 0;
for (Map.Entry<String, File> entry : genomes.entrySet()) {
JButton removeButton = new JButton("-");
removeButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
removeGenome(entry.getKey());
}
});
GridBagConstraints c = new GridBagConstraints();
c.gridx = 0;
c.gridy = row;
genomesPanel.add(removeButton, c);
JTextField genomeNameTextField = new JTextField(entry.getKey(), DEFAULT_TEXTFIELD_COLUMNS);
genomeNameTextField.addFocusListener(new FocusListener() {
@Override
public void focusLost(FocusEvent e) {
if (e.isTemporary()) {
return;
}
if (genomeNameTextField.getText().contains(" ")) {
genomeNameTextField.setText(
genomeNameTextField.getText().replace(" ", "_"));
showSpaceInNameWarningDialog();
}
checkDuplicateNames();
}
@Override
public void focusGained(FocusEvent e) {
}
});
genomeTextFields.put(genomeNameTextField, entry.getKey());
c = new GridBagConstraints();
c.fill = GridBagConstraints.HORIZONTAL;
c.gridx = 1;
c.gridy = row;
genomesPanel.add(genomeNameTextField, c);
JLabel genomePathLabel = new JLabel(entry.getValue().getAbsolutePath());
c = new GridBagConstraints();
c.fill = GridBagConstraints.HORIZONTAL;
c.gridx = 2;
c.gridy = row;
genomesPanel.add(genomePathLabel, c);
row++;
}
this.revalidate();
this.repaint();
}
protected void showSpaceInNameWarningDialog() {
JOptionPane.showMessageDialog(this,
"The proteome/genome name contained spaces, those have been automatically replaced by underscores.",
"Whitespace Replace Warning", JOptionPane.WARNING_MESSAGE);
}
protected void checkDuplicateNames() {
Set<String> usedNames = new HashSet<String>();
for (JTextField tf : proteomeTextFields.keySet()) {
String name = tf.getText();
if (usedNames.contains(name)) {
JOptionPane.showMessageDialog(this, "The name: '" + name
+ "' is used twice for different proteomes/genomes. Please fix otherwise one of the entries will be lost.",
"Duplicate Name Warning", JOptionPane.WARNING_MESSAGE);
}
usedNames.add(name);
}
for (JTextField tf : genomeTextFields.keySet()) {
String name = tf.getText();
if (usedNames.contains(name)) {
JOptionPane.showMessageDialog(this, "The name: '" + name
+ "' is used twice for different proteomes/genomes. Please fix otherwise one of the entries will be lost.",
"Duplicate Name Warning", JOptionPane.WARNING_MESSAGE);
}
usedNames.add(name);
}
}
// Helper class to process stdout and stderr of the command
// see
// http://www.javaworld.com/article/2071275/core-java/when-runtime-exec---won-t.html?page=2
class StreamGobbler extends Thread {
InputStream is;
String type;
StreamGobbler(InputStream is, String type) {
this.is = is;
this.type = type;
}
public void run() {
try {
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String line = null;
while ((line = br.readLine()) != null)
logTextArea.append(line + "\n");
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
}
// Helper class to check state of the process and reset GUI on finish
class PostProcessWorker extends Thread {
Process process;
PostProcessWorker(Process process) {
this.process = process;
}
public void run() {
int exitVal;
try {
exitVal = this.process.waitFor();
progressBar.setIndeterminate(false);
runButton.setEnabled(true);
if (exitVal != 0) {
progressBar.setValue(0);
logTextArea.setForeground(Color.RED);
JOptionPane.showMessageDialog(self,
"bcgTree did not complete your job successfully please check the log for details.",
"There was an Error", JOptionPane.ERROR_MESSAGE);
} else {
progressBar.setValue(100);
JOptionPane.showMessageDialog(self,
"bcgTree finished your job successfully. Output is in "
+ outdir,
"Success", JOptionPane.INFORMATION_MESSAGE);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
class PostCheckWorker extends Thread {
Process process;
PostCheckWorker(Process process) {
this.process = process;
}
public void run() {
int exitVal;
try {
exitVal = this.process.waitFor();
if (exitVal != 0) {
logTextArea.setForeground(Color.RED);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public void saveGlobalSettings() {
Properties globalSettings = new Properties();
for (String p : programPaths.keySet()) {
String path = programPaths.get(p).getText();
if (!path.equals("")) {
globalSettings.setProperty(p, path);
}
}
SettingsFileHandler.saveSettings(globalSettings);
}
public void loadGlobalSettings() {
Properties globalSettings = SettingsFileHandler.loadSettings();
if (globalSettings != null) {
hmmsearch_bin = globalSettings.getProperty("hmmsearch-bin", "");
muscle_bin = globalSettings.getProperty("muscle-bin", "");
gblocks_bin = globalSettings.getProperty("gblocks-bin", "");
raxml_bin = globalSettings.getProperty("raxml-bin", "");
prodigal_bin = globalSettings.getProperty("prodigal-bin", "");
}
}
}
| bcgTreeGUI/src/bcgTree/gui/BcgTree.java | package bcgTree.gui;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.TextArea;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.awt.image.BufferedImage;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.TreeMap;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JProgressBar;
import javax.swing.JScrollPane;
import javax.swing.JSpinner;
import javax.swing.JTextField;
import javax.swing.SpinnerNumberModel;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.UIManager.LookAndFeelInfo;
public class BcgTree extends JFrame {
private static final long serialVersionUID = 1L;
public static final String VERSION = "1.0.10";
private static final int DEFAULT_TEXTFIELD_COLUMNS = 30;
public static void main(String[] args) {
BcgTree mainWindow = new BcgTree();
mainWindow.pack();
mainWindow.setVisible(true);
}
private Map<String, File> proteomes;
private String outdir;
private String hmmsearch_bin = "";
private String muscle_bin = "";
private String gblocks_bin = "";
private String raxml_bin = "";
private TextArea logTextArea;
private JPanel proteomesPanel;
private Map<JTextField, String> proteomeTextFields;
private JTextField outdirTextField;
private JProgressBar progressBar;
private BcgTree self;
private JButton runButton;
private JPanel settingsPanel;
private Map<String, JTextField> programPaths = new HashMap<String, JTextField>();
private JPanel checkProgramsPanel;
private JSpinner bootstrapSpinner;
private JSpinner threadsSpinner;
private JTextField randomSeedXTextField;
private JTextField randomSeedPTextField;
private JTextField hmmfileTextField;
private JSpinner minProteomesSpinner;
private JCheckBox allProteomesCheckbox;
private JTextField raxmlAaSubstitutionModelTextField;
private JTextField raxmlArgsTextField;
public BcgTree(){
self = this;
proteomes = new TreeMap<String, File>();
outdir = System.getProperty("user.home")+"/bcgTree";
loadGlobalSettings();
initGUI();
}
public void initGUI(){
// Basic settings
this.setTitle("bcgTree "+VERSION);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setLayout(new BorderLayout());
// Set look and file
try {
for (LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (Exception e) {
// If Nimbus is not available, you can set the GUI to another look and feel.
}
// Add central panel (split in parameter section and log/output section)
JPanel mainPanel = new JPanel();
mainPanel.setLayout(new GridLayout(1, 2));
this.add(mainPanel, BorderLayout.CENTER);
settingsPanel = new JPanel();
JScrollPane settingsScrollPane = new JScrollPane(settingsPanel);
settingsPanel.setLayout(new GridBagLayout());
mainPanel.add(settingsScrollPane);
JPanel logPanel = new JPanel();
logPanel.setLayout(new BorderLayout());
mainPanel.add(logPanel);
// Add Elements to settingsPanel
// proteome settings
JPanel proteomesPane = new JPanel();
Accordion proteomeAccordion = new Accordion("Add proteomes", proteomesPane);
GridBagConstraints c = new GridBagConstraints();
c.fill = GridBagConstraints.HORIZONTAL;
c.gridx = 0;
c.gridy = 0;
settingsPanel.add(proteomeAccordion, c);
JButton proteomesAddButton = new JButton("+");
proteomesAddButton.addActionListener(proteomeAddActionListener);
proteomesPane.add(proteomesAddButton);
proteomesPanel = new JPanel();
proteomesPanel.setLayout(new GridBagLayout());
proteomesPane.add(proteomesPanel);
// outputdir settings
JPanel outdirPane = new JPanel();
JLabel outdirLabel = new JLabel("Output directory:");
outdirPane.add(outdirLabel);
outdirTextField = new JTextField(outdir, DEFAULT_TEXTFIELD_COLUMNS);
outdirPane.add(outdirTextField);
JButton outdirChooseButton = new JButton("choose");
outdirChooseButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
openOutdirChooseDialog();
}
});
outdirPane.add(outdirChooseButton);
Accordion outdirAccordion = new Accordion("Set output directory", outdirPane);
c = new GridBagConstraints();
c.fill = GridBagConstraints.HORIZONTAL;
c.gridx = 0;
c.gridy = 1;
settingsPanel.add(outdirAccordion, c);
// Add check programms
JPanel checkProgramsMainPanel = new JPanel(new BorderLayout());
checkProgramsPanel = new JPanel(new GridBagLayout());
checkProgramsMainPanel.add(checkProgramsPanel, BorderLayout.CENTER);
addCheckProgramPanel("hmmsearch", hmmsearch_bin, "hmmsearch-bin", 0);
addCheckProgramPanel("muscle", muscle_bin, "muscle-bin", 1);
addCheckProgramPanel("Gblocks", gblocks_bin, "gblocks-bin", 2);
addCheckProgramPanel("RAxML", raxml_bin, "raxml-bin",3);
JPanel checkProgramsButtonPanel = new JPanel(new GridLayout(1,2));
JButton checkProgramsButton = new JButton("check");
checkProgramsButton.addActionListener(checkProgramsActionListener);
checkProgramsButtonPanel.add(checkProgramsButton);
JButton saveProgramsButton = new JButton("save");
saveProgramsButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
saveGlobalSettings();
}
});
checkProgramsButtonPanel.add(saveProgramsButton);
checkProgramsMainPanel.add(checkProgramsButtonPanel, BorderLayout.SOUTH);
Accordion checkProgramsAccordion = new Accordion("Check external programs", checkProgramsMainPanel);
c = new GridBagConstraints();
c.fill = GridBagConstraints.HORIZONTAL;
c.gridx = 0;
c.gridy = 2;
settingsPanel.add(checkProgramsAccordion, c);
// Add check programms
Accordion advancedSettingsAccordion = new Accordion("Advanced settings", getAdvancedSettingsPanel());
c = new GridBagConstraints();
c.fill = GridBagConstraints.HORIZONTAL;
c.gridx = 0;
c.gridy = 3;
settingsPanel.add(advancedSettingsAccordion, c);
// Add "Run" button
runButton = new JButton("Run");
c = new GridBagConstraints();
c.anchor = GridBagConstraints.CENTER;
c.gridx = 0;
c.gridy = 4;
settingsPanel.add(runButton, c);
runButton.addActionListener(runActionListener);
// Add bcgTree logo
try {
BufferedImage logo = ImageIO.read(getClass().getResource("/bcgTree.png"));
JLabel picLabel = new JLabel(new ImageIcon(logo));
logPanel.add(picLabel, BorderLayout.NORTH);
} catch (IOException e1) {
e1.printStackTrace();
}
// Add log textarea
logTextArea = new TextArea();
logTextArea.setEditable(false);
logPanel.add(logTextArea, BorderLayout.CENTER);
// Add progressBar
progressBar = new JProgressBar(0, 100);
logPanel.add(progressBar, BorderLayout.SOUTH);
// final adjustments
SwingUtilities.updateComponentTreeUI(this);
this.pack();
}
private JPanel getAdvancedSettingsPanel(){
JPanel advancedSettingsPanel = new JPanel(new GridLayout(9, 2));
advancedSettingsPanel.add(new JLabel("--bootstraps"));
bootstrapSpinner = new JSpinner(new SpinnerNumberModel(10, 1, 1000, 1));
advancedSettingsPanel.add(bootstrapSpinner);
advancedSettingsPanel.add(new JLabel("--threads"));
threadsSpinner = new JSpinner(new SpinnerNumberModel(2, 1, 80, 1));
advancedSettingsPanel.add(threadsSpinner);
advancedSettingsPanel.add(new JLabel("--raxml-x-rapidBootstrapRandomNumberSeed"));
randomSeedXTextField = new JTextField("", DEFAULT_TEXTFIELD_COLUMNS);
advancedSettingsPanel.add(randomSeedXTextField);
advancedSettingsPanel.add(new JLabel("--raxml-p-parsimonyRandomSeed"));
randomSeedPTextField = new JTextField("", DEFAULT_TEXTFIELD_COLUMNS);
advancedSettingsPanel.add(randomSeedPTextField);
advancedSettingsPanel.add(new JLabel("--raxml-aa-substitution-model"));
raxmlAaSubstitutionModelTextField = new JTextField("AUTO", DEFAULT_TEXTFIELD_COLUMNS);
advancedSettingsPanel.add(raxmlAaSubstitutionModelTextField);
advancedSettingsPanel.add(new JLabel("--raxml-args"));
raxmlArgsTextField = new JTextField("", DEFAULT_TEXTFIELD_COLUMNS);
advancedSettingsPanel.add(raxmlArgsTextField);
advancedSettingsPanel.add(new JLabel("--hmmfile"));
hmmfileTextField = new JTextField(System.getProperty("user.dir")+"/../data/essential.hmm", DEFAULT_TEXTFIELD_COLUMNS);
advancedSettingsPanel.add(hmmfileTextField);
advancedSettingsPanel.add(new JLabel("--min-proteomes"));
minProteomesSpinner = new JSpinner(new SpinnerNumberModel(2, 1, 10000, 1));
advancedSettingsPanel.add(minProteomesSpinner);
advancedSettingsPanel.add(new JLabel("--all-proteomes"));
allProteomesCheckbox = new JCheckBox();
allProteomesCheckbox.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
minProteomesSpinner.setEnabled(!allProteomesCheckbox.isSelected());
}
});
advancedSettingsPanel.add(allProteomesCheckbox);
return advancedSettingsPanel;
}
protected void openOutdirChooseDialog() {
JFileChooser chooser = new JFileChooser();
chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
int exitOption = chooser.showOpenDialog(this);
if(exitOption == JFileChooser.APPROVE_OPTION){
outdir = chooser.getSelectedFile().getAbsolutePath();
outdirTextField.setText(outdir);
}
}
ActionListener runActionListener = new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// Clear Textfield
logTextArea.setText("");
logTextArea.setForeground(Color.BLACK);
// Apply changes to proteome names
renameProteomes();
// create outdir and write options file there:
outdir = outdirTextField.getText();
new File(outdir).mkdirs();
PrintWriter writer;
try {
writer = new PrintWriter(outdir+"/options.txt", "UTF-8");
writer.println("--outdir=\""+outdir+"\"");
writer.println("--bootstraps="+bootstrapSpinner.getValue());
writer.println("--threads="+threadsSpinner.getValue());
writer.println("--hmmfile=\""+hmmfileTextField.getText()+"\"");
if(allProteomesCheckbox.isSelected()){
writer.println("--all-proteomes");
} else {
writer.println("--min-proteomes="+minProteomesSpinner.getValue());
}
String pSeed = randomSeedPTextField.getText();
if(! pSeed.equals("")){
writer.println("--raxml-p-parsimonyRandomSeed="+pSeed);
}
String xSeed = randomSeedXTextField.getText();
if(! xSeed.equals("")){
writer.println("--raxml-x-rapidBootstrapRandomNumberSeed="+xSeed);
}
String raxmlAaSubstitutionModel = raxmlAaSubstitutionModelTextField.getText();
if(! raxmlAaSubstitutionModel.equals("")){
writer.println("--raxml-aa-substitution-model=\""+raxmlAaSubstitutionModel+"\"");
}
String raxmlArgs = raxmlArgsTextField.getText();
if(! raxmlArgs.equals("")){
writer.println("--raxml-args=\""+raxmlArgs+"\"");
}
for(String p : programPaths.keySet()){
String path = programPaths.get(p).getText();
if(!path.equals("")){
writer.println("--" + p + "=" + programPaths.get(p).getText());
}
}
for(Map.Entry<String, File> entry: proteomes.entrySet()){
writer.println("--proteome "+entry.getKey()+"="+"\""+entry.getValue().getAbsolutePath()+"\"");
}
writer.close();
} catch (FileNotFoundException | UnsupportedEncodingException e2) {
e2.printStackTrace();
}
try {
Process proc = Runtime.getRuntime().exec("perl "+System.getProperty("user.dir")+"/../bin/bcgTree.pl @"+outdir+"/options.txt");
// collect stderr
StreamGobbler errorGobbler = new StreamGobbler(proc.getErrorStream(), "ERROR");
// collect stdout
StreamGobbler outputGobbler = new StreamGobbler(proc.getInputStream(), "OUTPUT");
// start gobblers
errorGobbler.start();
outputGobbler.start();
PostProcessWorker postProcessWorker = new PostProcessWorker(proc);
postProcessWorker.start();
progressBar.setIndeterminate(true);
runButton.setEnabled(false);
} catch (Exception e1) {
e1.printStackTrace();
}
}
};
ActionListener checkProgramsActionListener = new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// Clear Textfield
logTextArea.setText("WARNING: It is only checked whether the paths of each program point to an executable file.\nIt is not checked whether it is the correct program.\n\n");
logTextArea.setForeground(Color.BLACK);
try {
String callBcgTree = "perl "+System.getProperty("user.dir")+"/../bin/bcgTree.pl --check-external-programs";
for(String p : programPaths.keySet()){
String path = programPaths.get(p).getText();
if(!path.equals("")){
callBcgTree += " --" + p + "=" + programPaths.get(p).getText();
}
}
logTextArea.append(callBcgTree+"\n");
Process proc = Runtime.getRuntime().exec(callBcgTree);
// collect stderr
StreamGobbler errorGobbler = new StreamGobbler(proc.getErrorStream(), "ERROR");
// collect stdout
StreamGobbler outputGobbler = new StreamGobbler(proc.getInputStream(), "OUTPUT");
// start gobblers
errorGobbler.start();
outputGobbler.start();
PostCheckWorker postCheckWorker = new PostCheckWorker(proc);
postCheckWorker.start();
} catch (Exception e1) {
e1.printStackTrace();
}
}
};
ActionListener proteomeAddActionListener = new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
proteomeAddAction();
}
};
public void proteomeAddAction(){
JFileChooser chooser = new JFileChooser();
chooser.setMultiSelectionEnabled(true);
int exitOption = chooser.showOpenDialog(this);
if(exitOption != JFileChooser.APPROVE_OPTION){
return;
}
File[] files = chooser.getSelectedFiles();
for(int i=0; i<files.length; i++){
String name = files[i].getName().replace(" ", "_");
String path = files[i].getAbsolutePath();
// avoid name collisions (does not matter if name and path are identical)
if(proteomes.get(name) != null && !proteomes.get(name).getAbsolutePath().equals(path)){
int suffix = 1;
while(proteomes.get(name+"_"+suffix) != null && !proteomes.get(name+"_"+suffix).getAbsolutePath().equals(path)){
suffix++;
}
name = name + "_" + suffix;
}
proteomes.put(name, files[i]);
}
updateProteomePanel();
}
private void addCheckProgramPanel(String name, String currentPath, String commandLineOption, int row){
JLabel checkProgramLabel = new JLabel(name);
GridBagConstraints c = new GridBagConstraints();
c.gridx = 0;
c.gridy = row;
checkProgramsPanel.add(checkProgramLabel, c);
JTextField checkProgramTextField = new JTextField(currentPath, DEFAULT_TEXTFIELD_COLUMNS);
programPaths.put(commandLineOption, checkProgramTextField);
c = new GridBagConstraints();
c.fill = GridBagConstraints.HORIZONTAL;
c.ipadx = 100;
c.gridx = 1;
c.gridy = row;
checkProgramsPanel.add(checkProgramTextField, c);
JButton outdirChooseButton = new JButton("choose");
outdirChooseButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
String newPath = openProgramChooseDialog();
if(newPath != null){
checkProgramTextField.setText(newPath);
}
}
});
c = new GridBagConstraints();
c.gridx = 2;
c.gridy = row;
checkProgramsPanel.add(outdirChooseButton, c);
}
protected String openProgramChooseDialog() {
JFileChooser chooser = new JFileChooser();
chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
int exitOption = chooser.showOpenDialog(this);
if(exitOption == JFileChooser.APPROVE_OPTION){
return chooser.getSelectedFile().getAbsolutePath();
}
return null;
}
public void removeProteome(String name){
proteomes.remove(name);
renameProteomes();
updateProteomePanel();
}
public void renameProteomes(){
TreeMap<String, File> newProteomes = new TreeMap<String, File>();
for(Map.Entry<JTextField, String> entry: proteomeTextFields.entrySet()){
if(proteomes.containsKey(entry.getValue())){
newProteomes.put(entry.getKey().getText(), proteomes.get(entry.getValue()));
}
}
proteomes = newProteomes;
}
public void updateProteomePanel(){
proteomesPanel.removeAll();
proteomeTextFields = new HashMap<JTextField, String>();
int row = 0;
for(Map.Entry<String, File> entry : proteomes.entrySet()){
JButton removeButton = new JButton("-");
removeButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
removeProteome(entry.getKey());
}
});
GridBagConstraints c = new GridBagConstraints();
c.gridx = 0;
c.gridy = row;
proteomesPanel.add(removeButton, c);
JTextField proteomeNameTextField = new JTextField(entry.getKey(), DEFAULT_TEXTFIELD_COLUMNS);
proteomeNameTextField.addFocusListener(new FocusListener() {
@Override
public void focusLost(FocusEvent e) {
if(e.isTemporary()){
return;
}
if(proteomeNameTextField.getText().contains(" ")){
proteomeNameTextField.setText(proteomeNameTextField.getText().replace(" ", "_"));
showSpaceInProteomeNameWarningDialog();
}
checkDuplicateProteomeNames();
}
@Override
public void focusGained(FocusEvent e) {
}
});
proteomeTextFields.put(proteomeNameTextField, entry.getKey());
c = new GridBagConstraints();
c.fill = GridBagConstraints.HORIZONTAL;
c.gridx = 1;
c.gridy = row;
proteomesPanel.add(proteomeNameTextField, c);
JLabel proteomePathLabel = new JLabel(entry.getValue().getAbsolutePath());
c = new GridBagConstraints();
c.fill = GridBagConstraints.HORIZONTAL;
c.gridx = 2;
c.gridy = row;
proteomesPanel.add(proteomePathLabel, c);
row++;
}
this.revalidate();
this.repaint();
}
protected void showSpaceInProteomeNameWarningDialog() {
JOptionPane.showMessageDialog(this, "The proteome name contained spaces, those have been automatically replaced by underscores.", "Whitespace Replace Warning", JOptionPane.WARNING_MESSAGE);
}
protected void checkDuplicateProteomeNames(){
Set<String> usedNames = new HashSet<String>();
for(JTextField tf: proteomeTextFields.keySet()){
String name = tf.getText();
if(usedNames.contains(name)){
JOptionPane.showMessageDialog(this, "The name: '"+name+"' is used twice for different proteomes. Please fix otherwise one of the entries will be lost.", "Duplicate Name Warning", JOptionPane.WARNING_MESSAGE);
}
usedNames.add(name);
}
}
// Helper class to process stdout and stderr of the command
// see http://www.javaworld.com/article/2071275/core-java/when-runtime-exec---won-t.html?page=2
class StreamGobbler extends Thread
{
InputStream is;
String type;
StreamGobbler(InputStream is, String type)
{
this.is = is;
this.type = type;
}
public void run()
{
try
{
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String line=null;
while ( (line = br.readLine()) != null)
logTextArea.append(line + "\n");
} catch (IOException ioe)
{
ioe.printStackTrace();
}
}
}
// Helper class to check state of the process and reset GUI on finish
class PostProcessWorker extends Thread{
Process process;
PostProcessWorker(Process process){
this.process = process;
}
public void run(){
int exitVal;
try {
exitVal = this.process.waitFor();
progressBar.setIndeterminate(false);
runButton.setEnabled(true);
if(exitVal != 0){
progressBar.setValue(0);
logTextArea.setForeground(Color.RED);
JOptionPane.showMessageDialog(self, "bcgTree did not complete your job successfully please check the log for details.", "There was an Error", JOptionPane.ERROR_MESSAGE);
}
else{
progressBar.setValue(100);
JOptionPane.showMessageDialog(self, "bcgTree finished your job successfully. Output is in "+outdir, "Success", JOptionPane.INFORMATION_MESSAGE);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
class PostCheckWorker extends Thread{
Process process;
PostCheckWorker(Process process){
this.process = process;
}
public void run(){
int exitVal;
try {
exitVal = this.process.waitFor();
if(exitVal != 0){
logTextArea.setForeground(Color.RED);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public void saveGlobalSettings(){
Properties globalSettings = new Properties();
for(String p : programPaths.keySet()){
String path = programPaths.get(p).getText();
if(!path.equals("")){
globalSettings.setProperty(p, path);
}
}
SettingsFileHandler.saveSettings(globalSettings);
}
public void loadGlobalSettings(){
Properties globalSettings = SettingsFileHandler.loadSettings();
if(globalSettings != null){
hmmsearch_bin = globalSettings.getProperty("hmmsearch-bin", "");
muscle_bin = globalSettings.getProperty("muscle-bin", "");
gblocks_bin = globalSettings.getProperty("gblocks-bin", "");
raxml_bin = globalSettings.getProperty("raxml-bin", "");
}
}
}
| Add --genome option to GUI
| bcgTreeGUI/src/bcgTree/gui/BcgTree.java | Add --genome option to GUI | <ide><path>cgTreeGUI/src/bcgTree/gui/BcgTree.java
<ide> }
<ide>
<ide> private Map<String, File> proteomes;
<add> private Map<String, File> genomes;
<ide> private String outdir;
<ide> private String hmmsearch_bin = "";
<ide> private String muscle_bin = "";
<ide> private String gblocks_bin = "";
<ide> private String raxml_bin = "";
<add> private String prodigal_bin = "";
<ide> private TextArea logTextArea;
<ide> private JPanel proteomesPanel;
<ide> private Map<JTextField, String> proteomeTextFields;
<ide> private JCheckBox allProteomesCheckbox;
<ide> private JTextField raxmlAaSubstitutionModelTextField;
<ide> private JTextField raxmlArgsTextField;
<del>
<del> public BcgTree(){
<add> private JPanel genomesPanel;
<add>
<add> public BcgTree() {
<ide> self = this;
<ide> proteomes = new TreeMap<String, File>();
<del> outdir = System.getProperty("user.home")+"/bcgTree";
<add> genomes = new TreeMap<String, File>();
<add> outdir = System.getProperty("user.home") + "/bcgTree";
<ide> loadGlobalSettings();
<ide> initGUI();
<ide> }
<del>
<del> public void initGUI(){
<add>
<add> public void initGUI() {
<ide> // Basic settings
<del> this.setTitle("bcgTree "+VERSION);
<add> this.setTitle("bcgTree " + VERSION);
<ide> this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
<ide> this.setLayout(new BorderLayout());
<ide> // Set look and file
<ide> try {
<del> for (LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) {
<del> if ("Nimbus".equals(info.getName())) {
<del> UIManager.setLookAndFeel(info.getClassName());
<del> break;
<del> }
<del> }
<add> for (LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) {
<add> if ("Nimbus".equals(info.getName())) {
<add> UIManager.setLookAndFeel(info.getClassName());
<add> break;
<add> }
<add> }
<ide> } catch (Exception e) {
<del> // If Nimbus is not available, you can set the GUI to another look and feel.
<add> // If Nimbus is not available, you can set the GUI to another look and feel.
<ide> }
<ide> // Add central panel (split in parameter section and log/output section)
<ide> JPanel mainPanel = new JPanel();
<ide> // Add Elements to settingsPanel
<ide> // proteome settings
<ide> JPanel proteomesPane = new JPanel();
<del> Accordion proteomeAccordion = new Accordion("Add proteomes", proteomesPane);
<add> Accordion proteomeAccordion = new Accordion("Add proteomes (peptide fasta)", proteomesPane);
<ide> GridBagConstraints c = new GridBagConstraints();
<ide> c.fill = GridBagConstraints.HORIZONTAL;
<ide> c.gridx = 0;
<ide> proteomesPanel = new JPanel();
<ide> proteomesPanel.setLayout(new GridBagLayout());
<ide> proteomesPane.add(proteomesPanel);
<add> // genome settings
<add> JPanel genomePane = new JPanel();
<add> Accordion genomeAccordion = new Accordion("Add genomes (nucleotide fasta, will be translated)", genomePane);
<add> c = new GridBagConstraints();
<add> c.fill = GridBagConstraints.HORIZONTAL;
<add> c.gridx = 0;
<add> c.gridy = 1;
<add> settingsPanel.add(genomeAccordion, c);
<add> JButton genomeAddButton = new JButton("+");
<add> genomeAddButton.addActionListener(genomeAddActionListener);
<add> genomePane.add(genomeAddButton);
<add> genomesPanel = new JPanel();
<add> genomesPanel.setLayout(new GridBagLayout());
<add> genomePane.add(genomesPanel);
<ide> // outputdir settings
<ide> JPanel outdirPane = new JPanel();
<ide> JLabel outdirLabel = new JLabel("Output directory:");
<ide> c = new GridBagConstraints();
<ide> c.fill = GridBagConstraints.HORIZONTAL;
<ide> c.gridx = 0;
<del> c.gridy = 1;
<add> c.gridy = 2;
<ide> settingsPanel.add(outdirAccordion, c);
<ide> // Add check programms
<ide> JPanel checkProgramsMainPanel = new JPanel(new BorderLayout());
<ide> addCheckProgramPanel("hmmsearch", hmmsearch_bin, "hmmsearch-bin", 0);
<ide> addCheckProgramPanel("muscle", muscle_bin, "muscle-bin", 1);
<ide> addCheckProgramPanel("Gblocks", gblocks_bin, "gblocks-bin", 2);
<del> addCheckProgramPanel("RAxML", raxml_bin, "raxml-bin",3);
<del> JPanel checkProgramsButtonPanel = new JPanel(new GridLayout(1,2));
<add> addCheckProgramPanel("RAxML", raxml_bin, "raxml-bin", 3);
<add> addCheckProgramPanel("prodigal", prodigal_bin, "prodigal-bin", 4);
<add> JPanel checkProgramsButtonPanel = new JPanel(new GridLayout(1, 2));
<ide> JButton checkProgramsButton = new JButton("check");
<ide> checkProgramsButton.addActionListener(checkProgramsActionListener);
<ide> checkProgramsButtonPanel.add(checkProgramsButton);
<ide> });
<ide> checkProgramsButtonPanel.add(saveProgramsButton);
<ide> checkProgramsMainPanel.add(checkProgramsButtonPanel, BorderLayout.SOUTH);
<del>
<add>
<ide> Accordion checkProgramsAccordion = new Accordion("Check external programs", checkProgramsMainPanel);
<ide> c = new GridBagConstraints();
<ide> c.fill = GridBagConstraints.HORIZONTAL;
<ide> c.gridx = 0;
<del> c.gridy = 2;
<add> c.gridy = 3;
<ide> settingsPanel.add(checkProgramsAccordion, c);
<ide> // Add check programms
<ide> Accordion advancedSettingsAccordion = new Accordion("Advanced settings", getAdvancedSettingsPanel());
<ide> c = new GridBagConstraints();
<ide> c.fill = GridBagConstraints.HORIZONTAL;
<ide> c.gridx = 0;
<del> c.gridy = 3;
<add> c.gridy = 4;
<ide> settingsPanel.add(advancedSettingsAccordion, c);
<ide> // Add "Run" button
<ide> runButton = new JButton("Run");
<ide> c = new GridBagConstraints();
<ide> c.anchor = GridBagConstraints.CENTER;
<ide> c.gridx = 0;
<del> c.gridy = 4;
<add> c.gridy = 5;
<ide> settingsPanel.add(runButton, c);
<ide> runButton.addActionListener(runActionListener);
<ide> // Add bcgTree logo
<ide> SwingUtilities.updateComponentTreeUI(this);
<ide> this.pack();
<ide> }
<del>
<del> private JPanel getAdvancedSettingsPanel(){
<add>
<add> private JPanel getAdvancedSettingsPanel() {
<ide> JPanel advancedSettingsPanel = new JPanel(new GridLayout(9, 2));
<ide> advancedSettingsPanel.add(new JLabel("--bootstraps"));
<ide> bootstrapSpinner = new JSpinner(new SpinnerNumberModel(10, 1, 1000, 1));
<ide> raxmlArgsTextField = new JTextField("", DEFAULT_TEXTFIELD_COLUMNS);
<ide> advancedSettingsPanel.add(raxmlArgsTextField);
<ide> advancedSettingsPanel.add(new JLabel("--hmmfile"));
<del> hmmfileTextField = new JTextField(System.getProperty("user.dir")+"/../data/essential.hmm", DEFAULT_TEXTFIELD_COLUMNS);
<add> hmmfileTextField = new JTextField(System.getProperty("user.dir") + "/../data/essential.hmm",
<add> DEFAULT_TEXTFIELD_COLUMNS);
<ide> advancedSettingsPanel.add(hmmfileTextField);
<ide> advancedSettingsPanel.add(new JLabel("--min-proteomes"));
<ide> minProteomesSpinner = new JSpinner(new SpinnerNumberModel(2, 1, 10000, 1));
<ide> advancedSettingsPanel.add(allProteomesCheckbox);
<ide> return advancedSettingsPanel;
<ide> }
<del>
<add>
<ide> protected void openOutdirChooseDialog() {
<ide> JFileChooser chooser = new JFileChooser();
<ide> chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
<ide> int exitOption = chooser.showOpenDialog(this);
<del> if(exitOption == JFileChooser.APPROVE_OPTION){
<add> if (exitOption == JFileChooser.APPROVE_OPTION) {
<ide> outdir = chooser.getSelectedFile().getAbsolutePath();
<ide> outdirTextField.setText(outdir);
<ide> }
<ide> }
<ide>
<del> ActionListener runActionListener = new ActionListener() {
<add> ActionListener runActionListener = new ActionListener() {
<ide> @Override
<ide> public void actionPerformed(ActionEvent e) {
<ide> // Clear Textfield
<ide> new File(outdir).mkdirs();
<ide> PrintWriter writer;
<ide> try {
<del> writer = new PrintWriter(outdir+"/options.txt", "UTF-8");
<del> writer.println("--outdir=\""+outdir+"\"");
<del> writer.println("--bootstraps="+bootstrapSpinner.getValue());
<del> writer.println("--threads="+threadsSpinner.getValue());
<del> writer.println("--hmmfile=\""+hmmfileTextField.getText()+"\"");
<del> if(allProteomesCheckbox.isSelected()){
<add> writer = new PrintWriter(outdir + "/options.txt", "UTF-8");
<add> writer.println("--outdir=\"" + outdir + "\"");
<add> writer.println("--bootstraps=" + bootstrapSpinner.getValue());
<add> writer.println("--threads=" + threadsSpinner.getValue());
<add> writer.println("--hmmfile=\"" + hmmfileTextField.getText() + "\"");
<add> if (allProteomesCheckbox.isSelected()) {
<ide> writer.println("--all-proteomes");
<ide> } else {
<del> writer.println("--min-proteomes="+minProteomesSpinner.getValue());
<add> writer.println("--min-proteomes=" + minProteomesSpinner.getValue());
<ide> }
<ide> String pSeed = randomSeedPTextField.getText();
<del> if(! pSeed.equals("")){
<del> writer.println("--raxml-p-parsimonyRandomSeed="+pSeed);
<add> if (!pSeed.equals("")) {
<add> writer.println("--raxml-p-parsimonyRandomSeed=" + pSeed);
<ide> }
<ide> String xSeed = randomSeedXTextField.getText();
<del> if(! xSeed.equals("")){
<del> writer.println("--raxml-x-rapidBootstrapRandomNumberSeed="+xSeed);
<add> if (!xSeed.equals("")) {
<add> writer.println("--raxml-x-rapidBootstrapRandomNumberSeed=" + xSeed);
<ide> }
<ide> String raxmlAaSubstitutionModel = raxmlAaSubstitutionModelTextField.getText();
<del> if(! raxmlAaSubstitutionModel.equals("")){
<del> writer.println("--raxml-aa-substitution-model=\""+raxmlAaSubstitutionModel+"\"");
<add> if (!raxmlAaSubstitutionModel.equals("")) {
<add> writer.println("--raxml-aa-substitution-model=\"" + raxmlAaSubstitutionModel
<add> + "\"");
<ide> }
<ide> String raxmlArgs = raxmlArgsTextField.getText();
<del> if(! raxmlArgs.equals("")){
<del> writer.println("--raxml-args=\""+raxmlArgs+"\"");
<del> }
<del> for(String p : programPaths.keySet()){
<add> if (!raxmlArgs.equals("")) {
<add> writer.println("--raxml-args=\"" + raxmlArgs + "\"");
<add> }
<add> for (String p : programPaths.keySet()) {
<ide> String path = programPaths.get(p).getText();
<del> if(!path.equals("")){
<add> if (!path.equals("")) {
<ide> writer.println("--" + p + "=" + programPaths.get(p).getText());
<ide> }
<ide> }
<del> for(Map.Entry<String, File> entry: proteomes.entrySet()){
<del> writer.println("--proteome "+entry.getKey()+"="+"\""+entry.getValue().getAbsolutePath()+"\"");
<add> for (Map.Entry<String, File> entry : proteomes.entrySet()) {
<add> writer.println("--proteome " + entry.getKey() + "=" + "\""
<add> + entry.getValue().getAbsolutePath() + "\"");
<add> }
<add> for (Map.Entry<String, File> entry : genomes.entrySet()) {
<add> writer.println("--genome " + entry.getKey() + "=" + "\""
<add> + entry.getValue().getAbsolutePath() + "\"");
<ide> }
<ide> writer.close();
<ide> } catch (FileNotFoundException | UnsupportedEncodingException e2) {
<ide> e2.printStackTrace();
<ide> }
<ide> try {
<del> Process proc = Runtime.getRuntime().exec("perl "+System.getProperty("user.dir")+"/../bin/bcgTree.pl @"+outdir+"/options.txt");
<add> Process proc = Runtime.getRuntime().exec("perl " + System.getProperty("user.dir")
<add> + "/../bin/bcgTree.pl @" + outdir + "/options.txt");
<ide> // collect stderr
<del> StreamGobbler errorGobbler = new StreamGobbler(proc.getErrorStream(), "ERROR");
<del> // collect stdout
<del> StreamGobbler outputGobbler = new StreamGobbler(proc.getInputStream(), "OUTPUT");
<del> // start gobblers
<del> errorGobbler.start();
<del> outputGobbler.start();
<del> PostProcessWorker postProcessWorker = new PostProcessWorker(proc);
<del> postProcessWorker.start();
<del> progressBar.setIndeterminate(true);
<del> runButton.setEnabled(false);
<del>
<add> StreamGobbler errorGobbler = new StreamGobbler(proc.getErrorStream(), "ERROR");
<add> // collect stdout
<add> StreamGobbler outputGobbler = new StreamGobbler(proc.getInputStream(), "OUTPUT");
<add> // start gobblers
<add> errorGobbler.start();
<add> outputGobbler.start();
<add> PostProcessWorker postProcessWorker = new PostProcessWorker(proc);
<add> postProcessWorker.start();
<add> progressBar.setIndeterminate(true);
<add> runButton.setEnabled(false);
<add>
<ide> } catch (Exception e1) {
<ide> e1.printStackTrace();
<ide> }
<ide> }
<ide> };
<del>
<del> ActionListener checkProgramsActionListener = new ActionListener() {
<add>
<add> ActionListener checkProgramsActionListener = new ActionListener() {
<ide> @Override
<ide> public void actionPerformed(ActionEvent e) {
<ide> // Clear Textfield
<del> logTextArea.setText("WARNING: It is only checked whether the paths of each program point to an executable file.\nIt is not checked whether it is the correct program.\n\n");
<add> logTextArea.setText(
<add> "WARNING: It is only checked whether the paths of each program point to an executable file.\nIt is not checked whether it is the correct program.\n\n");
<ide> logTextArea.setForeground(Color.BLACK);
<ide> try {
<del> String callBcgTree = "perl "+System.getProperty("user.dir")+"/../bin/bcgTree.pl --check-external-programs";
<del> for(String p : programPaths.keySet()){
<add> String callBcgTree = "perl " + System.getProperty("user.dir")
<add> + "/../bin/bcgTree.pl --check-external-programs";
<add> for (String p : programPaths.keySet()) {
<ide> String path = programPaths.get(p).getText();
<del> if(!path.equals("")){
<add> if (!path.equals("")) {
<ide> callBcgTree += " --" + p + "=" + programPaths.get(p).getText();
<ide> }
<ide> }
<del> logTextArea.append(callBcgTree+"\n");
<add> logTextArea.append(callBcgTree + "\n");
<ide> Process proc = Runtime.getRuntime().exec(callBcgTree);
<ide> // collect stderr
<del> StreamGobbler errorGobbler = new StreamGobbler(proc.getErrorStream(), "ERROR");
<del> // collect stdout
<del> StreamGobbler outputGobbler = new StreamGobbler(proc.getInputStream(), "OUTPUT");
<del> // start gobblers
<del> errorGobbler.start();
<del> outputGobbler.start();
<del> PostCheckWorker postCheckWorker = new PostCheckWorker(proc);
<del> postCheckWorker.start();
<add> StreamGobbler errorGobbler = new StreamGobbler(proc.getErrorStream(), "ERROR");
<add> // collect stdout
<add> StreamGobbler outputGobbler = new StreamGobbler(proc.getInputStream(), "OUTPUT");
<add> // start gobblers
<add> errorGobbler.start();
<add> outputGobbler.start();
<add> PostCheckWorker postCheckWorker = new PostCheckWorker(proc);
<add> postCheckWorker.start();
<ide> } catch (Exception e1) {
<ide> e1.printStackTrace();
<ide> }
<ide> }
<ide> };
<del>
<add>
<ide> ActionListener proteomeAddActionListener = new ActionListener() {
<ide> @Override
<ide> public void actionPerformed(ActionEvent e) {
<ide> proteomeAddAction();
<ide> }
<ide> };
<del>
<del> public void proteomeAddAction(){
<add>
<add> ActionListener genomeAddActionListener = new ActionListener() {
<add> @Override
<add> public void actionPerformed(ActionEvent e) {
<add> genomeAddAction();
<add> }
<add> };
<add> private HashMap<JTextField, String> genomeTextFields;
<add>
<add> public void proteomeAddAction() {
<ide> JFileChooser chooser = new JFileChooser();
<ide> chooser.setMultiSelectionEnabled(true);
<ide> int exitOption = chooser.showOpenDialog(this);
<del> if(exitOption != JFileChooser.APPROVE_OPTION){
<add> if (exitOption != JFileChooser.APPROVE_OPTION) {
<ide> return;
<ide> }
<ide> File[] files = chooser.getSelectedFiles();
<del> for(int i=0; i<files.length; i++){
<add> for (int i = 0; i < files.length; i++) {
<ide> String name = files[i].getName().replace(" ", "_");
<ide> String path = files[i].getAbsolutePath();
<ide> // avoid name collisions (does not matter if name and path are identical)
<del> if(proteomes.get(name) != null && !proteomes.get(name).getAbsolutePath().equals(path)){
<add> if (proteomes.get(name) != null && !proteomes.get(name).getAbsolutePath().equals(path)) {
<ide> int suffix = 1;
<del> while(proteomes.get(name+"_"+suffix) != null && !proteomes.get(name+"_"+suffix).getAbsolutePath().equals(path)){
<add> while (proteomes.get(name + "_" + suffix) != null
<add> && !proteomes.get(name + "_" + suffix).getAbsolutePath().equals(path)) {
<ide> suffix++;
<ide> }
<ide> name = name + "_" + suffix;
<ide> }
<ide> updateProteomePanel();
<ide> }
<del>
<del> private void addCheckProgramPanel(String name, String currentPath, String commandLineOption, int row){
<add>
<add> public void genomeAddAction() {
<add> JFileChooser chooser = new JFileChooser();
<add> chooser.setMultiSelectionEnabled(true);
<add> int exitOption = chooser.showOpenDialog(this);
<add> if (exitOption != JFileChooser.APPROVE_OPTION) {
<add> return;
<add> }
<add> File[] files = chooser.getSelectedFiles();
<add> for (int i = 0; i < files.length; i++) {
<add> String name = files[i].getName().replace(" ", "_");
<add> String path = files[i].getAbsolutePath();
<add> // avoid name collisions (does not matter if name and path are identical)
<add> if (genomes.get(name) != null && !genomes.get(name).getAbsolutePath().equals(path)) {
<add> int suffix = 1;
<add> while (genomes.get(name + "_" + suffix) != null
<add> && !genomes.get(name + "_" + suffix).getAbsolutePath().equals(path)) {
<add> suffix++;
<add> }
<add> name = name + "_" + suffix;
<add> }
<add> genomes.put(name, files[i]);
<add> }
<add> updateGenomePanel();
<add> }
<add>
<add> private void addCheckProgramPanel(String name, String currentPath, String commandLineOption, int row) {
<ide> JLabel checkProgramLabel = new JLabel(name);
<ide> GridBagConstraints c = new GridBagConstraints();
<ide> c.gridx = 0;
<ide> @Override
<ide> public void actionPerformed(ActionEvent e) {
<ide> String newPath = openProgramChooseDialog();
<del> if(newPath != null){
<add> if (newPath != null) {
<ide> checkProgramTextField.setText(newPath);
<ide> }
<ide> }
<ide> c.gridy = row;
<ide> checkProgramsPanel.add(outdirChooseButton, c);
<ide> }
<del>
<add>
<ide> protected String openProgramChooseDialog() {
<ide> JFileChooser chooser = new JFileChooser();
<ide> chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
<ide> int exitOption = chooser.showOpenDialog(this);
<del> if(exitOption == JFileChooser.APPROVE_OPTION){
<add> if (exitOption == JFileChooser.APPROVE_OPTION) {
<ide> return chooser.getSelectedFile().getAbsolutePath();
<ide> }
<ide> return null;
<ide> }
<ide>
<del> public void removeProteome(String name){
<add> public void removeProteome(String name) {
<ide> proteomes.remove(name);
<ide> renameProteomes();
<ide> updateProteomePanel();
<ide> }
<del>
<del> public void renameProteomes(){
<add>
<add> public void removeGenome(String name) {
<add> genomes.remove(name);
<add> renameGenomes();
<add> updateGenomePanel();
<add> }
<add>
<add> public void renameGenomes() {
<add> TreeMap<String, File> newGenomes = new TreeMap<String, File>();
<add> for (Map.Entry<JTextField, String> entry : genomeTextFields.entrySet()) {
<add> if (genomes.containsKey(entry.getValue())) {
<add> newGenomes.put(entry.getKey().getText(), genomes.get(entry.getValue()));
<add> }
<add> }
<add> genomes = newGenomes;
<add> }
<add>
<add> public void renameProteomes() {
<ide> TreeMap<String, File> newProteomes = new TreeMap<String, File>();
<del> for(Map.Entry<JTextField, String> entry: proteomeTextFields.entrySet()){
<del> if(proteomes.containsKey(entry.getValue())){
<add> for (Map.Entry<JTextField, String> entry : proteomeTextFields.entrySet()) {
<add> if (proteomes.containsKey(entry.getValue())) {
<ide> newProteomes.put(entry.getKey().getText(), proteomes.get(entry.getValue()));
<ide> }
<ide> }
<ide> proteomes = newProteomes;
<ide> }
<del>
<del> public void updateProteomePanel(){
<add>
<add> public void updateProteomePanel() {
<ide> proteomesPanel.removeAll();
<ide> proteomeTextFields = new HashMap<JTextField, String>();
<ide> int row = 0;
<del> for(Map.Entry<String, File> entry : proteomes.entrySet()){
<add> for (Map.Entry<String, File> entry : proteomes.entrySet()) {
<ide> JButton removeButton = new JButton("-");
<ide> removeButton.addActionListener(new ActionListener() {
<ide> @Override
<ide> proteomeNameTextField.addFocusListener(new FocusListener() {
<ide> @Override
<ide> public void focusLost(FocusEvent e) {
<del> if(e.isTemporary()){
<add> if (e.isTemporary()) {
<ide> return;
<ide> }
<del> if(proteomeNameTextField.getText().contains(" ")){
<del> proteomeNameTextField.setText(proteomeNameTextField.getText().replace(" ", "_"));
<del> showSpaceInProteomeNameWarningDialog();
<add> if (proteomeNameTextField.getText().contains(" ")) {
<add> proteomeNameTextField.setText(
<add> proteomeNameTextField.getText().replace(" ", "_"));
<add> showSpaceInNameWarningDialog();
<ide> }
<del> checkDuplicateProteomeNames();
<del> }
<add> checkDuplicateNames();
<add> }
<add>
<ide> @Override
<del> public void focusGained(FocusEvent e) {
<add> public void focusGained(FocusEvent e) {
<ide> }
<ide> });
<ide> proteomeTextFields.put(proteomeNameTextField, entry.getKey());
<ide> this.revalidate();
<ide> this.repaint();
<ide> }
<del>
<del> protected void showSpaceInProteomeNameWarningDialog() {
<del> JOptionPane.showMessageDialog(this, "The proteome name contained spaces, those have been automatically replaced by underscores.", "Whitespace Replace Warning", JOptionPane.WARNING_MESSAGE);
<del> }
<del>
<del> protected void checkDuplicateProteomeNames(){
<add>
<add> public void updateGenomePanel() {
<add> genomesPanel.removeAll();
<add> genomeTextFields = new HashMap<JTextField, String>();
<add> int row = 0;
<add> for (Map.Entry<String, File> entry : genomes.entrySet()) {
<add> JButton removeButton = new JButton("-");
<add> removeButton.addActionListener(new ActionListener() {
<add> @Override
<add> public void actionPerformed(ActionEvent e) {
<add> removeGenome(entry.getKey());
<add> }
<add> });
<add> GridBagConstraints c = new GridBagConstraints();
<add> c.gridx = 0;
<add> c.gridy = row;
<add> genomesPanel.add(removeButton, c);
<add> JTextField genomeNameTextField = new JTextField(entry.getKey(), DEFAULT_TEXTFIELD_COLUMNS);
<add> genomeNameTextField.addFocusListener(new FocusListener() {
<add> @Override
<add> public void focusLost(FocusEvent e) {
<add> if (e.isTemporary()) {
<add> return;
<add> }
<add> if (genomeNameTextField.getText().contains(" ")) {
<add> genomeNameTextField.setText(
<add> genomeNameTextField.getText().replace(" ", "_"));
<add> showSpaceInNameWarningDialog();
<add> }
<add> checkDuplicateNames();
<add> }
<add>
<add> @Override
<add> public void focusGained(FocusEvent e) {
<add> }
<add> });
<add> genomeTextFields.put(genomeNameTextField, entry.getKey());
<add> c = new GridBagConstraints();
<add> c.fill = GridBagConstraints.HORIZONTAL;
<add> c.gridx = 1;
<add> c.gridy = row;
<add> genomesPanel.add(genomeNameTextField, c);
<add> JLabel genomePathLabel = new JLabel(entry.getValue().getAbsolutePath());
<add> c = new GridBagConstraints();
<add> c.fill = GridBagConstraints.HORIZONTAL;
<add> c.gridx = 2;
<add> c.gridy = row;
<add> genomesPanel.add(genomePathLabel, c);
<add> row++;
<add> }
<add> this.revalidate();
<add> this.repaint();
<add> }
<add>
<add> protected void showSpaceInNameWarningDialog() {
<add> JOptionPane.showMessageDialog(this,
<add> "The proteome/genome name contained spaces, those have been automatically replaced by underscores.",
<add> "Whitespace Replace Warning", JOptionPane.WARNING_MESSAGE);
<add> }
<add>
<add> protected void checkDuplicateNames() {
<ide> Set<String> usedNames = new HashSet<String>();
<del> for(JTextField tf: proteomeTextFields.keySet()){
<add> for (JTextField tf : proteomeTextFields.keySet()) {
<ide> String name = tf.getText();
<del> if(usedNames.contains(name)){
<del> JOptionPane.showMessageDialog(this, "The name: '"+name+"' is used twice for different proteomes. Please fix otherwise one of the entries will be lost.", "Duplicate Name Warning", JOptionPane.WARNING_MESSAGE);
<add> if (usedNames.contains(name)) {
<add> JOptionPane.showMessageDialog(this, "The name: '" + name
<add> + "' is used twice for different proteomes/genomes. Please fix otherwise one of the entries will be lost.",
<add> "Duplicate Name Warning", JOptionPane.WARNING_MESSAGE);
<ide> }
<ide> usedNames.add(name);
<ide> }
<del> }
<del>
<add> for (JTextField tf : genomeTextFields.keySet()) {
<add> String name = tf.getText();
<add> if (usedNames.contains(name)) {
<add> JOptionPane.showMessageDialog(this, "The name: '" + name
<add> + "' is used twice for different proteomes/genomes. Please fix otherwise one of the entries will be lost.",
<add> "Duplicate Name Warning", JOptionPane.WARNING_MESSAGE);
<add> }
<add> usedNames.add(name);
<add> }
<add> }
<add>
<ide> // Helper class to process stdout and stderr of the command
<del> // see http://www.javaworld.com/article/2071275/core-java/when-runtime-exec---won-t.html?page=2
<del> class StreamGobbler extends Thread
<del> {
<del> InputStream is;
<del> String type;
<del>
<del> StreamGobbler(InputStream is, String type)
<del> {
<del> this.is = is;
<del> this.type = type;
<del> }
<del>
<del> public void run()
<del> {
<del> try
<del> {
<del> InputStreamReader isr = new InputStreamReader(is);
<del> BufferedReader br = new BufferedReader(isr);
<del> String line=null;
<del> while ( (line = br.readLine()) != null)
<del> logTextArea.append(line + "\n");
<del> } catch (IOException ioe)
<del> {
<del> ioe.printStackTrace();
<del> }
<del> }
<del> }
<del>
<add> // see
<add> // http://www.javaworld.com/article/2071275/core-java/when-runtime-exec---won-t.html?page=2
<add> class StreamGobbler extends Thread {
<add> InputStream is;
<add> String type;
<add>
<add> StreamGobbler(InputStream is, String type) {
<add> this.is = is;
<add> this.type = type;
<add> }
<add>
<add> public void run() {
<add> try {
<add> InputStreamReader isr = new InputStreamReader(is);
<add> BufferedReader br = new BufferedReader(isr);
<add> String line = null;
<add> while ((line = br.readLine()) != null)
<add> logTextArea.append(line + "\n");
<add> } catch (IOException ioe) {
<add> ioe.printStackTrace();
<add> }
<add> }
<add> }
<add>
<ide> // Helper class to check state of the process and reset GUI on finish
<del> class PostProcessWorker extends Thread{
<add> class PostProcessWorker extends Thread {
<ide> Process process;
<del> PostProcessWorker(Process process){
<add>
<add> PostProcessWorker(Process process) {
<ide> this.process = process;
<ide> }
<del> public void run(){
<add>
<add> public void run() {
<ide> int exitVal;
<ide> try {
<ide> exitVal = this.process.waitFor();
<ide> progressBar.setIndeterminate(false);
<ide> runButton.setEnabled(true);
<del> if(exitVal != 0){
<add> if (exitVal != 0) {
<ide> progressBar.setValue(0);
<ide> logTextArea.setForeground(Color.RED);
<del> JOptionPane.showMessageDialog(self, "bcgTree did not complete your job successfully please check the log for details.", "There was an Error", JOptionPane.ERROR_MESSAGE);
<del> }
<del> else{
<add> JOptionPane.showMessageDialog(self,
<add> "bcgTree did not complete your job successfully please check the log for details.",
<add> "There was an Error", JOptionPane.ERROR_MESSAGE);
<add> } else {
<ide> progressBar.setValue(100);
<del> JOptionPane.showMessageDialog(self, "bcgTree finished your job successfully. Output is in "+outdir, "Success", JOptionPane.INFORMATION_MESSAGE);
<add> JOptionPane.showMessageDialog(self,
<add> "bcgTree finished your job successfully. Output is in "
<add> + outdir,
<add> "Success", JOptionPane.INFORMATION_MESSAGE);
<ide> }
<ide> } catch (InterruptedException e) {
<ide> e.printStackTrace();
<ide> }
<ide> }
<ide> }
<del>
<del> class PostCheckWorker extends Thread{
<add>
<add> class PostCheckWorker extends Thread {
<ide> Process process;
<del> PostCheckWorker(Process process){
<add>
<add> PostCheckWorker(Process process) {
<ide> this.process = process;
<ide> }
<del> public void run(){
<add>
<add> public void run() {
<ide> int exitVal;
<ide> try {
<ide> exitVal = this.process.waitFor();
<del> if(exitVal != 0){
<add> if (exitVal != 0) {
<ide> logTextArea.setForeground(Color.RED);
<ide> }
<ide> } catch (InterruptedException e) {
<ide> }
<ide> }
<ide> }
<del>
<del> public void saveGlobalSettings(){
<add>
<add> public void saveGlobalSettings() {
<ide> Properties globalSettings = new Properties();
<del> for(String p : programPaths.keySet()){
<add> for (String p : programPaths.keySet()) {
<ide> String path = programPaths.get(p).getText();
<del> if(!path.equals("")){
<add> if (!path.equals("")) {
<ide> globalSettings.setProperty(p, path);
<ide> }
<ide> }
<ide> SettingsFileHandler.saveSettings(globalSettings);
<ide> }
<del>
<del> public void loadGlobalSettings(){
<add>
<add> public void loadGlobalSettings() {
<ide> Properties globalSettings = SettingsFileHandler.loadSettings();
<del> if(globalSettings != null){
<add> if (globalSettings != null) {
<ide> hmmsearch_bin = globalSettings.getProperty("hmmsearch-bin", "");
<ide> muscle_bin = globalSettings.getProperty("muscle-bin", "");
<ide> gblocks_bin = globalSettings.getProperty("gblocks-bin", "");
<ide> raxml_bin = globalSettings.getProperty("raxml-bin", "");
<add> prodigal_bin = globalSettings.getProperty("prodigal-bin", "");
<ide> }
<ide> }
<ide> |
|
Java | mpl-2.0 | bc0a06fdc2c8b700aedc159a889dd9a1ab22a071 | 0 | MyzelYam/SuperVanish | /*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
package de.myzelyam.supervanish.events;
import de.myzelyam.supervanish.SuperVanish;
import de.myzelyam.supervanish.hooks.EssentialsHook;
import de.myzelyam.supervanish.utils.PlayerCache;
import de.myzelyam.supervanish.utils.ProtocolLibPacketUtils;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.entity.Player;
import org.bukkit.event.Event;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.metadata.FixedMetadataValue;
import org.bukkit.plugin.EventExecutor;
import org.bukkit.potion.PotionEffect;
import org.bukkit.potion.PotionEffectType;
import java.util.List;
public class JoinEvent implements EventExecutor, Listener {
private final SuperVanish plugin;
public JoinEvent(SuperVanish plugin) {
this.plugin = plugin;
}
private FileConfiguration getSettings() {
return plugin.settings;
}
@SuppressWarnings("deprecation")
@Override
public void execute(Listener listener, Event event) {
try {
if (event instanceof PlayerJoinEvent) {
PlayerJoinEvent e = (PlayerJoinEvent) event;
final Player p = e.getPlayer();
PlayerCache.fromPlayer(p, plugin);
final List<String> invisiblePlayers = plugin.getAllInvisiblePlayers();
if (getSettings().getBoolean("Configuration.Players.AutoVanishOnJoin", false)
&& p.hasPermission("sv.joinvanished")
&& !invisiblePlayers.contains(p.getUniqueId().toString())) {
invisiblePlayers.add(p.getUniqueId().toString());
plugin.playerData.set("InvisiblePlayers", invisiblePlayers);
plugin.savePlayerData();
}
// vanished:
if (invisiblePlayers.contains(p.getUniqueId().toString())) {
if (getSettings().getBoolean(
"Configuration.Messages.HideNormalJoinAndLeaveMessagesWhileInvisible", true)) {
e.setJoinMessage(null);
}
if (plugin.getServer().getPluginManager()
.getPlugin("Essentials") != null
&& getSettings().getBoolean("Configuration.Hooks.EnableEssentialsHook")) {
EssentialsHook.hidePlayer(p);
}
if (getSettings().getBoolean("Configuration.Messages.RemindInvisiblePlayersOnJoin")) {
p.sendMessage(plugin.convertString(
plugin.getMsg("RemindingMessage"), p));
}
plugin.getVisibilityAdjuster().getHider().hideToAll(p);
p.setMetadata("vanished", new FixedMetadataValue(plugin, true));
if (plugin.getActionBarMgr() != null
&& getSettings().getBoolean(
"Configuration.Messages.DisplayActionBarsToInvisiblePlayers")) {
plugin.getActionBarMgr().addActionBar(p);
}
if (plugin.packetNightVision && getSettings().getBoolean(
"Configuration.Players.AddNightVision"))
plugin.getProtocolLibPacketUtils().sendAddPotionEffect(p, new PotionEffect(
PotionEffectType.NIGHT_VISION,
ProtocolLibPacketUtils.INFINITE_POTION_DURATION, 0));
if (plugin.getTeamMgr() != null)
plugin.getTeamMgr().setCantPush(p);
}
// not necessarily vanished:
plugin.getVisibilityAdjuster().getHider().hideAllInvisibleTo(p);
}
} catch (Exception er) {
plugin.printException(er);
}
}
} | src/main/java/de/myzelyam/supervanish/events/JoinEvent.java | /*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
package de.myzelyam.supervanish.events;
import de.myzelyam.supervanish.SuperVanish;
import de.myzelyam.supervanish.hooks.EssentialsHook;
import de.myzelyam.supervanish.utils.PlayerCache;
import de.myzelyam.supervanish.utils.ProtocolLibPacketUtils;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.entity.Player;
import org.bukkit.event.Event;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.metadata.FixedMetadataValue;
import org.bukkit.plugin.EventExecutor;
import org.bukkit.potion.PotionEffect;
import org.bukkit.potion.PotionEffectType;
import java.util.List;
public class JoinEvent implements EventExecutor, Listener {
private final SuperVanish plugin;
public JoinEvent(SuperVanish plugin) {
this.plugin = plugin;
}
private FileConfiguration getSettings() {
return plugin.settings;
}
@SuppressWarnings("deprecation")
@Override
public void execute(Listener listener, Event event) {
try {
if (event instanceof PlayerJoinEvent) {
PlayerJoinEvent e = (PlayerJoinEvent) event;
final Player p = e.getPlayer();
PlayerCache.fromPlayer(p, plugin);
final List<String> invisiblePlayers = plugin.getAllInvisiblePlayers();
if (getSettings().getBoolean("Configuration.Players.AutoVanishOnJoin", false)
&& p.hasPermission("sv.joinvanished")) {
invisiblePlayers.add(p.getUniqueId().toString());
plugin.playerData.set("InvisiblePlayers", invisiblePlayers);
plugin.savePlayerData();
}
// vanished:
if (invisiblePlayers.contains(p.getUniqueId().toString())) {
if (getSettings().getBoolean(
"Configuration.Messages.HideNormalJoinAndLeaveMessagesWhileInvisible", true)) {
e.setJoinMessage(null);
}
if (plugin.getServer().getPluginManager()
.getPlugin("Essentials") != null
&& getSettings().getBoolean("Configuration.Hooks.EnableEssentialsHook")) {
EssentialsHook.hidePlayer(p);
}
if (getSettings().getBoolean("Configuration.Messages.RemindInvisiblePlayersOnJoin")) {
p.sendMessage(plugin.convertString(
plugin.getMsg("RemindingMessage"), p));
}
plugin.getVisibilityAdjuster().getHider().hideToAll(p);
p.setMetadata("vanished", new FixedMetadataValue(plugin, true));
if (plugin.getActionBarMgr() != null
&& getSettings().getBoolean(
"Configuration.Messages.DisplayActionBarsToInvisiblePlayers")) {
plugin.getActionBarMgr().addActionBar(p);
}
if (plugin.packetNightVision && getSettings().getBoolean(
"Configuration.Players.AddNightVision"))
plugin.getProtocolLibPacketUtils().sendAddPotionEffect(p, new PotionEffect(
PotionEffectType.NIGHT_VISION,
ProtocolLibPacketUtils.INFINITE_POTION_DURATION, 0));
if (plugin.getTeamMgr() != null)
plugin.getTeamMgr().setCantPush(p);
}
// not necessarily vanished:
plugin.getVisibilityAdjuster().getHider().hideAllInvisibleTo(p);
}
} catch (Exception er) {
plugin.printException(er);
}
}
} | Fix duplicate uuids in playerdata
| src/main/java/de/myzelyam/supervanish/events/JoinEvent.java | Fix duplicate uuids in playerdata | <ide><path>rc/main/java/de/myzelyam/supervanish/events/JoinEvent.java
<ide> final List<String> invisiblePlayers = plugin.getAllInvisiblePlayers();
<ide>
<ide> if (getSettings().getBoolean("Configuration.Players.AutoVanishOnJoin", false)
<del> && p.hasPermission("sv.joinvanished")) {
<add> && p.hasPermission("sv.joinvanished")
<add> && !invisiblePlayers.contains(p.getUniqueId().toString())) {
<ide> invisiblePlayers.add(p.getUniqueId().toString());
<ide> plugin.playerData.set("InvisiblePlayers", invisiblePlayers);
<ide> plugin.savePlayerData(); |
|
Java | apache-2.0 | ee85679be3aa28162dff650f4ddca7893f52e555 | 0 | cleliameneghin/sling,codders/k2-sling-fork,SylvesterAbreu/sling,mikibrv/sling,sdmcraft/sling,tyge68/sling,anchela/sling,trekawek/sling,wimsymons/sling,headwirecom/sling,ieb/sling,cleliameneghin/sling,awadheshv/sling,tmaret/sling,mcdan/sling,labertasch/sling,headwirecom/sling,labertasch/sling,headwirecom/sling,trekawek/sling,tteofili/sling,mmanski/sling,ffromm/sling,labertasch/sling,vladbailescu/sling,Sivaramvt/sling,ist-dresden/sling,Sivaramvt/sling,ffromm/sling,awadheshv/sling,sdmcraft/sling,plutext/sling,cleliameneghin/sling,headwirecom/sling,wimsymons/sling,roele/sling,tyge68/sling,gutsy/sling,ieb/sling,ist-dresden/sling,tmaret/sling,labertasch/sling,ieb/sling,mikibrv/sling,SylvesterAbreu/sling,mikibrv/sling,roele/sling,SylvesterAbreu/sling,wimsymons/sling,awadheshv/sling,trekawek/sling,JEBailey/sling,cleliameneghin/sling,cleliameneghin/sling,JEBailey/sling,Nimco/sling,nleite/sling,gutsy/sling,awadheshv/sling,ist-dresden/sling,ffromm/sling,trekawek/sling,mcdan/sling,codders/k2-sling-fork,Nimco/sling,mmanski/sling,tteofili/sling,Nimco/sling,ist-dresden/sling,Nimco/sling,labertasch/sling,dulvac/sling,Nimco/sling,mikibrv/sling,tteofili/sling,codders/k2-sling-fork,sdmcraft/sling,vladbailescu/sling,tyge68/sling,vladbailescu/sling,ieb/sling,tteofili/sling,roele/sling,JEBailey/sling,sdmcraft/sling,anchela/sling,klcodanr/sling,wimsymons/sling,mmanski/sling,gutsy/sling,nleite/sling,Nimco/sling,plutext/sling,ieb/sling,klcodanr/sling,mcdan/sling,dulvac/sling,ffromm/sling,Sivaramvt/sling,mcdan/sling,Sivaramvt/sling,klcodanr/sling,plutext/sling,tmaret/sling,trekawek/sling,anchela/sling,plutext/sling,plutext/sling,headwirecom/sling,wimsymons/sling,dulvac/sling,ist-dresden/sling,anchela/sling,mmanski/sling,tyge68/sling,klcodanr/sling,gutsy/sling,gutsy/sling,roele/sling,mikibrv/sling,dulvac/sling,gutsy/sling,Sivaramvt/sling,dulvac/sling,ffromm/sling,SylvesterAbreu/sling,nleite/sling,plutext/sling,mmanski/sling,nleite/sling,klcodanr/sling,roele/sling,dulvac/sling,JEBailey/sling,tmaret/sling,JEBailey/sling,nleite/sling,mmanski/sling,SylvesterAbreu/sling,mcdan/sling,mcdan/sling,tteofili/sling,SylvesterAbreu/sling,sdmcraft/sling,ffromm/sling,tyge68/sling,ieb/sling,vladbailescu/sling,awadheshv/sling,tmaret/sling,trekawek/sling,Sivaramvt/sling,anchela/sling,nleite/sling,sdmcraft/sling,tyge68/sling,awadheshv/sling,klcodanr/sling,vladbailescu/sling,wimsymons/sling,tteofili/sling,mikibrv/sling | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.sling.jcr.resource.testhelper;
import java.io.IOException;
import java.io.InputStream;
import java.util.Hashtable;
import javax.jcr.Credentials;
import javax.jcr.LoginException;
import javax.jcr.NoSuchWorkspaceException;
import javax.jcr.Repository;
import javax.jcr.RepositoryException;
import javax.jcr.Session;
import javax.jcr.SimpleCredentials;
import javax.jcr.Workspace;
import javax.jcr.nodetype.NodeTypeManager;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import org.apache.jackrabbit.api.JackrabbitNodeTypeManager;
import org.apache.jackrabbit.core.jndi.RegistryHelper;
import org.apache.sling.jcr.api.SlingRepository;
/**
* Utility class for managing JCR repositories.
*/
public class RepositoryUtil {
public static final String REPOSITORY_NAME = "repositoryTest";
public static final String ADMIN_NAME = "admin";
public static final String ADMIN_PASSWORD = "admin";
public static final String CONTEXT_FACTORY = "org.apache.jackrabbit.core.jndi.provider.DummyInitialContextFactory";
public static final String PROVIDER_URL = "localhost";
public static final String CONFIG_FILE = "./src/test/test-config/repository-derby.xml";
public static final String HOME_DIR = "target/repository";
protected static InitialContext getInitialContext() throws NamingException {
final Hashtable<String, String> env = new Hashtable<String, String>();
env.put(Context.INITIAL_CONTEXT_FACTORY, CONTEXT_FACTORY);
env.put(Context.PROVIDER_URL, PROVIDER_URL);
return new InitialContext(env);
}
/**
* Start a new repository
*
* @throws RepositoryException when it is not possible to start the
* repository.
* @throws NamingException
*/
public static void startRepository() throws RepositoryException,
NamingException {
RegistryHelper.registerRepository(getInitialContext(), REPOSITORY_NAME,
CONFIG_FILE, HOME_DIR, true);
}
/**
* Stop a repository.
*
* @throws NamingException when it is not possible to stop the
* repository
* @throws NamingException
*/
public static void stopRepository() throws NamingException {
RegistryHelper.unregisterRepository(getInitialContext(),
REPOSITORY_NAME);
}
/**
* Get a repository
*
* @return a JCR repository reference
* @throws NamingException when it is not possible to get the
* repository. Before calling this method, the repository has to
* be registered (@see RepositoryUtil#registerRepository(String,
* String, String)
* @throws NamingException
*/
public static SlingRepository getRepository() throws NamingException {
return new RepositoryWrapper((Repository) getInitialContext().lookup(
REPOSITORY_NAME));
}
/**
* Registers node types from the CND file read from the <code>source</code>
* with the node type manager available from the given <code>session</code>.
* <p>
* The <code>NodeTypeManager</code> returned by the <code>session</code>'s
* workspace is expected to be of type
* <code>org.apache.jackrabbit.api.JackrabbitNodeTypeManager</code> for
* the node type registration to succeed.
* <p>
* This method is not synchronized. It is up to the calling method to
* prevent paralell execution.
*
* @param session The <code>Session</code> providing the node type manager
* through which the node type is to be registered.
* @param source The <code>InputStream</code> from which the CND file is
* read.
* @return <code>true</code> if registration of all node types succeeded.
*/
public static boolean registerNodeType(Session session, InputStream source)
throws IOException, RepositoryException {
Workspace workspace = session.getWorkspace();
NodeTypeManager ntm = workspace.getNodeTypeManager();
if (ntm instanceof JackrabbitNodeTypeManager) {
JackrabbitNodeTypeManager jntm = (JackrabbitNodeTypeManager) ntm;
try {
jntm.registerNodeTypes(source,
JackrabbitNodeTypeManager.TEXT_X_JCR_CND);
return true;
} catch (RepositoryException re) {
Throwable t = re.getCause();
if (t != null
&& t.getClass().getName().endsWith(
".InvalidNodeTypeDefException")) {
// hacky wacky: interpret message to check whether it is for
// duplicate node type -> very bad, that this is the only
// way to check !!!
if (re.getCause().getMessage().indexOf("already exists") >= 0) {
// alright, node types are already registered, ignore
// this
return true;
}
}
// get here to rethrow the RepositoryException
throw re;
}
}
return false;
}
public static final class RepositoryWrapper implements SlingRepository {
protected final Repository wrapped;
public RepositoryWrapper(Repository r) {
wrapped = r;
}
public String getDescriptor(String key) {
return wrapped.getDescriptor(key);
}
public String[] getDescriptorKeys() {
return wrapped.getDescriptorKeys();
}
public Session login() throws LoginException, RepositoryException {
return wrapped.login();
}
public Session login(Credentials credentials, String workspaceName)
throws LoginException, NoSuchWorkspaceException,
RepositoryException {
return wrapped.login(credentials, workspaceName);
}
public Session login(Credentials credentials) throws LoginException,
RepositoryException {
return wrapped.login(credentials);
}
public Session login(String workspaceName) throws LoginException,
NoSuchWorkspaceException, RepositoryException {
return wrapped.login(workspaceName);
}
public String getDefaultWorkspace() {
return "default";
}
public Session loginAdministrative(String workspace)
throws RepositoryException {
final Credentials credentials = new SimpleCredentials(ADMIN_NAME,
ADMIN_PASSWORD.toCharArray());
return this.login(credentials, workspace);
}
}
} | jcr/resource/src/test/java/org/apache/sling/jcr/resource/testhelper/RepositoryUtil.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.sling.jcr.resource.testhelper;
import java.io.IOException;
import java.io.InputStream;
import java.util.Hashtable;
import javax.jcr.Credentials;
import javax.jcr.LoginException;
import javax.jcr.NoSuchWorkspaceException;
import javax.jcr.Repository;
import javax.jcr.RepositoryException;
import javax.jcr.Session;
import javax.jcr.SimpleCredentials;
import javax.jcr.Workspace;
import javax.jcr.nodetype.NodeTypeManager;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import org.apache.jackrabbit.api.JackrabbitNodeTypeManager;
import org.apache.jackrabbit.core.jndi.RegistryHelper;
import org.apache.sling.jcr.api.SlingRepository;
/**
* Utility class for managing JCR repositories.
*/
public class RepositoryUtil {
public static final String REPOSITORY_NAME = "repositoryTest";
public static final String ADMIN_NAME = "admin";
public static final String ADMIN_PASSWORD = "admin";
public static final String CONTEXT_FACTORY = "org.apache.jackrabbit.core.jndi.provider.DummyInitialContextFactory";
public static final String PROVIDER_URL = "localhost";
public static final String CONFIG_FILE = "./src/test/test-config/repository-derby.xml";
public static final String HOME_DIR = "target/repository";
protected static InitialContext getInitialContext() throws NamingException {
final Hashtable<String, String> env = new Hashtable<String, String>();
env.put(Context.INITIAL_CONTEXT_FACTORY, CONTEXT_FACTORY);
env.put(Context.PROVIDER_URL, PROVIDER_URL);
return new InitialContext(env);
}
/**
* Start a new repository
*
* @throws RepositoryException when it is not possible to start the
* repository.
* @throws NamingException
*/
public static void startRepository() throws RepositoryException,
NamingException {
RegistryHelper.registerRepository(getInitialContext(), REPOSITORY_NAME,
CONFIG_FILE, HOME_DIR, true);
}
/**
* Stop a repository.
*
* @throws RepositoryException when it is not possible to stop the
* repository
* @throws NamingException
*/
public static void stopRepository() throws NamingException {
RegistryHelper.unregisterRepository(getInitialContext(),
REPOSITORY_NAME);
}
/**
* Get a repository
*
* @return a JCR repository reference
* @throws RepositoryException when it is not possible to get the
* repository. Before calling this method, the repository has to
* be registered (@see RepositoryUtil#registerRepository(String,
* String, String)
* @throws NamingException
*/
public static SlingRepository getRepository() throws NamingException {
return new RepositoryWrapper((Repository) getInitialContext().lookup(
REPOSITORY_NAME));
}
/**
* Registers node types from the CND file read from the <code>source</code>
* with the node type manager available from the given <code>session</code>.
* <p>
* The <code>NodeTypeManager</code> returned by the <code>session</code>'s
* workspace is expected to be of type
* <code>org.apache.jackrabbit.api.JackrabbitNodeTypeManager</code> for
* the node type registration to succeed.
* <p>
* This method is not synchronized. It is up to the calling method to
* prevent paralell execution.
*
* @param session The <code>Session</code> providing the node type manager
* through which the node type is to be registered.
* @param source The <code>InputStream</code> from which the CND file is
* read.
* @return <code>true</code> if registration of all node types succeeded.
*/
public static boolean registerNodeType(Session session, InputStream source)
throws IOException, RepositoryException {
Workspace workspace = session.getWorkspace();
NodeTypeManager ntm = workspace.getNodeTypeManager();
if (ntm instanceof JackrabbitNodeTypeManager) {
JackrabbitNodeTypeManager jntm = (JackrabbitNodeTypeManager) ntm;
try {
jntm.registerNodeTypes(source,
JackrabbitNodeTypeManager.TEXT_X_JCR_CND);
return true;
} catch (RepositoryException re) {
Throwable t = re.getCause();
if (t != null
&& t.getClass().getName().endsWith(
".InvalidNodeTypeDefException")) {
// hacky wacky: interpret message to check whether it is for
// duplicate node type -> very bad, that this is the only
// way to check !!!
if (re.getCause().getMessage().indexOf("already exists") >= 0) {
// alright, node types are already registered, ignore
// this
return true;
}
}
// get here to rethrow the RepositoryException
throw re;
}
}
return false;
}
public static final class RepositoryWrapper implements SlingRepository {
protected final Repository wrapped;
public RepositoryWrapper(Repository r) {
wrapped = r;
}
public String getDescriptor(String key) {
return wrapped.getDescriptor(key);
}
public String[] getDescriptorKeys() {
return wrapped.getDescriptorKeys();
}
public Session login() throws LoginException, RepositoryException {
return wrapped.login();
}
public Session login(Credentials credentials, String workspaceName)
throws LoginException, NoSuchWorkspaceException,
RepositoryException {
return wrapped.login(credentials, workspaceName);
}
public Session login(Credentials credentials) throws LoginException,
RepositoryException {
return wrapped.login(credentials);
}
public Session login(String workspaceName) throws LoginException,
NoSuchWorkspaceException, RepositoryException {
return wrapped.login(workspaceName);
}
public String getDefaultWorkspace() {
return "default";
}
public Session loginAdministrative(String workspace)
throws RepositoryException {
final Credentials credentials = new SimpleCredentials(ADMIN_NAME,
ADMIN_PASSWORD.toCharArray());
return this.login(credentials, workspace);
}
}
} | Fix javadocs.
git-svn-id: c3eb811ccca381e673aa62a65336ec26649ed58c@605563 13f79535-47bb-0310-9956-ffa450edef68
| jcr/resource/src/test/java/org/apache/sling/jcr/resource/testhelper/RepositoryUtil.java | Fix javadocs. | <ide><path>cr/resource/src/test/java/org/apache/sling/jcr/resource/testhelper/RepositoryUtil.java
<ide> /**
<ide> * Stop a repository.
<ide> *
<del> * @throws RepositoryException when it is not possible to stop the
<add> * @throws NamingException when it is not possible to stop the
<ide> * repository
<ide> * @throws NamingException
<ide> */
<ide> * Get a repository
<ide> *
<ide> * @return a JCR repository reference
<del> * @throws RepositoryException when it is not possible to get the
<add> * @throws NamingException when it is not possible to get the
<ide> * repository. Before calling this method, the repository has to
<ide> * be registered (@see RepositoryUtil#registerRepository(String,
<ide> * String, String) |
|
Java | apache-2.0 | c07b12428d5549a8512978ab040fdd20e2cc627d | 0 | volodymyrpavlenko/muon-java,microserviceux/muon-java,microserviceux/muon-java | package io.muoncore.test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
import io.muoncore.Discovery;
import io.muoncore.Muon;
import io.muoncore.MuonClient.MuonResult;
import io.muoncore.MuonService;
import io.muoncore.MuonStreamGenerator;
import io.muoncore.extension.amqp.AmqpTransportExtension;
import io.muoncore.extension.amqp.discovery.AmqpDiscovery;
import io.muoncore.future.MuonFuture;
import io.muoncore.future.MuonFutures;
import io.muoncore.transport.resource.MuonResourceEvent;
import io.muoncore.transport.resource.MuonResourceEventBuilder;
import java.net.URISyntaxException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.LinkedBlockingQueue;
import org.junit.Before;
import org.junit.Test;
import org.reactivestreams.Publisher;
import org.reactivestreams.Subscriber;
import org.reactivestreams.Subscription;
/**
* @author sergio
*
*/
public class MuonTestCase {
private Muon m, c;
private String uuid;
@SuppressWarnings({ "unchecked", "rawtypes" })
@Before
public void setUp() throws Exception {
uuid = UUID.randomUUID().toString();
Discovery d = new AmqpDiscovery("amqp://muon:microservices@localhost");
AmqpTransportExtension ate = new AmqpTransportExtension("amqp://muon:microservices@localhost");
m = new Muon(d);
m.setServiceIdentifer("test-" + uuid);
m.addTag("server");
ate.extend(m);
m.start();
m.onCommand("/post-endpoint", Map.class,
new MuonService.MuonCommand() {
@Override
public MuonFuture onCommand(MuonResourceEvent queryEvent) {
System.out.println("onCommand");
Map res = new HashMap();
Map resource = (Map) queryEvent.getDecodedContent();
System.out.println(resource);
res.put("val", (Double) resource.get("val") + 1.0);
return MuonFutures.immediately(res);
}
});
m.streamSource("/stream-endpoint", Map.class,
new MuonStreamGenerator<Map>() {
@Override
public Publisher<Map> generatePublisher(
Map<String, String> parameters) {
return new Publisher<Map>() {
@Override
public void subscribe(Subscriber<? super Map> s) {
Map elem = new HashMap();
for(double i=1.0;i<6.0;i=i+1) {
elem.put("val", i);
s.onNext(elem);
}
s.onComplete();
}
};
}
});
d = new AmqpDiscovery("amqp://muon:microservices@localhost");
ate = new AmqpTransportExtension("amqp://muon:microservices@localhost");
c = new Muon(d);
c.setServiceIdentifer("test-" + uuid + "-client");
c.addTag("client");
ate.extend(c);
c.start();
Thread.sleep(10000);
}
//
// @SuppressWarnings({ "rawtypes", "unchecked" })
// @Test
// public void onePost() throws InterruptedException, ExecutionException {
// Map resource = new HashMap();
// resource.put("val", 1.0);
//
// MuonResourceEventBuilder mre = MuonResourceEventBuilder.event(resource);
// mre.withUri("muon://test-" + uuid + "/post-endpoint");
// MuonFuture mf = c.command("muon://test-" + uuid + "/post-endpoint", mre.build(), Map.class);
// System.out.println(mf.get().getClass());
// MuonResult result = (MuonResult) mf.get();
// Map mResult = (Map) result.getResponseEvent().getDecodedContent();
//
// assertEquals(mResult.get("val"), 2.0);
// }
@SuppressWarnings({ "rawtypes", "unchecked" })
@Test
public void manyPosts() throws InterruptedException, ExecutionException {
for(int i=0;i<10;i++) {
System.out.println("----------------------------------------------------------------------------------");
Map resource = new HashMap();
resource.put("val", 1.0);
MuonResourceEventBuilder mre = MuonResourceEventBuilder.event(resource);
mre.withUri("muon://test-" + uuid + "/post-endpoint");
MuonFuture mf = c.command("muon://test-" + uuid + "/post-endpoint", mre.build(), Map.class);
MuonResult result = (MuonResult) mf.get();
if (!result.isSuccess()) {
System.out.println("Not working");
}
Map mResult = (Map) result.getResponseEvent().getDecodedContent();
System.out.println(" Return is " + mResult);
assertEquals(mResult.get("val"), 2.0);
System.out.println("===========================================================================================");
}
}
@SuppressWarnings({ "rawtypes", "unchecked" })
@Test
public void streamTest() throws URISyntaxException, InterruptedException {
BlockingQueue bq;
Map endToken;
bq = new LinkedBlockingQueue();
endToken = new HashMap();
endToken.put("end", "ok");
c.subscribe("muon://test-" + uuid + "/stream-endpoint",
Map.class, new Subscriber() {
@Override
public void onSubscribe(Subscription s) {
System.out.println("Subscribed!");
}
@Override
public void onNext(Object t) {
try {
bq.put(t);
} catch (InterruptedException e) {
fail(e.getMessage());
}
}
@Override
public void onError(Throwable t) {
fail(t.getMessage());
}
@Override
public void onComplete() {
try {
bq.put(endToken);
} catch (InterruptedException e) {
fail(e.getMessage());
}
}
});
Map elem = (Map) bq.take();
double i = 1.0;
while(elem.get("end") == null || !elem.get("end").equals("ok")) {
assertEquals(elem.get("val"), i);
i = i + 1.0;
}
}
}
| muon-tck/src/test/java/io/muoncore/test/MuonTestCase.java | package io.muoncore.test;
import static org.junit.Assert.assertEquals;
import io.muoncore.Discovery;
import io.muoncore.Muon;
import io.muoncore.MuonClient.MuonResult;
import io.muoncore.MuonService;
import io.muoncore.extension.amqp.AmqpTransportExtension;
import io.muoncore.extension.amqp.discovery.AmqpDiscovery;
import io.muoncore.future.MuonFuture;
import io.muoncore.future.MuonFutures;
import io.muoncore.transport.resource.MuonResourceEvent;
import io.muoncore.transport.resource.MuonResourceEventBuilder;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ExecutionException;
import org.junit.Before;
import org.junit.Test;
/**
* @author sergio
*
*/
public class MuonTestCase {
private Muon m, c;
private String uuid;
@SuppressWarnings({ "unchecked", "rawtypes" })
@Before
public void setUp() throws Exception {
uuid = UUID.randomUUID().toString();
Discovery d = new AmqpDiscovery("amqp://muon:microservices@localhost");
AmqpTransportExtension ate = new AmqpTransportExtension("amqp://muon:microservices@localhost");
m = new Muon(d);
m.setServiceIdentifer("test-" + uuid);
m.addTag("server");
ate.extend(m);
m.start();
m.onCommand("/post-endpoint", Map.class,
new MuonService.MuonCommand() {
@Override
public MuonFuture onCommand(MuonResourceEvent queryEvent) {
System.out.println("onCommand");
Map res = new HashMap();
Map resource = (Map) queryEvent.getDecodedContent();
System.out.println(resource);
res.put("val", (Double) resource.get("val") + 1.0);
return MuonFutures.immediately(res);
}
});
d = new AmqpDiscovery("amqp://muon:microservices@localhost");
ate = new AmqpTransportExtension("amqp://muon:microservices@localhost");
c = new Muon(d);
c.setServiceIdentifer("test-" + uuid + "-client");
c.addTag("client");
ate.extend(c);
c.start();
Thread.sleep(10000);
}
//
// @SuppressWarnings({ "rawtypes", "unchecked" })
// @Test
// public void onePost() throws InterruptedException, ExecutionException {
// Map resource = new HashMap();
// resource.put("val", 1.0);
//
// MuonResourceEventBuilder mre = MuonResourceEventBuilder.event(resource);
// mre.withUri("muon://test-" + uuid + "/post-endpoint");
// MuonFuture mf = c.command("muon://test-" + uuid + "/post-endpoint", mre.build(), Map.class);
// System.out.println(mf.get().getClass());
// MuonResult result = (MuonResult) mf.get();
// Map mResult = (Map) result.getResponseEvent().getDecodedContent();
//
// assertEquals(mResult.get("val"), 2.0);
// }
@SuppressWarnings({ "rawtypes", "unchecked" })
@Test
public void manyPosts() throws InterruptedException, ExecutionException {
for(int i=0;i<10;i++) {
System.out.println("----------------------------------------------------------------------------------");
Map resource = new HashMap();
resource.put("val", 1.0);
MuonResourceEventBuilder mre = MuonResourceEventBuilder.event(resource);
mre.withUri("muon://test-" + uuid + "/post-endpoint");
MuonFuture mf = c.command("muon://test-" + uuid + "/post-endpoint", mre.build(), Map.class);
MuonResult result = (MuonResult) mf.get();
if (!result.isSuccess()) {
System.out.println("Not working");
}
Map mResult = (Map) result.getResponseEvent().getDecodedContent();
System.out.println(" Return is " + mResult);
assertEquals(mResult.get("val"), 2.0);
System.out.println("===========================================================================================");
}
}
}
| Add test that checks that stream elements come correctly | muon-tck/src/test/java/io/muoncore/test/MuonTestCase.java | Add test that checks that stream elements come correctly | <ide><path>uon-tck/src/test/java/io/muoncore/test/MuonTestCase.java
<ide> package io.muoncore.test;
<ide>
<ide> import static org.junit.Assert.assertEquals;
<add>import static org.junit.Assert.fail;
<ide> import io.muoncore.Discovery;
<ide> import io.muoncore.Muon;
<ide> import io.muoncore.MuonClient.MuonResult;
<ide> import io.muoncore.MuonService;
<add>import io.muoncore.MuonStreamGenerator;
<ide> import io.muoncore.extension.amqp.AmqpTransportExtension;
<ide> import io.muoncore.extension.amqp.discovery.AmqpDiscovery;
<ide> import io.muoncore.future.MuonFuture;
<ide> import io.muoncore.transport.resource.MuonResourceEvent;
<ide> import io.muoncore.transport.resource.MuonResourceEventBuilder;
<ide>
<add>import java.net.URISyntaxException;
<ide> import java.util.HashMap;
<ide> import java.util.Map;
<ide> import java.util.UUID;
<add>import java.util.concurrent.BlockingQueue;
<ide> import java.util.concurrent.ExecutionException;
<add>import java.util.concurrent.LinkedBlockingQueue;
<ide>
<ide> import org.junit.Before;
<ide> import org.junit.Test;
<add>import org.reactivestreams.Publisher;
<add>import org.reactivestreams.Subscriber;
<add>import org.reactivestreams.Subscription;
<ide>
<ide> /**
<ide> * @author sergio
<ide> *
<ide> */
<ide> public class MuonTestCase {
<del> private Muon m, c;
<del> private String uuid;
<add> private Muon m, c;
<add> private String uuid;
<ide>
<ide> @SuppressWarnings({ "unchecked", "rawtypes" })
<ide> @Before
<ide> res.put("val", (Double) resource.get("val") + 1.0);
<ide>
<ide> return MuonFutures.immediately(res);
<add> }
<add> });
<add> m.streamSource("/stream-endpoint", Map.class,
<add> new MuonStreamGenerator<Map>() {
<add> @Override
<add> public Publisher<Map> generatePublisher(
<add> Map<String, String> parameters) {
<add> return new Publisher<Map>() {
<add> @Override
<add> public void subscribe(Subscriber<? super Map> s) {
<add> Map elem = new HashMap();
<add> for(double i=1.0;i<6.0;i=i+1) {
<add> elem.put("val", i);
<add> s.onNext(elem);
<add> }
<add> s.onComplete();
<add> }
<add> };
<ide> }
<ide> });
<ide>
<ide> System.out.println("===========================================================================================");
<ide> }
<ide> }
<add>
<add> @SuppressWarnings({ "rawtypes", "unchecked" })
<add> @Test
<add> public void streamTest() throws URISyntaxException, InterruptedException {
<add> BlockingQueue bq;
<add> Map endToken;
<add>
<add> bq = new LinkedBlockingQueue();
<add> endToken = new HashMap();
<add> endToken.put("end", "ok");
<add>
<add> c.subscribe("muon://test-" + uuid + "/stream-endpoint",
<add> Map.class, new Subscriber() {
<add> @Override
<add> public void onSubscribe(Subscription s) {
<add> System.out.println("Subscribed!");
<add> }
<add>
<add> @Override
<add> public void onNext(Object t) {
<add> try {
<add> bq.put(t);
<add> } catch (InterruptedException e) {
<add> fail(e.getMessage());
<add> }
<add> }
<add>
<add> @Override
<add> public void onError(Throwable t) {
<add> fail(t.getMessage());
<add> }
<add>
<add> @Override
<add> public void onComplete() {
<add> try {
<add> bq.put(endToken);
<add> } catch (InterruptedException e) {
<add> fail(e.getMessage());
<add> }
<add> }
<add> });
<add>
<add> Map elem = (Map) bq.take();
<add> double i = 1.0;
<add> while(elem.get("end") == null || !elem.get("end").equals("ok")) {
<add> assertEquals(elem.get("val"), i);
<add> i = i + 1.0;
<add> }
<add> }
<ide> } |
|
Java | agpl-3.0 | 9a759a3d820a8f1df697fb065586a3fdfd17b3d7 | 0 | dgray16/libreplan,dgray16/libreplan,poum/libreplan,Marine-22/libre,skylow95/libreplan,dgray16/libreplan,skylow95/libreplan,skylow95/libreplan,LibrePlan/libreplan,dgray16/libreplan,poum/libreplan,dgray16/libreplan,LibrePlan/libreplan,Marine-22/libre,poum/libreplan,LibrePlan/libreplan,PaulLuchyn/libreplan,LibrePlan/libreplan,Marine-22/libre,LibrePlan/libreplan,dgray16/libreplan,skylow95/libreplan,dgray16/libreplan,skylow95/libreplan,poum/libreplan,PaulLuchyn/libreplan,PaulLuchyn/libreplan,Marine-22/libre,poum/libreplan,PaulLuchyn/libreplan,LibrePlan/libreplan,LibrePlan/libreplan,PaulLuchyn/libreplan,poum/libreplan,skylow95/libreplan,Marine-22/libre,PaulLuchyn/libreplan,PaulLuchyn/libreplan,Marine-22/libre | /*
* This file is part of LibrePlan
*
* Copyright (C) 2009-2010 Fundación para o Fomento da Calidade Industrial e
* Desenvolvemento Tecnolóxico de Galicia
* Copyright (C) 2010-2011 Igalia, S.L.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.libreplan.web.planner.company;
import static org.libreplan.web.I18nHelper._;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang.Validate;
import org.libreplan.business.common.entities.ProgressType;
import org.libreplan.business.planner.entities.TaskElement;
import org.libreplan.web.common.components.bandboxsearch.BandboxMultipleSearch;
import org.libreplan.web.common.components.finders.FilterPair;
import org.libreplan.web.planner.TaskGroupPredicate;
import org.libreplan.web.planner.tabs.MultipleTabsPlannerController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.context.annotation.Scope;
import org.zkoss.ganttz.IPredicate;
import org.zkoss.ganttz.Planner;
import org.zkoss.ganttz.extensions.ICommandOnTask;
import org.zkoss.ganttz.timetracker.zoom.ZoomLevel;
import org.zkoss.zk.ui.Component;
import org.zkoss.zk.ui.Executions;
import org.zkoss.zk.ui.WrongValueException;
import org.zkoss.zk.ui.event.Event;
import org.zkoss.zk.ui.event.EventListener;
import org.zkoss.zk.ui.event.Events;
import org.zkoss.zk.ui.util.Composer;
import org.zkoss.zul.Button;
import org.zkoss.zul.Checkbox;
import org.zkoss.zul.Combobox;
import org.zkoss.zul.Comboitem;
import org.zkoss.zul.ComboitemRenderer;
import org.zkoss.zul.Constraint;
import org.zkoss.zul.Datebox;
import org.zkoss.zul.ListModelList;
import org.zkoss.zul.Vbox;
/**
* Controller for company planning view. Representation of company orders in the
* planner.
*
* @author Manuel Rego Casasnovas <[email protected]>
*/
@org.springframework.stereotype.Component
@Scope(BeanDefinition.SCOPE_PROTOTYPE)
public class CompanyPlanningController implements Composer {
@Autowired
private ICompanyPlanningModel model;
private List<ICommandOnTask<TaskElement>> additional = new ArrayList<ICommandOnTask<TaskElement>>();
private Planner planner;
private Vbox orderFilter;
private Datebox filterStartDate;
private Datebox filterFinishDate;
private BandboxMultipleSearch bdFilters;
private Checkbox checkIncludeOrderElements;
private ICommandOnTask<TaskElement> doubleClickCommand;
private Map<String, String[]> parameters;
private MultipleTabsPlannerController tabsController;
public CompanyPlanningController() {
}
private Combobox cbProgressTypes;
private Button btnShowAdvances;
@Override
public void doAfterCompose(org.zkoss.zk.ui.Component comp) {
planner = (Planner) comp;
String zoomLevelParameter = null;
if ((parameters != null) && (parameters.get("zoom") != null)
&& !(parameters.isEmpty())) {
zoomLevelParameter = parameters.get("zoom")[0];
}
if (zoomLevelParameter != null) {
planner.setInitialZoomLevel(ZoomLevel
.getFromString(zoomLevelParameter));
}
planner.setAreContainersExpandedByDefault(Planner
.guessContainersExpandedByDefault(parameters));
initializeListboxProgressTypes();
planner.setAreShownAdvancesByDefault(Planner
.guessShowAdvancesByDefault(parameters));
planner.setAreShownReportedHoursByDefault(Planner
.guessShowReportedHoursByDefault(parameters));
orderFilter = (Vbox) planner.getFellow("orderFilter");
// Configuration of the order filter
Component filterComponent = Executions.createComponents(
"/orders/_orderFilter.zul", orderFilter,
new HashMap<String, String>());
filterComponent.setVariable("orderFilterController", this, true);
filterStartDate = (Datebox) filterComponent
.getFellow("filterStartDate");
filterFinishDate = (Datebox) filterComponent
.getFellow("filterFinishDate");
bdFilters = (BandboxMultipleSearch) filterComponent
.getFellow("bdFilters");
bdFilters.setFinder("taskGroupsMultipleFiltersFinder");
checkIncludeOrderElements = (Checkbox) filterComponent
.getFellow("checkIncludeOrderElements");
filterComponent.setVisible(true);
}
private void initializeListboxProgressTypes() {
if (cbProgressTypes == null) {
cbProgressTypes = (Combobox) planner.getFellow("cbProgressTypes");
}
if (btnShowAdvances == null) {
btnShowAdvances = (Button) planner.getFellow("showAdvances");
}
cbProgressTypes.setModel(new ListModelList(ProgressType.getAll()));
cbProgressTypes.setItemRenderer(new ProgressTypeRenderer());
// Update completion of tasks on selecting new progress type
cbProgressTypes.addEventListener(Events.ON_SELECT, new EventListener() {
@Override
public void onEvent(Event event) {
planner.forcedShowAdvances();
planner.updateCompletion(getSelectedProgressType().toString());
}
private ProgressType getSelectedProgressType() {
return (ProgressType) cbProgressTypes.getSelectedItem().getValue();
}
});
cbProgressTypes.setVisible(true);
ProgressType progressType = getProgressTypeFromConfiguration();
if (progressType != null) {
planner.updateCompletion(progressType.toString());
}
}
private class ProgressTypeRenderer implements ComboitemRenderer {
@Override
public void render(Comboitem item, Object data) {
ProgressType progressType = (ProgressType) data;
item.setValue(progressType);
item.setLabel(_(progressType.getValue()));
ProgressType configuredProgressType = getProgressTypeFromConfiguration();
if ((configuredProgressType != null)
&& configuredProgressType.equals(progressType)) {
cbProgressTypes.setSelectedItem(item);
}
}
}
public ProgressType getProgressTypeFromConfiguration() {
return model.getProgressTypeFromConfiguration();
}
public void setConfigurationForPlanner() {
// Added predicate
model
.setConfigurationToPlanner(planner, additional,
doubleClickCommand, createPredicate());
model.setTabsController(tabsController);
planner.updateSelectedZoomLevel();
planner.invalidate();
}
public void setAdditional(List<ICommandOnTask<TaskElement>> additional) {
Validate.notNull(additional);
Validate.noNullElements(additional);
this.additional = additional;
}
public void setDoubleClickCommand(
ICommandOnTask<TaskElement> doubleClickCommand) {
this.doubleClickCommand = doubleClickCommand;
}
public void setURLParameters(Map<String, String[]> parameters) {
this.parameters = parameters;
}
/**
* Operations to filter the tasks by multiple filters
*/
public Constraint checkConstraintFinishDate() {
return new Constraint() {
@Override
public void validate(Component comp, Object value)
throws WrongValueException {
Date finishDate = (Date) value;
if ((finishDate != null)
&& (filterStartDate.getValue() != null)
&& (finishDate.compareTo(filterStartDate.getValue()) < 0)) {
filterFinishDate.setValue(null);
throw new WrongValueException(comp,
_("must be greater than start date"));
}
}
};
}
public Constraint checkConstraintStartDate() {
return new Constraint() {
@Override
public void validate(Component comp, Object value)
throws WrongValueException {
Date startDate = (Date) value;
if ((startDate != null)
&& (filterFinishDate.getValue() != null)
&& (startDate.compareTo(filterFinishDate.getValue()) > 0)) {
filterStartDate.setValue(null);
throw new WrongValueException(comp,
_("must be lower than finish date"));
}
}
};
}
public void onApplyFilter() {
filterByPredicate(createPredicate());
}
private IPredicate createPredicate() {
List<FilterPair> listFilters = (List<FilterPair>) bdFilters
.getSelectedElements();
Date startDate = filterStartDate.getValue();
Date finishDate = filterFinishDate.getValue();
Boolean includeOrderElements = checkIncludeOrderElements.isChecked();
if (listFilters.isEmpty() && startDate == null && finishDate == null) {
return null;
}
return new TaskGroupPredicate(listFilters, startDate, finishDate,
includeOrderElements);
}
private void filterByPredicate(IPredicate predicate) {
// Recalculate predicate
model.setConfigurationToPlanner(planner, additional,
doubleClickCommand, predicate);
planner.updateSelectedZoomLevel();
planner.invalidate();
}
public void setTabsController(MultipleTabsPlannerController tabsController) {
this.tabsController = tabsController;
}
}
| libreplan-webapp/src/main/java/org/libreplan/web/planner/company/CompanyPlanningController.java | /*
* This file is part of LibrePlan
*
* Copyright (C) 2009-2010 Fundación para o Fomento da Calidade Industrial e
* Desenvolvemento Tecnolóxico de Galicia
* Copyright (C) 2010-2011 Igalia, S.L.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.libreplan.web.planner.company;
import static org.libreplan.web.I18nHelper._;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang.Validate;
import org.libreplan.business.common.entities.ProgressType;
import org.libreplan.business.planner.entities.TaskElement;
import org.libreplan.web.common.components.bandboxsearch.BandboxMultipleSearch;
import org.libreplan.web.common.components.finders.FilterPair;
import org.libreplan.web.planner.TaskGroupPredicate;
import org.libreplan.web.planner.tabs.MultipleTabsPlannerController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.context.annotation.Scope;
import org.zkoss.ganttz.IPredicate;
import org.zkoss.ganttz.Planner;
import org.zkoss.ganttz.extensions.ICommandOnTask;
import org.zkoss.ganttz.timetracker.zoom.ZoomLevel;
import org.zkoss.zk.ui.Component;
import org.zkoss.zk.ui.Executions;
import org.zkoss.zk.ui.WrongValueException;
import org.zkoss.zk.ui.event.Event;
import org.zkoss.zk.ui.event.EventListener;
import org.zkoss.zk.ui.event.Events;
import org.zkoss.zk.ui.util.Composer;
import org.zkoss.zul.Button;
import org.zkoss.zul.Checkbox;
import org.zkoss.zul.Combobox;
import org.zkoss.zul.Comboitem;
import org.zkoss.zul.ComboitemRenderer;
import org.zkoss.zul.Constraint;
import org.zkoss.zul.Datebox;
import org.zkoss.zul.ListModelList;
import org.zkoss.zul.Vbox;
/**
* Controller for company planning view. Representation of company orders in the
* planner.
*
* @author Manuel Rego Casasnovas <[email protected]>
*/
@org.springframework.stereotype.Component
@Scope(BeanDefinition.SCOPE_PROTOTYPE)
public class CompanyPlanningController implements Composer {
@Autowired
private ICompanyPlanningModel model;
private List<ICommandOnTask<TaskElement>> additional = new ArrayList<ICommandOnTask<TaskElement>>();
private Planner planner;
private Vbox orderFilter;
private Datebox filterStartDate;
private Datebox filterFinishDate;
private BandboxMultipleSearch bdFilters;
private Checkbox checkIncludeOrderElements;
private ICommandOnTask<TaskElement> doubleClickCommand;
private Map<String, String[]> parameters;
private MultipleTabsPlannerController tabsController;
public CompanyPlanningController() {
}
private Combobox cbProgressTypes;
private Button btnShowAdvances;
@Override
public void doAfterCompose(org.zkoss.zk.ui.Component comp) {
planner = (Planner) comp;
String zoomLevelParameter = null;
if ((parameters != null) && (parameters.get("zoom") != null)
&& !(parameters.isEmpty())) {
zoomLevelParameter = parameters.get("zoom")[0];
}
if (zoomLevelParameter != null) {
planner.setInitialZoomLevel(ZoomLevel
.getFromString(zoomLevelParameter));
}
planner.setAreContainersExpandedByDefault(Planner
.guessContainersExpandedByDefault(parameters));
initializeListboxProgressTypes();
planner.setAreShownAdvancesByDefault(Planner
.guessShowAdvancesByDefault(parameters));
planner.setAreShownReportedHoursByDefault(Planner
.guessShowReportedHoursByDefault(parameters));
orderFilter = (Vbox) planner.getFellow("orderFilter");
// Configuration of the order filter
Component filterComponent = Executions.createComponents(
"/orders/_orderFilter.zul", orderFilter,
new HashMap<String, String>());
filterComponent.setVariable("orderFilterController", this, true);
filterStartDate = (Datebox) filterComponent
.getFellow("filterStartDate");
filterFinishDate = (Datebox) filterComponent
.getFellow("filterFinishDate");
bdFilters = (BandboxMultipleSearch) filterComponent
.getFellow("bdFilters");
bdFilters.setFinder("taskGroupsMultipleFiltersFinder");
checkIncludeOrderElements = (Checkbox) filterComponent
.getFellow("checkIncludeOrderElements");
filterComponent.setVisible(true);
}
private void initializeListboxProgressTypes() {
if (cbProgressTypes == null) {
cbProgressTypes = (Combobox) planner.getFellow("cbProgressTypes");
}
if (btnShowAdvances == null) {
btnShowAdvances = (Button) planner.getFellow("showAdvances");
}
cbProgressTypes.setModel(new ListModelList(ProgressType.getAll()));
cbProgressTypes.setItemRenderer(new ProgressTypeRenderer());
// Update completion of tasks on selecting new progress type
cbProgressTypes.addEventListener(Events.ON_SELECT, new EventListener() {
@Override
public void onEvent(Event event) {
planner.forcedShowAdvances();
planner.updateCompletion(getSelectedProgressType().toString());
}
private ProgressType getSelectedProgressType() {
return (ProgressType) cbProgressTypes.getSelectedItem().getValue();
}
});
cbProgressTypes.setVisible(true);
ProgressType progressType = getProgressTypeFromConfiguration();
if (progressType != null) {
planner.updateCompletion(progressType.toString());
}
}
private class ProgressTypeRenderer implements ComboitemRenderer {
@Override
public void render(Comboitem item, Object data) {
ProgressType progressType = (ProgressType) data;
item.setValue(progressType);
item.setLabel(_(progressType.getValue()));
if (getProgressTypeFromConfiguration().equals(progressType)) {
cbProgressTypes.setSelectedItem(item);
}
}
}
public ProgressType getProgressTypeFromConfiguration() {
return model.getProgressTypeFromConfiguration();
}
public void setConfigurationForPlanner() {
// Added predicate
model
.setConfigurationToPlanner(planner, additional,
doubleClickCommand, createPredicate());
model.setTabsController(tabsController);
planner.updateSelectedZoomLevel();
planner.invalidate();
}
public void setAdditional(List<ICommandOnTask<TaskElement>> additional) {
Validate.notNull(additional);
Validate.noNullElements(additional);
this.additional = additional;
}
public void setDoubleClickCommand(
ICommandOnTask<TaskElement> doubleClickCommand) {
this.doubleClickCommand = doubleClickCommand;
}
public void setURLParameters(Map<String, String[]> parameters) {
this.parameters = parameters;
}
/**
* Operations to filter the tasks by multiple filters
*/
public Constraint checkConstraintFinishDate() {
return new Constraint() {
@Override
public void validate(Component comp, Object value)
throws WrongValueException {
Date finishDate = (Date) value;
if ((finishDate != null)
&& (filterStartDate.getValue() != null)
&& (finishDate.compareTo(filterStartDate.getValue()) < 0)) {
filterFinishDate.setValue(null);
throw new WrongValueException(comp,
_("must be greater than start date"));
}
}
};
}
public Constraint checkConstraintStartDate() {
return new Constraint() {
@Override
public void validate(Component comp, Object value)
throws WrongValueException {
Date startDate = (Date) value;
if ((startDate != null)
&& (filterFinishDate.getValue() != null)
&& (startDate.compareTo(filterFinishDate.getValue()) > 0)) {
filterStartDate.setValue(null);
throw new WrongValueException(comp,
_("must be lower than finish date"));
}
}
};
}
public void onApplyFilter() {
filterByPredicate(createPredicate());
}
private IPredicate createPredicate() {
List<FilterPair> listFilters = (List<FilterPair>) bdFilters
.getSelectedElements();
Date startDate = filterStartDate.getValue();
Date finishDate = filterFinishDate.getValue();
Boolean includeOrderElements = checkIncludeOrderElements.isChecked();
if (listFilters.isEmpty() && startDate == null && finishDate == null) {
return null;
}
return new TaskGroupPredicate(listFilters, startDate, finishDate,
includeOrderElements);
}
private void filterByPredicate(IPredicate predicate) {
// Recalculate predicate
model.setConfigurationToPlanner(planner, additional,
doubleClickCommand, predicate);
planner.updateSelectedZoomLevel();
planner.invalidate();
}
public void setTabsController(MultipleTabsPlannerController tabsController) {
this.tabsController = tabsController;
}
}
| Prevent NullPointerException filling progress type combo
FEA: ItEr75S04BugFixing
| libreplan-webapp/src/main/java/org/libreplan/web/planner/company/CompanyPlanningController.java | Prevent NullPointerException filling progress type combo | <ide><path>ibreplan-webapp/src/main/java/org/libreplan/web/planner/company/CompanyPlanningController.java
<ide> item.setValue(progressType);
<ide> item.setLabel(_(progressType.getValue()));
<ide>
<del> if (getProgressTypeFromConfiguration().equals(progressType)) {
<add> ProgressType configuredProgressType = getProgressTypeFromConfiguration();
<add> if ((configuredProgressType != null)
<add> && configuredProgressType.equals(progressType)) {
<ide> cbProgressTypes.setSelectedItem(item);
<ide> }
<ide> } |
|
Java | bsd-3-clause | 69ac43fbb838129da8a18032eb083ae83a2015f4 | 0 | Hyperion3360/HyperionRobot2014 | // RobotBuilder Version: 1.0
//
// This file was generated by RobotBuilder. It contains sections of
// code that are automatically generated and assigned by robotbuilder.
// These sections will be updated in the future when you export to
// Java from RobotBuilder. Do not put any code or make any change in
// the blocks indicating autogenerated code or it will be lost on an
// update. Deleting the comments indicating the section will prevent
// it from being updated in the future.
package org.usfirst.frc3360.Hyperion2014;
import edu.wpi.first.wpilibj.IterativeRobot;
import edu.wpi.first.wpilibj.command.Command;
import edu.wpi.first.wpilibj.command.Scheduler;
import edu.wpi.first.wpilibj.livewindow.LiveWindow;
import org.usfirst.frc3360.Hyperion2014.commands.*;
import org.usfirst.frc3360.Hyperion2014.subsystems.*;
import edu.wpi.first.wpilibj.Compressor;
import edu.wpi.first.wpilibj.Relay;
/**
* The VM is configured to automatically run this class, and to call the
* functions corresponding to each mode, as described in the IterativeRobot
* documentation. If you change the name of this class or the package after
* creating this project, you must also update the manifest file in the resource
* directory.
*/
public class Robot extends IterativeRobot {
Command autonomousCommand;
public static OI oi;
public static CanonAngle canonAngle;
public static CanonSpinner canonSpinner;
public static CanonShooter canonShooter;
public static DriveTrain driveTrain;
public static LedsSetter LedsSetter;
public static Vision vision;
/**
* This function is run when the robot is first started up and should be
* used for any initialization code.
*/
public void robotInit() {
RobotMap.init();
vision = new Vision();
canonAngle = new CanonAngle();
canonSpinner = new CanonSpinner();
canonShooter = new CanonShooter();
driveTrain = new DriveTrain();
LedsSetter = new LedsSetter();
// This MUST be here. If the OI creates Commands (which it very likely
// will), constructing it during the construction of CommandBase (from
// which commands extend), subsystems are not guaranteed to be
// yet. Thus, their requires() statements may grab null pointers. Bad
// news. Don't move it.
oi = new OI();
// instantiate the command used for the autonomous period
double axisPos = oi.getDriverLeftJoystick().getRawAxis(3);
if(axisPos > .5){
autonomousCommand = new Autonomous_2balls();
}else if(axisPos < -.5){
autonomousCommand = new AutonomousMode();
}else{
autonomousCommand = null;
}
Compressor m_compressor = RobotMap.m_compressor;
m_compressor.start();
}
public void autonomousInit() {
// schedule the autonomous command (example)
if (autonomousCommand != null) autonomousCommand.start();
}
/**
* This function is called periodically during autonomous
*/
public void autonomousPeriodic() {
Scheduler.getInstance().run();
Robot.LedsSetter.FlashLedsPeriodic();
Robot.LedsSetter.SetBumpersColor();
}
public void teleopInit() {
// This makes sure that the autonomous stops running when
// teleop starts running. If you want the autonomous to
// continue until interrupted by another command, remove
// this line or comment it out.
if (autonomousCommand != null) autonomousCommand.cancel();
}
/**
* This function is called periodically during operator control
*/
public void teleopPeriodic() {
Scheduler.getInstance().run();
Robot.LedsSetter.FlashLedsPeriodic();
Robot.LedsSetter.SetBumpersColor();
}
/**
* This function called periodically during test mode
*/
public void testPeriodic() {
LiveWindow.run();
}
public void disabledInit() {
System.out.println("Robot.disabledInit");
Robot.LedsSetter.FlashLedsPeriodic();
Robot.LedsSetter.SetBumpersColor();
driveTrain.resetGyro();
canonAngle.AngleStop();
canonAngle.ResetSecurity();
}
}
| src/org/usfirst/frc3360/Hyperion2014/Robot.java | // RobotBuilder Version: 1.0
//
// This file was generated by RobotBuilder. It contains sections of
// code that are automatically generated and assigned by robotbuilder.
// These sections will be updated in the future when you export to
// Java from RobotBuilder. Do not put any code or make any change in
// the blocks indicating autogenerated code or it will be lost on an
// update. Deleting the comments indicating the section will prevent
// it from being updated in the future.
package org.usfirst.frc3360.Hyperion2014;
import edu.wpi.first.wpilibj.IterativeRobot;
import edu.wpi.first.wpilibj.command.Command;
import edu.wpi.first.wpilibj.command.Scheduler;
import edu.wpi.first.wpilibj.livewindow.LiveWindow;
import org.usfirst.frc3360.Hyperion2014.commands.*;
import org.usfirst.frc3360.Hyperion2014.subsystems.*;
import edu.wpi.first.wpilibj.Compressor;
import edu.wpi.first.wpilibj.Relay;
/**
* The VM is configured to automatically run this class, and to call the
* functions corresponding to each mode, as described in the IterativeRobot
* documentation. If you change the name of this class or the package after
* creating this project, you must also update the manifest file in the resource
* directory.
*/
public class Robot extends IterativeRobot {
Command autonomousCommand;
public static OI oi;
public static CanonAngle canonAngle;
public static CanonSpinner canonSpinner;
public static CanonShooter canonShooter;
public static DriveTrain driveTrain;
public static LedsSetter LedsSetter;
public static Vision vision;
/**
* This function is run when the robot is first started up and should be
* used for any initialization code.
*/
public void robotInit() {
RobotMap.init();
vision = new Vision();
canonAngle = new CanonAngle();
canonSpinner = new CanonSpinner();
canonShooter = new CanonShooter();
driveTrain = new DriveTrain();
LedsSetter = new LedsSetter();
// This MUST be here. If the OI creates Commands (which it very likely
// will), constructing it during the construction of CommandBase (from
// which commands extend), subsystems are not guaranteed to be
// yet. Thus, their requires() statements may grab null pointers. Bad
// news. Don't move it.
oi = new OI();
// instantiate the command used for the autonomous period
autonomousCommand = new Autonomous_2balls();
Compressor m_compressor = RobotMap.m_compressor;
m_compressor.start();
}
public void autonomousInit() {
// schedule the autonomous command (example)
if (autonomousCommand != null) autonomousCommand.start();
}
/**
* This function is called periodically during autonomous
*/
public void autonomousPeriodic() {
Scheduler.getInstance().run();
Robot.LedsSetter.FlashLedsPeriodic();
Robot.LedsSetter.SetBumpersColor();
}
public void teleopInit() {
// This makes sure that the autonomous stops running when
// teleop starts running. If you want the autonomous to
// continue until interrupted by another command, remove
// this line or comment it out.
if (autonomousCommand != null) autonomousCommand.cancel();
}
/**
* This function is called periodically during operator control
*/
public void teleopPeriodic() {
Scheduler.getInstance().run();
Robot.LedsSetter.FlashLedsPeriodic();
Robot.LedsSetter.SetBumpersColor();
}
/**
* This function called periodically during test mode
*/
public void testPeriodic() {
LiveWindow.run();
}
public void disabledInit() {
System.out.println("Robot.disabledInit");
Robot.LedsSetter.FlashLedsPeriodic();
Robot.LedsSetter.SetBumpersColor();
driveTrain.resetGyro();
canonAngle.AngleStop();
canonAngle.ResetSecurity();
}
}
| Can select which autonomous mode is used.
| src/org/usfirst/frc3360/Hyperion2014/Robot.java | Can select which autonomous mode is used. | <ide><path>rc/org/usfirst/frc3360/Hyperion2014/Robot.java
<ide> oi = new OI();
<ide>
<ide> // instantiate the command used for the autonomous period
<add> double axisPos = oi.getDriverLeftJoystick().getRawAxis(3);
<add> if(axisPos > .5){
<ide> autonomousCommand = new Autonomous_2balls();
<add> }else if(axisPos < -.5){
<add> autonomousCommand = new AutonomousMode();
<add> }else{
<add> autonomousCommand = null;
<add> }
<ide>
<ide> Compressor m_compressor = RobotMap.m_compressor;
<ide> m_compressor.start(); |
|
Java | apache-2.0 | b2703c52aba1966a370c768391553f2bca6a07a7 | 0 | dan-zx/rox-server | package com.grayfox.server.service.impl;
import java.util.ArrayList;
import java.util.List;
import javax.inject.Inject;
import javax.inject.Named;
import com.google.maps.DirectionsApi;
import com.google.maps.DirectionsApiRequest;
import com.google.maps.GeoApiContext;
import com.google.maps.model.DirectionsLeg;
import com.google.maps.model.DirectionsRoute;
import com.google.maps.model.DirectionsStep;
import com.google.maps.model.TravelMode;
import com.grayfox.server.service.RouteService;
import com.grayfox.server.service.model.Location;
import com.grayfox.server.service.model.Poi;
@Named
public class GoogleDirectionsRouteService implements RouteService {
private final GeoApiContext geoApiContext;
@Inject
public GoogleDirectionsRouteService(GeoApiContext geoApiContext) {
this.geoApiContext = geoApiContext;
}
@Override
public List<Location> createRoute(List<Poi> pois, Transportation transportation) {
if (pois.size() > 1) {
DirectionsApiRequest directionRequest = DirectionsApi.newRequest(geoApiContext)
.origin(pois.get(0).getLocation().stringValues())
.destination(pois.get(pois.size()-1).getLocation().stringValues())
.mode(toTravelMode(transportation));
String[] waypoints = new String[pois.size()-2];
for (int index = 1; index < pois.size()-1; index++) waypoints[index-1] = pois.get(index).getLocation().stringValues();
try {
DirectionsRoute[] routes = directionRequest.waypoints(waypoints).await();
if (routes.length > 0) return toListOfPoints(routes[0]);
else return new ArrayList<>(0); // TODO: Handle case when route is unavailable
} catch (Exception ex) {
// FIXME: Hardcoded exception message
throw new ServiceException("Route creation error", ex);
}
} else return new ArrayList<>(0);
}
private TravelMode toTravelMode(Transportation transportation) {
if (transportation == null) return TravelMode.DRIVING;
switch (transportation) {
case DRIVING: return TravelMode.DRIVING;
case WALKING: return TravelMode.WALKING;
case BICYCLING: return TravelMode.BICYCLING;
// case TRANSIT: return TravelMode.TRANSIT;
default: return TravelMode.UNKNOWN;
}
}
private List<Location> toListOfPoints(DirectionsRoute route) {
List<Location> routePoints = new ArrayList<>();
for (DirectionsLeg leg : route.legs) {
for (DirectionsStep step : leg.steps) {
Location startLocation = new Location();
startLocation.setLatitude(step.startLocation.lat);
startLocation.setLongitude(step.startLocation.lng);
Location endLocation = new Location();
endLocation.setLatitude(step.endLocation.lat);
endLocation.setLongitude(step.endLocation.lng);
routePoints.add(startLocation);
routePoints.add(endLocation);
}
}
return routePoints;
}
} | src/main/java/com/grayfox/server/service/impl/GoogleDirectionsRouteService.java | package com.grayfox.server.service.impl;
import java.util.ArrayList;
import java.util.List;
import javax.inject.Inject;
import javax.inject.Named;
import com.google.maps.DirectionsApi;
import com.google.maps.DirectionsApiRequest;
import com.google.maps.GeoApiContext;
import com.google.maps.model.DirectionsLeg;
import com.google.maps.model.DirectionsRoute;
import com.google.maps.model.DirectionsStep;
import com.google.maps.model.TravelMode;
import com.grayfox.server.service.RouteService;
import com.grayfox.server.service.model.Location;
import com.grayfox.server.service.model.Poi;
@Named
public class GoogleDirectionsRouteService implements RouteService {
private final GeoApiContext geoApiContext;
@Inject
public GoogleDirectionsRouteService(GeoApiContext geoApiContext) {
this.geoApiContext = geoApiContext;
}
@Override
public List<Location> createRoute(List<Poi> pois, Transportation transportation) {
if (pois.size() > 1) {
DirectionsApiRequest directionRequest = DirectionsApi.newRequest(geoApiContext)
.origin(pois.get(0).getLocation().stringValues())
.destination(pois.get(pois.size()-1).getLocation().stringValues())
.mode(toTravelMode(transportation));
String[] waypoints = new String[pois.size()-2];
for (int index = 1; index < pois.size()-1; index++) waypoints[index-1] = pois.get(index).getLocation().stringValues();
try {
DirectionsRoute[] routes = directionRequest.waypoints(waypoints).await();
if (routes.length > 0) return toListOfPoints(routes[0]);
else return new ArrayList<>(0); // TODO: Handle case when route is unavailable
} catch (Exception ex) {
// FIXME: Hardcoded exception message
throw new ServiceException("Route creation error", ex);
}
} else return new ArrayList<>(0);
}
private TravelMode toTravelMode(Transportation transportation) {
if (transportation == null) return TravelMode.DRIVING;
switch (transportation) {
case DRIVING: return TravelMode.DRIVING;
case WALKING: return TravelMode.WALKING;
case BICYCLING: return TravelMode.BICYCLING;
// case TRANSIT: return TravelMode.TRANSIT;
default: return TravelMode.UNKNOWN;
}
}
private List<Location> toListOfPoints(DirectionsRoute route) {
List<Location> routePoints = new ArrayList<>();
for (DirectionsLeg leg : route.legs) {
for (DirectionsStep step : leg.steps) {
Location startLocation = new Location();
startLocation.setLatitude(step.startLocation.lat);
startLocation.setLongitude(step.startLocation.lat);
Location endLocation = new Location();
endLocation.setLatitude(step.endLocation.lat);
endLocation.setLongitude(step.endLocation.lat);
routePoints.add(startLocation);
routePoints.add(endLocation);
}
}
return routePoints;
}
} | Bug fix
| src/main/java/com/grayfox/server/service/impl/GoogleDirectionsRouteService.java | Bug fix | <ide><path>rc/main/java/com/grayfox/server/service/impl/GoogleDirectionsRouteService.java
<ide> for (DirectionsStep step : leg.steps) {
<ide> Location startLocation = new Location();
<ide> startLocation.setLatitude(step.startLocation.lat);
<del> startLocation.setLongitude(step.startLocation.lat);
<add> startLocation.setLongitude(step.startLocation.lng);
<ide> Location endLocation = new Location();
<ide> endLocation.setLatitude(step.endLocation.lat);
<del> endLocation.setLongitude(step.endLocation.lat);
<add> endLocation.setLongitude(step.endLocation.lng);
<ide> routePoints.add(startLocation);
<ide> routePoints.add(endLocation);
<ide> } |
|
Java | mit | 11c41f16f5382faaecc22d9968ead4f5a652c419 | 0 | mcqueary/jnats | // Copyright 2015-2018 The NATS Authors
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at:
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package io.nats.client.impl;
import io.nats.client.*;
import io.nats.client.ConnectionListener.Events;
import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
import static io.nats.client.utils.TestBase.*;
import static org.junit.jupiter.api.Assertions.*;
public class ReconnectTests {
void checkReconnectingStatus(Connection nc) {
Connection.Status status = nc.getStatus();
assertTrue(Connection.Status.RECONNECTING == status ||
Connection.Status.DISCONNECTED == status, "Reconnecting status");
}
@Test
public void testSimpleReconnect() throws Exception { //Includes test for subscriptions and dispatchers across reconnect
NatsConnection nc;
TestHandler handler = new TestHandler();
int port = NatsTestServer.nextPort();
Subscription sub;
long start;
long end;
handler.setPrintExceptions(true);
try (NatsTestServer ts = new NatsTestServer(port, false)) {
Options options = new Options.Builder().
server(ts.getURI()).
maxReconnects(-1).
reconnectWait(Duration.ofMillis(1000)).
connectionListener(handler).
build();
port = ts.getPort();
nc = (NatsConnection)standardConnection(options);
sub = nc.subscribe("subsubject");
final NatsConnection nnc = nc; // final for the lambda
Dispatcher d = nc.createDispatcher((msg) -> nnc.publish(msg.getReplyTo(), msg.getData()) );
d.subscribe("dispatchSubject");
flushConnection(nc);
Future<Message> inc = nc.request("dispatchSubject", "test".getBytes(StandardCharsets.UTF_8));
Message msg = inc.get();
assertNotNull(msg);
nc.publish("subsubject", null);
msg = sub.nextMessage(Duration.ofMillis(100));
assertNotNull(msg);
handler.prepForStatusChange(Events.DISCONNECTED);
start = System.nanoTime();
}
flushAndWaitLong(nc, handler);
checkReconnectingStatus(nc);
handler.prepForStatusChange(Events.RESUBSCRIBED);
try (NatsTestServer ts = new NatsTestServer(port, false)) {
standardConnectionWait(nc, handler);
end = System.nanoTime();
assertTrue(1_000_000 * (end-start) > 1000, "reconnect wait");
// Make sure dispatcher and subscription are still there
Future<Message> inc = nc.request("dispatchSubject", "test".getBytes(StandardCharsets.UTF_8));
Message msg = inc.get(500, TimeUnit.MILLISECONDS);
assertNotNull(msg);
// make sure the subscription survived
nc.publish("subsubject", null);
msg = sub.nextMessage(Duration.ofMillis(100));
assertNotNull(msg);
}
assertEquals(1, nc.getNatsStatistics().getReconnects(), "reconnect count");
assertTrue(nc.getNatsStatistics().getExceptions() > 0, "exception count");
standardCloseConnection(nc);
}
@Test
public void testSubscribeDuringReconnect() throws Exception {
NatsConnection nc;
TestHandler handler = new TestHandler();
int port;
Subscription sub;
try (NatsTestServer ts = new NatsTestServer()) {
Options options = new Options.Builder().
server(ts.getURI()).
maxReconnects(-1).
reconnectWait(Duration.ofMillis(20)).
connectionListener(handler).
build();
port = ts.getPort();
nc = (NatsConnection) standardConnection(options);
handler.prepForStatusChange(Events.DISCONNECTED);
}
flushAndWaitLong(nc, handler);
checkReconnectingStatus(nc);
sub = nc.subscribe("subsubject");
final NatsConnection nnc = nc;
Dispatcher d = nc.createDispatcher((msg) -> nnc.publish(msg.getReplyTo(), msg.getData()));
d.subscribe("dispatchSubject");
handler.prepForStatusChange(Events.RECONNECTED);
try (NatsTestServer ts = new NatsTestServer(port, false)) {
standardConnectionWait(nc, handler);
// Make sure dispatcher and subscription are still there
Future<Message> inc = nc.request("dispatchSubject", "test".getBytes(StandardCharsets.UTF_8));
Message msg = inc.get();
assertNotNull(msg);
// make sure the subscription survived
nc.publish("subsubject", null);
msg = sub.nextMessage(Duration.ofMillis(100));
assertNotNull(msg);
}
assertEquals(1, nc.getNatsStatistics().getReconnects(), "reconnect count");
assertTrue(nc.getNatsStatistics().getExceptions() > 0, "exception count");
standardCloseConnection(nc);
}
@Test
public void testReconnectBuffer() throws Exception {
NatsConnection nc;
TestHandler handler = new TestHandler();
int port = NatsTestServer.nextPort();
Subscription sub;
long start;
long end;
String[] customArgs = {"--user","stephen","--pass","password"};
handler.setPrintExceptions(true);
try (NatsTestServer ts = new NatsTestServer(customArgs, port, false)) {
Options options = new Options.Builder().
server(ts.getURI()).
maxReconnects(-1).
userInfo("stephen".toCharArray(), "password".toCharArray()).
reconnectWait(Duration.ofMillis(1000)).
connectionListener(handler).
build();
nc = (NatsConnection) standardConnection(options);
sub = nc.subscribe("subsubject");
final NatsConnection nnc = nc;
Dispatcher d = nc.createDispatcher((msg) -> nnc.publish(msg.getReplyTo(), msg.getData()));
d.subscribe("dispatchSubject");
nc.flush(Duration.ofMillis(1000));
Future<Message> inc = nc.request("dispatchSubject", "test".getBytes(StandardCharsets.UTF_8));
Message msg = inc.get();
assertNotNull(msg);
nc.publish("subsubject", null);
msg = sub.nextMessage(Duration.ofMillis(100));
assertNotNull(msg);
handler.prepForStatusChange(Events.DISCONNECTED);
start = System.nanoTime();
}
flushAndWaitLong(nc, handler);
checkReconnectingStatus(nc);
// Send a message to the dispatcher and one to the subscriber
// These should be sent on reconnect
Future<Message> inc = nc.request("dispatchSubject", "test".getBytes(StandardCharsets.UTF_8));
nc.publish("subsubject", null);
nc.publish("subsubject", null);
handler.prepForStatusChange(Events.RESUBSCRIBED);
try (NatsTestServer ts = new NatsTestServer(customArgs, port, false)) {
standardConnectionWait(nc, handler);
end = System.nanoTime();
assertTrue(1_000_000 * (end-start) > 1000, "reconnect wait");
// Check the message we sent to dispatcher
Message msg = inc.get(500, TimeUnit.MILLISECONDS);
assertNotNull(msg);
// Check the two we sent to subscriber
msg = sub.nextMessage(Duration.ofMillis(500));
assertNotNull(msg);
msg = sub.nextMessage(Duration.ofMillis(500));
assertNotNull(msg);
}
assertEquals(1, nc.getNatsStatistics().getReconnects(), "reconnect count");
assertTrue(nc.getNatsStatistics().getExceptions() > 0, "exception count");
standardCloseConnection(nc);
}
@Test
public void testMaxReconnects() throws Exception {
Connection nc;
TestHandler handler = new TestHandler();
int port = NatsTestServer.nextPort();
try (NatsTestServer ts = new NatsTestServer(port, false)) {
Options options = new Options.Builder().
server(ts.getURI()).
maxReconnects(1).
connectionListener(handler).
reconnectWait(Duration.ofMillis(10)).
build();
nc = standardConnection(options);
handler.prepForStatusChange(Events.CLOSED);
}
flushAndWaitLong(nc, handler);
assertSame(Connection.Status.CLOSED, nc.getStatus(), "Closed Status");
standardCloseConnection(nc);
}
@Test
public void testReconnectToSecondServer() throws Exception {
NatsConnection nc;
TestHandler handler = new TestHandler();
try (NatsTestServer ts = new NatsTestServer()) {
try (NatsTestServer ts2 = new NatsTestServer()) {
Options options = new Options.Builder().
server(ts2.getURI()).
server(ts.getURI()).
noRandomize().
connectionListener(handler).
maxReconnects(-1).
build();
nc = (NatsConnection) standardConnection(options);
assertEquals(ts2.getURI(), nc.getConnectedUrl());
handler.prepForStatusChange(Events.RECONNECTED);
}
flushAndWaitLong(nc, handler);
assertConnected(nc);
assertEquals(ts.getURI(), nc.getConnectedUrl());
standardCloseConnection(nc);
}
}
@Test
public void testNoRandomizeReconnectToSecondServer() throws Exception {
NatsConnection nc;
TestHandler handler = new TestHandler();
try (NatsTestServer ts = new NatsTestServer()) {
try (NatsTestServer ts2 = new NatsTestServer()) {
Options options = new Options.Builder().
server(ts2.getURI()).
server(ts.getURI()).
connectionListener(handler).
maxReconnects(-1).
noRandomize().
build();
nc = (NatsConnection) standardConnection(options);
assertEquals(nc.getConnectedUrl(), ts2.getURI());
handler.prepForStatusChange(Events.RECONNECTED);
}
flushAndWaitLong(nc, handler);
assertConnected(nc);
assertEquals(ts.getURI(), nc.getConnectedUrl());
standardCloseConnection(nc);
}
}
@Test
public void testReconnectToSecondServerFromInfo() throws Exception {
NatsConnection nc;
TestHandler handler = new TestHandler();
try (NatsTestServer ts = new NatsTestServer()) {
String striped = ts.getURI().substring("nats://".length()); // info doesn't have protocol
String customInfo = "{\"server_id\":\"myid\",\"connect_urls\": [\""+striped+"\"]}";
try (NatsServerProtocolMock ts2 = new NatsServerProtocolMock(null, customInfo)) {
Options options = new Options.Builder().
server(ts2.getURI()).
connectionListener(handler).
maxReconnects(-1).
connectionTimeout(Duration.ofSeconds(5)).
reconnectWait(Duration.ofSeconds(1)).
build();
nc = (NatsConnection) standardConnection(options);
assertEquals(nc.getConnectedUrl(), ts2.getURI());
handler.prepForStatusChange(Events.RECONNECTED);
}
flushAndWaitLong(nc, handler);
assertConnected(nc);
assertTrue(ts.getURI().endsWith(nc.getConnectedUrl()));
standardCloseConnection(nc);
}
}
@Test
public void testOverflowReconnectBuffer() {
assertThrows(IllegalStateException.class, () -> {
Connection nc;
TestHandler handler = new TestHandler();
try (NatsTestServer ts = new NatsTestServer()) {
Options options = new Options.Builder().
server(ts.getURI()).
maxReconnects(-1).
connectionListener(handler).
reconnectBufferSize(4*512).
reconnectWait(Duration.ofSeconds(480)).
build();
nc = standardConnection(options);
handler.prepForStatusChange(Events.DISCONNECTED);
}
flushAndWaitLong(nc, handler);
checkReconnectingStatus(nc);
for (int i=0;i<20;i++) {
nc.publish("test", new byte[512]);// Should blow up by the 5th message
}
});
}
@Test
public void testInfiniteReconnectBuffer() throws Exception {
Connection nc;
TestHandler handler = new TestHandler();
handler.setPrintExceptions(false);
try (NatsTestServer ts = new NatsTestServer()) {
Options options = new Options.Builder().
server(ts.getURI()).
maxReconnects(5).
connectionListener(handler).
reconnectBufferSize(-1).
reconnectWait(Duration.ofSeconds(30)).
build();
nc = standardConnection(options);
handler.prepForStatusChange(Events.DISCONNECTED);
}
flushAndWaitLong(nc, handler);
checkReconnectingStatus(nc);
byte[] payload = new byte[1024];
for (int i=0;i<1_000;i++) {
nc.publish("test", payload);
}
standardCloseConnection(nc);
}
@Test
public void testReconnectDropOnLineFeed() throws Exception {
NatsConnection nc;
TestHandler handler = new TestHandler();
int port = NatsTestServer.nextPort();
Duration reconnectWait = Duration.ofMillis(100); // thrash
int thrashCount = 5;
CompletableFuture<Boolean> gotSub = new CompletableFuture<>();
AtomicReference<CompletableFuture<Boolean>> subRef = new AtomicReference<>(gotSub);
CompletableFuture<Boolean> sendMsg = new CompletableFuture<>();
AtomicReference<CompletableFuture<Boolean>> sendRef = new AtomicReference<>(sendMsg);
NatsServerProtocolMock.Customizer receiveMessageCustomizer = (ts, r,w) -> {
String subLine;
System.out.println("*** Mock Server @" + ts.getPort() + " waiting for SUB ...");
try {
subLine = r.readLine();
} catch(Exception e) {
subRef.get().cancel(true);
return;
}
if (subLine.startsWith("SUB")) {
subRef.get().complete(Boolean.TRUE);
}
try {
sendRef.get().get();
} catch (Exception e) {
//keep going
}
w.write("MSG\r"); // Drop the line feed
w.flush();
};
try (NatsServerProtocolMock ts = new NatsServerProtocolMock(receiveMessageCustomizer, port, true)) {
Options options = new Options.Builder().
server(ts.getURI()).
maxReconnects(-1).
reconnectWait(reconnectWait).
connectionListener(handler).
build();
port = ts.getPort();
nc = (NatsConnection) Nats.connect(options);
assertEquals(Connection.Status.CONNECTED, nc.getStatus(), "Connected Status");
nc.subscribe("test");
subRef.get().get();
handler.prepForStatusChange(Events.DISCONNECTED);
sendRef.get().complete(true);
flushAndWaitLong(nc, handler); // mock server will close so we do this inside the curly
}
// Thrash in and out of connect status
// server starts thrashCount times so we should succeed thrashCount x
for (int i=0;i<thrashCount;i++) {
checkReconnectingStatus(nc);
// connect good then bad
handler.prepForStatusChange(Events.RESUBSCRIBED);
try (NatsTestServer ts = new NatsTestServer(port, false)) {
standardConnectionWait(nc, handler);
handler.prepForStatusChange(Events.DISCONNECTED);
}
flushAndWaitLong(nc, handler); // nats won't close until we tell it, so put this outside the curly
checkReconnectingStatus(nc);
gotSub = new CompletableFuture<>();
subRef.set(gotSub);
sendMsg = new CompletableFuture<>();
sendRef.set(sendMsg);
handler.prepForStatusChange(Events.RESUBSCRIBED);
try (NatsServerProtocolMock ts = new NatsServerProtocolMock(receiveMessageCustomizer, port, true)) {
standardConnectionWait(nc, handler);
subRef.get().get();
handler.prepForStatusChange(Events.DISCONNECTED);
sendRef.get().complete(true);
flushAndWaitLong(nc, handler); // mock server will close so we do this inside the curly
}
}
assertEquals(2 * thrashCount, nc.getNatsStatistics().getReconnects(), "reconnect count");
standardCloseConnection(nc);
}
@Test
public void testReconnectNoIPTLSConnection() throws Exception {
NatsConnection nc;
TestHandler handler = new TestHandler();
int tsPort = NatsTestServer.nextPort();
int ts2Port = NatsTestServer.nextPort();
int tsCPort = NatsTestServer.nextPort();
int ts2CPort = NatsTestServer.nextPort();
String[] tsInserts = {
"cluster {",
"name: testClusterName",
"listen: localhost:" + tsCPort,
"routes = [",
"nats-route://localhost:" + ts2CPort,
"]",
"}"
};
String[] ts2Inserts = {
"cluster {",
"name: testClusterName",
"listen: localhost:" + ts2CPort,
"routes = [",
"nats-route://127.0.0.1:" + tsCPort,
"]",
"}"
};
// Regular tls for first connection, then no ip for second
try ( NatsTestServer ts = new NatsTestServer("src/test/resources/tls_noip.conf", tsInserts, tsPort, false);
NatsTestServer ts2 = new NatsTestServer("src/test/resources/tls_noip.conf", ts2Inserts, ts2Port, false) ) {
TestSSLUtils.setKeystoreSystemParameters();
Options options = new Options.Builder().
server(ts.getURI()).
secure().
connectionListener(handler).
maxReconnects(20). // we get multiples for some, so need enough
reconnectWait(Duration.ofMillis(100)).
connectionTimeout(Duration.ofSeconds(5)).
noRandomize().
build();
handler.prepForStatusChange(Events.DISCOVERED_SERVERS);
nc = (NatsConnection) standardConnection(options);
assertEquals(nc.getConnectedUrl(), ts.getURI());
flushAndWaitLong(nc, handler); // make sure we get the new server via info
handler.prepForStatusChange(Events.RECONNECTED);
ts.close();
flushAndWaitLong(nc, handler);
assertConnected(nc);
URI uri = options.createURIForServer(nc.getConnectedUrl());
assertEquals(ts2.getPort(), uri.getPort()); // full uri will have some ip address, just check port
standardCloseConnection(nc);
}
}
@Test
public void testURISchemeNoIPTLSConnection() throws Exception {
//System.setProperty("javax.net.debug", "all");
TestSSLUtils.setKeystoreSystemParameters();
try (NatsTestServer ts = new NatsTestServer("src/test/resources/tls_noip.conf", false)) {
Options options = new Options.Builder().
server("tls://localhost:"+ts.getPort()).
maxReconnects(0).
build();
assertCanConnect(options);
}
}
@Test
public void testURISchemeNoIPOpenTLSConnection() throws Exception {
//System.setProperty("javax.net.debug", "all");
TestSSLUtils.setKeystoreSystemParameters();
try (NatsTestServer ts = new NatsTestServer("src/test/resources/tls_noip.conf", false)) {
Options options = new Options.Builder().
server("opentls://localhost:"+ts.getPort()).
maxReconnects(0).
build();
assertCanConnect(options);
}
}
@Test
public void testWriterFilterTiming() throws Exception {
NatsConnection nc;
TestHandler handler = new TestHandler();
int port = NatsTestServer.nextPort();
try (NatsTestServer ts = new NatsTestServer(port, false)) {
Options options = new Options.Builder().
server(ts.getURI()).
noReconnect().
connectionListener(handler).
build();
nc = (NatsConnection) Nats.connect(options);
assertConnected(nc);
for (int i = 0; i < 100; i++) {
// stop and start in a loop without waiting for the future to complete
nc.getWriter().stop();
nc.getWriter().start(nc.getDataPortFuture());
}
nc.getWriter().stop();
sleep(1000);
// Should have thrown an exception if #203 isn't fixed
standardCloseConnection(nc);
}
}
private static class TestReconnecWaitHandler implements ConnectionListener {
int disconnectCount = 0;
public synchronized int getDisconnectCount() {
return disconnectCount;
}
private synchronized void incrementDisconnectedCount() {
disconnectCount++;
}
@Override
public void connectionEvent(Connection conn, Events type) {
if (type == Events.DISCONNECTED) {
// disconnect is called after every failed reconnect attempt.
incrementDisconnectedCount();
}
}
}
@Test
public void testReconnectWait() throws IOException, InterruptedException {
TestReconnecWaitHandler trwh = new TestReconnecWaitHandler();
int port = NatsTestServer.nextPort();
Options options = new Options.Builder().
server("nats://localhost:"+port).
maxReconnects(-1).
connectionTimeout(Duration.ofSeconds(1)).
reconnectWait(Duration.ofMillis(250)).
connectionListener(trwh).
build();
NatsTestServer ts = new NatsTestServer(port, false);
Connection c = Nats.connect(options);
ts.close();
sleep(250);
assertTrue(trwh.getDisconnectCount() < 3, "disconnectCount");
c.close();
}
} | src/test/java/io/nats/client/impl/ReconnectTests.java | // Copyright 2015-2018 The NATS Authors
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at:
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package io.nats.client.impl;
import io.nats.client.*;
import io.nats.client.ConnectionListener.Events;
import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
import static io.nats.client.utils.TestBase.*;
import static org.junit.jupiter.api.Assertions.*;
public class ReconnectTests {
void checkReconnectingStatus(Connection nc) {
Connection.Status status = nc.getStatus();
assertTrue(Connection.Status.RECONNECTING == status ||
Connection.Status.DISCONNECTED == status, "Reconnecting status");
}
@Test
public void testSimpleReconnect() throws Exception { //Includes test for subscriptions and dispatchers across reconnect
NatsConnection nc;
TestHandler handler = new TestHandler();
int port = NatsTestServer.nextPort();
Subscription sub;
long start;
long end;
handler.setPrintExceptions(true);
try (NatsTestServer ts = new NatsTestServer(port, false)) {
Options options = new Options.Builder().
server(ts.getURI()).
maxReconnects(-1).
reconnectWait(Duration.ofMillis(1000)).
connectionListener(handler).
build();
port = ts.getPort();
nc = (NatsConnection)standardConnection(options);
sub = nc.subscribe("subsubject");
final NatsConnection nnc = nc; // final for the lambda
Dispatcher d = nc.createDispatcher((msg) -> nnc.publish(msg.getReplyTo(), msg.getData()) );
d.subscribe("dispatchSubject");
flushConnection(nc);
Future<Message> inc = nc.request("dispatchSubject", "test".getBytes(StandardCharsets.UTF_8));
Message msg = inc.get();
assertNotNull(msg);
nc.publish("subsubject", null);
msg = sub.nextMessage(Duration.ofMillis(100));
assertNotNull(msg);
handler.prepForStatusChange(Events.DISCONNECTED);
start = System.nanoTime();
}
flushAndWaitLong(nc, handler);
checkReconnectingStatus(nc);
handler.prepForStatusChange(Events.RESUBSCRIBED);
try (NatsTestServer ts = new NatsTestServer(port, false)) {
standardConnectionWait(nc, handler);
end = System.nanoTime();
assertTrue(1_000_000 * (end-start) > 1000, "reconnect wait");
// Make sure dispatcher and subscription are still there
Future<Message> inc = nc.request("dispatchSubject", "test".getBytes(StandardCharsets.UTF_8));
Message msg = inc.get(500, TimeUnit.MILLISECONDS);
assertNotNull(msg);
// make sure the subscription survived
nc.publish("subsubject", null);
msg = sub.nextMessage(Duration.ofMillis(100));
assertNotNull(msg);
}
assertEquals(1, nc.getNatsStatistics().getReconnects(), "reconnect count");
assertTrue(nc.getNatsStatistics().getExceptions() > 0, "exception count");
standardCloseConnection(nc);
}
@Test
public void testSubscribeDuringReconnect() throws Exception {
NatsConnection nc;
TestHandler handler = new TestHandler();
int port;
Subscription sub;
try (NatsTestServer ts = new NatsTestServer()) {
Options options = new Options.Builder().
server(ts.getURI()).
maxReconnects(-1).
reconnectWait(Duration.ofMillis(20)).
connectionListener(handler).
build();
port = ts.getPort();
nc = (NatsConnection) standardConnection(options);
handler.prepForStatusChange(Events.DISCONNECTED);
}
flushAndWaitLong(nc, handler);
checkReconnectingStatus(nc);
sub = nc.subscribe("subsubject");
final NatsConnection nnc = nc;
Dispatcher d = nc.createDispatcher((msg) -> nnc.publish(msg.getReplyTo(), msg.getData()));
d.subscribe("dispatchSubject");
handler.prepForStatusChange(Events.RECONNECTED);
try (NatsTestServer ts = new NatsTestServer(port, false)) {
standardConnectionWait(nc, handler);
// Make sure dispatcher and subscription are still there
Future<Message> inc = nc.request("dispatchSubject", "test".getBytes(StandardCharsets.UTF_8));
Message msg = inc.get();
assertNotNull(msg);
// make sure the subscription survived
nc.publish("subsubject", null);
msg = sub.nextMessage(Duration.ofMillis(100));
assertNotNull(msg);
}
assertEquals(1, nc.getNatsStatistics().getReconnects(), "reconnect count");
assertTrue(nc.getNatsStatistics().getExceptions() > 0, "exception count");
standardCloseConnection(nc);
}
@Test
public void testReconnectBuffer() throws Exception {
NatsConnection nc;
TestHandler handler = new TestHandler();
int port = NatsTestServer.nextPort();
Subscription sub;
long start;
long end;
String[] customArgs = {"--user","stephen","--pass","password"};
handler.setPrintExceptions(true);
try (NatsTestServer ts = new NatsTestServer(customArgs, port, false)) {
Options options = new Options.Builder().
server(ts.getURI()).
maxReconnects(-1).
userInfo("stephen".toCharArray(), "password".toCharArray()).
reconnectWait(Duration.ofMillis(1000)).
connectionListener(handler).
build();
nc = (NatsConnection) standardConnection(options);
sub = nc.subscribe("subsubject");
final NatsConnection nnc = nc;
Dispatcher d = nc.createDispatcher((msg) -> nnc.publish(msg.getReplyTo(), msg.getData()));
d.subscribe("dispatchSubject");
nc.flush(Duration.ofMillis(1000));
Future<Message> inc = nc.request("dispatchSubject", "test".getBytes(StandardCharsets.UTF_8));
Message msg = inc.get();
assertNotNull(msg);
nc.publish("subsubject", null);
msg = sub.nextMessage(Duration.ofMillis(100));
assertNotNull(msg);
handler.prepForStatusChange(Events.DISCONNECTED);
start = System.nanoTime();
}
flushAndWaitLong(nc, handler);
checkReconnectingStatus(nc);
// Send a message to the dispatcher and one to the subscriber
// These should be sent on reconnect
Future<Message> inc = nc.request("dispatchSubject", "test".getBytes(StandardCharsets.UTF_8));
nc.publish("subsubject", null);
nc.publish("subsubject", null);
handler.prepForStatusChange(Events.RESUBSCRIBED);
try (NatsTestServer ts = new NatsTestServer(customArgs, port, false)) {
standardConnectionWait(nc, handler);
end = System.nanoTime();
assertTrue(1_000_000 * (end-start) > 1000, "reconnect wait");
// Check the message we sent to dispatcher
Message msg = inc.get(500, TimeUnit.MILLISECONDS);
assertNotNull(msg);
// Check the two we sent to subscriber
msg = sub.nextMessage(Duration.ofMillis(500));
assertNotNull(msg);
msg = sub.nextMessage(Duration.ofMillis(500));
assertNotNull(msg);
}
assertEquals(1, nc.getNatsStatistics().getReconnects(), "reconnect count");
assertTrue(nc.getNatsStatistics().getExceptions() > 0, "exception count");
standardCloseConnection(nc);
}
@Test
public void testMaxReconnects() throws Exception {
Connection nc;
TestHandler handler = new TestHandler();
int port = NatsTestServer.nextPort();
try (NatsTestServer ts = new NatsTestServer(port, false)) {
Options options = new Options.Builder().
server(ts.getURI()).
maxReconnects(1).
connectionListener(handler).
reconnectWait(Duration.ofMillis(10)).
build();
nc = standardConnection(options);
handler.prepForStatusChange(Events.CLOSED);
}
flushAndWaitLong(nc, handler);
assertSame(Connection.Status.CLOSED, nc.getStatus(), "Closed Status");
standardCloseConnection(nc);
}
@Test
public void testReconnectToSecondServer() throws Exception {
NatsConnection nc;
TestHandler handler = new TestHandler();
try (NatsTestServer ts = new NatsTestServer()) {
try (NatsTestServer ts2 = new NatsTestServer()) {
Options options = new Options.Builder().
server(ts2.getURI()).
server(ts.getURI()).
noRandomize().
connectionListener(handler).
maxReconnects(-1).
build();
nc = (NatsConnection) standardConnection(options);
assertEquals(ts2.getURI(), nc.getConnectedUrl());
handler.prepForStatusChange(Events.RECONNECTED);
}
flushAndWaitLong(nc, handler);
assertConnected(nc);
assertEquals(ts.getURI(), nc.getConnectedUrl());
standardCloseConnection(nc);
}
}
@Test
public void testNoRandomizeReconnectToSecondServer() throws Exception {
NatsConnection nc;
TestHandler handler = new TestHandler();
try (NatsTestServer ts = new NatsTestServer()) {
try (NatsTestServer ts2 = new NatsTestServer()) {
Options options = new Options.Builder().
server(ts2.getURI()).
server(ts.getURI()).
connectionListener(handler).
maxReconnects(-1).
noRandomize().
build();
nc = (NatsConnection) standardConnection(options);
assertEquals(nc.getConnectedUrl(), ts2.getURI());
handler.prepForStatusChange(Events.RECONNECTED);
}
flushAndWaitLong(nc, handler);
assertConnected(nc);
assertEquals(ts.getURI(), nc.getConnectedUrl());
standardCloseConnection(nc);
}
}
@Test
public void testReconnectToSecondServerFromInfo() throws Exception {
NatsConnection nc;
TestHandler handler = new TestHandler();
try (NatsTestServer ts = new NatsTestServer()) {
String striped = ts.getURI().substring("nats://".length()); // info doesn't have protocol
String customInfo = "{\"server_id\":\"myid\",\"connect_urls\": [\""+striped+"\"]}";
try (NatsServerProtocolMock ts2 = new NatsServerProtocolMock(null, customInfo)) {
Options options = new Options.Builder().
server(ts2.getURI()).
connectionListener(handler).
maxReconnects(-1).
connectionTimeout(Duration.ofSeconds(5)).
reconnectWait(Duration.ofSeconds(1)).
build();
nc = (NatsConnection) standardConnection(options);
assertEquals(nc.getConnectedUrl(), ts2.getURI());
handler.prepForStatusChange(Events.RECONNECTED);
}
flushAndWaitLong(nc, handler);
assertConnected(nc);
assertTrue(ts.getURI().endsWith(nc.getConnectedUrl()));
standardCloseConnection(nc);
}
}
@Test
public void testOverflowReconnectBuffer() {
assertThrows(IllegalStateException.class, () -> {
Connection nc;
TestHandler handler = new TestHandler();
try (NatsTestServer ts = new NatsTestServer()) {
Options options = new Options.Builder().
server(ts.getURI()).
maxReconnects(-1).
connectionListener(handler).
reconnectBufferSize(4*512).
reconnectWait(Duration.ofSeconds(480)).
build();
nc = standardConnection(options);
handler.prepForStatusChange(Events.DISCONNECTED);
}
flushAndWaitLong(nc, handler);
checkReconnectingStatus(nc);
for (int i=0;i<20;i++) {
nc.publish("test", new byte[512]);// Should blow up by the 5th message
}
});
}
@Test
public void testInfiniteReconnectBuffer() throws Exception {
Connection nc;
TestHandler handler = new TestHandler();
handler.setPrintExceptions(false);
try (NatsTestServer ts = new NatsTestServer()) {
Options options = new Options.Builder().
server(ts.getURI()).
maxReconnects(5).
connectionListener(handler).
reconnectBufferSize(-1).
reconnectWait(Duration.ofSeconds(30)).
build();
nc = standardConnection(options);
handler.prepForStatusChange(Events.DISCONNECTED);
}
flushAndWaitLong(nc, handler);
checkReconnectingStatus(nc);
byte[] payload = new byte[1024];
for (int i=0;i<1_000;i++) {
nc.publish("test", payload);
}
standardCloseConnection(nc);
}
@Test
public void testReconnectDropOnLineFeed() throws Exception {
NatsConnection nc;
TestHandler handler = new TestHandler();
int port = NatsTestServer.nextPort();
Duration reconnectWait = Duration.ofMillis(100); // thrash
int thrashCount = 5;
CompletableFuture<Boolean> gotSub = new CompletableFuture<>();
AtomicReference<CompletableFuture<Boolean>> subRef = new AtomicReference<>(gotSub);
CompletableFuture<Boolean> sendMsg = new CompletableFuture<>();
AtomicReference<CompletableFuture<Boolean>> sendRef = new AtomicReference<>(sendMsg);
NatsServerProtocolMock.Customizer receiveMessageCustomizer = (ts, r,w) -> {
String subLine;
System.out.println("*** Mock Server @" + ts.getPort() + " waiting for SUB ...");
try {
subLine = r.readLine();
} catch(Exception e) {
subRef.get().cancel(true);
return;
}
if (subLine.startsWith("SUB")) {
subRef.get().complete(Boolean.TRUE);
}
try {
sendRef.get().get();
} catch (Exception e) {
//keep going
}
w.write("MSG\r"); // Drop the line feed
w.flush();
};
try (NatsServerProtocolMock ts = new NatsServerProtocolMock(receiveMessageCustomizer, port, true)) {
Options options = new Options.Builder().
server(ts.getURI()).
maxReconnects(-1).
reconnectWait(reconnectWait).
connectionListener(handler).
build();
port = ts.getPort();
nc = (NatsConnection) Nats.connect(options);
assertEquals(Connection.Status.CONNECTED, nc.getStatus(), "Connected Status");
nc.subscribe("test");
subRef.get().get();
handler.prepForStatusChange(Events.DISCONNECTED);
sendRef.get().complete(true);
flushAndWaitLong(nc, handler); // mock server will close so we do this inside the curly
}
// Thrash in and out of connect status
// server starts thrashCount times so we should succeed thrashCount x
for (int i=0;i<thrashCount;i++) {
checkReconnectingStatus(nc);
// connect good then bad
handler.prepForStatusChange(Events.RESUBSCRIBED);
try (NatsTestServer ts = new NatsTestServer(port, false)) {
standardConnectionWait(nc, handler);
handler.prepForStatusChange(Events.DISCONNECTED);
}
flushAndWaitLong(nc, handler); // nats won't close until we tell it, so put this outside the curly
checkReconnectingStatus(nc);
gotSub = new CompletableFuture<>();
subRef.set(gotSub);
sendMsg = new CompletableFuture<>();
sendRef.set(sendMsg);
handler.prepForStatusChange(Events.RESUBSCRIBED);
try (NatsServerProtocolMock ts = new NatsServerProtocolMock(receiveMessageCustomizer, port, true)) {
standardConnectionWait(nc, handler);
subRef.get().get();
handler.prepForStatusChange(Events.DISCONNECTED);
sendRef.get().complete(true);
flushAndWaitLong(nc, handler); // mock server will close so we do this inside the curly
}
}
assertEquals(2 * thrashCount, nc.getNatsStatistics().getReconnects(), "reconnect count");
standardCloseConnection(nc);
}
@Test
public void testReconnectNoIPTLSConnection() throws Exception {
NatsConnection nc;
TestHandler handler = new TestHandler();
int tsPort = NatsTestServer.nextPort();
int ts2Port = NatsTestServer.nextPort();
int tsCPort = NatsTestServer.nextPort();
int ts2CPort = NatsTestServer.nextPort();
String[] tsInserts = {
"",
"cluster {",
"listen: localhost:" + tsCPort,
"routes = [",
"nats-route://localhost:" + ts2CPort,
"]",
"}"
};
String[] ts2Inserts = {
"cluster {",
"listen: localhost:" + ts2CPort,
"routes = [",
"nats-route://127.0.0.1:" + tsCPort,
"]",
"}"
};
// Regular tls for first connection, then no ip for second
try ( NatsTestServer ts = new NatsTestServer("src/test/resources/tls_noip.conf", tsInserts, tsPort, false);
NatsTestServer ts2 = new NatsTestServer("src/test/resources/tls_noip.conf", ts2Inserts, ts2Port, false) ) {
TestSSLUtils.setKeystoreSystemParameters();
Options options = new Options.Builder().
server(ts.getURI()).
secure().
connectionListener(handler).
maxReconnects(20). // we get multiples for some, so need enough
reconnectWait(Duration.ofMillis(100)).
connectionTimeout(Duration.ofSeconds(5)).
noRandomize().
build();
handler.prepForStatusChange(Events.DISCOVERED_SERVERS);
nc = (NatsConnection) standardConnection(options);
assertEquals(nc.getConnectedUrl(), ts.getURI());
flushAndWaitLong(nc, handler); // make sure we get the new server via info
handler.prepForStatusChange(Events.RECONNECTED);
ts.close();
flushAndWait(nc, handler, VERY_LONG_TIMEOUT_MS, VERY_LONG_TIMEOUT_MS);
assertConnected(nc);
URI uri = options.createURIForServer(nc.getConnectedUrl());
assertEquals(ts2.getPort(), uri.getPort()); // full uri will have some ip address, just check port
standardCloseConnection(nc);
}
}
@Test
public void testURISchemeNoIPTLSConnection() throws Exception {
//System.setProperty("javax.net.debug", "all");
TestSSLUtils.setKeystoreSystemParameters();
try (NatsTestServer ts = new NatsTestServer("src/test/resources/tls_noip.conf", false)) {
Options options = new Options.Builder().
server("tls://localhost:"+ts.getPort()).
maxReconnects(0).
build();
assertCanConnect(options);
}
}
@Test
public void testURISchemeNoIPOpenTLSConnection() throws Exception {
//System.setProperty("javax.net.debug", "all");
TestSSLUtils.setKeystoreSystemParameters();
try (NatsTestServer ts = new NatsTestServer("src/test/resources/tls_noip.conf", false)) {
Options options = new Options.Builder().
server("opentls://localhost:"+ts.getPort()).
maxReconnects(0).
build();
assertCanConnect(options);
}
}
@Test
public void testWriterFilterTiming() throws Exception {
NatsConnection nc;
TestHandler handler = new TestHandler();
int port = NatsTestServer.nextPort();
try (NatsTestServer ts = new NatsTestServer(port, false)) {
Options options = new Options.Builder().
server(ts.getURI()).
noReconnect().
connectionListener(handler).
build();
nc = (NatsConnection) Nats.connect(options);
assertConnected(nc);
for (int i = 0; i < 100; i++) {
// stop and start in a loop without waiting for the future to complete
nc.getWriter().stop();
nc.getWriter().start(nc.getDataPortFuture());
}
nc.getWriter().stop();
sleep(1000);
// Should have thrown an exception if #203 isn't fixed
standardCloseConnection(nc);
}
}
private static class TestReconnecWaitHandler implements ConnectionListener {
int disconnectCount = 0;
public synchronized int getDisconnectCount() {
return disconnectCount;
}
private synchronized void incrementDisconnectedCount() {
disconnectCount++;
}
@Override
public void connectionEvent(Connection conn, Events type) {
if (type == Events.DISCONNECTED) {
// disconnect is called after every failed reconnect attempt.
incrementDisconnectedCount();
}
}
}
@Test
public void testReconnectWait() throws IOException, InterruptedException {
TestReconnecWaitHandler trwh = new TestReconnecWaitHandler();
int port = NatsTestServer.nextPort();
Options options = new Options.Builder().
server("nats://localhost:"+port).
maxReconnects(-1).
connectionTimeout(Duration.ofSeconds(1)).
reconnectWait(Duration.ofMillis(250)).
connectionListener(trwh).
build();
NatsTestServer ts = new NatsTestServer(port, false);
Connection c = Nats.connect(options);
ts.close();
sleep(250);
assertTrue(trwh.getDisconnectCount() < 3, "disconnectCount");
c.close();
}
} | cluster name required in test config (#499)
| src/test/java/io/nats/client/impl/ReconnectTests.java | cluster name required in test config (#499) | <ide><path>rc/test/java/io/nats/client/impl/ReconnectTests.java
<ide> int ts2CPort = NatsTestServer.nextPort();
<ide>
<ide> String[] tsInserts = {
<del> "",
<ide> "cluster {",
<add> "name: testClusterName",
<ide> "listen: localhost:" + tsCPort,
<ide> "routes = [",
<ide> "nats-route://localhost:" + ts2CPort,
<ide> };
<ide> String[] ts2Inserts = {
<ide> "cluster {",
<add> "name: testClusterName",
<ide> "listen: localhost:" + ts2CPort,
<ide> "routes = [",
<ide> "nats-route://127.0.0.1:" + tsCPort,
<ide> handler.prepForStatusChange(Events.RECONNECTED);
<ide>
<ide> ts.close();
<del> flushAndWait(nc, handler, VERY_LONG_TIMEOUT_MS, VERY_LONG_TIMEOUT_MS);
<add> flushAndWaitLong(nc, handler);
<ide> assertConnected(nc);
<ide>
<ide> URI uri = options.createURIForServer(nc.getConnectedUrl()); |
|
Java | apache-2.0 | a3d1901f62b3b799e9a38bb91ada766243f7e1de | 0 | AndroidX/androidx,AndroidX/androidx,androidx/androidx,androidx/androidx,AndroidX/androidx,androidx/androidx,AndroidX/androidx,androidx/androidx,androidx/androidx,androidx/androidx,AndroidX/androidx,AndroidX/androidx,androidx/androidx,androidx/androidx,androidx/androidx,AndroidX/androidx,AndroidX/androidx,AndroidX/androidx,AndroidX/androidx,androidx/androidx | /*
* Copyright 2018 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.slice.render;
import static android.os.Build.VERSION.SDK_INT;
import static androidx.slice.render.SliceRenderer.SCREENSHOT_DIR;
import static org.junit.Assert.assertTrue;
import android.Manifest;
import android.os.Build;
import androidx.test.ext.junit.runners.AndroidJUnit4;
import androidx.test.filters.LargeTest;
import androidx.test.filters.SdkSuppress;
import androidx.test.platform.app.InstrumentationRegistry;
import androidx.test.rule.ActivityTestRule;
import androidx.test.rule.GrantPermissionRule;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.concurrent.TimeUnit;
@LargeTest
@RunWith(AndroidJUnit4.class)
@SdkSuppress(minSdkVersion = 19)
public class RenderTest {
@Rule
public GrantPermissionRule mRuntimePermissionRule =
GrantPermissionRule.grant(Manifest.permission.WRITE_EXTERNAL_STORAGE);
@Rule
public ActivityTestRule<SliceRenderActivity> mActivityRule =
new ActivityTestRule<>(SliceRenderActivity.class);
@Test
public void testRender() throws Exception {
if (Build.VERSION.SDK_INT == Build.VERSION_CODES.O && Build.MODEL.contains("Nexus 6P")) {
// Known issue b/157980437, disabling the test on this specific combination
return;
}
final SliceRenderActivity activity = mActivityRule.getActivity();
final SliceRenderer[] renderer = new SliceRenderer[1];
InstrumentationRegistry.getInstrumentation().runOnMainSync(new Runnable() {
@Override
public void run() {
renderer[0] = new SliceRenderer(activity);
}
});
assertTrue(renderer[0].doRender(30000, TimeUnit.MILLISECONDS));
String path = renderer[0].getScreenshotDirectory().getAbsolutePath();
if (SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
InstrumentationRegistry.getInstrumentation().getUiAutomation().executeShellCommand(
"mv " + path + " " + "/sdcard/");
} else {
deleteDir(new File("/sdcard/" + SCREENSHOT_DIR));
copyDirectory(new File(path), new File("/sdcard/" + SCREENSHOT_DIR));
}
}
public static void copyDirectory(File sourceLocation, File targetLocation) throws Exception {
if (sourceLocation.isDirectory()) {
if (!targetLocation.exists()) {
assertTrue(targetLocation.mkdirs());
}
String[] children = sourceLocation.list();
for (int i = 0; i < children.length; i++) {
copyDirectory(new File(sourceLocation, children[i]), new File(
targetLocation, children[i]));
}
} else {
copyFile(sourceLocation, targetLocation);
}
}
public static void copyFile(File sourceLocation, File targetLocation) throws Exception {
InputStream in = new FileInputStream(sourceLocation);
OutputStream out = new FileOutputStream(targetLocation);
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
in.close();
out.close();
}
static void deleteDir(File file) {
File[] contents = file.listFiles();
if (contents != null) {
for (File f : contents) {
deleteDir(f);
}
}
file.delete();
}
}
| slices/view/src/androidTest/java/androidx/slice/render/RenderTest.java | /*
* Copyright 2018 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.slice.render;
import static android.os.Build.VERSION.SDK_INT;
import static androidx.slice.render.SliceRenderer.SCREENSHOT_DIR;
import static org.junit.Assert.assertTrue;
import android.Manifest;
import android.os.Build;
import androidx.test.ext.junit.runners.AndroidJUnit4;
import androidx.test.filters.LargeTest;
import androidx.test.filters.SdkSuppress;
import androidx.test.platform.app.InstrumentationRegistry;
import androidx.test.rule.ActivityTestRule;
import androidx.test.rule.GrantPermissionRule;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.concurrent.TimeUnit;
@LargeTest
@RunWith(AndroidJUnit4.class)
@SdkSuppress(minSdkVersion = 19)
public class RenderTest {
@Rule
public GrantPermissionRule mRuntimePermissionRule =
GrantPermissionRule.grant(Manifest.permission.WRITE_EXTERNAL_STORAGE);
@Rule
public ActivityTestRule<SliceRenderActivity> mActivityRule =
new ActivityTestRule<>(SliceRenderActivity.class);
@Test
public void testRender() throws Exception {
final SliceRenderActivity activity = mActivityRule.getActivity();
final SliceRenderer[] renderer = new SliceRenderer[1];
InstrumentationRegistry.getInstrumentation().runOnMainSync(new Runnable() {
@Override
public void run() {
renderer[0] = new SliceRenderer(activity);
}
});
assertTrue(renderer[0].doRender(30000, TimeUnit.MILLISECONDS));
String path = renderer[0].getScreenshotDirectory().getAbsolutePath();
if (SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
InstrumentationRegistry.getInstrumentation().getUiAutomation().executeShellCommand(
"mv " + path + " " + "/sdcard/");
} else {
deleteDir(new File("/sdcard/" + SCREENSHOT_DIR));
copyDirectory(new File(path), new File("/sdcard/" + SCREENSHOT_DIR));
}
}
public static void copyDirectory(File sourceLocation, File targetLocation) throws Exception {
if (sourceLocation.isDirectory()) {
if (!targetLocation.exists()) {
assertTrue(targetLocation.mkdirs());
}
String[] children = sourceLocation.list();
for (int i = 0; i < children.length; i++) {
copyDirectory(new File(sourceLocation, children[i]), new File(
targetLocation, children[i]));
}
} else {
copyFile(sourceLocation, targetLocation);
}
}
public static void copyFile(File sourceLocation, File targetLocation) throws Exception {
InputStream in = new FileInputStream(sourceLocation);
OutputStream out = new FileOutputStream(targetLocation);
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
in.close();
out.close();
}
static void deleteDir(File file) {
File[] contents = file.listFiles();
if (contents != null) {
for (File f : contents) {
deleteDir(f);
}
}
file.delete();
}
}
| disable slice render test on Nexus 6P api 26 because it's failing for no
apparent reason.
Bug: 157980437
Test: The test works locally and slices in sample app can be rendered
properly.
Change-Id: Id891654e6d02ed855e78853e541823af7bfb4a11
| slices/view/src/androidTest/java/androidx/slice/render/RenderTest.java | disable slice render test on Nexus 6P api 26 because it's failing for no apparent reason. | <ide><path>lices/view/src/androidTest/java/androidx/slice/render/RenderTest.java
<ide>
<ide> @Test
<ide> public void testRender() throws Exception {
<add> if (Build.VERSION.SDK_INT == Build.VERSION_CODES.O && Build.MODEL.contains("Nexus 6P")) {
<add> // Known issue b/157980437, disabling the test on this specific combination
<add> return;
<add> }
<ide> final SliceRenderActivity activity = mActivityRule.getActivity();
<ide> final SliceRenderer[] renderer = new SliceRenderer[1];
<ide> InstrumentationRegistry.getInstrumentation().runOnMainSync(new Runnable() { |
|
JavaScript | bsd-2-clause | 5dd48ffdff9a25689491639769fb0f34c9ff1376 | 0 | sethlu/electron-osx-sign,electron-userland/electron-osx-sign | var fs = require('fs')
var path = require('path')
var child = require('child_process')
var series = require('run-series')
function generateAppBasename (opts) {
return path.basename(opts.app, '.app')
}
function generateAppFrameworksPath (opts) {
return path.join(opts.app, 'Contents', 'Frameworks')
}
function generateHelperAppPath (opts, opt, suffix, callback) {
var appFrameworksPath = generateAppFrameworksPath(opts)
var appBasename = generateAppBasename(opts)
if (opts[opt]) {
// Use helper path if specified
if (fs.existsSync(opts['helper-path'])) return opts['helper-path']
else return callback(new Error('Specified Electron Helper not found.'))
} else {
var helperPath
if (fs.existsSync(helperPath = path.join(appFrameworksPath, appBasename + ' Helper' + (suffix || '') + '.app'))) {
// Try to look for helper named after app (assume renamed)
return helperPath
} else if (fs.existsSync(helperPath = path.join(appFrameworksPath,
'Electron Helper' + (suffix || '') + '.app'))) {
// Try to look for helper by default
return helperPath
} else {
// Helper not found
callback(new Error('Electron Helper' + (suffix || '') + ' not found.'))
return null
}
}
}
function generateHelperAppExecutablePath (opts, helperPath, suffix, callback) {
var appBasename = generateAppBasename(opts)
var helperExecutablePath
if (fs.existsSync(helperExecutablePath = path.join(helperPath, 'Contents', 'MacOS', appBasename + ' Helper' + (suffix || '')))) {
// Try to look for helper named after app (assume renamed)
return helperExecutablePath
} else if (fs.existsSync(helperExecutablePath = path.join(helperPath, 'Contents', 'MacOS', 'Electron Helper' + (suffix || '')))) {
// Try to look for helper by default
return helperExecutablePath
} else {
// Helper not found
callback(new Error('Electron Helper' + (suffix || '') + ' executable not found.'))
return null
}
}
function signApplication (opts, callback) {
var operations = []
var appFrameworksPath = generateAppFrameworksPath(opts)
var childPaths
if (opts.platform === 'mas') {
childPaths = [
path.join(appFrameworksPath, 'Electron Framework.framework', 'Libraries', 'libnode.dylib'),
path.join(appFrameworksPath, 'Electron Framework.framework', 'Versions', 'A', 'Electron Framework'),
path.join(appFrameworksPath, 'Electron Framework.framework')
]
} else if (opts.platform === 'darwin') {
childPaths = [
path.join(appFrameworksPath, 'Electron Framework.framework', 'Libraries', 'libnode.dylib'),
path.join(appFrameworksPath, 'Electron Framework.framework', 'Versions', 'A', 'Electron Framework'),
path.join(appFrameworksPath, 'Electron Framework.framework'),
path.join(appFrameworksPath, 'Mantle.framework', 'Versions', 'A', 'Mantle'),
path.join(appFrameworksPath, 'Mantle.framework'),
path.join(appFrameworksPath, 'ReactiveCocoa.framework', 'Versions', 'A', 'ReactiveCocoa'),
path.join(appFrameworksPath, 'ReactiveCocoa.framework'),
path.join(appFrameworksPath, 'Squirrel.framework', 'Versions', 'A', 'Squirrel'),
path.join(appFrameworksPath, 'Squirrel.framework')
]
}
var helperPath = generateHelperAppPath(opts, 'helper-path', null, callback)
if (helperPath) {
var helperExecutablePath = generateHelperAppExecutablePath(opts, helperPath, null, callback)
if (helperExecutablePath) childPaths.unshift(helperExecutablePath, helperPath)
else return callback(new Error('Missing Electron Helper, stopped.'))
}
var helperEHPath = generateHelperAppPath(opts, 'helper-eh-path', ' EH', callback)
if (helperEHPath) {
var helperEHExecutablePath = generateHelperAppExecutablePath(opts, helperEHPath, ' EH', callback)
if (helperEHExecutablePath) childPaths.unshift(helperEHExecutablePath, helperEHPath)
else return callback(new Error('Missing Electron Helper EH, stopped.'))
}
var helperNPPath = generateHelperAppPath(opts, 'helper-np-path', ' NP', callback)
if (helperNPPath) {
var helperNPExecutablePath = generateHelperAppExecutablePath(opts, helperNPPath, ' NP', callback)
if (helperNPExecutablePath) childPaths.unshift(helperNPExecutablePath, helperNPPath)
else return callback(new Error('Missing Electron Helper NP, stopped.'))
}
if (opts.entitlements) {
if (opts.platform === 'mas') {
// Sign with entitlements
childPaths.forEach(function (path) {
operations.push(function (cb) {
child.exec('codesign -f -s "' + opts.identity + '" -fv \ '
+ '--entitlements "' + opts['entitlements-inherit'] + '" \ '
+ '"' + path + '"'
, cb)
})
})
operations.push(function (cb) {
child.exec('codesign -f -s "' + opts.identity + '" -fv \ '
+ '--entitlements "' + opts.entitlements + '" \ '
+ '"' + opts.app + '"'
, cb)
})
} else if (opts.platform === 'darwin') {
// TODO: Signing darwin builds with entitlements
}
} else {
// Otherwise normally
childPaths.forEach(function (path) {
operations.push(function (cb) {
child.exec('codesign -f -s "' + opts.identity + '" -fv \ '
+ '"' + path + '"'
, cb)
})
})
operations.push(function (cb) {
child.exec('codesign -f -s "' + opts.identity + '" -fv \ '
+ '"' + opts.app + '"'
, cb)
})
}
// Lastly verify codesign
operations.push(function (cb) {
child.exec('codesign -v --verbose=4 \ '
+ '"' + opts.app + '"'
, cb)
})
if (opts.entitlements) {
// Check entitlements
operations.push(function (cb) {
child.exec('codesign -d --entitlements - \ '
+ '"' + opts.app + '"'
, function (err, stdout, stderr) {
if (err) return cb(err)
if (!stdout) return cb(new Error('Entitlements failed to be signed.'))
cb()
})
})
}
series(operations, function (err) {
if (err) return callback(err)
callback()
})
}
module.exports = function sign (opts, cb) {
if (!opts.app) return cb(new Error('Path to aplication must be specified.'))
if (!fs.existsSync(opts.app)) return cb(new Error('Application not found.'))
if (!cb) cb = function () {}
// Match platform if none is provided
if (!opts.platform) {
var appFrameworksPath = generateAppFrameworksPath(opts)
if (!fs.existsSync(path.join(appFrameworksPath, 'Mantle.framework'))
&& !fs.existsSync(path.join(appFrameworksPath, 'ReactiveCocoa.framework'))
&& !fs.existsSync(path.join(appFrameworksPath, 'Squirrel.framework'))) {
// These frameworks do not exist in an Mac App Store version
opts.platform = 'mas'
} else {
opts.platform = 'darwin'
}
}
if (opts.platform === 'mas') {
// To sign apps for Mac App Store, an entitlements file is required,
// especially for app sandboxing (as well some other services).
// Fallback entitlements for sandboxing by default:
// Note this may cause troubles while running an signed app due to
// missing keys special to the project.
// Further reading: https://developer.apple.com/library/mac/documentation/Miscellaneous/Reference/EntitlementKeyReference/Chapters/EnablingAppSandbox.html
if (!opts.entitlements) opts.entitlements = path.join(__dirname, 'mas.default.plist')
if (!opts['entitlements-inherit']) opts['entitlements-inherit'] = path.join(__dirname, 'mas.inherit.default.plist')
} else if (opts.platform === 'darwin') {
// Not necessary to have entitlements for non Mac App Store distribution
if (opts.entitlements) return cb(new Error('Unable to sign for darwin platform with entitlements.'))
} else {
return cb(new Error('Only platform darwin and mas are supported.'))
}
series([
function (cb) {
// Checking identity with series for async execution of child process
if (!opts.identity) {
child.exec('security find-identity', function (err, stdout, stderr) {
if (err) return cb(new Error('Error in finding an identity.'))
var lines = stdout.split('\n')
var location
for (var i = 0, l = lines.length; i < l && !opts.identity; i++) {
var line = lines[i]
if (opts.platform === 'mas') {
location = line.indexOf('3rd Party Mac Developer Application')
if (location >= 0) {
opts.identity = line.substring(location, line.length - 1)
break
}
} else if (opts.platform === 'darwin') {
location = line.indexOf('Developer ID Application')
if (location >= 0) {
opts.identity = line.substring(location, line.length - 1)
break
}
}
}
if (!opts.identity) cb(new Error('No identity found for signing.'))
cb()
})
} else cb()
}
], function (err) {
if (err) return cb(err)
return signApplication(opts, cb)
})
}
| index.js | var fs = require('fs')
var path = require('path')
var child = require('child_process')
var series = require('run-series')
function generateAppBasename (opts) {
return path.basename(opts.app, '.app')
}
function generateAppFrameworksPath (opts) {
return path.join(opts.app, 'Contents', 'Frameworks')
}
function generateHelperAppPath (opts, opt, suffix, callback) {
var appFrameworksPath = generateAppFrameworksPath(opts)
var appBasename = generateAppBasename(opts)
if (opts[opt]) {
// Use helper path if specified
if (fs.existsSync(opts['helper-path'])) return opts['helper-path']
else return callback(new Error('Specified Electron Helper not found.'))
} else {
var helperPath
if (fs.existsSync(helperPath = path.join(appFrameworksPath, appBasename + ' Helper' + (suffix || '') + '.app'))) {
// Try to look for helper named after app (assume renamed)
return helperPath
} else if (fs.existsSync(helperPath = path.join(appFrameworksPath,
'Electron Helper' + (suffix || '') + '.app'))) {
// Try to look for helper by default
return helperPath
} else {
// Helper not found
callback(new Error('Electron Helper' + (suffix || '') + ' not found.'))
return null
}
}
}
function generateHelperAppExecutablePath (opts, helperPath, suffix, callback) {
var appBasename = generateAppBasename(opts)
var helperExecutablePath
if (fs.existsSync(helperExecutablePath = path.join(helperPath, 'Contents', 'MacOS', appBasename + ' Helper' + (suffix || '')))) {
// Try to look for helper named after app (assume renamed)
return helperExecutablePath
} else if (fs.existsSync(helperExecutablePath = path.join(helperPath, 'Contents', 'MacOS', 'Electron Helper' + (suffix || '')))) {
// Try to look for helper by default
return helperExecutablePath
} else {
// Helper not found
callback(new Error('Electron Helper' + (suffix || '') + ' executable not found.'))
return null
}
}
function signApplication (opts, callback) {
var operations = []
var appFrameworksPath = generateAppFrameworksPath(opts)
var childPaths
if (opts.platform === 'mas') {
childPaths = [
path.join(appFrameworksPath, 'Electron Framework.framework', 'Versions', 'A', 'Electron Framework'),
path.join(appFrameworksPath, 'Electron Framework.framework')
]
} else if (opts.platform === 'darwin') {
childPaths = [
path.join(appFrameworksPath, 'Electron Framework.framework', 'Versions', 'A', 'Electron Framework'),
path.join(appFrameworksPath, 'Electron Framework.framework'),
path.join(appFrameworksPath, 'Mantle.framework', 'Versions', 'A', 'Mantle'),
path.join(appFrameworksPath, 'Mantle.framework'),
path.join(appFrameworksPath, 'ReactiveCocoa.framework', 'Versions', 'A', 'ReactiveCocoa'),
path.join(appFrameworksPath, 'ReactiveCocoa.framework'),
path.join(appFrameworksPath, 'Squirrel.framework', 'Versions', 'A', 'Squirrel'),
path.join(appFrameworksPath, 'Squirrel.framework')
]
}
var helperPath = generateHelperAppPath(opts, 'helper-path', null, callback)
if (helperPath) {
var helperExecutablePath = generateHelperAppExecutablePath(opts, helperPath, null, callback)
if (helperExecutablePath) childPaths.unshift(helperExecutablePath, helperPath)
else return callback(new Error('Missing Electron Helper, stopped.'))
}
var helperEHPath = generateHelperAppPath(opts, 'helper-eh-path', ' EH', callback)
if (helperEHPath) {
var helperEHExecutablePath = generateHelperAppExecutablePath(opts, helperEHPath, ' EH', callback)
if (helperEHExecutablePath) childPaths.unshift(helperEHExecutablePath, helperEHPath)
else return callback(new Error('Missing Electron Helper EH, stopped.'))
}
var helperNPPath = generateHelperAppPath(opts, 'helper-np-path', ' NP', callback)
if (helperNPPath) {
var helperNPExecutablePath = generateHelperAppExecutablePath(opts, helperNPPath, ' NP', callback)
if (helperNPExecutablePath) childPaths.unshift(helperNPExecutablePath, helperNPPath)
else return callback(new Error('Missing Electron Helper NP, stopped.'))
}
if (opts.entitlements) {
if (opts.platform === 'mas') {
// Sign with entitlements
childPaths.forEach(function (path) {
operations.push(function (cb) {
child.exec('codesign -f -s "' + opts.identity + '" -fv \ '
+ '--entitlements "' + opts['entitlements-inherit'] + '" \ '
+ '"' + path + '"'
, cb)
})
})
operations.push(function (cb) {
child.exec('codesign -f -s "' + opts.identity + '" -fv \ '
+ '--entitlements "' + opts.entitlements + '" \ '
+ '"' + opts.app + '"'
, cb)
})
} else if (opts.platform === 'darwin') {
// TODO: Signing darwin builds with entitlements
}
} else {
// Otherwise normally
childPaths.forEach(function (path) {
operations.push(function (cb) {
child.exec('codesign -f -s "' + opts.identity + '" -fv \ '
+ '"' + path + '"'
, cb)
})
})
operations.push(function (cb) {
child.exec('codesign -f -s "' + opts.identity + '" -fv \ '
+ '"' + opts.app + '"'
, cb)
})
}
// Lastly verify codesign
operations.push(function (cb) {
child.exec('codesign -v --verbose=4 \ '
+ '"' + opts.app + '"'
, cb)
})
if (opts.entitlements) {
// Check entitlements
operations.push(function (cb) {
child.exec('codesign -d --entitlements - \ '
+ '"' + opts.app + '"'
, function (err, stdout, stderr) {
if (err) return cb(err)
if (!stdout) return cb(new Error('Entitlements failed to be signed.'))
cb()
})
})
}
series(operations, function (err) {
if (err) return callback(err)
callback()
})
}
module.exports = function sign (opts, cb) {
if (!opts.app) return cb(new Error('Path to aplication must be specified.'))
if (!fs.existsSync(opts.app)) return cb(new Error('Application not found.'))
if (!cb) cb = function () {}
// Match platform if none is provided
if (!opts.platform) {
var appFrameworksPath = generateAppFrameworksPath(opts)
if (!fs.existsSync(path.join(appFrameworksPath, 'Mantle.framework'))
&& !fs.existsSync(path.join(appFrameworksPath, 'ReactiveCocoa.framework'))
&& !fs.existsSync(path.join(appFrameworksPath, 'Squirrel.framework'))) {
// These frameworks do not exist in an Mac App Store version
opts.platform = 'mas'
} else {
opts.platform = 'darwin'
}
}
if (opts.platform === 'mas') {
// To sign apps for Mac App Store, an entitlements file is required,
// especially for app sandboxing (as well some other services).
// Fallback entitlements for sandboxing by default:
// Note this may cause troubles while running an signed app due to
// missing keys special to the project.
// Further reading: https://developer.apple.com/library/mac/documentation/Miscellaneous/Reference/EntitlementKeyReference/Chapters/EnablingAppSandbox.html
if (!opts.entitlements) opts.entitlements = path.join(__dirname, 'mas.default.plist')
if (!opts['entitlements-inherit']) opts['entitlements-inherit'] = path.join(__dirname, 'mas.inherit.default.plist')
} else if (opts.platform === 'darwin') {
// Not necessary to have entitlements for non Mac App Store distribution
if (opts.entitlements) return cb(new Error('Unable to sign for darwin platform with entitlements.'))
} else {
return cb(new Error('Only platform darwin and mas are supported.'))
}
series([
function (cb) {
// Checking identity with series for async execution of child process
if (!opts.identity) {
child.exec('security find-identity', function (err, stdout, stderr) {
if (err) return cb(new Error('Error in finding an identity.'))
var lines = stdout.split('\n')
var location
for (var i = 0, l = lines.length; i < l && !opts.identity; i++) {
var line = lines[i]
if (opts.platform === 'mas') {
location = line.indexOf('3rd Party Mac Developer Application')
if (location >= 0) {
opts.identity = line.substring(location, line.length - 1)
break
}
} else if (opts.platform === 'darwin') {
location = line.indexOf('Developer ID Application')
if (location >= 0) {
opts.identity = line.substring(location, line.length - 1)
break
}
}
}
if (!opts.identity) cb(new Error('No identity found for signing.'))
cb()
})
} else cb()
}
], function (err) {
if (err) return cb(err)
return signApplication(opts, cb)
})
}
| Sign libnode.dylib
| index.js | Sign libnode.dylib | <ide><path>ndex.js
<ide> var childPaths
<ide> if (opts.platform === 'mas') {
<ide> childPaths = [
<add> path.join(appFrameworksPath, 'Electron Framework.framework', 'Libraries', 'libnode.dylib'),
<ide> path.join(appFrameworksPath, 'Electron Framework.framework', 'Versions', 'A', 'Electron Framework'),
<ide> path.join(appFrameworksPath, 'Electron Framework.framework')
<ide> ]
<ide> } else if (opts.platform === 'darwin') {
<ide> childPaths = [
<add> path.join(appFrameworksPath, 'Electron Framework.framework', 'Libraries', 'libnode.dylib'),
<ide> path.join(appFrameworksPath, 'Electron Framework.framework', 'Versions', 'A', 'Electron Framework'),
<ide> path.join(appFrameworksPath, 'Electron Framework.framework'),
<ide> path.join(appFrameworksPath, 'Mantle.framework', 'Versions', 'A', 'Mantle'),
<ide> if (!opts.app) return cb(new Error('Path to aplication must be specified.'))
<ide> if (!fs.existsSync(opts.app)) return cb(new Error('Application not found.'))
<ide> if (!cb) cb = function () {}
<del>
<add>
<ide> // Match platform if none is provided
<ide> if (!opts.platform) {
<ide> var appFrameworksPath = generateAppFrameworksPath(opts) |
|
Java | apache-2.0 | e1a3db40cd4ad857f56bd93f9e8aae4aabc6b2cd | 0 | SimonVT/cathode,SimonVT/cathode | /*
* Copyright (C) 2016 Simon Vig Therkildsen
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.simonvt.cathode.ui.show;
import android.app.Activity;
import android.database.Cursor;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.Loader;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;
import butterknife.BindView;
import butterknife.ButterKnife;
import java.util.Locale;
import javax.inject.Inject;
import net.simonvt.cathode.CathodeApp;
import net.simonvt.cathode.R;
import net.simonvt.cathode.api.enumeration.ItemType;
import net.simonvt.cathode.api.enumeration.ShowStatus;
import net.simonvt.cathode.api.util.TraktUtils;
import net.simonvt.cathode.database.SimpleCursor;
import net.simonvt.cathode.database.SimpleCursorLoader;
import net.simonvt.cathode.database.SimpleMergeCursor;
import net.simonvt.cathode.images.ImageType;
import net.simonvt.cathode.images.ImageUri;
import net.simonvt.cathode.jobqueue.Job;
import net.simonvt.cathode.provider.CollectLoader;
import net.simonvt.cathode.provider.DatabaseContract;
import net.simonvt.cathode.provider.DatabaseContract.CommentColumns;
import net.simonvt.cathode.provider.DatabaseContract.EpisodeColumns;
import net.simonvt.cathode.provider.DatabaseContract.HiddenColumns;
import net.simonvt.cathode.provider.DatabaseContract.PersonColumns;
import net.simonvt.cathode.provider.DatabaseContract.RelatedShowsColumns;
import net.simonvt.cathode.provider.DatabaseContract.ShowCastColumns;
import net.simonvt.cathode.provider.DatabaseContract.ShowColumns;
import net.simonvt.cathode.provider.DatabaseContract.ShowGenreColumns;
import net.simonvt.cathode.provider.DatabaseContract.UserColumns;
import net.simonvt.cathode.provider.DatabaseSchematic.Tables;
import net.simonvt.cathode.provider.ProviderSchematic;
import net.simonvt.cathode.provider.ProviderSchematic.Comments;
import net.simonvt.cathode.provider.ProviderSchematic.RelatedShows;
import net.simonvt.cathode.provider.ProviderSchematic.Seasons;
import net.simonvt.cathode.provider.ProviderSchematic.ShowGenres;
import net.simonvt.cathode.provider.ProviderSchematic.Shows;
import net.simonvt.cathode.provider.WatchedLoader;
import net.simonvt.cathode.scheduler.EpisodeTaskScheduler;
import net.simonvt.cathode.scheduler.PersonTaskScheduler;
import net.simonvt.cathode.scheduler.ShowTaskScheduler;
import net.simonvt.cathode.settings.TraktTimestamps;
import net.simonvt.cathode.ui.LibraryType;
import net.simonvt.cathode.ui.NavigationListener;
import net.simonvt.cathode.ui.comments.LinearCommentsAdapter;
import net.simonvt.cathode.ui.dialog.CheckInDialog;
import net.simonvt.cathode.ui.dialog.CheckInDialog.Type;
import net.simonvt.cathode.ui.dialog.RatingDialog;
import net.simonvt.cathode.ui.fragment.RefreshableAppBarFragment;
import net.simonvt.cathode.ui.listener.SeasonClickListener;
import net.simonvt.cathode.ui.lists.ListsDialog;
import net.simonvt.cathode.util.DataHelper;
import net.simonvt.cathode.util.DateUtils;
import net.simonvt.cathode.util.Ids;
import net.simonvt.cathode.util.Intents;
import net.simonvt.cathode.util.SqlColumn;
import net.simonvt.cathode.widget.CircleTransformation;
import net.simonvt.cathode.widget.CircularProgressIndicator;
import net.simonvt.cathode.widget.HiddenPaneLayout;
import net.simonvt.cathode.widget.OverflowView;
import net.simonvt.cathode.widget.RecyclerViewManager;
import net.simonvt.cathode.widget.RemoteImageView;
import net.simonvt.schematic.Cursors;
import timber.log.Timber;
public class ShowFragment extends RefreshableAppBarFragment {
private static final String TAG = "net.simonvt.cathode.ui.show.ShowFragment";
private static final String ARG_SHOWID = "net.simonvt.cathode.ui.show.ShowFragment.showId";
private static final String ARG_TITLE = "net.simonvt.cathode.ui.show.ShowFragment.title";
private static final String ARG_OVERVIEW = "net.simonvt.cathode.ui.show.ShowFragment.overview";
private static final String ARG_TYPE = "net.simonvt.cathode.ui.show.ShowFragment.type";
private static final String DIALOG_RATING =
"net.simonvt.cathode.ui.show.ShowFragment.ratingDialog";
private static final String DIALOG_LISTS_ADD =
"net.simonvt.cathode.ui.show.ShowFragment.listsAddDialog";
private static final String DIALOG_COMMENT_UPDATE =
"net.simonvt.cathode.ui.show.ShowFragment.updateCommentDialog";
private static final int LOADER_SHOW = 1;
private static final int LOADER_SHOW_WATCH = 2;
private static final int LOADER_SHOW_COLLECT = 3;
private static final int LOADER_SHOW_GENRES = 4;
private static final int LOADER_SHOW_SEASONS = 5;
private static final int LOADER_SHOW_CAST = 6;
private static final int LOADER_SHOW_USER_COMMENTS = 7;
private static final int LOADER_SHOW_COMMENTS = 8;
private static final int LOADER_RELATED = 9;
private static final String[] SHOW_PROJECTION = new String[] {
ShowColumns.TRAKT_ID, ShowColumns.TITLE, ShowColumns.YEAR, ShowColumns.AIR_TIME,
ShowColumns.AIR_DAY, ShowColumns.NETWORK, ShowColumns.CERTIFICATION, ShowColumns.STATUS,
ShowColumns.USER_RATING, ShowColumns.RATING, ShowColumns.OVERVIEW, ShowColumns.IN_WATCHLIST,
ShowColumns.IN_COLLECTION_COUNT, ShowColumns.WATCHED_COUNT, ShowColumns.LAST_SYNC,
ShowColumns.LAST_COMMENT_SYNC, ShowColumns.LAST_CREDITS_SYNC, ShowColumns.LAST_RELATED_SYNC,
ShowColumns.HOMEPAGE, ShowColumns.TRAILER, ShowColumns.IMDB_ID, ShowColumns.TVDB_ID,
ShowColumns.TMDB_ID, ShowColumns.NEEDS_SYNC, HiddenColumns.HIDDEN_CALENDAR,
};
private static final String[] EPISODE_PROJECTION = new String[] {
EpisodeColumns.ID, EpisodeColumns.TITLE, EpisodeColumns.FIRST_AIRED, EpisodeColumns.SEASON,
EpisodeColumns.EPISODE, EpisodeColumns.WATCHING, EpisodeColumns.CHECKED_IN,
};
private static final String[] GENRES_PROJECTION = new String[] {
ShowGenreColumns.GENRE,
};
@Inject PersonTaskScheduler personScheduler;
private NavigationListener navigationListener;
private long showId;
@BindView(R.id.hiddenPaneLayout) HiddenPaneLayout hiddenPaneLayout;
@BindView(R.id.seasons) RecyclerView seasons;
@BindView(R.id.seasonsEmpty) View seasonsEmpty;
private SeasonsAdapter seasonsAdapter;
private Cursor seasonsCursor;
@BindView(R.id.rating) CircularProgressIndicator rating;
@BindView(R.id.airtime) TextView airTime;
@BindView(R.id.status) TextView status;
@BindView(R.id.overview) TextView overview;
@BindView(R.id.genresTitle) View genresTitle;
@BindView(R.id.genres) TextView genres;
@BindView(R.id.isWatched) TextView watched;
@BindView(R.id.inCollection) TextView collection;
@BindView(R.id.inWatchlist) TextView watchlist;
@BindView(R.id.trailer) View trailer;
@BindView(R.id.castParent) View castParent;
@BindView(R.id.castHeader) View castHeader;
@BindView(R.id.cast) LinearLayout cast;
@BindView(R.id.castContainer) LinearLayout castContainer;
@BindView(R.id.commentsParent) View commentsParent;
@BindView(R.id.commentsHeader) View commentsHeader;
@BindView(R.id.commentsContainer) LinearLayout commentsContainer;
@BindView(R.id.relatedParent) View relatedParent;
@BindView(R.id.relatedHeader) View relatedHeader;
@BindView(R.id.related) LinearLayout related;
@BindView(R.id.relatedContainer) LinearLayout relatedContainer;
@BindView(R.id.websiteTitle) View websiteTitle;
@BindView(R.id.website) TextView website;
@BindView(R.id.viewOnTrakt) View viewOnTrakt;
@BindView(R.id.viewOnImdb) View viewOnImdb;
@BindView(R.id.viewOnTvdb) View viewOnTvdb;
@BindView(R.id.viewOnTmdb) View viewOnTmdb;
private Cursor userComments;
private Cursor comments;
@BindView(R.id.episodes) LinearLayout episodes;
@BindView(R.id.toWatch) View toWatch;
private EpisodeHolder toWatchHolder;
private long toWatchId = -1;
private String toWatchTitle;
@BindView(R.id.lastWatched) @Nullable View lastWatched;
private EpisodeHolder lastWatchedHolder;
private long lastWatchedId = -1;
@BindView(R.id.toCollect) View toCollect;
private EpisodeHolder toCollectHolder;
private long toCollectId = -1;
@BindView(R.id.lastCollected) @Nullable View lastCollected;
private EpisodeHolder lastCollectedHolder;
private long lastCollectedId = -1;
static class EpisodeHolder {
@BindView(R.id.episodeScreenshot) RemoteImageView episodeScreenshot;
@BindView(R.id.episodeTitle) TextView episodeTitle;
@BindView(R.id.episodeAirTime) TextView episodeAirTime;
@BindView(R.id.episodeEpisode) TextView episodeEpisode;
@BindView(R.id.episodeOverflow) OverflowView episodeOverflow;
public EpisodeHolder(View v) {
ButterKnife.bind(this, v);
}
}
@Inject ShowTaskScheduler showScheduler;
@Inject EpisodeTaskScheduler episodeScheduler;
private String showTitle;
private String showOverview;
private boolean inWatchlist;
private int currentRating;
private boolean calendarHidden;
private LibraryType type;
RecyclerViewManager seasonsManager;
public static String getTag(long showId) {
return TAG + "/" + showId + "/" + Ids.newId();
}
public static Bundle getArgs(long showId, String title, String overview, LibraryType type) {
if (showId < 0) {
throw new IllegalArgumentException("showId must be >= 0");
}
Bundle args = new Bundle();
args.putLong(ARG_SHOWID, showId);
args.putString(ARG_TITLE, title);
args.putString(ARG_OVERVIEW, overview);
args.putSerializable(ARG_TYPE, type);
return args;
}
public long getShowId() {
return showId;
}
@Override public void onAttach(Activity activity) {
super.onAttach(activity);
navigationListener = (NavigationListener) activity;
}
@Override public void onCreate(Bundle inState) {
super.onCreate(inState);
Timber.d("ShowFragment#onCreate");
CathodeApp.inject(getActivity(), this);
Bundle args = getArguments();
showId = args.getLong(ARG_SHOWID);
showTitle = args.getString(ARG_TITLE);
showOverview = args.getString(ARG_OVERVIEW);
type = (LibraryType) args.getSerializable(ARG_TYPE);
setTitle(showTitle);
seasonsAdapter = new SeasonsAdapter(getActivity(), new SeasonClickListener() {
@Override
public void onSeasonClick(long showId, long seasonId, String showTitle, int seasonNumber) {
navigationListener.onDisplaySeason(showId, seasonId, showTitle, seasonNumber, type);
}
}, type);
}
@Override public boolean onBackPressed() {
if (hiddenPaneLayout != null) {
final int state = hiddenPaneLayout.getState();
if (state == HiddenPaneLayout.STATE_OPEN || state == HiddenPaneLayout.STATE_OPENING) {
hiddenPaneLayout.close();
return true;
}
}
return super.onBackPressed();
}
@Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle inState) {
HiddenPaneLayout hiddenPane =
(HiddenPaneLayout) inflater.inflate(R.layout.fragment_show_hiddenpanelayout, container,
false);
View v = super.onCreateView(inflater, hiddenPane, inState);
hiddenPane.addView(v);
inflater.inflate(R.layout.fragment_show_seasons, hiddenPane, true);
return hiddenPane;
}
@Override public View createView(LayoutInflater inflater, ViewGroup container, Bundle inState) {
return inflater.inflate(R.layout.fragment_show, container, false);
}
@Override public void onViewCreated(View view, Bundle inState) {
super.onViewCreated(view, inState);
overview.setText(showOverview);
seasonsManager =
new RecyclerViewManager(seasons, new LinearLayoutManager(getActivity()), seasonsEmpty);
seasonsManager.setAdapter(seasonsAdapter);
seasons.setAdapter(seasonsAdapter);
((DefaultItemAnimator) seasons.getItemAnimator()).setSupportsChangeAnimations(false);
rating.setOnClickListener(new View.OnClickListener() {
@Override public void onClick(View view) {
RatingDialog.newInstance(RatingDialog.Type.SHOW, showId, currentRating)
.show(getFragmentManager(), DIALOG_RATING);
}
});
castHeader.setOnClickListener(new View.OnClickListener() {
@Override public void onClick(View v) {
navigationListener.onDisplayCredits(ItemType.SHOW, showId, showTitle);
}
});
commentsHeader.setOnClickListener(new View.OnClickListener() {
@Override public void onClick(View v) {
navigationListener.onDisplayComments(ItemType.SHOW, showId);
}
});
relatedHeader.setOnClickListener(new View.OnClickListener() {
@Override public void onClick(View v) {
navigationListener.onDisplayRelatedShows(showId, showTitle);
}
});
toWatchHolder = new EpisodeHolder(toWatch);
toWatch.setOnClickListener(new View.OnClickListener() {
@Override public void onClick(View view) {
if (toWatchId != -1) navigationListener.onDisplayEpisode(toWatchId, showTitle);
}
});
toWatchHolder.episodeOverflow.setListener(new OverflowView.OverflowActionListener() {
@Override public void onPopupShown() {
}
@Override public void onPopupDismissed() {
}
@Override public void onActionSelected(int action) {
switch (action) {
case R.id.action_checkin:
if (toWatchId != -1) {
CheckInDialog.showDialogIfNecessary(getActivity(), Type.SHOW, toWatchTitle,
toWatchId);
}
break;
case R.id.action_checkin_cancel:
if (toWatchId != -1) {
showScheduler.cancelCheckin();
}
break;
case R.id.action_watched:
if (toWatchId != -1) {
episodeScheduler.setWatched(toWatchId, true);
}
break;
}
}
});
if (lastWatched != null) {
lastWatchedHolder = new EpisodeHolder(lastWatched);
lastWatched.setOnClickListener(new View.OnClickListener() {
@Override public void onClick(View view) {
if (lastWatchedId != -1) {
navigationListener.onDisplayEpisode(lastWatchedId, showTitle);
}
}
});
lastWatchedHolder.episodeOverflow.addItem(R.id.action_unwatched, R.string.action_unwatched);
lastWatchedHolder.episodeOverflow.setListener(new OverflowView.OverflowActionListener() {
@Override public void onPopupShown() {
}
@Override public void onPopupDismissed() {
}
@Override public void onActionSelected(int action) {
switch (action) {
case R.id.action_unwatched:
if (lastWatchedId != -1) {
episodeScheduler.setWatched(lastWatchedId, false);
}
break;
}
}
});
}
toCollectHolder = new EpisodeHolder(toCollect);
toCollect.setOnClickListener(new View.OnClickListener() {
@Override public void onClick(View view) {
if (toCollectId != -1) navigationListener.onDisplayEpisode(toCollectId, showTitle);
}
});
toCollectHolder.episodeOverflow.addItem(R.id.action_collection_add,
R.string.action_collection_add);
toCollectHolder.episodeOverflow.setListener(new OverflowView.OverflowActionListener() {
@Override public void onPopupShown() {
}
@Override public void onPopupDismissed() {
}
@Override public void onActionSelected(int action) {
switch (action) {
case R.id.action_collection_add:
if (toCollectId != -1) {
episodeScheduler.setIsInCollection(toCollectId, true);
}
break;
}
}
});
if (lastCollected != null) {
lastCollectedHolder = new EpisodeHolder(lastCollected);
lastCollected.setOnClickListener(new View.OnClickListener() {
@Override public void onClick(View view) {
if (lastCollectedId != -1) {
navigationListener.onDisplayEpisode(lastCollectedId, showTitle);
}
}
});
lastCollectedHolder.episodeOverflow.addItem(R.id.action_collection_remove,
R.string.action_collection_remove);
lastCollectedHolder.episodeOverflow.setListener(new OverflowView.OverflowActionListener() {
@Override public void onPopupShown() {
}
@Override public void onPopupDismissed() {
}
@Override public void onActionSelected(int action) {
switch (action) {
case R.id.action_collection_add:
if (lastCollectedId != -1) {
episodeScheduler.setIsInCollection(lastCollectedId, true);
}
break;
}
}
});
}
getLoaderManager().initLoader(LOADER_SHOW, null, showCallbacks);
getLoaderManager().initLoader(LOADER_SHOW_GENRES, null, genreCallbacks);
getLoaderManager().initLoader(LOADER_SHOW_CAST, null, castCallback);
getLoaderManager().initLoader(LOADER_SHOW_WATCH, null, episodeWatchCallbacks);
getLoaderManager().initLoader(LOADER_SHOW_COLLECT, null, episodeCollectCallbacks);
getLoaderManager().initLoader(LOADER_SHOW_SEASONS, null, seasonsLoader);
getLoaderManager().initLoader(LOADER_SHOW_USER_COMMENTS, null, userCommentsLoader);
getLoaderManager().initLoader(LOADER_SHOW_COMMENTS, null, commentsLoader);
getLoaderManager().initLoader(LOADER_RELATED, null, relatedLoader);
}
private Job.OnDoneListener onDoneListener = new Job.OnDoneListener() {
@Override public void onDone(Job job) {
setRefreshing(false);
}
};
@Override public void onRefresh() {
showScheduler.sync(showId, onDoneListener);
}
@Override public void createMenu(Toolbar toolbar) {
super.createMenu(toolbar);
Menu menu = toolbar.getMenu();
toolbar.inflateMenu(R.menu.fragment_show);
if (inWatchlist) {
menu.add(0, R.id.action_watchlist_remove, 300, R.string.action_watchlist_remove);
} else {
menu.add(0, R.id.action_watchlist_add, 300, R.string.action_watchlist_add);
}
if (calendarHidden) {
menu.add(0, R.id.action_calendar_unhide, 400, R.string.action_calendar_unhide);
} else {
menu.add(0, R.id.action_calendar_hide, 400, R.string.action_calendar_hide);
}
}
@Override public boolean onMenuItemClick(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_seasons:
hiddenPaneLayout.toggle();
return true;
case R.id.action_watchlist_remove:
showScheduler.setIsInWatchlist(showId, false);
return true;
case R.id.action_watchlist_add:
showScheduler.setIsInWatchlist(showId, true);
return true;
case R.id.menu_lists_add:
ListsDialog.newInstance(DatabaseContract.ItemType.SHOW, showId)
.show(getFragmentManager(), DIALOG_LISTS_ADD);
return true;
case R.id.action_calendar_hide:
showScheduler.hideFromCalendar(showId, true);
return true;
case R.id.action_calendar_unhide:
showScheduler.hideFromCalendar(showId, false);
return true;
}
return super.onMenuItemClick(item);
}
private void updateShowView(final Cursor cursor) {
if (cursor == null || !cursor.moveToFirst()) return;
final long traktId = Cursors.getLong(cursor, ShowColumns.TRAKT_ID);
String title = Cursors.getString(cursor, ShowColumns.TITLE);
if (!TextUtils.equals(title, showTitle)) {
showTitle = title;
setTitle(title);
}
final String airTime = Cursors.getString(cursor, ShowColumns.AIR_TIME);
final String airDay = Cursors.getString(cursor, ShowColumns.AIR_DAY);
final String network = Cursors.getString(cursor, ShowColumns.NETWORK);
final String certification = Cursors.getString(cursor, ShowColumns.CERTIFICATION);
final String showStatus = Cursors.getString(cursor, ShowColumns.STATUS);
final String backdropUri = ImageUri.create(ImageUri.ITEM_SHOW, ImageType.BACKDROP, showId);
setBackdrop(backdropUri, true);
showOverview = Cursors.getString(cursor, ShowColumns.OVERVIEW);
inWatchlist = Cursors.getBoolean(cursor, ShowColumns.IN_WATCHLIST);
final int inCollectionCount = Cursors.getInt(cursor, ShowColumns.IN_COLLECTION_COUNT);
final int watchedCount = Cursors.getInt(cursor, ShowColumns.WATCHED_COUNT);
currentRating = Cursors.getInt(cursor, ShowColumns.USER_RATING);
final float ratingAll = Cursors.getFloat(cursor, ShowColumns.RATING);
rating.setValue(ratingAll);
calendarHidden = Cursors.getBoolean(cursor, HiddenColumns.HIDDEN_CALENDAR);
watched.setVisibility(watchedCount > 0 ? View.VISIBLE : View.GONE);
collection.setVisibility(inCollectionCount > 0 ? View.VISIBLE : View.GONE);
watchlist.setVisibility(inWatchlist ? View.VISIBLE : View.GONE);
String airTimeString = null;
if (airDay != null && airTime != null) {
airTimeString = airDay + " " + airTime;
}
if (network != null) {
if (airTimeString != null) {
airTimeString += ", " + network;
} else {
airTimeString = network;
}
}
if (certification != null) {
if (airTimeString != null) {
airTimeString += ", " + certification;
} else {
airTimeString = certification;
}
}
this.airTime.setText(airTimeString);
String statusString = null;
if (showStatus != null) {
final ShowStatus status = ShowStatus.fromValue(showStatus);
switch (status) {
case ENDED:
statusString = getString(R.string.show_status_ended);
break;
case RETURNING:
statusString = getString(R.string.show_status_returning);
break;
case CANCELED:
statusString = getString(R.string.show_status_canceled);
break;
case IN_PRODUCTION:
statusString = getString(R.string.show_status_in_production);
break;
case PLANNED:
statusString = getString(R.string.show_status_planned);
break;
}
}
this.status.setText(statusString);
this.overview.setText(showOverview);
final String trailer = Cursors.getString(cursor, ShowColumns.TRAILER);
if (!TextUtils.isEmpty(trailer)) {
this.trailer.setVisibility(View.VISIBLE);
this.trailer.setOnClickListener(new View.OnClickListener() {
@Override public void onClick(View v) {
Intents.openUrl(getActivity(), trailer);
}
});
} else {
this.trailer.setVisibility(View.GONE);
}
final boolean needsSync = Cursors.getBoolean(cursor, ShowColumns.NEEDS_SYNC);
if (needsSync) {
Timber.d("Needs sync: %d", showId);
showScheduler.sync(showId);
}
final long lastSync = Cursors.getLong(cursor, ShowColumns.LAST_SYNC);
final long lastCommentSync = Cursors.getLong(cursor, ShowColumns.LAST_COMMENT_SYNC);
if (TraktTimestamps.shouldSyncComments(lastCommentSync)) {
showScheduler.syncComments(showId);
}
final long lastActorsSync = Cursors.getLong(cursor, ShowColumns.LAST_CREDITS_SYNC);
if (lastSync > lastActorsSync) {
showScheduler.syncCredits(showId, null);
}
final long lastRelatedSync = Cursors.getLong(cursor, ShowColumns.LAST_RELATED_SYNC);
if (lastSync > lastRelatedSync) {
showScheduler.syncRelated(showId, null);
}
final String website = Cursors.getString(cursor, ShowColumns.HOMEPAGE);
if (!TextUtils.isEmpty(website)) {
this.websiteTitle.setVisibility(View.VISIBLE);
this.website.setVisibility(View.VISIBLE);
this.website.setText(website);
this.website.setOnClickListener(new View.OnClickListener() {
@Override public void onClick(View v) {
Intents.openUrl(getContext(), website);
}
});
} else {
this.websiteTitle.setVisibility(View.GONE);
this.website.setVisibility(View.GONE);
}
final String imdbId = Cursors.getString(cursor, ShowColumns.IMDB_ID);
final int tvdbId = Cursors.getInt(cursor, ShowColumns.TVDB_ID);
final int tmdbId = Cursors.getInt(cursor, ShowColumns.TMDB_ID);
viewOnTrakt.setOnClickListener(new View.OnClickListener() {
@Override public void onClick(View v) {
Intents.openUrl(getContext(), TraktUtils.getTraktShowUrl(traktId));
}
});
final boolean hasImdbId = !TextUtils.isEmpty(imdbId);
if (hasImdbId) {
viewOnImdb.setVisibility(View.VISIBLE);
viewOnImdb.setOnClickListener(new View.OnClickListener() {
@Override public void onClick(View v) {
Intents.openUrl(getContext(), TraktUtils.getImdbUrl(imdbId));
}
});
} else {
viewOnImdb.setVisibility(View.GONE);
}
if (tvdbId > 0) {
viewOnTvdb.setVisibility(View.VISIBLE);
viewOnTvdb.setOnClickListener(new View.OnClickListener() {
@Override public void onClick(View v) {
Intents.openUrl(getContext(), TraktUtils.getTvdbUrl(tvdbId));
}
});
} else {
viewOnTvdb.setVisibility(View.GONE);
}
if (tmdbId > 0) {
viewOnTmdb.setVisibility(View.VISIBLE);
viewOnTmdb.setOnClickListener(new View.OnClickListener() {
@Override public void onClick(View v) {
Intents.openUrl(getContext(), TraktUtils.getTmdbTvUrl(tmdbId));
}
});
} else {
viewOnTmdb.setVisibility(View.GONE);
}
invalidateMenu();
}
private void updateGenreViews(final Cursor cursor) {
if (cursor.getCount() > 0) {
StringBuilder sb = new StringBuilder();
final int genreColumnIndex = cursor.getColumnIndex(ShowGenreColumns.GENRE);
cursor.moveToPosition(-1);
while (cursor.moveToNext()) {
sb.append(cursor.getString(genreColumnIndex));
if (!cursor.isLast()) sb.append(", ");
}
genresTitle.setVisibility(View.VISIBLE);
genres.setVisibility(View.VISIBLE);
genres.setText(sb.toString());
} else {
genresTitle.setVisibility(View.GONE);
genres.setVisibility(View.GONE);
}
}
private void updateCastViews(Cursor c) {
castContainer.removeAllViews();
final int count = c.getCount();
final int visibility = count > 0 ? View.VISIBLE : View.GONE;
castParent.setVisibility(visibility);
int index = 0;
c.moveToPosition(-1);
while (c.moveToNext() && index < 3) {
View v =
LayoutInflater.from(getActivity()).inflate(R.layout.item_person, castContainer, false);
final long personId = Cursors.getLong(c, ShowCastColumns.PERSON_ID);
final String headshotUrl = ImageUri.create(ImageUri.ITEM_PERSON, ImageType.PROFILE, personId);
RemoteImageView headshot = (RemoteImageView) v.findViewById(R.id.headshot);
headshot.addTransformation(new CircleTransformation());
headshot.setImage(headshotUrl);
TextView name = (TextView) v.findViewById(R.id.person_name);
name.setText(Cursors.getString(c, PersonColumns.NAME));
TextView character = (TextView) v.findViewById(R.id.person_job);
character.setText(Cursors.getString(c, ShowCastColumns.CHARACTER));
v.setOnClickListener(new View.OnClickListener() {
@Override public void onClick(View v) {
navigationListener.onDisplayPerson(personId);
}
});
castContainer.addView(v);
index++;
}
}
private void updateRelatedView(Cursor related) {
relatedContainer.removeAllViews();
final int count = related.getCount();
final int visibility = count > 0 ? View.VISIBLE : View.GONE;
relatedParent.setVisibility(visibility);
int index = 0;
related.moveToPosition(-1);
while (related.moveToNext() && index < 3) {
View v = LayoutInflater.from(getActivity())
.inflate(R.layout.item_related, this.relatedContainer, false);
final long relatedShowId = Cursors.getLong(related, RelatedShowsColumns.RELATED_SHOW_ID);
final String title = Cursors.getString(related, ShowColumns.TITLE);
final String overview = Cursors.getString(related, ShowColumns.OVERVIEW);
final float rating = Cursors.getFloat(related, ShowColumns.RATING);
final int votes = Cursors.getInt(related, ShowColumns.VOTES);
final String poster = ImageUri.create(ImageUri.ITEM_SHOW, ImageType.POSTER, relatedShowId);
RemoteImageView posterView = (RemoteImageView) v.findViewById(R.id.related_poster);
posterView.addTransformation(new CircleTransformation());
posterView.setImage(poster);
TextView titleView = (TextView) v.findViewById(R.id.related_title);
titleView.setText(title);
final String formattedRating = String.format(Locale.getDefault(), "%.1f", rating);
String ratingText;
if (votes >= 1000) {
final float convertedVotes = votes / 1000.0f;
final String formattedVotes = String.format(Locale.getDefault(), "%.1f", convertedVotes);
ratingText = getString(R.string.related_rating_thousands, formattedRating, formattedVotes);
} else {
ratingText = getString(R.string.related_rating, formattedRating, votes);
}
TextView ratingView = (TextView) v.findViewById(R.id.related_rating);
ratingView.setText(ratingText);
v.setOnClickListener(new View.OnClickListener() {
@Override public void onClick(View v) {
navigationListener.onDisplayShow(relatedShowId, title, overview, LibraryType.WATCHED);
}
});
relatedContainer.addView(v);
index++;
}
}
private void updateEpisodeWatchViews(Cursor cursor) {
if (cursor.moveToFirst()) {
toWatch.setVisibility(View.VISIBLE);
toWatchId = Cursors.getLong(cursor, EpisodeColumns.ID);
final long firstAired = DataHelper.getFirstAired(cursor);
final int season = Cursors.getInt(cursor, EpisodeColumns.SEASON);
final int episode = Cursors.getInt(cursor, EpisodeColumns.EPISODE);
toWatchTitle = DataHelper.getEpisodeTitle(getContext(), cursor, season, episode);
final String toWatchEpisodeText = getString(R.string.season_x_episode_y, season, episode);
toWatchHolder.episodeTitle.setText(toWatchTitle);
toWatchHolder.episodeEpisode.setText(toWatchEpisodeText);
final String screenshotUri =
ImageUri.create(ImageUri.ITEM_EPISODE, ImageType.STILL, toWatchId);
toWatchHolder.episodeScreenshot.setImage(screenshotUri);
String firstAiredString = DateUtils.millisToString(getActivity(), firstAired, false);
final boolean watching = Cursors.getBoolean(cursor, EpisodeColumns.WATCHING);
final boolean checkedIn = Cursors.getBoolean(cursor, EpisodeColumns.CHECKED_IN);
toWatchHolder.episodeOverflow.removeItems();
if (checkedIn) {
toWatchHolder.episodeOverflow.addItem(R.id.action_checkin_cancel,
R.string.action_checkin_cancel);
firstAiredString = getResources().getString(R.string.show_watching);
} else if (!watching) {
toWatchHolder.episodeOverflow.addItem(R.id.action_checkin, R.string.action_checkin);
toWatchHolder.episodeOverflow.addItem(R.id.action_watched, R.string.action_watched);
}
toWatchHolder.episodeAirTime.setText(firstAiredString);
} else {
toWatch.setVisibility(View.GONE);
toWatchId = -1;
}
if (lastWatched != null) {
if (cursor.moveToNext()) {
lastWatched.setVisibility(View.VISIBLE);
lastWatchedId = Cursors.getLong(cursor, EpisodeColumns.ID);
final int season = Cursors.getInt(cursor, EpisodeColumns.SEASON);
final int episode = Cursors.getInt(cursor, EpisodeColumns.EPISODE);
final String title = DataHelper.getEpisodeTitle(getContext(), cursor, season, episode);
lastWatchedHolder.episodeTitle.setText(title);
final long firstAired = DataHelper.getFirstAired(cursor);
final String firstAiredString = DateUtils.millisToString(getActivity(), firstAired, false);
lastWatchedHolder.episodeAirTime.setText(firstAiredString);
final String lastWatchedEpisodeText =
getString(R.string.season_x_episode_y, season, episode);
lastWatchedHolder.episodeEpisode.setText(lastWatchedEpisodeText);
final String screenshotUri =
ImageUri.create(ImageUri.ITEM_EPISODE, ImageType.STILL, lastWatchedId);
lastWatchedHolder.episodeScreenshot.setImage(screenshotUri);
} else {
lastWatched.setVisibility(toWatchId == -1 ? View.GONE : View.INVISIBLE);
lastWatchedId = -1;
}
}
if (toWatchId == -1 && lastWatchedId == -1 && toCollectId == -1 && lastCollectedId == -1) {
episodes.setVisibility(View.GONE);
} else {
episodes.setVisibility(View.VISIBLE);
}
}
private void updateEpisodeCollectViews(Cursor cursor) {
if (cursor.moveToFirst()) {
toCollect.setVisibility(View.VISIBLE);
toCollectId = Cursors.getLong(cursor, EpisodeColumns.ID);
final int season = Cursors.getInt(cursor, EpisodeColumns.SEASON);
final int episode = Cursors.getInt(cursor, EpisodeColumns.EPISODE);
final String title = DataHelper.getEpisodeTitle(getContext(), cursor, season, episode);
toCollectHolder.episodeTitle.setText(title);
final long firstAired = DataHelper.getFirstAired(cursor);
final String firstAiredString = DateUtils.millisToString(getActivity(), firstAired, false);
toCollectHolder.episodeAirTime.setText(firstAiredString);
final String toCollectEpisodeText = getString(R.string.season_x_episode_y, season, episode);
toCollectHolder.episodeEpisode.setText(toCollectEpisodeText);
final String screenshotUri =
ImageUri.create(ImageUri.ITEM_EPISODE, ImageType.STILL, toCollectId);
toCollectHolder.episodeScreenshot.setImage(screenshotUri);
} else {
toCollect.setVisibility(View.GONE);
toCollectId = -1;
}
if (lastCollected != null) {
if (cursor.moveToNext()) {
lastCollected.setVisibility(View.VISIBLE);
lastCollectedId = Cursors.getLong(cursor, EpisodeColumns.ID);
final int season = Cursors.getInt(cursor, EpisodeColumns.SEASON);
final int episode = Cursors.getInt(cursor, EpisodeColumns.EPISODE);
final String title = DataHelper.getEpisodeTitle(getContext(), cursor, season, episode);
lastCollectedHolder.episodeTitle.setText(title);
final long firstAired = DataHelper.getFirstAired(cursor);
final String firstAiredString = DateUtils.millisToString(getActivity(), firstAired, false);
lastCollectedHolder.episodeAirTime.setText(firstAiredString);
final String lastCollectedEpisodeText =
getString(R.string.season_x_episode_y, season, episode);
lastCollectedHolder.episodeEpisode.setText(lastCollectedEpisodeText);
final String screenshotUri =
ImageUri.create(ImageUri.ITEM_EPISODE, ImageType.STILL, lastCollectedId);
lastCollectedHolder.episodeScreenshot.setImage(screenshotUri);
} else {
lastCollectedId = -1;
lastCollected.setVisibility(View.INVISIBLE);
}
}
if (toWatchId == -1 && lastWatchedId == -1 && toCollectId == -1 && lastCollectedId == -1) {
episodes.setVisibility(View.GONE);
} else {
episodes.setVisibility(View.VISIBLE);
}
}
private void updateComments() {
LinearCommentsAdapter.updateComments(getContext(), commentsContainer, userComments, comments);
commentsParent.setVisibility(View.VISIBLE);
}
private LoaderManager.LoaderCallbacks<SimpleCursor> showCallbacks =
new LoaderManager.LoaderCallbacks<SimpleCursor>() {
@Override public Loader<SimpleCursor> onCreateLoader(int id, Bundle args) {
return new SimpleCursorLoader(getActivity(), Shows.withId(showId), SHOW_PROJECTION, null,
null, null);
}
@Override public void onLoadFinished(Loader<SimpleCursor> cursorLoader, SimpleCursor data) {
updateShowView(data);
}
@Override public void onLoaderReset(Loader<SimpleCursor> cursorLoader) {
}
};
private LoaderManager.LoaderCallbacks<SimpleCursor> genreCallbacks =
new LoaderManager.LoaderCallbacks<SimpleCursor>() {
@Override public Loader<SimpleCursor> onCreateLoader(int id, Bundle args) {
return new SimpleCursorLoader(getActivity(), ShowGenres.fromShow(showId),
GENRES_PROJECTION, null, null, ShowGenres.DEFAULT_SORT);
}
@Override public void onLoadFinished(Loader<SimpleCursor> cursorLoader, SimpleCursor data) {
updateGenreViews(data);
}
@Override public void onLoaderReset(Loader<SimpleCursor> cursorLoader) {
}
};
private static final String[] CAST_PROJECTION = new String[] {
Tables.SHOW_CAST + "." + ShowCastColumns.ID,
Tables.SHOW_CAST + "." + ShowCastColumns.CHARACTER,
Tables.SHOW_CAST + "." + ShowCastColumns.PERSON_ID, Tables.PEOPLE + "." + PersonColumns.NAME,
};
private LoaderManager.LoaderCallbacks<SimpleCursor> castCallback =
new LoaderManager.LoaderCallbacks<SimpleCursor>() {
@Override public Loader<SimpleCursor> onCreateLoader(int id, Bundle args) {
return new SimpleCursorLoader(getActivity(), ProviderSchematic.ShowCast.fromShow(showId),
CAST_PROJECTION, Tables.PEOPLE + "." + PersonColumns.NEEDS_SYNC + "=0", null, null);
}
@Override public void onLoadFinished(Loader<SimpleCursor> loader, SimpleCursor data) {
updateCastViews(data);
}
@Override public void onLoaderReset(Loader<SimpleCursor> loader) {
}
};
private LoaderManager.LoaderCallbacks<SimpleMergeCursor> episodeWatchCallbacks =
new LoaderManager.LoaderCallbacks<SimpleMergeCursor>() {
@Override public Loader<SimpleMergeCursor> onCreateLoader(int i, Bundle bundle) {
return new WatchedLoader(getActivity(), showId, EPISODE_PROJECTION);
}
@Override public void onLoadFinished(Loader<SimpleMergeCursor> cursorLoader,
SimpleMergeCursor cursor) {
updateEpisodeWatchViews(cursor);
}
@Override public void onLoaderReset(Loader<SimpleMergeCursor> cursorLoader) {
}
};
private LoaderManager.LoaderCallbacks<SimpleMergeCursor> episodeCollectCallbacks =
new LoaderManager.LoaderCallbacks<SimpleMergeCursor>() {
@Override public Loader<SimpleMergeCursor> onCreateLoader(int i, Bundle bundle) {
return new CollectLoader(getActivity(), showId, EPISODE_PROJECTION);
}
@Override public void onLoadFinished(Loader<SimpleMergeCursor> cursorLoader,
SimpleMergeCursor cursor) {
updateEpisodeCollectViews(cursor);
}
@Override public void onLoaderReset(Loader<SimpleMergeCursor> cursorLoader) {
}
};
private LoaderManager.LoaderCallbacks<SimpleCursor> seasonsLoader =
new LoaderManager.LoaderCallbacks<SimpleCursor>() {
@Override public Loader<SimpleCursor> onCreateLoader(int id, Bundle args) {
return new SimpleCursorLoader(getActivity(), Seasons.fromShow(showId),
SeasonsAdapter.PROJECTION, null, null, Seasons.DEFAULT_SORT);
}
@Override public void onLoadFinished(Loader<SimpleCursor> cursorLoader, SimpleCursor data) {
seasonsCursor = data;
seasonsAdapter.changeCursor(data);
}
@Override public void onLoaderReset(Loader<SimpleCursor> cursorLoader) {
seasonsCursor = null;
seasonsAdapter.changeCursor(null);
}
};
private static final String[] COMMENTS_PROJECTION = new String[] {
SqlColumn.table(Tables.COMMENTS).column(CommentColumns.ID),
SqlColumn.table(Tables.COMMENTS).column(CommentColumns.COMMENT),
SqlColumn.table(Tables.COMMENTS).column(CommentColumns.SPOILER),
SqlColumn.table(Tables.COMMENTS).column(CommentColumns.REVIEW),
SqlColumn.table(Tables.COMMENTS).column(CommentColumns.CREATED_AT),
SqlColumn.table(Tables.COMMENTS).column(CommentColumns.LIKES),
SqlColumn.table(Tables.COMMENTS).column(CommentColumns.USER_RATING),
SqlColumn.table(Tables.USERS).column(UserColumns.USERNAME),
SqlColumn.table(Tables.USERS).column(UserColumns.NAME),
SqlColumn.table(Tables.USERS).column(UserColumns.AVATAR),
};
private LoaderManager.LoaderCallbacks<SimpleCursor> userCommentsLoader =
new LoaderManager.LoaderCallbacks<SimpleCursor>() {
@Override public Loader<SimpleCursor> onCreateLoader(int id, Bundle args) {
return new SimpleCursorLoader(getContext(), Comments.fromShow(showId),
COMMENTS_PROJECTION, CommentColumns.IS_USER_COMMENT + "=1", null, null);
}
@Override public void onLoadFinished(Loader<SimpleCursor> loader, SimpleCursor data) {
userComments = data;
updateComments();
}
@Override public void onLoaderReset(Loader<SimpleCursor> loader) {
}
};
private LoaderManager.LoaderCallbacks<SimpleCursor> commentsLoader =
new LoaderManager.LoaderCallbacks<SimpleCursor>() {
@Override public Loader<SimpleCursor> onCreateLoader(int id, Bundle args) {
return new SimpleCursorLoader(getContext(), Comments.fromShow(showId),
COMMENTS_PROJECTION,
CommentColumns.IS_USER_COMMENT + "=0 AND " + CommentColumns.SPOILER + "=0", null,
CommentColumns.LIKES + " DESC LIMIT 3");
}
@Override public void onLoadFinished(Loader<SimpleCursor> loader, SimpleCursor data) {
comments = data;
updateComments();
}
@Override public void onLoaderReset(Loader<SimpleCursor> loader) {
}
};
private static final String[] RELATED_PROJECTION = new String[] {
SqlColumn.table(Tables.SHOW_RELATED).column(RelatedShowsColumns.RELATED_SHOW_ID),
SqlColumn.table(Tables.SHOWS).column(ShowColumns.TITLE),
SqlColumn.table(Tables.SHOWS).column(ShowColumns.OVERVIEW),
SqlColumn.table(Tables.SHOWS).column(ShowColumns.RATING),
SqlColumn.table(Tables.SHOWS).column(ShowColumns.VOTES),
};
private LoaderManager.LoaderCallbacks<SimpleCursor> relatedLoader =
new LoaderManager.LoaderCallbacks<SimpleCursor>() {
@Override public Loader<SimpleCursor> onCreateLoader(int id, Bundle args) {
return new SimpleCursorLoader(getContext(), RelatedShows.fromShow(showId),
RELATED_PROJECTION, null, null, RelatedShowsColumns.RELATED_INDEX + " ASC LIMIT 3");
}
@Override public void onLoadFinished(Loader<SimpleCursor> loader, SimpleCursor data) {
updateRelatedView(data);
}
@Override public void onLoaderReset(Loader<SimpleCursor> loader) {
}
};
}
| cathode/src/main/java/net/simonvt/cathode/ui/show/ShowFragment.java | /*
* Copyright (C) 2016 Simon Vig Therkildsen
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.simonvt.cathode.ui.show;
import android.app.Activity;
import android.database.Cursor;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.Loader;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;
import butterknife.BindView;
import butterknife.ButterKnife;
import java.util.Locale;
import javax.inject.Inject;
import net.simonvt.cathode.CathodeApp;
import net.simonvt.cathode.R;
import net.simonvt.cathode.api.enumeration.ItemType;
import net.simonvt.cathode.api.enumeration.ShowStatus;
import net.simonvt.cathode.api.util.TraktUtils;
import net.simonvt.cathode.database.SimpleCursor;
import net.simonvt.cathode.database.SimpleCursorLoader;
import net.simonvt.cathode.database.SimpleMergeCursor;
import net.simonvt.cathode.images.ImageType;
import net.simonvt.cathode.images.ImageUri;
import net.simonvt.cathode.jobqueue.Job;
import net.simonvt.cathode.provider.CollectLoader;
import net.simonvt.cathode.provider.DatabaseContract;
import net.simonvt.cathode.provider.DatabaseContract.CommentColumns;
import net.simonvt.cathode.provider.DatabaseContract.EpisodeColumns;
import net.simonvt.cathode.provider.DatabaseContract.HiddenColumns;
import net.simonvt.cathode.provider.DatabaseContract.PersonColumns;
import net.simonvt.cathode.provider.DatabaseContract.RelatedShowsColumns;
import net.simonvt.cathode.provider.DatabaseContract.ShowCastColumns;
import net.simonvt.cathode.provider.DatabaseContract.ShowColumns;
import net.simonvt.cathode.provider.DatabaseContract.ShowGenreColumns;
import net.simonvt.cathode.provider.DatabaseContract.UserColumns;
import net.simonvt.cathode.provider.DatabaseSchematic.Tables;
import net.simonvt.cathode.provider.ProviderSchematic;
import net.simonvt.cathode.provider.ProviderSchematic.Comments;
import net.simonvt.cathode.provider.ProviderSchematic.RelatedShows;
import net.simonvt.cathode.provider.ProviderSchematic.Seasons;
import net.simonvt.cathode.provider.ProviderSchematic.ShowGenres;
import net.simonvt.cathode.provider.ProviderSchematic.Shows;
import net.simonvt.cathode.provider.WatchedLoader;
import net.simonvt.cathode.scheduler.EpisodeTaskScheduler;
import net.simonvt.cathode.scheduler.PersonTaskScheduler;
import net.simonvt.cathode.scheduler.ShowTaskScheduler;
import net.simonvt.cathode.settings.TraktTimestamps;
import net.simonvt.cathode.ui.LibraryType;
import net.simonvt.cathode.ui.NavigationListener;
import net.simonvt.cathode.ui.comments.LinearCommentsAdapter;
import net.simonvt.cathode.ui.dialog.CheckInDialog;
import net.simonvt.cathode.ui.dialog.CheckInDialog.Type;
import net.simonvt.cathode.ui.dialog.RatingDialog;
import net.simonvt.cathode.ui.fragment.RefreshableAppBarFragment;
import net.simonvt.cathode.ui.listener.SeasonClickListener;
import net.simonvt.cathode.ui.lists.ListsDialog;
import net.simonvt.cathode.util.DataHelper;
import net.simonvt.cathode.util.DateUtils;
import net.simonvt.cathode.util.Ids;
import net.simonvt.cathode.util.Intents;
import net.simonvt.cathode.util.SqlColumn;
import net.simonvt.cathode.widget.CircleTransformation;
import net.simonvt.cathode.widget.CircularProgressIndicator;
import net.simonvt.cathode.widget.HiddenPaneLayout;
import net.simonvt.cathode.widget.OverflowView;
import net.simonvt.cathode.widget.RecyclerViewManager;
import net.simonvt.cathode.widget.RemoteImageView;
import net.simonvt.schematic.Cursors;
import timber.log.Timber;
public class ShowFragment extends RefreshableAppBarFragment {
private static final String TAG = "net.simonvt.cathode.ui.show.ShowFragment";
private static final String ARG_SHOWID = "net.simonvt.cathode.ui.show.ShowFragment.showId";
private static final String ARG_TITLE = "net.simonvt.cathode.ui.show.ShowFragment.title";
private static final String ARG_OVERVIEW = "net.simonvt.cathode.ui.show.ShowFragment.overview";
private static final String ARG_TYPE = "net.simonvt.cathode.ui.show.ShowFragment.type";
private static final String DIALOG_RATING =
"net.simonvt.cathode.ui.show.ShowFragment.ratingDialog";
private static final String DIALOG_LISTS_ADD =
"net.simonvt.cathode.ui.show.ShowFragment.listsAddDialog";
private static final String DIALOG_COMMENT_UPDATE =
"net.simonvt.cathode.ui.show.ShowFragment.updateCommentDialog";
private static final int LOADER_SHOW = 1;
private static final int LOADER_SHOW_WATCH = 2;
private static final int LOADER_SHOW_COLLECT = 3;
private static final int LOADER_SHOW_GENRES = 4;
private static final int LOADER_SHOW_SEASONS = 5;
private static final int LOADER_SHOW_CAST = 6;
private static final int LOADER_SHOW_USER_COMMENTS = 7;
private static final int LOADER_SHOW_COMMENTS = 8;
private static final int LOADER_RELATED = 9;
private static final String[] SHOW_PROJECTION = new String[] {
ShowColumns.TRAKT_ID, ShowColumns.TITLE, ShowColumns.YEAR, ShowColumns.AIR_TIME,
ShowColumns.AIR_DAY, ShowColumns.NETWORK, ShowColumns.CERTIFICATION, ShowColumns.STATUS,
ShowColumns.USER_RATING, ShowColumns.RATING, ShowColumns.OVERVIEW, ShowColumns.IN_WATCHLIST,
ShowColumns.IN_COLLECTION_COUNT, ShowColumns.WATCHED_COUNT, ShowColumns.LAST_SYNC,
ShowColumns.LAST_COMMENT_SYNC, ShowColumns.LAST_CREDITS_SYNC, ShowColumns.LAST_RELATED_SYNC,
ShowColumns.HOMEPAGE, ShowColumns.TRAILER, ShowColumns.IMDB_ID, ShowColumns.TVDB_ID,
ShowColumns.TMDB_ID, ShowColumns.NEEDS_SYNC, HiddenColumns.HIDDEN_CALENDAR,
};
private static final String[] EPISODE_PROJECTION = new String[] {
EpisodeColumns.ID, EpisodeColumns.TITLE, EpisodeColumns.FIRST_AIRED, EpisodeColumns.SEASON,
EpisodeColumns.EPISODE, EpisodeColumns.WATCHING, EpisodeColumns.CHECKED_IN,
};
private static final String[] GENRES_PROJECTION = new String[] {
ShowGenreColumns.GENRE,
};
@Inject PersonTaskScheduler personScheduler;
private NavigationListener navigationListener;
private long showId;
@BindView(R.id.hiddenPaneLayout) HiddenPaneLayout hiddenPaneLayout;
@BindView(R.id.seasons) RecyclerView seasons;
@BindView(R.id.seasonsEmpty) View seasonsEmpty;
private SeasonsAdapter seasonsAdapter;
private Cursor seasonsCursor;
@BindView(R.id.rating) CircularProgressIndicator rating;
@BindView(R.id.airtime) TextView airTime;
@BindView(R.id.status) TextView status;
@BindView(R.id.overview) TextView overview;
@BindView(R.id.genresTitle) View genresTitle;
@BindView(R.id.genres) TextView genres;
@BindView(R.id.isWatched) TextView watched;
@BindView(R.id.inCollection) TextView collection;
@BindView(R.id.inWatchlist) TextView watchlist;
@BindView(R.id.trailer) View trailer;
@BindView(R.id.castParent) View castParent;
@BindView(R.id.castHeader) View castHeader;
@BindView(R.id.cast) LinearLayout cast;
@BindView(R.id.castContainer) LinearLayout castContainer;
@BindView(R.id.commentsParent) View commentsParent;
@BindView(R.id.commentsHeader) View commentsHeader;
@BindView(R.id.commentsContainer) LinearLayout commentsContainer;
@BindView(R.id.relatedParent) View relatedParent;
@BindView(R.id.relatedHeader) View relatedHeader;
@BindView(R.id.related) LinearLayout related;
@BindView(R.id.relatedContainer) LinearLayout relatedContainer;
@BindView(R.id.websiteTitle) View websiteTitle;
@BindView(R.id.website) TextView website;
@BindView(R.id.viewOnTrakt) View viewOnTrakt;
@BindView(R.id.viewOnImdb) View viewOnImdb;
@BindView(R.id.viewOnTvdb) View viewOnTvdb;
@BindView(R.id.viewOnTmdb) View viewOnTmdb;
private Cursor userComments;
private Cursor comments;
@BindView(R.id.episodes) LinearLayout episodes;
@BindView(R.id.toWatch) View toWatch;
private EpisodeHolder toWatchHolder;
private long toWatchId = -1;
private String toWatchTitle;
@BindView(R.id.lastWatched) @Nullable View lastWatched;
private EpisodeHolder lastWatchedHolder;
private long lastWatchedId = -1;
@BindView(R.id.toCollect) View toCollect;
private EpisodeHolder toCollectHolder;
private long toCollectId = -1;
@BindView(R.id.lastCollected) @Nullable View lastCollected;
private EpisodeHolder lastCollectedHolder;
private long lastCollectedId = -1;
static class EpisodeHolder {
@BindView(R.id.episodeScreenshot) RemoteImageView episodeScreenshot;
@BindView(R.id.episodeTitle) TextView episodeTitle;
@BindView(R.id.episodeAirTime) TextView episodeAirTime;
@BindView(R.id.episodeEpisode) TextView episodeEpisode;
@BindView(R.id.episodeOverflow) OverflowView episodeOverflow;
public EpisodeHolder(View v) {
ButterKnife.bind(this, v);
}
}
@Inject ShowTaskScheduler showScheduler;
@Inject EpisodeTaskScheduler episodeScheduler;
private String showTitle;
private String showOverview;
private boolean inWatchlist;
private int currentRating;
private boolean calendarHidden;
private LibraryType type;
RecyclerViewManager seasonsManager;
public static String getTag(long showId) {
return TAG + "/" + showId + "/" + Ids.newId();
}
public static Bundle getArgs(long showId, String title, String overview, LibraryType type) {
if (showId < 0) {
throw new IllegalArgumentException("showId must be >= 0");
}
Bundle args = new Bundle();
args.putLong(ARG_SHOWID, showId);
args.putString(ARG_TITLE, title);
args.putString(ARG_OVERVIEW, overview);
args.putSerializable(ARG_TYPE, type);
return args;
}
public long getShowId() {
return showId;
}
@Override public void onAttach(Activity activity) {
super.onAttach(activity);
navigationListener = (NavigationListener) activity;
}
@Override public void onCreate(Bundle inState) {
super.onCreate(inState);
Timber.d("ShowFragment#onCreate");
CathodeApp.inject(getActivity(), this);
Bundle args = getArguments();
showId = args.getLong(ARG_SHOWID);
showTitle = args.getString(ARG_TITLE);
showOverview = args.getString(ARG_OVERVIEW);
type = (LibraryType) args.getSerializable(ARG_TYPE);
setTitle(showTitle);
seasonsAdapter = new SeasonsAdapter(getActivity(), new SeasonClickListener() {
@Override
public void onSeasonClick(long showId, long seasonId, String showTitle, int seasonNumber) {
navigationListener.onDisplaySeason(showId, seasonId, showTitle, seasonNumber, type);
}
}, type);
}
@Override public boolean onBackPressed() {
if (hiddenPaneLayout != null) {
final int state = hiddenPaneLayout.getState();
if (state == HiddenPaneLayout.STATE_OPEN || state == HiddenPaneLayout.STATE_OPENING) {
hiddenPaneLayout.close();
return true;
}
}
return super.onBackPressed();
}
@Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle inState) {
HiddenPaneLayout hiddenPane =
(HiddenPaneLayout) inflater.inflate(R.layout.fragment_show_hiddenpanelayout, container,
false);
View v = super.onCreateView(inflater, hiddenPane, inState);
hiddenPane.addView(v);
inflater.inflate(R.layout.fragment_show_seasons, hiddenPane, true);
return hiddenPane;
}
@Override public View createView(LayoutInflater inflater, ViewGroup container, Bundle inState) {
return inflater.inflate(R.layout.fragment_show, container, false);
}
@Override public void onViewCreated(View view, Bundle inState) {
super.onViewCreated(view, inState);
overview.setText(showOverview);
seasonsManager =
new RecyclerViewManager(seasons, new LinearLayoutManager(getActivity()), seasonsEmpty);
seasonsManager.setAdapter(seasonsAdapter);
seasons.setAdapter(seasonsAdapter);
((DefaultItemAnimator) seasons.getItemAnimator()).setSupportsChangeAnimations(false);
rating.setOnClickListener(new View.OnClickListener() {
@Override public void onClick(View view) {
RatingDialog.newInstance(RatingDialog.Type.SHOW, showId, currentRating)
.show(getFragmentManager(), DIALOG_RATING);
}
});
castHeader.setOnClickListener(new View.OnClickListener() {
@Override public void onClick(View v) {
navigationListener.onDisplayCredits(ItemType.SHOW, showId, showTitle);
}
});
commentsHeader.setOnClickListener(new View.OnClickListener() {
@Override public void onClick(View v) {
navigationListener.onDisplayComments(ItemType.SHOW, showId);
}
});
relatedHeader.setOnClickListener(new View.OnClickListener() {
@Override public void onClick(View v) {
navigationListener.onDisplayRelatedShows(showId, showTitle);
}
});
toWatchHolder = new EpisodeHolder(toWatch);
toWatch.setOnClickListener(new View.OnClickListener() {
@Override public void onClick(View view) {
if (toWatchId != -1) navigationListener.onDisplayEpisode(toWatchId, showTitle);
}
});
toWatchHolder.episodeOverflow.setListener(new OverflowView.OverflowActionListener() {
@Override public void onPopupShown() {
}
@Override public void onPopupDismissed() {
}
@Override public void onActionSelected(int action) {
switch (action) {
case R.id.action_checkin:
if (toWatchId != -1) {
CheckInDialog.showDialogIfNecessary(getActivity(), Type.SHOW, toWatchTitle,
toWatchId);
}
break;
case R.id.action_checkin_cancel:
if (toWatchId != -1) {
showScheduler.cancelCheckin();
}
break;
case R.id.action_watched:
if (toWatchId != -1) {
episodeScheduler.setWatched(toWatchId, true);
}
break;
}
}
});
if (lastWatched != null) {
lastWatchedHolder = new EpisodeHolder(lastWatched);
lastWatched.setOnClickListener(new View.OnClickListener() {
@Override public void onClick(View view) {
if (lastWatchedId != -1) {
navigationListener.onDisplayEpisode(lastWatchedId, showTitle);
}
}
});
lastWatchedHolder.episodeOverflow.addItem(R.id.action_unwatched, R.string.action_unwatched);
lastWatchedHolder.episodeOverflow.setListener(new OverflowView.OverflowActionListener() {
@Override public void onPopupShown() {
}
@Override public void onPopupDismissed() {
}
@Override public void onActionSelected(int action) {
switch (action) {
case R.id.action_unwatched:
if (lastWatchedId != -1) {
episodeScheduler.setWatched(lastWatchedId, false);
}
break;
}
}
});
}
toCollectHolder = new EpisodeHolder(toCollect);
toCollect.setOnClickListener(new View.OnClickListener() {
@Override public void onClick(View view) {
if (toCollectId != -1) navigationListener.onDisplayEpisode(toCollectId, showTitle);
}
});
toCollectHolder.episodeOverflow.addItem(R.id.action_collection_add,
R.string.action_collection_add);
toCollectHolder.episodeOverflow.setListener(new OverflowView.OverflowActionListener() {
@Override public void onPopupShown() {
}
@Override public void onPopupDismissed() {
}
@Override public void onActionSelected(int action) {
switch (action) {
case R.id.action_collection_add:
if (toCollectId != -1) {
episodeScheduler.setIsInCollection(toCollectId, true);
}
break;
}
}
});
if (lastCollected != null) {
lastCollectedHolder = new EpisodeHolder(lastCollected);
lastCollected.setOnClickListener(new View.OnClickListener() {
@Override public void onClick(View view) {
if (lastCollectedId != -1) {
navigationListener.onDisplayEpisode(lastCollectedId, showTitle);
}
}
});
lastCollectedHolder.episodeOverflow.addItem(R.id.action_collection_remove,
R.string.action_collection_remove);
lastCollectedHolder.episodeOverflow.setListener(new OverflowView.OverflowActionListener() {
@Override public void onPopupShown() {
}
@Override public void onPopupDismissed() {
}
@Override public void onActionSelected(int action) {
switch (action) {
case R.id.action_collection_add:
if (lastCollectedId != -1) {
episodeScheduler.setIsInCollection(lastCollectedId, true);
}
break;
}
}
});
}
getLoaderManager().initLoader(LOADER_SHOW, null, showCallbacks);
getLoaderManager().initLoader(LOADER_SHOW_GENRES, null, genreCallbacks);
getLoaderManager().initLoader(LOADER_SHOW_CAST, null, castCallback);
getLoaderManager().initLoader(LOADER_SHOW_WATCH, null, episodeWatchCallbacks);
getLoaderManager().initLoader(LOADER_SHOW_COLLECT, null, episodeCollectCallbacks);
getLoaderManager().initLoader(LOADER_SHOW_SEASONS, null, seasonsLoader);
getLoaderManager().initLoader(LOADER_SHOW_USER_COMMENTS, null, userCommentsLoader);
getLoaderManager().initLoader(LOADER_SHOW_COMMENTS, null, commentsLoader);
getLoaderManager().initLoader(LOADER_RELATED, null, relatedLoader);
}
private Job.OnDoneListener onDoneListener = new Job.OnDoneListener() {
@Override public void onDone(Job job) {
setRefreshing(false);
}
};
@Override public void onRefresh() {
showScheduler.sync(showId, onDoneListener);
}
@Override public void createMenu(Toolbar toolbar) {
super.createMenu(toolbar);
Menu menu = toolbar.getMenu();
toolbar.inflateMenu(R.menu.fragment_show);
if (inWatchlist) {
menu.add(0, R.id.action_watchlist_remove, 300, R.string.action_watchlist_remove);
} else {
menu.add(0, R.id.action_watchlist_add, 300, R.string.action_watchlist_add);
}
if (calendarHidden) {
menu.add(0, R.id.action_calendar_unhide, 400, R.string.action_calendar_unhide);
} else {
menu.add(0, R.id.action_calendar_hide, 400, R.string.action_calendar_hide);
}
}
@Override public boolean onMenuItemClick(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_seasons:
hiddenPaneLayout.toggle();
return true;
case R.id.action_watchlist_remove:
showScheduler.setIsInWatchlist(showId, false);
return true;
case R.id.action_watchlist_add:
showScheduler.setIsInWatchlist(showId, true);
return true;
case R.id.menu_lists_add:
ListsDialog.newInstance(DatabaseContract.ItemType.SHOW, showId)
.show(getFragmentManager(), DIALOG_LISTS_ADD);
return true;
case R.id.action_calendar_hide:
showScheduler.hideFromCalendar(showId, true);
return true;
case R.id.action_calendar_unhide:
showScheduler.hideFromCalendar(showId, false);
return true;
}
return super.onMenuItemClick(item);
}
private void updateShowView(final Cursor cursor) {
if (cursor == null || !cursor.moveToFirst()) return;
final long traktId = Cursors.getLong(cursor, ShowColumns.TRAKT_ID);
String title = Cursors.getString(cursor, ShowColumns.TITLE);
if (!TextUtils.equals(title, showTitle)) {
showTitle = title;
setTitle(title);
}
final String airTime = Cursors.getString(cursor, ShowColumns.AIR_TIME);
final String airDay = Cursors.getString(cursor, ShowColumns.AIR_DAY);
final String network = Cursors.getString(cursor, ShowColumns.NETWORK);
final String certification = Cursors.getString(cursor, ShowColumns.CERTIFICATION);
final ShowStatus status = ShowStatus.fromValue(Cursors.getString(cursor, ShowColumns.STATUS));
final String backdropUri = ImageUri.create(ImageUri.ITEM_SHOW, ImageType.BACKDROP, showId);
setBackdrop(backdropUri, true);
showOverview = Cursors.getString(cursor, ShowColumns.OVERVIEW);
inWatchlist = Cursors.getBoolean(cursor, ShowColumns.IN_WATCHLIST);
final int inCollectionCount = Cursors.getInt(cursor, ShowColumns.IN_COLLECTION_COUNT);
final int watchedCount = Cursors.getInt(cursor, ShowColumns.WATCHED_COUNT);
currentRating = Cursors.getInt(cursor, ShowColumns.USER_RATING);
final float ratingAll = Cursors.getFloat(cursor, ShowColumns.RATING);
rating.setValue(ratingAll);
calendarHidden = Cursors.getBoolean(cursor, HiddenColumns.HIDDEN_CALENDAR);
watched.setVisibility(watchedCount > 0 ? View.VISIBLE : View.GONE);
collection.setVisibility(inCollectionCount > 0 ? View.VISIBLE : View.GONE);
watchlist.setVisibility(inWatchlist ? View.VISIBLE : View.GONE);
String airTimeString = null;
if (airDay != null && airTime != null) {
airTimeString = airDay + " " + airTime;
}
if (network != null) {
if (airTimeString != null) {
airTimeString += ", " + network;
} else {
airTimeString = network;
}
}
if (certification != null) {
if (airTimeString != null) {
airTimeString += ", " + certification;
} else {
airTimeString = certification;
}
}
this.airTime.setText(airTimeString);
String statusString = null;
switch (status) {
case ENDED:
statusString = getString(R.string.show_status_ended);
break;
case RETURNING:
statusString = getString(R.string.show_status_returning);
break;
case CANCELED:
statusString = getString(R.string.show_status_canceled);
break;
case IN_PRODUCTION:
statusString = getString(R.string.show_status_in_production);
break;
case PLANNED:
statusString = getString(R.string.show_status_planned);
break;
}
this.status.setText(statusString);
this.overview.setText(showOverview);
final String trailer = Cursors.getString(cursor, ShowColumns.TRAILER);
if (!TextUtils.isEmpty(trailer)) {
this.trailer.setVisibility(View.VISIBLE);
this.trailer.setOnClickListener(new View.OnClickListener() {
@Override public void onClick(View v) {
Intents.openUrl(getActivity(), trailer);
}
});
} else {
this.trailer.setVisibility(View.GONE);
}
final boolean needsSync = Cursors.getBoolean(cursor, ShowColumns.NEEDS_SYNC);
if (needsSync) {
Timber.d("Needs sync: %d", showId);
showScheduler.sync(showId);
}
final long lastSync = Cursors.getLong(cursor, ShowColumns.LAST_SYNC);
final long lastCommentSync = Cursors.getLong(cursor, ShowColumns.LAST_COMMENT_SYNC);
if (TraktTimestamps.shouldSyncComments(lastCommentSync)) {
showScheduler.syncComments(showId);
}
final long lastActorsSync = Cursors.getLong(cursor, ShowColumns.LAST_CREDITS_SYNC);
if (lastSync > lastActorsSync) {
showScheduler.syncCredits(showId, null);
}
final long lastRelatedSync = Cursors.getLong(cursor, ShowColumns.LAST_RELATED_SYNC);
if (lastSync > lastRelatedSync) {
showScheduler.syncRelated(showId, null);
}
final String website = Cursors.getString(cursor, ShowColumns.HOMEPAGE);
if (!TextUtils.isEmpty(website)) {
this.websiteTitle.setVisibility(View.VISIBLE);
this.website.setVisibility(View.VISIBLE);
this.website.setText(website);
this.website.setOnClickListener(new View.OnClickListener() {
@Override public void onClick(View v) {
Intents.openUrl(getContext(), website);
}
});
} else {
this.websiteTitle.setVisibility(View.GONE);
this.website.setVisibility(View.GONE);
}
final String imdbId = Cursors.getString(cursor, ShowColumns.IMDB_ID);
final int tvdbId = Cursors.getInt(cursor, ShowColumns.TVDB_ID);
final int tmdbId = Cursors.getInt(cursor, ShowColumns.TMDB_ID);
viewOnTrakt.setOnClickListener(new View.OnClickListener() {
@Override public void onClick(View v) {
Intents.openUrl(getContext(), TraktUtils.getTraktShowUrl(traktId));
}
});
final boolean hasImdbId = !TextUtils.isEmpty(imdbId);
if (hasImdbId) {
viewOnImdb.setVisibility(View.VISIBLE);
viewOnImdb.setOnClickListener(new View.OnClickListener() {
@Override public void onClick(View v) {
Intents.openUrl(getContext(), TraktUtils.getImdbUrl(imdbId));
}
});
} else {
viewOnImdb.setVisibility(View.GONE);
}
if (tvdbId > 0) {
viewOnTvdb.setVisibility(View.VISIBLE);
viewOnTvdb.setOnClickListener(new View.OnClickListener() {
@Override public void onClick(View v) {
Intents.openUrl(getContext(), TraktUtils.getTvdbUrl(tvdbId));
}
});
} else {
viewOnTvdb.setVisibility(View.GONE);
}
if (tmdbId > 0) {
viewOnTmdb.setVisibility(View.VISIBLE);
viewOnTmdb.setOnClickListener(new View.OnClickListener() {
@Override public void onClick(View v) {
Intents.openUrl(getContext(), TraktUtils.getTmdbTvUrl(tmdbId));
}
});
} else {
viewOnTmdb.setVisibility(View.GONE);
}
invalidateMenu();
}
private void updateGenreViews(final Cursor cursor) {
if (cursor.getCount() > 0) {
StringBuilder sb = new StringBuilder();
final int genreColumnIndex = cursor.getColumnIndex(ShowGenreColumns.GENRE);
cursor.moveToPosition(-1);
while (cursor.moveToNext()) {
sb.append(cursor.getString(genreColumnIndex));
if (!cursor.isLast()) sb.append(", ");
}
genresTitle.setVisibility(View.VISIBLE);
genres.setVisibility(View.VISIBLE);
genres.setText(sb.toString());
} else {
genresTitle.setVisibility(View.GONE);
genres.setVisibility(View.GONE);
}
}
private void updateCastViews(Cursor c) {
castContainer.removeAllViews();
final int count = c.getCount();
final int visibility = count > 0 ? View.VISIBLE : View.GONE;
castParent.setVisibility(visibility);
int index = 0;
c.moveToPosition(-1);
while (c.moveToNext() && index < 3) {
View v =
LayoutInflater.from(getActivity()).inflate(R.layout.item_person, castContainer, false);
final long personId = Cursors.getLong(c, ShowCastColumns.PERSON_ID);
final String headshotUrl = ImageUri.create(ImageUri.ITEM_PERSON, ImageType.PROFILE, personId);
RemoteImageView headshot = (RemoteImageView) v.findViewById(R.id.headshot);
headshot.addTransformation(new CircleTransformation());
headshot.setImage(headshotUrl);
TextView name = (TextView) v.findViewById(R.id.person_name);
name.setText(Cursors.getString(c, PersonColumns.NAME));
TextView character = (TextView) v.findViewById(R.id.person_job);
character.setText(Cursors.getString(c, ShowCastColumns.CHARACTER));
v.setOnClickListener(new View.OnClickListener() {
@Override public void onClick(View v) {
navigationListener.onDisplayPerson(personId);
}
});
castContainer.addView(v);
index++;
}
}
private void updateRelatedView(Cursor related) {
relatedContainer.removeAllViews();
final int count = related.getCount();
final int visibility = count > 0 ? View.VISIBLE : View.GONE;
relatedParent.setVisibility(visibility);
int index = 0;
related.moveToPosition(-1);
while (related.moveToNext() && index < 3) {
View v = LayoutInflater.from(getActivity())
.inflate(R.layout.item_related, this.relatedContainer, false);
final long relatedShowId = Cursors.getLong(related, RelatedShowsColumns.RELATED_SHOW_ID);
final String title = Cursors.getString(related, ShowColumns.TITLE);
final String overview = Cursors.getString(related, ShowColumns.OVERVIEW);
final float rating = Cursors.getFloat(related, ShowColumns.RATING);
final int votes = Cursors.getInt(related, ShowColumns.VOTES);
final String poster = ImageUri.create(ImageUri.ITEM_SHOW, ImageType.POSTER, relatedShowId);
RemoteImageView posterView = (RemoteImageView) v.findViewById(R.id.related_poster);
posterView.addTransformation(new CircleTransformation());
posterView.setImage(poster);
TextView titleView = (TextView) v.findViewById(R.id.related_title);
titleView.setText(title);
final String formattedRating = String.format(Locale.getDefault(), "%.1f", rating);
String ratingText;
if (votes >= 1000) {
final float convertedVotes = votes / 1000.0f;
final String formattedVotes = String.format(Locale.getDefault(), "%.1f", convertedVotes);
ratingText = getString(R.string.related_rating_thousands, formattedRating, formattedVotes);
} else {
ratingText = getString(R.string.related_rating, formattedRating, votes);
}
TextView ratingView = (TextView) v.findViewById(R.id.related_rating);
ratingView.setText(ratingText);
v.setOnClickListener(new View.OnClickListener() {
@Override public void onClick(View v) {
navigationListener.onDisplayShow(relatedShowId, title, overview, LibraryType.WATCHED);
}
});
relatedContainer.addView(v);
index++;
}
}
private void updateEpisodeWatchViews(Cursor cursor) {
if (cursor.moveToFirst()) {
toWatch.setVisibility(View.VISIBLE);
toWatchId = Cursors.getLong(cursor, EpisodeColumns.ID);
final long firstAired = DataHelper.getFirstAired(cursor);
final int season = Cursors.getInt(cursor, EpisodeColumns.SEASON);
final int episode = Cursors.getInt(cursor, EpisodeColumns.EPISODE);
toWatchTitle = DataHelper.getEpisodeTitle(getContext(), cursor, season, episode);
final String toWatchEpisodeText = getString(R.string.season_x_episode_y, season, episode);
toWatchHolder.episodeTitle.setText(toWatchTitle);
toWatchHolder.episodeEpisode.setText(toWatchEpisodeText);
final String screenshotUri =
ImageUri.create(ImageUri.ITEM_EPISODE, ImageType.STILL, toWatchId);
toWatchHolder.episodeScreenshot.setImage(screenshotUri);
String firstAiredString = DateUtils.millisToString(getActivity(), firstAired, false);
final boolean watching = Cursors.getBoolean(cursor, EpisodeColumns.WATCHING);
final boolean checkedIn = Cursors.getBoolean(cursor, EpisodeColumns.CHECKED_IN);
toWatchHolder.episodeOverflow.removeItems();
if (checkedIn) {
toWatchHolder.episodeOverflow.addItem(R.id.action_checkin_cancel,
R.string.action_checkin_cancel);
firstAiredString = getResources().getString(R.string.show_watching);
} else if (!watching) {
toWatchHolder.episodeOverflow.addItem(R.id.action_checkin, R.string.action_checkin);
toWatchHolder.episodeOverflow.addItem(R.id.action_watched, R.string.action_watched);
}
toWatchHolder.episodeAirTime.setText(firstAiredString);
} else {
toWatch.setVisibility(View.GONE);
toWatchId = -1;
}
if (lastWatched != null) {
if (cursor.moveToNext()) {
lastWatched.setVisibility(View.VISIBLE);
lastWatchedId = Cursors.getLong(cursor, EpisodeColumns.ID);
final int season = Cursors.getInt(cursor, EpisodeColumns.SEASON);
final int episode = Cursors.getInt(cursor, EpisodeColumns.EPISODE);
final String title = DataHelper.getEpisodeTitle(getContext(), cursor, season, episode);
lastWatchedHolder.episodeTitle.setText(title);
final long firstAired = DataHelper.getFirstAired(cursor);
final String firstAiredString = DateUtils.millisToString(getActivity(), firstAired, false);
lastWatchedHolder.episodeAirTime.setText(firstAiredString);
final String lastWatchedEpisodeText =
getString(R.string.season_x_episode_y, season, episode);
lastWatchedHolder.episodeEpisode.setText(lastWatchedEpisodeText);
final String screenshotUri =
ImageUri.create(ImageUri.ITEM_EPISODE, ImageType.STILL, lastWatchedId);
lastWatchedHolder.episodeScreenshot.setImage(screenshotUri);
} else {
lastWatched.setVisibility(toWatchId == -1 ? View.GONE : View.INVISIBLE);
lastWatchedId = -1;
}
}
if (toWatchId == -1 && lastWatchedId == -1 && toCollectId == -1 && lastCollectedId == -1) {
episodes.setVisibility(View.GONE);
} else {
episodes.setVisibility(View.VISIBLE);
}
}
private void updateEpisodeCollectViews(Cursor cursor) {
if (cursor.moveToFirst()) {
toCollect.setVisibility(View.VISIBLE);
toCollectId = Cursors.getLong(cursor, EpisodeColumns.ID);
final int season = Cursors.getInt(cursor, EpisodeColumns.SEASON);
final int episode = Cursors.getInt(cursor, EpisodeColumns.EPISODE);
final String title = DataHelper.getEpisodeTitle(getContext(), cursor, season, episode);
toCollectHolder.episodeTitle.setText(title);
final long firstAired = DataHelper.getFirstAired(cursor);
final String firstAiredString = DateUtils.millisToString(getActivity(), firstAired, false);
toCollectHolder.episodeAirTime.setText(firstAiredString);
final String toCollectEpisodeText = getString(R.string.season_x_episode_y, season, episode);
toCollectHolder.episodeEpisode.setText(toCollectEpisodeText);
final String screenshotUri =
ImageUri.create(ImageUri.ITEM_EPISODE, ImageType.STILL, toCollectId);
toCollectHolder.episodeScreenshot.setImage(screenshotUri);
} else {
toCollect.setVisibility(View.GONE);
toCollectId = -1;
}
if (lastCollected != null) {
if (cursor.moveToNext()) {
lastCollected.setVisibility(View.VISIBLE);
lastCollectedId = Cursors.getLong(cursor, EpisodeColumns.ID);
final int season = Cursors.getInt(cursor, EpisodeColumns.SEASON);
final int episode = Cursors.getInt(cursor, EpisodeColumns.EPISODE);
final String title = DataHelper.getEpisodeTitle(getContext(), cursor, season, episode);
lastCollectedHolder.episodeTitle.setText(title);
final long firstAired = DataHelper.getFirstAired(cursor);
final String firstAiredString = DateUtils.millisToString(getActivity(), firstAired, false);
lastCollectedHolder.episodeAirTime.setText(firstAiredString);
final String lastCollectedEpisodeText =
getString(R.string.season_x_episode_y, season, episode);
lastCollectedHolder.episodeEpisode.setText(lastCollectedEpisodeText);
final String screenshotUri =
ImageUri.create(ImageUri.ITEM_EPISODE, ImageType.STILL, lastCollectedId);
lastCollectedHolder.episodeScreenshot.setImage(screenshotUri);
} else {
lastCollectedId = -1;
lastCollected.setVisibility(View.INVISIBLE);
}
}
if (toWatchId == -1 && lastWatchedId == -1 && toCollectId == -1 && lastCollectedId == -1) {
episodes.setVisibility(View.GONE);
} else {
episodes.setVisibility(View.VISIBLE);
}
}
private void updateComments() {
LinearCommentsAdapter.updateComments(getContext(), commentsContainer, userComments, comments);
commentsParent.setVisibility(View.VISIBLE);
}
private LoaderManager.LoaderCallbacks<SimpleCursor> showCallbacks =
new LoaderManager.LoaderCallbacks<SimpleCursor>() {
@Override public Loader<SimpleCursor> onCreateLoader(int id, Bundle args) {
return new SimpleCursorLoader(getActivity(), Shows.withId(showId), SHOW_PROJECTION, null,
null, null);
}
@Override public void onLoadFinished(Loader<SimpleCursor> cursorLoader, SimpleCursor data) {
updateShowView(data);
}
@Override public void onLoaderReset(Loader<SimpleCursor> cursorLoader) {
}
};
private LoaderManager.LoaderCallbacks<SimpleCursor> genreCallbacks =
new LoaderManager.LoaderCallbacks<SimpleCursor>() {
@Override public Loader<SimpleCursor> onCreateLoader(int id, Bundle args) {
return new SimpleCursorLoader(getActivity(), ShowGenres.fromShow(showId),
GENRES_PROJECTION, null, null, ShowGenres.DEFAULT_SORT);
}
@Override public void onLoadFinished(Loader<SimpleCursor> cursorLoader, SimpleCursor data) {
updateGenreViews(data);
}
@Override public void onLoaderReset(Loader<SimpleCursor> cursorLoader) {
}
};
private static final String[] CAST_PROJECTION = new String[] {
Tables.SHOW_CAST + "." + ShowCastColumns.ID,
Tables.SHOW_CAST + "." + ShowCastColumns.CHARACTER,
Tables.SHOW_CAST + "." + ShowCastColumns.PERSON_ID, Tables.PEOPLE + "." + PersonColumns.NAME,
};
private LoaderManager.LoaderCallbacks<SimpleCursor> castCallback =
new LoaderManager.LoaderCallbacks<SimpleCursor>() {
@Override public Loader<SimpleCursor> onCreateLoader(int id, Bundle args) {
return new SimpleCursorLoader(getActivity(), ProviderSchematic.ShowCast.fromShow(showId),
CAST_PROJECTION, Tables.PEOPLE + "." + PersonColumns.NEEDS_SYNC + "=0", null, null);
}
@Override public void onLoadFinished(Loader<SimpleCursor> loader, SimpleCursor data) {
updateCastViews(data);
}
@Override public void onLoaderReset(Loader<SimpleCursor> loader) {
}
};
private LoaderManager.LoaderCallbacks<SimpleMergeCursor> episodeWatchCallbacks =
new LoaderManager.LoaderCallbacks<SimpleMergeCursor>() {
@Override public Loader<SimpleMergeCursor> onCreateLoader(int i, Bundle bundle) {
return new WatchedLoader(getActivity(), showId, EPISODE_PROJECTION);
}
@Override public void onLoadFinished(Loader<SimpleMergeCursor> cursorLoader,
SimpleMergeCursor cursor) {
updateEpisodeWatchViews(cursor);
}
@Override public void onLoaderReset(Loader<SimpleMergeCursor> cursorLoader) {
}
};
private LoaderManager.LoaderCallbacks<SimpleMergeCursor> episodeCollectCallbacks =
new LoaderManager.LoaderCallbacks<SimpleMergeCursor>() {
@Override public Loader<SimpleMergeCursor> onCreateLoader(int i, Bundle bundle) {
return new CollectLoader(getActivity(), showId, EPISODE_PROJECTION);
}
@Override public void onLoadFinished(Loader<SimpleMergeCursor> cursorLoader,
SimpleMergeCursor cursor) {
updateEpisodeCollectViews(cursor);
}
@Override public void onLoaderReset(Loader<SimpleMergeCursor> cursorLoader) {
}
};
private LoaderManager.LoaderCallbacks<SimpleCursor> seasonsLoader =
new LoaderManager.LoaderCallbacks<SimpleCursor>() {
@Override public Loader<SimpleCursor> onCreateLoader(int id, Bundle args) {
return new SimpleCursorLoader(getActivity(), Seasons.fromShow(showId),
SeasonsAdapter.PROJECTION, null, null, Seasons.DEFAULT_SORT);
}
@Override public void onLoadFinished(Loader<SimpleCursor> cursorLoader, SimpleCursor data) {
seasonsCursor = data;
seasonsAdapter.changeCursor(data);
}
@Override public void onLoaderReset(Loader<SimpleCursor> cursorLoader) {
seasonsCursor = null;
seasonsAdapter.changeCursor(null);
}
};
private static final String[] COMMENTS_PROJECTION = new String[] {
SqlColumn.table(Tables.COMMENTS).column(CommentColumns.ID),
SqlColumn.table(Tables.COMMENTS).column(CommentColumns.COMMENT),
SqlColumn.table(Tables.COMMENTS).column(CommentColumns.SPOILER),
SqlColumn.table(Tables.COMMENTS).column(CommentColumns.REVIEW),
SqlColumn.table(Tables.COMMENTS).column(CommentColumns.CREATED_AT),
SqlColumn.table(Tables.COMMENTS).column(CommentColumns.LIKES),
SqlColumn.table(Tables.COMMENTS).column(CommentColumns.USER_RATING),
SqlColumn.table(Tables.USERS).column(UserColumns.USERNAME),
SqlColumn.table(Tables.USERS).column(UserColumns.NAME),
SqlColumn.table(Tables.USERS).column(UserColumns.AVATAR),
};
private LoaderManager.LoaderCallbacks<SimpleCursor> userCommentsLoader =
new LoaderManager.LoaderCallbacks<SimpleCursor>() {
@Override public Loader<SimpleCursor> onCreateLoader(int id, Bundle args) {
return new SimpleCursorLoader(getContext(), Comments.fromShow(showId),
COMMENTS_PROJECTION, CommentColumns.IS_USER_COMMENT + "=1", null, null);
}
@Override public void onLoadFinished(Loader<SimpleCursor> loader, SimpleCursor data) {
userComments = data;
updateComments();
}
@Override public void onLoaderReset(Loader<SimpleCursor> loader) {
}
};
private LoaderManager.LoaderCallbacks<SimpleCursor> commentsLoader =
new LoaderManager.LoaderCallbacks<SimpleCursor>() {
@Override public Loader<SimpleCursor> onCreateLoader(int id, Bundle args) {
return new SimpleCursorLoader(getContext(), Comments.fromShow(showId),
COMMENTS_PROJECTION,
CommentColumns.IS_USER_COMMENT + "=0 AND " + CommentColumns.SPOILER + "=0", null,
CommentColumns.LIKES + " DESC LIMIT 3");
}
@Override public void onLoadFinished(Loader<SimpleCursor> loader, SimpleCursor data) {
comments = data;
updateComments();
}
@Override public void onLoaderReset(Loader<SimpleCursor> loader) {
}
};
private static final String[] RELATED_PROJECTION = new String[] {
SqlColumn.table(Tables.SHOW_RELATED).column(RelatedShowsColumns.RELATED_SHOW_ID),
SqlColumn.table(Tables.SHOWS).column(ShowColumns.TITLE),
SqlColumn.table(Tables.SHOWS).column(ShowColumns.OVERVIEW),
SqlColumn.table(Tables.SHOWS).column(ShowColumns.RATING),
SqlColumn.table(Tables.SHOWS).column(ShowColumns.VOTES),
};
private LoaderManager.LoaderCallbacks<SimpleCursor> relatedLoader =
new LoaderManager.LoaderCallbacks<SimpleCursor>() {
@Override public Loader<SimpleCursor> onCreateLoader(int id, Bundle args) {
return new SimpleCursorLoader(getContext(), RelatedShows.fromShow(showId),
RELATED_PROJECTION, null, null, RelatedShowsColumns.RELATED_INDEX + " ASC LIMIT 3");
}
@Override public void onLoadFinished(Loader<SimpleCursor> loader, SimpleCursor data) {
updateRelatedView(data);
}
@Override public void onLoaderReset(Loader<SimpleCursor> loader) {
}
};
}
| Handle case where ShowStatus is null.
| cathode/src/main/java/net/simonvt/cathode/ui/show/ShowFragment.java | Handle case where ShowStatus is null. | <ide><path>athode/src/main/java/net/simonvt/cathode/ui/show/ShowFragment.java
<ide> final String airDay = Cursors.getString(cursor, ShowColumns.AIR_DAY);
<ide> final String network = Cursors.getString(cursor, ShowColumns.NETWORK);
<ide> final String certification = Cursors.getString(cursor, ShowColumns.CERTIFICATION);
<del> final ShowStatus status = ShowStatus.fromValue(Cursors.getString(cursor, ShowColumns.STATUS));
<add> final String showStatus = Cursors.getString(cursor, ShowColumns.STATUS);
<ide> final String backdropUri = ImageUri.create(ImageUri.ITEM_SHOW, ImageType.BACKDROP, showId);
<ide> setBackdrop(backdropUri, true);
<ide> showOverview = Cursors.getString(cursor, ShowColumns.OVERVIEW);
<ide> this.airTime.setText(airTimeString);
<ide>
<ide> String statusString = null;
<del> switch (status) {
<del> case ENDED:
<del> statusString = getString(R.string.show_status_ended);
<del> break;
<del>
<del> case RETURNING:
<del> statusString = getString(R.string.show_status_returning);
<del> break;
<del>
<del> case CANCELED:
<del> statusString = getString(R.string.show_status_canceled);
<del> break;
<del>
<del> case IN_PRODUCTION:
<del> statusString = getString(R.string.show_status_in_production);
<del> break;
<del>
<del> case PLANNED:
<del> statusString = getString(R.string.show_status_planned);
<del> break;
<add> if (showStatus != null) {
<add> final ShowStatus status = ShowStatus.fromValue(showStatus);
<add>
<add> switch (status) {
<add> case ENDED:
<add> statusString = getString(R.string.show_status_ended);
<add> break;
<add>
<add> case RETURNING:
<add> statusString = getString(R.string.show_status_returning);
<add> break;
<add>
<add> case CANCELED:
<add> statusString = getString(R.string.show_status_canceled);
<add> break;
<add>
<add> case IN_PRODUCTION:
<add> statusString = getString(R.string.show_status_in_production);
<add> break;
<add>
<add> case PLANNED:
<add> statusString = getString(R.string.show_status_planned);
<add> break;
<add> }
<ide> }
<ide>
<ide> this.status.setText(statusString); |
|
Java | apache-2.0 | 4b3f5ad358e69a36ed97edc83d41f3161a2dc14c | 0 | vipshop/Saturn,vipshop/Saturn,vipshop/Saturn,vipshop/Saturn,vipshop/Saturn | package com.vip.saturn.job.basic;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map.Entry;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicBoolean;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import ch.qos.logback.classic.LoggerContext;
import sun.misc.Signal;
import sun.misc.SignalHandler;
/**
* Saturn优雅退出: 退出时清理信息
* @author dylan.xue
*/
@SuppressWarnings("restriction")
public class ShutdownHandler implements SignalHandler {
private static Logger log = LoggerFactory.getLogger(ShutdownHandler.class);
private static ConcurrentHashMap<String, List<Runnable>> listeners = new ConcurrentHashMap<>();
private static List<Runnable> globalListeners = new ArrayList<>();
private static ShutdownHandler handler;
private static volatile boolean exit = true;
private final AtomicBoolean handling = new AtomicBoolean(false);
static {
handler = new ShutdownHandler();
Signal.handle(new Signal("TERM"), handler); // 相当于kill -15
Signal.handle(new Signal("INT"), handler); // 相当于Ctrl+C
}
public static void addShutdownCallback(Runnable c) {
globalListeners.add(c);
}
public static void addShutdownCallback(String executorName, Runnable c) {
if (!listeners.containsKey(executorName)) {
listeners.putIfAbsent(executorName, new ArrayList<Runnable>());
}
listeners.get(executorName).add(c);
}
public static void removeShutdownCallback(String executorName) {
listeners.remove(executorName);
}
public static void exitAfterHandler(boolean exit) {
ShutdownHandler.exit = exit;
}
@Override
public void handle(Signal sn) {
if (handling.compareAndSet(false, true)) {
try {
doHandle(sn);
} finally {
handling.set(false);
}
}
}
private void doHandle(Signal sn) {
log.info("msg=Received the kill command");
Iterator<Entry<String, List<Runnable>>> iterator = listeners.entrySet().iterator();
while (iterator.hasNext()) {
Entry<String, List<Runnable>> next = iterator.next();
List<Runnable> value = next.getValue();
for (Runnable runnable : value) {
try {
if (runnable != null) {
runnable.run();
}
} catch (Exception e) {
log.error("msg=" + e.getMessage(), e);
}
}
}
listeners.clear();
for (Runnable runnable : globalListeners) {
try {
if (runnable != null) {
runnable.run();
}
} catch (Exception e) {
log.error("msg=" + e.getMessage(), e);
}
}
globalListeners.clear();
log.info("msg=Saturn executor is closed");
if (exit) {
LoggerContext loggerContext = (LoggerContext) LoggerFactory.getILoggerFactory();
loggerContext.stop();
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace(); // NOSONAR
}
System.exit(-1);
}
}
}
| saturn-core/src/main/java/com/vip/saturn/job/basic/ShutdownHandler.java | package com.vip.saturn.job.basic;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map.Entry;
import java.util.concurrent.ConcurrentHashMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import ch.qos.logback.classic.LoggerContext;
import sun.misc.Signal;
import sun.misc.SignalHandler;
/**
* Saturn优雅退出: 退出时清理信息
* @author dylan.xue
*/
@SuppressWarnings("restriction")
public class ShutdownHandler implements SignalHandler {
private static Logger log = LoggerFactory.getLogger(ShutdownHandler.class);
private static ConcurrentHashMap<String, List<Runnable>> listeners = new ConcurrentHashMap<>();
private static List<Runnable> globalListeners = new ArrayList<>();
private static ShutdownHandler handler;
private static volatile boolean exit = true;
static {
handler = new ShutdownHandler();
Signal.handle(new Signal("TERM"), handler); // 相当于kill -15
Signal.handle(new Signal("INT"), handler); // 相当于Ctrl+C
}
public static void addShutdownCallback(Runnable c) {
globalListeners.add(c);
}
public static void addShutdownCallback(String executorName, Runnable c) {
if (!listeners.containsKey(executorName)) {
listeners.putIfAbsent(executorName, new ArrayList<Runnable>());
}
listeners.get(executorName).add(c);
}
public static void removeShutdownCallback(String executorName) {
listeners.remove(executorName);
}
public static void exitAfterHandler(boolean exit) {
ShutdownHandler.exit = exit;
}
@Override
public void handle(Signal sn) {
log.info("msg=Received the kill command");
Iterator<Entry<String, List<Runnable>>> iterator = listeners.entrySet().iterator();
while (iterator.hasNext()) {
Entry<String, List<Runnable>> next = iterator.next();
List<Runnable> value = next.getValue();
for (Runnable runnable : value) {
try {
if (runnable != null) {
runnable.run();
}
} catch (Exception e) {
log.error("msg=" + e.getMessage(), e);
}
}
}
listeners.clear();
for (Runnable runnable : globalListeners) {
try {
if (runnable != null) {
runnable.run();
}
} catch (Exception e) {
log.error("msg=" + e.getMessage(), e);
}
}
globalListeners.clear();
log.info("msg=Saturn executor is closed");
if (exit) {
LoggerContext loggerContext = (LoggerContext) LoggerFactory.getILoggerFactory();
loggerContext.stop();
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace(); // NOSONAR
}
System.exit(-1);
}
}
}
| #277 fix shutdow handle | saturn-core/src/main/java/com/vip/saturn/job/basic/ShutdownHandler.java | #277 fix shutdow handle | <ide><path>aturn-core/src/main/java/com/vip/saturn/job/basic/ShutdownHandler.java
<ide> import java.util.List;
<ide> import java.util.Map.Entry;
<ide> import java.util.concurrent.ConcurrentHashMap;
<add>import java.util.concurrent.atomic.AtomicBoolean;
<ide>
<ide> import org.slf4j.Logger;
<ide> import org.slf4j.LoggerFactory;
<ide>
<ide> private static ShutdownHandler handler;
<ide> private static volatile boolean exit = true;
<add>
<add> private final AtomicBoolean handling = new AtomicBoolean(false);
<ide>
<ide> static {
<ide> handler = new ShutdownHandler();
<ide>
<ide> @Override
<ide> public void handle(Signal sn) {
<add> if (handling.compareAndSet(false, true)) {
<add> try {
<add> doHandle(sn);
<add> } finally {
<add> handling.set(false);
<add> }
<add> }
<add> }
<add>
<add> private void doHandle(Signal sn) {
<ide> log.info("msg=Received the kill command");
<ide>
<ide> Iterator<Entry<String, List<Runnable>>> iterator = listeners.entrySet().iterator();
<ide> System.exit(-1);
<ide> }
<ide> }
<del>
<ide> } |
|
Java | mit | 6446b27b7072a92e440fb5fc736f81f30bcf49ca | 0 | AmadouSallah/Programming-Interview-Questions,AmadouSallah/Programming-Interview-Questions | /*
Leetcode Problem 114: Flatten Binary Tree to Linked List
https://leetcode.com/problems/flatten-binary-tree-to-linked-list/description/
Given a binary tree, flatten it to a linked list in-place.
For example, given the following tree:
1
/ \
2 5
/ \ \
3 4 6
The flattened tree should look like:
1
\
2
\
3
\
4
\
5
\
6
*/
import java.util.Stack;
public class FlattenBinaryTree {
public static class TreeNode {
int value;
TreeNode left, right;
public TreeNode(int value) {
this.value = value;
}
}
public static void flatten(TreeNode root) {
if (root == null) return;
Stack<TreeNode> stack = new Stack<>();
stack.push(root);
TreeNode current;
while (!stack.isEmpty()) {
current = stack.pop();
if (current.right != null) stack.push(current.right);
if (current.left != null) stack.push(current.left);
current.left = null;
if (!stack.isEmpty()) current.right = stack.peek();
}
}
}
| leetcode/java/prob114FlattenBinaryTree/FlattenBinaryTree.java | /*
Leetcode Problem 114: Flatten Binary Tree to Linked List
https://leetcode.com/problems/flatten-binary-tree-to-linked-list/description/
Given a binary tree, flatten it to a linked list in-place.
For example, given the following tree:
1
/ \
2 5
/ \ \
3 4 6
The flattened tree should look like:
1
\
2
\
3
\
4
\
5
\
6
*/
| Added solution for FlattenBinaryTree.java
| leetcode/java/prob114FlattenBinaryTree/FlattenBinaryTree.java | Added solution for FlattenBinaryTree.java | <ide><path>eetcode/java/prob114FlattenBinaryTree/FlattenBinaryTree.java
<ide> \
<ide> 6
<ide> */
<add>import java.util.Stack;
<add>
<add>public class FlattenBinaryTree {
<add>
<add> public static class TreeNode {
<add> int value;
<add> TreeNode left, right;
<add> public TreeNode(int value) {
<add> this.value = value;
<add> }
<add> }
<add> public static void flatten(TreeNode root) {
<add> if (root == null) return;
<add> Stack<TreeNode> stack = new Stack<>();
<add> stack.push(root);
<add> TreeNode current;
<add>
<add> while (!stack.isEmpty()) {
<add> current = stack.pop();
<add> if (current.right != null) stack.push(current.right);
<add> if (current.left != null) stack.push(current.left);
<add>
<add> current.left = null;
<add> if (!stack.isEmpty()) current.right = stack.peek();
<add> }
<add> }
<add>} |
|
Java | apache-2.0 | c1c3a60a56565d39e93ea92e0819ce5c19bf9146 | 0 | SeanRoy/lambda-maven-plugin | package com.github.seanroy.plugins;
import static com.amazonaws.services.lambda.model.EventSourcePosition.LATEST;
import static java.util.Optional.empty;
import static java.util.Optional.of;
import static java.util.Optional.ofNullable;
import static java.util.stream.Collectors.toList;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.UUID;
import java.util.function.BiFunction;
import java.util.function.BiPredicate;
import java.util.function.Function;
import java.util.stream.Collectors;
import com.amazonaws.services.lambda.AWSLambda;
import com.amazonaws.services.s3.AmazonS3;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.logging.Log;
import org.apache.maven.plugins.annotations.Mojo;
import com.amazonaws.auth.policy.Policy;
import com.amazonaws.auth.policy.Statement;
import com.amazonaws.services.cloudwatchevents.model.DeleteRuleRequest;
import com.amazonaws.services.cloudwatchevents.model.DescribeRuleRequest;
import com.amazonaws.services.cloudwatchevents.model.DescribeRuleResult;
import com.amazonaws.services.cloudwatchevents.model.ListRuleNamesByTargetRequest;
import com.amazonaws.services.cloudwatchevents.model.PutRuleRequest;
import com.amazonaws.services.cloudwatchevents.model.PutRuleResult;
import com.amazonaws.services.cloudwatchevents.model.PutTargetsRequest;
import com.amazonaws.services.cloudwatchevents.model.RemoveTargetsRequest;
import com.amazonaws.services.cloudwatchevents.model.Target;
import com.amazonaws.services.dynamodbv2.model.DescribeStreamRequest;
import com.amazonaws.services.dynamodbv2.model.ListStreamsRequest;
import com.amazonaws.services.dynamodbv2.model.ListStreamsResult;
import com.amazonaws.services.dynamodbv2.model.Stream;
import com.amazonaws.services.dynamodbv2.model.StreamDescription;
import com.amazonaws.services.lambda.model.AddPermissionRequest;
import com.amazonaws.services.lambda.model.AddPermissionResult;
import com.amazonaws.services.lambda.model.AliasConfiguration;
import com.amazonaws.services.lambda.model.CreateAliasRequest;
import com.amazonaws.services.lambda.model.CreateEventSourceMappingRequest;
import com.amazonaws.services.lambda.model.CreateEventSourceMappingResult;
import com.amazonaws.services.lambda.model.CreateFunctionRequest;
import com.amazonaws.services.lambda.model.CreateFunctionResult;
import com.amazonaws.services.lambda.model.DeleteEventSourceMappingRequest;
import com.amazonaws.services.lambda.model.Environment;
import com.amazonaws.services.lambda.model.EventSourceMappingConfiguration;
import com.amazonaws.services.lambda.model.EventSourcePosition;
import com.amazonaws.services.lambda.model.FunctionCode;
import com.amazonaws.services.lambda.model.GetFunctionRequest;
import com.amazonaws.services.lambda.model.GetFunctionResult;
import com.amazonaws.services.lambda.model.GetPolicyRequest;
import com.amazonaws.services.lambda.model.GetPolicyResult;
import com.amazonaws.services.lambda.model.ListAliasesRequest;
import com.amazonaws.services.lambda.model.ListAliasesResult;
import com.amazonaws.services.lambda.model.ListEventSourceMappingsRequest;
import com.amazonaws.services.lambda.model.ListEventSourceMappingsResult;
import com.amazonaws.services.lambda.model.RemovePermissionRequest;
import com.amazonaws.services.lambda.model.ResourceNotFoundException;
import com.amazonaws.services.lambda.model.UpdateAliasRequest;
import com.amazonaws.services.lambda.model.UpdateEventSourceMappingRequest;
import com.amazonaws.services.lambda.model.UpdateEventSourceMappingResult;
import com.amazonaws.services.lambda.model.UpdateFunctionCodeRequest;
import com.amazonaws.services.lambda.model.UpdateFunctionCodeResult;
import com.amazonaws.services.lambda.model.UpdateFunctionConfigurationRequest;
import com.amazonaws.services.lambda.model.VpcConfig;
import com.amazonaws.services.lambda.model.VpcConfigResponse;
import com.amazonaws.services.s3.model.AmazonS3Exception;
import com.amazonaws.services.s3.model.ObjectMetadata;
import com.amazonaws.services.s3.model.PutObjectResult;
import com.amazonaws.services.sns.model.CreateTopicRequest;
import com.amazonaws.services.sns.model.CreateTopicResult;
import com.amazonaws.services.sns.model.ListSubscriptionsResult;
import com.amazonaws.services.sns.model.SubscribeRequest;
import com.amazonaws.services.sns.model.SubscribeResult;
import com.amazonaws.services.sns.model.Subscription;
import com.amazonaws.services.sns.model.UnsubscribeRequest;
/**
* I am a deploy mojo responsible to upload and create or update lambda function in AWS.
*
* @author Sean N. Roy, <a href="mailto:[email protected]">Sean Roy</a> 11/08/16.
*/
@Mojo(name = "deploy-lambda")
public class DeployLambdaMojo extends AbstractLambdaMojo {
@Override
public void execute() throws MojoExecutionException {
super.execute();
try {
final LambdaCodeComparisonOutcome codeDeployOutcome = uploadJarToS3();
lambdaFunctions.stream()
.peek(f ->
getLog().info("---- Create or update " + f.getFunctionName() + " -----"))
.forEach(lf -> {
// check if we need to update
final GetFunctionResult functionResult = getLambdaFunction(lambdaClient, lf.getFunctionName());
final Function<LambdaFunction, LambdaFunction> updateFunction;
updateFunction = shouldUpdate(lf, functionResult, codeDeployOutcome)
? createOrUpdate
: Function.identity();
// clean up and update
getFunctionPolicy
.andThen(cleanUpOrphans)
.andThen(updateFunction)
.apply(lf);
});
} catch (Exception e) {
getLog().error("Error during processing", e);
throw new MojoExecutionException(e.getMessage());
}
}
private boolean shouldUpdate(
LambdaFunction lambdaFunction, GetFunctionResult getFunctionResult,
LambdaCodeComparisonOutcome codeDeployOutcome) {
// shortcut: if function does not exist we need to deploy
if (getFunctionResult == null) {
getLog().info(String.format("Deploy. Function %s does not exist.", lambdaFunction.getFunctionName()));
return true;
}
boolean isConfigurationChanged = isConfigurationChanged(lambdaFunction, getFunctionResult);
if (!isConfigurationChanged) {
getLog().info(String.format("Config hasn't changed for %s.", lambdaFunction.getFunctionName()));
}
if (forceUpdate) {
getLog().info(String.format("Deploy. Update forced for %s.", lambdaFunction.getFunctionName()));
}
if (codeDeployOutcome.shouldUpdateS3) {
getLog().info(String.format("Deploy. Local function code differs with S3 for %s.", lambdaFunction.getFunctionName()));
}
return forceUpdate || isConfigurationChanged || codeDeployOutcome.shouldUpdateS3;
}
/*
* Get the existing policy function (on updates) and assign it to the lambdaFunction.
*/
private Function<LambdaFunction, LambdaFunction> getFunctionPolicy = (LambdaFunction lambdaFunction) -> {
try {
lambdaFunction.setExistingPolicy(Policy.fromJson(lambdaClient.getPolicy(new GetPolicyRequest()
.withFunctionName(lambdaFunction.getFunctionName())
.withQualifier(lambdaFunction.getQualifier())).getPolicy()));
} catch (ResourceNotFoundException rnfe3) {
getLog().debug("Probably creating a new function, policy doesn't exist yet: " + rnfe3.getMessage());
}
return lambdaFunction;
};
private Function<LambdaFunction, LambdaFunction> updateFunctionCode = (LambdaFunction lambdaFunction) -> {
getLog().info("About to update functionCode for " + lambdaFunction.getFunctionName());
UpdateFunctionCodeRequest updateFunctionRequest = new UpdateFunctionCodeRequest()
.withFunctionName(lambdaFunction.getFunctionName())
.withS3Bucket(s3Bucket)
.withS3Key(fileName)
.withPublish(lambdaFunction.isPublish());
UpdateFunctionCodeResult updateFunctionCodeResult = lambdaClient.updateFunctionCode(updateFunctionRequest);
return lambdaFunction
.withVersion(updateFunctionCodeResult.getVersion())
.withFunctionArn(updateFunctionCodeResult.getFunctionArn());
};
private Function<LambdaFunction, LambdaFunction> updateFunctionConfig = (LambdaFunction lambdaFunction) -> {
getLog().info("About to update functionConfig for " + lambdaFunction.getFunctionName());
UpdateFunctionConfigurationRequest updateFunctionRequest = new UpdateFunctionConfigurationRequest()
.withFunctionName(lambdaFunction.getFunctionName())
.withDescription(lambdaFunction.getDescription())
.withHandler(lambdaFunction.getHandler())
.withRole(lambdaRoleArn)
.withTimeout(lambdaFunction.getTimeout())
.withMemorySize(lambdaFunction.getMemorySize())
.withRuntime(runtime)
.withVpcConfig(getVpcConfig(lambdaFunction))
.withEnvironment(new Environment().withVariables(lambdaFunction.getEnvironmentVariables()));
lambdaClient.updateFunctionConfiguration(updateFunctionRequest);
return lambdaFunction;
};
private Function<LambdaFunction, LambdaFunction> createOrUpdateAliases = (LambdaFunction lambdaFunction) -> {
lambdaFunction.getAliases().forEach(alias -> {
UpdateAliasRequest updateAliasRequest = new UpdateAliasRequest()
.withFunctionName(lambdaFunction.getFunctionName())
.withFunctionVersion(lambdaFunction.getVersion())
.withName(alias);
try {
lambdaClient.updateAlias(updateAliasRequest
);
getLog().info("Alias " + alias + " updated for " + lambdaFunction.getFunctionName() + " with version " + lambdaFunction.getVersion());
} catch (ResourceNotFoundException ignored) {
CreateAliasRequest createAliasRequest = new CreateAliasRequest()
.withFunctionName(lambdaFunction.getFunctionName())
.withFunctionVersion(lambdaFunction.getVersion())
.withName(alias);
lambdaClient.createAlias(createAliasRequest);
getLog().info("Alias " + alias + " created for " + lambdaFunction.getFunctionName() + " with version " + lambdaFunction.getVersion());
}
});
return lambdaFunction;
};
private BiFunction<Trigger, LambdaFunction, Trigger> createOrUpdateSNSTopicSubscription = (Trigger trigger, LambdaFunction lambdaFunction) -> {
getLog().info("About to create or update " + trigger.getIntegration() + " trigger for " + trigger.getSNSTopic());
CreateTopicRequest createTopicRequest = new CreateTopicRequest()
.withName(trigger.getSNSTopic());
CreateTopicResult createTopicResult = snsClient.createTopic(createTopicRequest);
getLog().info("Topic " + createTopicResult.getTopicArn() + " created");
SubscribeRequest subscribeRequest = new SubscribeRequest()
.withTopicArn(createTopicResult.getTopicArn())
.withEndpoint(lambdaFunction.getUnqualifiedFunctionArn())
.withProtocol("lambda");
SubscribeResult subscribeResult = snsClient.subscribe(subscribeRequest);
getLog().info("Lambda function " + lambdaFunction.getFunctionName() + " subscribed to " + createTopicResult.getTopicArn());
getLog().info("Created " + trigger.getIntegration() + " trigger " + subscribeResult.getSubscriptionArn());
Optional<Statement> statementOpt;
try {
GetPolicyRequest getPolicyRequest = new GetPolicyRequest()
.withFunctionName(lambdaFunction.getFunctionName());
GetPolicyResult GetPolicyResult = lambdaClient.getPolicy(getPolicyRequest);
statementOpt = Policy.fromJson(GetPolicyResult.getPolicy()).getStatements().stream()
.filter(statement -> statement.getActions().stream().anyMatch(e -> PERM_LAMBDA_INVOKE.equals(e.getActionName())) &&
statement.getPrincipals().stream().anyMatch(principal -> PRINCIPAL_SNS.equals(principal.getId())) &&
statement.getConditions().stream().anyMatch(condition -> condition.getValues().stream().anyMatch(s -> Objects.equals(createTopicResult.getTopicArn(), s)))
).findAny();
} catch (ResourceNotFoundException ignored) {
// no policy found
statementOpt = empty();
}
if (!statementOpt.isPresent()) {
AddPermissionRequest addPermissionRequest = new AddPermissionRequest()
.withAction(PERM_LAMBDA_INVOKE)
.withPrincipal(PRINCIPAL_SNS)
.withSourceArn(createTopicResult.getTopicArn())
.withFunctionName(lambdaFunction.getFunctionName())
.withStatementId(UUID.randomUUID().toString());
AddPermissionResult addPermissionResult = lambdaClient.addPermission(addPermissionRequest);
getLog().debug("Added permission to lambda function " + addPermissionResult.toString());
}
return trigger;
};
/**
* TODO: Much of this code can be factored out into an addPermission function.
*/
private BiFunction<Trigger, LambdaFunction, Trigger> addAlexaSkillsKitPermission = (Trigger trigger, LambdaFunction lambdaFunction) -> {
if (!ofNullable(lambdaFunction.getExistingPolicy()).orElse(new Policy()).getStatements().stream().anyMatch(s ->
s.getId().equals(getAlexaPermissionStatementId()))) {
getLog().info("Granting invoke permission to " + trigger.getIntegration());
AddPermissionRequest addPermissionRequest = new AddPermissionRequest()
.withAction(PERM_LAMBDA_INVOKE)
.withPrincipal(PRINCIPAL_ALEXA)
.withFunctionName(lambdaFunction.getFunctionName())
.withQualifier(lambdaFunction.getQualifier())
.withStatementId(getAlexaPermissionStatementId());
AddPermissionResult addPermissionResult = lambdaClient.addPermission(addPermissionRequest);
}
return trigger;
};
private String getAlexaPermissionStatementId() {
return "lambda-maven-plugin-alexa-" + regionName + "-permission";
}
/**
* TODO: Much of this code can be factored out into an addPermission function.
*/
private BiFunction<Trigger, LambdaFunction, Trigger> addLexPermission = (Trigger trigger, LambdaFunction lambdaFunction) -> {
if (!ofNullable(lambdaFunction.getExistingPolicy()).orElse(new Policy()).getStatements().stream().anyMatch(s ->
s.getId().equals(getLexPermissionStatementId(trigger.getLexBotName())))) {
getLog().info("Granting invoke permission to Lex bot " + trigger.getLexBotName());
AddPermissionRequest addPermissionRequest = new AddPermissionRequest()
.withAction(PERM_LAMBDA_INVOKE)
.withPrincipal(PRINCIPAL_LEX)
.withFunctionName(lambdaFunction.getFunctionName())
.withQualifier(lambdaFunction.getQualifier())
.withStatementId(getLexPermissionStatementId(trigger.getLexBotName()));
AddPermissionResult addPermissionResult = lambdaClient.addPermission(addPermissionRequest);
}
return trigger;
};
private String getLexPermissionStatementId(String botName) {
return "lambda-maven-plugin-lex-" + regionName + "-permission-" + botName;
}
private BiFunction<Trigger, LambdaFunction, Trigger> createOrUpdateScheduledRule = (Trigger trigger, LambdaFunction lambdaFunction) -> {
// TODO: I hate that these checks are done twice, but for the time being it beats updates that just didn't work.
if ( isScheduleRuleChanged(lambdaFunction) || isKeepAliveChanged(lambdaFunction)) {
getLog().info("About to create or update " + trigger.getIntegration() + " trigger for " + trigger.getRuleName());
PutRuleRequest putRuleRequest = new PutRuleRequest()
.withName(trigger.getRuleName())
.withDescription(trigger.getRuleDescription())
.withScheduleExpression(trigger.getScheduleExpression());
PutRuleResult putRuleResult = eventsClient.putRule(putRuleRequest);
getLog().info("Created " + trigger.getIntegration() + " trigger " + putRuleResult.getRuleArn());
AddPermissionRequest addPermissionRequest = new AddPermissionRequest()
.withAction(PERM_LAMBDA_INVOKE)
.withPrincipal(PRINCIPAL_EVENTS)
.withSourceArn(putRuleResult.getRuleArn())
.withFunctionName(lambdaFunction.getFunctionName())
.withStatementId(UUID.randomUUID().toString());
AddPermissionResult addPermissionResult = lambdaClient.addPermission(addPermissionRequest);
getLog().debug("Added permission to lambda function " + addPermissionResult.toString());
PutTargetsRequest putTargetsRequest = new PutTargetsRequest()
.withRule(trigger.getRuleName())
.withTargets(new Target().withId("1").withArn(lambdaFunction.getUnqualifiedFunctionArn()));
eventsClient.putTargets(putTargetsRequest);
}
return trigger;
};
private Function<LambdaFunction, LambdaFunction> createOrUpdateKeepAlive = (LambdaFunction lambdaFunction) -> {
if (isKeepAliveChanged(lambdaFunction)) {
ofNullable(lambdaFunction.getKeepAlive()).flatMap(f -> {
if ( f > 0 ) {
getLog().info("Setting keepAlive to " + f + " minutes.");
createOrUpdateScheduledRule.apply(new Trigger()
.withIntegration("Function Keep Alive")
.withDescription(String.format("This feature pings function %s every %d %s.",
lambdaFunction.getFunctionName(), f,
f > 1 ? "minutes" : "minute"))
.withRuleName(lambdaFunction.getKeepAliveRuleName())
.withScheduleExpression(lambdaFunction.getKeepAliveScheduleExpression()),
lambdaFunction);
}
return Optional.of(f);
});
}
return lambdaFunction;
};
private BiFunction<Trigger, LambdaFunction, Trigger> createOrUpdateDynamoDBTrigger = (Trigger trigger, LambdaFunction lambdaFunction) -> {
getLog().info("About to create or update " + trigger.getIntegration() + " trigger for " + trigger.getDynamoDBTable());
ListStreamsRequest listStreamsRequest = new ListStreamsRequest().withTableName(trigger.getDynamoDBTable());
ListStreamsResult listStreamsResult = dynamoDBStreamsClient.listStreams(listStreamsRequest);
String streamArn = listStreamsResult.getStreams().stream()
.filter(s -> Objects.equals(trigger.getDynamoDBTable(), s.getTableName()))
.findFirst()
.map(Stream::getStreamArn)
.orElseThrow(() -> new IllegalArgumentException("Unable to find stream for table " + trigger.getDynamoDBTable()));
return findorUpdateMappingConfiguration(trigger, lambdaFunction, streamArn);
};
private BiFunction<Trigger, LambdaFunction, Trigger> createOrUpdateKinesisStream = (Trigger trigger, LambdaFunction lambdaFunction) -> {
getLog().info("About to create or update " + trigger.getIntegration() + " trigger for " + trigger.getKinesisStream());
try {
return findorUpdateMappingConfiguration(trigger, lambdaFunction,
kinesisClient.describeStream(trigger.getKinesisStream()).getStreamDescription().getStreamARN());
} catch (Exception rnfe) {
getLog().info(rnfe.getMessage());
throw new IllegalArgumentException("Unable to find stream with name " + trigger.getKinesisStream());
}
};
private Trigger findorUpdateMappingConfiguration(Trigger trigger, LambdaFunction lambdaFunction, String streamArn) {
ListEventSourceMappingsRequest listEventSourceMappingsRequest = new ListEventSourceMappingsRequest()
.withFunctionName(lambdaFunction.getUnqualifiedFunctionArn());
ListEventSourceMappingsResult listEventSourceMappingsResult = lambdaClient.listEventSourceMappings(listEventSourceMappingsRequest);
Optional<EventSourceMappingConfiguration> eventSourceMappingConfiguration = listEventSourceMappingsResult.getEventSourceMappings().stream()
.filter(stream -> {
boolean isSameFunctionArn = Objects.equals(stream.getFunctionArn(), lambdaFunction.getUnqualifiedFunctionArn());
boolean isSameSourceArn = Objects.equals(stream.getEventSourceArn(), streamArn);
return isSameFunctionArn && isSameSourceArn;
})
.findFirst();
if (eventSourceMappingConfiguration.isPresent()) {
UpdateEventSourceMappingRequest updateEventSourceMappingRequest = new UpdateEventSourceMappingRequest()
.withUUID(eventSourceMappingConfiguration.get().getUUID())
.withFunctionName(lambdaFunction.getUnqualifiedFunctionArn())
.withBatchSize(ofNullable(trigger.getBatchSize()).orElse(10))
.withEnabled(ofNullable(trigger.getEnabled()).orElse(true));
UpdateEventSourceMappingResult updateEventSourceMappingResult = lambdaClient.updateEventSourceMapping(updateEventSourceMappingRequest);
trigger.withTriggerArn(updateEventSourceMappingResult.getEventSourceArn());
getLog().info("Updated " + trigger.getIntegration() + " trigger " + trigger.getTriggerArn());
} else {
CreateEventSourceMappingRequest createEventSourceMappingRequest = new CreateEventSourceMappingRequest()
.withFunctionName(lambdaFunction.getUnqualifiedFunctionArn())
.withEventSourceArn(streamArn)
.withBatchSize(ofNullable(trigger.getBatchSize()).orElse(10))
.withStartingPosition(EventSourcePosition.fromValue(ofNullable(trigger.getStartingPosition()).orElse(LATEST.toString())))
.withEnabled(ofNullable(trigger.getEnabled()).orElse(true));
CreateEventSourceMappingResult createEventSourceMappingResult = lambdaClient.createEventSourceMapping(createEventSourceMappingRequest);
trigger.withTriggerArn(createEventSourceMappingResult.getEventSourceArn());
getLog().info("Created " + trigger.getIntegration() + " trigger " + trigger.getTriggerArn());
}
return trigger;
}
private Function<LambdaFunction, LambdaFunction> createOrUpdateTriggers = (LambdaFunction lambdaFunction) -> {
lambdaFunction.getTriggers().forEach(trigger -> {
if (TRIG_INT_LABEL_CLOUDWATCH_EVENTS.equals(trigger.getIntegration())) {
createOrUpdateScheduledRule.apply(trigger, lambdaFunction);
} else if (TRIG_INT_LABEL_DYNAMO_DB.equals(trigger.getIntegration())) {
createOrUpdateDynamoDBTrigger.apply(trigger, lambdaFunction);
} else if (TRIG_INT_LABEL_KINESIS.equals(trigger.getIntegration())) {
createOrUpdateKinesisStream.apply(trigger, lambdaFunction);
} else if (TRIG_INT_LABEL_SNS.equals(trigger.getIntegration())) {
createOrUpdateSNSTopicSubscription.apply(trigger, lambdaFunction);
} else if (TRIG_INT_LABEL_ALEXA_SK.equals(trigger.getIntegration())) {
addAlexaSkillsKitPermission.apply(trigger, lambdaFunction);
} else if (TRIG_INT_LABEL_LEX.equals(trigger.getIntegration())) {
addLexPermission.apply(trigger, lambdaFunction);
} else {
throw new IllegalArgumentException("Unknown integration for trigger " + trigger.getIntegration() + ". Correct your configuration");
}
});
return lambdaFunction;
};
private GetFunctionResult getFunction(LambdaFunction lambdaFunction) {
return lambdaClient.getFunction(new GetFunctionRequest().withFunctionName(lambdaFunction.getFunctionName()));
}
private boolean isConfigurationChanged(LambdaFunction lambdaFunction, GetFunctionResult function) {
BiPredicate<String, String> isChangeStr = (s0, s1) -> !Objects.equals(s0, s1);
BiPredicate<Integer, Integer> isChangeInt = (i0, i1) -> !Objects.equals(i0, i1);
BiPredicate<List<String>, List<String>> isChangeList = (l0, l1) -> !(l0.containsAll(l1) && l1.containsAll(l0));
return of(function.getConfiguration())
.map(config -> {
VpcConfigResponse vpcConfig = config.getVpcConfig();
if (vpcConfig == null) {
vpcConfig = new VpcConfigResponse();
}
boolean isDescriptionChanged = isChangeStr.test(config.getDescription(), lambdaFunction.getDescription());
boolean isHandlerChanged = isChangeStr.test(config.getHandler(), lambdaFunction.getHandler());
boolean isRoleChanged = isChangeStr.test(config.getRole(), lambdaRoleArn);
boolean isTimeoutChanged = isChangeInt.test(config.getTimeout(), lambdaFunction.getTimeout());
boolean isMemoryChanged = isChangeInt.test(config.getMemorySize(), lambdaFunction.getMemorySize());
boolean isSecurityGroupIdsChanged = isChangeList.test(vpcConfig.getSecurityGroupIds(), lambdaFunction.getSecurityGroupIds());
boolean isVpcSubnetIdsChanged = isChangeList.test(vpcConfig.getSubnetIds(), lambdaFunction.getSubnetIds());
return isDescriptionChanged || isHandlerChanged || isRoleChanged || isTimeoutChanged || isMemoryChanged ||
isSecurityGroupIdsChanged || isVpcSubnetIdsChanged || isAliasesChanged(lambdaFunction) || isKeepAliveChanged(lambdaFunction) ||
isScheduleRuleChanged(lambdaFunction);
})
.orElse(true);
}
private boolean isKeepAliveChanged(LambdaFunction lambdaFunction) {
try {
return ofNullable(lambdaFunction.getKeepAlive()).map( ka -> {
DescribeRuleResult res = eventsClient.describeRule(new DescribeRuleRequest().withName(lambdaFunction.getKeepAliveRuleName()));
return !Objects.equals(res.getScheduleExpression(), lambdaFunction.getKeepAliveScheduleExpression());
}).orElse(false);
} catch( com.amazonaws.services.cloudwatchevents.model.ResourceNotFoundException ignored ) {
return true;
}
}
private boolean isScheduleRuleChanged(LambdaFunction lambdaFunction) {
try {
return lambdaFunction.getTriggers().stream().filter(t -> TRIG_INT_LABEL_CLOUDWATCH_EVENTS.equals(t.getIntegration())).anyMatch(trigger -> {
DescribeRuleResult res = eventsClient.describeRule(new DescribeRuleRequest().withName(trigger.getRuleName()));
return !(Objects.equals(res.getName(), trigger.getRuleName()) &&
Objects.equals(res.getDescription(), trigger.getRuleDescription()) &&
Objects.equals(res.getScheduleExpression(), trigger.getScheduleExpression()));
});
} catch( com.amazonaws.services.cloudwatchevents.model.ResourceNotFoundException ignored ) {
return true;
}
}
private boolean isAliasesChanged(LambdaFunction lambdaFunction) {
try {
ListAliasesResult listAliasesResult = lambdaClient.listAliases(new ListAliasesRequest()
.withFunctionName(lambdaFunction.getFunctionName()));
List<String> configuredAliases = listAliasesResult.getAliases().stream()
.map(AliasConfiguration::getName)
.collect(toList());
return !configuredAliases.containsAll(lambdaFunction.getAliases());
} catch (ResourceNotFoundException ignored) {
return true;
}
}
private Function<LambdaFunction, LambdaFunction> createFunction = (LambdaFunction lambdaFunction) -> {
getLog().info("About to create function " + lambdaFunction.getFunctionName());
CreateFunctionRequest createFunctionRequest = new CreateFunctionRequest()
.withDescription(lambdaFunction.getDescription())
.withRole(lambdaRoleArn)
.withFunctionName(lambdaFunction.getFunctionName())
.withHandler(lambdaFunction.getHandler())
.withRuntime(runtime)
.withTimeout(ofNullable(lambdaFunction.getTimeout()).orElse(timeout))
.withMemorySize(ofNullable(lambdaFunction.getMemorySize()).orElse(memorySize))
.withVpcConfig(getVpcConfig(lambdaFunction))
.withCode(new FunctionCode()
.withS3Bucket(s3Bucket)
.withS3Key(fileName))
.withEnvironment(new Environment().withVariables(lambdaFunction.getEnvironmentVariables()));
CreateFunctionResult createFunctionResult = lambdaClient.createFunction(createFunctionRequest);
lambdaFunction.withVersion(createFunctionResult.getVersion())
.withFunctionArn(createFunctionResult.getFunctionArn());
getLog().info("Function " + createFunctionResult.getFunctionName() + " created. Function Arn: " + createFunctionResult.getFunctionArn());
return lambdaFunction;
};
private VpcConfig getVpcConfig(LambdaFunction lambdaFunction) {
return new VpcConfig()
.withSecurityGroupIds(lambdaFunction.getSecurityGroupIds())
.withSubnetIds(lambdaFunction.getSubnetIds());
}
private LambdaCodeComparisonOutcome uploadJarToS3() throws IOException {
final File localFunctionCode = new File(functionCode);
final LambdaCodeComparisonOutcome outcome = compareCodeWithS3(localFunctionCode, s3Bucket, fileName, s3Client, getLog());
if (outcome.shouldUpdateS3) {
upload(localFunctionCode);
}
return outcome;
}
private static LambdaCodeComparisonOutcome compareCodeWithS3(
final File localDeliverable, final String s3Bucket, final String remoteS3File,
final AmazonS3 s3, final Log log) throws IOException {
String localMD5 = DigestUtils.md5Hex(new FileInputStream(localDeliverable));
log.debug(String.format("Local file's MD5 hash is %s.", localMD5));
final ObjectMetadata objectMetadata = getObjectMetadata(s3, s3Bucket, remoteS3File);
if (objectMetadata == null) {
return LambdaCodeComparisonOutcome.S3_OBJECT_MISSING;
}
final String remoteS3FileMD5 = objectMetadata.getETag();
log.info(String.format("%s exists in S3 with MD5 hash %s", remoteS3File, remoteS3FileMD5));
if (localMD5.equals(remoteS3FileMD5)) {
log.info(String.format("%s is up to date in AWS S3 bucket %s. Not uploading...", remoteS3File, s3Bucket));
return LambdaCodeComparisonOutcome.MD5_EQUALS;
} else {
log.info(String.format("Local file %s hash differs with file in AWS S3 bucket %s. Uploading...", localDeliverable, s3Bucket));
return LambdaCodeComparisonOutcome.MD5_DIFFERENT;
}
}
/**
* Remove orphaned kinesis stream triggers.
* TODO: Combine with cleanUpOrphanedDynamoDBTriggers.
*/
Function<LambdaFunction, LambdaFunction> cleanUpOrphanedKinesisTriggers = lambdaFunction -> {
ListEventSourceMappingsResult listEventSourceMappingsResult =
lambdaClient.listEventSourceMappings(new ListEventSourceMappingsRequest()
.withFunctionName(lambdaFunction.getUnqualifiedFunctionArn()));
List<String> streamNames = new ArrayList<String>();
// This nonsense is to prevent cleanupOrphanedDynamoDBTriggers from removing DynamoDB triggers
// and vice versa. Unfortunately this assumes that stream names won't be the same as table names.
lambdaFunction.getTriggers().stream().forEach(t -> {
ofNullable(t.getKinesisStream()).ifPresent(x -> streamNames.add(x));
ofNullable(t.getDynamoDBTable()).ifPresent(x -> streamNames.add(x));
});
listEventSourceMappingsResult.getEventSourceMappings().stream().forEach(s -> {
if ( s.getEventSourceArn().contains(":kinesis:") ) {
if ( ! streamNames.contains(kinesisClient.describeStream(new com.amazonaws.services.kinesis.model.DescribeStreamRequest()
.withStreamName(s.getEventSourceArn().substring(s.getEventSourceArn().lastIndexOf('/')+1)))
.getStreamDescription()
.getStreamName()) ){
getLog().info(" Removing orphaned Kinesis trigger for stream " + s.getEventSourceArn());
try {
lambdaClient.deleteEventSourceMapping(new DeleteEventSourceMappingRequest().withUUID(s.getUUID()));
} catch(Exception e8) {
getLog().error(" Error removing orphaned Kinesis trigger for stream " + s.getEventSourceArn());
}
}
}
});
return lambdaFunction;
};
/**
* Removes orphaned sns triggers.
*/
Function<LambdaFunction, LambdaFunction> cleanUpOrphanedSNSTriggers = lambdaFunction -> {
List<Subscription> subscriptions = new ArrayList<Subscription>();
ListSubscriptionsResult result = snsClient.listSubscriptions();
do {
subscriptions.addAll(result.getSubscriptions().stream().filter( sub -> {
return sub.getEndpoint().equals(lambdaFunction.getFunctionArn());
}).collect(Collectors.toList()));
result = snsClient.listSubscriptions(result.getNextToken());
} while( result.getNextToken() != null );
if (subscriptions.size() > 0 ) {
List<String> snsTopicNames = lambdaFunction.getTriggers().stream().map(t -> {
return ofNullable(t.getSNSTopic()).orElse("");
}).collect(Collectors.toList());
subscriptions.stream().forEach(s -> {
String topicName = s.getTopicArn().substring(s.getTopicArn().lastIndexOf(":")+1);
if (!snsTopicNames.contains(topicName)) {
getLog().info(" Removing orphaned SNS trigger for topic " + topicName);
try {
snsClient.unsubscribe(new UnsubscribeRequest().withSubscriptionArn(s.getSubscriptionArn()));
ofNullable(lambdaFunction.getExistingPolicy()).flatMap( policy -> {
policy.getStatements().stream()
.filter(
stmt -> stmt.getActions().stream().anyMatch( e -> PERM_LAMBDA_INVOKE.equals(e.getActionName())) &&
stmt.getPrincipals().stream().anyMatch(principal -> PRINCIPAL_SNS.equals(principal.getId())) &&
stmt.getResources().stream().anyMatch(r -> r.getId().equals(lambdaFunction.getFunctionArn()))
).forEach( st -> {
if( st.getConditions().stream().anyMatch(condition -> condition.getValues().contains(s.getTopicArn())) ) {
getLog().info(" Removing invoke permission for SNS trigger");
try {
lambdaClient.removePermission(new RemovePermissionRequest()
.withFunctionName(lambdaFunction.getFunctionName())
.withQualifier(lambdaFunction.getQualifier())
.withStatementId(st.getId()));
} catch (Exception e7) {
getLog().error(" Error removing invoke permission for SNS trigger");
}
}
});
return of(policy);
});
} catch(Exception e5) {
getLog().error(" Error removing SNS trigger for topic " + topicName);
}
}
});
}
return lambdaFunction;
};
/**
* Removes orphaned dynamo db triggers.
* TODO: Combine with cleanUpOrphanedKinesisTriggers
*/
Function<LambdaFunction, LambdaFunction> cleanUpOrphanedDynamoDBTriggers = lambdaFunction -> {
ListEventSourceMappingsResult listEventSourceMappingsResult =
lambdaClient.listEventSourceMappings(new ListEventSourceMappingsRequest()
.withFunctionName(lambdaFunction.getUnqualifiedFunctionArn()));
List<String> tableNames = new ArrayList<String>();
// This nonsense is to prevent cleanupOrphanedDynamoDBTriggers from removing DynamoDB triggers
// and vice versa. Unfortunately this assumes that stream names won't be the same as table names.
lambdaFunction.getTriggers().stream().forEach(t -> {
ofNullable(t.getKinesisStream()).ifPresent(x -> tableNames.add(x));
ofNullable(t.getDynamoDBTable()).ifPresent(x -> tableNames.add(x));
});
listEventSourceMappingsResult.getEventSourceMappings().stream().forEach(s -> {
if ( s.getEventSourceArn().contains(":dynamodb:")) {
StreamDescription sd = dynamoDBStreamsClient.describeStream(new DescribeStreamRequest()
.withStreamArn(s.getEventSourceArn())).getStreamDescription();
if ( ! tableNames.contains(sd.getTableName()) ) {
getLog().info(" Removing orphaned DynamoDB trigger for table " + sd.getTableName());
try {
lambdaClient.deleteEventSourceMapping(new DeleteEventSourceMappingRequest().withUUID(s.getUUID()));
} catch (Exception e4) {
getLog().error(" Error removing DynamoDB trigger for table " + sd.getTableName());
}
}
}
});
return lambdaFunction;
};
/**
* Removes the Alexa permission if it isn't found in the current configuration.
* TODO: Factor out code common with other orphan clean up functions.
*/
Function<LambdaFunction, LambdaFunction> cleanUpOrphanedAlexaSkillsTriggers = lambdaFunction -> {
ofNullable(lambdaFunction.getExistingPolicy()).flatMap( policy -> {
policy.getStatements().stream()
.filter(
stmt -> stmt.getActions().stream().anyMatch( e -> PERM_LAMBDA_INVOKE.equals(e.getActionName())) &&
stmt.getPrincipals().stream().anyMatch(principal -> PRINCIPAL_ALEXA.equals(principal.getId())) &&
!lambdaFunction.getTriggers().stream().anyMatch( t -> t.getIntegration().equals(TRIG_INT_LABEL_ALEXA_SK)))
.forEach( s -> {
try {
getLog().info(" Removing orphaned Alexa permission " + s.getId());
lambdaClient.removePermission(new RemovePermissionRequest()
.withFunctionName(lambdaFunction.getFunctionName())
.withQualifier(lambdaFunction.getQualifier())
.withStatementId(s.getId()));
} catch (ResourceNotFoundException rnfe1) {
getLog().error(" Error removing permission for " + s.getId() + ": " + rnfe1.getMessage());
}
});
return of(policy);
});
return lambdaFunction;
};
/**
* Removes any Lex permissions that aren't found in the current configuration.
* TODO: Factor out code common with other orphan clean up functions.
*/
Function<LambdaFunction, LambdaFunction> cleanUpOrphanedLexSkillsTriggers = lambdaFunction -> {
ofNullable(lambdaFunction.getExistingPolicy()).flatMap( policy -> {
policy.getStatements().stream()
.filter(stmt -> stmt.getActions().stream().anyMatch( e -> PERM_LAMBDA_INVOKE.equals(e.getActionName())) &&
stmt.getPrincipals().stream().anyMatch(principal -> PRINCIPAL_LEX.equals(principal.getId())) &&
!lambdaFunction.getTriggers().stream().anyMatch( t -> stmt.getId().contains(ofNullable(t.getLexBotName()).orElse(""))))
.forEach( s -> {
try {
getLog().info(" Removing orphaned Lex permission " + s.getId());
lambdaClient.removePermission(new RemovePermissionRequest()
.withFunctionName(lambdaFunction.getFunctionName())
.withQualifier(lambdaFunction.getQualifier())
.withStatementId(s.getId()));
} catch (Exception ign2) {
getLog().error(" Error removing permission for " + s.getId() + ign2.getMessage() );
}
});
return of(policy);
});
return lambdaFunction;
};
Function<LambdaFunction, LambdaFunction> cleanUpOrphanedCloudWatchEventRules = lambdaFunction -> {
// Get the list of cloudwatch event rules defined for this function (if any).
List<String> existingRuleNames = cloudWatchEventsClient.listRuleNamesByTarget(new ListRuleNamesByTargetRequest()
.withTargetArn(lambdaFunction.getFunctionArn())).getRuleNames();
// Get the list of cloudwatch event rules to be defined for this function (if any).
List<String> definedRuleNames = lambdaFunction.getTriggers().stream().filter(
t -> TRIG_INT_LABEL_CLOUDWATCH_EVENTS.equals(t.getIntegration())).map(t -> {
return t.getRuleName();
}).collect(toList());
// Add the keep alive rule name if the user has disabled keep alive for the function.
ofNullable(lambdaFunction.getKeepAlive()).ifPresent(ka -> {
if ( ka > 0 ) {
definedRuleNames.add(lambdaFunction.getKeepAliveRuleName());
}
});
// Remove all of the rules that will be defined from the list of existing rules.
// The remainder is a set of event rules which should no longer be associated to this
// function.
existingRuleNames.removeAll(definedRuleNames);
// For each remaining rule, remove the function as a target and attempt to delete
// the rule.
existingRuleNames.stream().forEach(ern -> {
getLog().info(" Removing CloudWatch Event Rule: " + ern);
cloudWatchEventsClient.removeTargets(new RemoveTargetsRequest()
.withIds("1")
.withRule(ern));
try {
cloudWatchEventsClient.deleteRule(new DeleteRuleRequest().withName(ern));
} catch (Exception e) {
getLog().error(" Error removing orphaned rule: " + e.getMessage());
}
});
return lambdaFunction;
};
Function<LambdaFunction, LambdaFunction> cleanUpOrphans = lambdaFunction -> {
try {
lambdaFunction.setFunctionArn(lambdaClient.getFunction(
new GetFunctionRequest().withFunctionName(lambdaFunction.getFunctionName())).getConfiguration().getFunctionArn());
getLog().info("Cleaning up orphaned triggers.");
// Add clean up orphaned trigger functions for each integration here:
cleanUpOrphanedCloudWatchEventRules
.andThen(cleanUpOrphanedDynamoDBTriggers)
.andThen(cleanUpOrphanedKinesisTriggers)
.andThen(cleanUpOrphanedSNSTriggers)
.andThen(cleanUpOrphanedAlexaSkillsTriggers)
.andThen(cleanUpOrphanedLexSkillsTriggers)
.apply(lambdaFunction);
} catch (ResourceNotFoundException ign1) {
getLog().debug("Assuming function has no orphan triggers to clean up since it doesn't exist yet.");
}
return lambdaFunction;
};
Function<LambdaFunction, LambdaFunction> createOrUpdate = (lambdaFunction) -> {
final GetFunctionResult result = getLambdaFunction(lambdaClient, lambdaFunction.getFunctionName());
if (result == null) {
createFunction.andThen(createOrUpdateAliases)
.andThen(createOrUpdateTriggers)
.apply(lambdaFunction);
} else {
lambdaFunction.setFunctionArn(result.getConfiguration().getFunctionArn());
updateFunctionCode
.andThen(updateFunctionConfig)
.andThen(createOrUpdateAliases)
.andThen(createOrUpdateTriggers)
.andThen(createOrUpdateKeepAlive)
.apply(lambdaFunction);
}
return lambdaFunction;
};
private PutObjectResult upload(File file) {
getLog().info("Uploading " + functionCode + " to AWS S3 bucket " + s3Bucket);
PutObjectResult putObjectResult = s3Client.putObject(s3Bucket, fileName, file);
getLog().info("Upload complete...");
return putObjectResult;
}
private static ObjectMetadata getObjectMetadata(final AmazonS3 s3, final String bucket, final String fileName) {
try {
return s3.getObjectMetadata(bucket, fileName);
} catch (AmazonS3Exception ignored) {
return null;
}
}
private static GetFunctionResult getLambdaFunction(final AWSLambda lambda, final String name) {
try {
return lambda.getFunction(new GetFunctionRequest().withFunctionName(name));
} catch (ResourceNotFoundException rnfe) {
return null;
}
}
private String getBucket() {
if (s3Client.listBuckets().stream().noneMatch(p -> Objects.equals(p.getName(), s3Bucket))) {
getLog().info("Created bucket s3://" + s3Client.createBucket(s3Bucket).getName());
}
return s3Bucket;
}
/**
* {@link LambdaCodeComparisonOutcome} states the possible outcomes of comparing the local
* lambda code deliverable with the corresponding object in S3.
*/
enum LambdaCodeComparisonOutcome {
MD5_EQUALS(false),
MD5_DIFFERENT(true),
S3_OBJECT_MISSING(true);
final boolean shouldUpdateS3;
LambdaCodeComparisonOutcome(final boolean shouldUpdateS3) {
this.shouldUpdateS3 = shouldUpdateS3;
}
}
}
| src/main/java/com/github/seanroy/plugins/DeployLambdaMojo.java | package com.github.seanroy.plugins;
import static com.amazonaws.services.lambda.model.EventSourcePosition.LATEST;
import static java.util.Optional.empty;
import static java.util.Optional.of;
import static java.util.Optional.ofNullable;
import static java.util.stream.Collectors.toList;
import java.io.File;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.UUID;
import java.util.function.BiFunction;
import java.util.function.BiPredicate;
import java.util.function.Function;
import java.util.stream.Collectors;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugins.annotations.Mojo;
import com.amazonaws.auth.policy.Policy;
import com.amazonaws.auth.policy.Statement;
import com.amazonaws.services.cloudwatchevents.model.DeleteRuleRequest;
import com.amazonaws.services.cloudwatchevents.model.DescribeRuleRequest;
import com.amazonaws.services.cloudwatchevents.model.DescribeRuleResult;
import com.amazonaws.services.cloudwatchevents.model.ListRuleNamesByTargetRequest;
import com.amazonaws.services.cloudwatchevents.model.PutRuleRequest;
import com.amazonaws.services.cloudwatchevents.model.PutRuleResult;
import com.amazonaws.services.cloudwatchevents.model.PutTargetsRequest;
import com.amazonaws.services.cloudwatchevents.model.RemoveTargetsRequest;
import com.amazonaws.services.cloudwatchevents.model.Target;
import com.amazonaws.services.dynamodbv2.model.DescribeStreamRequest;
import com.amazonaws.services.dynamodbv2.model.ListStreamsRequest;
import com.amazonaws.services.dynamodbv2.model.ListStreamsResult;
import com.amazonaws.services.dynamodbv2.model.Stream;
import com.amazonaws.services.dynamodbv2.model.StreamDescription;
import com.amazonaws.services.lambda.model.AddPermissionRequest;
import com.amazonaws.services.lambda.model.AddPermissionResult;
import com.amazonaws.services.lambda.model.AliasConfiguration;
import com.amazonaws.services.lambda.model.CreateAliasRequest;
import com.amazonaws.services.lambda.model.CreateEventSourceMappingRequest;
import com.amazonaws.services.lambda.model.CreateEventSourceMappingResult;
import com.amazonaws.services.lambda.model.CreateFunctionRequest;
import com.amazonaws.services.lambda.model.CreateFunctionResult;
import com.amazonaws.services.lambda.model.DeleteEventSourceMappingRequest;
import com.amazonaws.services.lambda.model.Environment;
import com.amazonaws.services.lambda.model.EventSourceMappingConfiguration;
import com.amazonaws.services.lambda.model.EventSourcePosition;
import com.amazonaws.services.lambda.model.FunctionCode;
import com.amazonaws.services.lambda.model.GetFunctionRequest;
import com.amazonaws.services.lambda.model.GetFunctionResult;
import com.amazonaws.services.lambda.model.GetPolicyRequest;
import com.amazonaws.services.lambda.model.GetPolicyResult;
import com.amazonaws.services.lambda.model.ListAliasesRequest;
import com.amazonaws.services.lambda.model.ListAliasesResult;
import com.amazonaws.services.lambda.model.ListEventSourceMappingsRequest;
import com.amazonaws.services.lambda.model.ListEventSourceMappingsResult;
import com.amazonaws.services.lambda.model.RemovePermissionRequest;
import com.amazonaws.services.lambda.model.ResourceNotFoundException;
import com.amazonaws.services.lambda.model.UpdateAliasRequest;
import com.amazonaws.services.lambda.model.UpdateEventSourceMappingRequest;
import com.amazonaws.services.lambda.model.UpdateEventSourceMappingResult;
import com.amazonaws.services.lambda.model.UpdateFunctionCodeRequest;
import com.amazonaws.services.lambda.model.UpdateFunctionCodeResult;
import com.amazonaws.services.lambda.model.UpdateFunctionConfigurationRequest;
import com.amazonaws.services.lambda.model.VpcConfig;
import com.amazonaws.services.lambda.model.VpcConfigResponse;
import com.amazonaws.services.s3.model.AmazonS3Exception;
import com.amazonaws.services.s3.model.ObjectMetadata;
import com.amazonaws.services.s3.model.PutObjectResult;
import com.amazonaws.services.sns.model.CreateTopicRequest;
import com.amazonaws.services.sns.model.CreateTopicResult;
import com.amazonaws.services.sns.model.ListSubscriptionsResult;
import com.amazonaws.services.sns.model.SubscribeRequest;
import com.amazonaws.services.sns.model.SubscribeResult;
import com.amazonaws.services.sns.model.Subscription;
import com.amazonaws.services.sns.model.UnsubscribeRequest;
/**
* I am a deploy mojo responsible to upload and create or update lambda function in AWS.
*
* @author Sean N. Roy, <a href="mailto:[email protected]">Sean Roy</a> 11/08/16.
*/
@Mojo(name = "deploy-lambda")
public class DeployLambdaMojo extends AbstractLambdaMojo {
@Override
public void execute() throws MojoExecutionException {
super.execute();
try {
uploadJarToS3();
lambdaFunctions.stream().map(f -> {
getLog().info("---- Create or update " + f.getFunctionName() + " -----");
return f;
}).forEach(lf ->
getFunctionPolicy
.andThen(cleanUpOrphans)
.andThen(createOrUpdate)
.apply(lf));
} catch (Exception e) {
getLog().error("Error during processing", e);
throw new MojoExecutionException(e.getMessage());
}
}
private boolean shouldUpdate(LambdaFunction lambdaFunction, GetFunctionResult getFunctionResult) {
boolean isConfigurationChanged = isConfigurationChanged(lambdaFunction, getFunctionResult);
if (!isConfigurationChanged) {
getLog().info("Config hasn't changed for " + lambdaFunction.getFunctionName());
}
if (forceUpdate) {
getLog().info("Forcing update for " + lambdaFunction.getFunctionName());
}
return forceUpdate || isConfigurationChanged;
}
/*
* Get the existing policy function (on updates) and assign it to the lambdaFunction.
*/
private Function<LambdaFunction, LambdaFunction> getFunctionPolicy = (LambdaFunction lambdaFunction) -> {
try {
lambdaFunction.setExistingPolicy(Policy.fromJson(lambdaClient.getPolicy(new GetPolicyRequest()
.withFunctionName(lambdaFunction.getFunctionName())
.withQualifier(lambdaFunction.getQualifier())).getPolicy()));
} catch (ResourceNotFoundException rnfe3) {
getLog().debug("Probably creating a new function, policy doesn't exist yet: " + rnfe3.getMessage());
}
return lambdaFunction;
};
private Function<LambdaFunction, LambdaFunction> updateFunctionCode = (LambdaFunction lambdaFunction) -> {
getLog().info("About to update functionCode for " + lambdaFunction.getFunctionName());
UpdateFunctionCodeRequest updateFunctionRequest = new UpdateFunctionCodeRequest()
.withFunctionName(lambdaFunction.getFunctionName())
.withS3Bucket(s3Bucket)
.withS3Key(fileName)
.withPublish(lambdaFunction.isPublish());
UpdateFunctionCodeResult updateFunctionCodeResult = lambdaClient.updateFunctionCode(updateFunctionRequest);
return lambdaFunction
.withVersion(updateFunctionCodeResult.getVersion())
.withFunctionArn(updateFunctionCodeResult.getFunctionArn());
};
private Function<LambdaFunction, LambdaFunction> updateFunctionConfig = (LambdaFunction lambdaFunction) -> {
getLog().info("About to update functionConfig for " + lambdaFunction.getFunctionName());
UpdateFunctionConfigurationRequest updateFunctionRequest = new UpdateFunctionConfigurationRequest()
.withFunctionName(lambdaFunction.getFunctionName())
.withDescription(lambdaFunction.getDescription())
.withHandler(lambdaFunction.getHandler())
.withRole(lambdaRoleArn)
.withTimeout(lambdaFunction.getTimeout())
.withMemorySize(lambdaFunction.getMemorySize())
.withRuntime(runtime)
.withVpcConfig(getVpcConfig(lambdaFunction))
.withEnvironment(new Environment().withVariables(lambdaFunction.getEnvironmentVariables()));
lambdaClient.updateFunctionConfiguration(updateFunctionRequest);
return lambdaFunction;
};
private Function<LambdaFunction, LambdaFunction> createOrUpdateAliases = (LambdaFunction lambdaFunction) -> {
lambdaFunction.getAliases().forEach(alias -> {
UpdateAliasRequest updateAliasRequest = new UpdateAliasRequest()
.withFunctionName(lambdaFunction.getFunctionName())
.withFunctionVersion(lambdaFunction.getVersion())
.withName(alias);
try {
lambdaClient.updateAlias(updateAliasRequest
);
getLog().info("Alias " + alias + " updated for " + lambdaFunction.getFunctionName() + " with version " + lambdaFunction.getVersion());
} catch (ResourceNotFoundException ignored) {
CreateAliasRequest createAliasRequest = new CreateAliasRequest()
.withFunctionName(lambdaFunction.getFunctionName())
.withFunctionVersion(lambdaFunction.getVersion())
.withName(alias);
lambdaClient.createAlias(createAliasRequest);
getLog().info("Alias " + alias + " created for " + lambdaFunction.getFunctionName() + " with version " + lambdaFunction.getVersion());
}
});
return lambdaFunction;
};
private BiFunction<Trigger, LambdaFunction, Trigger> createOrUpdateSNSTopicSubscription = (Trigger trigger, LambdaFunction lambdaFunction) -> {
getLog().info("About to create or update " + trigger.getIntegration() + " trigger for " + trigger.getSNSTopic());
CreateTopicRequest createTopicRequest = new CreateTopicRequest()
.withName(trigger.getSNSTopic());
CreateTopicResult createTopicResult = snsClient.createTopic(createTopicRequest);
getLog().info("Topic " + createTopicResult.getTopicArn() + " created");
SubscribeRequest subscribeRequest = new SubscribeRequest()
.withTopicArn(createTopicResult.getTopicArn())
.withEndpoint(lambdaFunction.getUnqualifiedFunctionArn())
.withProtocol("lambda");
SubscribeResult subscribeResult = snsClient.subscribe(subscribeRequest);
getLog().info("Lambda function " + lambdaFunction.getFunctionName() + " subscribed to " + createTopicResult.getTopicArn());
getLog().info("Created " + trigger.getIntegration() + " trigger " + subscribeResult.getSubscriptionArn());
Optional<Statement> statementOpt;
try {
GetPolicyRequest getPolicyRequest = new GetPolicyRequest()
.withFunctionName(lambdaFunction.getFunctionName());
GetPolicyResult GetPolicyResult = lambdaClient.getPolicy(getPolicyRequest);
statementOpt = Policy.fromJson(GetPolicyResult.getPolicy()).getStatements().stream()
.filter(statement -> statement.getActions().stream().anyMatch(e -> PERM_LAMBDA_INVOKE.equals(e.getActionName())) &&
statement.getPrincipals().stream().anyMatch(principal -> PRINCIPAL_SNS.equals(principal.getId())) &&
statement.getConditions().stream().anyMatch(condition -> condition.getValues().stream().anyMatch(s -> Objects.equals(createTopicResult.getTopicArn(), s)))
).findAny();
} catch (ResourceNotFoundException ignored) {
// no policy found
statementOpt = empty();
}
if (!statementOpt.isPresent()) {
AddPermissionRequest addPermissionRequest = new AddPermissionRequest()
.withAction(PERM_LAMBDA_INVOKE)
.withPrincipal(PRINCIPAL_SNS)
.withSourceArn(createTopicResult.getTopicArn())
.withFunctionName(lambdaFunction.getFunctionName())
.withStatementId(UUID.randomUUID().toString());
AddPermissionResult addPermissionResult = lambdaClient.addPermission(addPermissionRequest);
getLog().debug("Added permission to lambda function " + addPermissionResult.toString());
}
return trigger;
};
/**
* TODO: Much of this code can be factored out into an addPermission function.
*/
private BiFunction<Trigger, LambdaFunction, Trigger> addAlexaSkillsKitPermission = (Trigger trigger, LambdaFunction lambdaFunction) -> {
if (!ofNullable(lambdaFunction.getExistingPolicy()).orElse(new Policy()).getStatements().stream().anyMatch(s ->
s.getId().equals(getAlexaPermissionStatementId()))) {
getLog().info("Granting invoke permission to " + trigger.getIntegration());
AddPermissionRequest addPermissionRequest = new AddPermissionRequest()
.withAction(PERM_LAMBDA_INVOKE)
.withPrincipal(PRINCIPAL_ALEXA)
.withFunctionName(lambdaFunction.getFunctionName())
.withQualifier(lambdaFunction.getQualifier())
.withStatementId(getAlexaPermissionStatementId());
AddPermissionResult addPermissionResult = lambdaClient.addPermission(addPermissionRequest);
}
return trigger;
};
private String getAlexaPermissionStatementId() {
return "lambda-maven-plugin-alexa-" + regionName + "-permission";
}
/**
* TODO: Much of this code can be factored out into an addPermission function.
*/
private BiFunction<Trigger, LambdaFunction, Trigger> addLexPermission = (Trigger trigger, LambdaFunction lambdaFunction) -> {
if (!ofNullable(lambdaFunction.getExistingPolicy()).orElse(new Policy()).getStatements().stream().anyMatch(s ->
s.getId().equals(getLexPermissionStatementId(trigger.getLexBotName())))) {
getLog().info("Granting invoke permission to Lex bot " + trigger.getLexBotName());
AddPermissionRequest addPermissionRequest = new AddPermissionRequest()
.withAction(PERM_LAMBDA_INVOKE)
.withPrincipal(PRINCIPAL_LEX)
.withFunctionName(lambdaFunction.getFunctionName())
.withQualifier(lambdaFunction.getQualifier())
.withStatementId(getLexPermissionStatementId(trigger.getLexBotName()));
AddPermissionResult addPermissionResult = lambdaClient.addPermission(addPermissionRequest);
}
return trigger;
};
private String getLexPermissionStatementId(String botName) {
return "lambda-maven-plugin-lex-" + regionName + "-permission-" + botName;
}
private BiFunction<Trigger, LambdaFunction, Trigger> createOrUpdateScheduledRule = (Trigger trigger, LambdaFunction lambdaFunction) -> {
// TODO: I hate that these checks are done twice, but for the time being it beats updates that just didn't work.
if ( isScheduleRuleChanged(lambdaFunction) || isKeepAliveChanged(lambdaFunction)) {
getLog().info("About to create or update " + trigger.getIntegration() + " trigger for " + trigger.getRuleName());
PutRuleRequest putRuleRequest = new PutRuleRequest()
.withName(trigger.getRuleName())
.withDescription(trigger.getRuleDescription())
.withScheduleExpression(trigger.getScheduleExpression());
PutRuleResult putRuleResult = eventsClient.putRule(putRuleRequest);
getLog().info("Created " + trigger.getIntegration() + " trigger " + putRuleResult.getRuleArn());
AddPermissionRequest addPermissionRequest = new AddPermissionRequest()
.withAction(PERM_LAMBDA_INVOKE)
.withPrincipal(PRINCIPAL_EVENTS)
.withSourceArn(putRuleResult.getRuleArn())
.withFunctionName(lambdaFunction.getFunctionName())
.withStatementId(UUID.randomUUID().toString());
AddPermissionResult addPermissionResult = lambdaClient.addPermission(addPermissionRequest);
getLog().debug("Added permission to lambda function " + addPermissionResult.toString());
PutTargetsRequest putTargetsRequest = new PutTargetsRequest()
.withRule(trigger.getRuleName())
.withTargets(new Target().withId("1").withArn(lambdaFunction.getUnqualifiedFunctionArn()));
eventsClient.putTargets(putTargetsRequest);
}
return trigger;
};
private Function<LambdaFunction, LambdaFunction> createOrUpdateKeepAlive = (LambdaFunction lambdaFunction) -> {
if (isKeepAliveChanged(lambdaFunction)) {
ofNullable(lambdaFunction.getKeepAlive()).flatMap(f -> {
if ( f > 0 ) {
getLog().info("Setting keepAlive to " + f + " minutes.");
createOrUpdateScheduledRule.apply(new Trigger()
.withIntegration("Function Keep Alive")
.withDescription(String.format("This feature pings function %s every %d %s.",
lambdaFunction.getFunctionName(), f,
f > 1 ? "minutes" : "minute"))
.withRuleName(lambdaFunction.getKeepAliveRuleName())
.withScheduleExpression(lambdaFunction.getKeepAliveScheduleExpression()),
lambdaFunction);
}
return Optional.of(f);
});
}
return lambdaFunction;
};
private BiFunction<Trigger, LambdaFunction, Trigger> createOrUpdateDynamoDBTrigger = (Trigger trigger, LambdaFunction lambdaFunction) -> {
getLog().info("About to create or update " + trigger.getIntegration() + " trigger for " + trigger.getDynamoDBTable());
ListStreamsRequest listStreamsRequest = new ListStreamsRequest().withTableName(trigger.getDynamoDBTable());
ListStreamsResult listStreamsResult = dynamoDBStreamsClient.listStreams(listStreamsRequest);
String streamArn = listStreamsResult.getStreams().stream()
.filter(s -> Objects.equals(trigger.getDynamoDBTable(), s.getTableName()))
.findFirst()
.map(Stream::getStreamArn)
.orElseThrow(() -> new IllegalArgumentException("Unable to find stream for table " + trigger.getDynamoDBTable()));
return findorUpdateMappingConfiguration(trigger, lambdaFunction, streamArn);
};
private BiFunction<Trigger, LambdaFunction, Trigger> createOrUpdateKinesisStream = (Trigger trigger, LambdaFunction lambdaFunction) -> {
getLog().info("About to create or update " + trigger.getIntegration() + " trigger for " + trigger.getKinesisStream());
try {
return findorUpdateMappingConfiguration(trigger, lambdaFunction,
kinesisClient.describeStream(trigger.getKinesisStream()).getStreamDescription().getStreamARN());
} catch (Exception rnfe) {
getLog().info(rnfe.getMessage());
throw new IllegalArgumentException("Unable to find stream with name " + trigger.getKinesisStream());
}
};
private Trigger findorUpdateMappingConfiguration(Trigger trigger, LambdaFunction lambdaFunction, String streamArn) {
ListEventSourceMappingsRequest listEventSourceMappingsRequest = new ListEventSourceMappingsRequest()
.withFunctionName(lambdaFunction.getUnqualifiedFunctionArn());
ListEventSourceMappingsResult listEventSourceMappingsResult = lambdaClient.listEventSourceMappings(listEventSourceMappingsRequest);
Optional<EventSourceMappingConfiguration> eventSourceMappingConfiguration = listEventSourceMappingsResult.getEventSourceMappings().stream()
.filter(stream -> {
boolean isSameFunctionArn = Objects.equals(stream.getFunctionArn(), lambdaFunction.getUnqualifiedFunctionArn());
boolean isSameSourceArn = Objects.equals(stream.getEventSourceArn(), streamArn);
return isSameFunctionArn && isSameSourceArn;
})
.findFirst();
if (eventSourceMappingConfiguration.isPresent()) {
UpdateEventSourceMappingRequest updateEventSourceMappingRequest = new UpdateEventSourceMappingRequest()
.withUUID(eventSourceMappingConfiguration.get().getUUID())
.withFunctionName(lambdaFunction.getUnqualifiedFunctionArn())
.withBatchSize(ofNullable(trigger.getBatchSize()).orElse(10))
.withEnabled(ofNullable(trigger.getEnabled()).orElse(true));
UpdateEventSourceMappingResult updateEventSourceMappingResult = lambdaClient.updateEventSourceMapping(updateEventSourceMappingRequest);
trigger.withTriggerArn(updateEventSourceMappingResult.getEventSourceArn());
getLog().info("Updated " + trigger.getIntegration() + " trigger " + trigger.getTriggerArn());
} else {
CreateEventSourceMappingRequest createEventSourceMappingRequest = new CreateEventSourceMappingRequest()
.withFunctionName(lambdaFunction.getUnqualifiedFunctionArn())
.withEventSourceArn(streamArn)
.withBatchSize(ofNullable(trigger.getBatchSize()).orElse(10))
.withStartingPosition(EventSourcePosition.fromValue(ofNullable(trigger.getStartingPosition()).orElse(LATEST.toString())))
.withEnabled(ofNullable(trigger.getEnabled()).orElse(true));
CreateEventSourceMappingResult createEventSourceMappingResult = lambdaClient.createEventSourceMapping(createEventSourceMappingRequest);
trigger.withTriggerArn(createEventSourceMappingResult.getEventSourceArn());
getLog().info("Created " + trigger.getIntegration() + " trigger " + trigger.getTriggerArn());
}
return trigger;
}
private Function<LambdaFunction, LambdaFunction> createOrUpdateTriggers = (LambdaFunction lambdaFunction) -> {
lambdaFunction.getTriggers().forEach(trigger -> {
if (TRIG_INT_LABEL_CLOUDWATCH_EVENTS.equals(trigger.getIntegration())) {
createOrUpdateScheduledRule.apply(trigger, lambdaFunction);
} else if (TRIG_INT_LABEL_DYNAMO_DB.equals(trigger.getIntegration())) {
createOrUpdateDynamoDBTrigger.apply(trigger, lambdaFunction);
} else if (TRIG_INT_LABEL_KINESIS.equals(trigger.getIntegration())) {
createOrUpdateKinesisStream.apply(trigger, lambdaFunction);
} else if (TRIG_INT_LABEL_SNS.equals(trigger.getIntegration())) {
createOrUpdateSNSTopicSubscription.apply(trigger, lambdaFunction);
} else if (TRIG_INT_LABEL_ALEXA_SK.equals(trigger.getIntegration())) {
addAlexaSkillsKitPermission.apply(trigger, lambdaFunction);
} else if (TRIG_INT_LABEL_LEX.equals(trigger.getIntegration())) {
addLexPermission.apply(trigger, lambdaFunction);
} else {
throw new IllegalArgumentException("Unknown integration for trigger " + trigger.getIntegration() + ". Correct your configuration");
}
});
return lambdaFunction;
};
private GetFunctionResult getFunction(LambdaFunction lambdaFunction) {
return lambdaClient.getFunction(new GetFunctionRequest().withFunctionName(lambdaFunction.getFunctionName()));
}
private boolean isConfigurationChanged(LambdaFunction lambdaFunction, GetFunctionResult function) {
BiPredicate<String, String> isChangeStr = (s0, s1) -> !Objects.equals(s0, s1);
BiPredicate<Integer, Integer> isChangeInt = (i0, i1) -> !Objects.equals(i0, i1);
BiPredicate<List<String>, List<String>> isChangeList = (l0, l1) -> !(l0.containsAll(l1) && l1.containsAll(l0));
return of(function.getConfiguration())
.map(config -> {
VpcConfigResponse vpcConfig = config.getVpcConfig();
if (vpcConfig == null) {
vpcConfig = new VpcConfigResponse();
}
boolean isDescriptionChanged = isChangeStr.test(config.getDescription(), lambdaFunction.getDescription());
boolean isHandlerChanged = isChangeStr.test(config.getHandler(), lambdaFunction.getHandler());
boolean isRoleChanged = isChangeStr.test(config.getRole(), lambdaRoleArn);
boolean isTimeoutChanged = isChangeInt.test(config.getTimeout(), lambdaFunction.getTimeout());
boolean isMemoryChanged = isChangeInt.test(config.getMemorySize(), lambdaFunction.getMemorySize());
boolean isSecurityGroupIdsChanged = isChangeList.test(vpcConfig.getSecurityGroupIds(), lambdaFunction.getSecurityGroupIds());
boolean isVpcSubnetIdsChanged = isChangeList.test(vpcConfig.getSubnetIds(), lambdaFunction.getSubnetIds());
return isDescriptionChanged || isHandlerChanged || isRoleChanged || isTimeoutChanged || isMemoryChanged ||
isSecurityGroupIdsChanged || isVpcSubnetIdsChanged || isAliasesChanged(lambdaFunction) || isKeepAliveChanged(lambdaFunction) ||
isScheduleRuleChanged(lambdaFunction);
})
.orElse(true);
}
private boolean isKeepAliveChanged(LambdaFunction lambdaFunction) {
try {
return ofNullable(lambdaFunction.getKeepAlive()).map( ka -> {
DescribeRuleResult res = eventsClient.describeRule(new DescribeRuleRequest().withName(lambdaFunction.getKeepAliveRuleName()));
return !Objects.equals(res.getScheduleExpression(), lambdaFunction.getKeepAliveScheduleExpression());
}).orElse(false);
} catch( com.amazonaws.services.cloudwatchevents.model.ResourceNotFoundException ignored ) {
return true;
}
}
private boolean isScheduleRuleChanged(LambdaFunction lambdaFunction) {
try {
return lambdaFunction.getTriggers().stream().filter(t -> TRIG_INT_LABEL_CLOUDWATCH_EVENTS.equals(t.getIntegration())).anyMatch(trigger -> {
DescribeRuleResult res = eventsClient.describeRule(new DescribeRuleRequest().withName(trigger.getRuleName()));
return !(Objects.equals(res.getName(), trigger.getRuleName()) &&
Objects.equals(res.getDescription(), trigger.getRuleDescription()) &&
Objects.equals(res.getScheduleExpression(), trigger.getScheduleExpression()));
});
} catch( com.amazonaws.services.cloudwatchevents.model.ResourceNotFoundException ignored ) {
return true;
}
}
private boolean isAliasesChanged(LambdaFunction lambdaFunction) {
try {
ListAliasesResult listAliasesResult = lambdaClient.listAliases(new ListAliasesRequest()
.withFunctionName(lambdaFunction.getFunctionName()));
List<String> configuredAliases = listAliasesResult.getAliases().stream()
.map(AliasConfiguration::getName)
.collect(toList());
return !configuredAliases.containsAll(lambdaFunction.getAliases());
} catch (ResourceNotFoundException ignored) {
return true;
}
}
private Function<LambdaFunction, LambdaFunction> createFunction = (LambdaFunction lambdaFunction) -> {
getLog().info("About to create function " + lambdaFunction.getFunctionName());
CreateFunctionRequest createFunctionRequest = new CreateFunctionRequest()
.withDescription(lambdaFunction.getDescription())
.withRole(lambdaRoleArn)
.withFunctionName(lambdaFunction.getFunctionName())
.withHandler(lambdaFunction.getHandler())
.withRuntime(runtime)
.withTimeout(ofNullable(lambdaFunction.getTimeout()).orElse(timeout))
.withMemorySize(ofNullable(lambdaFunction.getMemorySize()).orElse(memorySize))
.withVpcConfig(getVpcConfig(lambdaFunction))
.withCode(new FunctionCode()
.withS3Bucket(s3Bucket)
.withS3Key(fileName))
.withEnvironment(new Environment().withVariables(lambdaFunction.getEnvironmentVariables()));
CreateFunctionResult createFunctionResult = lambdaClient.createFunction(createFunctionRequest);
lambdaFunction.withVersion(createFunctionResult.getVersion())
.withFunctionArn(createFunctionResult.getFunctionArn());
getLog().info("Function " + createFunctionResult.getFunctionName() + " created. Function Arn: " + createFunctionResult.getFunctionArn());
return lambdaFunction;
};
private VpcConfig getVpcConfig(LambdaFunction lambdaFunction) {
return new VpcConfig()
.withSecurityGroupIds(lambdaFunction.getSecurityGroupIds())
.withSubnetIds(lambdaFunction.getSubnetIds());
}
private void uploadJarToS3() throws Exception {
String bucket = getBucket();
File file = new File(functionCode);
String localmd5 = DigestUtils.md5Hex(new FileInputStream(file));
getLog().debug(String.format("Local file's MD5 hash is %s.", localmd5));
ofNullable(getObjectMetadata(bucket))
.map(ObjectMetadata::getETag)
.map(remoteMD5 -> {
getLog().info(fileName + " exists in S3 with MD5 hash " + remoteMD5);
// This comparison will no longer work if we ever go to multipart uploads. Etags are not
// computed as MD5 sums for multipart uploads in s3.
return localmd5.equals(remoteMD5);
})
.map(isTheSame -> {
if (isTheSame) {
getLog().info(fileName + " is up to date in AWS S3 bucket " + s3Bucket + ". Not uploading...");
return true;
}
return null; // file should be imported
})
.orElseGet(() -> {
upload(file);
return true;
});
}
/**
* Remove orphaned kinesis stream triggers.
* TODO: Combine with cleanUpOrphanedDynamoDBTriggers.
*/
Function<LambdaFunction, LambdaFunction> cleanUpOrphanedKinesisTriggers = lambdaFunction -> {
ListEventSourceMappingsResult listEventSourceMappingsResult =
lambdaClient.listEventSourceMappings(new ListEventSourceMappingsRequest()
.withFunctionName(lambdaFunction.getUnqualifiedFunctionArn()));
List<String> streamNames = new ArrayList<String>();
// This nonsense is to prevent cleanupOrphanedDynamoDBTriggers from removing DynamoDB triggers
// and vice versa. Unfortunately this assumes that stream names won't be the same as table names.
lambdaFunction.getTriggers().stream().forEach(t -> {
ofNullable(t.getKinesisStream()).ifPresent(x -> streamNames.add(x));
ofNullable(t.getDynamoDBTable()).ifPresent(x -> streamNames.add(x));
});
listEventSourceMappingsResult.getEventSourceMappings().stream().forEach(s -> {
if ( s.getEventSourceArn().contains(":kinesis:") ) {
if ( ! streamNames.contains(kinesisClient.describeStream(new com.amazonaws.services.kinesis.model.DescribeStreamRequest()
.withStreamName(s.getEventSourceArn().substring(s.getEventSourceArn().lastIndexOf('/')+1)))
.getStreamDescription()
.getStreamName()) ){
getLog().info(" Removing orphaned Kinesis trigger for stream " + s.getEventSourceArn());
try {
lambdaClient.deleteEventSourceMapping(new DeleteEventSourceMappingRequest().withUUID(s.getUUID()));
} catch(Exception e8) {
getLog().error(" Error removing orphaned Kinesis trigger for stream " + s.getEventSourceArn());
}
}
}
});
return lambdaFunction;
};
/**
* Removes orphaned sns triggers.
*/
Function<LambdaFunction, LambdaFunction> cleanUpOrphanedSNSTriggers = lambdaFunction -> {
List<Subscription> subscriptions = new ArrayList<Subscription>();
ListSubscriptionsResult result = snsClient.listSubscriptions();
do {
subscriptions.addAll(result.getSubscriptions().stream().filter( sub -> {
return sub.getEndpoint().equals(lambdaFunction.getFunctionArn());
}).collect(Collectors.toList()));
result = snsClient.listSubscriptions(result.getNextToken());
} while( result.getNextToken() != null );
if (subscriptions.size() > 0 ) {
List<String> snsTopicNames = lambdaFunction.getTriggers().stream().map(t -> {
return ofNullable(t.getSNSTopic()).orElse("");
}).collect(Collectors.toList());
subscriptions.stream().forEach(s -> {
String topicName = s.getTopicArn().substring(s.getTopicArn().lastIndexOf(":")+1);
if (!snsTopicNames.contains(topicName)) {
getLog().info(" Removing orphaned SNS trigger for topic " + topicName);
try {
snsClient.unsubscribe(new UnsubscribeRequest().withSubscriptionArn(s.getSubscriptionArn()));
ofNullable(lambdaFunction.getExistingPolicy()).flatMap( policy -> {
policy.getStatements().stream()
.filter(
stmt -> stmt.getActions().stream().anyMatch( e -> PERM_LAMBDA_INVOKE.equals(e.getActionName())) &&
stmt.getPrincipals().stream().anyMatch(principal -> PRINCIPAL_SNS.equals(principal.getId())) &&
stmt.getResources().stream().anyMatch(r -> r.getId().equals(lambdaFunction.getFunctionArn()))
).forEach( st -> {
if( st.getConditions().stream().anyMatch(condition -> condition.getValues().contains(s.getTopicArn())) ) {
getLog().info(" Removing invoke permission for SNS trigger");
try {
lambdaClient.removePermission(new RemovePermissionRequest()
.withFunctionName(lambdaFunction.getFunctionName())
.withQualifier(lambdaFunction.getQualifier())
.withStatementId(st.getId()));
} catch (Exception e7) {
getLog().error(" Error removing invoke permission for SNS trigger");
}
}
});
return of(policy);
});
} catch(Exception e5) {
getLog().error(" Error removing SNS trigger for topic " + topicName);
}
}
});
}
return lambdaFunction;
};
/**
* Removes orphaned dynamo db triggers.
* TODO: Combine with cleanUpOrphanedKinesisTriggers
*/
Function<LambdaFunction, LambdaFunction> cleanUpOrphanedDynamoDBTriggers = lambdaFunction -> {
ListEventSourceMappingsResult listEventSourceMappingsResult =
lambdaClient.listEventSourceMappings(new ListEventSourceMappingsRequest()
.withFunctionName(lambdaFunction.getUnqualifiedFunctionArn()));
List<String> tableNames = new ArrayList<String>();
// This nonsense is to prevent cleanupOrphanedDynamoDBTriggers from removing DynamoDB triggers
// and vice versa. Unfortunately this assumes that stream names won't be the same as table names.
lambdaFunction.getTriggers().stream().forEach(t -> {
ofNullable(t.getKinesisStream()).ifPresent(x -> tableNames.add(x));
ofNullable(t.getDynamoDBTable()).ifPresent(x -> tableNames.add(x));
});
listEventSourceMappingsResult.getEventSourceMappings().stream().forEach(s -> {
if ( s.getEventSourceArn().contains(":dynamodb:")) {
StreamDescription sd = dynamoDBStreamsClient.describeStream(new DescribeStreamRequest()
.withStreamArn(s.getEventSourceArn())).getStreamDescription();
if ( ! tableNames.contains(sd.getTableName()) ) {
getLog().info(" Removing orphaned DynamoDB trigger for table " + sd.getTableName());
try {
lambdaClient.deleteEventSourceMapping(new DeleteEventSourceMappingRequest().withUUID(s.getUUID()));
} catch (Exception e4) {
getLog().error(" Error removing DynamoDB trigger for table " + sd.getTableName());
}
}
}
});
return lambdaFunction;
};
/**
* Removes the Alexa permission if it isn't found in the current configuration.
* TODO: Factor out code common with other orphan clean up functions.
*/
Function<LambdaFunction, LambdaFunction> cleanUpOrphanedAlexaSkillsTriggers = lambdaFunction -> {
ofNullable(lambdaFunction.getExistingPolicy()).flatMap( policy -> {
policy.getStatements().stream()
.filter(
stmt -> stmt.getActions().stream().anyMatch( e -> PERM_LAMBDA_INVOKE.equals(e.getActionName())) &&
stmt.getPrincipals().stream().anyMatch(principal -> PRINCIPAL_ALEXA.equals(principal.getId())) &&
!lambdaFunction.getTriggers().stream().anyMatch( t -> t.getIntegration().equals(TRIG_INT_LABEL_ALEXA_SK)))
.forEach( s -> {
try {
getLog().info(" Removing orphaned Alexa permission " + s.getId());
lambdaClient.removePermission(new RemovePermissionRequest()
.withFunctionName(lambdaFunction.getFunctionName())
.withQualifier(lambdaFunction.getQualifier())
.withStatementId(s.getId()));
} catch (ResourceNotFoundException rnfe1) {
getLog().error(" Error removing permission for " + s.getId() + ": " + rnfe1.getMessage());
}
});
return of(policy);
});
return lambdaFunction;
};
/**
* Removes any Lex permissions that aren't found in the current configuration.
* TODO: Factor out code common with other orphan clean up functions.
*/
Function<LambdaFunction, LambdaFunction> cleanUpOrphanedLexSkillsTriggers = lambdaFunction -> {
ofNullable(lambdaFunction.getExistingPolicy()).flatMap( policy -> {
policy.getStatements().stream()
.filter(stmt -> stmt.getActions().stream().anyMatch( e -> PERM_LAMBDA_INVOKE.equals(e.getActionName())) &&
stmt.getPrincipals().stream().anyMatch(principal -> PRINCIPAL_LEX.equals(principal.getId())) &&
!lambdaFunction.getTriggers().stream().anyMatch( t -> stmt.getId().contains(ofNullable(t.getLexBotName()).orElse(""))))
.forEach( s -> {
try {
getLog().info(" Removing orphaned Lex permission " + s.getId());
lambdaClient.removePermission(new RemovePermissionRequest()
.withFunctionName(lambdaFunction.getFunctionName())
.withQualifier(lambdaFunction.getQualifier())
.withStatementId(s.getId()));
} catch (Exception ign2) {
getLog().error(" Error removing permission for " + s.getId() + ign2.getMessage() );
}
});
return of(policy);
});
return lambdaFunction;
};
Function<LambdaFunction, LambdaFunction> cleanUpOrphanedCloudWatchEventRules = lambdaFunction -> {
// Get the list of cloudwatch event rules defined for this function (if any).
List<String> existingRuleNames = cloudWatchEventsClient.listRuleNamesByTarget(new ListRuleNamesByTargetRequest()
.withTargetArn(lambdaFunction.getFunctionArn())).getRuleNames();
// Get the list of cloudwatch event rules to be defined for this function (if any).
List<String> definedRuleNames = lambdaFunction.getTriggers().stream().filter(
t -> TRIG_INT_LABEL_CLOUDWATCH_EVENTS.equals(t.getIntegration())).map(t -> {
return t.getRuleName();
}).collect(toList());
// Add the keep alive rule name if the user has disabled keep alive for the function.
ofNullable(lambdaFunction.getKeepAlive()).ifPresent(ka -> {
if ( ka > 0 ) {
definedRuleNames.add(lambdaFunction.getKeepAliveRuleName());
}
});
// Remove all of the rules that will be defined from the list of existing rules.
// The remainder is a set of event rules which should no longer be associated to this
// function.
existingRuleNames.removeAll(definedRuleNames);
// For each remaining rule, remove the function as a target and attempt to delete
// the rule.
existingRuleNames.stream().forEach(ern -> {
getLog().info(" Removing CloudWatch Event Rule: " + ern);
cloudWatchEventsClient.removeTargets(new RemoveTargetsRequest()
.withIds("1")
.withRule(ern));
try {
cloudWatchEventsClient.deleteRule(new DeleteRuleRequest().withName(ern));
} catch (Exception e) {
getLog().error(" Error removing orphaned rule: " + e.getMessage());
}
});
return lambdaFunction;
};
Function<LambdaFunction, LambdaFunction> cleanUpOrphans = lambdaFunction -> {
try {
lambdaFunction.setFunctionArn(lambdaClient.getFunction(
new GetFunctionRequest().withFunctionName(lambdaFunction.getFunctionName())).getConfiguration().getFunctionArn());
getLog().info("Cleaning up orphaned triggers.");
// Add clean up orphaned trigger functions for each integration here:
cleanUpOrphanedCloudWatchEventRules
.andThen(cleanUpOrphanedDynamoDBTriggers)
.andThen(cleanUpOrphanedKinesisTriggers)
.andThen(cleanUpOrphanedSNSTriggers)
.andThen(cleanUpOrphanedAlexaSkillsTriggers)
.andThen(cleanUpOrphanedLexSkillsTriggers)
.apply(lambdaFunction);
} catch (ResourceNotFoundException ign1) {
getLog().debug("Assuming function has no orphan triggers to clean up since it doesn't exist yet.");
}
return lambdaFunction;
};
Function<LambdaFunction, LambdaFunction> createOrUpdate = lambdaFunction -> {
try {
lambdaFunction.setFunctionArn(lambdaClient.getFunction(
new GetFunctionRequest().withFunctionName(lambdaFunction.getFunctionName())).getConfiguration().getFunctionArn());
of(getFunction(lambdaFunction))
.filter(getFunctionResult -> shouldUpdate(lambdaFunction, getFunctionResult))
.map(getFujnctionResult ->
updateFunctionCode
.andThen(updateFunctionConfig)
.andThen(createOrUpdateAliases)
.andThen(createOrUpdateTriggers)
.andThen(createOrUpdateKeepAlive)
.apply(lambdaFunction));
} catch (ResourceNotFoundException ign) {
createFunction.andThen(createOrUpdateAliases)
.andThen(createOrUpdateTriggers)
.apply(lambdaFunction);
}
return lambdaFunction;
};
private PutObjectResult upload(File file) {
getLog().info("Uploading " + functionCode + " to AWS S3 bucket " + s3Bucket);
PutObjectResult putObjectResult = s3Client.putObject(s3Bucket, fileName, file);
getLog().info("Upload complete...");
return putObjectResult;
}
private ObjectMetadata getObjectMetadata(String bucket) {
try {
return s3Client.getObjectMetadata(bucket, fileName);
} catch (AmazonS3Exception ignored) {
return null;
}
}
private String getBucket() {
if (s3Client.listBuckets().stream().noneMatch(p -> Objects.equals(p.getName(), s3Bucket))) {
getLog().info("Created bucket s3://" + s3Client.createBucket(s3Bucket).getName());
}
return s3Bucket;
}
}
| deploy λ function if local code ≠ s3 code
Motivation
Assuming the S3 location is the canonical source for your λ code
it is right to deploy a function only when the code differs.
Previously the decision to update was base on either of three
things:
- function does not exist on AWS Lambda
- function JSON configuration has changed (local ≠ lambda)
- forced update using the <forceUpdate> setting
Changes
λ functions are deployed when the code package's MD5 hash
differs with the S3 object.
For example, say your code.zip file's hash is XXXY and S3's
object s3://yourpackages/code.zip has a hash of XXXZ. Your lambda
functions will be deployed in this case.
If the hashes match then no code changes were made, hence no
deployment is necessary. One could still <forceUpdate> if they
wanted to.
Code Changes
- Introduced outcome enum to determine if local function code
differs with S3.
- Cleaned up create/update process to not rely on exception
handing.
- Consistent use of String.format.
Problems
- MD5 hashes have the potential for collisions but it's probably
unlikely. S3 only computes MD5 checksums for objects anyway. In
the future we could compute SHA256 checksums and store on the
objects though.
| src/main/java/com/github/seanroy/plugins/DeployLambdaMojo.java | deploy λ function if local code ≠ s3 code | <ide><path>rc/main/java/com/github/seanroy/plugins/DeployLambdaMojo.java
<ide>
<ide> import java.io.File;
<ide> import java.io.FileInputStream;
<add>import java.io.IOException;
<ide> import java.util.ArrayList;
<ide> import java.util.List;
<ide> import java.util.Objects;
<ide> import java.util.function.Function;
<ide> import java.util.stream.Collectors;
<ide>
<add>import com.amazonaws.services.lambda.AWSLambda;
<add>import com.amazonaws.services.s3.AmazonS3;
<ide> import org.apache.commons.codec.digest.DigestUtils;
<ide> import org.apache.maven.plugin.MojoExecutionException;
<add>import org.apache.maven.plugin.logging.Log;
<ide> import org.apache.maven.plugins.annotations.Mojo;
<ide>
<ide> import com.amazonaws.auth.policy.Policy;
<ide> public void execute() throws MojoExecutionException {
<ide> super.execute();
<ide> try {
<del> uploadJarToS3();
<del> lambdaFunctions.stream().map(f -> {
<del> getLog().info("---- Create or update " + f.getFunctionName() + " -----");
<del> return f;
<del> }).forEach(lf ->
<del> getFunctionPolicy
<del> .andThen(cleanUpOrphans)
<del> .andThen(createOrUpdate)
<del> .apply(lf));
<add> final LambdaCodeComparisonOutcome codeDeployOutcome = uploadJarToS3();
<add> lambdaFunctions.stream()
<add> .peek(f ->
<add> getLog().info("---- Create or update " + f.getFunctionName() + " -----"))
<add> .forEach(lf -> {
<add> // check if we need to update
<add> final GetFunctionResult functionResult = getLambdaFunction(lambdaClient, lf.getFunctionName());
<add> final Function<LambdaFunction, LambdaFunction> updateFunction;
<add> updateFunction = shouldUpdate(lf, functionResult, codeDeployOutcome)
<add> ? createOrUpdate
<add> : Function.identity();
<add>
<add> // clean up and update
<add> getFunctionPolicy
<add> .andThen(cleanUpOrphans)
<add> .andThen(updateFunction)
<add> .apply(lf);
<add> });
<ide> } catch (Exception e) {
<ide> getLog().error("Error during processing", e);
<ide> throw new MojoExecutionException(e.getMessage());
<ide> }
<ide> }
<ide>
<del> private boolean shouldUpdate(LambdaFunction lambdaFunction, GetFunctionResult getFunctionResult) {
<add> private boolean shouldUpdate(
<add> LambdaFunction lambdaFunction, GetFunctionResult getFunctionResult,
<add> LambdaCodeComparisonOutcome codeDeployOutcome) {
<add>
<add> // shortcut: if function does not exist we need to deploy
<add> if (getFunctionResult == null) {
<add> getLog().info(String.format("Deploy. Function %s does not exist.", lambdaFunction.getFunctionName()));
<add> return true;
<add> }
<add>
<ide> boolean isConfigurationChanged = isConfigurationChanged(lambdaFunction, getFunctionResult);
<ide> if (!isConfigurationChanged) {
<del> getLog().info("Config hasn't changed for " + lambdaFunction.getFunctionName());
<add> getLog().info(String.format("Config hasn't changed for %s.", lambdaFunction.getFunctionName()));
<ide> }
<ide> if (forceUpdate) {
<del> getLog().info("Forcing update for " + lambdaFunction.getFunctionName());
<del> }
<del>
<del> return forceUpdate || isConfigurationChanged;
<add> getLog().info(String.format("Deploy. Update forced for %s.", lambdaFunction.getFunctionName()));
<add> }
<add> if (codeDeployOutcome.shouldUpdateS3) {
<add> getLog().info(String.format("Deploy. Local function code differs with S3 for %s.", lambdaFunction.getFunctionName()));
<add> }
<add>
<add> return forceUpdate || isConfigurationChanged || codeDeployOutcome.shouldUpdateS3;
<ide> }
<ide>
<ide> /*
<ide> .withSubnetIds(lambdaFunction.getSubnetIds());
<ide> }
<ide>
<del> private void uploadJarToS3() throws Exception {
<del> String bucket = getBucket();
<del> File file = new File(functionCode);
<del> String localmd5 = DigestUtils.md5Hex(new FileInputStream(file));
<del> getLog().debug(String.format("Local file's MD5 hash is %s.", localmd5));
<del>
<del> ofNullable(getObjectMetadata(bucket))
<del> .map(ObjectMetadata::getETag)
<del> .map(remoteMD5 -> {
<del> getLog().info(fileName + " exists in S3 with MD5 hash " + remoteMD5);
<del> // This comparison will no longer work if we ever go to multipart uploads. Etags are not
<del> // computed as MD5 sums for multipart uploads in s3.
<del> return localmd5.equals(remoteMD5);
<del> })
<del> .map(isTheSame -> {
<del> if (isTheSame) {
<del> getLog().info(fileName + " is up to date in AWS S3 bucket " + s3Bucket + ". Not uploading...");
<del> return true;
<del> }
<del> return null; // file should be imported
<del> })
<del> .orElseGet(() -> {
<del> upload(file);
<del> return true;
<del> });
<add> private LambdaCodeComparisonOutcome uploadJarToS3() throws IOException {
<add> final File localFunctionCode = new File(functionCode);
<add> final LambdaCodeComparisonOutcome outcome = compareCodeWithS3(localFunctionCode, s3Bucket, fileName, s3Client, getLog());
<add> if (outcome.shouldUpdateS3) {
<add> upload(localFunctionCode);
<add> }
<add>
<add> return outcome;
<add> }
<add>
<add> private static LambdaCodeComparisonOutcome compareCodeWithS3(
<add> final File localDeliverable, final String s3Bucket, final String remoteS3File,
<add> final AmazonS3 s3, final Log log) throws IOException {
<add>
<add> String localMD5 = DigestUtils.md5Hex(new FileInputStream(localDeliverable));
<add> log.debug(String.format("Local file's MD5 hash is %s.", localMD5));
<add>
<add> final ObjectMetadata objectMetadata = getObjectMetadata(s3, s3Bucket, remoteS3File);
<add> if (objectMetadata == null) {
<add> return LambdaCodeComparisonOutcome.S3_OBJECT_MISSING;
<add> }
<add>
<add> final String remoteS3FileMD5 = objectMetadata.getETag();
<add> log.info(String.format("%s exists in S3 with MD5 hash %s", remoteS3File, remoteS3FileMD5));
<add>
<add> if (localMD5.equals(remoteS3FileMD5)) {
<add> log.info(String.format("%s is up to date in AWS S3 bucket %s. Not uploading...", remoteS3File, s3Bucket));
<add> return LambdaCodeComparisonOutcome.MD5_EQUALS;
<add> } else {
<add> log.info(String.format("Local file %s hash differs with file in AWS S3 bucket %s. Uploading...", localDeliverable, s3Bucket));
<add> return LambdaCodeComparisonOutcome.MD5_DIFFERENT;
<add> }
<ide> }
<ide>
<ide> /**
<ide> return lambdaFunction;
<ide> };
<ide>
<del> Function<LambdaFunction, LambdaFunction> createOrUpdate = lambdaFunction -> {
<del> try {
<del> lambdaFunction.setFunctionArn(lambdaClient.getFunction(
<del> new GetFunctionRequest().withFunctionName(lambdaFunction.getFunctionName())).getConfiguration().getFunctionArn());
<del> of(getFunction(lambdaFunction))
<del> .filter(getFunctionResult -> shouldUpdate(lambdaFunction, getFunctionResult))
<del> .map(getFujnctionResult ->
<del> updateFunctionCode
<del> .andThen(updateFunctionConfig)
<del> .andThen(createOrUpdateAliases)
<del> .andThen(createOrUpdateTriggers)
<del> .andThen(createOrUpdateKeepAlive)
<del> .apply(lambdaFunction));
<del> } catch (ResourceNotFoundException ign) {
<del> createFunction.andThen(createOrUpdateAliases)
<del> .andThen(createOrUpdateTriggers)
<del> .apply(lambdaFunction);
<del> }
<del>
<del> return lambdaFunction;
<add> Function<LambdaFunction, LambdaFunction> createOrUpdate = (lambdaFunction) -> {
<add> final GetFunctionResult result = getLambdaFunction(lambdaClient, lambdaFunction.getFunctionName());
<add> if (result == null) {
<add> createFunction.andThen(createOrUpdateAliases)
<add> .andThen(createOrUpdateTriggers)
<add> .apply(lambdaFunction);
<add> } else {
<add> lambdaFunction.setFunctionArn(result.getConfiguration().getFunctionArn());
<add> updateFunctionCode
<add> .andThen(updateFunctionConfig)
<add> .andThen(createOrUpdateAliases)
<add> .andThen(createOrUpdateTriggers)
<add> .andThen(createOrUpdateKeepAlive)
<add> .apply(lambdaFunction);
<add> }
<add> return lambdaFunction;
<ide> };
<ide>
<ide> private PutObjectResult upload(File file) {
<ide> return putObjectResult;
<ide> }
<ide>
<del> private ObjectMetadata getObjectMetadata(String bucket) {
<del> try {
<del> return s3Client.getObjectMetadata(bucket, fileName);
<add> private static ObjectMetadata getObjectMetadata(final AmazonS3 s3, final String bucket, final String fileName) {
<add> try {
<add> return s3.getObjectMetadata(bucket, fileName);
<ide> } catch (AmazonS3Exception ignored) {
<add> return null;
<add> }
<add> }
<add>
<add> private static GetFunctionResult getLambdaFunction(final AWSLambda lambda, final String name) {
<add> try {
<add> return lambda.getFunction(new GetFunctionRequest().withFunctionName(name));
<add> } catch (ResourceNotFoundException rnfe) {
<ide> return null;
<ide> }
<ide> }
<ide> }
<ide> return s3Bucket;
<ide> }
<add>
<add> /**
<add> * {@link LambdaCodeComparisonOutcome} states the possible outcomes of comparing the local
<add> * lambda code deliverable with the corresponding object in S3.
<add> */
<add> enum LambdaCodeComparisonOutcome {
<add> MD5_EQUALS(false),
<add> MD5_DIFFERENT(true),
<add> S3_OBJECT_MISSING(true);
<add>
<add> final boolean shouldUpdateS3;
<add>
<add> LambdaCodeComparisonOutcome(final boolean shouldUpdateS3) {
<add> this.shouldUpdateS3 = shouldUpdateS3;
<add> }
<add> }
<ide> } |
|
Java | apache-2.0 | 38bafeaf27b0a0d033c727c174b75ef4ae23d93a | 0 | jeremylong/DependencyCheck,stefanneuhaus/DependencyCheck,jeremylong/DependencyCheck,stefanneuhaus/DependencyCheck,jeremylong/DependencyCheck,awhitford/DependencyCheck,stefanneuhaus/DependencyCheck,awhitford/DependencyCheck,awhitford/DependencyCheck,awhitford/DependencyCheck,awhitford/DependencyCheck,jeremylong/DependencyCheck,stefanneuhaus/DependencyCheck,jeremylong/DependencyCheck,awhitford/DependencyCheck,awhitford/DependencyCheck,stefanneuhaus/DependencyCheck,jeremylong/DependencyCheck,stefanneuhaus/DependencyCheck,awhitford/DependencyCheck,jeremylong/DependencyCheck,jeremylong/DependencyCheck,stefanneuhaus/DependencyCheck,stefanneuhaus/DependencyCheck | /*
* This file is part of dependency-check-core.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Copyright (c) 2015 Institute for Defense Analyses. All Rights Reserved.
*/
package org.owasp.dependencycheck.analyzer;
import edu.emory.mathcs.backport.java.util.Arrays;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import org.junit.After;
import org.junit.Assume;
import org.junit.Before;
import org.junit.Test;
import org.owasp.dependencycheck.BaseDBTestCase;
import org.owasp.dependencycheck.BaseTest;
import org.owasp.dependencycheck.Engine;
import org.owasp.dependencycheck.analyzer.exception.AnalysisException;
import org.owasp.dependencycheck.data.nvdcve.DatabaseException;
import org.owasp.dependencycheck.dependency.Dependency;
import org.owasp.dependencycheck.dependency.Vulnerability;
import org.owasp.dependencycheck.exception.ExceptionCollection;
import org.owasp.dependencycheck.utils.Settings;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.owasp.dependencycheck.data.update.exception.UpdateException;
import org.owasp.dependencycheck.exception.InitializationException;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import org.owasp.dependencycheck.dependency.EvidenceType;
/**
* Unit tests for {@link RubyBundleAuditAnalyzer}.
*
* @author Dale Visser
*/
public class RubyBundleAuditAnalyzerIT extends BaseDBTestCase {
private static final Logger LOGGER = LoggerFactory.getLogger(RubyBundleAuditAnalyzerIT.class);
/**
* The analyzer to test.
*/
private RubyBundleAuditAnalyzer analyzer;
/**
* Correctly setup the analyzer for testing.
*
* @throws Exception thrown if there is a problem
*/
@Before
@Override
public void setUp() throws Exception {
super.setUp();
//test testAddCriticalityToVulnerability requires CVE-2015-3225 so we must ensure db is updated.
//getSettings().setBoolean(Settings.KEYS.AUTO_UPDATE, false);
getSettings().setBoolean(Settings.KEYS.ANALYZER_NEXUS_ENABLED, false);
getSettings().setBoolean(Settings.KEYS.ANALYZER_CENTRAL_ENABLED, false);
analyzer = new RubyBundleAuditAnalyzer();
analyzer.initialize(getSettings());
analyzer.setFilesMatched(true);
}
/**
* Cleanup the analyzer's temp files, etc.
*
* @throws Exception thrown if there is a problem
*/
@After
@Override
public void tearDown() throws Exception {
if (analyzer != null) {
analyzer.close();
analyzer = null;
}
super.tearDown();
}
/**
* Test Ruby Gemspec name.
*/
@Test
public void testGetName() {
assertThat(analyzer.getName(), is("Ruby Bundle Audit Analyzer"));
}
/**
* Test Ruby Bundler Audit file support.
*/
@Test
public void testSupportsFiles() {
assertThat(analyzer.accept(new File("Gemfile.lock")), is(true));
}
/**
* Test Ruby BundlerAudit analysis.
*
* @throws AnalysisException is thrown when an exception occurs.
*/
@Test
public void testAnalysis() throws AnalysisException, DatabaseException {
try (Engine engine = new Engine(getSettings())) {
engine.openDatabase();
analyzer.prepare(engine);
final String resource = "ruby/vulnerable/gems/rails-4.1.15/Gemfile.lock";
final Dependency result = new Dependency(BaseTest.getResourceAsFile(this, resource));
analyzer.analyze(result, engine);
final Dependency[] dependencies = engine.getDependencies();
final int size = dependencies.length;
assertTrue(size >= 1);
boolean found = false;
for (Dependency dependency : dependencies) {
found = dependency.getEvidence(EvidenceType.PRODUCT).toString().toLowerCase().contains("redcarpet");
found &= dependency.getEvidence(EvidenceType.VERSION).toString().toLowerCase().contains("2.2.2");
found &= dependency.getFilePath().endsWith(resource);
found &= dependency.getFileName().equals("Gemfile.lock");
if (found) {
break;
}
}
assertTrue("redcarpet was not identified", found);
} catch (InitializationException | DatabaseException | AnalysisException e) {
LOGGER.warn("Exception setting up RubyBundleAuditAnalyzer. Make sure Ruby gem bundle-audit is installed. You may also need to set property \"analyzer.bundle.audit.path\".");
Assume.assumeNoException("Exception setting up RubyBundleAuditAnalyzer; bundle audit may not be installed, or property \"analyzer.bundle.audit.path\" may not be set.", e);
}
}
/**
* Test Ruby addCriticalityToVulnerability
*/
@Test
public void testAddCriticalityToVulnerability() throws AnalysisException, DatabaseException {
try (Engine engine = new Engine(getSettings())) {
engine.doUpdates(true);
analyzer.prepare(engine);
final Dependency result = new Dependency(BaseTest.getResourceAsFile(this,
"ruby/vulnerable/gems/sinatra/Gemfile.lock"));
analyzer.analyze(result, engine);
Dependency dependency = engine.getDependencies()[0];
Vulnerability vulnerability = dependency.getVulnerabilities(true).iterator().next();
assertEquals(vulnerability.getCvssScore(), 5.0f, 0.0);
} catch (InitializationException | DatabaseException | AnalysisException | UpdateException e) {
LOGGER.warn("Exception setting up RubyBundleAuditAnalyzer. Make sure Ruby gem bundle-audit is installed. You may also need to set property \"analyzer.bundle.audit.path\".");
Assume.assumeNoException("Exception setting up RubyBundleAuditAnalyzer; bundle audit may not be installed, or property \"analyzer.bundle.audit.path\" may not be set.", e);
}
}
/**
* Test when Ruby bundle-audit is not available on the system.
*
* @throws AnalysisException is thrown when an exception occurs.
*/
@Test
public void testMissingBundleAudit() throws AnalysisException, DatabaseException {
//TODO - this test is invalid as phantom bundle audit may not exist - but if bundle-audit
// is still on the path then initialization works and the bundle-audit on the path works.
//set a non-exist bundle-audit
// getSettings().setString(Settings.KEYS.ANALYZER_BUNDLE_AUDIT_PATH, "phantom-bundle-audit");
// analyzer.initialize(getSettings());
// try {
// //initialize should fail.
// analyzer.prepare(null);
// } catch (Exception e) {
// //expected, so ignore.
// assertNotNull(e);
// } finally {
// assertThat(analyzer.isEnabled(), is(false));
// LOGGER.info("phantom-bundle-audit is not available. Ruby Bundle Audit Analyzer is disabled as expected.");
// }
}
/**
* Test Ruby dependencies and their paths.
*
* @throws AnalysisException is thrown when an exception occurs.
* @throws DatabaseException thrown when an exception occurs
*/
@Test
public void testDependenciesPath() throws AnalysisException, DatabaseException {
try (Engine engine = new Engine(getSettings())) {
try {
engine.scan(BaseTest.getResourceAsFile(this, "ruby/vulnerable/gems/rails-4.1.15/"));
engine.analyzeDependencies();
} catch (NullPointerException ex) {
LOGGER.error("NPE", ex);
fail(ex.getMessage());
} catch (ExceptionCollection ex) {
Assume.assumeNoException("Exception setting up RubyBundleAuditAnalyzer; bundle audit may not be installed, or property \"analyzer.bundle.audit.path\" may not be set.", ex);
return;
}
Dependency[] dependencies = engine.getDependencies();
LOGGER.info("{} dependencies found.", dependencies.length);
}
}
}
| core/src/test/java/org/owasp/dependencycheck/analyzer/RubyBundleAuditAnalyzerIT.java | /*
* This file is part of dependency-check-core.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Copyright (c) 2015 Institute for Defense Analyses. All Rights Reserved.
*/
package org.owasp.dependencycheck.analyzer;
import edu.emory.mathcs.backport.java.util.Arrays;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import org.junit.After;
import org.junit.Assume;
import org.junit.Before;
import org.junit.Test;
import org.owasp.dependencycheck.BaseDBTestCase;
import org.owasp.dependencycheck.BaseTest;
import org.owasp.dependencycheck.Engine;
import org.owasp.dependencycheck.analyzer.exception.AnalysisException;
import org.owasp.dependencycheck.data.nvdcve.DatabaseException;
import org.owasp.dependencycheck.dependency.Dependency;
import org.owasp.dependencycheck.dependency.Vulnerability;
import org.owasp.dependencycheck.exception.ExceptionCollection;
import org.owasp.dependencycheck.utils.Settings;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.owasp.dependencycheck.data.update.exception.UpdateException;
import org.owasp.dependencycheck.exception.InitializationException;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import org.owasp.dependencycheck.dependency.EvidenceType;
/**
* Unit tests for {@link RubyBundleAuditAnalyzer}.
*
* @author Dale Visser
*/
public class RubyBundleAuditAnalyzerIT extends BaseDBTestCase {
private static final Logger LOGGER = LoggerFactory.getLogger(RubyBundleAuditAnalyzerIT.class);
/**
* The analyzer to test.
*/
private RubyBundleAuditAnalyzer analyzer;
/**
* Correctly setup the analyzer for testing.
*
* @throws Exception thrown if there is a problem
*/
@Before
@Override
public void setUp() throws Exception {
super.setUp();
//test testAddCriticalityToVulnerability requires CVE-2015-3225 so we must ensure db is updated.
//getSettings().setBoolean(Settings.KEYS.AUTO_UPDATE, false);
getSettings().setBoolean(Settings.KEYS.ANALYZER_NEXUS_ENABLED, false);
getSettings().setBoolean(Settings.KEYS.ANALYZER_CENTRAL_ENABLED, false);
analyzer = new RubyBundleAuditAnalyzer();
analyzer.initialize(getSettings());
analyzer.setFilesMatched(true);
}
/**
* Cleanup the analyzer's temp files, etc.
*
* @throws Exception thrown if there is a problem
*/
@After
@Override
public void tearDown() throws Exception {
if (analyzer != null) {
analyzer.close();
analyzer = null;
}
super.tearDown();
}
/**
* Test Ruby Gemspec name.
*/
@Test
public void testGetName() {
assertThat(analyzer.getName(), is("Ruby Bundle Audit Analyzer"));
}
/**
* Test Ruby Bundler Audit file support.
*/
@Test
public void testSupportsFiles() {
assertThat(analyzer.accept(new File("Gemfile.lock")), is(true));
}
/**
* Test Ruby BundlerAudit analysis.
*
* @throws AnalysisException is thrown when an exception occurs.
*/
@Test
public void testAnalysis() throws AnalysisException, DatabaseException {
try (Engine engine = new Engine(getSettings())) {
engine.openDatabase();
analyzer.prepare(engine);
final String resource = "ruby/vulnerable/gems/rails-4.1.15/Gemfile.lock";
final Dependency result = new Dependency(BaseTest.getResourceAsFile(this, resource));
analyzer.analyze(result, engine);
final Dependency[] dependencies = engine.getDependencies();
final int size = dependencies.length;
assertTrue(size >= 1);
boolean found = false;
for (Dependency dependency : dependencies) {
found = dependency.getEvidence(EvidenceType.PRODUCT).toString().toLowerCase().contains("redcarpet");
found &= dependency.getEvidence(EvidenceType.VERSION).toString().toLowerCase().contains("2.2.2");
found &= dependency.getFilePath().endsWith(resource);
found &= dependency.getFileName().equals("Gemfile.lock");
if (found) {
break;
}
}
assertTrue("redcarpet was not identified", found);
} catch (InitializationException | DatabaseException | AnalysisException e) {
LOGGER.warn("Exception setting up RubyBundleAuditAnalyzer. Make sure Ruby gem bundle-audit is installed. You may also need to set property \"analyzer.bundle.audit.path\".");
Assume.assumeNoException("Exception setting up RubyBundleAuditAnalyzer; bundle audit may not be installed, or property \"analyzer.bundle.audit.path\" may not be set.", e);
}
}
/**
* Test Ruby addCriticalityToVulnerability
*/
@Test
public void testAddCriticalityToVulnerability() throws AnalysisException, DatabaseException {
try (Engine engine = new Engine(getSettings())) {
engine.doUpdates(true);
analyzer.prepare(engine);
final Dependency result = new Dependency(BaseTest.getResourceAsFile(this,
"ruby/vulnerable/gems/sinatra/Gemfile.lock"));
analyzer.analyze(result, engine);
Dependency dependency = engine.getDependencies()[0];
Vulnerability vulnerability = dependency.getVulnerabilities(true).iterator().next();
assertEquals(vulnerability.getCvssScore(), 5.0f, 0.0);
} catch (InitializationException | DatabaseException | AnalysisException | UpdateException e) {
LOGGER.warn("Exception setting up RubyBundleAuditAnalyzer. Make sure Ruby gem bundle-audit is installed. You may also need to set property \"analyzer.bundle.audit.path\".");
Assume.assumeNoException("Exception setting up RubyBundleAuditAnalyzer; bundle audit may not be installed, or property \"analyzer.bundle.audit.path\" may not be set.", e);
}
}
/**
* Test when Ruby bundle-audit is not available on the system.
*
* @throws AnalysisException is thrown when an exception occurs.
*/
@Test
public void testMissingBundleAudit() throws AnalysisException, DatabaseException {
//TODO - this test is invalid as phantom bundle audit may not exist - but if bundle-audit
// is still on the path then initialization works and the bundle-audit on the path works.
//set a non-exist bundle-audit
// getSettings().setString(Settings.KEYS.ANALYZER_BUNDLE_AUDIT_PATH, "phantom-bundle-audit");
// analyzer.initialize(getSettings());
// try {
// //initialize should fail.
// analyzer.prepare(null);
// } catch (Exception e) {
// //expected, so ignore.
// assertNotNull(e);
// } finally {
// assertThat(analyzer.isEnabled(), is(false));
// LOGGER.info("phantom-bundle-audit is not available. Ruby Bundle Audit Analyzer is disabled as expected.");
// }
}
/**
* Test Ruby dependencies and their paths.
*
* @throws AnalysisException is thrown when an exception occurs.
* @throws DatabaseException thrown when an exception occurs
*/
@Test
public void testDependenciesPath() throws AnalysisException, DatabaseException {
try (Engine engine = new Engine(getSettings())) {
try {
engine.scan(BaseTest.getResourceAsFile(this, "ruby/vulnerable/gems/rails-4.1.15/"));
engine.analyzeDependencies();
} catch (NullPointerException ex) {
LOGGER.error("NPE", ex);
fail(ex.getMessage());
} catch (ExceptionCollection ex) {
Assume.assumeNoException("Exception setting up RubyBundleAuditAnalyzer; bundle audit may not be installed, or property \"analyzer.bundle.audit.path\" may not be set.", ex);
return;
}
List<Dependency> dependencies = new ArrayList<>(Arrays.asList(engine.getDependencies()));
LOGGER.info("{} dependencies found.", dependencies.size());
}
}
}
| minor updates to avoid build warnings
| core/src/test/java/org/owasp/dependencycheck/analyzer/RubyBundleAuditAnalyzerIT.java | minor updates to avoid build warnings | <ide><path>ore/src/test/java/org/owasp/dependencycheck/analyzer/RubyBundleAuditAnalyzerIT.java
<ide> Assume.assumeNoException("Exception setting up RubyBundleAuditAnalyzer; bundle audit may not be installed, or property \"analyzer.bundle.audit.path\" may not be set.", ex);
<ide> return;
<ide> }
<del> List<Dependency> dependencies = new ArrayList<>(Arrays.asList(engine.getDependencies()));
<del> LOGGER.info("{} dependencies found.", dependencies.size());
<add> Dependency[] dependencies = engine.getDependencies();
<add> LOGGER.info("{} dependencies found.", dependencies.length);
<ide> }
<ide> }
<ide> } |
|
Java | lgpl-2.1 | 8f860e5f4fee9a371c6d06a1120ef56b30bed4b3 | 0 | xwiki/xwiki-platform,xwiki/xwiki-platform,xwiki/xwiki-platform,xwiki/xwiki-platform,xwiki/xwiki-platform | /*
* See the NOTICE file distributed with this work for additional
* information regarding copyright ownership.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.xwiki.test.docker.internal.junit5.database;
import java.util.Properties;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.testcontainers.containers.Container;
import org.testcontainers.containers.JdbcDatabaseContainer;
import org.testcontainers.containers.MariaDBContainer;
import org.testcontainers.containers.MySQLContainer;
import org.testcontainers.containers.Network;
import org.testcontainers.containers.OracleContainer;
import org.testcontainers.containers.PostgreSQLContainer;
import org.xwiki.test.docker.internal.junit5.AbstractContainerExecutor;
import org.xwiki.test.docker.junit5.TestConfiguration;
/**
* Create and execute the Docker database container for the tests.
*
* @version $Id$
* @since 10.9
*/
public class DatabaseContainerExecutor extends AbstractContainerExecutor
{
private static final Logger LOGGER = LoggerFactory.getLogger(DatabaseContainerExecutor.class);
private static final String DBNAME = "xwiki";
private static final String DBUSERNAME = DBNAME;
private static final String DBPASSWORD = DBUSERNAME;
/**
* @param testConfiguration the configuration to build (database, debug mode, etc)
* @throws Exception if the container fails to start
*/
public void start(TestConfiguration testConfiguration) throws Exception
{
switch (testConfiguration.getDatabase()) {
case MYSQL:
startMySQLContainer(testConfiguration);
break;
case MARIADB:
startMariaDBContainer(testConfiguration);
break;
case POSTGRESQL:
startPostgreSQLContainer(testConfiguration);
break;
case ORACLE:
startOracleContainer(testConfiguration);
break;
case HSQLDB_EMBEDDED:
// We don't need a Docker image/container since HSQLDB can work in embedded mode.
// It's configured automatically in the custom XWiki WAR.
// Thus, nothing to do here!
testConfiguration.getDatabase().setIP("localhost");
break;
default:
throw new RuntimeException(String.format("Database [%s] is not yet supported!",
testConfiguration.getDatabase()));
}
}
/**
* @param testConfiguration the configuration to build (database, debug mode, etc)
*/
public void stop(TestConfiguration testConfiguration)
{
// Note that we don't need to stop the container as this is taken care of by TestContainers
}
private void startMySQLContainer(TestConfiguration testConfiguration) throws Exception
{
// docker run --net=xwiki-nw --name mysql-xwiki -v /my/own/mysql:/var/lib/mysql
// -e MYSQL_ROOT_PASSWORD=xwiki -e MYSQL_USER=xwiki -e MYSQL_PASSWORD=xwiki
// -e MYSQL_DATABASE=xwiki -d mysql:5.7 --character-set-server=utf8 --collation-server=utf8_bin
// --explicit-defaults-for-timestamp=1
JdbcDatabaseContainer<?> databaseContainer;
if (testConfiguration.getDatabaseTag() != null) {
databaseContainer = new MySQLContainer<>(String.format("mysql:%s", testConfiguration.getDatabaseTag()));
} else {
databaseContainer = new MySQLContainer<>();
}
startMySQLContainer(databaseContainer, testConfiguration);
}
private void startMySQLContainer(JdbcDatabaseContainer<?> databaseContainer, TestConfiguration testConfiguration)
throws Exception
{
databaseContainer
.withDatabaseName(DBNAME)
.withUsername(DBUSERNAME)
.withPassword(DBPASSWORD);
mountDatabaseDataIfNeeded(databaseContainer, "./target/mysql", "/var/lib/mysql", testConfiguration);
// Note: the "explicit-defaults-for-timestamp" parameter has been introduced in MySQL 5.6.6+ only and using it
// in older versions make MySQL fail to start.
Properties commands = new Properties();
commands.setProperty("character-set-server", "utf8mb4");
commands.setProperty("collation-server", "utf8mb4_bin");
if (!isMySQL55x(testConfiguration)) {
commands.setProperty("explicit-defaults-for-timestamp", "1");
}
// MySQL 8.x has changed the default authentication plugin value so we need to explicitly configure it to get
// the native password mechanism.
// The reason we don't include when the tag is null is because with the TC version we use, MySQLContainer
// defaults to
if (isMySQL8xPlus(testConfiguration)) {
commands.setProperty("default-authentication-plugin", "mysql_native_password");
}
databaseContainer.withCommand(mergeCommands(commands, testConfiguration.getDatabaseCommands()));
startDatabaseContainer(databaseContainer, 3306, testConfiguration);
// Allow the XWiki user to create databases (ie create subwikis)
grantMySQLPrivileges(databaseContainer);
}
private void grantMySQLPrivileges(JdbcDatabaseContainer<?> databaseContainer) throws Exception
{
// Retry 3 times, as we're getting some flickering from time to time with the message:
// ERROR 1045 (28000): Access denied for user 'root'@'localhost' (using password: YES)
LOGGER.info("Setting MySQL permissions to create subwikis");
for (int i = 0; i < 3; i++) {
// In order to avoid "Warning: Using a password on the command line interface can be insecure.", we
// put the credentials in a file.
databaseContainer.execInContainer("sh", "-c",
String.format("echo '[client]\nuser = root\npassword = %s' > credentials.cnf", DBPASSWORD));
Container.ExecResult result = databaseContainer.execInContainer("mysql",
"--defaults-extra-file=credentials.cnf", "-e",
String.format("grant all privileges on *.* to '%s'@'%%'", DBUSERNAME));
if (result.getExitCode() == 0) {
break;
} else {
String errorMessage = result.getStderr().isEmpty() ? result.getStdout() : result.getStderr();
if (i == 2) {
throw new RuntimeException(String.format("Failed to grant all privileges to user [%s] on MySQL "
+ "with return code [%d] and console logs [%s]", DBUSERNAME, result.getExitCode(),
errorMessage));
} else {
LOGGER.info("Failed to set MySQL permissions, retrying ({}/2)... Error: [{}]", i + 1, errorMessage);
Thread.sleep(1000L);
}
}
}
}
private boolean isMySQL55x(TestConfiguration testConfiguration)
{
return testConfiguration.getDatabaseTag() != null && testConfiguration.getDatabaseTag().startsWith("5.5");
}
private boolean isMySQL8xPlus(TestConfiguration testConfiguration)
{
boolean isMySQL8xPlus;
if (testConfiguration.getDatabaseTag() != null) {
isMySQL8xPlus = testConfiguration.getDatabaseTag().equals("latest")
|| extractMajor(testConfiguration.getDatabaseTag()) >= 8;
} else {
isMySQL8xPlus = extractMajor(MySQLContainer.DEFAULT_TAG) >= 8;
}
return isMySQL8xPlus;
}
private int extractMajor(String version)
{
return Integer.valueOf(StringUtils.substringBefore(version, "."));
}
private void startMariaDBContainer(TestConfiguration testConfiguration) throws Exception
{
JdbcDatabaseContainer<?> databaseContainer;
if (testConfiguration.getDatabaseTag() != null) {
databaseContainer = new MariaDBContainer<>(String.format("mariadb:%s", testConfiguration.getDatabaseTag()));
} else {
databaseContainer = new MariaDBContainer<>();
}
startMySQLContainer(databaseContainer, testConfiguration);
}
private void startPostgreSQLContainer(TestConfiguration testConfiguration) throws Exception
{
// docker run --net=xwiki-nw --name postgres-xwiki -v /my/own/postgres:/var/lib/postgresql/data
// -e POSTGRES_ROOT_PASSWORD=xwiki -e POSTGRES_USER=xwiki -e POSTGRES_PASSWORD=xwiki
// -e POSTGRES_DB=xwiki -e POSTGRES_INITDB_ARGS="--encoding=UTF8" -d postgres:9.5
JdbcDatabaseContainer<?> databaseContainer;
if (testConfiguration.getDatabaseTag() != null) {
databaseContainer =
new PostgreSQLContainer<>(String.format("postgres:%s", testConfiguration.getDatabaseTag()));
} else {
databaseContainer = new PostgreSQLContainer<>();
}
databaseContainer
.withDatabaseName(DBNAME)
.withUsername(DBUSERNAME)
.withPassword(DBPASSWORD);
mountDatabaseDataIfNeeded(databaseContainer, "./target/postgres", "/var/lib/postgresql/data",
testConfiguration);
databaseContainer.addEnv("POSTGRES_ROOT_PASSWORD", DBPASSWORD);
databaseContainer.addEnv("POSTGRES_INITDB_ARGS", "--encoding=UTF8");
startDatabaseContainer(databaseContainer, 5432, testConfiguration);
}
private void mountDatabaseDataIfNeeded(JdbcDatabaseContainer<?> databaseContainer, String hostPath,
String containerPath, TestConfiguration testConfiguration)
{
if (testConfiguration.isDatabaseDataSaved()) {
// Note 1: This allows re-running the test with the database already provisioned without having to redo
// the provisioning. Running "mvn clean" will remove the database data.
// Note 2: This won't work in the DOOD use case. For that to work we would need to copy the data instead
// of mounting the volume but the time to do that would be counter productive and cost in execution time
// when the goal is to win time...
databaseContainer.withFileSystemBind(hostPath, containerPath);
}
}
private void startOracleContainer(TestConfiguration testConfiguration) throws Exception
{
JdbcDatabaseContainer<?> databaseContainer;
if (testConfiguration.getDatabaseTag() != null) {
databaseContainer = new OracleContainer(String.format("xwiki/oracle-database:%s",
testConfiguration.getDatabaseTag()));
} else {
databaseContainer = new OracleContainer("xwiki/oracle-database");
}
databaseContainer
.withUsername("system")
.withPassword("oracle");
startDatabaseContainer(databaseContainer, 1521, testConfiguration);
}
private void startDatabaseContainer(JdbcDatabaseContainer<?> databaseContainer, int port,
TestConfiguration testConfiguration) throws Exception
{
databaseContainer
.withExposedPorts(port)
.withNetwork(Network.SHARED)
.withNetworkAliases("xwikidb");
start(databaseContainer, testConfiguration);
if (testConfiguration.getServletEngine().isOutsideDocker()) {
testConfiguration.getDatabase().setIP(databaseContainer.getContainerIpAddress());
testConfiguration.getDatabase().setPort(databaseContainer.getMappedPort(port));
} else {
testConfiguration.getDatabase().setIP(databaseContainer.getNetworkAliases().get(0));
testConfiguration.getDatabase().setPort(port);
}
}
}
| xwiki-platform-core/xwiki-platform-test/xwiki-platform-test-docker/src/main/java/org/xwiki/test/docker/internal/junit5/database/DatabaseContainerExecutor.java | /*
* See the NOTICE file distributed with this work for additional
* information regarding copyright ownership.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.xwiki.test.docker.internal.junit5.database;
import java.util.Properties;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.testcontainers.containers.Container;
import org.testcontainers.containers.JdbcDatabaseContainer;
import org.testcontainers.containers.MariaDBContainer;
import org.testcontainers.containers.MySQLContainer;
import org.testcontainers.containers.Network;
import org.testcontainers.containers.OracleContainer;
import org.testcontainers.containers.PostgreSQLContainer;
import org.xwiki.test.docker.internal.junit5.AbstractContainerExecutor;
import org.xwiki.test.docker.junit5.TestConfiguration;
/**
* Create and execute the Docker database container for the tests.
*
* @version $Id$
* @since 10.9
*/
public class DatabaseContainerExecutor extends AbstractContainerExecutor
{
private static final Logger LOGGER = LoggerFactory.getLogger(DatabaseContainerExecutor.class);
private static final String DBNAME = "xwiki";
private static final String DBUSERNAME = DBNAME;
private static final String DBPASSWORD = DBUSERNAME;
/**
* @param testConfiguration the configuration to build (database, debug mode, etc)
* @throws Exception if the container fails to start
*/
public void start(TestConfiguration testConfiguration) throws Exception
{
switch (testConfiguration.getDatabase()) {
case MYSQL:
startMySQLContainer(testConfiguration);
break;
case MARIADB:
startMariaDBContainer(testConfiguration);
break;
case POSTGRESQL:
startPostgreSQLContainer(testConfiguration);
break;
case ORACLE:
startOracleContainer(testConfiguration);
break;
case HSQLDB_EMBEDDED:
// We don't need a Docker image/container since HSQLDB can work in embedded mode.
// It's configured automatically in the custom XWiki WAR.
// Thus, nothing to do here!
testConfiguration.getDatabase().setIP("localhost");
break;
default:
throw new RuntimeException(String.format("Database [%s] is not yet supported!",
testConfiguration.getDatabase()));
}
}
/**
* @param testConfiguration the configuration to build (database, debug mode, etc)
*/
public void stop(TestConfiguration testConfiguration)
{
// Note that we don't need to stop the container as this is taken care of by TestContainers
}
private void startMySQLContainer(TestConfiguration testConfiguration) throws Exception
{
// docker run --net=xwiki-nw --name mysql-xwiki -v /my/own/mysql:/var/lib/mysql
// -e MYSQL_ROOT_PASSWORD=xwiki -e MYSQL_USER=xwiki -e MYSQL_PASSWORD=xwiki
// -e MYSQL_DATABASE=xwiki -d mysql:5.7 --character-set-server=utf8 --collation-server=utf8_bin
// --explicit-defaults-for-timestamp=1
JdbcDatabaseContainer<?> databaseContainer;
if (testConfiguration.getDatabaseTag() != null) {
databaseContainer = new MySQLContainer<>(String.format("mysql:%s", testConfiguration.getDatabaseTag()));
} else {
databaseContainer = new MySQLContainer<>();
}
startMySQLContainer(databaseContainer, testConfiguration);
}
private void startMySQLContainer(JdbcDatabaseContainer<?> databaseContainer, TestConfiguration testConfiguration)
throws Exception
{
databaseContainer
.withDatabaseName(DBNAME)
.withUsername(DBUSERNAME)
.withPassword(DBPASSWORD);
mountDatabaseDataIfNeeded(databaseContainer, "./target/mysql", "/var/lib/mysql", testConfiguration);
// Note: the "explicit-defaults-for-timestamp" parameter has been introduced in MySQL 5.6.6+ only and using it
// in older versions make MySQL fail to start.
Properties commands = new Properties();
commands.setProperty("character-set-server", "utf8mb4");
commands.setProperty("collation-server", "utf8mb4_bin");
if (!isMySQL55x(testConfiguration)) {
commands.setProperty("explicit-defaults-for-timestamp", "1");
}
// MySQL 8.x has changed the default authentication plugin value so we need to explicitly configure it to get
// the native password mechanism.
// The reason we don't include when the tag is null is because with the TC version we use, MySQLContainer
// defaults to
if (isMySQL8xPlus(testConfiguration)) {
commands.setProperty("default-authentication-plugin", "mysql_native_password");
}
databaseContainer.withCommand(mergeCommands(commands, testConfiguration.getDatabaseCommands()));
startDatabaseContainer(databaseContainer, 3306, testConfiguration);
// Allow the XWiki user to create databases (ie create subwikis)
grantMySQLPrivileges(databaseContainer);
}
private void grantMySQLPrivileges(JdbcDatabaseContainer<?> databaseContainer) throws Exception
{
// Retry 3 times, as we're getting some flickering from time to time with the message:
// ERROR 1045 (28000): Access denied for user 'root'@'localhost' (using password: YES)
LOGGER.info("Setting MySQL permissions to create subwikis");
for (int i = 0; i < 3; i++) {
// In order to avoid "Warning: Using a password on the command line interface can be insecure.", we
// put the credentials in a file.
databaseContainer.execInContainer("sh", "-c",
String.format("echo '[client]\nuser = root\npassword = %s' > credentials.cnf", DBPASSWORD));
Container.ExecResult result = databaseContainer.execInContainer("mysql",
"--defaults-extra-file=credentials.cnf", "-e",
String.format("grant all privileges on *.* to '%s'@'%%'", DBUSERNAME));
if (result.getExitCode() == 0) {
break;
} else {
String errorMessage = result.getStderr().isEmpty() ? result.getStdout() : result.getStderr();
if (i == 2) {
throw new RuntimeException(String.format("Failed to grant all privileges to user [%s] on MySQL "
+ "with return code [%d] and console logs [%s]", DBUSERNAME, result.getExitCode(),
errorMessage));
} else {
LOGGER.info("Failed to set MySQL permissions, retrying ({}/2)... Error: [{}]", i + 1, errorMessage);
Thread.sleep(1000L);
}
}
}
}
private boolean isMySQL55x(TestConfiguration testConfiguration)
{
return testConfiguration.getDatabaseTag() != null && testConfiguration.getDatabaseTag().startsWith("5.5");
}
private boolean isMySQL8xPlus(TestConfiguration testConfiguration)
{
return (testConfiguration.getDatabaseTag() != null && extractMajor(testConfiguration.getDatabaseTag()) >= 8)
|| (extractMajor(MySQLContainer.DEFAULT_TAG) >= 8 && testConfiguration.getDatabaseTag() == null);
}
private int extractMajor(String version)
{
return Integer.valueOf(StringUtils.substringBefore(version, "."));
}
private void startMariaDBContainer(TestConfiguration testConfiguration) throws Exception
{
JdbcDatabaseContainer<?> databaseContainer;
if (testConfiguration.getDatabaseTag() != null) {
databaseContainer = new MariaDBContainer<>(String.format("mariadb:%s", testConfiguration.getDatabaseTag()));
} else {
databaseContainer = new MariaDBContainer<>();
}
startMySQLContainer(databaseContainer, testConfiguration);
}
private void startPostgreSQLContainer(TestConfiguration testConfiguration) throws Exception
{
// docker run --net=xwiki-nw --name postgres-xwiki -v /my/own/postgres:/var/lib/postgresql/data
// -e POSTGRES_ROOT_PASSWORD=xwiki -e POSTGRES_USER=xwiki -e POSTGRES_PASSWORD=xwiki
// -e POSTGRES_DB=xwiki -e POSTGRES_INITDB_ARGS="--encoding=UTF8" -d postgres:9.5
JdbcDatabaseContainer<?> databaseContainer;
if (testConfiguration.getDatabaseTag() != null) {
databaseContainer =
new PostgreSQLContainer<>(String.format("postgres:%s", testConfiguration.getDatabaseTag()));
} else {
databaseContainer = new PostgreSQLContainer<>();
}
databaseContainer
.withDatabaseName(DBNAME)
.withUsername(DBUSERNAME)
.withPassword(DBPASSWORD);
mountDatabaseDataIfNeeded(databaseContainer, "./target/postgres", "/var/lib/postgresql/data",
testConfiguration);
databaseContainer.addEnv("POSTGRES_ROOT_PASSWORD", DBPASSWORD);
databaseContainer.addEnv("POSTGRES_INITDB_ARGS", "--encoding=UTF8");
startDatabaseContainer(databaseContainer, 5432, testConfiguration);
}
private void mountDatabaseDataIfNeeded(JdbcDatabaseContainer<?> databaseContainer, String hostPath,
String containerPath, TestConfiguration testConfiguration)
{
if (testConfiguration.isDatabaseDataSaved()) {
// Note 1: This allows re-running the test with the database already provisioned without having to redo
// the provisioning. Running "mvn clean" will remove the database data.
// Note 2: This won't work in the DOOD use case. For that to work we would need to copy the data instead
// of mounting the volume but the time to do that would be counter productive and cost in execution time
// when the goal is to win time...
databaseContainer.withFileSystemBind(hostPath, containerPath);
}
}
private void startOracleContainer(TestConfiguration testConfiguration) throws Exception
{
JdbcDatabaseContainer<?> databaseContainer;
if (testConfiguration.getDatabaseTag() != null) {
databaseContainer = new OracleContainer(String.format("xwiki/oracle-database:%s",
testConfiguration.getDatabaseTag()));
} else {
databaseContainer = new OracleContainer("xwiki/oracle-database");
}
databaseContainer
.withUsername("system")
.withPassword("oracle");
startDatabaseContainer(databaseContainer, 1521, testConfiguration);
}
private void startDatabaseContainer(JdbcDatabaseContainer<?> databaseContainer, int port,
TestConfiguration testConfiguration) throws Exception
{
databaseContainer
.withExposedPorts(port)
.withNetwork(Network.SHARED)
.withNetworkAliases("xwikidb");
start(databaseContainer, testConfiguration);
if (testConfiguration.getServletEngine().isOutsideDocker()) {
testConfiguration.getDatabase().setIP(databaseContainer.getContainerIpAddress());
testConfiguration.getDatabase().setPort(databaseContainer.getMappedPort(port));
} else {
testConfiguration.getDatabase().setIP(databaseContainer.getNetworkAliases().get(0));
testConfiguration.getDatabase().setPort(port);
}
}
}
| [Misc] Make it work when the MySQL or MariaDB DB docker tag is "latest"
| xwiki-platform-core/xwiki-platform-test/xwiki-platform-test-docker/src/main/java/org/xwiki/test/docker/internal/junit5/database/DatabaseContainerExecutor.java | [Misc] Make it work when the MySQL or MariaDB DB docker tag is "latest" | <ide><path>wiki-platform-core/xwiki-platform-test/xwiki-platform-test-docker/src/main/java/org/xwiki/test/docker/internal/junit5/database/DatabaseContainerExecutor.java
<ide>
<ide> private boolean isMySQL8xPlus(TestConfiguration testConfiguration)
<ide> {
<del> return (testConfiguration.getDatabaseTag() != null && extractMajor(testConfiguration.getDatabaseTag()) >= 8)
<del> || (extractMajor(MySQLContainer.DEFAULT_TAG) >= 8 && testConfiguration.getDatabaseTag() == null);
<add> boolean isMySQL8xPlus;
<add> if (testConfiguration.getDatabaseTag() != null) {
<add> isMySQL8xPlus = testConfiguration.getDatabaseTag().equals("latest")
<add> || extractMajor(testConfiguration.getDatabaseTag()) >= 8;
<add> } else {
<add> isMySQL8xPlus = extractMajor(MySQLContainer.DEFAULT_TAG) >= 8;
<add> }
<add> return isMySQL8xPlus;
<ide> }
<ide>
<ide> private int extractMajor(String version) |
|
JavaScript | mit | c31fa813b1e1a9c3c1ee65da183504cde9095717 | 0 | beni55/primus,colinbate/primus,STRML/primus,dercodebearer/primus,primus/primus,STRML/primus,dercodebearer/primus,colinbate/primus,beni55/primus,STRML/primus,beni55/primus,primus/primus,primus/primus,dercodebearer/primus,colinbate/primus | (function(f){var g;if(typeof window!=='undefined'){g=window}else if(typeof self!=='undefined'){g=self}g.eio=f()})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(_dereq_,module,exports){
module.exports = _dereq_('./socket');
/**
* Exports parser
*
* @api public
*
*/
module.exports.parser = _dereq_('engine.io-parser');
},{"./socket":2,"engine.io-parser":15}],2:[function(_dereq_,module,exports){
(function (global){
/**
* Module dependencies.
*/
var transports = _dereq_('./transports');
var Emitter = _dereq_('component-emitter');
var debug = _dereq_('debug')('engine.io-client:socket');
var index = _dereq_('indexof');
var parser = _dereq_('engine.io-parser');
var parseuri = _dereq_('parseuri');
var parsejson = _dereq_('parsejson');
var parseqs = _dereq_('parseqs');
/**
* Module exports.
*/
module.exports = Socket;
/**
* Noop function.
*
* @api private
*/
function noop(){}
/**
* Socket constructor.
*
* @param {String|Object} uri or options
* @param {Object} options
* @api public
*/
function Socket(uri, opts){
if (!(this instanceof Socket)) return new Socket(uri, opts);
opts = opts || {};
if (uri && 'object' == typeof uri) {
opts = uri;
uri = null;
}
if (uri) {
uri = parseuri(uri);
opts.host = uri.host;
opts.secure = uri.protocol == 'https' || uri.protocol == 'wss';
opts.port = uri.port;
if (uri.query) opts.query = uri.query;
}
this.secure = null != opts.secure ? opts.secure :
(global.location && 'https:' == location.protocol);
if (opts.host) {
var pieces = opts.host.split(':');
opts.hostname = pieces.shift();
if (pieces.length) {
opts.port = pieces.pop();
} else if (!opts.port) {
// if no port is specified manually, use the protocol default
opts.port = this.secure ? '443' : '80';
}
}
this.agent = opts.agent || false;
this.hostname = opts.hostname ||
(global.location ? location.hostname : 'localhost');
this.port = opts.port || (global.location && location.port ?
location.port :
(this.secure ? 443 : 80));
this.query = opts.query || {};
if ('string' == typeof this.query) this.query = parseqs.decode(this.query);
this.upgrade = false !== opts.upgrade;
this.path = (opts.path || '/engine.io').replace(/\/$/, '') + '/';
this.forceJSONP = !!opts.forceJSONP;
this.jsonp = false !== opts.jsonp;
this.forceBase64 = !!opts.forceBase64;
this.enablesXDR = !!opts.enablesXDR;
this.timestampParam = opts.timestampParam || 't';
this.timestampRequests = opts.timestampRequests;
this.transports = opts.transports || ['polling', 'websocket'];
this.readyState = '';
this.writeBuffer = [];
this.callbackBuffer = [];
this.policyPort = opts.policyPort || 843;
this.rememberUpgrade = opts.rememberUpgrade || false;
this.binaryType = null;
this.onlyBinaryUpgrades = opts.onlyBinaryUpgrades;
// SSL options for Node.js client
this.pfx = opts.pfx || null;
this.key = opts.key || null;
this.passphrase = opts.passphrase || null;
this.cert = opts.cert || null;
this.ca = opts.ca || null;
this.ciphers = opts.ciphers || null;
this.rejectUnauthorized = opts.rejectUnauthorized || null;
this.open();
}
Socket.priorWebsocketSuccess = false;
/**
* Mix in `Emitter`.
*/
Emitter(Socket.prototype);
/**
* Protocol version.
*
* @api public
*/
Socket.protocol = parser.protocol; // this is an int
/**
* Expose deps for legacy compatibility
* and standalone browser access.
*/
Socket.Socket = Socket;
Socket.Transport = _dereq_('./transport');
Socket.transports = _dereq_('./transports');
Socket.parser = _dereq_('engine.io-parser');
/**
* Creates transport of the given type.
*
* @param {String} transport name
* @return {Transport}
* @api private
*/
Socket.prototype.createTransport = function (name) {
debug('creating transport "%s"', name);
var query = clone(this.query);
// append engine.io protocol identifier
query.EIO = parser.protocol;
// transport name
query.transport = name;
// session id if we already have one
if (this.id) query.sid = this.id;
var transport = new transports[name]({
agent: this.agent,
hostname: this.hostname,
port: this.port,
secure: this.secure,
path: this.path,
query: query,
forceJSONP: this.forceJSONP,
jsonp: this.jsonp,
forceBase64: this.forceBase64,
enablesXDR: this.enablesXDR,
timestampRequests: this.timestampRequests,
timestampParam: this.timestampParam,
policyPort: this.policyPort,
socket: this,
pfx: this.pfx,
key: this.key,
passphrase: this.passphrase,
cert: this.cert,
ca: this.ca,
ciphers: this.ciphers,
rejectUnauthorized: this.rejectUnauthorized
});
return transport;
};
function clone (obj) {
var o = {};
for (var i in obj) {
if (obj.hasOwnProperty(i)) {
o[i] = obj[i];
}
}
return o;
}
/**
* Initializes transport to use and starts probe.
*
* @api private
*/
Socket.prototype.open = function () {
var transport;
if (this.rememberUpgrade && Socket.priorWebsocketSuccess && this.transports.indexOf('websocket') != -1) {
transport = 'websocket';
} else if (0 == this.transports.length) {
// Emit error on next tick so it can be listened to
var self = this;
setTimeout(function() {
self.emit('error', 'No transports available');
}, 0);
return;
} else {
transport = this.transports[0];
}
this.readyState = 'opening';
// Retry with the next transport if the transport is disabled (jsonp: false)
var transport;
try {
transport = this.createTransport(transport);
} catch (e) {
this.transports.shift();
this.open();
return;
}
transport.open();
this.setTransport(transport);
};
/**
* Sets the current transport. Disables the existing one (if any).
*
* @api private
*/
Socket.prototype.setTransport = function(transport){
debug('setting transport %s', transport.name);
var self = this;
if (this.transport) {
debug('clearing existing transport %s', this.transport.name);
this.transport.removeAllListeners();
}
// set up transport
this.transport = transport;
// set up transport listeners
transport
.on('drain', function(){
self.onDrain();
})
.on('packet', function(packet){
self.onPacket(packet);
})
.on('error', function(e){
self.onError(e);
})
.on('close', function(){
self.onClose('transport close');
});
};
/**
* Probes a transport.
*
* @param {String} transport name
* @api private
*/
Socket.prototype.probe = function (name) {
debug('probing transport "%s"', name);
var transport = this.createTransport(name, { probe: 1 })
, failed = false
, self = this;
Socket.priorWebsocketSuccess = false;
function onTransportOpen(){
if (self.onlyBinaryUpgrades) {
var upgradeLosesBinary = !this.supportsBinary && self.transport.supportsBinary;
failed = failed || upgradeLosesBinary;
}
if (failed) return;
debug('probe transport "%s" opened', name);
transport.send([{ type: 'ping', data: 'probe' }]);
transport.once('packet', function (msg) {
if (failed) return;
if ('pong' == msg.type && 'probe' == msg.data) {
debug('probe transport "%s" pong', name);
self.upgrading = true;
self.emit('upgrading', transport);
if (!transport) return;
Socket.priorWebsocketSuccess = 'websocket' == transport.name;
debug('pausing current transport "%s"', self.transport.name);
self.transport.pause(function () {
if (failed) return;
if ('closed' == self.readyState) return;
debug('changing transport and sending upgrade packet');
cleanup();
self.setTransport(transport);
transport.send([{ type: 'upgrade' }]);
self.emit('upgrade', transport);
transport = null;
self.upgrading = false;
self.flush();
});
} else {
debug('probe transport "%s" failed', name);
var err = new Error('probe error');
err.transport = transport.name;
self.emit('upgradeError', err);
}
});
}
function freezeTransport() {
if (failed) return;
// Any callback called by transport should be ignored since now
failed = true;
cleanup();
transport.close();
transport = null;
}
//Handle any error that happens while probing
function onerror(err) {
var error = new Error('probe error: ' + err);
error.transport = transport.name;
freezeTransport();
debug('probe transport "%s" failed because of error: %s', name, err);
self.emit('upgradeError', error);
}
function onTransportClose(){
onerror("transport closed");
}
//When the socket is closed while we're probing
function onclose(){
onerror("socket closed");
}
//When the socket is upgraded while we're probing
function onupgrade(to){
if (transport && to.name != transport.name) {
debug('"%s" works - aborting "%s"', to.name, transport.name);
freezeTransport();
}
}
//Remove all listeners on the transport and on self
function cleanup(){
transport.removeListener('open', onTransportOpen);
transport.removeListener('error', onerror);
transport.removeListener('close', onTransportClose);
self.removeListener('close', onclose);
self.removeListener('upgrading', onupgrade);
}
transport.once('open', onTransportOpen);
transport.once('error', onerror);
transport.once('close', onTransportClose);
this.once('close', onclose);
this.once('upgrading', onupgrade);
transport.open();
};
/**
* Called when connection is deemed open.
*
* @api public
*/
Socket.prototype.onOpen = function () {
debug('socket open');
this.readyState = 'open';
Socket.priorWebsocketSuccess = 'websocket' == this.transport.name;
this.emit('open');
this.flush();
// we check for `readyState` in case an `open`
// listener already closed the socket
if ('open' == this.readyState && this.upgrade && this.transport.pause) {
debug('starting upgrade probes');
for (var i = 0, l = this.upgrades.length; i < l; i++) {
this.probe(this.upgrades[i]);
}
}
};
/**
* Handles a packet.
*
* @api private
*/
Socket.prototype.onPacket = function (packet) {
if ('opening' == this.readyState || 'open' == this.readyState) {
debug('socket receive: type "%s", data "%s"', packet.type, packet.data);
this.emit('packet', packet);
// Socket is live - any packet counts
this.emit('heartbeat');
switch (packet.type) {
case 'open':
this.onHandshake(parsejson(packet.data));
break;
case 'pong':
this.setPing();
break;
case 'error':
var err = new Error('server error');
err.code = packet.data;
this.emit('error', err);
break;
case 'message':
this.emit('data', packet.data);
this.emit('message', packet.data);
break;
}
} else {
debug('packet received with socket readyState "%s"', this.readyState);
}
};
/**
* Called upon handshake completion.
*
* @param {Object} handshake obj
* @api private
*/
Socket.prototype.onHandshake = function (data) {
this.emit('handshake', data);
this.id = data.sid;
this.transport.query.sid = data.sid;
this.upgrades = this.filterUpgrades(data.upgrades);
this.pingInterval = data.pingInterval;
this.pingTimeout = data.pingTimeout;
this.onOpen();
// In case open handler closes socket
if ('closed' == this.readyState) return;
this.setPing();
// Prolong liveness of socket on heartbeat
this.removeListener('heartbeat', this.onHeartbeat);
this.on('heartbeat', this.onHeartbeat);
};
/**
* Resets ping timeout.
*
* @api private
*/
Socket.prototype.onHeartbeat = function (timeout) {
clearTimeout(this.pingTimeoutTimer);
var self = this;
self.pingTimeoutTimer = setTimeout(function () {
if ('closed' == self.readyState) return;
self.onClose('ping timeout');
}, timeout || (self.pingInterval + self.pingTimeout));
};
/**
* Pings server every `this.pingInterval` and expects response
* within `this.pingTimeout` or closes connection.
*
* @api private
*/
Socket.prototype.setPing = function () {
var self = this;
clearTimeout(self.pingIntervalTimer);
self.pingIntervalTimer = setTimeout(function () {
debug('writing ping packet - expecting pong within %sms', self.pingTimeout);
self.ping();
self.onHeartbeat(self.pingTimeout);
}, self.pingInterval);
};
/**
* Sends a ping packet.
*
* @api public
*/
Socket.prototype.ping = function () {
this.sendPacket('ping');
};
/**
* Called on `drain` event
*
* @api private
*/
Socket.prototype.onDrain = function() {
for (var i = 0; i < this.prevBufferLen; i++) {
if (this.callbackBuffer[i]) {
this.callbackBuffer[i]();
}
}
this.writeBuffer.splice(0, this.prevBufferLen);
this.callbackBuffer.splice(0, this.prevBufferLen);
// setting prevBufferLen = 0 is very important
// for example, when upgrading, upgrade packet is sent over,
// and a nonzero prevBufferLen could cause problems on `drain`
this.prevBufferLen = 0;
if (this.writeBuffer.length == 0) {
this.emit('drain');
} else {
this.flush();
}
};
/**
* Flush write buffers.
*
* @api private
*/
Socket.prototype.flush = function () {
if ('closed' != this.readyState && this.transport.writable &&
!this.upgrading && this.writeBuffer.length) {
debug('flushing %d packets in socket', this.writeBuffer.length);
this.transport.send(this.writeBuffer);
// keep track of current length of writeBuffer
// splice writeBuffer and callbackBuffer on `drain`
this.prevBufferLen = this.writeBuffer.length;
this.emit('flush');
}
};
/**
* Sends a message.
*
* @param {String} message.
* @param {Function} callback function.
* @return {Socket} for chaining.
* @api public
*/
Socket.prototype.write =
Socket.prototype.send = function (msg, fn) {
this.sendPacket('message', msg, fn);
return this;
};
/**
* Sends a packet.
*
* @param {String} packet type.
* @param {String} data.
* @param {Function} callback function.
* @api private
*/
Socket.prototype.sendPacket = function (type, data, fn) {
if ('closing' == this.readyState || 'closed' == this.readyState) {
return;
}
var packet = { type: type, data: data };
this.emit('packetCreate', packet);
this.writeBuffer.push(packet);
this.callbackBuffer.push(fn);
this.flush();
};
/**
* Closes the connection.
*
* @api private
*/
Socket.prototype.close = function () {
if ('opening' == this.readyState || 'open' == this.readyState) {
this.readyState = 'closing';
var self = this;
function close() {
self.onClose('forced close');
debug('socket closing - telling transport to close');
self.transport.close();
}
function cleanupAndClose() {
self.removeListener('upgrade', cleanupAndClose);
self.removeListener('upgradeError', cleanupAndClose);
close();
}
function waitForUpgrade() {
// wait for upgrade to finish since we can't send packets while pausing a transport
self.once('upgrade', cleanupAndClose);
self.once('upgradeError', cleanupAndClose);
}
if (this.writeBuffer.length) {
this.once('drain', function() {
if (this.upgrading) {
waitForUpgrade();
} else {
close();
}
});
} else if (this.upgrading) {
waitForUpgrade();
} else {
close();
}
}
return this;
};
/**
* Called upon transport error
*
* @api private
*/
Socket.prototype.onError = function (err) {
debug('socket error %j', err);
Socket.priorWebsocketSuccess = false;
this.emit('error', err);
this.onClose('transport error', err);
};
/**
* Called upon transport close.
*
* @api private
*/
Socket.prototype.onClose = function (reason, desc) {
if ('opening' == this.readyState || 'open' == this.readyState || 'closing' == this.readyState) {
debug('socket close with reason: "%s"', reason);
var self = this;
// clear timers
clearTimeout(this.pingIntervalTimer);
clearTimeout(this.pingTimeoutTimer);
// clean buffers in next tick, so developers can still
// grab the buffers on `close` event
setTimeout(function() {
self.writeBuffer = [];
self.callbackBuffer = [];
self.prevBufferLen = 0;
}, 0);
// stop event from firing again for transport
this.transport.removeAllListeners('close');
// ensure transport won't stay open
this.transport.close();
// ignore further transport communication
this.transport.removeAllListeners();
// set ready state
this.readyState = 'closed';
// clear session id
this.id = null;
// emit close event
this.emit('close', reason, desc);
}
};
/**
* Filters upgrades, returning only those matching client transports.
*
* @param {Array} server upgrades
* @api private
*
*/
Socket.prototype.filterUpgrades = function (upgrades) {
var filteredUpgrades = [];
for (var i = 0, j = upgrades.length; i<j; i++) {
if (~index(this.transports, upgrades[i])) filteredUpgrades.push(upgrades[i]);
}
return filteredUpgrades;
};
}).call(this,typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{"./transport":3,"./transports":4,"component-emitter":10,"debug":12,"engine.io-parser":15,"indexof":26,"parsejson":27,"parseqs":28,"parseuri":29}],3:[function(_dereq_,module,exports){
/**
* Module dependencies.
*/
var parser = _dereq_('engine.io-parser');
var Emitter = _dereq_('component-emitter');
/**
* Module exports.
*/
module.exports = Transport;
/**
* Transport abstract constructor.
*
* @param {Object} options.
* @api private
*/
function Transport (opts) {
this.path = opts.path;
this.hostname = opts.hostname;
this.port = opts.port;
this.secure = opts.secure;
this.query = opts.query;
this.timestampParam = opts.timestampParam;
this.timestampRequests = opts.timestampRequests;
this.readyState = '';
this.agent = opts.agent || false;
this.socket = opts.socket;
this.enablesXDR = opts.enablesXDR;
// SSL options for Node.js client
this.pfx = opts.pfx;
this.key = opts.key;
this.passphrase = opts.passphrase;
this.cert = opts.cert;
this.ca = opts.ca;
this.ciphers = opts.ciphers;
this.rejectUnauthorized = opts.rejectUnauthorized;
}
/**
* Mix in `Emitter`.
*/
Emitter(Transport.prototype);
/**
* A counter used to prevent collisions in the timestamps used
* for cache busting.
*/
Transport.timestamps = 0;
/**
* Emits an error.
*
* @param {String} str
* @return {Transport} for chaining
* @api public
*/
Transport.prototype.onError = function (msg, desc) {
var err = new Error(msg);
err.type = 'TransportError';
err.description = desc;
this.emit('error', err);
return this;
};
/**
* Opens the transport.
*
* @api public
*/
Transport.prototype.open = function () {
if ('closed' == this.readyState || '' == this.readyState) {
this.readyState = 'opening';
this.doOpen();
}
return this;
};
/**
* Closes the transport.
*
* @api private
*/
Transport.prototype.close = function () {
if ('opening' == this.readyState || 'open' == this.readyState) {
this.doClose();
this.onClose();
}
return this;
};
/**
* Sends multiple packets.
*
* @param {Array} packets
* @api private
*/
Transport.prototype.send = function(packets){
if ('open' == this.readyState) {
this.write(packets);
} else {
throw new Error('Transport not open');
}
};
/**
* Called upon open
*
* @api private
*/
Transport.prototype.onOpen = function () {
this.readyState = 'open';
this.writable = true;
this.emit('open');
};
/**
* Called with data.
*
* @param {String} data
* @api private
*/
Transport.prototype.onData = function(data){
var packet = parser.decodePacket(data, this.socket.binaryType);
this.onPacket(packet);
};
/**
* Called with a decoded packet.
*/
Transport.prototype.onPacket = function (packet) {
this.emit('packet', packet);
};
/**
* Called upon close.
*
* @api private
*/
Transport.prototype.onClose = function () {
this.readyState = 'closed';
this.emit('close');
};
},{"component-emitter":10,"engine.io-parser":15}],4:[function(_dereq_,module,exports){
(function (global){
/**
* Module dependencies
*/
var XMLHttpRequest = _dereq_('xmlhttprequest');
var XHR = _dereq_('./polling-xhr');
var JSONP = _dereq_('./polling-jsonp');
var websocket = _dereq_('./websocket');
/**
* Export transports.
*/
exports.polling = polling;
exports.websocket = websocket;
/**
* Polling transport polymorphic constructor.
* Decides on xhr vs jsonp based on feature detection.
*
* @api private
*/
function polling(opts){
var xhr;
var xd = false;
var xs = false;
var jsonp = false !== opts.jsonp;
if (global.location) {
var isSSL = 'https:' == location.protocol;
var port = location.port;
// some user agents have empty `location.port`
if (!port) {
port = isSSL ? 443 : 80;
}
xd = opts.hostname != location.hostname || port != opts.port;
xs = opts.secure != isSSL;
}
opts.xdomain = xd;
opts.xscheme = xs;
xhr = new XMLHttpRequest(opts);
if ('open' in xhr && !opts.forceJSONP) {
return new XHR(opts);
} else {
if (!jsonp) throw new Error('JSONP disabled');
return new JSONP(opts);
}
}
}).call(this,typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{"./polling-jsonp":5,"./polling-xhr":6,"./websocket":8,"xmlhttprequest":9}],5:[function(_dereq_,module,exports){
(function (global){
/**
* Module requirements.
*/
var Polling = _dereq_('./polling');
var inherit = _dereq_('component-inherit');
/**
* Module exports.
*/
module.exports = JSONPPolling;
/**
* Cached regular expressions.
*/
var rNewline = /\n/g;
var rEscapedNewline = /\\n/g;
/**
* Global JSONP callbacks.
*/
var callbacks;
/**
* Callbacks count.
*/
var index = 0;
/**
* Noop.
*/
function empty () { }
/**
* JSONP Polling constructor.
*
* @param {Object} opts.
* @api public
*/
function JSONPPolling (opts) {
Polling.call(this, opts);
this.query = this.query || {};
// define global callbacks array if not present
// we do this here (lazily) to avoid unneeded global pollution
if (!callbacks) {
// we need to consider multiple engines in the same page
if (!global.___eio) global.___eio = [];
callbacks = global.___eio;
}
// callback identifier
this.index = callbacks.length;
// add callback to jsonp global
var self = this;
callbacks.push(function (msg) {
self.onData(msg);
});
// append to query string
this.query.j = this.index;
// prevent spurious errors from being emitted when the window is unloaded
if (global.document && global.addEventListener) {
global.addEventListener('beforeunload', function () {
if (self.script) self.script.onerror = empty;
}, false);
}
}
/**
* Inherits from Polling.
*/
inherit(JSONPPolling, Polling);
/*
* JSONP only supports binary as base64 encoded strings
*/
JSONPPolling.prototype.supportsBinary = false;
/**
* Closes the socket.
*
* @api private
*/
JSONPPolling.prototype.doClose = function () {
if (this.script) {
this.script.parentNode.removeChild(this.script);
this.script = null;
}
if (this.form) {
this.form.parentNode.removeChild(this.form);
this.form = null;
this.iframe = null;
}
Polling.prototype.doClose.call(this);
};
/**
* Starts a poll cycle.
*
* @api private
*/
JSONPPolling.prototype.doPoll = function () {
var self = this;
var script = document.createElement('script');
if (this.script) {
this.script.parentNode.removeChild(this.script);
this.script = null;
}
script.async = true;
script.src = this.uri();
script.onerror = function(e){
self.onError('jsonp poll error',e);
};
var insertAt = document.getElementsByTagName('script')[0];
insertAt.parentNode.insertBefore(script, insertAt);
this.script = script;
var isUAgecko = 'undefined' != typeof navigator && /gecko/i.test(navigator.userAgent);
if (isUAgecko) {
setTimeout(function () {
var iframe = document.createElement('iframe');
document.body.appendChild(iframe);
document.body.removeChild(iframe);
}, 100);
}
};
/**
* Writes with a hidden iframe.
*
* @param {String} data to send
* @param {Function} called upon flush.
* @api private
*/
JSONPPolling.prototype.doWrite = function (data, fn) {
var self = this;
if (!this.form) {
var form = document.createElement('form');
var area = document.createElement('textarea');
var id = this.iframeId = 'eio_iframe_' + this.index;
var iframe;
form.className = 'socketio';
form.style.position = 'absolute';
form.style.top = '-1000px';
form.style.left = '-1000px';
form.target = id;
form.method = 'POST';
form.setAttribute('accept-charset', 'utf-8');
area.name = 'd';
form.appendChild(area);
document.body.appendChild(form);
this.form = form;
this.area = area;
}
this.form.action = this.uri();
function complete () {
initIframe();
fn();
}
function initIframe () {
if (self.iframe) {
try {
self.form.removeChild(self.iframe);
} catch (e) {
self.onError('jsonp polling iframe removal error', e);
}
}
try {
// ie6 dynamic iframes with target="" support (thanks Chris Lambacher)
var html = '<iframe src="javascript:0" name="'+ self.iframeId +'">';
iframe = document.createElement(html);
} catch (e) {
iframe = document.createElement('iframe');
iframe.name = self.iframeId;
iframe.src = 'javascript:0';
}
iframe.id = self.iframeId;
self.form.appendChild(iframe);
self.iframe = iframe;
}
initIframe();
// escape \n to prevent it from being converted into \r\n by some UAs
// double escaping is required for escaped new lines because unescaping of new lines can be done safely on server-side
data = data.replace(rEscapedNewline, '\\\n');
this.area.value = data.replace(rNewline, '\\n');
try {
this.form.submit();
} catch(e) {}
if (this.iframe.attachEvent) {
this.iframe.onreadystatechange = function(){
if (self.iframe.readyState == 'complete') {
complete();
}
};
} else {
this.iframe.onload = complete;
}
};
}).call(this,typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{"./polling":7,"component-inherit":11}],6:[function(_dereq_,module,exports){
(function (global){
/**
* Module requirements.
*/
var XMLHttpRequest = _dereq_('xmlhttprequest');
var Polling = _dereq_('./polling');
var Emitter = _dereq_('component-emitter');
var inherit = _dereq_('component-inherit');
var debug = _dereq_('debug')('engine.io-client:polling-xhr');
/**
* Module exports.
*/
module.exports = XHR;
module.exports.Request = Request;
/**
* Empty function
*/
function empty(){}
/**
* XHR Polling constructor.
*
* @param {Object} opts
* @api public
*/
function XHR(opts){
Polling.call(this, opts);
if (global.location) {
var isSSL = 'https:' == location.protocol;
var port = location.port;
// some user agents have empty `location.port`
if (!port) {
port = isSSL ? 443 : 80;
}
this.xd = opts.hostname != global.location.hostname ||
port != opts.port;
this.xs = opts.secure != isSSL;
}
}
/**
* Inherits from Polling.
*/
inherit(XHR, Polling);
/**
* XHR supports binary
*/
XHR.prototype.supportsBinary = true;
/**
* Creates a request.
*
* @param {String} method
* @api private
*/
XHR.prototype.request = function(opts){
opts = opts || {};
opts.uri = this.uri();
opts.xd = this.xd;
opts.xs = this.xs;
opts.agent = this.agent || false;
opts.supportsBinary = this.supportsBinary;
opts.enablesXDR = this.enablesXDR;
// SSL options for Node.js client
opts.pfx = this.pfx;
opts.key = this.key;
opts.passphrase = this.passphrase;
opts.cert = this.cert;
opts.ca = this.ca;
opts.ciphers = this.ciphers;
opts.rejectUnauthorized = this.rejectUnauthorized;
return new Request(opts);
};
/**
* Sends data.
*
* @param {String} data to send.
* @param {Function} called upon flush.
* @api private
*/
XHR.prototype.doWrite = function(data, fn){
var isBinary = typeof data !== 'string' && data !== undefined;
var req = this.request({ method: 'POST', data: data, isBinary: isBinary });
var self = this;
req.on('success', fn);
req.on('error', function(err){
self.onError('xhr post error', err);
});
this.sendXhr = req;
};
/**
* Starts a poll cycle.
*
* @api private
*/
XHR.prototype.doPoll = function(){
debug('xhr poll');
var req = this.request();
var self = this;
req.on('data', function(data){
self.onData(data);
});
req.on('error', function(err){
self.onError('xhr poll error', err);
});
this.pollXhr = req;
};
/**
* Request constructor
*
* @param {Object} options
* @api public
*/
function Request(opts){
this.method = opts.method || 'GET';
this.uri = opts.uri;
this.xd = !!opts.xd;
this.xs = !!opts.xs;
this.async = false !== opts.async;
this.data = undefined != opts.data ? opts.data : null;
this.agent = opts.agent;
this.isBinary = opts.isBinary;
this.supportsBinary = opts.supportsBinary;
this.enablesXDR = opts.enablesXDR;
// SSL options for Node.js client
this.pfx = opts.pfx;
this.key = opts.key;
this.passphrase = opts.passphrase;
this.cert = opts.cert;
this.ca = opts.ca;
this.ciphers = opts.ciphers;
this.rejectUnauthorized = opts.rejectUnauthorized;
this.create();
}
/**
* Mix in `Emitter`.
*/
Emitter(Request.prototype);
/**
* Creates the XHR object and sends the request.
*
* @api private
*/
Request.prototype.create = function(){
var opts = { agent: this.agent, xdomain: this.xd, xscheme: this.xs, enablesXDR: this.enablesXDR };
// SSL options for Node.js client
opts.pfx = this.pfx;
opts.key = this.key;
opts.passphrase = this.passphrase;
opts.cert = this.cert;
opts.ca = this.ca;
opts.ciphers = this.ciphers;
opts.rejectUnauthorized = this.rejectUnauthorized;
var xhr = this.xhr = new XMLHttpRequest(opts);
var self = this;
try {
debug('xhr open %s: %s', this.method, this.uri);
xhr.open(this.method, this.uri, this.async);
if (this.supportsBinary) {
// This has to be done after open because Firefox is stupid
// http://stackoverflow.com/questions/13216903/get-binary-data-with-xmlhttprequest-in-a-firefox-extension
xhr.responseType = 'arraybuffer';
}
if ('POST' == this.method) {
try {
if (this.isBinary) {
xhr.setRequestHeader('Content-type', 'application/octet-stream');
} else {
xhr.setRequestHeader('Content-type', 'text/plain;charset=UTF-8');
}
} catch (e) {}
}
// ie6 check
if ('withCredentials' in xhr) {
xhr.withCredentials = true;
}
if (this.hasXDR()) {
xhr.onload = function(){
self.onLoad();
};
xhr.onerror = function(){
self.onError(xhr.responseText);
};
} else {
xhr.onreadystatechange = function(){
if (4 != xhr.readyState) return;
if (200 == xhr.status || 1223 == xhr.status) {
self.onLoad();
} else {
// make sure the `error` event handler that's user-set
// does not throw in the same tick and gets caught here
setTimeout(function(){
self.onError(xhr.status);
}, 0);
}
};
}
debug('xhr data %s', this.data);
xhr.send(this.data);
} catch (e) {
// Need to defer since .create() is called directly fhrom the constructor
// and thus the 'error' event can only be only bound *after* this exception
// occurs. Therefore, also, we cannot throw here at all.
setTimeout(function() {
self.onError(e);
}, 0);
return;
}
if (global.document) {
this.index = Request.requestsCount++;
Request.requests[this.index] = this;
}
};
/**
* Called upon successful response.
*
* @api private
*/
Request.prototype.onSuccess = function(){
this.emit('success');
this.cleanup();
};
/**
* Called if we have data.
*
* @api private
*/
Request.prototype.onData = function(data){
this.emit('data', data);
this.onSuccess();
};
/**
* Called upon error.
*
* @api private
*/
Request.prototype.onError = function(err){
this.emit('error', err);
this.cleanup(true);
};
/**
* Cleans up house.
*
* @api private
*/
Request.prototype.cleanup = function(fromError){
if ('undefined' == typeof this.xhr || null === this.xhr) {
return;
}
// xmlhttprequest
if (this.hasXDR()) {
this.xhr.onload = this.xhr.onerror = empty;
} else {
this.xhr.onreadystatechange = empty;
}
if (fromError) {
try {
this.xhr.abort();
} catch(e) {}
}
if (global.document) {
delete Request.requests[this.index];
}
this.xhr = null;
};
/**
* Called upon load.
*
* @api private
*/
Request.prototype.onLoad = function(){
var data;
try {
var contentType;
try {
contentType = this.xhr.getResponseHeader('Content-Type').split(';')[0];
} catch (e) {}
if (contentType === 'application/octet-stream') {
data = this.xhr.response;
} else {
if (!this.supportsBinary) {
data = this.xhr.responseText;
} else {
data = 'ok';
}
}
} catch (e) {
this.onError(e);
}
if (null != data) {
this.onData(data);
}
};
/**
* Check if it has XDomainRequest.
*
* @api private
*/
Request.prototype.hasXDR = function(){
return 'undefined' !== typeof global.XDomainRequest && !this.xs && this.enablesXDR;
};
/**
* Aborts the request.
*
* @api public
*/
Request.prototype.abort = function(){
this.cleanup();
};
/**
* Aborts pending requests when unloading the window. This is needed to prevent
* memory leaks (e.g. when using IE) and to ensure that no spurious error is
* emitted.
*/
if (global.document) {
Request.requestsCount = 0;
Request.requests = {};
if (global.attachEvent) {
global.attachEvent('onunload', unloadHandler);
} else if (global.addEventListener) {
global.addEventListener('beforeunload', unloadHandler, false);
}
}
function unloadHandler() {
for (var i in Request.requests) {
if (Request.requests.hasOwnProperty(i)) {
Request.requests[i].abort();
}
}
}
}).call(this,typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{"./polling":7,"component-emitter":10,"component-inherit":11,"debug":12,"xmlhttprequest":9}],7:[function(_dereq_,module,exports){
/**
* Module dependencies.
*/
var Transport = _dereq_('../transport');
var parseqs = _dereq_('parseqs');
var parser = _dereq_('engine.io-parser');
var inherit = _dereq_('component-inherit');
var debug = _dereq_('debug')('engine.io-client:polling');
/**
* Module exports.
*/
module.exports = Polling;
/**
* Is XHR2 supported?
*/
var hasXHR2 = (function() {
var XMLHttpRequest = _dereq_('xmlhttprequest');
var xhr = new XMLHttpRequest({ xdomain: false });
return null != xhr.responseType;
})();
/**
* Polling interface.
*
* @param {Object} opts
* @api private
*/
function Polling(opts){
var forceBase64 = (opts && opts.forceBase64);
if (!hasXHR2 || forceBase64) {
this.supportsBinary = false;
}
Transport.call(this, opts);
}
/**
* Inherits from Transport.
*/
inherit(Polling, Transport);
/**
* Transport name.
*/
Polling.prototype.name = 'polling';
/**
* Opens the socket (triggers polling). We write a PING message to determine
* when the transport is open.
*
* @api private
*/
Polling.prototype.doOpen = function(){
this.poll();
};
/**
* Pauses polling.
*
* @param {Function} callback upon buffers are flushed and transport is paused
* @api private
*/
Polling.prototype.pause = function(onPause){
var pending = 0;
var self = this;
this.readyState = 'pausing';
function pause(){
debug('paused');
self.readyState = 'paused';
onPause();
}
if (this.polling || !this.writable) {
var total = 0;
if (this.polling) {
debug('we are currently polling - waiting to pause');
total++;
this.once('pollComplete', function(){
debug('pre-pause polling complete');
--total || pause();
});
}
if (!this.writable) {
debug('we are currently writing - waiting to pause');
total++;
this.once('drain', function(){
debug('pre-pause writing complete');
--total || pause();
});
}
} else {
pause();
}
};
/**
* Starts polling cycle.
*
* @api public
*/
Polling.prototype.poll = function(){
debug('polling');
this.polling = true;
this.doPoll();
this.emit('poll');
};
/**
* Overloads onData to detect payloads.
*
* @api private
*/
Polling.prototype.onData = function(data){
var self = this;
debug('polling got data %s', data);
var callback = function(packet, index, total) {
// if its the first message we consider the transport open
if ('opening' == self.readyState) {
self.onOpen();
}
// if its a close packet, we close the ongoing requests
if ('close' == packet.type) {
self.onClose();
return false;
}
// otherwise bypass onData and handle the message
self.onPacket(packet);
};
// decode payload
parser.decodePayload(data, this.socket.binaryType, callback);
// if an event did not trigger closing
if ('closed' != this.readyState) {
// if we got data we're not polling
this.polling = false;
this.emit('pollComplete');
if ('open' == this.readyState) {
this.poll();
} else {
debug('ignoring poll - transport state "%s"', this.readyState);
}
}
};
/**
* For polling, send a close packet.
*
* @api private
*/
Polling.prototype.doClose = function(){
var self = this;
function close(){
debug('writing close packet');
self.write([{ type: 'close' }]);
}
if ('open' == this.readyState) {
debug('transport open - closing');
close();
} else {
// in case we're trying to close while
// handshaking is in progress (GH-164)
debug('transport not open - deferring close');
this.once('open', close);
}
};
/**
* Writes a packets payload.
*
* @param {Array} data packets
* @param {Function} drain callback
* @api private
*/
Polling.prototype.write = function(packets){
var self = this;
this.writable = false;
var callbackfn = function() {
self.writable = true;
self.emit('drain');
};
var self = this;
parser.encodePayload(packets, this.supportsBinary, function(data) {
self.doWrite(data, callbackfn);
});
};
/**
* Generates uri for connection.
*
* @api private
*/
Polling.prototype.uri = function(){
var query = this.query || {};
var schema = this.secure ? 'https' : 'http';
var port = '';
// cache busting is forced
if (false !== this.timestampRequests) {
query[this.timestampParam] = +new Date + '-' + Transport.timestamps++;
}
if (!this.supportsBinary && !query.sid) {
query.b64 = 1;
}
query = parseqs.encode(query);
// avoid port if default for schema
if (this.port && (('https' == schema && this.port != 443) ||
('http' == schema && this.port != 80))) {
port = ':' + this.port;
}
// prepend ? to query
if (query.length) {
query = '?' + query;
}
return schema + '://' + this.hostname + port + this.path + query;
};
},{"../transport":3,"component-inherit":11,"debug":12,"engine.io-parser":15,"parseqs":28,"xmlhttprequest":9}],8:[function(_dereq_,module,exports){
/**
* Module dependencies.
*/
var Transport = _dereq_('../transport');
var parser = _dereq_('engine.io-parser');
var parseqs = _dereq_('parseqs');
var inherit = _dereq_('component-inherit');
var debug = _dereq_('debug')('engine.io-client:websocket');
/**
* `ws` exposes a WebSocket-compatible interface in
* Node, or the `WebSocket` or `MozWebSocket` globals
* in the browser.
*/
var WebSocket = _dereq_('ws');
/**
* Module exports.
*/
module.exports = WS;
/**
* WebSocket transport constructor.
*
* @api {Object} connection options
* @api public
*/
function WS(opts){
var forceBase64 = (opts && opts.forceBase64);
if (forceBase64) {
this.supportsBinary = false;
}
Transport.call(this, opts);
}
/**
* Inherits from Transport.
*/
inherit(WS, Transport);
/**
* Transport name.
*
* @api public
*/
WS.prototype.name = 'websocket';
/*
* WebSockets support binary
*/
WS.prototype.supportsBinary = true;
/**
* Opens socket.
*
* @api private
*/
WS.prototype.doOpen = function(){
if (!this.check()) {
// let probe timeout
return;
}
var self = this;
var uri = this.uri();
var protocols = void(0);
var opts = { agent: this.agent };
// SSL options for Node.js client
opts.pfx = this.pfx;
opts.key = this.key;
opts.passphrase = this.passphrase;
opts.cert = this.cert;
opts.ca = this.ca;
opts.ciphers = this.ciphers;
opts.rejectUnauthorized = this.rejectUnauthorized;
this.ws = new WebSocket(uri, protocols, opts);
if (this.ws.binaryType === undefined) {
this.supportsBinary = false;
}
this.ws.binaryType = 'arraybuffer';
this.addEventListeners();
};
/**
* Adds event listeners to the socket
*
* @api private
*/
WS.prototype.addEventListeners = function(){
var self = this;
this.ws.onopen = function(){
self.onOpen();
};
this.ws.onclose = function(){
self.onClose();
};
this.ws.onmessage = function(ev){
self.onData(ev.data);
};
this.ws.onerror = function(e){
self.onError('websocket error', e);
};
};
/**
* Override `onData` to use a timer on iOS.
* See: https://gist.github.com/mloughran/2052006
*
* @api private
*/
if ('undefined' != typeof navigator
&& /iPad|iPhone|iPod/i.test(navigator.userAgent)) {
WS.prototype.onData = function(data){
var self = this;
setTimeout(function(){
Transport.prototype.onData.call(self, data);
}, 0);
};
}
/**
* Writes data to socket.
*
* @param {Array} array of packets.
* @api private
*/
WS.prototype.write = function(packets){
var self = this;
this.writable = false;
// encodePacket efficient as it uses WS framing
// no need for encodePayload
for (var i = 0, l = packets.length; i < l; i++) {
parser.encodePacket(packets[i], this.supportsBinary, function(data) {
//Sometimes the websocket has already been closed but the browser didn't
//have a chance of informing us about it yet, in that case send will
//throw an error
try {
self.ws.send(data);
} catch (e){
debug('websocket closed before onclose event');
}
});
}
function ondrain() {
self.writable = true;
self.emit('drain');
}
// fake drain
// defer to next tick to allow Socket to clear writeBuffer
setTimeout(ondrain, 0);
};
/**
* Called upon close
*
* @api private
*/
WS.prototype.onClose = function(){
Transport.prototype.onClose.call(this);
};
/**
* Closes socket.
*
* @api private
*/
WS.prototype.doClose = function(){
if (typeof this.ws !== 'undefined') {
this.ws.close();
}
};
/**
* Generates uri for connection.
*
* @api private
*/
WS.prototype.uri = function(){
var query = this.query || {};
var schema = this.secure ? 'wss' : 'ws';
var port = '';
// avoid port if default for schema
if (this.port && (('wss' == schema && this.port != 443)
|| ('ws' == schema && this.port != 80))) {
port = ':' + this.port;
}
// append timestamp to URI
if (this.timestampRequests) {
query[this.timestampParam] = +new Date;
}
// communicate binary support capabilities
if (!this.supportsBinary) {
query.b64 = 1;
}
query = parseqs.encode(query);
// prepend ? to query
if (query.length) {
query = '?' + query;
}
return schema + '://' + this.hostname + port + this.path + query;
};
/**
* Feature detection for WebSocket.
*
* @return {Boolean} whether this transport is available.
* @api public
*/
WS.prototype.check = function(){
return !!WebSocket && !('__initialize' in WebSocket && this.name === WS.prototype.name);
};
},{"../transport":3,"component-inherit":11,"debug":12,"engine.io-parser":15,"parseqs":28,"ws":30}],9:[function(_dereq_,module,exports){
// browser shim for xmlhttprequest module
var hasCORS = _dereq_('has-cors');
module.exports = function(opts) {
var xdomain = opts.xdomain;
// scheme must be same when usign XDomainRequest
// http://blogs.msdn.com/b/ieinternals/archive/2010/05/13/xdomainrequest-restrictions-limitations-and-workarounds.aspx
var xscheme = opts.xscheme;
// XDomainRequest has a flow of not sending cookie, therefore it should be disabled as a default.
// https://github.com/Automattic/engine.io-client/pull/217
var enablesXDR = opts.enablesXDR;
// XMLHttpRequest can be disabled on IE
try {
if ('undefined' != typeof XMLHttpRequest && (!xdomain || hasCORS)) {
return new XMLHttpRequest();
}
} catch (e) { }
// Use XDomainRequest for IE8 if enablesXDR is true
// because loading bar keeps flashing when using jsonp-polling
// https://github.com/yujiosaka/socke.io-ie8-loading-example
try {
if ('undefined' != typeof XDomainRequest && !xscheme && enablesXDR) {
return new XDomainRequest();
}
} catch (e) { }
if (!xdomain) {
try {
return new window[(['Active'].concat('Object').join('X'))]('Microsoft.XMLHTTP');
} catch(e) { }
}
}
},{"has-cors":24}],10:[function(_dereq_,module,exports){
/**
* Expose `Emitter`.
*/
module.exports = Emitter;
/**
* Initialize a new `Emitter`.
*
* @api public
*/
function Emitter(obj) {
if (obj) return mixin(obj);
};
/**
* Mixin the emitter properties.
*
* @param {Object} obj
* @return {Object}
* @api private
*/
function mixin(obj) {
for (var key in Emitter.prototype) {
obj[key] = Emitter.prototype[key];
}
return obj;
}
/**
* Listen on the given `event` with `fn`.
*
* @param {String} event
* @param {Function} fn
* @return {Emitter}
* @api public
*/
Emitter.prototype.on =
Emitter.prototype.addEventListener = function(event, fn){
this._callbacks = this._callbacks || {};
(this._callbacks[event] = this._callbacks[event] || [])
.push(fn);
return this;
};
/**
* Adds an `event` listener that will be invoked a single
* time then automatically removed.
*
* @param {String} event
* @param {Function} fn
* @return {Emitter}
* @api public
*/
Emitter.prototype.once = function(event, fn){
var self = this;
this._callbacks = this._callbacks || {};
function on() {
self.off(event, on);
fn.apply(this, arguments);
}
on.fn = fn;
this.on(event, on);
return this;
};
/**
* Remove the given callback for `event` or all
* registered callbacks.
*
* @param {String} event
* @param {Function} fn
* @return {Emitter}
* @api public
*/
Emitter.prototype.off =
Emitter.prototype.removeListener =
Emitter.prototype.removeAllListeners =
Emitter.prototype.removeEventListener = function(event, fn){
this._callbacks = this._callbacks || {};
// all
if (0 == arguments.length) {
this._callbacks = {};
return this;
}
// specific event
var callbacks = this._callbacks[event];
if (!callbacks) return this;
// remove all handlers
if (1 == arguments.length) {
delete this._callbacks[event];
return this;
}
// remove specific handler
var cb;
for (var i = 0; i < callbacks.length; i++) {
cb = callbacks[i];
if (cb === fn || cb.fn === fn) {
callbacks.splice(i, 1);
break;
}
}
return this;
};
/**
* Emit `event` with the given args.
*
* @param {String} event
* @param {Mixed} ...
* @return {Emitter}
*/
Emitter.prototype.emit = function(event){
this._callbacks = this._callbacks || {};
var args = [].slice.call(arguments, 1)
, callbacks = this._callbacks[event];
if (callbacks) {
callbacks = callbacks.slice(0);
for (var i = 0, len = callbacks.length; i < len; ++i) {
callbacks[i].apply(this, args);
}
}
return this;
};
/**
* Return array of callbacks for `event`.
*
* @param {String} event
* @return {Array}
* @api public
*/
Emitter.prototype.listeners = function(event){
this._callbacks = this._callbacks || {};
return this._callbacks[event] || [];
};
/**
* Check if this emitter has `event` handlers.
*
* @param {String} event
* @return {Boolean}
* @api public
*/
Emitter.prototype.hasListeners = function(event){
return !! this.listeners(event).length;
};
},{}],11:[function(_dereq_,module,exports){
module.exports = function(a, b){
var fn = function(){};
fn.prototype = b.prototype;
a.prototype = new fn;
a.prototype.constructor = a;
};
},{}],12:[function(_dereq_,module,exports){
/**
* This is the web browser implementation of `debug()`.
*
* Expose `debug()` as the module.
*/
exports = module.exports = _dereq_('./debug');
exports.log = log;
exports.formatArgs = formatArgs;
exports.save = save;
exports.load = load;
exports.useColors = useColors;
/**
* Colors.
*/
exports.colors = [
'lightseagreen',
'forestgreen',
'goldenrod',
'dodgerblue',
'darkorchid',
'crimson'
];
/**
* Currently only WebKit-based Web Inspectors, Firefox >= v31,
* and the Firebug extension (any Firefox version) are known
* to support "%c" CSS customizations.
*
* TODO: add a `localStorage` variable to explicitly enable/disable colors
*/
function useColors() {
// is webkit? http://stackoverflow.com/a/16459606/376773
return ('WebkitAppearance' in document.documentElement.style) ||
// is firebug? http://stackoverflow.com/a/398120/376773
(window.console && (console.firebug || (console.exception && console.table))) ||
// is firefox >= v31?
// https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages
(navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31);
}
/**
* Map %j to `JSON.stringify()`, since no Web Inspectors do that by default.
*/
exports.formatters.j = function(v) {
return JSON.stringify(v);
};
/**
* Colorize log arguments if enabled.
*
* @api public
*/
function formatArgs() {
var args = arguments;
var useColors = this.useColors;
args[0] = (useColors ? '%c' : '')
+ this.namespace
+ (useColors ? ' %c' : ' ')
+ args[0]
+ (useColors ? '%c ' : ' ')
+ '+' + exports.humanize(this.diff);
if (!useColors) return args;
var c = 'color: ' + this.color;
args = [args[0], c, 'color: inherit'].concat(Array.prototype.slice.call(args, 1));
// the final "%c" is somewhat tricky, because there could be other
// arguments passed either before or after the %c, so we need to
// figure out the correct index to insert the CSS into
var index = 0;
var lastC = 0;
args[0].replace(/%[a-z%]/g, function(match) {
if ('%%' === match) return;
index++;
if ('%c' === match) {
// we only are interested in the *last* %c
// (the user may have provided their own)
lastC = index;
}
});
args.splice(lastC, 0, c);
return args;
}
/**
* Invokes `console.log()` when available.
* No-op when `console.log` is not a "function".
*
* @api public
*/
function log() {
// This hackery is required for IE8,
// where the `console.log` function doesn't have 'apply'
return 'object' == typeof console
&& 'function' == typeof console.log
&& Function.prototype.apply.call(console.log, console, arguments);
}
/**
* Save `namespaces`.
*
* @param {String} namespaces
* @api private
*/
function save(namespaces) {
try {
if (null == namespaces) {
localStorage.removeItem('debug');
} else {
localStorage.debug = namespaces;
}
} catch(e) {}
}
/**
* Load `namespaces`.
*
* @return {String} returns the previously persisted debug modes
* @api private
*/
function load() {
var r;
try {
r = localStorage.debug;
} catch(e) {}
return r;
}
/**
* Enable namespaces listed in `localStorage.debug` initially.
*/
exports.enable(load());
},{"./debug":13}],13:[function(_dereq_,module,exports){
/**
* This is the common logic for both the Node.js and web browser
* implementations of `debug()`.
*
* Expose `debug()` as the module.
*/
exports = module.exports = debug;
exports.coerce = coerce;
exports.disable = disable;
exports.enable = enable;
exports.enabled = enabled;
exports.humanize = _dereq_('ms');
/**
* The currently active debug mode names, and names to skip.
*/
exports.names = [];
exports.skips = [];
/**
* Map of special "%n" handling functions, for the debug "format" argument.
*
* Valid key names are a single, lowercased letter, i.e. "n".
*/
exports.formatters = {};
/**
* Previously assigned color.
*/
var prevColor = 0;
/**
* Previous log timestamp.
*/
var prevTime;
/**
* Select a color.
*
* @return {Number}
* @api private
*/
function selectColor() {
return exports.colors[prevColor++ % exports.colors.length];
}
/**
* Create a debugger with the given `namespace`.
*
* @param {String} namespace
* @return {Function}
* @api public
*/
function debug(namespace) {
// define the `disabled` version
function disabled() {
}
disabled.enabled = false;
// define the `enabled` version
function enabled() {
var self = enabled;
// set `diff` timestamp
var curr = +new Date();
var ms = curr - (prevTime || curr);
self.diff = ms;
self.prev = prevTime;
self.curr = curr;
prevTime = curr;
// add the `color` if not set
if (null == self.useColors) self.useColors = exports.useColors();
if (null == self.color && self.useColors) self.color = selectColor();
var args = Array.prototype.slice.call(arguments);
args[0] = exports.coerce(args[0]);
if ('string' !== typeof args[0]) {
// anything else let's inspect with %o
args = ['%o'].concat(args);
}
// apply any `formatters` transformations
var index = 0;
args[0] = args[0].replace(/%([a-z%])/g, function(match, format) {
// if we encounter an escaped % then don't increase the array index
if (match === '%%') return match;
index++;
var formatter = exports.formatters[format];
if ('function' === typeof formatter) {
var val = args[index];
match = formatter.call(self, val);
// now we need to remove `args[index]` since it's inlined in the `format`
args.splice(index, 1);
index--;
}
return match;
});
if ('function' === typeof exports.formatArgs) {
args = exports.formatArgs.apply(self, args);
}
var logFn = enabled.log || exports.log || console.log.bind(console);
logFn.apply(self, args);
}
enabled.enabled = true;
var fn = exports.enabled(namespace) ? enabled : disabled;
fn.namespace = namespace;
return fn;
}
/**
* Enables a debug mode by namespaces. This can include modes
* separated by a colon and wildcards.
*
* @param {String} namespaces
* @api public
*/
function enable(namespaces) {
exports.save(namespaces);
var split = (namespaces || '').split(/[\s,]+/);
var len = split.length;
for (var i = 0; i < len; i++) {
if (!split[i]) continue; // ignore empty strings
namespaces = split[i].replace(/\*/g, '.*?');
if (namespaces[0] === '-') {
exports.skips.push(new RegExp('^' + namespaces.substr(1) + '$'));
} else {
exports.names.push(new RegExp('^' + namespaces + '$'));
}
}
}
/**
* Disable debug output.
*
* @api public
*/
function disable() {
exports.enable('');
}
/**
* Returns true if the given mode name is enabled, false otherwise.
*
* @param {String} name
* @return {Boolean}
* @api public
*/
function enabled(name) {
var i, len;
for (i = 0, len = exports.skips.length; i < len; i++) {
if (exports.skips[i].test(name)) {
return false;
}
}
for (i = 0, len = exports.names.length; i < len; i++) {
if (exports.names[i].test(name)) {
return true;
}
}
return false;
}
/**
* Coerce `val`.
*
* @param {Mixed} val
* @return {Mixed}
* @api private
*/
function coerce(val) {
if (val instanceof Error) return val.stack || val.message;
return val;
}
},{"ms":14}],14:[function(_dereq_,module,exports){
/**
* Helpers.
*/
var s = 1000;
var m = s * 60;
var h = m * 60;
var d = h * 24;
var y = d * 365.25;
/**
* Parse or format the given `val`.
*
* Options:
*
* - `long` verbose formatting [false]
*
* @param {String|Number} val
* @param {Object} options
* @return {String|Number}
* @api public
*/
module.exports = function(val, options){
options = options || {};
if ('string' == typeof val) return parse(val);
return options.long
? long(val)
: short(val);
};
/**
* Parse the given `str` and return milliseconds.
*
* @param {String} str
* @return {Number}
* @api private
*/
function parse(str) {
var match = /^((?:\d+)?\.?\d+) *(ms|seconds?|s|minutes?|m|hours?|h|days?|d|years?|y)?$/i.exec(str);
if (!match) return;
var n = parseFloat(match[1]);
var type = (match[2] || 'ms').toLowerCase();
switch (type) {
case 'years':
case 'year':
case 'y':
return n * y;
case 'days':
case 'day':
case 'd':
return n * d;
case 'hours':
case 'hour':
case 'h':
return n * h;
case 'minutes':
case 'minute':
case 'm':
return n * m;
case 'seconds':
case 'second':
case 's':
return n * s;
case 'ms':
return n;
}
}
/**
* Short format for `ms`.
*
* @param {Number} ms
* @return {String}
* @api private
*/
function short(ms) {
if (ms >= d) return Math.round(ms / d) + 'd';
if (ms >= h) return Math.round(ms / h) + 'h';
if (ms >= m) return Math.round(ms / m) + 'm';
if (ms >= s) return Math.round(ms / s) + 's';
return ms + 'ms';
}
/**
* Long format for `ms`.
*
* @param {Number} ms
* @return {String}
* @api private
*/
function long(ms) {
return plural(ms, d, 'day')
|| plural(ms, h, 'hour')
|| plural(ms, m, 'minute')
|| plural(ms, s, 'second')
|| ms + ' ms';
}
/**
* Pluralization helper.
*/
function plural(ms, n, name) {
if (ms < n) return;
if (ms < n * 1.5) return Math.floor(ms / n) + ' ' + name;
return Math.ceil(ms / n) + ' ' + name + 's';
}
},{}],15:[function(_dereq_,module,exports){
(function (global){
/**
* Module dependencies.
*/
var keys = _dereq_('./keys');
var hasBinary = _dereq_('has-binary');
var sliceBuffer = _dereq_('arraybuffer.slice');
var base64encoder = _dereq_('base64-arraybuffer');
var after = _dereq_('after');
var utf8 = _dereq_('utf8');
/**
* Check if we are running an android browser. That requires us to use
* ArrayBuffer with polling transports...
*
* http://ghinda.net/jpeg-blob-ajax-android/
*/
var isAndroid = navigator.userAgent.match(/Android/i);
/**
* Check if we are running in PhantomJS.
* Uploading a Blob with PhantomJS does not work correctly, as reported here:
* https://github.com/ariya/phantomjs/issues/11395
* @type boolean
*/
var isPhantomJS = /PhantomJS/i.test(navigator.userAgent);
/**
* When true, avoids using Blobs to encode payloads.
* @type boolean
*/
var dontSendBlobs = isAndroid || isPhantomJS;
/**
* Current protocol version.
*/
exports.protocol = 3;
/**
* Packet types.
*/
var packets = exports.packets = {
open: 0 // non-ws
, close: 1 // non-ws
, ping: 2
, pong: 3
, message: 4
, upgrade: 5
, noop: 6
};
var packetslist = keys(packets);
/**
* Premade error packet.
*/
var err = { type: 'error', data: 'parser error' };
/**
* Create a blob api even for blob builder when vendor prefixes exist
*/
var Blob = _dereq_('blob');
/**
* Encodes a packet.
*
* <packet type id> [ <data> ]
*
* Example:
*
* 5hello world
* 3
* 4
*
* Binary is encoded in an identical principle
*
* @api private
*/
exports.encodePacket = function (packet, supportsBinary, utf8encode, callback) {
if ('function' == typeof supportsBinary) {
callback = supportsBinary;
supportsBinary = false;
}
if ('function' == typeof utf8encode) {
callback = utf8encode;
utf8encode = null;
}
var data = (packet.data === undefined)
? undefined
: packet.data.buffer || packet.data;
if (global.ArrayBuffer && data instanceof ArrayBuffer) {
return encodeArrayBuffer(packet, supportsBinary, callback);
} else if (Blob && data instanceof global.Blob) {
return encodeBlob(packet, supportsBinary, callback);
}
// might be an object with { base64: true, data: dataAsBase64String }
if (data && data.base64) {
return encodeBase64Object(packet, callback);
}
// Sending data as a utf-8 string
var encoded = packets[packet.type];
// data fragment is optional
if (undefined !== packet.data) {
encoded += utf8encode ? utf8.encode(String(packet.data)) : String(packet.data);
}
return callback('' + encoded);
};
function encodeBase64Object(packet, callback) {
// packet data is an object { base64: true, data: dataAsBase64String }
var message = 'b' + exports.packets[packet.type] + packet.data.data;
return callback(message);
}
/**
* Encode packet helpers for binary types
*/
function encodeArrayBuffer(packet, supportsBinary, callback) {
if (!supportsBinary) {
return exports.encodeBase64Packet(packet, callback);
}
var data = packet.data;
var contentArray = new Uint8Array(data);
var resultBuffer = new Uint8Array(1 + data.byteLength);
resultBuffer[0] = packets[packet.type];
for (var i = 0; i < contentArray.length; i++) {
resultBuffer[i+1] = contentArray[i];
}
return callback(resultBuffer.buffer);
}
function encodeBlobAsArrayBuffer(packet, supportsBinary, callback) {
if (!supportsBinary) {
return exports.encodeBase64Packet(packet, callback);
}
var fr = new FileReader();
fr.onload = function() {
packet.data = fr.result;
exports.encodePacket(packet, supportsBinary, true, callback);
};
return fr.readAsArrayBuffer(packet.data);
}
function encodeBlob(packet, supportsBinary, callback) {
if (!supportsBinary) {
return exports.encodeBase64Packet(packet, callback);
}
if (dontSendBlobs) {
return encodeBlobAsArrayBuffer(packet, supportsBinary, callback);
}
var length = new Uint8Array(1);
length[0] = packets[packet.type];
var blob = new Blob([length.buffer, packet.data]);
return callback(blob);
}
/**
* Encodes a packet with binary data in a base64 string
*
* @param {Object} packet, has `type` and `data`
* @return {String} base64 encoded message
*/
exports.encodeBase64Packet = function(packet, callback) {
var message = 'b' + exports.packets[packet.type];
if (Blob && packet.data instanceof Blob) {
var fr = new FileReader();
fr.onload = function() {
var b64 = fr.result.split(',')[1];
callback(message + b64);
};
return fr.readAsDataURL(packet.data);
}
var b64data;
try {
b64data = String.fromCharCode.apply(null, new Uint8Array(packet.data));
} catch (e) {
// iPhone Safari doesn't let you apply with typed arrays
var typed = new Uint8Array(packet.data);
var basic = new Array(typed.length);
for (var i = 0; i < typed.length; i++) {
basic[i] = typed[i];
}
b64data = String.fromCharCode.apply(null, basic);
}
message += global.btoa(b64data);
return callback(message);
};
/**
* Decodes a packet. Changes format to Blob if requested.
*
* @return {Object} with `type` and `data` (if any)
* @api private
*/
exports.decodePacket = function (data, binaryType, utf8decode) {
// String data
if (typeof data == 'string' || data === undefined) {
if (data.charAt(0) == 'b') {
return exports.decodeBase64Packet(data.substr(1), binaryType);
}
if (utf8decode) {
try {
data = utf8.decode(data);
} catch (e) {
return err;
}
}
var type = data.charAt(0);
if (Number(type) != type || !packetslist[type]) {
return err;
}
if (data.length > 1) {
return { type: packetslist[type], data: data.substring(1) };
} else {
return { type: packetslist[type] };
}
}
var asArray = new Uint8Array(data);
var type = asArray[0];
var rest = sliceBuffer(data, 1);
if (Blob && binaryType === 'blob') {
rest = new Blob([rest]);
}
return { type: packetslist[type], data: rest };
};
/**
* Decodes a packet encoded in a base64 string
*
* @param {String} base64 encoded message
* @return {Object} with `type` and `data` (if any)
*/
exports.decodeBase64Packet = function(msg, binaryType) {
var type = packetslist[msg.charAt(0)];
if (!global.ArrayBuffer) {
return { type: type, data: { base64: true, data: msg.substr(1) } };
}
var data = base64encoder.decode(msg.substr(1));
if (binaryType === 'blob' && Blob) {
data = new Blob([data]);
}
return { type: type, data: data };
};
/**
* Encodes multiple messages (payload).
*
* <length>:data
*
* Example:
*
* 11:hello world2:hi
*
* If any contents are binary, they will be encoded as base64 strings. Base64
* encoded strings are marked with a b before the length specifier
*
* @param {Array} packets
* @api private
*/
exports.encodePayload = function (packets, supportsBinary, callback) {
if (typeof supportsBinary == 'function') {
callback = supportsBinary;
supportsBinary = null;
}
var isBinary = hasBinary(packets);
if (supportsBinary && isBinary) {
if (Blob && !dontSendBlobs) {
return exports.encodePayloadAsBlob(packets, callback);
}
return exports.encodePayloadAsArrayBuffer(packets, callback);
}
if (!packets.length) {
return callback('0:');
}
function setLengthHeader(message) {
return message.length + ':' + message;
}
function encodeOne(packet, doneCallback) {
exports.encodePacket(packet, !isBinary ? false : supportsBinary, true, function(message) {
doneCallback(null, setLengthHeader(message));
});
}
map(packets, encodeOne, function(err, results) {
return callback(results.join(''));
});
};
/**
* Async array map using after
*/
function map(ary, each, done) {
var result = new Array(ary.length);
var next = after(ary.length, done);
var eachWithIndex = function(i, el, cb) {
each(el, function(error, msg) {
result[i] = msg;
cb(error, result);
});
};
for (var i = 0; i < ary.length; i++) {
eachWithIndex(i, ary[i], next);
}
}
/*
* Decodes data when a payload is maybe expected. Possible binary contents are
* decoded from their base64 representation
*
* @param {String} data, callback method
* @api public
*/
exports.decodePayload = function (data, binaryType, callback) {
if (typeof data != 'string') {
return exports.decodePayloadAsBinary(data, binaryType, callback);
}
if (typeof binaryType === 'function') {
callback = binaryType;
binaryType = null;
}
var packet;
if (data == '') {
// parser error - ignoring payload
return callback(err, 0, 1);
}
var length = ''
, n, msg;
for (var i = 0, l = data.length; i < l; i++) {
var chr = data.charAt(i);
if (':' != chr) {
length += chr;
} else {
if ('' == length || (length != (n = Number(length)))) {
// parser error - ignoring payload
return callback(err, 0, 1);
}
msg = data.substr(i + 1, n);
if (length != msg.length) {
// parser error - ignoring payload
return callback(err, 0, 1);
}
if (msg.length) {
packet = exports.decodePacket(msg, binaryType, true);
if (err.type == packet.type && err.data == packet.data) {
// parser error in individual packet - ignoring payload
return callback(err, 0, 1);
}
var ret = callback(packet, i + n, l);
if (false === ret) return;
}
// advance cursor
i += n;
length = '';
}
}
if (length != '') {
// parser error - ignoring payload
return callback(err, 0, 1);
}
};
/**
* Encodes multiple messages (payload) as binary.
*
* <1 = binary, 0 = string><number from 0-9><number from 0-9>[...]<number
* 255><data>
*
* Example:
* 1 3 255 1 2 3, if the binary contents are interpreted as 8 bit integers
*
* @param {Array} packets
* @return {ArrayBuffer} encoded payload
* @api private
*/
exports.encodePayloadAsArrayBuffer = function(packets, callback) {
if (!packets.length) {
return callback(new ArrayBuffer(0));
}
function encodeOne(packet, doneCallback) {
exports.encodePacket(packet, true, true, function(data) {
return doneCallback(null, data);
});
}
map(packets, encodeOne, function(err, encodedPackets) {
var totalLength = encodedPackets.reduce(function(acc, p) {
var len;
if (typeof p === 'string'){
len = p.length;
} else {
len = p.byteLength;
}
return acc + len.toString().length + len + 2; // string/binary identifier + separator = 2
}, 0);
var resultArray = new Uint8Array(totalLength);
var bufferIndex = 0;
encodedPackets.forEach(function(p) {
var isString = typeof p === 'string';
var ab = p;
if (isString) {
var view = new Uint8Array(p.length);
for (var i = 0; i < p.length; i++) {
view[i] = p.charCodeAt(i);
}
ab = view.buffer;
}
if (isString) { // not true binary
resultArray[bufferIndex++] = 0;
} else { // true binary
resultArray[bufferIndex++] = 1;
}
var lenStr = ab.byteLength.toString();
for (var i = 0; i < lenStr.length; i++) {
resultArray[bufferIndex++] = parseInt(lenStr[i]);
}
resultArray[bufferIndex++] = 255;
var view = new Uint8Array(ab);
for (var i = 0; i < view.length; i++) {
resultArray[bufferIndex++] = view[i];
}
});
return callback(resultArray.buffer);
});
};
/**
* Encode as Blob
*/
exports.encodePayloadAsBlob = function(packets, callback) {
function encodeOne(packet, doneCallback) {
exports.encodePacket(packet, true, true, function(encoded) {
var binaryIdentifier = new Uint8Array(1);
binaryIdentifier[0] = 1;
if (typeof encoded === 'string') {
var view = new Uint8Array(encoded.length);
for (var i = 0; i < encoded.length; i++) {
view[i] = encoded.charCodeAt(i);
}
encoded = view.buffer;
binaryIdentifier[0] = 0;
}
var len = (encoded instanceof ArrayBuffer)
? encoded.byteLength
: encoded.size;
var lenStr = len.toString();
var lengthAry = new Uint8Array(lenStr.length + 1);
for (var i = 0; i < lenStr.length; i++) {
lengthAry[i] = parseInt(lenStr[i]);
}
lengthAry[lenStr.length] = 255;
if (Blob) {
var blob = new Blob([binaryIdentifier.buffer, lengthAry.buffer, encoded]);
doneCallback(null, blob);
}
});
}
map(packets, encodeOne, function(err, results) {
return callback(new Blob(results));
});
};
/*
* Decodes data when a payload is maybe expected. Strings are decoded by
* interpreting each byte as a key code for entries marked to start with 0. See
* description of encodePayloadAsBinary
*
* @param {ArrayBuffer} data, callback method
* @api public
*/
exports.decodePayloadAsBinary = function (data, binaryType, callback) {
if (typeof binaryType === 'function') {
callback = binaryType;
binaryType = null;
}
var bufferTail = data;
var buffers = [];
var numberTooLong = false;
while (bufferTail.byteLength > 0) {
var tailArray = new Uint8Array(bufferTail);
var isString = tailArray[0] === 0;
var msgLength = '';
for (var i = 1; ; i++) {
if (tailArray[i] == 255) break;
if (msgLength.length > 310) {
numberTooLong = true;
break;
}
msgLength += tailArray[i];
}
if(numberTooLong) return callback(err, 0, 1);
bufferTail = sliceBuffer(bufferTail, 2 + msgLength.length);
msgLength = parseInt(msgLength);
var msg = sliceBuffer(bufferTail, 0, msgLength);
if (isString) {
try {
msg = String.fromCharCode.apply(null, new Uint8Array(msg));
} catch (e) {
// iPhone Safari doesn't let you apply to typed arrays
var typed = new Uint8Array(msg);
msg = '';
for (var i = 0; i < typed.length; i++) {
msg += String.fromCharCode(typed[i]);
}
}
}
buffers.push(msg);
bufferTail = sliceBuffer(bufferTail, msgLength);
}
var total = buffers.length;
buffers.forEach(function(buffer, i) {
callback(exports.decodePacket(buffer, binaryType, true), i, total);
});
};
}).call(this,typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{"./keys":16,"after":17,"arraybuffer.slice":18,"base64-arraybuffer":19,"blob":20,"has-binary":21,"utf8":23}],16:[function(_dereq_,module,exports){
/**
* Gets the keys for an object.
*
* @return {Array} keys
* @api private
*/
module.exports = Object.keys || function keys (obj){
var arr = [];
var has = Object.prototype.hasOwnProperty;
for (var i in obj) {
if (has.call(obj, i)) {
arr.push(i);
}
}
return arr;
};
},{}],17:[function(_dereq_,module,exports){
module.exports = after
function after(count, callback, err_cb) {
var bail = false
err_cb = err_cb || noop
proxy.count = count
return (count === 0) ? callback() : proxy
function proxy(err, result) {
if (proxy.count <= 0) {
throw new Error('after called too many times')
}
--proxy.count
// after first error, rest are passed to err_cb
if (err) {
bail = true
callback(err)
// future error callbacks will go to error handler
callback = err_cb
} else if (proxy.count === 0 && !bail) {
callback(null, result)
}
}
}
function noop() {}
},{}],18:[function(_dereq_,module,exports){
/**
* An abstraction for slicing an arraybuffer even when
* ArrayBuffer.prototype.slice is not supported
*
* @api public
*/
module.exports = function(arraybuffer, start, end) {
var bytes = arraybuffer.byteLength;
start = start || 0;
end = end || bytes;
if (arraybuffer.slice) { return arraybuffer.slice(start, end); }
if (start < 0) { start += bytes; }
if (end < 0) { end += bytes; }
if (end > bytes) { end = bytes; }
if (start >= bytes || start >= end || bytes === 0) {
return new ArrayBuffer(0);
}
var abv = new Uint8Array(arraybuffer);
var result = new Uint8Array(end - start);
for (var i = start, ii = 0; i < end; i++, ii++) {
result[ii] = abv[i];
}
return result.buffer;
};
},{}],19:[function(_dereq_,module,exports){
/*
* base64-arraybuffer
* https://github.com/niklasvh/base64-arraybuffer
*
* Copyright (c) 2012 Niklas von Hertzen
* Licensed under the MIT license.
*/
(function(chars){
"use strict";
exports.encode = function(arraybuffer) {
var bytes = new Uint8Array(arraybuffer),
i, len = bytes.length, base64 = "";
for (i = 0; i < len; i+=3) {
base64 += chars[bytes[i] >> 2];
base64 += chars[((bytes[i] & 3) << 4) | (bytes[i + 1] >> 4)];
base64 += chars[((bytes[i + 1] & 15) << 2) | (bytes[i + 2] >> 6)];
base64 += chars[bytes[i + 2] & 63];
}
if ((len % 3) === 2) {
base64 = base64.substring(0, base64.length - 1) + "=";
} else if (len % 3 === 1) {
base64 = base64.substring(0, base64.length - 2) + "==";
}
return base64;
};
exports.decode = function(base64) {
var bufferLength = base64.length * 0.75,
len = base64.length, i, p = 0,
encoded1, encoded2, encoded3, encoded4;
if (base64[base64.length - 1] === "=") {
bufferLength--;
if (base64[base64.length - 2] === "=") {
bufferLength--;
}
}
var arraybuffer = new ArrayBuffer(bufferLength),
bytes = new Uint8Array(arraybuffer);
for (i = 0; i < len; i+=4) {
encoded1 = chars.indexOf(base64[i]);
encoded2 = chars.indexOf(base64[i+1]);
encoded3 = chars.indexOf(base64[i+2]);
encoded4 = chars.indexOf(base64[i+3]);
bytes[p++] = (encoded1 << 2) | (encoded2 >> 4);
bytes[p++] = ((encoded2 & 15) << 4) | (encoded3 >> 2);
bytes[p++] = ((encoded3 & 3) << 6) | (encoded4 & 63);
}
return arraybuffer;
};
})("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/");
},{}],20:[function(_dereq_,module,exports){
(function (global){
/**
* Create a blob builder even when vendor prefixes exist
*/
var BlobBuilder = global.BlobBuilder
|| global.WebKitBlobBuilder
|| global.MSBlobBuilder
|| global.MozBlobBuilder;
/**
* Check if Blob constructor is supported
*/
var blobSupported = (function() {
try {
var a = new Blob(['hi']);
return a.size === 2;
} catch(e) {
return false;
}
})();
/**
* Check if Blob constructor supports ArrayBufferViews
* Fails in Safari 6, so we need to map to ArrayBuffers there.
*/
var blobSupportsArrayBufferView = blobSupported && (function() {
try {
var b = new Blob([new Uint8Array([1,2])]);
return b.size === 2;
} catch(e) {
return false;
}
})();
/**
* Check if BlobBuilder is supported
*/
var blobBuilderSupported = BlobBuilder
&& BlobBuilder.prototype.append
&& BlobBuilder.prototype.getBlob;
/**
* Helper function that maps ArrayBufferViews to ArrayBuffers
* Used by BlobBuilder constructor and old browsers that didn't
* support it in the Blob constructor.
*/
function mapArrayBufferViews(ary) {
for (var i = 0; i < ary.length; i++) {
var chunk = ary[i];
if (chunk.buffer instanceof ArrayBuffer) {
var buf = chunk.buffer;
// if this is a subarray, make a copy so we only
// include the subarray region from the underlying buffer
if (chunk.byteLength !== buf.byteLength) {
var copy = new Uint8Array(chunk.byteLength);
copy.set(new Uint8Array(buf, chunk.byteOffset, chunk.byteLength));
buf = copy.buffer;
}
ary[i] = buf;
}
}
}
function BlobBuilderConstructor(ary, options) {
options = options || {};
var bb = new BlobBuilder();
mapArrayBufferViews(ary);
for (var i = 0; i < ary.length; i++) {
bb.append(ary[i]);
}
return (options.type) ? bb.getBlob(options.type) : bb.getBlob();
};
function BlobConstructor(ary, options) {
mapArrayBufferViews(ary);
return new Blob(ary, options || {});
};
module.exports = (function() {
if (blobSupported) {
return blobSupportsArrayBufferView ? global.Blob : BlobConstructor;
} else if (blobBuilderSupported) {
return BlobBuilderConstructor;
} else {
return undefined;
}
})();
}).call(this,typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{}],21:[function(_dereq_,module,exports){
(function (global){
/*
* Module requirements.
*/
var isArray = _dereq_('isarray');
/**
* Module exports.
*/
module.exports = hasBinary;
/**
* Checks for binary data.
*
* Right now only Buffer and ArrayBuffer are supported..
*
* @param {Object} anything
* @api public
*/
function hasBinary(data) {
function _hasBinary(obj) {
if (!obj) return false;
if ( (global.Buffer && global.Buffer.isBuffer(obj)) ||
(global.ArrayBuffer && obj instanceof ArrayBuffer) ||
(global.Blob && obj instanceof Blob) ||
(global.File && obj instanceof File)
) {
return true;
}
if (isArray(obj)) {
for (var i = 0; i < obj.length; i++) {
if (_hasBinary(obj[i])) {
return true;
}
}
} else if (obj && 'object' == typeof obj) {
if (obj.toJSON) {
obj = obj.toJSON();
}
for (var key in obj) {
if (Object.prototype.hasOwnProperty.call(obj, key) && _hasBinary(obj[key])) {
return true;
}
}
}
return false;
}
return _hasBinary(data);
}
}).call(this,typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{"isarray":22}],22:[function(_dereq_,module,exports){
module.exports = Array.isArray || function (arr) {
return Object.prototype.toString.call(arr) == '[object Array]';
};
},{}],23:[function(_dereq_,module,exports){
(function (global){
/*! https://mths.be/utf8js v2.0.0 by @mathias */
;(function(root) {
// Detect free variables `exports`
var freeExports = typeof exports == 'object' && exports;
// Detect free variable `module`
var freeModule = typeof module == 'object' && module &&
module.exports == freeExports && module;
// Detect free variable `global`, from Node.js or Browserified code,
// and use it as `root`
var freeGlobal = typeof global == 'object' && global;
if (freeGlobal.global === freeGlobal || freeGlobal.window === freeGlobal) {
root = freeGlobal;
}
/*--------------------------------------------------------------------------*/
var stringFromCharCode = String.fromCharCode;
// Taken from https://mths.be/punycode
function ucs2decode(string) {
var output = [];
var counter = 0;
var length = string.length;
var value;
var extra;
while (counter < length) {
value = string.charCodeAt(counter++);
if (value >= 0xD800 && value <= 0xDBFF && counter < length) {
// high surrogate, and there is a next character
extra = string.charCodeAt(counter++);
if ((extra & 0xFC00) == 0xDC00) { // low surrogate
output.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000);
} else {
// unmatched surrogate; only append this code unit, in case the next
// code unit is the high surrogate of a surrogate pair
output.push(value);
counter--;
}
} else {
output.push(value);
}
}
return output;
}
// Taken from https://mths.be/punycode
function ucs2encode(array) {
var length = array.length;
var index = -1;
var value;
var output = '';
while (++index < length) {
value = array[index];
if (value > 0xFFFF) {
value -= 0x10000;
output += stringFromCharCode(value >>> 10 & 0x3FF | 0xD800);
value = 0xDC00 | value & 0x3FF;
}
output += stringFromCharCode(value);
}
return output;
}
function checkScalarValue(codePoint) {
if (codePoint >= 0xD800 && codePoint <= 0xDFFF) {
throw Error(
'Lone surrogate U+' + codePoint.toString(16).toUpperCase() +
' is not a scalar value'
);
}
}
/*--------------------------------------------------------------------------*/
function createByte(codePoint, shift) {
return stringFromCharCode(((codePoint >> shift) & 0x3F) | 0x80);
}
function encodeCodePoint(codePoint) {
if ((codePoint & 0xFFFFFF80) == 0) { // 1-byte sequence
return stringFromCharCode(codePoint);
}
var symbol = '';
if ((codePoint & 0xFFFFF800) == 0) { // 2-byte sequence
symbol = stringFromCharCode(((codePoint >> 6) & 0x1F) | 0xC0);
}
else if ((codePoint & 0xFFFF0000) == 0) { // 3-byte sequence
checkScalarValue(codePoint);
symbol = stringFromCharCode(((codePoint >> 12) & 0x0F) | 0xE0);
symbol += createByte(codePoint, 6);
}
else if ((codePoint & 0xFFE00000) == 0) { // 4-byte sequence
symbol = stringFromCharCode(((codePoint >> 18) & 0x07) | 0xF0);
symbol += createByte(codePoint, 12);
symbol += createByte(codePoint, 6);
}
symbol += stringFromCharCode((codePoint & 0x3F) | 0x80);
return symbol;
}
function utf8encode(string) {
var codePoints = ucs2decode(string);
var length = codePoints.length;
var index = -1;
var codePoint;
var byteString = '';
while (++index < length) {
codePoint = codePoints[index];
byteString += encodeCodePoint(codePoint);
}
return byteString;
}
/*--------------------------------------------------------------------------*/
function readContinuationByte() {
if (byteIndex >= byteCount) {
throw Error('Invalid byte index');
}
var continuationByte = byteArray[byteIndex] & 0xFF;
byteIndex++;
if ((continuationByte & 0xC0) == 0x80) {
return continuationByte & 0x3F;
}
// If we end up here, it’s not a continuation byte
throw Error('Invalid continuation byte');
}
function decodeSymbol() {
var byte1;
var byte2;
var byte3;
var byte4;
var codePoint;
if (byteIndex > byteCount) {
throw Error('Invalid byte index');
}
if (byteIndex == byteCount) {
return false;
}
// Read first byte
byte1 = byteArray[byteIndex] & 0xFF;
byteIndex++;
// 1-byte sequence (no continuation bytes)
if ((byte1 & 0x80) == 0) {
return byte1;
}
// 2-byte sequence
if ((byte1 & 0xE0) == 0xC0) {
var byte2 = readContinuationByte();
codePoint = ((byte1 & 0x1F) << 6) | byte2;
if (codePoint >= 0x80) {
return codePoint;
} else {
throw Error('Invalid continuation byte');
}
}
// 3-byte sequence (may include unpaired surrogates)
if ((byte1 & 0xF0) == 0xE0) {
byte2 = readContinuationByte();
byte3 = readContinuationByte();
codePoint = ((byte1 & 0x0F) << 12) | (byte2 << 6) | byte3;
if (codePoint >= 0x0800) {
checkScalarValue(codePoint);
return codePoint;
} else {
throw Error('Invalid continuation byte');
}
}
// 4-byte sequence
if ((byte1 & 0xF8) == 0xF0) {
byte2 = readContinuationByte();
byte3 = readContinuationByte();
byte4 = readContinuationByte();
codePoint = ((byte1 & 0x0F) << 0x12) | (byte2 << 0x0C) |
(byte3 << 0x06) | byte4;
if (codePoint >= 0x010000 && codePoint <= 0x10FFFF) {
return codePoint;
}
}
throw Error('Invalid UTF-8 detected');
}
var byteArray;
var byteCount;
var byteIndex;
function utf8decode(byteString) {
byteArray = ucs2decode(byteString);
byteCount = byteArray.length;
byteIndex = 0;
var codePoints = [];
var tmp;
while ((tmp = decodeSymbol()) !== false) {
codePoints.push(tmp);
}
return ucs2encode(codePoints);
}
/*--------------------------------------------------------------------------*/
var utf8 = {
'version': '2.0.0',
'encode': utf8encode,
'decode': utf8decode
};
if (freeExports && !freeExports.nodeType) {
if (freeModule) { // in Node.js or RingoJS v0.8.0+
freeModule.exports = utf8;
} else { // in Narwhal or RingoJS v0.7.0-
var object = {};
var hasOwnProperty = object.hasOwnProperty;
for (var key in utf8) {
hasOwnProperty.call(utf8, key) && (freeExports[key] = utf8[key]);
}
}
} else { // in Rhino or a web browser
root.utf8 = utf8;
}
}(this));
}).call(this,typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{}],24:[function(_dereq_,module,exports){
/**
* Module dependencies.
*/
var global = _dereq_('global');
/**
* Module exports.
*
* Logic borrowed from Modernizr:
*
* - https://github.com/Modernizr/Modernizr/blob/master/feature-detects/cors.js
*/
try {
module.exports = 'XMLHttpRequest' in global &&
'withCredentials' in new global.XMLHttpRequest();
} catch (err) {
// if XMLHttp support is disabled in IE then it will throw
// when trying to create
module.exports = false;
}
},{"global":25}],25:[function(_dereq_,module,exports){
/**
* Returns `this`. Execute this without a "context" (i.e. without it being
* attached to an object of the left-hand side), and `this` points to the
* "global" scope of the current JS execution.
*/
module.exports = (function () { return this; })();
},{}],26:[function(_dereq_,module,exports){
var indexOf = [].indexOf;
module.exports = function(arr, obj){
if (indexOf) return arr.indexOf(obj);
for (var i = 0; i < arr.length; ++i) {
if (arr[i] === obj) return i;
}
return -1;
};
},{}],27:[function(_dereq_,module,exports){
(function (global){
/**
* JSON parse.
*
* @see Based on jQuery#parseJSON (MIT) and JSON2
* @api private
*/
var rvalidchars = /^[\],:{}\s]*$/;
var rvalidescape = /\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g;
var rvalidtokens = /"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g;
var rvalidbraces = /(?:^|:|,)(?:\s*\[)+/g;
var rtrimLeft = /^\s+/;
var rtrimRight = /\s+$/;
module.exports = function parsejson(data) {
if ('string' != typeof data || !data) {
return null;
}
data = data.replace(rtrimLeft, '').replace(rtrimRight, '');
// Attempt to parse using the native JSON parser first
if (global.JSON && JSON.parse) {
return JSON.parse(data);
}
if (rvalidchars.test(data.replace(rvalidescape, '@')
.replace(rvalidtokens, ']')
.replace(rvalidbraces, ''))) {
return (new Function('return ' + data))();
}
};
}).call(this,typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{}],28:[function(_dereq_,module,exports){
/**
* Compiles a querystring
* Returns string representation of the object
*
* @param {Object}
* @api private
*/
exports.encode = function (obj) {
var str = '';
for (var i in obj) {
if (obj.hasOwnProperty(i)) {
if (str.length) str += '&';
str += encodeURIComponent(i) + '=' + encodeURIComponent(obj[i]);
}
}
return str;
};
/**
* Parses a simple querystring into an object
*
* @param {String} qs
* @api private
*/
exports.decode = function(qs){
var qry = {};
var pairs = qs.split('&');
for (var i = 0, l = pairs.length; i < l; i++) {
var pair = pairs[i].split('=');
qry[decodeURIComponent(pair[0])] = decodeURIComponent(pair[1]);
}
return qry;
};
},{}],29:[function(_dereq_,module,exports){
/**
* Parses an URI
*
* @author Steven Levithan <stevenlevithan.com> (MIT license)
* @api private
*/
var re = /^(?:(?![^:@]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/;
var parts = [
'source', 'protocol', 'authority', 'userInfo', 'user', 'password', 'host', 'port', 'relative', 'path', 'directory', 'file', 'query', 'anchor'
];
module.exports = function parseuri(str) {
var src = str,
b = str.indexOf('['),
e = str.indexOf(']');
if (b != -1 && e != -1) {
str = str.substring(0, b) + str.substring(b, e).replace(/:/g, ';') + str.substring(e, str.length);
}
var m = re.exec(str || ''),
uri = {},
i = 14;
while (i--) {
uri[parts[i]] = m[i] || '';
}
if (b != -1 && e != -1) {
uri.source = src;
uri.host = uri.host.substring(1, uri.host.length - 1).replace(/;/g, ':');
uri.authority = uri.authority.replace('[', '').replace(']', '').replace(/;/g, ':');
uri.ipv6uri = true;
}
return uri;
};
},{}],30:[function(_dereq_,module,exports){
/**
* Module dependencies.
*/
var global = (function() { return this; })();
/**
* WebSocket constructor.
*/
var WebSocket = global.WebSocket || global.MozWebSocket;
/**
* Module exports.
*/
module.exports = WebSocket ? ws : null;
/**
* WebSocket constructor.
*
* The third `opts` options object gets ignored in web browsers, since it's
* non-standard, and throws a TypeError if passed to the constructor.
* See: https://github.com/einaros/ws/issues/227
*
* @param {String} uri
* @param {Array} protocols (optional)
* @param {Object) opts (optional)
* @api public
*/
function ws(uri, protocols, opts) {
var instance;
if (protocols) {
instance = new WebSocket(uri, protocols);
} else {
instance = new WebSocket(uri);
}
return instance;
}
if (WebSocket) ws.prototype = WebSocket.prototype;
},{}],31:[function(_dereq_,module,exports){
module.exports = _dereq_('./lib/');
},{"./lib/":1}]},{},[31])(31)
}); | transformers/engine.io/library.js | !function(e){var f;'undefined'!=typeof window?f=window:'undefined'!=typeof self&&(f=self),f.eio=e()}(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(_dereq_,module,exports){
module.exports = _dereq_('./lib/');
},{"./lib/":2}],2:[function(_dereq_,module,exports){
module.exports = _dereq_('./socket');
/**
* Exports parser
*
* @api public
*
*/
module.exports.parser = _dereq_('engine.io-parser');
},{"./socket":3,"engine.io-parser":16}],3:[function(_dereq_,module,exports){
(function (global){
/**
* Module dependencies.
*/
var transports = _dereq_('./transports');
var Emitter = _dereq_('component-emitter');
var debug = _dereq_('debug')('engine.io-client:socket');
var index = _dereq_('indexof');
var parser = _dereq_('engine.io-parser');
var parseuri = _dereq_('parseuri');
var parsejson = _dereq_('parsejson');
var parseqs = _dereq_('parseqs');
/**
* Module exports.
*/
module.exports = Socket;
/**
* Noop function.
*
* @api private
*/
function noop(){}
/**
* Socket constructor.
*
* @param {String|Object} uri or options
* @param {Object} options
* @api public
*/
function Socket(uri, opts){
if (!(this instanceof Socket)) return new Socket(uri, opts);
opts = opts || {};
if (uri && 'object' == typeof uri) {
opts = uri;
uri = null;
}
if (uri) {
uri = parseuri(uri);
opts.host = uri.host;
opts.secure = uri.protocol == 'https' || uri.protocol == 'wss';
opts.port = uri.port;
if (uri.query) opts.query = uri.query;
}
this.secure = null != opts.secure ? opts.secure :
(global.location && 'https:' == location.protocol);
if (opts.host) {
var pieces = opts.host.split(':');
opts.hostname = pieces.shift();
if (pieces.length) {
opts.port = pieces.pop();
} else if (!opts.port) {
// if no port is specified manually, use the protocol default
opts.port = this.secure ? '443' : '80';
}
}
this.agent = opts.agent || false;
this.hostname = opts.hostname ||
(global.location ? location.hostname : 'localhost');
this.port = opts.port || (global.location && location.port ?
location.port :
(this.secure ? 443 : 80));
this.query = opts.query || {};
if ('string' == typeof this.query) this.query = parseqs.decode(this.query);
this.upgrade = false !== opts.upgrade;
this.path = (opts.path || '/engine.io').replace(/\/$/, '') + '/';
this.forceJSONP = !!opts.forceJSONP;
this.jsonp = false !== opts.jsonp;
this.forceBase64 = !!opts.forceBase64;
this.enablesXDR = !!opts.enablesXDR;
this.timestampParam = opts.timestampParam || 't';
this.timestampRequests = opts.timestampRequests;
this.transports = opts.transports || ['polling', 'websocket'];
this.readyState = '';
this.writeBuffer = [];
this.callbackBuffer = [];
this.policyPort = opts.policyPort || 843;
this.rememberUpgrade = opts.rememberUpgrade || false;
this.binaryType = null;
this.onlyBinaryUpgrades = opts.onlyBinaryUpgrades;
// SSL options for Node.js client
this.pfx = opts.pfx || null;
this.key = opts.key || null;
this.passphrase = opts.passphrase || null;
this.cert = opts.cert || null;
this.ca = opts.ca || null;
this.ciphers = opts.ciphers || null;
this.rejectUnauthorized = opts.rejectUnauthorized || null;
this.open();
}
Socket.priorWebsocketSuccess = false;
/**
* Mix in `Emitter`.
*/
Emitter(Socket.prototype);
/**
* Protocol version.
*
* @api public
*/
Socket.protocol = parser.protocol; // this is an int
/**
* Expose deps for legacy compatibility
* and standalone browser access.
*/
Socket.Socket = Socket;
Socket.Transport = _dereq_('./transport');
Socket.transports = _dereq_('./transports');
Socket.parser = _dereq_('engine.io-parser');
/**
* Creates transport of the given type.
*
* @param {String} transport name
* @return {Transport}
* @api private
*/
Socket.prototype.createTransport = function (name) {
debug('creating transport "%s"', name);
var query = clone(this.query);
// append engine.io protocol identifier
query.EIO = parser.protocol;
// transport name
query.transport = name;
// session id if we already have one
if (this.id) query.sid = this.id;
var transport = new transports[name]({
agent: this.agent,
hostname: this.hostname,
port: this.port,
secure: this.secure,
path: this.path,
query: query,
forceJSONP: this.forceJSONP,
jsonp: this.jsonp,
forceBase64: this.forceBase64,
enablesXDR: this.enablesXDR,
timestampRequests: this.timestampRequests,
timestampParam: this.timestampParam,
policyPort: this.policyPort,
socket: this,
pfx: this.pfx,
key: this.key,
passphrase: this.passphrase,
cert: this.cert,
ca: this.ca,
ciphers: this.ciphers,
rejectUnauthorized: this.rejectUnauthorized
});
return transport;
};
function clone (obj) {
var o = {};
for (var i in obj) {
if (obj.hasOwnProperty(i)) {
o[i] = obj[i];
}
}
return o;
}
/**
* Initializes transport to use and starts probe.
*
* @api private
*/
Socket.prototype.open = function () {
var transport;
if (this.rememberUpgrade && Socket.priorWebsocketSuccess && this.transports.indexOf('websocket') != -1) {
transport = 'websocket';
} else if (0 == this.transports.length) {
// Emit error on next tick so it can be listened to
var self = this;
setTimeout(function() {
self.emit('error', 'No transports available');
}, 0);
return;
} else {
transport = this.transports[0];
}
this.readyState = 'opening';
// Retry with the next transport if the transport is disabled (jsonp: false)
var transport;
try {
transport = this.createTransport(transport);
} catch (e) {
this.transports.shift();
this.open();
return;
}
transport.open();
this.setTransport(transport);
};
/**
* Sets the current transport. Disables the existing one (if any).
*
* @api private
*/
Socket.prototype.setTransport = function(transport){
debug('setting transport %s', transport.name);
var self = this;
if (this.transport) {
debug('clearing existing transport %s', this.transport.name);
this.transport.removeAllListeners();
}
// set up transport
this.transport = transport;
// set up transport listeners
transport
.on('drain', function(){
self.onDrain();
})
.on('packet', function(packet){
self.onPacket(packet);
})
.on('error', function(e){
self.onError(e);
})
.on('close', function(){
self.onClose('transport close');
});
};
/**
* Probes a transport.
*
* @param {String} transport name
* @api private
*/
Socket.prototype.probe = function (name) {
debug('probing transport "%s"', name);
var transport = this.createTransport(name, { probe: 1 })
, failed = false
, self = this;
Socket.priorWebsocketSuccess = false;
function onTransportOpen(){
if (self.onlyBinaryUpgrades) {
var upgradeLosesBinary = !this.supportsBinary && self.transport.supportsBinary;
failed = failed || upgradeLosesBinary;
}
if (failed) return;
debug('probe transport "%s" opened', name);
transport.send([{ type: 'ping', data: 'probe' }]);
transport.once('packet', function (msg) {
if (failed) return;
if ('pong' == msg.type && 'probe' == msg.data) {
debug('probe transport "%s" pong', name);
self.upgrading = true;
self.emit('upgrading', transport);
if (!transport) return;
Socket.priorWebsocketSuccess = 'websocket' == transport.name;
debug('pausing current transport "%s"', self.transport.name);
self.transport.pause(function () {
if (failed) return;
if ('closed' == self.readyState) return;
debug('changing transport and sending upgrade packet');
cleanup();
self.setTransport(transport);
transport.send([{ type: 'upgrade' }]);
self.emit('upgrade', transport);
transport = null;
self.upgrading = false;
self.flush();
});
} else {
debug('probe transport "%s" failed', name);
var err = new Error('probe error');
err.transport = transport.name;
self.emit('upgradeError', err);
}
});
}
function freezeTransport() {
if (failed) return;
// Any callback called by transport should be ignored since now
failed = true;
cleanup();
transport.close();
transport = null;
}
//Handle any error that happens while probing
function onerror(err) {
var error = new Error('probe error: ' + err);
error.transport = transport.name;
freezeTransport();
debug('probe transport "%s" failed because of error: %s', name, err);
self.emit('upgradeError', error);
}
function onTransportClose(){
onerror("transport closed");
}
//When the socket is closed while we're probing
function onclose(){
onerror("socket closed");
}
//When the socket is upgraded while we're probing
function onupgrade(to){
if (transport && to.name != transport.name) {
debug('"%s" works - aborting "%s"', to.name, transport.name);
freezeTransport();
}
}
//Remove all listeners on the transport and on self
function cleanup(){
transport.removeListener('open', onTransportOpen);
transport.removeListener('error', onerror);
transport.removeListener('close', onTransportClose);
self.removeListener('close', onclose);
self.removeListener('upgrading', onupgrade);
}
transport.once('open', onTransportOpen);
transport.once('error', onerror);
transport.once('close', onTransportClose);
this.once('close', onclose);
this.once('upgrading', onupgrade);
transport.open();
};
/**
* Called when connection is deemed open.
*
* @api public
*/
Socket.prototype.onOpen = function () {
debug('socket open');
this.readyState = 'open';
Socket.priorWebsocketSuccess = 'websocket' == this.transport.name;
this.emit('open');
this.flush();
// we check for `readyState` in case an `open`
// listener already closed the socket
if ('open' == this.readyState && this.upgrade && this.transport.pause) {
debug('starting upgrade probes');
for (var i = 0, l = this.upgrades.length; i < l; i++) {
this.probe(this.upgrades[i]);
}
}
};
/**
* Handles a packet.
*
* @api private
*/
Socket.prototype.onPacket = function (packet) {
if ('opening' == this.readyState || 'open' == this.readyState) {
debug('socket receive: type "%s", data "%s"', packet.type, packet.data);
this.emit('packet', packet);
// Socket is live - any packet counts
this.emit('heartbeat');
switch (packet.type) {
case 'open':
this.onHandshake(parsejson(packet.data));
break;
case 'pong':
this.setPing();
break;
case 'error':
var err = new Error('server error');
err.code = packet.data;
this.emit('error', err);
break;
case 'message':
this.emit('data', packet.data);
this.emit('message', packet.data);
break;
}
} else {
debug('packet received with socket readyState "%s"', this.readyState);
}
};
/**
* Called upon handshake completion.
*
* @param {Object} handshake obj
* @api private
*/
Socket.prototype.onHandshake = function (data) {
this.emit('handshake', data);
this.id = data.sid;
this.transport.query.sid = data.sid;
this.upgrades = this.filterUpgrades(data.upgrades);
this.pingInterval = data.pingInterval;
this.pingTimeout = data.pingTimeout;
this.onOpen();
// In case open handler closes socket
if ('closed' == this.readyState) return;
this.setPing();
// Prolong liveness of socket on heartbeat
this.removeListener('heartbeat', this.onHeartbeat);
this.on('heartbeat', this.onHeartbeat);
};
/**
* Resets ping timeout.
*
* @api private
*/
Socket.prototype.onHeartbeat = function (timeout) {
clearTimeout(this.pingTimeoutTimer);
var self = this;
self.pingTimeoutTimer = setTimeout(function () {
if ('closed' == self.readyState) return;
self.onClose('ping timeout');
}, timeout || (self.pingInterval + self.pingTimeout));
};
/**
* Pings server every `this.pingInterval` and expects response
* within `this.pingTimeout` or closes connection.
*
* @api private
*/
Socket.prototype.setPing = function () {
var self = this;
clearTimeout(self.pingIntervalTimer);
self.pingIntervalTimer = setTimeout(function () {
debug('writing ping packet - expecting pong within %sms', self.pingTimeout);
self.ping();
self.onHeartbeat(self.pingTimeout);
}, self.pingInterval);
};
/**
* Sends a ping packet.
*
* @api public
*/
Socket.prototype.ping = function () {
this.sendPacket('ping');
};
/**
* Called on `drain` event
*
* @api private
*/
Socket.prototype.onDrain = function() {
for (var i = 0; i < this.prevBufferLen; i++) {
if (this.callbackBuffer[i]) {
this.callbackBuffer[i]();
}
}
this.writeBuffer.splice(0, this.prevBufferLen);
this.callbackBuffer.splice(0, this.prevBufferLen);
// setting prevBufferLen = 0 is very important
// for example, when upgrading, upgrade packet is sent over,
// and a nonzero prevBufferLen could cause problems on `drain`
this.prevBufferLen = 0;
if (this.writeBuffer.length == 0) {
this.emit('drain');
} else {
this.flush();
}
};
/**
* Flush write buffers.
*
* @api private
*/
Socket.prototype.flush = function () {
if ('closed' != this.readyState && this.transport.writable &&
!this.upgrading && this.writeBuffer.length) {
debug('flushing %d packets in socket', this.writeBuffer.length);
this.transport.send(this.writeBuffer);
// keep track of current length of writeBuffer
// splice writeBuffer and callbackBuffer on `drain`
this.prevBufferLen = this.writeBuffer.length;
this.emit('flush');
}
};
/**
* Sends a message.
*
* @param {String} message.
* @param {Function} callback function.
* @return {Socket} for chaining.
* @api public
*/
Socket.prototype.write =
Socket.prototype.send = function (msg, fn) {
this.sendPacket('message', msg, fn);
return this;
};
/**
* Sends a packet.
*
* @param {String} packet type.
* @param {String} data.
* @param {Function} callback function.
* @api private
*/
Socket.prototype.sendPacket = function (type, data, fn) {
if ('closing' == this.readyState || 'closed' == this.readyState) {
return;
}
var packet = { type: type, data: data };
this.emit('packetCreate', packet);
this.writeBuffer.push(packet);
this.callbackBuffer.push(fn);
this.flush();
};
/**
* Closes the connection.
*
* @api private
*/
Socket.prototype.close = function () {
if ('opening' == this.readyState || 'open' == this.readyState) {
this.readyState = 'closing';
var self = this;
function close() {
self.onClose('forced close');
debug('socket closing - telling transport to close');
self.transport.close();
}
function cleanupAndClose() {
self.removeListener('upgrade', cleanupAndClose);
self.removeListener('upgradeError', cleanupAndClose);
close();
}
function waitForUpgrade() {
// wait for upgrade to finish since we can't send packets while pausing a transport
self.once('upgrade', cleanupAndClose);
self.once('upgradeError', cleanupAndClose);
}
if (this.writeBuffer.length) {
this.once('drain', function() {
if (this.upgrading) {
waitForUpgrade();
} else {
close();
}
});
} else if (this.upgrading) {
waitForUpgrade();
} else {
close();
}
}
return this;
};
/**
* Called upon transport error
*
* @api private
*/
Socket.prototype.onError = function (err) {
debug('socket error %j', err);
Socket.priorWebsocketSuccess = false;
this.emit('error', err);
this.onClose('transport error', err);
};
/**
* Called upon transport close.
*
* @api private
*/
Socket.prototype.onClose = function (reason, desc) {
if ('opening' == this.readyState || 'open' == this.readyState || 'closing' == this.readyState) {
debug('socket close with reason: "%s"', reason);
var self = this;
// clear timers
clearTimeout(this.pingIntervalTimer);
clearTimeout(this.pingTimeoutTimer);
// clean buffers in next tick, so developers can still
// grab the buffers on `close` event
setTimeout(function() {
self.writeBuffer = [];
self.callbackBuffer = [];
self.prevBufferLen = 0;
}, 0);
// stop event from firing again for transport
this.transport.removeAllListeners('close');
// ensure transport won't stay open
this.transport.close();
// ignore further transport communication
this.transport.removeAllListeners();
// set ready state
this.readyState = 'closed';
// clear session id
this.id = null;
// emit close event
this.emit('close', reason, desc);
}
};
/**
* Filters upgrades, returning only those matching client transports.
*
* @param {Array} server upgrades
* @api private
*
*/
Socket.prototype.filterUpgrades = function (upgrades) {
var filteredUpgrades = [];
for (var i = 0, j = upgrades.length; i<j; i++) {
if (~index(this.transports, upgrades[i])) filteredUpgrades.push(upgrades[i]);
}
return filteredUpgrades;
};
}).call(this,typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{"./transport":4,"./transports":5,"component-emitter":11,"debug":13,"engine.io-parser":16,"indexof":27,"parsejson":28,"parseqs":29,"parseuri":30}],4:[function(_dereq_,module,exports){
/**
* Module dependencies.
*/
var parser = _dereq_('engine.io-parser');
var Emitter = _dereq_('component-emitter');
/**
* Module exports.
*/
module.exports = Transport;
/**
* Transport abstract constructor.
*
* @param {Object} options.
* @api private
*/
function Transport (opts) {
this.path = opts.path;
this.hostname = opts.hostname;
this.port = opts.port;
this.secure = opts.secure;
this.query = opts.query;
this.timestampParam = opts.timestampParam;
this.timestampRequests = opts.timestampRequests;
this.readyState = '';
this.agent = opts.agent || false;
this.socket = opts.socket;
this.enablesXDR = opts.enablesXDR;
// SSL options for Node.js client
this.pfx = opts.pfx;
this.key = opts.key;
this.passphrase = opts.passphrase;
this.cert = opts.cert;
this.ca = opts.ca;
this.ciphers = opts.ciphers;
this.rejectUnauthorized = opts.rejectUnauthorized;
}
/**
* Mix in `Emitter`.
*/
Emitter(Transport.prototype);
/**
* A counter used to prevent collisions in the timestamps used
* for cache busting.
*/
Transport.timestamps = 0;
/**
* Emits an error.
*
* @param {String} str
* @return {Transport} for chaining
* @api public
*/
Transport.prototype.onError = function (msg, desc) {
var err = new Error(msg);
err.type = 'TransportError';
err.description = desc;
this.emit('error', err);
return this;
};
/**
* Opens the transport.
*
* @api public
*/
Transport.prototype.open = function () {
if ('closed' == this.readyState || '' == this.readyState) {
this.readyState = 'opening';
this.doOpen();
}
return this;
};
/**
* Closes the transport.
*
* @api private
*/
Transport.prototype.close = function () {
if ('opening' == this.readyState || 'open' == this.readyState) {
this.doClose();
this.onClose();
}
return this;
};
/**
* Sends multiple packets.
*
* @param {Array} packets
* @api private
*/
Transport.prototype.send = function(packets){
if ('open' == this.readyState) {
this.write(packets);
} else {
throw new Error('Transport not open');
}
};
/**
* Called upon open
*
* @api private
*/
Transport.prototype.onOpen = function () {
this.readyState = 'open';
this.writable = true;
this.emit('open');
};
/**
* Called with data.
*
* @param {String} data
* @api private
*/
Transport.prototype.onData = function(data){
var packet = parser.decodePacket(data, this.socket.binaryType);
this.onPacket(packet);
};
/**
* Called with a decoded packet.
*/
Transport.prototype.onPacket = function (packet) {
this.emit('packet', packet);
};
/**
* Called upon close.
*
* @api private
*/
Transport.prototype.onClose = function () {
this.readyState = 'closed';
this.emit('close');
};
},{"component-emitter":11,"engine.io-parser":16}],5:[function(_dereq_,module,exports){
(function (global){
/**
* Module dependencies
*/
var XMLHttpRequest = _dereq_('xmlhttprequest');
var XHR = _dereq_('./polling-xhr');
var JSONP = _dereq_('./polling-jsonp');
var websocket = _dereq_('./websocket');
/**
* Export transports.
*/
exports.polling = polling;
exports.websocket = websocket;
/**
* Polling transport polymorphic constructor.
* Decides on xhr vs jsonp based on feature detection.
*
* @api private
*/
function polling(opts){
var xhr;
var xd = false;
var xs = false;
var jsonp = false !== opts.jsonp;
if (global.location) {
var isSSL = 'https:' == location.protocol;
var port = location.port;
// some user agents have empty `location.port`
if (!port) {
port = isSSL ? 443 : 80;
}
xd = opts.hostname != location.hostname || port != opts.port;
xs = opts.secure != isSSL;
}
opts.xdomain = xd;
opts.xscheme = xs;
xhr = new XMLHttpRequest(opts);
if ('open' in xhr && !opts.forceJSONP) {
return new XHR(opts);
} else {
if (!jsonp) throw new Error('JSONP disabled');
return new JSONP(opts);
}
}
}).call(this,typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{"./polling-jsonp":6,"./polling-xhr":7,"./websocket":9,"xmlhttprequest":10}],6:[function(_dereq_,module,exports){
(function (global){
/**
* Module requirements.
*/
var Polling = _dereq_('./polling');
var inherit = _dereq_('component-inherit');
/**
* Module exports.
*/
module.exports = JSONPPolling;
/**
* Cached regular expressions.
*/
var rNewline = /\n/g;
var rEscapedNewline = /\\n/g;
/**
* Global JSONP callbacks.
*/
var callbacks;
/**
* Callbacks count.
*/
var index = 0;
/**
* Noop.
*/
function empty () { }
/**
* JSONP Polling constructor.
*
* @param {Object} opts.
* @api public
*/
function JSONPPolling (opts) {
Polling.call(this, opts);
this.query = this.query || {};
// define global callbacks array if not present
// we do this here (lazily) to avoid unneeded global pollution
if (!callbacks) {
// we need to consider multiple engines in the same page
if (!global.___eio) global.___eio = [];
callbacks = global.___eio;
}
// callback identifier
this.index = callbacks.length;
// add callback to jsonp global
var self = this;
callbacks.push(function (msg) {
self.onData(msg);
});
// append to query string
this.query.j = this.index;
// prevent spurious errors from being emitted when the window is unloaded
if (global.document && global.addEventListener) {
global.addEventListener('beforeunload', function () {
if (self.script) self.script.onerror = empty;
}, false);
}
}
/**
* Inherits from Polling.
*/
inherit(JSONPPolling, Polling);
/*
* JSONP only supports binary as base64 encoded strings
*/
JSONPPolling.prototype.supportsBinary = false;
/**
* Closes the socket.
*
* @api private
*/
JSONPPolling.prototype.doClose = function () {
if (this.script) {
this.script.parentNode.removeChild(this.script);
this.script = null;
}
if (this.form) {
this.form.parentNode.removeChild(this.form);
this.form = null;
this.iframe = null;
}
Polling.prototype.doClose.call(this);
};
/**
* Starts a poll cycle.
*
* @api private
*/
JSONPPolling.prototype.doPoll = function () {
var self = this;
var script = document.createElement('script');
if (this.script) {
this.script.parentNode.removeChild(this.script);
this.script = null;
}
script.async = true;
script.src = this.uri();
script.onerror = function(e){
self.onError('jsonp poll error',e);
};
var insertAt = document.getElementsByTagName('script')[0];
insertAt.parentNode.insertBefore(script, insertAt);
this.script = script;
var isUAgecko = 'undefined' != typeof navigator && /gecko/i.test(navigator.userAgent);
if (isUAgecko) {
setTimeout(function () {
var iframe = document.createElement('iframe');
document.body.appendChild(iframe);
document.body.removeChild(iframe);
}, 100);
}
};
/**
* Writes with a hidden iframe.
*
* @param {String} data to send
* @param {Function} called upon flush.
* @api private
*/
JSONPPolling.prototype.doWrite = function (data, fn) {
var self = this;
if (!this.form) {
var form = document.createElement('form');
var area = document.createElement('textarea');
var id = this.iframeId = 'eio_iframe_' + this.index;
var iframe;
form.className = 'socketio';
form.style.position = 'absolute';
form.style.top = '-1000px';
form.style.left = '-1000px';
form.target = id;
form.method = 'POST';
form.setAttribute('accept-charset', 'utf-8');
area.name = 'd';
form.appendChild(area);
document.body.appendChild(form);
this.form = form;
this.area = area;
}
this.form.action = this.uri();
function complete () {
initIframe();
fn();
}
function initIframe () {
if (self.iframe) {
try {
self.form.removeChild(self.iframe);
} catch (e) {
self.onError('jsonp polling iframe removal error', e);
}
}
try {
// ie6 dynamic iframes with target="" support (thanks Chris Lambacher)
var html = '<iframe src="javascript:0" name="'+ self.iframeId +'">';
iframe = document.createElement(html);
} catch (e) {
iframe = document.createElement('iframe');
iframe.name = self.iframeId;
iframe.src = 'javascript:0';
}
iframe.id = self.iframeId;
self.form.appendChild(iframe);
self.iframe = iframe;
}
initIframe();
// escape \n to prevent it from being converted into \r\n by some UAs
// double escaping is required for escaped new lines because unescaping of new lines can be done safely on server-side
data = data.replace(rEscapedNewline, '\\\n');
this.area.value = data.replace(rNewline, '\\n');
try {
this.form.submit();
} catch(e) {}
if (this.iframe.attachEvent) {
this.iframe.onreadystatechange = function(){
if (self.iframe.readyState == 'complete') {
complete();
}
};
} else {
this.iframe.onload = complete;
}
};
}).call(this,typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{"./polling":8,"component-inherit":12}],7:[function(_dereq_,module,exports){
(function (global){
/**
* Module requirements.
*/
var XMLHttpRequest = _dereq_('xmlhttprequest');
var Polling = _dereq_('./polling');
var Emitter = _dereq_('component-emitter');
var inherit = _dereq_('component-inherit');
var debug = _dereq_('debug')('engine.io-client:polling-xhr');
/**
* Module exports.
*/
module.exports = XHR;
module.exports.Request = Request;
/**
* Empty function
*/
function empty(){}
/**
* XHR Polling constructor.
*
* @param {Object} opts
* @api public
*/
function XHR(opts){
Polling.call(this, opts);
if (global.location) {
var isSSL = 'https:' == location.protocol;
var port = location.port;
// some user agents have empty `location.port`
if (!port) {
port = isSSL ? 443 : 80;
}
this.xd = opts.hostname != global.location.hostname ||
port != opts.port;
this.xs = opts.secure != isSSL;
}
}
/**
* Inherits from Polling.
*/
inherit(XHR, Polling);
/**
* XHR supports binary
*/
XHR.prototype.supportsBinary = true;
/**
* Creates a request.
*
* @param {String} method
* @api private
*/
XHR.prototype.request = function(opts){
opts = opts || {};
opts.uri = this.uri();
opts.xd = this.xd;
opts.xs = this.xs;
opts.agent = this.agent || false;
opts.supportsBinary = this.supportsBinary;
opts.enablesXDR = this.enablesXDR;
// SSL options for Node.js client
opts.pfx = this.pfx;
opts.key = this.key;
opts.passphrase = this.passphrase;
opts.cert = this.cert;
opts.ca = this.ca;
opts.ciphers = this.ciphers;
opts.rejectUnauthorized = this.rejectUnauthorized;
return new Request(opts);
};
/**
* Sends data.
*
* @param {String} data to send.
* @param {Function} called upon flush.
* @api private
*/
XHR.prototype.doWrite = function(data, fn){
var isBinary = typeof data !== 'string' && data !== undefined;
var req = this.request({ method: 'POST', data: data, isBinary: isBinary });
var self = this;
req.on('success', fn);
req.on('error', function(err){
self.onError('xhr post error', err);
});
this.sendXhr = req;
};
/**
* Starts a poll cycle.
*
* @api private
*/
XHR.prototype.doPoll = function(){
debug('xhr poll');
var req = this.request();
var self = this;
req.on('data', function(data){
self.onData(data);
});
req.on('error', function(err){
self.onError('xhr poll error', err);
});
this.pollXhr = req;
};
/**
* Request constructor
*
* @param {Object} options
* @api public
*/
function Request(opts){
this.method = opts.method || 'GET';
this.uri = opts.uri;
this.xd = !!opts.xd;
this.xs = !!opts.xs;
this.async = false !== opts.async;
this.data = undefined != opts.data ? opts.data : null;
this.agent = opts.agent;
this.isBinary = opts.isBinary;
this.supportsBinary = opts.supportsBinary;
this.enablesXDR = opts.enablesXDR;
// SSL options for Node.js client
this.pfx = opts.pfx;
this.key = opts.key;
this.passphrase = opts.passphrase;
this.cert = opts.cert;
this.ca = opts.ca;
this.ciphers = opts.ciphers;
this.rejectUnauthorized = opts.rejectUnauthorized;
this.create();
}
/**
* Mix in `Emitter`.
*/
Emitter(Request.prototype);
/**
* Creates the XHR object and sends the request.
*
* @api private
*/
Request.prototype.create = function(){
var opts = { agent: this.agent, xdomain: this.xd, xscheme: this.xs, enablesXDR: this.enablesXDR };
// SSL options for Node.js client
opts.pfx = this.pfx;
opts.key = this.key;
opts.passphrase = this.passphrase;
opts.cert = this.cert;
opts.ca = this.ca;
opts.ciphers = this.ciphers;
opts.rejectUnauthorized = this.rejectUnauthorized;
var xhr = this.xhr = new XMLHttpRequest(opts);
var self = this;
try {
debug('xhr open %s: %s', this.method, this.uri);
xhr.open(this.method, this.uri, this.async);
if (this.supportsBinary) {
// This has to be done after open because Firefox is stupid
// http://stackoverflow.com/questions/13216903/get-binary-data-with-xmlhttprequest-in-a-firefox-extension
xhr.responseType = 'arraybuffer';
}
if ('POST' == this.method) {
try {
if (this.isBinary) {
xhr.setRequestHeader('Content-type', 'application/octet-stream');
} else {
xhr.setRequestHeader('Content-type', 'text/plain;charset=UTF-8');
}
} catch (e) {}
}
// ie6 check
if ('withCredentials' in xhr) {
xhr.withCredentials = true;
}
if (this.hasXDR()) {
xhr.onload = function(){
self.onLoad();
};
xhr.onerror = function(){
self.onError(xhr.responseText);
};
} else {
xhr.onreadystatechange = function(){
if (4 != xhr.readyState) return;
if (200 == xhr.status || 1223 == xhr.status) {
self.onLoad();
} else {
// make sure the `error` event handler that's user-set
// does not throw in the same tick and gets caught here
setTimeout(function(){
self.onError(xhr.status);
}, 0);
}
};
}
debug('xhr data %s', this.data);
xhr.send(this.data);
} catch (e) {
// Need to defer since .create() is called directly fhrom the constructor
// and thus the 'error' event can only be only bound *after* this exception
// occurs. Therefore, also, we cannot throw here at all.
setTimeout(function() {
self.onError(e);
}, 0);
return;
}
if (global.document) {
this.index = Request.requestsCount++;
Request.requests[this.index] = this;
}
};
/**
* Called upon successful response.
*
* @api private
*/
Request.prototype.onSuccess = function(){
this.emit('success');
this.cleanup();
};
/**
* Called if we have data.
*
* @api private
*/
Request.prototype.onData = function(data){
this.emit('data', data);
this.onSuccess();
};
/**
* Called upon error.
*
* @api private
*/
Request.prototype.onError = function(err){
this.emit('error', err);
this.cleanup(true);
};
/**
* Cleans up house.
*
* @api private
*/
Request.prototype.cleanup = function(fromError){
if ('undefined' == typeof this.xhr || null === this.xhr) {
return;
}
// xmlhttprequest
if (this.hasXDR()) {
this.xhr.onload = this.xhr.onerror = empty;
} else {
this.xhr.onreadystatechange = empty;
}
if (fromError) {
try {
this.xhr.abort();
} catch(e) {}
}
if (global.document) {
delete Request.requests[this.index];
}
this.xhr = null;
};
/**
* Called upon load.
*
* @api private
*/
Request.prototype.onLoad = function(){
var data;
try {
var contentType;
try {
contentType = this.xhr.getResponseHeader('Content-Type').split(';')[0];
} catch (e) {}
if (contentType === 'application/octet-stream') {
data = this.xhr.response;
} else {
if (!this.supportsBinary) {
data = this.xhr.responseText;
} else {
data = 'ok';
}
}
} catch (e) {
this.onError(e);
}
if (null != data) {
this.onData(data);
}
};
/**
* Check if it has XDomainRequest.
*
* @api private
*/
Request.prototype.hasXDR = function(){
return 'undefined' !== typeof global.XDomainRequest && !this.xs && this.enablesXDR;
};
/**
* Aborts the request.
*
* @api public
*/
Request.prototype.abort = function(){
this.cleanup();
};
/**
* Aborts pending requests when unloading the window. This is needed to prevent
* memory leaks (e.g. when using IE) and to ensure that no spurious error is
* emitted.
*/
if (global.document) {
Request.requestsCount = 0;
Request.requests = {};
if (global.attachEvent) {
global.attachEvent('onunload', unloadHandler);
} else if (global.addEventListener) {
global.addEventListener('beforeunload', unloadHandler, false);
}
}
function unloadHandler() {
for (var i in Request.requests) {
if (Request.requests.hasOwnProperty(i)) {
Request.requests[i].abort();
}
}
}
}).call(this,typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{"./polling":8,"component-emitter":11,"component-inherit":12,"debug":13,"xmlhttprequest":10}],8:[function(_dereq_,module,exports){
/**
* Module dependencies.
*/
var Transport = _dereq_('../transport');
var parseqs = _dereq_('parseqs');
var parser = _dereq_('engine.io-parser');
var inherit = _dereq_('component-inherit');
var debug = _dereq_('debug')('engine.io-client:polling');
/**
* Module exports.
*/
module.exports = Polling;
/**
* Is XHR2 supported?
*/
var hasXHR2 = (function() {
var XMLHttpRequest = _dereq_('xmlhttprequest');
var xhr = new XMLHttpRequest({ xdomain: false });
return null != xhr.responseType;
})();
/**
* Polling interface.
*
* @param {Object} opts
* @api private
*/
function Polling(opts){
var forceBase64 = (opts && opts.forceBase64);
if (!hasXHR2 || forceBase64) {
this.supportsBinary = false;
}
Transport.call(this, opts);
}
/**
* Inherits from Transport.
*/
inherit(Polling, Transport);
/**
* Transport name.
*/
Polling.prototype.name = 'polling';
/**
* Opens the socket (triggers polling). We write a PING message to determine
* when the transport is open.
*
* @api private
*/
Polling.prototype.doOpen = function(){
this.poll();
};
/**
* Pauses polling.
*
* @param {Function} callback upon buffers are flushed and transport is paused
* @api private
*/
Polling.prototype.pause = function(onPause){
var pending = 0;
var self = this;
this.readyState = 'pausing';
function pause(){
debug('paused');
self.readyState = 'paused';
onPause();
}
if (this.polling || !this.writable) {
var total = 0;
if (this.polling) {
debug('we are currently polling - waiting to pause');
total++;
this.once('pollComplete', function(){
debug('pre-pause polling complete');
--total || pause();
});
}
if (!this.writable) {
debug('we are currently writing - waiting to pause');
total++;
this.once('drain', function(){
debug('pre-pause writing complete');
--total || pause();
});
}
} else {
pause();
}
};
/**
* Starts polling cycle.
*
* @api public
*/
Polling.prototype.poll = function(){
debug('polling');
this.polling = true;
this.doPoll();
this.emit('poll');
};
/**
* Overloads onData to detect payloads.
*
* @api private
*/
Polling.prototype.onData = function(data){
var self = this;
debug('polling got data %s', data);
var callback = function(packet, index, total) {
// if its the first message we consider the transport open
if ('opening' == self.readyState) {
self.onOpen();
}
// if its a close packet, we close the ongoing requests
if ('close' == packet.type) {
self.onClose();
return false;
}
// otherwise bypass onData and handle the message
self.onPacket(packet);
};
// decode payload
parser.decodePayload(data, this.socket.binaryType, callback);
// if an event did not trigger closing
if ('closed' != this.readyState) {
// if we got data we're not polling
this.polling = false;
this.emit('pollComplete');
if ('open' == this.readyState) {
this.poll();
} else {
debug('ignoring poll - transport state "%s"', this.readyState);
}
}
};
/**
* For polling, send a close packet.
*
* @api private
*/
Polling.prototype.doClose = function(){
var self = this;
function close(){
debug('writing close packet');
self.write([{ type: 'close' }]);
}
if ('open' == this.readyState) {
debug('transport open - closing');
close();
} else {
// in case we're trying to close while
// handshaking is in progress (GH-164)
debug('transport not open - deferring close');
this.once('open', close);
}
};
/**
* Writes a packets payload.
*
* @param {Array} data packets
* @param {Function} drain callback
* @api private
*/
Polling.prototype.write = function(packets){
var self = this;
this.writable = false;
var callbackfn = function() {
self.writable = true;
self.emit('drain');
};
var self = this;
parser.encodePayload(packets, this.supportsBinary, function(data) {
self.doWrite(data, callbackfn);
});
};
/**
* Generates uri for connection.
*
* @api private
*/
Polling.prototype.uri = function(){
var query = this.query || {};
var schema = this.secure ? 'https' : 'http';
var port = '';
// cache busting is forced
if (false !== this.timestampRequests) {
query[this.timestampParam] = +new Date + '-' + Transport.timestamps++;
}
if (!this.supportsBinary && !query.sid) {
query.b64 = 1;
}
query = parseqs.encode(query);
// avoid port if default for schema
if (this.port && (('https' == schema && this.port != 443) ||
('http' == schema && this.port != 80))) {
port = ':' + this.port;
}
// prepend ? to query
if (query.length) {
query = '?' + query;
}
return schema + '://' + this.hostname + port + this.path + query;
};
},{"../transport":4,"component-inherit":12,"debug":13,"engine.io-parser":16,"parseqs":29,"xmlhttprequest":10}],9:[function(_dereq_,module,exports){
/**
* Module dependencies.
*/
var Transport = _dereq_('../transport');
var parser = _dereq_('engine.io-parser');
var parseqs = _dereq_('parseqs');
var inherit = _dereq_('component-inherit');
var debug = _dereq_('debug')('engine.io-client:websocket');
/**
* `ws` exposes a WebSocket-compatible interface in
* Node, or the `WebSocket` or `MozWebSocket` globals
* in the browser.
*/
var WebSocket = _dereq_('ws');
/**
* Module exports.
*/
module.exports = WS;
/**
* WebSocket transport constructor.
*
* @api {Object} connection options
* @api public
*/
function WS(opts){
var forceBase64 = (opts && opts.forceBase64);
if (forceBase64) {
this.supportsBinary = false;
}
Transport.call(this, opts);
}
/**
* Inherits from Transport.
*/
inherit(WS, Transport);
/**
* Transport name.
*
* @api public
*/
WS.prototype.name = 'websocket';
/*
* WebSockets support binary
*/
WS.prototype.supportsBinary = true;
/**
* Opens socket.
*
* @api private
*/
WS.prototype.doOpen = function(){
if (!this.check()) {
// let probe timeout
return;
}
var self = this;
var uri = this.uri();
var protocols = void(0);
var opts = { agent: this.agent };
// SSL options for Node.js client
opts.pfx = this.pfx;
opts.key = this.key;
opts.passphrase = this.passphrase;
opts.cert = this.cert;
opts.ca = this.ca;
opts.ciphers = this.ciphers;
opts.rejectUnauthorized = this.rejectUnauthorized;
this.ws = new WebSocket(uri, protocols, opts);
if (this.ws.binaryType === undefined) {
this.supportsBinary = false;
}
this.ws.binaryType = 'arraybuffer';
this.addEventListeners();
};
/**
* Adds event listeners to the socket
*
* @api private
*/
WS.prototype.addEventListeners = function(){
var self = this;
this.ws.onopen = function(){
self.onOpen();
};
this.ws.onclose = function(){
self.onClose();
};
this.ws.onmessage = function(ev){
self.onData(ev.data);
};
this.ws.onerror = function(e){
self.onError('websocket error', e);
};
};
/**
* Override `onData` to use a timer on iOS.
* See: https://gist.github.com/mloughran/2052006
*
* @api private
*/
if ('undefined' != typeof navigator
&& /iPad|iPhone|iPod/i.test(navigator.userAgent)) {
WS.prototype.onData = function(data){
var self = this;
setTimeout(function(){
Transport.prototype.onData.call(self, data);
}, 0);
};
}
/**
* Writes data to socket.
*
* @param {Array} array of packets.
* @api private
*/
WS.prototype.write = function(packets){
var self = this;
this.writable = false;
// encodePacket efficient as it uses WS framing
// no need for encodePayload
for (var i = 0, l = packets.length; i < l; i++) {
parser.encodePacket(packets[i], this.supportsBinary, function(data) {
//Sometimes the websocket has already been closed but the browser didn't
//have a chance of informing us about it yet, in that case send will
//throw an error
try {
self.ws.send(data);
} catch (e){
debug('websocket closed before onclose event');
}
});
}
function ondrain() {
self.writable = true;
self.emit('drain');
}
// fake drain
// defer to next tick to allow Socket to clear writeBuffer
setTimeout(ondrain, 0);
};
/**
* Called upon close
*
* @api private
*/
WS.prototype.onClose = function(){
Transport.prototype.onClose.call(this);
};
/**
* Closes socket.
*
* @api private
*/
WS.prototype.doClose = function(){
if (typeof this.ws !== 'undefined') {
this.ws.close();
}
};
/**
* Generates uri for connection.
*
* @api private
*/
WS.prototype.uri = function(){
var query = this.query || {};
var schema = this.secure ? 'wss' : 'ws';
var port = '';
// avoid port if default for schema
if (this.port && (('wss' == schema && this.port != 443)
|| ('ws' == schema && this.port != 80))) {
port = ':' + this.port;
}
// append timestamp to URI
if (this.timestampRequests) {
query[this.timestampParam] = +new Date;
}
// communicate binary support capabilities
if (!this.supportsBinary) {
query.b64 = 1;
}
query = parseqs.encode(query);
// prepend ? to query
if (query.length) {
query = '?' + query;
}
return schema + '://' + this.hostname + port + this.path + query;
};
/**
* Feature detection for WebSocket.
*
* @return {Boolean} whether this transport is available.
* @api public
*/
WS.prototype.check = function(){
return !!WebSocket && !('__initialize' in WebSocket && this.name === WS.prototype.name);
};
},{"../transport":4,"component-inherit":12,"debug":13,"engine.io-parser":16,"parseqs":29,"ws":31}],10:[function(_dereq_,module,exports){
// browser shim for xmlhttprequest module
var hasCORS = _dereq_('has-cors');
module.exports = function(opts) {
var xdomain = opts.xdomain;
// scheme must be same when usign XDomainRequest
// http://blogs.msdn.com/b/ieinternals/archive/2010/05/13/xdomainrequest-restrictions-limitations-and-workarounds.aspx
var xscheme = opts.xscheme;
// XDomainRequest has a flow of not sending cookie, therefore it should be disabled as a default.
// https://github.com/Automattic/engine.io-client/pull/217
var enablesXDR = opts.enablesXDR;
// XMLHttpRequest can be disabled on IE
try {
if ('undefined' != typeof XMLHttpRequest && (!xdomain || hasCORS)) {
return new XMLHttpRequest();
}
} catch (e) { }
// Use XDomainRequest for IE8 if enablesXDR is true
// because loading bar keeps flashing when using jsonp-polling
// https://github.com/yujiosaka/socke.io-ie8-loading-example
try {
if ('undefined' != typeof XDomainRequest && !xscheme && enablesXDR) {
return new XDomainRequest();
}
} catch (e) { }
if (!xdomain) {
try {
return new window[(['Active'].concat('Object').join('X'))]('Microsoft.XMLHTTP');
} catch(e) { }
}
}
},{"has-cors":25}],11:[function(_dereq_,module,exports){
/**
* Expose `Emitter`.
*/
module.exports = Emitter;
/**
* Initialize a new `Emitter`.
*
* @api public
*/
function Emitter(obj) {
if (obj) return mixin(obj);
};
/**
* Mixin the emitter properties.
*
* @param {Object} obj
* @return {Object}
* @api private
*/
function mixin(obj) {
for (var key in Emitter.prototype) {
obj[key] = Emitter.prototype[key];
}
return obj;
}
/**
* Listen on the given `event` with `fn`.
*
* @param {String} event
* @param {Function} fn
* @return {Emitter}
* @api public
*/
Emitter.prototype.on =
Emitter.prototype.addEventListener = function(event, fn){
this._callbacks = this._callbacks || {};
(this._callbacks[event] = this._callbacks[event] || [])
.push(fn);
return this;
};
/**
* Adds an `event` listener that will be invoked a single
* time then automatically removed.
*
* @param {String} event
* @param {Function} fn
* @return {Emitter}
* @api public
*/
Emitter.prototype.once = function(event, fn){
var self = this;
this._callbacks = this._callbacks || {};
function on() {
self.off(event, on);
fn.apply(this, arguments);
}
on.fn = fn;
this.on(event, on);
return this;
};
/**
* Remove the given callback for `event` or all
* registered callbacks.
*
* @param {String} event
* @param {Function} fn
* @return {Emitter}
* @api public
*/
Emitter.prototype.off =
Emitter.prototype.removeListener =
Emitter.prototype.removeAllListeners =
Emitter.prototype.removeEventListener = function(event, fn){
this._callbacks = this._callbacks || {};
// all
if (0 == arguments.length) {
this._callbacks = {};
return this;
}
// specific event
var callbacks = this._callbacks[event];
if (!callbacks) return this;
// remove all handlers
if (1 == arguments.length) {
delete this._callbacks[event];
return this;
}
// remove specific handler
var cb;
for (var i = 0; i < callbacks.length; i++) {
cb = callbacks[i];
if (cb === fn || cb.fn === fn) {
callbacks.splice(i, 1);
break;
}
}
return this;
};
/**
* Emit `event` with the given args.
*
* @param {String} event
* @param {Mixed} ...
* @return {Emitter}
*/
Emitter.prototype.emit = function(event){
this._callbacks = this._callbacks || {};
var args = [].slice.call(arguments, 1)
, callbacks = this._callbacks[event];
if (callbacks) {
callbacks = callbacks.slice(0);
for (var i = 0, len = callbacks.length; i < len; ++i) {
callbacks[i].apply(this, args);
}
}
return this;
};
/**
* Return array of callbacks for `event`.
*
* @param {String} event
* @return {Array}
* @api public
*/
Emitter.prototype.listeners = function(event){
this._callbacks = this._callbacks || {};
return this._callbacks[event] || [];
};
/**
* Check if this emitter has `event` handlers.
*
* @param {String} event
* @return {Boolean}
* @api public
*/
Emitter.prototype.hasListeners = function(event){
return !! this.listeners(event).length;
};
},{}],12:[function(_dereq_,module,exports){
module.exports = function(a, b){
var fn = function(){};
fn.prototype = b.prototype;
a.prototype = new fn;
a.prototype.constructor = a;
};
},{}],13:[function(_dereq_,module,exports){
/**
* This is the web browser implementation of `debug()`.
*
* Expose `debug()` as the module.
*/
exports = module.exports = _dereq_('./debug');
exports.log = log;
exports.formatArgs = formatArgs;
exports.save = save;
exports.load = load;
exports.useColors = useColors;
/**
* Colors.
*/
exports.colors = [
'lightseagreen',
'forestgreen',
'goldenrod',
'dodgerblue',
'darkorchid',
'crimson'
];
/**
* Currently only WebKit-based Web Inspectors, Firefox >= v31,
* and the Firebug extension (any Firefox version) are known
* to support "%c" CSS customizations.
*
* TODO: add a `localStorage` variable to explicitly enable/disable colors
*/
function useColors() {
// is webkit? http://stackoverflow.com/a/16459606/376773
return ('WebkitAppearance' in document.documentElement.style) ||
// is firebug? http://stackoverflow.com/a/398120/376773
(window.console && (console.firebug || (console.exception && console.table))) ||
// is firefox >= v31?
// https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages
(navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31);
}
/**
* Map %j to `JSON.stringify()`, since no Web Inspectors do that by default.
*/
exports.formatters.j = function(v) {
return JSON.stringify(v);
};
/**
* Colorize log arguments if enabled.
*
* @api public
*/
function formatArgs() {
var args = arguments;
var useColors = this.useColors;
args[0] = (useColors ? '%c' : '')
+ this.namespace
+ (useColors ? ' %c' : ' ')
+ args[0]
+ (useColors ? '%c ' : ' ')
+ '+' + exports.humanize(this.diff);
if (!useColors) return args;
var c = 'color: ' + this.color;
args = [args[0], c, 'color: inherit'].concat(Array.prototype.slice.call(args, 1));
// the final "%c" is somewhat tricky, because there could be other
// arguments passed either before or after the %c, so we need to
// figure out the correct index to insert the CSS into
var index = 0;
var lastC = 0;
args[0].replace(/%[a-z%]/g, function(match) {
if ('%%' === match) return;
index++;
if ('%c' === match) {
// we only are interested in the *last* %c
// (the user may have provided their own)
lastC = index;
}
});
args.splice(lastC, 0, c);
return args;
}
/**
* Invokes `console.log()` when available.
* No-op when `console.log` is not a "function".
*
* @api public
*/
function log() {
// This hackery is required for IE8,
// where the `console.log` function doesn't have 'apply'
return 'object' == typeof console
&& 'function' == typeof console.log
&& Function.prototype.apply.call(console.log, console, arguments);
}
/**
* Save `namespaces`.
*
* @param {String} namespaces
* @api private
*/
function save(namespaces) {
try {
if (null == namespaces) {
localStorage.removeItem('debug');
} else {
localStorage.debug = namespaces;
}
} catch(e) {}
}
/**
* Load `namespaces`.
*
* @return {String} returns the previously persisted debug modes
* @api private
*/
function load() {
var r;
try {
r = localStorage.debug;
} catch(e) {}
return r;
}
/**
* Enable namespaces listed in `localStorage.debug` initially.
*/
exports.enable(load());
},{"./debug":14}],14:[function(_dereq_,module,exports){
/**
* This is the common logic for both the Node.js and web browser
* implementations of `debug()`.
*
* Expose `debug()` as the module.
*/
exports = module.exports = debug;
exports.coerce = coerce;
exports.disable = disable;
exports.enable = enable;
exports.enabled = enabled;
exports.humanize = _dereq_('ms');
/**
* The currently active debug mode names, and names to skip.
*/
exports.names = [];
exports.skips = [];
/**
* Map of special "%n" handling functions, for the debug "format" argument.
*
* Valid key names are a single, lowercased letter, i.e. "n".
*/
exports.formatters = {};
/**
* Previously assigned color.
*/
var prevColor = 0;
/**
* Previous log timestamp.
*/
var prevTime;
/**
* Select a color.
*
* @return {Number}
* @api private
*/
function selectColor() {
return exports.colors[prevColor++ % exports.colors.length];
}
/**
* Create a debugger with the given `namespace`.
*
* @param {String} namespace
* @return {Function}
* @api public
*/
function debug(namespace) {
// define the `disabled` version
function disabled() {
}
disabled.enabled = false;
// define the `enabled` version
function enabled() {
var self = enabled;
// set `diff` timestamp
var curr = +new Date();
var ms = curr - (prevTime || curr);
self.diff = ms;
self.prev = prevTime;
self.curr = curr;
prevTime = curr;
// add the `color` if not set
if (null == self.useColors) self.useColors = exports.useColors();
if (null == self.color && self.useColors) self.color = selectColor();
var args = Array.prototype.slice.call(arguments);
args[0] = exports.coerce(args[0]);
if ('string' !== typeof args[0]) {
// anything else let's inspect with %o
args = ['%o'].concat(args);
}
// apply any `formatters` transformations
var index = 0;
args[0] = args[0].replace(/%([a-z%])/g, function(match, format) {
// if we encounter an escaped % then don't increase the array index
if (match === '%%') return match;
index++;
var formatter = exports.formatters[format];
if ('function' === typeof formatter) {
var val = args[index];
match = formatter.call(self, val);
// now we need to remove `args[index]` since it's inlined in the `format`
args.splice(index, 1);
index--;
}
return match;
});
if ('function' === typeof exports.formatArgs) {
args = exports.formatArgs.apply(self, args);
}
var logFn = enabled.log || exports.log || console.log.bind(console);
logFn.apply(self, args);
}
enabled.enabled = true;
var fn = exports.enabled(namespace) ? enabled : disabled;
fn.namespace = namespace;
return fn;
}
/**
* Enables a debug mode by namespaces. This can include modes
* separated by a colon and wildcards.
*
* @param {String} namespaces
* @api public
*/
function enable(namespaces) {
exports.save(namespaces);
var split = (namespaces || '').split(/[\s,]+/);
var len = split.length;
for (var i = 0; i < len; i++) {
if (!split[i]) continue; // ignore empty strings
namespaces = split[i].replace(/\*/g, '.*?');
if (namespaces[0] === '-') {
exports.skips.push(new RegExp('^' + namespaces.substr(1) + '$'));
} else {
exports.names.push(new RegExp('^' + namespaces + '$'));
}
}
}
/**
* Disable debug output.
*
* @api public
*/
function disable() {
exports.enable('');
}
/**
* Returns true if the given mode name is enabled, false otherwise.
*
* @param {String} name
* @return {Boolean}
* @api public
*/
function enabled(name) {
var i, len;
for (i = 0, len = exports.skips.length; i < len; i++) {
if (exports.skips[i].test(name)) {
return false;
}
}
for (i = 0, len = exports.names.length; i < len; i++) {
if (exports.names[i].test(name)) {
return true;
}
}
return false;
}
/**
* Coerce `val`.
*
* @param {Mixed} val
* @return {Mixed}
* @api private
*/
function coerce(val) {
if (val instanceof Error) return val.stack || val.message;
return val;
}
},{"ms":15}],15:[function(_dereq_,module,exports){
/**
* Helpers.
*/
var s = 1000;
var m = s * 60;
var h = m * 60;
var d = h * 24;
var y = d * 365.25;
/**
* Parse or format the given `val`.
*
* Options:
*
* - `long` verbose formatting [false]
*
* @param {String|Number} val
* @param {Object} options
* @return {String|Number}
* @api public
*/
module.exports = function(val, options){
options = options || {};
if ('string' == typeof val) return parse(val);
return options.long
? long(val)
: short(val);
};
/**
* Parse the given `str` and return milliseconds.
*
* @param {String} str
* @return {Number}
* @api private
*/
function parse(str) {
var match = /^((?:\d+)?\.?\d+) *(ms|seconds?|s|minutes?|m|hours?|h|days?|d|years?|y)?$/i.exec(str);
if (!match) return;
var n = parseFloat(match[1]);
var type = (match[2] || 'ms').toLowerCase();
switch (type) {
case 'years':
case 'year':
case 'y':
return n * y;
case 'days':
case 'day':
case 'd':
return n * d;
case 'hours':
case 'hour':
case 'h':
return n * h;
case 'minutes':
case 'minute':
case 'm':
return n * m;
case 'seconds':
case 'second':
case 's':
return n * s;
case 'ms':
return n;
}
}
/**
* Short format for `ms`.
*
* @param {Number} ms
* @return {String}
* @api private
*/
function short(ms) {
if (ms >= d) return Math.round(ms / d) + 'd';
if (ms >= h) return Math.round(ms / h) + 'h';
if (ms >= m) return Math.round(ms / m) + 'm';
if (ms >= s) return Math.round(ms / s) + 's';
return ms + 'ms';
}
/**
* Long format for `ms`.
*
* @param {Number} ms
* @return {String}
* @api private
*/
function long(ms) {
return plural(ms, d, 'day')
|| plural(ms, h, 'hour')
|| plural(ms, m, 'minute')
|| plural(ms, s, 'second')
|| ms + ' ms';
}
/**
* Pluralization helper.
*/
function plural(ms, n, name) {
if (ms < n) return;
if (ms < n * 1.5) return Math.floor(ms / n) + ' ' + name;
return Math.ceil(ms / n) + ' ' + name + 's';
}
},{}],16:[function(_dereq_,module,exports){
(function (global){
/**
* Module dependencies.
*/
var keys = _dereq_('./keys');
var hasBinary = _dereq_('has-binary');
var sliceBuffer = _dereq_('arraybuffer.slice');
var base64encoder = _dereq_('base64-arraybuffer');
var after = _dereq_('after');
var utf8 = _dereq_('utf8');
/**
* Check if we are running an android browser. That requires us to use
* ArrayBuffer with polling transports...
*
* http://ghinda.net/jpeg-blob-ajax-android/
*/
var isAndroid = navigator.userAgent.match(/Android/i);
/**
* Check if we are running in PhantomJS.
* Uploading a Blob with PhantomJS does not work correctly, as reported here:
* https://github.com/ariya/phantomjs/issues/11395
* @type boolean
*/
var isPhantomJS = /PhantomJS/i.test(navigator.userAgent);
/**
* When true, avoids using Blobs to encode payloads.
* @type boolean
*/
var dontSendBlobs = isAndroid || isPhantomJS;
/**
* Current protocol version.
*/
exports.protocol = 3;
/**
* Packet types.
*/
var packets = exports.packets = {
open: 0 // non-ws
, close: 1 // non-ws
, ping: 2
, pong: 3
, message: 4
, upgrade: 5
, noop: 6
};
var packetslist = keys(packets);
/**
* Premade error packet.
*/
var err = { type: 'error', data: 'parser error' };
/**
* Create a blob api even for blob builder when vendor prefixes exist
*/
var Blob = _dereq_('blob');
/**
* Encodes a packet.
*
* <packet type id> [ <data> ]
*
* Example:
*
* 5hello world
* 3
* 4
*
* Binary is encoded in an identical principle
*
* @api private
*/
exports.encodePacket = function (packet, supportsBinary, utf8encode, callback) {
if ('function' == typeof supportsBinary) {
callback = supportsBinary;
supportsBinary = false;
}
if ('function' == typeof utf8encode) {
callback = utf8encode;
utf8encode = null;
}
var data = (packet.data === undefined)
? undefined
: packet.data.buffer || packet.data;
if (global.ArrayBuffer && data instanceof ArrayBuffer) {
return encodeArrayBuffer(packet, supportsBinary, callback);
} else if (Blob && data instanceof global.Blob) {
return encodeBlob(packet, supportsBinary, callback);
}
// might be an object with { base64: true, data: dataAsBase64String }
if (data && data.base64) {
return encodeBase64Object(packet, callback);
}
// Sending data as a utf-8 string
var encoded = packets[packet.type];
// data fragment is optional
if (undefined !== packet.data) {
encoded += utf8encode ? utf8.encode(String(packet.data)) : String(packet.data);
}
return callback('' + encoded);
};
function encodeBase64Object(packet, callback) {
// packet data is an object { base64: true, data: dataAsBase64String }
var message = 'b' + exports.packets[packet.type] + packet.data.data;
return callback(message);
}
/**
* Encode packet helpers for binary types
*/
function encodeArrayBuffer(packet, supportsBinary, callback) {
if (!supportsBinary) {
return exports.encodeBase64Packet(packet, callback);
}
var data = packet.data;
var contentArray = new Uint8Array(data);
var resultBuffer = new Uint8Array(1 + data.byteLength);
resultBuffer[0] = packets[packet.type];
for (var i = 0; i < contentArray.length; i++) {
resultBuffer[i+1] = contentArray[i];
}
return callback(resultBuffer.buffer);
}
function encodeBlobAsArrayBuffer(packet, supportsBinary, callback) {
if (!supportsBinary) {
return exports.encodeBase64Packet(packet, callback);
}
var fr = new FileReader();
fr.onload = function() {
packet.data = fr.result;
exports.encodePacket(packet, supportsBinary, true, callback);
};
return fr.readAsArrayBuffer(packet.data);
}
function encodeBlob(packet, supportsBinary, callback) {
if (!supportsBinary) {
return exports.encodeBase64Packet(packet, callback);
}
if (dontSendBlobs) {
return encodeBlobAsArrayBuffer(packet, supportsBinary, callback);
}
var length = new Uint8Array(1);
length[0] = packets[packet.type];
var blob = new Blob([length.buffer, packet.data]);
return callback(blob);
}
/**
* Encodes a packet with binary data in a base64 string
*
* @param {Object} packet, has `type` and `data`
* @return {String} base64 encoded message
*/
exports.encodeBase64Packet = function(packet, callback) {
var message = 'b' + exports.packets[packet.type];
if (Blob && packet.data instanceof Blob) {
var fr = new FileReader();
fr.onload = function() {
var b64 = fr.result.split(',')[1];
callback(message + b64);
};
return fr.readAsDataURL(packet.data);
}
var b64data;
try {
b64data = String.fromCharCode.apply(null, new Uint8Array(packet.data));
} catch (e) {
// iPhone Safari doesn't let you apply with typed arrays
var typed = new Uint8Array(packet.data);
var basic = new Array(typed.length);
for (var i = 0; i < typed.length; i++) {
basic[i] = typed[i];
}
b64data = String.fromCharCode.apply(null, basic);
}
message += global.btoa(b64data);
return callback(message);
};
/**
* Decodes a packet. Changes format to Blob if requested.
*
* @return {Object} with `type` and `data` (if any)
* @api private
*/
exports.decodePacket = function (data, binaryType, utf8decode) {
// String data
if (typeof data == 'string' || data === undefined) {
if (data.charAt(0) == 'b') {
return exports.decodeBase64Packet(data.substr(1), binaryType);
}
if (utf8decode) {
try {
data = utf8.decode(data);
} catch (e) {
return err;
}
}
var type = data.charAt(0);
if (Number(type) != type || !packetslist[type]) {
return err;
}
if (data.length > 1) {
return { type: packetslist[type], data: data.substring(1) };
} else {
return { type: packetslist[type] };
}
}
var asArray = new Uint8Array(data);
var type = asArray[0];
var rest = sliceBuffer(data, 1);
if (Blob && binaryType === 'blob') {
rest = new Blob([rest]);
}
return { type: packetslist[type], data: rest };
};
/**
* Decodes a packet encoded in a base64 string
*
* @param {String} base64 encoded message
* @return {Object} with `type` and `data` (if any)
*/
exports.decodeBase64Packet = function(msg, binaryType) {
var type = packetslist[msg.charAt(0)];
if (!global.ArrayBuffer) {
return { type: type, data: { base64: true, data: msg.substr(1) } };
}
var data = base64encoder.decode(msg.substr(1));
if (binaryType === 'blob' && Blob) {
data = new Blob([data]);
}
return { type: type, data: data };
};
/**
* Encodes multiple messages (payload).
*
* <length>:data
*
* Example:
*
* 11:hello world2:hi
*
* If any contents are binary, they will be encoded as base64 strings. Base64
* encoded strings are marked with a b before the length specifier
*
* @param {Array} packets
* @api private
*/
exports.encodePayload = function (packets, supportsBinary, callback) {
if (typeof supportsBinary == 'function') {
callback = supportsBinary;
supportsBinary = null;
}
var isBinary = hasBinary(packets);
if (supportsBinary && isBinary) {
if (Blob && !dontSendBlobs) {
return exports.encodePayloadAsBlob(packets, callback);
}
return exports.encodePayloadAsArrayBuffer(packets, callback);
}
if (!packets.length) {
return callback('0:');
}
function setLengthHeader(message) {
return message.length + ':' + message;
}
function encodeOne(packet, doneCallback) {
exports.encodePacket(packet, !isBinary ? false : supportsBinary, true, function(message) {
doneCallback(null, setLengthHeader(message));
});
}
map(packets, encodeOne, function(err, results) {
return callback(results.join(''));
});
};
/**
* Async array map using after
*/
function map(ary, each, done) {
var result = new Array(ary.length);
var next = after(ary.length, done);
var eachWithIndex = function(i, el, cb) {
each(el, function(error, msg) {
result[i] = msg;
cb(error, result);
});
};
for (var i = 0; i < ary.length; i++) {
eachWithIndex(i, ary[i], next);
}
}
/*
* Decodes data when a payload is maybe expected. Possible binary contents are
* decoded from their base64 representation
*
* @param {String} data, callback method
* @api public
*/
exports.decodePayload = function (data, binaryType, callback) {
if (typeof data != 'string') {
return exports.decodePayloadAsBinary(data, binaryType, callback);
}
if (typeof binaryType === 'function') {
callback = binaryType;
binaryType = null;
}
var packet;
if (data == '') {
// parser error - ignoring payload
return callback(err, 0, 1);
}
var length = ''
, n, msg;
for (var i = 0, l = data.length; i < l; i++) {
var chr = data.charAt(i);
if (':' != chr) {
length += chr;
} else {
if ('' == length || (length != (n = Number(length)))) {
// parser error - ignoring payload
return callback(err, 0, 1);
}
msg = data.substr(i + 1, n);
if (length != msg.length) {
// parser error - ignoring payload
return callback(err, 0, 1);
}
if (msg.length) {
packet = exports.decodePacket(msg, binaryType, true);
if (err.type == packet.type && err.data == packet.data) {
// parser error in individual packet - ignoring payload
return callback(err, 0, 1);
}
var ret = callback(packet, i + n, l);
if (false === ret) return;
}
// advance cursor
i += n;
length = '';
}
}
if (length != '') {
// parser error - ignoring payload
return callback(err, 0, 1);
}
};
/**
* Encodes multiple messages (payload) as binary.
*
* <1 = binary, 0 = string><number from 0-9><number from 0-9>[...]<number
* 255><data>
*
* Example:
* 1 3 255 1 2 3, if the binary contents are interpreted as 8 bit integers
*
* @param {Array} packets
* @return {ArrayBuffer} encoded payload
* @api private
*/
exports.encodePayloadAsArrayBuffer = function(packets, callback) {
if (!packets.length) {
return callback(new ArrayBuffer(0));
}
function encodeOne(packet, doneCallback) {
exports.encodePacket(packet, true, true, function(data) {
return doneCallback(null, data);
});
}
map(packets, encodeOne, function(err, encodedPackets) {
var totalLength = encodedPackets.reduce(function(acc, p) {
var len;
if (typeof p === 'string'){
len = p.length;
} else {
len = p.byteLength;
}
return acc + len.toString().length + len + 2; // string/binary identifier + separator = 2
}, 0);
var resultArray = new Uint8Array(totalLength);
var bufferIndex = 0;
encodedPackets.forEach(function(p) {
var isString = typeof p === 'string';
var ab = p;
if (isString) {
var view = new Uint8Array(p.length);
for (var i = 0; i < p.length; i++) {
view[i] = p.charCodeAt(i);
}
ab = view.buffer;
}
if (isString) { // not true binary
resultArray[bufferIndex++] = 0;
} else { // true binary
resultArray[bufferIndex++] = 1;
}
var lenStr = ab.byteLength.toString();
for (var i = 0; i < lenStr.length; i++) {
resultArray[bufferIndex++] = parseInt(lenStr[i]);
}
resultArray[bufferIndex++] = 255;
var view = new Uint8Array(ab);
for (var i = 0; i < view.length; i++) {
resultArray[bufferIndex++] = view[i];
}
});
return callback(resultArray.buffer);
});
};
/**
* Encode as Blob
*/
exports.encodePayloadAsBlob = function(packets, callback) {
function encodeOne(packet, doneCallback) {
exports.encodePacket(packet, true, true, function(encoded) {
var binaryIdentifier = new Uint8Array(1);
binaryIdentifier[0] = 1;
if (typeof encoded === 'string') {
var view = new Uint8Array(encoded.length);
for (var i = 0; i < encoded.length; i++) {
view[i] = encoded.charCodeAt(i);
}
encoded = view.buffer;
binaryIdentifier[0] = 0;
}
var len = (encoded instanceof ArrayBuffer)
? encoded.byteLength
: encoded.size;
var lenStr = len.toString();
var lengthAry = new Uint8Array(lenStr.length + 1);
for (var i = 0; i < lenStr.length; i++) {
lengthAry[i] = parseInt(lenStr[i]);
}
lengthAry[lenStr.length] = 255;
if (Blob) {
var blob = new Blob([binaryIdentifier.buffer, lengthAry.buffer, encoded]);
doneCallback(null, blob);
}
});
}
map(packets, encodeOne, function(err, results) {
return callback(new Blob(results));
});
};
/*
* Decodes data when a payload is maybe expected. Strings are decoded by
* interpreting each byte as a key code for entries marked to start with 0. See
* description of encodePayloadAsBinary
*
* @param {ArrayBuffer} data, callback method
* @api public
*/
exports.decodePayloadAsBinary = function (data, binaryType, callback) {
if (typeof binaryType === 'function') {
callback = binaryType;
binaryType = null;
}
var bufferTail = data;
var buffers = [];
var numberTooLong = false;
while (bufferTail.byteLength > 0) {
var tailArray = new Uint8Array(bufferTail);
var isString = tailArray[0] === 0;
var msgLength = '';
for (var i = 1; ; i++) {
if (tailArray[i] == 255) break;
if (msgLength.length > 310) {
numberTooLong = true;
break;
}
msgLength += tailArray[i];
}
if(numberTooLong) return callback(err, 0, 1);
bufferTail = sliceBuffer(bufferTail, 2 + msgLength.length);
msgLength = parseInt(msgLength);
var msg = sliceBuffer(bufferTail, 0, msgLength);
if (isString) {
try {
msg = String.fromCharCode.apply(null, new Uint8Array(msg));
} catch (e) {
// iPhone Safari doesn't let you apply to typed arrays
var typed = new Uint8Array(msg);
msg = '';
for (var i = 0; i < typed.length; i++) {
msg += String.fromCharCode(typed[i]);
}
}
}
buffers.push(msg);
bufferTail = sliceBuffer(bufferTail, msgLength);
}
var total = buffers.length;
buffers.forEach(function(buffer, i) {
callback(exports.decodePacket(buffer, binaryType, true), i, total);
});
};
}).call(this,typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{"./keys":17,"after":18,"arraybuffer.slice":19,"base64-arraybuffer":20,"blob":21,"has-binary":22,"utf8":24}],17:[function(_dereq_,module,exports){
/**
* Gets the keys for an object.
*
* @return {Array} keys
* @api private
*/
module.exports = Object.keys || function keys (obj){
var arr = [];
var has = Object.prototype.hasOwnProperty;
for (var i in obj) {
if (has.call(obj, i)) {
arr.push(i);
}
}
return arr;
};
},{}],18:[function(_dereq_,module,exports){
module.exports = after
function after(count, callback, err_cb) {
var bail = false
err_cb = err_cb || noop
proxy.count = count
return (count === 0) ? callback() : proxy
function proxy(err, result) {
if (proxy.count <= 0) {
throw new Error('after called too many times')
}
--proxy.count
// after first error, rest are passed to err_cb
if (err) {
bail = true
callback(err)
// future error callbacks will go to error handler
callback = err_cb
} else if (proxy.count === 0 && !bail) {
callback(null, result)
}
}
}
function noop() {}
},{}],19:[function(_dereq_,module,exports){
/**
* An abstraction for slicing an arraybuffer even when
* ArrayBuffer.prototype.slice is not supported
*
* @api public
*/
module.exports = function(arraybuffer, start, end) {
var bytes = arraybuffer.byteLength;
start = start || 0;
end = end || bytes;
if (arraybuffer.slice) { return arraybuffer.slice(start, end); }
if (start < 0) { start += bytes; }
if (end < 0) { end += bytes; }
if (end > bytes) { end = bytes; }
if (start >= bytes || start >= end || bytes === 0) {
return new ArrayBuffer(0);
}
var abv = new Uint8Array(arraybuffer);
var result = new Uint8Array(end - start);
for (var i = start, ii = 0; i < end; i++, ii++) {
result[ii] = abv[i];
}
return result.buffer;
};
},{}],20:[function(_dereq_,module,exports){
/*
* base64-arraybuffer
* https://github.com/niklasvh/base64-arraybuffer
*
* Copyright (c) 2012 Niklas von Hertzen
* Licensed under the MIT license.
*/
(function(chars){
"use strict";
exports.encode = function(arraybuffer) {
var bytes = new Uint8Array(arraybuffer),
i, len = bytes.length, base64 = "";
for (i = 0; i < len; i+=3) {
base64 += chars[bytes[i] >> 2];
base64 += chars[((bytes[i] & 3) << 4) | (bytes[i + 1] >> 4)];
base64 += chars[((bytes[i + 1] & 15) << 2) | (bytes[i + 2] >> 6)];
base64 += chars[bytes[i + 2] & 63];
}
if ((len % 3) === 2) {
base64 = base64.substring(0, base64.length - 1) + "=";
} else if (len % 3 === 1) {
base64 = base64.substring(0, base64.length - 2) + "==";
}
return base64;
};
exports.decode = function(base64) {
var bufferLength = base64.length * 0.75,
len = base64.length, i, p = 0,
encoded1, encoded2, encoded3, encoded4;
if (base64[base64.length - 1] === "=") {
bufferLength--;
if (base64[base64.length - 2] === "=") {
bufferLength--;
}
}
var arraybuffer = new ArrayBuffer(bufferLength),
bytes = new Uint8Array(arraybuffer);
for (i = 0; i < len; i+=4) {
encoded1 = chars.indexOf(base64[i]);
encoded2 = chars.indexOf(base64[i+1]);
encoded3 = chars.indexOf(base64[i+2]);
encoded4 = chars.indexOf(base64[i+3]);
bytes[p++] = (encoded1 << 2) | (encoded2 >> 4);
bytes[p++] = ((encoded2 & 15) << 4) | (encoded3 >> 2);
bytes[p++] = ((encoded3 & 3) << 6) | (encoded4 & 63);
}
return arraybuffer;
};
})("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/");
},{}],21:[function(_dereq_,module,exports){
(function (global){
/**
* Create a blob builder even when vendor prefixes exist
*/
var BlobBuilder = global.BlobBuilder
|| global.WebKitBlobBuilder
|| global.MSBlobBuilder
|| global.MozBlobBuilder;
/**
* Check if Blob constructor is supported
*/
var blobSupported = (function() {
try {
var b = new Blob(['hi']);
return b.size == 2;
} catch(e) {
return false;
}
})();
/**
* Check if BlobBuilder is supported
*/
var blobBuilderSupported = BlobBuilder
&& BlobBuilder.prototype.append
&& BlobBuilder.prototype.getBlob;
function BlobBuilderConstructor(ary, options) {
options = options || {};
var bb = new BlobBuilder();
for (var i = 0; i < ary.length; i++) {
bb.append(ary[i]);
}
return (options.type) ? bb.getBlob(options.type) : bb.getBlob();
};
module.exports = (function() {
if (blobSupported) {
return global.Blob;
} else if (blobBuilderSupported) {
return BlobBuilderConstructor;
} else {
return undefined;
}
})();
}).call(this,typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{}],22:[function(_dereq_,module,exports){
(function (global){
/*
* Module requirements.
*/
var isArray = _dereq_('isarray');
/**
* Module exports.
*/
module.exports = hasBinary;
/**
* Checks for binary data.
*
* Right now only Buffer and ArrayBuffer are supported..
*
* @param {Object} anything
* @api public
*/
function hasBinary(data) {
function _hasBinary(obj) {
if (!obj) return false;
if ( (global.Buffer && global.Buffer.isBuffer(obj)) ||
(global.ArrayBuffer && obj instanceof ArrayBuffer) ||
(global.Blob && obj instanceof Blob) ||
(global.File && obj instanceof File)
) {
return true;
}
if (isArray(obj)) {
for (var i = 0; i < obj.length; i++) {
if (_hasBinary(obj[i])) {
return true;
}
}
} else if (obj && 'object' == typeof obj) {
if (obj.toJSON) {
obj = obj.toJSON();
}
for (var key in obj) {
if (obj.hasOwnProperty(key) && _hasBinary(obj[key])) {
return true;
}
}
}
return false;
}
return _hasBinary(data);
}
}).call(this,typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{"isarray":23}],23:[function(_dereq_,module,exports){
module.exports = Array.isArray || function (arr) {
return Object.prototype.toString.call(arr) == '[object Array]';
};
},{}],24:[function(_dereq_,module,exports){
(function (global){
/*! http://mths.be/utf8js v2.0.0 by @mathias */
;(function(root) {
// Detect free variables `exports`
var freeExports = typeof exports == 'object' && exports;
// Detect free variable `module`
var freeModule = typeof module == 'object' && module &&
module.exports == freeExports && module;
// Detect free variable `global`, from Node.js or Browserified code,
// and use it as `root`
var freeGlobal = typeof global == 'object' && global;
if (freeGlobal.global === freeGlobal || freeGlobal.window === freeGlobal) {
root = freeGlobal;
}
/*--------------------------------------------------------------------------*/
var stringFromCharCode = String.fromCharCode;
// Taken from http://mths.be/punycode
function ucs2decode(string) {
var output = [];
var counter = 0;
var length = string.length;
var value;
var extra;
while (counter < length) {
value = string.charCodeAt(counter++);
if (value >= 0xD800 && value <= 0xDBFF && counter < length) {
// high surrogate, and there is a next character
extra = string.charCodeAt(counter++);
if ((extra & 0xFC00) == 0xDC00) { // low surrogate
output.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000);
} else {
// unmatched surrogate; only append this code unit, in case the next
// code unit is the high surrogate of a surrogate pair
output.push(value);
counter--;
}
} else {
output.push(value);
}
}
return output;
}
// Taken from http://mths.be/punycode
function ucs2encode(array) {
var length = array.length;
var index = -1;
var value;
var output = '';
while (++index < length) {
value = array[index];
if (value > 0xFFFF) {
value -= 0x10000;
output += stringFromCharCode(value >>> 10 & 0x3FF | 0xD800);
value = 0xDC00 | value & 0x3FF;
}
output += stringFromCharCode(value);
}
return output;
}
/*--------------------------------------------------------------------------*/
function createByte(codePoint, shift) {
return stringFromCharCode(((codePoint >> shift) & 0x3F) | 0x80);
}
function encodeCodePoint(codePoint) {
if ((codePoint & 0xFFFFFF80) == 0) { // 1-byte sequence
return stringFromCharCode(codePoint);
}
var symbol = '';
if ((codePoint & 0xFFFFF800) == 0) { // 2-byte sequence
symbol = stringFromCharCode(((codePoint >> 6) & 0x1F) | 0xC0);
}
else if ((codePoint & 0xFFFF0000) == 0) { // 3-byte sequence
symbol = stringFromCharCode(((codePoint >> 12) & 0x0F) | 0xE0);
symbol += createByte(codePoint, 6);
}
else if ((codePoint & 0xFFE00000) == 0) { // 4-byte sequence
symbol = stringFromCharCode(((codePoint >> 18) & 0x07) | 0xF0);
symbol += createByte(codePoint, 12);
symbol += createByte(codePoint, 6);
}
symbol += stringFromCharCode((codePoint & 0x3F) | 0x80);
return symbol;
}
function utf8encode(string) {
var codePoints = ucs2decode(string);
// console.log(JSON.stringify(codePoints.map(function(x) {
// return 'U+' + x.toString(16).toUpperCase();
// })));
var length = codePoints.length;
var index = -1;
var codePoint;
var byteString = '';
while (++index < length) {
codePoint = codePoints[index];
byteString += encodeCodePoint(codePoint);
}
return byteString;
}
/*--------------------------------------------------------------------------*/
function readContinuationByte() {
if (byteIndex >= byteCount) {
throw Error('Invalid byte index');
}
var continuationByte = byteArray[byteIndex] & 0xFF;
byteIndex++;
if ((continuationByte & 0xC0) == 0x80) {
return continuationByte & 0x3F;
}
// If we end up here, it’s not a continuation byte
throw Error('Invalid continuation byte');
}
function decodeSymbol() {
var byte1;
var byte2;
var byte3;
var byte4;
var codePoint;
if (byteIndex > byteCount) {
throw Error('Invalid byte index');
}
if (byteIndex == byteCount) {
return false;
}
// Read first byte
byte1 = byteArray[byteIndex] & 0xFF;
byteIndex++;
// 1-byte sequence (no continuation bytes)
if ((byte1 & 0x80) == 0) {
return byte1;
}
// 2-byte sequence
if ((byte1 & 0xE0) == 0xC0) {
var byte2 = readContinuationByte();
codePoint = ((byte1 & 0x1F) << 6) | byte2;
if (codePoint >= 0x80) {
return codePoint;
} else {
throw Error('Invalid continuation byte');
}
}
// 3-byte sequence (may include unpaired surrogates)
if ((byte1 & 0xF0) == 0xE0) {
byte2 = readContinuationByte();
byte3 = readContinuationByte();
codePoint = ((byte1 & 0x0F) << 12) | (byte2 << 6) | byte3;
if (codePoint >= 0x0800) {
return codePoint;
} else {
throw Error('Invalid continuation byte');
}
}
// 4-byte sequence
if ((byte1 & 0xF8) == 0xF0) {
byte2 = readContinuationByte();
byte3 = readContinuationByte();
byte4 = readContinuationByte();
codePoint = ((byte1 & 0x0F) << 0x12) | (byte2 << 0x0C) |
(byte3 << 0x06) | byte4;
if (codePoint >= 0x010000 && codePoint <= 0x10FFFF) {
return codePoint;
}
}
throw Error('Invalid UTF-8 detected');
}
var byteArray;
var byteCount;
var byteIndex;
function utf8decode(byteString) {
byteArray = ucs2decode(byteString);
byteCount = byteArray.length;
byteIndex = 0;
var codePoints = [];
var tmp;
while ((tmp = decodeSymbol()) !== false) {
codePoints.push(tmp);
}
return ucs2encode(codePoints);
}
/*--------------------------------------------------------------------------*/
var utf8 = {
'version': '2.0.0',
'encode': utf8encode,
'decode': utf8decode
};
if (freeExports && !freeExports.nodeType) {
if (freeModule) { // in Node.js or RingoJS v0.8.0+
freeModule.exports = utf8;
} else { // in Narwhal or RingoJS v0.7.0-
var object = {};
var hasOwnProperty = object.hasOwnProperty;
for (var key in utf8) {
hasOwnProperty.call(utf8, key) && (freeExports[key] = utf8[key]);
}
}
} else { // in Rhino or a web browser
root.utf8 = utf8;
}
}(this));
}).call(this,typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{}],25:[function(_dereq_,module,exports){
/**
* Module dependencies.
*/
var global = _dereq_('global');
/**
* Module exports.
*
* Logic borrowed from Modernizr:
*
* - https://github.com/Modernizr/Modernizr/blob/master/feature-detects/cors.js
*/
try {
module.exports = 'XMLHttpRequest' in global &&
'withCredentials' in new global.XMLHttpRequest();
} catch (err) {
// if XMLHttp support is disabled in IE then it will throw
// when trying to create
module.exports = false;
}
},{"global":26}],26:[function(_dereq_,module,exports){
/**
* Returns `this`. Execute this without a "context" (i.e. without it being
* attached to an object of the left-hand side), and `this` points to the
* "global" scope of the current JS execution.
*/
module.exports = (function () { return this; })();
},{}],27:[function(_dereq_,module,exports){
var indexOf = [].indexOf;
module.exports = function(arr, obj){
if (indexOf) return arr.indexOf(obj);
for (var i = 0; i < arr.length; ++i) {
if (arr[i] === obj) return i;
}
return -1;
};
},{}],28:[function(_dereq_,module,exports){
(function (global){
/**
* JSON parse.
*
* @see Based on jQuery#parseJSON (MIT) and JSON2
* @api private
*/
var rvalidchars = /^[\],:{}\s]*$/;
var rvalidescape = /\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g;
var rvalidtokens = /"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g;
var rvalidbraces = /(?:^|:|,)(?:\s*\[)+/g;
var rtrimLeft = /^\s+/;
var rtrimRight = /\s+$/;
module.exports = function parsejson(data) {
if ('string' != typeof data || !data) {
return null;
}
data = data.replace(rtrimLeft, '').replace(rtrimRight, '');
// Attempt to parse using the native JSON parser first
if (global.JSON && JSON.parse) {
return JSON.parse(data);
}
if (rvalidchars.test(data.replace(rvalidescape, '@')
.replace(rvalidtokens, ']')
.replace(rvalidbraces, ''))) {
return (new Function('return ' + data))();
}
};
}).call(this,typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{}],29:[function(_dereq_,module,exports){
/**
* Compiles a querystring
* Returns string representation of the object
*
* @param {Object}
* @api private
*/
exports.encode = function (obj) {
var str = '';
for (var i in obj) {
if (obj.hasOwnProperty(i)) {
if (str.length) str += '&';
str += encodeURIComponent(i) + '=' + encodeURIComponent(obj[i]);
}
}
return str;
};
/**
* Parses a simple querystring into an object
*
* @param {String} qs
* @api private
*/
exports.decode = function(qs){
var qry = {};
var pairs = qs.split('&');
for (var i = 0, l = pairs.length; i < l; i++) {
var pair = pairs[i].split('=');
qry[decodeURIComponent(pair[0])] = decodeURIComponent(pair[1]);
}
return qry;
};
},{}],30:[function(_dereq_,module,exports){
/**
* Parses an URI
*
* @author Steven Levithan <stevenlevithan.com> (MIT license)
* @api private
*/
var re = /^(?:(?![^:@]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/;
var parts = [
'source', 'protocol', 'authority', 'userInfo', 'user', 'password', 'host', 'port', 'relative', 'path', 'directory', 'file', 'query', 'anchor'
];
module.exports = function parseuri(str) {
var src = str,
b = str.indexOf('['),
e = str.indexOf(']');
if (b != -1 && e != -1) {
str = str.substring(0, b) + str.substring(b, e).replace(/:/g, ';') + str.substring(e, str.length);
}
var m = re.exec(str || ''),
uri = {},
i = 14;
while (i--) {
uri[parts[i]] = m[i] || '';
}
if (b != -1 && e != -1) {
uri.source = src;
uri.host = uri.host.substring(1, uri.host.length - 1).replace(/;/g, ':');
uri.authority = uri.authority.replace('[', '').replace(']', '').replace(/;/g, ':');
uri.ipv6uri = true;
}
return uri;
};
},{}],31:[function(_dereq_,module,exports){
/**
* Module dependencies.
*/
var global = (function() { return this; })();
/**
* WebSocket constructor.
*/
var WebSocket = global.WebSocket || global.MozWebSocket;
/**
* Module exports.
*/
module.exports = WebSocket ? ws : null;
/**
* WebSocket constructor.
*
* The third `opts` options object gets ignored in web browsers, since it's
* non-standard, and throws a TypeError if passed to the constructor.
* See: https://github.com/einaros/ws/issues/227
*
* @param {String} uri
* @param {Array} protocols (optional)
* @param {Object) opts (optional)
* @api public
*/
function ws(uri, protocols, opts) {
var instance;
if (protocols) {
instance = new WebSocket(uri, protocols);
} else {
instance = new WebSocket(uri);
}
return instance;
}
if (WebSocket) ws.prototype = WebSocket.prototype;
},{}]},{},[1])(1)
}); | [minor] Rebuild the Engine.IO client -- version 1.5.4
| transformers/engine.io/library.js | [minor] Rebuild the Engine.IO client -- version 1.5.4 | <ide><path>ransformers/engine.io/library.js
<del>!function(e){var f;'undefined'!=typeof window?f=window:'undefined'!=typeof self&&(f=self),f.eio=e()}(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(_dereq_,module,exports){
<del>
<del>module.exports = _dereq_('./lib/');
<del>
<del>},{"./lib/":2}],2:[function(_dereq_,module,exports){
<add>(function(f){var g;if(typeof window!=='undefined'){g=window}else if(typeof self!=='undefined'){g=self}g.eio=f()})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(_dereq_,module,exports){
<ide>
<ide> module.exports = _dereq_('./socket');
<ide>
<ide> */
<ide> module.exports.parser = _dereq_('engine.io-parser');
<ide>
<del>},{"./socket":3,"engine.io-parser":16}],3:[function(_dereq_,module,exports){
<add>},{"./socket":2,"engine.io-parser":15}],2:[function(_dereq_,module,exports){
<ide> (function (global){
<ide> /**
<ide> * Module dependencies.
<ide> };
<ide>
<ide> }).call(this,typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
<del>},{"./transport":4,"./transports":5,"component-emitter":11,"debug":13,"engine.io-parser":16,"indexof":27,"parsejson":28,"parseqs":29,"parseuri":30}],4:[function(_dereq_,module,exports){
<add>},{"./transport":3,"./transports":4,"component-emitter":10,"debug":12,"engine.io-parser":15,"indexof":26,"parsejson":27,"parseqs":28,"parseuri":29}],3:[function(_dereq_,module,exports){
<ide> /**
<ide> * Module dependencies.
<ide> */
<ide> this.emit('close');
<ide> };
<ide>
<del>},{"component-emitter":11,"engine.io-parser":16}],5:[function(_dereq_,module,exports){
<add>},{"component-emitter":10,"engine.io-parser":15}],4:[function(_dereq_,module,exports){
<ide> (function (global){
<ide> /**
<ide> * Module dependencies
<ide> }
<ide>
<ide> }).call(this,typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
<del>},{"./polling-jsonp":6,"./polling-xhr":7,"./websocket":9,"xmlhttprequest":10}],6:[function(_dereq_,module,exports){
<add>},{"./polling-jsonp":5,"./polling-xhr":6,"./websocket":8,"xmlhttprequest":9}],5:[function(_dereq_,module,exports){
<ide> (function (global){
<ide>
<ide> /**
<ide> };
<ide>
<ide> }).call(this,typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
<del>},{"./polling":8,"component-inherit":12}],7:[function(_dereq_,module,exports){
<add>},{"./polling":7,"component-inherit":11}],6:[function(_dereq_,module,exports){
<ide> (function (global){
<ide> /**
<ide> * Module requirements.
<ide> }
<ide>
<ide> }).call(this,typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
<del>},{"./polling":8,"component-emitter":11,"component-inherit":12,"debug":13,"xmlhttprequest":10}],8:[function(_dereq_,module,exports){
<add>},{"./polling":7,"component-emitter":10,"component-inherit":11,"debug":12,"xmlhttprequest":9}],7:[function(_dereq_,module,exports){
<ide> /**
<ide> * Module dependencies.
<ide> */
<ide> return schema + '://' + this.hostname + port + this.path + query;
<ide> };
<ide>
<del>},{"../transport":4,"component-inherit":12,"debug":13,"engine.io-parser":16,"parseqs":29,"xmlhttprequest":10}],9:[function(_dereq_,module,exports){
<add>},{"../transport":3,"component-inherit":11,"debug":12,"engine.io-parser":15,"parseqs":28,"xmlhttprequest":9}],8:[function(_dereq_,module,exports){
<ide> /**
<ide> * Module dependencies.
<ide> */
<ide> return !!WebSocket && !('__initialize' in WebSocket && this.name === WS.prototype.name);
<ide> };
<ide>
<del>},{"../transport":4,"component-inherit":12,"debug":13,"engine.io-parser":16,"parseqs":29,"ws":31}],10:[function(_dereq_,module,exports){
<add>},{"../transport":3,"component-inherit":11,"debug":12,"engine.io-parser":15,"parseqs":28,"ws":30}],9:[function(_dereq_,module,exports){
<ide> // browser shim for xmlhttprequest module
<ide> var hasCORS = _dereq_('has-cors');
<ide>
<ide> }
<ide> }
<ide>
<del>},{"has-cors":25}],11:[function(_dereq_,module,exports){
<add>},{"has-cors":24}],10:[function(_dereq_,module,exports){
<ide>
<ide> /**
<ide> * Expose `Emitter`.
<ide> return !! this.listeners(event).length;
<ide> };
<ide>
<del>},{}],12:[function(_dereq_,module,exports){
<add>},{}],11:[function(_dereq_,module,exports){
<ide>
<ide> module.exports = function(a, b){
<ide> var fn = function(){};
<ide> a.prototype = new fn;
<ide> a.prototype.constructor = a;
<ide> };
<del>},{}],13:[function(_dereq_,module,exports){
<add>},{}],12:[function(_dereq_,module,exports){
<ide>
<ide> /**
<ide> * This is the web browser implementation of `debug()`.
<ide>
<ide> exports.enable(load());
<ide>
<del>},{"./debug":14}],14:[function(_dereq_,module,exports){
<add>},{"./debug":13}],13:[function(_dereq_,module,exports){
<ide>
<ide> /**
<ide> * This is the common logic for both the Node.js and web browser
<ide> return val;
<ide> }
<ide>
<del>},{"ms":15}],15:[function(_dereq_,module,exports){
<add>},{"ms":14}],14:[function(_dereq_,module,exports){
<ide> /**
<ide> * Helpers.
<ide> */
<ide> return Math.ceil(ms / n) + ' ' + name + 's';
<ide> }
<ide>
<del>},{}],16:[function(_dereq_,module,exports){
<add>},{}],15:[function(_dereq_,module,exports){
<ide> (function (global){
<ide> /**
<ide> * Module dependencies.
<ide> };
<ide>
<ide> }).call(this,typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
<del>},{"./keys":17,"after":18,"arraybuffer.slice":19,"base64-arraybuffer":20,"blob":21,"has-binary":22,"utf8":24}],17:[function(_dereq_,module,exports){
<add>},{"./keys":16,"after":17,"arraybuffer.slice":18,"base64-arraybuffer":19,"blob":20,"has-binary":21,"utf8":23}],16:[function(_dereq_,module,exports){
<ide>
<ide> /**
<ide> * Gets the keys for an object.
<ide> return arr;
<ide> };
<ide>
<del>},{}],18:[function(_dereq_,module,exports){
<add>},{}],17:[function(_dereq_,module,exports){
<ide> module.exports = after
<ide>
<ide> function after(count, callback, err_cb) {
<ide>
<ide> function noop() {}
<ide>
<del>},{}],19:[function(_dereq_,module,exports){
<add>},{}],18:[function(_dereq_,module,exports){
<ide> /**
<ide> * An abstraction for slicing an arraybuffer even when
<ide> * ArrayBuffer.prototype.slice is not supported
<ide> return result.buffer;
<ide> };
<ide>
<del>},{}],20:[function(_dereq_,module,exports){
<add>},{}],19:[function(_dereq_,module,exports){
<ide> /*
<ide> * base64-arraybuffer
<ide> * https://github.com/niklasvh/base64-arraybuffer
<ide> };
<ide> })("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/");
<ide>
<del>},{}],21:[function(_dereq_,module,exports){
<add>},{}],20:[function(_dereq_,module,exports){
<ide> (function (global){
<ide> /**
<ide> * Create a blob builder even when vendor prefixes exist
<ide>
<ide> var blobSupported = (function() {
<ide> try {
<del> var b = new Blob(['hi']);
<del> return b.size == 2;
<add> var a = new Blob(['hi']);
<add> return a.size === 2;
<add> } catch(e) {
<add> return false;
<add> }
<add>})();
<add>
<add>/**
<add> * Check if Blob constructor supports ArrayBufferViews
<add> * Fails in Safari 6, so we need to map to ArrayBuffers there.
<add> */
<add>
<add>var blobSupportsArrayBufferView = blobSupported && (function() {
<add> try {
<add> var b = new Blob([new Uint8Array([1,2])]);
<add> return b.size === 2;
<ide> } catch(e) {
<ide> return false;
<ide> }
<ide> && BlobBuilder.prototype.append
<ide> && BlobBuilder.prototype.getBlob;
<ide>
<add>/**
<add> * Helper function that maps ArrayBufferViews to ArrayBuffers
<add> * Used by BlobBuilder constructor and old browsers that didn't
<add> * support it in the Blob constructor.
<add> */
<add>
<add>function mapArrayBufferViews(ary) {
<add> for (var i = 0; i < ary.length; i++) {
<add> var chunk = ary[i];
<add> if (chunk.buffer instanceof ArrayBuffer) {
<add> var buf = chunk.buffer;
<add>
<add> // if this is a subarray, make a copy so we only
<add> // include the subarray region from the underlying buffer
<add> if (chunk.byteLength !== buf.byteLength) {
<add> var copy = new Uint8Array(chunk.byteLength);
<add> copy.set(new Uint8Array(buf, chunk.byteOffset, chunk.byteLength));
<add> buf = copy.buffer;
<add> }
<add>
<add> ary[i] = buf;
<add> }
<add> }
<add>}
<add>
<ide> function BlobBuilderConstructor(ary, options) {
<ide> options = options || {};
<ide>
<ide> var bb = new BlobBuilder();
<add> mapArrayBufferViews(ary);
<add>
<ide> for (var i = 0; i < ary.length; i++) {
<ide> bb.append(ary[i]);
<ide> }
<add>
<ide> return (options.type) ? bb.getBlob(options.type) : bb.getBlob();
<add>};
<add>
<add>function BlobConstructor(ary, options) {
<add> mapArrayBufferViews(ary);
<add> return new Blob(ary, options || {});
<ide> };
<ide>
<ide> module.exports = (function() {
<ide> if (blobSupported) {
<del> return global.Blob;
<add> return blobSupportsArrayBufferView ? global.Blob : BlobConstructor;
<ide> } else if (blobBuilderSupported) {
<ide> return BlobBuilderConstructor;
<ide> } else {
<ide> })();
<ide>
<ide> }).call(this,typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
<del>},{}],22:[function(_dereq_,module,exports){
<add>},{}],21:[function(_dereq_,module,exports){
<ide> (function (global){
<ide>
<ide> /*
<ide> }
<ide>
<ide> for (var key in obj) {
<del> if (obj.hasOwnProperty(key) && _hasBinary(obj[key])) {
<add> if (Object.prototype.hasOwnProperty.call(obj, key) && _hasBinary(obj[key])) {
<ide> return true;
<ide> }
<ide> }
<ide> }
<ide>
<ide> }).call(this,typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
<del>},{"isarray":23}],23:[function(_dereq_,module,exports){
<add>},{"isarray":22}],22:[function(_dereq_,module,exports){
<ide> module.exports = Array.isArray || function (arr) {
<ide> return Object.prototype.toString.call(arr) == '[object Array]';
<ide> };
<ide>
<del>},{}],24:[function(_dereq_,module,exports){
<add>},{}],23:[function(_dereq_,module,exports){
<ide> (function (global){
<del>/*! http://mths.be/utf8js v2.0.0 by @mathias */
<add>/*! https://mths.be/utf8js v2.0.0 by @mathias */
<ide> ;(function(root) {
<ide>
<ide> // Detect free variables `exports`
<ide>
<ide> var stringFromCharCode = String.fromCharCode;
<ide>
<del> // Taken from http://mths.be/punycode
<add> // Taken from https://mths.be/punycode
<ide> function ucs2decode(string) {
<ide> var output = [];
<ide> var counter = 0;
<ide> return output;
<ide> }
<ide>
<del> // Taken from http://mths.be/punycode
<add> // Taken from https://mths.be/punycode
<ide> function ucs2encode(array) {
<ide> var length = array.length;
<ide> var index = -1;
<ide> return output;
<ide> }
<ide>
<add> function checkScalarValue(codePoint) {
<add> if (codePoint >= 0xD800 && codePoint <= 0xDFFF) {
<add> throw Error(
<add> 'Lone surrogate U+' + codePoint.toString(16).toUpperCase() +
<add> ' is not a scalar value'
<add> );
<add> }
<add> }
<ide> /*--------------------------------------------------------------------------*/
<ide>
<ide> function createByte(codePoint, shift) {
<ide> symbol = stringFromCharCode(((codePoint >> 6) & 0x1F) | 0xC0);
<ide> }
<ide> else if ((codePoint & 0xFFFF0000) == 0) { // 3-byte sequence
<add> checkScalarValue(codePoint);
<ide> symbol = stringFromCharCode(((codePoint >> 12) & 0x0F) | 0xE0);
<ide> symbol += createByte(codePoint, 6);
<ide> }
<ide>
<ide> function utf8encode(string) {
<ide> var codePoints = ucs2decode(string);
<del>
<del> // console.log(JSON.stringify(codePoints.map(function(x) {
<del> // return 'U+' + x.toString(16).toUpperCase();
<del> // })));
<del>
<ide> var length = codePoints.length;
<ide> var index = -1;
<ide> var codePoint;
<ide> byte3 = readContinuationByte();
<ide> codePoint = ((byte1 & 0x0F) << 12) | (byte2 << 6) | byte3;
<ide> if (codePoint >= 0x0800) {
<add> checkScalarValue(codePoint);
<ide> return codePoint;
<ide> } else {
<ide> throw Error('Invalid continuation byte');
<ide> }(this));
<ide>
<ide> }).call(this,typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
<del>},{}],25:[function(_dereq_,module,exports){
<add>},{}],24:[function(_dereq_,module,exports){
<ide>
<ide> /**
<ide> * Module dependencies.
<ide> module.exports = false;
<ide> }
<ide>
<del>},{"global":26}],26:[function(_dereq_,module,exports){
<add>},{"global":25}],25:[function(_dereq_,module,exports){
<ide>
<ide> /**
<ide> * Returns `this`. Execute this without a "context" (i.e. without it being
<ide>
<ide> module.exports = (function () { return this; })();
<ide>
<del>},{}],27:[function(_dereq_,module,exports){
<add>},{}],26:[function(_dereq_,module,exports){
<ide>
<ide> var indexOf = [].indexOf;
<ide>
<ide> }
<ide> return -1;
<ide> };
<del>},{}],28:[function(_dereq_,module,exports){
<add>},{}],27:[function(_dereq_,module,exports){
<ide> (function (global){
<ide> /**
<ide> * JSON parse.
<ide> }
<ide> };
<ide> }).call(this,typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
<del>},{}],29:[function(_dereq_,module,exports){
<add>},{}],28:[function(_dereq_,module,exports){
<ide> /**
<ide> * Compiles a querystring
<ide> * Returns string representation of the object
<ide> return qry;
<ide> };
<ide>
<del>},{}],30:[function(_dereq_,module,exports){
<add>},{}],29:[function(_dereq_,module,exports){
<ide> /**
<ide> * Parses an URI
<ide> *
<ide> return uri;
<ide> };
<ide>
<del>},{}],31:[function(_dereq_,module,exports){
<add>},{}],30:[function(_dereq_,module,exports){
<ide>
<ide> /**
<ide> * Module dependencies.
<ide>
<ide> if (WebSocket) ws.prototype = WebSocket.prototype;
<ide>
<del>},{}]},{},[1])(1)
<add>},{}],31:[function(_dereq_,module,exports){
<add>
<add>module.exports = _dereq_('./lib/');
<add>
<add>},{"./lib/":1}]},{},[31])(31)
<ide> }); |
|
Java | apache-2.0 | c4368994df71a212b7ec78c3879617fcfc638e7d | 0 | orientechnologies/orientdb,orientechnologies/orientdb,orientechnologies/orientdb,orientechnologies/orientdb | /*
*
* * Copyright 2010-2016 OrientDB LTD (http://orientdb.com)
* *
* * Licensed under the Apache License, Version 2.0 (the "License");
* * you may not use this file except in compliance with the License.
* * You may obtain a copy of the License at
* *
* * http://www.apache.org/licenses/LICENSE-2.0
* *
* * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS,
* * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* * limitations under the License.
* *
* * For more information: http://orientdb.com
*
*/
package com.orientechnologies.orient.core.index;
import com.orientechnologies.common.listener.OProgressListener;
import com.orientechnologies.common.types.OModifiableBoolean;
import com.orientechnologies.orient.core.db.ODatabaseDocumentInternal;
import com.orientechnologies.orient.core.db.record.OIdentifiable;
import com.orientechnologies.orient.core.exception.OInvalidIndexEngineIdException;
import com.orientechnologies.orient.core.record.impl.ODocument;
import com.orientechnologies.orient.core.serialization.serializer.OStringSerializerHelper;
import com.orientechnologies.orient.core.storage.impl.local.OAbstractPaginatedStorage;
import com.orientechnologies.orient.core.storage.ridbag.sbtree.OIndexRIDContainer;
import com.orientechnologies.orient.core.storage.ridbag.sbtree.OIndexRIDContainerSBTree;
import com.orientechnologies.orient.core.storage.ridbag.sbtree.OMixedIndexRIDContainer;
import com.orientechnologies.orient.core.tx.OTransaction;
import com.orientechnologies.orient.core.tx.OTransactionIndexChanges;
import com.orientechnologies.orient.core.tx.OTransactionIndexChanges.OPERATION;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.atomic.AtomicLong;
/**
* Fast index for full-text searches.
*
* @author Luca Garulli
*/
@Deprecated
public class OIndexFullText extends OIndexMultiValues {
private static final String CONFIG_STOP_WORDS = "stopWords";
private static final String CONFIG_SEPARATOR_CHARS = "separatorChars";
private static final String CONFIG_IGNORE_CHARS = "ignoreChars";
private static final String CONFIG_INDEX_RADIX = "indexRadix";
private static final String CONFIG_MIN_WORD_LEN = "minWordLength";
private static final boolean DEF_INDEX_RADIX = true;
private static final String DEF_SEPARATOR_CHARS = " \r\n\t:;,.|+*/\\=!?[]()";
private static final String DEF_IGNORE_CHARS = "'\"";
private static final String DEF_STOP_WORDS =
"the in a at as and or for his her "
+ "him this that what which while "
+ "up with be was were is";
private boolean indexRadix;
private String separatorChars;
private String ignoreChars;
private int minWordLength;
private Set<String> stopWords;
public OIndexFullText(
String name,
String typeId,
String algorithm,
int version,
OAbstractPaginatedStorage storage,
String valueContainerAlgorithm,
ODocument metadata,
int binaryFormatVersion) {
super(
name,
typeId,
algorithm,
version,
storage,
valueContainerAlgorithm,
metadata,
binaryFormatVersion);
acquireExclusiveLock();
try {
config();
configWithMetadata(metadata);
} finally {
releaseExclusiveLock();
}
}
/**
* Indexes a value and save the index. Splits the value in single words and index each one. Save
* of the index is responsibility of the caller.
*/
@Override
public OIndexFullText put(Object key, final OIdentifiable value) {
if (key == null) {
return this;
}
key = getCollatingValue(key);
final Set<String> words = splitIntoWords(key.toString());
ODatabaseDocumentInternal database = getDatabase();
database.begin();
OTransaction singleTx = database.getTransaction();
for (String word : words) {
singleTx.addIndexEntry(
this, super.getName(), OTransactionIndexChanges.OPERATION.PUT, word, value);
}
database.commit();
return this;
}
private void doPutV0(final OIdentifiable singleValue, final String word) {
Set<OIdentifiable> refs;
while (true) {
try {
//noinspection unchecked
refs = (Set<OIdentifiable>) storage.getIndexValue(indexId, word);
break;
} catch (OInvalidIndexEngineIdException ignore) {
doReloadIndexEngine();
}
}
final Set<OIdentifiable> refsc = refs;
// SAVE THE INDEX ENTRY
while (true) {
try {
storage.updateIndexEntry(
indexId,
word,
(oldValue, bonsayFileId) -> {
Set<OIdentifiable> result;
if (refsc == null) {
// WORD NOT EXISTS: CREATE THE KEYWORD CONTAINER THE FIRST TIME THE WORD IS FOUND
if (ODefaultIndexFactory.SBTREE_BONSAI_VALUE_CONTAINER.equals(
valueContainerAlgorithm)) {
if (binaryFormatVersion >= 13) {
result = new OMixedIndexRIDContainer(getName(), bonsayFileId);
} else {
result = new OIndexRIDContainer(getName(), true, bonsayFileId);
}
} else {
throw new IllegalStateException("MBRBTreeContainer is not supported any more");
}
} else {
result = refsc;
}
// ADD THE CURRENT DOCUMENT AS REF FOR THAT WORD
result.add(singleValue);
return OIndexUpdateAction.changed(result);
});
break;
} catch (OInvalidIndexEngineIdException ignore) {
doReloadIndexEngine();
}
}
}
/**
* Splits passed in key on several words and remove records with keys equals to any item of split
* result and values equals to passed in value.
*
* @param key Key to remove.
* @param rid Value to remove.
* @return <code>true</code> if at least one record is removed.
*/
@Override
public boolean remove(Object key, final OIdentifiable rid) {
if (key == null) {
return false;
}
key = getCollatingValue(key);
final Set<String> words = splitIntoWords(key.toString());
ODatabaseDocumentInternal database = getDatabase();
database.begin();
for (final String word : words) {
database.getTransaction().addIndexEntry(this, super.getName(), OPERATION.REMOVE, word, rid);
}
database.commit();
return true;
}
private void removeV0(OIdentifiable value, OModifiableBoolean removed, String word) {
Set<OIdentifiable> recs;
while (true) {
try {
//noinspection unchecked
recs = (Set<OIdentifiable>) storage.getIndexValue(indexId, word);
break;
} catch (OInvalidIndexEngineIdException ignore) {
doReloadIndexEngine();
}
}
if (recs != null && !recs.isEmpty()) {
while (true) {
try {
storage.updateIndexEntry(indexId, word, new EntityRemover(value, removed));
break;
} catch (OInvalidIndexEngineIdException ignore) {
doReloadIndexEngine();
}
}
}
}
@Override
public OIndexMultiValues create(
OIndexMetadata metadata, boolean rebuild, OProgressListener progressListener) {
if (metadata.getIndexDefinition().getFields().size() > 1) {
throw new OIndexException(type + " indexes cannot be used as composite ones.");
}
super.create(metadata, rebuild, progressListener);
return this;
}
@Override
public ODocument updateConfiguration() {
super.updateConfiguration();
return ((FullTextIndexConfiguration) configuration)
.updateFullTextIndexConfiguration(
separatorChars, ignoreChars, stopWords, minWordLength, indexRadix);
}
@Override
protected IndexConfiguration indexConfigurationInstance(ODocument document) {
return new FullTextIndexConfiguration(document);
}
public boolean canBeUsedInEqualityOperators() {
return false;
}
public boolean supportsOrderedIterations() {
return false;
}
private void configWithMetadata(ODocument metadata) {
if (metadata != null) {
if (metadata.containsField(CONFIG_IGNORE_CHARS)) {
ignoreChars = metadata.field(CONFIG_IGNORE_CHARS);
}
if (metadata.containsField(CONFIG_INDEX_RADIX)) {
indexRadix = metadata.field(CONFIG_INDEX_RADIX);
}
if (metadata.containsField(CONFIG_SEPARATOR_CHARS)) {
separatorChars = metadata.field(CONFIG_SEPARATOR_CHARS);
}
if (metadata.containsField(CONFIG_MIN_WORD_LEN)) {
minWordLength = metadata.field(CONFIG_MIN_WORD_LEN);
}
if (metadata.containsField(CONFIG_STOP_WORDS)) {
stopWords = new HashSet<>(metadata.field(CONFIG_STOP_WORDS));
}
}
}
private void config() {
ignoreChars = DEF_IGNORE_CHARS;
indexRadix = DEF_INDEX_RADIX;
separatorChars = DEF_SEPARATOR_CHARS;
minWordLength = 3;
stopWords = new HashSet<>(OStringSerializerHelper.split(DEF_STOP_WORDS, ' '));
}
private Set<String> splitIntoWords(final String iKey) {
final Set<String> result = new HashSet<>();
final List<String> words = new ArrayList<>();
OStringSerializerHelper.split(words, iKey, 0, -1, separatorChars);
final StringBuilder buffer = new StringBuilder(64);
// FOREACH WORD CREATE THE LINK TO THE CURRENT DOCUMENT
char c;
boolean ignore;
for (String word : words) {
buffer.setLength(0);
for (int i = 0; i < word.length(); ++i) {
c = word.charAt(i);
ignore = false;
for (int k = 0; k < ignoreChars.length(); ++k) {
if (c == ignoreChars.charAt(k)) {
ignore = true;
break;
}
}
if (!ignore) {
buffer.append(c);
}
}
int length = buffer.length();
while (length >= minWordLength) {
buffer.setLength(length);
word = buffer.toString();
// CHECK IF IT'S A STOP WORD
if (!stopWords.contains(word))
// ADD THE WORD TO THE RESULT SET
{
result.add(word);
}
if (indexRadix) {
length--;
} else {
break;
}
}
}
return result;
}
private static class EntityRemover implements OIndexKeyUpdater<Object> {
private final OIdentifiable value;
private final OModifiableBoolean removed;
private EntityRemover(OIdentifiable value, OModifiableBoolean removed) {
this.value = value;
this.removed = removed;
}
@Override
public OIndexUpdateAction<Object> update(Object old, AtomicLong bonsayFileId) {
@SuppressWarnings("unchecked")
Set<OIdentifiable> recs = (Set<OIdentifiable>) old;
if (recs.remove(value)) {
removed.setValue(true);
if (recs.isEmpty()) {
if (recs instanceof OMixedIndexRIDContainer) {
((OMixedIndexRIDContainer) recs).delete();
} else if (recs instanceof OIndexRIDContainerSBTree) {
((OIndexRIDContainerSBTree) recs).delete();
}
//noinspection unchecked
return OIndexUpdateAction.remove();
} else {
return OIndexUpdateAction.changed(recs);
}
}
return OIndexUpdateAction.changed(recs);
}
}
private static final class FullTextIndexConfiguration extends IndexConfiguration {
private FullTextIndexConfiguration(ODocument document) {
super(document);
}
private synchronized ODocument updateFullTextIndexConfiguration(
String separatorChars,
String ignoreChars,
Set<String> stopWords,
int minWordLength,
boolean indexRadix) {
document.field(CONFIG_SEPARATOR_CHARS, separatorChars);
document.field(CONFIG_IGNORE_CHARS, ignoreChars);
document.field(CONFIG_STOP_WORDS, stopWords);
document.field(CONFIG_MIN_WORD_LEN, minWordLength);
document.field(CONFIG_INDEX_RADIX, indexRadix);
return document;
}
}
}
| core/src/main/java/com/orientechnologies/orient/core/index/OIndexFullText.java | /*
*
* * Copyright 2010-2016 OrientDB LTD (http://orientdb.com)
* *
* * Licensed under the Apache License, Version 2.0 (the "License");
* * you may not use this file except in compliance with the License.
* * You may obtain a copy of the License at
* *
* * http://www.apache.org/licenses/LICENSE-2.0
* *
* * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS,
* * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* * limitations under the License.
* *
* * For more information: http://orientdb.com
*
*/
package com.orientechnologies.orient.core.index;
import com.orientechnologies.common.listener.OProgressListener;
import com.orientechnologies.common.types.OModifiableBoolean;
import com.orientechnologies.orient.core.db.ODatabaseDocumentInternal;
import com.orientechnologies.orient.core.db.record.OIdentifiable;
import com.orientechnologies.orient.core.exception.OInvalidIndexEngineIdException;
import com.orientechnologies.orient.core.record.impl.ODocument;
import com.orientechnologies.orient.core.serialization.serializer.OStringSerializerHelper;
import com.orientechnologies.orient.core.storage.impl.local.OAbstractPaginatedStorage;
import com.orientechnologies.orient.core.storage.ridbag.sbtree.OIndexRIDContainer;
import com.orientechnologies.orient.core.storage.ridbag.sbtree.OIndexRIDContainerSBTree;
import com.orientechnologies.orient.core.storage.ridbag.sbtree.OMixedIndexRIDContainer;
import com.orientechnologies.orient.core.tx.OTransaction;
import com.orientechnologies.orient.core.tx.OTransactionIndexChanges;
import com.orientechnologies.orient.core.tx.OTransactionIndexChanges.OPERATION;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.atomic.AtomicLong;
/**
* Fast index for full-text searches.
*
* @author Luca Garulli
*/
@Deprecated
public class OIndexFullText extends OIndexMultiValues {
private static final String CONFIG_STOP_WORDS = "stopWords";
private static final String CONFIG_SEPARATOR_CHARS = "separatorChars";
private static final String CONFIG_IGNORE_CHARS = "ignoreChars";
private static final String CONFIG_INDEX_RADIX = "indexRadix";
private static final String CONFIG_MIN_WORD_LEN = "minWordLength";
private static final boolean DEF_INDEX_RADIX = true;
private static final String DEF_SEPARATOR_CHARS = " \r\n\t:;,.|+*/\\=!?[]()";
private static final String DEF_IGNORE_CHARS = "'\"";
private static final String DEF_STOP_WORDS =
"the in a at as and or for his her "
+ "him this that what which while "
+ "up with be was were is";
private boolean indexRadix;
private String separatorChars;
private String ignoreChars;
private int minWordLength;
private Set<String> stopWords;
public OIndexFullText(
String name,
String typeId,
String algorithm,
int version,
OAbstractPaginatedStorage storage,
String valueContainerAlgorithm,
ODocument metadata,
int binaryFormatVersion) {
super(
name,
typeId,
algorithm,
version,
storage,
valueContainerAlgorithm,
metadata,
binaryFormatVersion);
acquireExclusiveLock();
try {
config();
configWithMetadata(metadata);
} finally {
releaseExclusiveLock();
}
}
/**
* Indexes a value and save the index. Splits the value in single words and index each one. Save
* of the index is responsibility of the caller.
*/
@Override
public OIndexFullText put(Object key, final OIdentifiable value) {
if (key == null) {
return this;
}
key = getCollatingValue(key);
final Set<String> words = splitIntoWords(key.toString());
ODatabaseDocumentInternal database = getDatabase();
database.begin();
OTransaction singleTx = database.getTransaction();
for (String word : words) {
singleTx.addIndexEntry(
this, super.getName(), OTransactionIndexChanges.OPERATION.PUT, word, value);
}
database.commit();
return this;
}
private void doPutV0(final OIdentifiable singleValue, final String word) {
Set<OIdentifiable> refs;
while (true) {
try {
//noinspection unchecked
refs = (Set<OIdentifiable>) storage.getIndexValue(indexId, word);
break;
} catch (OInvalidIndexEngineIdException ignore) {
doReloadIndexEngine();
}
}
final Set<OIdentifiable> refsc = refs;
// SAVE THE INDEX ENTRY
while (true) {
try {
storage.updateIndexEntry(
indexId,
word,
(oldValue, bonsayFileId) -> {
Set<OIdentifiable> result;
if (refsc == null) {
// WORD NOT EXISTS: CREATE THE KEYWORD CONTAINER THE FIRST TIME THE WORD IS FOUND
if (ODefaultIndexFactory.SBTREE_BONSAI_VALUE_CONTAINER.equals(
valueContainerAlgorithm)) {
if (binaryFormatVersion >= 13) {
result = new OMixedIndexRIDContainer(getName(), bonsayFileId);
} else {
result = new OIndexRIDContainer(getName(), true, bonsayFileId);
}
} else {
throw new IllegalStateException("MBRBTreeContainer is not supported any more");
}
} else {
result = refsc;
}
// ADD THE CURRENT DOCUMENT AS REF FOR THAT WORD
result.add(singleValue);
return OIndexUpdateAction.changed(result);
});
break;
} catch (OInvalidIndexEngineIdException ignore) {
doReloadIndexEngine();
}
}
}
private void doPutV1(OIdentifiable singleValue, String word) {
while (true) {
try {
storage.putRidIndexEntry(indexId, word, singleValue.getIdentity());
break;
} catch (OInvalidIndexEngineIdException ignore) {
doReloadIndexEngine();
}
}
}
/**
* Splits passed in key on several words and remove records with keys equals to any item of split
* result and values equals to passed in value.
*
* @param key Key to remove.
* @param rid Value to remove.
* @return <code>true</code> if at least one record is removed.
*/
@Override
public boolean remove(Object key, final OIdentifiable rid) {
if (key == null) {
return false;
}
key = getCollatingValue(key);
final Set<String> words = splitIntoWords(key.toString());
ODatabaseDocumentInternal database = getDatabase();
database.begin();
for (final String word : words) {
database.getTransaction().addIndexEntry(this, super.getName(), OPERATION.REMOVE, word, rid);
}
database.commit();
return true;
}
private void removeV0(OIdentifiable value, OModifiableBoolean removed, String word) {
Set<OIdentifiable> recs;
while (true) {
try {
//noinspection unchecked
recs = (Set<OIdentifiable>) storage.getIndexValue(indexId, word);
break;
} catch (OInvalidIndexEngineIdException ignore) {
doReloadIndexEngine();
}
}
if (recs != null && !recs.isEmpty()) {
while (true) {
try {
storage.updateIndexEntry(indexId, word, new EntityRemover(value, removed));
break;
} catch (OInvalidIndexEngineIdException ignore) {
doReloadIndexEngine();
}
}
}
}
private void removeV1(OIdentifiable value, OModifiableBoolean removed, String word) {
while (true) {
try {
final boolean rm = storage.removeRidIndexEntry(indexId, word, value.getIdentity());
removed.setValue(rm);
break;
} catch (OInvalidIndexEngineIdException ignore) {
doReloadIndexEngine();
}
}
}
@Override
public OIndexMultiValues create(
OIndexMetadata metadata, boolean rebuild, OProgressListener progressListener) {
if (metadata.getIndexDefinition().getFields().size() > 1) {
throw new OIndexException(type + " indexes cannot be used as composite ones.");
}
super.create(metadata, rebuild, progressListener);
return this;
}
@Override
public ODocument updateConfiguration() {
super.updateConfiguration();
return ((FullTextIndexConfiguration) configuration)
.updateFullTextIndexConfiguration(
separatorChars, ignoreChars, stopWords, minWordLength, indexRadix);
}
@Override
protected IndexConfiguration indexConfigurationInstance(ODocument document) {
return new FullTextIndexConfiguration(document);
}
public boolean canBeUsedInEqualityOperators() {
return false;
}
public boolean supportsOrderedIterations() {
return false;
}
private void configWithMetadata(ODocument metadata) {
if (metadata != null) {
if (metadata.containsField(CONFIG_IGNORE_CHARS)) {
ignoreChars = metadata.field(CONFIG_IGNORE_CHARS);
}
if (metadata.containsField(CONFIG_INDEX_RADIX)) {
indexRadix = metadata.field(CONFIG_INDEX_RADIX);
}
if (metadata.containsField(CONFIG_SEPARATOR_CHARS)) {
separatorChars = metadata.field(CONFIG_SEPARATOR_CHARS);
}
if (metadata.containsField(CONFIG_MIN_WORD_LEN)) {
minWordLength = metadata.field(CONFIG_MIN_WORD_LEN);
}
if (metadata.containsField(CONFIG_STOP_WORDS)) {
stopWords = new HashSet<>(metadata.field(CONFIG_STOP_WORDS));
}
}
}
private void config() {
ignoreChars = DEF_IGNORE_CHARS;
indexRadix = DEF_INDEX_RADIX;
separatorChars = DEF_SEPARATOR_CHARS;
minWordLength = 3;
stopWords = new HashSet<>(OStringSerializerHelper.split(DEF_STOP_WORDS, ' '));
}
private Set<String> splitIntoWords(final String iKey) {
final Set<String> result = new HashSet<>();
final List<String> words = new ArrayList<>();
OStringSerializerHelper.split(words, iKey, 0, -1, separatorChars);
final StringBuilder buffer = new StringBuilder(64);
// FOREACH WORD CREATE THE LINK TO THE CURRENT DOCUMENT
char c;
boolean ignore;
for (String word : words) {
buffer.setLength(0);
for (int i = 0; i < word.length(); ++i) {
c = word.charAt(i);
ignore = false;
for (int k = 0; k < ignoreChars.length(); ++k) {
if (c == ignoreChars.charAt(k)) {
ignore = true;
break;
}
}
if (!ignore) {
buffer.append(c);
}
}
int length = buffer.length();
while (length >= minWordLength) {
buffer.setLength(length);
word = buffer.toString();
// CHECK IF IT'S A STOP WORD
if (!stopWords.contains(word))
// ADD THE WORD TO THE RESULT SET
{
result.add(word);
}
if (indexRadix) {
length--;
} else {
break;
}
}
}
return result;
}
private static class EntityRemover implements OIndexKeyUpdater<Object> {
private final OIdentifiable value;
private final OModifiableBoolean removed;
private EntityRemover(OIdentifiable value, OModifiableBoolean removed) {
this.value = value;
this.removed = removed;
}
@Override
public OIndexUpdateAction<Object> update(Object old, AtomicLong bonsayFileId) {
@SuppressWarnings("unchecked")
Set<OIdentifiable> recs = (Set<OIdentifiable>) old;
if (recs.remove(value)) {
removed.setValue(true);
if (recs.isEmpty()) {
if (recs instanceof OMixedIndexRIDContainer) {
((OMixedIndexRIDContainer) recs).delete();
} else if (recs instanceof OIndexRIDContainerSBTree) {
((OIndexRIDContainerSBTree) recs).delete();
}
//noinspection unchecked
return OIndexUpdateAction.remove();
} else {
return OIndexUpdateAction.changed(recs);
}
}
return OIndexUpdateAction.changed(recs);
}
}
private static final class FullTextIndexConfiguration extends IndexConfiguration {
private FullTextIndexConfiguration(ODocument document) {
super(document);
}
private synchronized ODocument updateFullTextIndexConfiguration(
String separatorChars,
String ignoreChars,
Set<String> stopWords,
int minWordLength,
boolean indexRadix) {
document.field(CONFIG_SEPARATOR_CHARS, separatorChars);
document.field(CONFIG_IGNORE_CHARS, ignoreChars);
document.field(CONFIG_STOP_WORDS, stopWords);
document.field(CONFIG_MIN_WORD_LEN, minWordLength);
document.field(CONFIG_INDEX_RADIX, indexRadix);
return document;
}
}
}
| chore: removed some index implementations not needed anymore
| core/src/main/java/com/orientechnologies/orient/core/index/OIndexFullText.java | chore: removed some index implementations not needed anymore | <ide><path>ore/src/main/java/com/orientechnologies/orient/core/index/OIndexFullText.java
<ide> }
<ide> }
<ide>
<del> private void doPutV1(OIdentifiable singleValue, String word) {
<del> while (true) {
<del> try {
<del> storage.putRidIndexEntry(indexId, word, singleValue.getIdentity());
<del> break;
<del> } catch (OInvalidIndexEngineIdException ignore) {
<del> doReloadIndexEngine();
<del> }
<del> }
<del> }
<del>
<ide> /**
<ide> * Splits passed in key on several words and remove records with keys equals to any item of split
<ide> * result and values equals to passed in value.
<ide> } catch (OInvalidIndexEngineIdException ignore) {
<ide> doReloadIndexEngine();
<ide> }
<del> }
<del> }
<del> }
<del>
<del> private void removeV1(OIdentifiable value, OModifiableBoolean removed, String word) {
<del> while (true) {
<del> try {
<del> final boolean rm = storage.removeRidIndexEntry(indexId, word, value.getIdentity());
<del> removed.setValue(rm);
<del> break;
<del> } catch (OInvalidIndexEngineIdException ignore) {
<del> doReloadIndexEngine();
<ide> }
<ide> }
<ide> } |
|
JavaScript | mit | 622ca8c05f5e5fb6d32ea6f284290b4339d91d36 | 0 | akshay-harale/akshay-harale.github.io,akshay-harale/akshay-harale.github.io | /******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
/******/
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId]) {
/******/ return installedModules[moduleId].exports;
/******/ }
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ i: moduleId,
/******/ l: false,
/******/ exports: {}
/******/ };
/******/
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/
/******/ // Flag the module as loaded
/******/ module.l = true;
/******/
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/
/******/
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = modules;
/******/
/******/ // expose the module cache
/******/ __webpack_require__.c = installedModules;
/******/
/******/ // define getter function for harmony exports
/******/ __webpack_require__.d = function(exports, name, getter) {
/******/ if(!__webpack_require__.o(exports, name)) {
/******/ Object.defineProperty(exports, name, { enumerable: true, get: getter });
/******/ }
/******/ };
/******/
/******/ // define __esModule on exports
/******/ __webpack_require__.r = function(exports) {
/******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {
/******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
/******/ }
/******/ Object.defineProperty(exports, '__esModule', { value: true });
/******/ };
/******/
/******/ // create a fake namespace object
/******/ // mode & 1: value is a module id, require it
/******/ // mode & 2: merge all properties of value into the ns
/******/ // mode & 4: return value when already ns object
/******/ // mode & 8|1: behave like require
/******/ __webpack_require__.t = function(value, mode) {
/******/ if(mode & 1) value = __webpack_require__(value);
/******/ if(mode & 8) return value;
/******/ if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value;
/******/ var ns = Object.create(null);
/******/ __webpack_require__.r(ns);
/******/ Object.defineProperty(ns, 'default', { enumerable: true, value: value });
/******/ if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key));
/******/ return ns;
/******/ };
/******/
/******/ // getDefaultExport function for compatibility with non-harmony modules
/******/ __webpack_require__.n = function(module) {
/******/ var getter = module && module.__esModule ?
/******/ function getDefault() { return module['default']; } :
/******/ function getModuleExports() { return module; };
/******/ __webpack_require__.d(getter, 'a', getter);
/******/ return getter;
/******/ };
/******/
/******/ // Object.prototype.hasOwnProperty.call
/******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
/******/
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "";
/******/
/******/
/******/ // Load entry module and return exports
/******/ return __webpack_require__(__webpack_require__.s = "./src/index.js");
/******/ })
/************************************************************************/
/******/ ({
/***/ "./node_modules/@babel/runtime/helpers/esm/extends.js":
/*!************************************************************!*\
!*** ./node_modules/@babel/runtime/helpers/esm/extends.js ***!
\************************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"default\", function() { return _extends; });\nfunction _extends() {\n _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\n//# sourceURL=webpack:///./node_modules/@babel/runtime/helpers/esm/extends.js?");
/***/ }),
/***/ "./node_modules/@babel/runtime/helpers/esm/inheritsLoose.js":
/*!******************************************************************!*\
!*** ./node_modules/@babel/runtime/helpers/esm/inheritsLoose.js ***!
\******************************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"default\", function() { return _inheritsLoose; });\nfunction _inheritsLoose(subClass, superClass) {\n subClass.prototype = Object.create(superClass.prototype);\n subClass.prototype.constructor = subClass;\n subClass.__proto__ = superClass;\n}\n\n//# sourceURL=webpack:///./node_modules/@babel/runtime/helpers/esm/inheritsLoose.js?");
/***/ }),
/***/ "./node_modules/@babel/runtime/helpers/esm/objectWithoutPropertiesLoose.js":
/*!*********************************************************************************!*\
!*** ./node_modules/@babel/runtime/helpers/esm/objectWithoutPropertiesLoose.js ***!
\*********************************************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"default\", function() { return _objectWithoutPropertiesLoose; });\nfunction _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}\n\n//# sourceURL=webpack:///./node_modules/@babel/runtime/helpers/esm/objectWithoutPropertiesLoose.js?");
/***/ }),
/***/ "./node_modules/@babel/runtime/helpers/inheritsLoose.js":
/*!**************************************************************!*\
!*** ./node_modules/@babel/runtime/helpers/inheritsLoose.js ***!
\**************************************************************/
/*! no static exports found */
/***/ (function(module, exports) {
eval("function _inheritsLoose(subClass, superClass) {\n subClass.prototype = Object.create(superClass.prototype);\n subClass.prototype.constructor = subClass;\n subClass.__proto__ = superClass;\n}\n\nmodule.exports = _inheritsLoose;\n\n//# sourceURL=webpack:///./node_modules/@babel/runtime/helpers/inheritsLoose.js?");
/***/ }),
/***/ "./node_modules/axios/index.js":
/*!*************************************!*\
!*** ./node_modules/axios/index.js ***!
\*************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
eval("module.exports = __webpack_require__(/*! ./lib/axios */ \"./node_modules/axios/lib/axios.js\");\n\n//# sourceURL=webpack:///./node_modules/axios/index.js?");
/***/ }),
/***/ "./node_modules/axios/lib/adapters/xhr.js":
/*!************************************************!*\
!*** ./node_modules/axios/lib/adapters/xhr.js ***!
\************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
eval("\n\nvar utils = __webpack_require__(/*! ./../utils */ \"./node_modules/axios/lib/utils.js\");\nvar settle = __webpack_require__(/*! ./../core/settle */ \"./node_modules/axios/lib/core/settle.js\");\nvar buildURL = __webpack_require__(/*! ./../helpers/buildURL */ \"./node_modules/axios/lib/helpers/buildURL.js\");\nvar buildFullPath = __webpack_require__(/*! ../core/buildFullPath */ \"./node_modules/axios/lib/core/buildFullPath.js\");\nvar parseHeaders = __webpack_require__(/*! ./../helpers/parseHeaders */ \"./node_modules/axios/lib/helpers/parseHeaders.js\");\nvar isURLSameOrigin = __webpack_require__(/*! ./../helpers/isURLSameOrigin */ \"./node_modules/axios/lib/helpers/isURLSameOrigin.js\");\nvar createError = __webpack_require__(/*! ../core/createError */ \"./node_modules/axios/lib/core/createError.js\");\n\nmodule.exports = function xhrAdapter(config) {\n return new Promise(function dispatchXhrRequest(resolve, reject) {\n var requestData = config.data;\n var requestHeaders = config.headers;\n\n if (utils.isFormData(requestData)) {\n delete requestHeaders['Content-Type']; // Let the browser set it\n }\n\n var request = new XMLHttpRequest();\n\n // HTTP basic authentication\n if (config.auth) {\n var username = config.auth.username || '';\n var password = config.auth.password || '';\n requestHeaders.Authorization = 'Basic ' + btoa(username + ':' + password);\n }\n\n var fullPath = buildFullPath(config.baseURL, config.url);\n request.open(config.method.toUpperCase(), buildURL(fullPath, config.params, config.paramsSerializer), true);\n\n // Set the request timeout in MS\n request.timeout = config.timeout;\n\n // Listen for ready state\n request.onreadystatechange = function handleLoad() {\n if (!request || request.readyState !== 4) {\n return;\n }\n\n // The request errored out and we didn't get a response, this will be\n // handled by onerror instead\n // With one exception: request that using file: protocol, most browsers\n // will return status as 0 even though it's a successful request\n if (request.status === 0 && !(request.responseURL && request.responseURL.indexOf('file:') === 0)) {\n return;\n }\n\n // Prepare the response\n var responseHeaders = 'getAllResponseHeaders' in request ? parseHeaders(request.getAllResponseHeaders()) : null;\n var responseData = !config.responseType || config.responseType === 'text' ? request.responseText : request.response;\n var response = {\n data: responseData,\n status: request.status,\n statusText: request.statusText,\n headers: responseHeaders,\n config: config,\n request: request\n };\n\n settle(resolve, reject, response);\n\n // Clean up request\n request = null;\n };\n\n // Handle browser request cancellation (as opposed to a manual cancellation)\n request.onabort = function handleAbort() {\n if (!request) {\n return;\n }\n\n reject(createError('Request aborted', config, 'ECONNABORTED', request));\n\n // Clean up request\n request = null;\n };\n\n // Handle low level network errors\n request.onerror = function handleError() {\n // Real errors are hidden from us by the browser\n // onerror should only fire if it's a network error\n reject(createError('Network Error', config, null, request));\n\n // Clean up request\n request = null;\n };\n\n // Handle timeout\n request.ontimeout = function handleTimeout() {\n var timeoutErrorMessage = 'timeout of ' + config.timeout + 'ms exceeded';\n if (config.timeoutErrorMessage) {\n timeoutErrorMessage = config.timeoutErrorMessage;\n }\n reject(createError(timeoutErrorMessage, config, 'ECONNABORTED',\n request));\n\n // Clean up request\n request = null;\n };\n\n // Add xsrf header\n // This is only done if running in a standard browser environment.\n // Specifically not if we're in a web worker, or react-native.\n if (utils.isStandardBrowserEnv()) {\n var cookies = __webpack_require__(/*! ./../helpers/cookies */ \"./node_modules/axios/lib/helpers/cookies.js\");\n\n // Add xsrf header\n var xsrfValue = (config.withCredentials || isURLSameOrigin(fullPath)) && config.xsrfCookieName ?\n cookies.read(config.xsrfCookieName) :\n undefined;\n\n if (xsrfValue) {\n requestHeaders[config.xsrfHeaderName] = xsrfValue;\n }\n }\n\n // Add headers to the request\n if ('setRequestHeader' in request) {\n utils.forEach(requestHeaders, function setRequestHeader(val, key) {\n if (typeof requestData === 'undefined' && key.toLowerCase() === 'content-type') {\n // Remove Content-Type if data is undefined\n delete requestHeaders[key];\n } else {\n // Otherwise add header to the request\n request.setRequestHeader(key, val);\n }\n });\n }\n\n // Add withCredentials to request if needed\n if (!utils.isUndefined(config.withCredentials)) {\n request.withCredentials = !!config.withCredentials;\n }\n\n // Add responseType to request if needed\n if (config.responseType) {\n try {\n request.responseType = config.responseType;\n } catch (e) {\n // Expected DOMException thrown by browsers not compatible XMLHttpRequest Level 2.\n // But, this can be suppressed for 'json' type as it can be parsed by default 'transformResponse' function.\n if (config.responseType !== 'json') {\n throw e;\n }\n }\n }\n\n // Handle progress if needed\n if (typeof config.onDownloadProgress === 'function') {\n request.addEventListener('progress', config.onDownloadProgress);\n }\n\n // Not all browsers support upload events\n if (typeof config.onUploadProgress === 'function' && request.upload) {\n request.upload.addEventListener('progress', config.onUploadProgress);\n }\n\n if (config.cancelToken) {\n // Handle cancellation\n config.cancelToken.promise.then(function onCanceled(cancel) {\n if (!request) {\n return;\n }\n\n request.abort();\n reject(cancel);\n // Clean up request\n request = null;\n });\n }\n\n if (requestData === undefined) {\n requestData = null;\n }\n\n // Send the request\n request.send(requestData);\n });\n};\n\n\n//# sourceURL=webpack:///./node_modules/axios/lib/adapters/xhr.js?");
/***/ }),
/***/ "./node_modules/axios/lib/axios.js":
/*!*****************************************!*\
!*** ./node_modules/axios/lib/axios.js ***!
\*****************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
eval("\n\nvar utils = __webpack_require__(/*! ./utils */ \"./node_modules/axios/lib/utils.js\");\nvar bind = __webpack_require__(/*! ./helpers/bind */ \"./node_modules/axios/lib/helpers/bind.js\");\nvar Axios = __webpack_require__(/*! ./core/Axios */ \"./node_modules/axios/lib/core/Axios.js\");\nvar mergeConfig = __webpack_require__(/*! ./core/mergeConfig */ \"./node_modules/axios/lib/core/mergeConfig.js\");\nvar defaults = __webpack_require__(/*! ./defaults */ \"./node_modules/axios/lib/defaults.js\");\n\n/**\n * Create an instance of Axios\n *\n * @param {Object} defaultConfig The default config for the instance\n * @return {Axios} A new instance of Axios\n */\nfunction createInstance(defaultConfig) {\n var context = new Axios(defaultConfig);\n var instance = bind(Axios.prototype.request, context);\n\n // Copy axios.prototype to instance\n utils.extend(instance, Axios.prototype, context);\n\n // Copy context to instance\n utils.extend(instance, context);\n\n return instance;\n}\n\n// Create the default instance to be exported\nvar axios = createInstance(defaults);\n\n// Expose Axios class to allow class inheritance\naxios.Axios = Axios;\n\n// Factory for creating new instances\naxios.create = function create(instanceConfig) {\n return createInstance(mergeConfig(axios.defaults, instanceConfig));\n};\n\n// Expose Cancel & CancelToken\naxios.Cancel = __webpack_require__(/*! ./cancel/Cancel */ \"./node_modules/axios/lib/cancel/Cancel.js\");\naxios.CancelToken = __webpack_require__(/*! ./cancel/CancelToken */ \"./node_modules/axios/lib/cancel/CancelToken.js\");\naxios.isCancel = __webpack_require__(/*! ./cancel/isCancel */ \"./node_modules/axios/lib/cancel/isCancel.js\");\n\n// Expose all/spread\naxios.all = function all(promises) {\n return Promise.all(promises);\n};\naxios.spread = __webpack_require__(/*! ./helpers/spread */ \"./node_modules/axios/lib/helpers/spread.js\");\n\nmodule.exports = axios;\n\n// Allow use of default import syntax in TypeScript\nmodule.exports.default = axios;\n\n\n//# sourceURL=webpack:///./node_modules/axios/lib/axios.js?");
/***/ }),
/***/ "./node_modules/axios/lib/cancel/Cancel.js":
/*!*************************************************!*\
!*** ./node_modules/axios/lib/cancel/Cancel.js ***!
\*************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
eval("\n\n/**\n * A `Cancel` is an object that is thrown when an operation is canceled.\n *\n * @class\n * @param {string=} message The message.\n */\nfunction Cancel(message) {\n this.message = message;\n}\n\nCancel.prototype.toString = function toString() {\n return 'Cancel' + (this.message ? ': ' + this.message : '');\n};\n\nCancel.prototype.__CANCEL__ = true;\n\nmodule.exports = Cancel;\n\n\n//# sourceURL=webpack:///./node_modules/axios/lib/cancel/Cancel.js?");
/***/ }),
/***/ "./node_modules/axios/lib/cancel/CancelToken.js":
/*!******************************************************!*\
!*** ./node_modules/axios/lib/cancel/CancelToken.js ***!
\******************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
eval("\n\nvar Cancel = __webpack_require__(/*! ./Cancel */ \"./node_modules/axios/lib/cancel/Cancel.js\");\n\n/**\n * A `CancelToken` is an object that can be used to request cancellation of an operation.\n *\n * @class\n * @param {Function} executor The executor function.\n */\nfunction CancelToken(executor) {\n if (typeof executor !== 'function') {\n throw new TypeError('executor must be a function.');\n }\n\n var resolvePromise;\n this.promise = new Promise(function promiseExecutor(resolve) {\n resolvePromise = resolve;\n });\n\n var token = this;\n executor(function cancel(message) {\n if (token.reason) {\n // Cancellation has already been requested\n return;\n }\n\n token.reason = new Cancel(message);\n resolvePromise(token.reason);\n });\n}\n\n/**\n * Throws a `Cancel` if cancellation has been requested.\n */\nCancelToken.prototype.throwIfRequested = function throwIfRequested() {\n if (this.reason) {\n throw this.reason;\n }\n};\n\n/**\n * Returns an object that contains a new `CancelToken` and a function that, when called,\n * cancels the `CancelToken`.\n */\nCancelToken.source = function source() {\n var cancel;\n var token = new CancelToken(function executor(c) {\n cancel = c;\n });\n return {\n token: token,\n cancel: cancel\n };\n};\n\nmodule.exports = CancelToken;\n\n\n//# sourceURL=webpack:///./node_modules/axios/lib/cancel/CancelToken.js?");
/***/ }),
/***/ "./node_modules/axios/lib/cancel/isCancel.js":
/*!***************************************************!*\
!*** ./node_modules/axios/lib/cancel/isCancel.js ***!
\***************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
eval("\n\nmodule.exports = function isCancel(value) {\n return !!(value && value.__CANCEL__);\n};\n\n\n//# sourceURL=webpack:///./node_modules/axios/lib/cancel/isCancel.js?");
/***/ }),
/***/ "./node_modules/axios/lib/core/Axios.js":
/*!**********************************************!*\
!*** ./node_modules/axios/lib/core/Axios.js ***!
\**********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
eval("\n\nvar utils = __webpack_require__(/*! ./../utils */ \"./node_modules/axios/lib/utils.js\");\nvar buildURL = __webpack_require__(/*! ../helpers/buildURL */ \"./node_modules/axios/lib/helpers/buildURL.js\");\nvar InterceptorManager = __webpack_require__(/*! ./InterceptorManager */ \"./node_modules/axios/lib/core/InterceptorManager.js\");\nvar dispatchRequest = __webpack_require__(/*! ./dispatchRequest */ \"./node_modules/axios/lib/core/dispatchRequest.js\");\nvar mergeConfig = __webpack_require__(/*! ./mergeConfig */ \"./node_modules/axios/lib/core/mergeConfig.js\");\n\n/**\n * Create a new instance of Axios\n *\n * @param {Object} instanceConfig The default config for the instance\n */\nfunction Axios(instanceConfig) {\n this.defaults = instanceConfig;\n this.interceptors = {\n request: new InterceptorManager(),\n response: new InterceptorManager()\n };\n}\n\n/**\n * Dispatch a request\n *\n * @param {Object} config The config specific for this request (merged with this.defaults)\n */\nAxios.prototype.request = function request(config) {\n /*eslint no-param-reassign:0*/\n // Allow for axios('example/url'[, config]) a la fetch API\n if (typeof config === 'string') {\n config = arguments[1] || {};\n config.url = arguments[0];\n } else {\n config = config || {};\n }\n\n config = mergeConfig(this.defaults, config);\n\n // Set config.method\n if (config.method) {\n config.method = config.method.toLowerCase();\n } else if (this.defaults.method) {\n config.method = this.defaults.method.toLowerCase();\n } else {\n config.method = 'get';\n }\n\n // Hook up interceptors middleware\n var chain = [dispatchRequest, undefined];\n var promise = Promise.resolve(config);\n\n this.interceptors.request.forEach(function unshiftRequestInterceptors(interceptor) {\n chain.unshift(interceptor.fulfilled, interceptor.rejected);\n });\n\n this.interceptors.response.forEach(function pushResponseInterceptors(interceptor) {\n chain.push(interceptor.fulfilled, interceptor.rejected);\n });\n\n while (chain.length) {\n promise = promise.then(chain.shift(), chain.shift());\n }\n\n return promise;\n};\n\nAxios.prototype.getUri = function getUri(config) {\n config = mergeConfig(this.defaults, config);\n return buildURL(config.url, config.params, config.paramsSerializer).replace(/^\\?/, '');\n};\n\n// Provide aliases for supported request methods\nutils.forEach(['delete', 'get', 'head', 'options'], function forEachMethodNoData(method) {\n /*eslint func-names:0*/\n Axios.prototype[method] = function(url, config) {\n return this.request(utils.merge(config || {}, {\n method: method,\n url: url\n }));\n };\n});\n\nutils.forEach(['post', 'put', 'patch'], function forEachMethodWithData(method) {\n /*eslint func-names:0*/\n Axios.prototype[method] = function(url, data, config) {\n return this.request(utils.merge(config || {}, {\n method: method,\n url: url,\n data: data\n }));\n };\n});\n\nmodule.exports = Axios;\n\n\n//# sourceURL=webpack:///./node_modules/axios/lib/core/Axios.js?");
/***/ }),
/***/ "./node_modules/axios/lib/core/InterceptorManager.js":
/*!***********************************************************!*\
!*** ./node_modules/axios/lib/core/InterceptorManager.js ***!
\***********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
eval("\n\nvar utils = __webpack_require__(/*! ./../utils */ \"./node_modules/axios/lib/utils.js\");\n\nfunction InterceptorManager() {\n this.handlers = [];\n}\n\n/**\n * Add a new interceptor to the stack\n *\n * @param {Function} fulfilled The function to handle `then` for a `Promise`\n * @param {Function} rejected The function to handle `reject` for a `Promise`\n *\n * @return {Number} An ID used to remove interceptor later\n */\nInterceptorManager.prototype.use = function use(fulfilled, rejected) {\n this.handlers.push({\n fulfilled: fulfilled,\n rejected: rejected\n });\n return this.handlers.length - 1;\n};\n\n/**\n * Remove an interceptor from the stack\n *\n * @param {Number} id The ID that was returned by `use`\n */\nInterceptorManager.prototype.eject = function eject(id) {\n if (this.handlers[id]) {\n this.handlers[id] = null;\n }\n};\n\n/**\n * Iterate over all the registered interceptors\n *\n * This method is particularly useful for skipping over any\n * interceptors that may have become `null` calling `eject`.\n *\n * @param {Function} fn The function to call for each interceptor\n */\nInterceptorManager.prototype.forEach = function forEach(fn) {\n utils.forEach(this.handlers, function forEachHandler(h) {\n if (h !== null) {\n fn(h);\n }\n });\n};\n\nmodule.exports = InterceptorManager;\n\n\n//# sourceURL=webpack:///./node_modules/axios/lib/core/InterceptorManager.js?");
/***/ }),
/***/ "./node_modules/axios/lib/core/buildFullPath.js":
/*!******************************************************!*\
!*** ./node_modules/axios/lib/core/buildFullPath.js ***!
\******************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
eval("\n\nvar isAbsoluteURL = __webpack_require__(/*! ../helpers/isAbsoluteURL */ \"./node_modules/axios/lib/helpers/isAbsoluteURL.js\");\nvar combineURLs = __webpack_require__(/*! ../helpers/combineURLs */ \"./node_modules/axios/lib/helpers/combineURLs.js\");\n\n/**\n * Creates a new URL by combining the baseURL with the requestedURL,\n * only when the requestedURL is not already an absolute URL.\n * If the requestURL is absolute, this function returns the requestedURL untouched.\n *\n * @param {string} baseURL The base URL\n * @param {string} requestedURL Absolute or relative URL to combine\n * @returns {string} The combined full path\n */\nmodule.exports = function buildFullPath(baseURL, requestedURL) {\n if (baseURL && !isAbsoluteURL(requestedURL)) {\n return combineURLs(baseURL, requestedURL);\n }\n return requestedURL;\n};\n\n\n//# sourceURL=webpack:///./node_modules/axios/lib/core/buildFullPath.js?");
/***/ }),
/***/ "./node_modules/axios/lib/core/createError.js":
/*!****************************************************!*\
!*** ./node_modules/axios/lib/core/createError.js ***!
\****************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
eval("\n\nvar enhanceError = __webpack_require__(/*! ./enhanceError */ \"./node_modules/axios/lib/core/enhanceError.js\");\n\n/**\n * Create an Error with the specified message, config, error code, request and response.\n *\n * @param {string} message The error message.\n * @param {Object} config The config.\n * @param {string} [code] The error code (for example, 'ECONNABORTED').\n * @param {Object} [request] The request.\n * @param {Object} [response] The response.\n * @returns {Error} The created error.\n */\nmodule.exports = function createError(message, config, code, request, response) {\n var error = new Error(message);\n return enhanceError(error, config, code, request, response);\n};\n\n\n//# sourceURL=webpack:///./node_modules/axios/lib/core/createError.js?");
/***/ }),
/***/ "./node_modules/axios/lib/core/dispatchRequest.js":
/*!********************************************************!*\
!*** ./node_modules/axios/lib/core/dispatchRequest.js ***!
\********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
eval("\n\nvar utils = __webpack_require__(/*! ./../utils */ \"./node_modules/axios/lib/utils.js\");\nvar transformData = __webpack_require__(/*! ./transformData */ \"./node_modules/axios/lib/core/transformData.js\");\nvar isCancel = __webpack_require__(/*! ../cancel/isCancel */ \"./node_modules/axios/lib/cancel/isCancel.js\");\nvar defaults = __webpack_require__(/*! ../defaults */ \"./node_modules/axios/lib/defaults.js\");\n\n/**\n * Throws a `Cancel` if cancellation has been requested.\n */\nfunction throwIfCancellationRequested(config) {\n if (config.cancelToken) {\n config.cancelToken.throwIfRequested();\n }\n}\n\n/**\n * Dispatch a request to the server using the configured adapter.\n *\n * @param {object} config The config that is to be used for the request\n * @returns {Promise} The Promise to be fulfilled\n */\nmodule.exports = function dispatchRequest(config) {\n throwIfCancellationRequested(config);\n\n // Ensure headers exist\n config.headers = config.headers || {};\n\n // Transform request data\n config.data = transformData(\n config.data,\n config.headers,\n config.transformRequest\n );\n\n // Flatten headers\n config.headers = utils.merge(\n config.headers.common || {},\n config.headers[config.method] || {},\n config.headers\n );\n\n utils.forEach(\n ['delete', 'get', 'head', 'post', 'put', 'patch', 'common'],\n function cleanHeaderConfig(method) {\n delete config.headers[method];\n }\n );\n\n var adapter = config.adapter || defaults.adapter;\n\n return adapter(config).then(function onAdapterResolution(response) {\n throwIfCancellationRequested(config);\n\n // Transform response data\n response.data = transformData(\n response.data,\n response.headers,\n config.transformResponse\n );\n\n return response;\n }, function onAdapterRejection(reason) {\n if (!isCancel(reason)) {\n throwIfCancellationRequested(config);\n\n // Transform response data\n if (reason && reason.response) {\n reason.response.data = transformData(\n reason.response.data,\n reason.response.headers,\n config.transformResponse\n );\n }\n }\n\n return Promise.reject(reason);\n });\n};\n\n\n//# sourceURL=webpack:///./node_modules/axios/lib/core/dispatchRequest.js?");
/***/ }),
/***/ "./node_modules/axios/lib/core/enhanceError.js":
/*!*****************************************************!*\
!*** ./node_modules/axios/lib/core/enhanceError.js ***!
\*****************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
eval("\n\n/**\n * Update an Error with the specified config, error code, and response.\n *\n * @param {Error} error The error to update.\n * @param {Object} config The config.\n * @param {string} [code] The error code (for example, 'ECONNABORTED').\n * @param {Object} [request] The request.\n * @param {Object} [response] The response.\n * @returns {Error} The error.\n */\nmodule.exports = function enhanceError(error, config, code, request, response) {\n error.config = config;\n if (code) {\n error.code = code;\n }\n\n error.request = request;\n error.response = response;\n error.isAxiosError = true;\n\n error.toJSON = function() {\n return {\n // Standard\n message: this.message,\n name: this.name,\n // Microsoft\n description: this.description,\n number: this.number,\n // Mozilla\n fileName: this.fileName,\n lineNumber: this.lineNumber,\n columnNumber: this.columnNumber,\n stack: this.stack,\n // Axios\n config: this.config,\n code: this.code\n };\n };\n return error;\n};\n\n\n//# sourceURL=webpack:///./node_modules/axios/lib/core/enhanceError.js?");
/***/ }),
/***/ "./node_modules/axios/lib/core/mergeConfig.js":
/*!****************************************************!*\
!*** ./node_modules/axios/lib/core/mergeConfig.js ***!
\****************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
eval("\n\nvar utils = __webpack_require__(/*! ../utils */ \"./node_modules/axios/lib/utils.js\");\n\n/**\n * Config-specific merge-function which creates a new config-object\n * by merging two configuration objects together.\n *\n * @param {Object} config1\n * @param {Object} config2\n * @returns {Object} New object resulting from merging config2 to config1\n */\nmodule.exports = function mergeConfig(config1, config2) {\n // eslint-disable-next-line no-param-reassign\n config2 = config2 || {};\n var config = {};\n\n var valueFromConfig2Keys = ['url', 'method', 'params', 'data'];\n var mergeDeepPropertiesKeys = ['headers', 'auth', 'proxy'];\n var defaultToConfig2Keys = [\n 'baseURL', 'url', 'transformRequest', 'transformResponse', 'paramsSerializer',\n 'timeout', 'withCredentials', 'adapter', 'responseType', 'xsrfCookieName',\n 'xsrfHeaderName', 'onUploadProgress', 'onDownloadProgress',\n 'maxContentLength', 'validateStatus', 'maxRedirects', 'httpAgent',\n 'httpsAgent', 'cancelToken', 'socketPath'\n ];\n\n utils.forEach(valueFromConfig2Keys, function valueFromConfig2(prop) {\n if (typeof config2[prop] !== 'undefined') {\n config[prop] = config2[prop];\n }\n });\n\n utils.forEach(mergeDeepPropertiesKeys, function mergeDeepProperties(prop) {\n if (utils.isObject(config2[prop])) {\n config[prop] = utils.deepMerge(config1[prop], config2[prop]);\n } else if (typeof config2[prop] !== 'undefined') {\n config[prop] = config2[prop];\n } else if (utils.isObject(config1[prop])) {\n config[prop] = utils.deepMerge(config1[prop]);\n } else if (typeof config1[prop] !== 'undefined') {\n config[prop] = config1[prop];\n }\n });\n\n utils.forEach(defaultToConfig2Keys, function defaultToConfig2(prop) {\n if (typeof config2[prop] !== 'undefined') {\n config[prop] = config2[prop];\n } else if (typeof config1[prop] !== 'undefined') {\n config[prop] = config1[prop];\n }\n });\n\n var axiosKeys = valueFromConfig2Keys\n .concat(mergeDeepPropertiesKeys)\n .concat(defaultToConfig2Keys);\n\n var otherKeys = Object\n .keys(config2)\n .filter(function filterAxiosKeys(key) {\n return axiosKeys.indexOf(key) === -1;\n });\n\n utils.forEach(otherKeys, function otherKeysDefaultToConfig2(prop) {\n if (typeof config2[prop] !== 'undefined') {\n config[prop] = config2[prop];\n } else if (typeof config1[prop] !== 'undefined') {\n config[prop] = config1[prop];\n }\n });\n\n return config;\n};\n\n\n//# sourceURL=webpack:///./node_modules/axios/lib/core/mergeConfig.js?");
/***/ }),
/***/ "./node_modules/axios/lib/core/settle.js":
/*!***********************************************!*\
!*** ./node_modules/axios/lib/core/settle.js ***!
\***********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
eval("\n\nvar createError = __webpack_require__(/*! ./createError */ \"./node_modules/axios/lib/core/createError.js\");\n\n/**\n * Resolve or reject a Promise based on response status.\n *\n * @param {Function} resolve A function that resolves the promise.\n * @param {Function} reject A function that rejects the promise.\n * @param {object} response The response.\n */\nmodule.exports = function settle(resolve, reject, response) {\n var validateStatus = response.config.validateStatus;\n if (!validateStatus || validateStatus(response.status)) {\n resolve(response);\n } else {\n reject(createError(\n 'Request failed with status code ' + response.status,\n response.config,\n null,\n response.request,\n response\n ));\n }\n};\n\n\n//# sourceURL=webpack:///./node_modules/axios/lib/core/settle.js?");
/***/ }),
/***/ "./node_modules/axios/lib/core/transformData.js":
/*!******************************************************!*\
!*** ./node_modules/axios/lib/core/transformData.js ***!
\******************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
eval("\n\nvar utils = __webpack_require__(/*! ./../utils */ \"./node_modules/axios/lib/utils.js\");\n\n/**\n * Transform the data for a request or a response\n *\n * @param {Object|String} data The data to be transformed\n * @param {Array} headers The headers for the request or response\n * @param {Array|Function} fns A single function or Array of functions\n * @returns {*} The resulting transformed data\n */\nmodule.exports = function transformData(data, headers, fns) {\n /*eslint no-param-reassign:0*/\n utils.forEach(fns, function transform(fn) {\n data = fn(data, headers);\n });\n\n return data;\n};\n\n\n//# sourceURL=webpack:///./node_modules/axios/lib/core/transformData.js?");
/***/ }),
/***/ "./node_modules/axios/lib/defaults.js":
/*!********************************************!*\
!*** ./node_modules/axios/lib/defaults.js ***!
\********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
eval("/* WEBPACK VAR INJECTION */(function(process) {\n\nvar utils = __webpack_require__(/*! ./utils */ \"./node_modules/axios/lib/utils.js\");\nvar normalizeHeaderName = __webpack_require__(/*! ./helpers/normalizeHeaderName */ \"./node_modules/axios/lib/helpers/normalizeHeaderName.js\");\n\nvar DEFAULT_CONTENT_TYPE = {\n 'Content-Type': 'application/x-www-form-urlencoded'\n};\n\nfunction setContentTypeIfUnset(headers, value) {\n if (!utils.isUndefined(headers) && utils.isUndefined(headers['Content-Type'])) {\n headers['Content-Type'] = value;\n }\n}\n\nfunction getDefaultAdapter() {\n var adapter;\n if (typeof XMLHttpRequest !== 'undefined') {\n // For browsers use XHR adapter\n adapter = __webpack_require__(/*! ./adapters/xhr */ \"./node_modules/axios/lib/adapters/xhr.js\");\n } else if (typeof process !== 'undefined' && Object.prototype.toString.call(process) === '[object process]') {\n // For node use HTTP adapter\n adapter = __webpack_require__(/*! ./adapters/http */ \"./node_modules/axios/lib/adapters/xhr.js\");\n }\n return adapter;\n}\n\nvar defaults = {\n adapter: getDefaultAdapter(),\n\n transformRequest: [function transformRequest(data, headers) {\n normalizeHeaderName(headers, 'Accept');\n normalizeHeaderName(headers, 'Content-Type');\n if (utils.isFormData(data) ||\n utils.isArrayBuffer(data) ||\n utils.isBuffer(data) ||\n utils.isStream(data) ||\n utils.isFile(data) ||\n utils.isBlob(data)\n ) {\n return data;\n }\n if (utils.isArrayBufferView(data)) {\n return data.buffer;\n }\n if (utils.isURLSearchParams(data)) {\n setContentTypeIfUnset(headers, 'application/x-www-form-urlencoded;charset=utf-8');\n return data.toString();\n }\n if (utils.isObject(data)) {\n setContentTypeIfUnset(headers, 'application/json;charset=utf-8');\n return JSON.stringify(data);\n }\n return data;\n }],\n\n transformResponse: [function transformResponse(data) {\n /*eslint no-param-reassign:0*/\n if (typeof data === 'string') {\n try {\n data = JSON.parse(data);\n } catch (e) { /* Ignore */ }\n }\n return data;\n }],\n\n /**\n * A timeout in milliseconds to abort a request. If set to 0 (default) a\n * timeout is not created.\n */\n timeout: 0,\n\n xsrfCookieName: 'XSRF-TOKEN',\n xsrfHeaderName: 'X-XSRF-TOKEN',\n\n maxContentLength: -1,\n\n validateStatus: function validateStatus(status) {\n return status >= 200 && status < 300;\n }\n};\n\ndefaults.headers = {\n common: {\n 'Accept': 'application/json, text/plain, */*'\n }\n};\n\nutils.forEach(['delete', 'get', 'head'], function forEachMethodNoData(method) {\n defaults.headers[method] = {};\n});\n\nutils.forEach(['post', 'put', 'patch'], function forEachMethodWithData(method) {\n defaults.headers[method] = utils.merge(DEFAULT_CONTENT_TYPE);\n});\n\nmodule.exports = defaults;\n\n/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./../../process/browser.js */ \"./node_modules/process/browser.js\")))\n\n//# sourceURL=webpack:///./node_modules/axios/lib/defaults.js?");
/***/ }),
/***/ "./node_modules/axios/lib/helpers/bind.js":
/*!************************************************!*\
!*** ./node_modules/axios/lib/helpers/bind.js ***!
\************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
eval("\n\nmodule.exports = function bind(fn, thisArg) {\n return function wrap() {\n var args = new Array(arguments.length);\n for (var i = 0; i < args.length; i++) {\n args[i] = arguments[i];\n }\n return fn.apply(thisArg, args);\n };\n};\n\n\n//# sourceURL=webpack:///./node_modules/axios/lib/helpers/bind.js?");
/***/ }),
/***/ "./node_modules/axios/lib/helpers/buildURL.js":
/*!****************************************************!*\
!*** ./node_modules/axios/lib/helpers/buildURL.js ***!
\****************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
eval("\n\nvar utils = __webpack_require__(/*! ./../utils */ \"./node_modules/axios/lib/utils.js\");\n\nfunction encode(val) {\n return encodeURIComponent(val).\n replace(/%40/gi, '@').\n replace(/%3A/gi, ':').\n replace(/%24/g, '$').\n replace(/%2C/gi, ',').\n replace(/%20/g, '+').\n replace(/%5B/gi, '[').\n replace(/%5D/gi, ']');\n}\n\n/**\n * Build a URL by appending params to the end\n *\n * @param {string} url The base of the url (e.g., http://www.google.com)\n * @param {object} [params] The params to be appended\n * @returns {string} The formatted url\n */\nmodule.exports = function buildURL(url, params, paramsSerializer) {\n /*eslint no-param-reassign:0*/\n if (!params) {\n return url;\n }\n\n var serializedParams;\n if (paramsSerializer) {\n serializedParams = paramsSerializer(params);\n } else if (utils.isURLSearchParams(params)) {\n serializedParams = params.toString();\n } else {\n var parts = [];\n\n utils.forEach(params, function serialize(val, key) {\n if (val === null || typeof val === 'undefined') {\n return;\n }\n\n if (utils.isArray(val)) {\n key = key + '[]';\n } else {\n val = [val];\n }\n\n utils.forEach(val, function parseValue(v) {\n if (utils.isDate(v)) {\n v = v.toISOString();\n } else if (utils.isObject(v)) {\n v = JSON.stringify(v);\n }\n parts.push(encode(key) + '=' + encode(v));\n });\n });\n\n serializedParams = parts.join('&');\n }\n\n if (serializedParams) {\n var hashmarkIndex = url.indexOf('#');\n if (hashmarkIndex !== -1) {\n url = url.slice(0, hashmarkIndex);\n }\n\n url += (url.indexOf('?') === -1 ? '?' : '&') + serializedParams;\n }\n\n return url;\n};\n\n\n//# sourceURL=webpack:///./node_modules/axios/lib/helpers/buildURL.js?");
/***/ }),
/***/ "./node_modules/axios/lib/helpers/combineURLs.js":
/*!*******************************************************!*\
!*** ./node_modules/axios/lib/helpers/combineURLs.js ***!
\*******************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
eval("\n\n/**\n * Creates a new URL by combining the specified URLs\n *\n * @param {string} baseURL The base URL\n * @param {string} relativeURL The relative URL\n * @returns {string} The combined URL\n */\nmodule.exports = function combineURLs(baseURL, relativeURL) {\n return relativeURL\n ? baseURL.replace(/\\/+$/, '') + '/' + relativeURL.replace(/^\\/+/, '')\n : baseURL;\n};\n\n\n//# sourceURL=webpack:///./node_modules/axios/lib/helpers/combineURLs.js?");
/***/ }),
/***/ "./node_modules/axios/lib/helpers/cookies.js":
/*!***************************************************!*\
!*** ./node_modules/axios/lib/helpers/cookies.js ***!
\***************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
eval("\n\nvar utils = __webpack_require__(/*! ./../utils */ \"./node_modules/axios/lib/utils.js\");\n\nmodule.exports = (\n utils.isStandardBrowserEnv() ?\n\n // Standard browser envs support document.cookie\n (function standardBrowserEnv() {\n return {\n write: function write(name, value, expires, path, domain, secure) {\n var cookie = [];\n cookie.push(name + '=' + encodeURIComponent(value));\n\n if (utils.isNumber(expires)) {\n cookie.push('expires=' + new Date(expires).toGMTString());\n }\n\n if (utils.isString(path)) {\n cookie.push('path=' + path);\n }\n\n if (utils.isString(domain)) {\n cookie.push('domain=' + domain);\n }\n\n if (secure === true) {\n cookie.push('secure');\n }\n\n document.cookie = cookie.join('; ');\n },\n\n read: function read(name) {\n var match = document.cookie.match(new RegExp('(^|;\\\\s*)(' + name + ')=([^;]*)'));\n return (match ? decodeURIComponent(match[3]) : null);\n },\n\n remove: function remove(name) {\n this.write(name, '', Date.now() - 86400000);\n }\n };\n })() :\n\n // Non standard browser env (web workers, react-native) lack needed support.\n (function nonStandardBrowserEnv() {\n return {\n write: function write() {},\n read: function read() { return null; },\n remove: function remove() {}\n };\n })()\n);\n\n\n//# sourceURL=webpack:///./node_modules/axios/lib/helpers/cookies.js?");
/***/ }),
/***/ "./node_modules/axios/lib/helpers/isAbsoluteURL.js":
/*!*********************************************************!*\
!*** ./node_modules/axios/lib/helpers/isAbsoluteURL.js ***!
\*********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
eval("\n\n/**\n * Determines whether the specified URL is absolute\n *\n * @param {string} url The URL to test\n * @returns {boolean} True if the specified URL is absolute, otherwise false\n */\nmodule.exports = function isAbsoluteURL(url) {\n // A URL is considered absolute if it begins with \"<scheme>://\" or \"//\" (protocol-relative URL).\n // RFC 3986 defines scheme name as a sequence of characters beginning with a letter and followed\n // by any combination of letters, digits, plus, period, or hyphen.\n return /^([a-z][a-z\\d\\+\\-\\.]*:)?\\/\\//i.test(url);\n};\n\n\n//# sourceURL=webpack:///./node_modules/axios/lib/helpers/isAbsoluteURL.js?");
/***/ }),
/***/ "./node_modules/axios/lib/helpers/isURLSameOrigin.js":
/*!***********************************************************!*\
!*** ./node_modules/axios/lib/helpers/isURLSameOrigin.js ***!
\***********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
eval("\n\nvar utils = __webpack_require__(/*! ./../utils */ \"./node_modules/axios/lib/utils.js\");\n\nmodule.exports = (\n utils.isStandardBrowserEnv() ?\n\n // Standard browser envs have full support of the APIs needed to test\n // whether the request URL is of the same origin as current location.\n (function standardBrowserEnv() {\n var msie = /(msie|trident)/i.test(navigator.userAgent);\n var urlParsingNode = document.createElement('a');\n var originURL;\n\n /**\n * Parse a URL to discover it's components\n *\n * @param {String} url The URL to be parsed\n * @returns {Object}\n */\n function resolveURL(url) {\n var href = url;\n\n if (msie) {\n // IE needs attribute set twice to normalize properties\n urlParsingNode.setAttribute('href', href);\n href = urlParsingNode.href;\n }\n\n urlParsingNode.setAttribute('href', href);\n\n // urlParsingNode provides the UrlUtils interface - http://url.spec.whatwg.org/#urlutils\n return {\n href: urlParsingNode.href,\n protocol: urlParsingNode.protocol ? urlParsingNode.protocol.replace(/:$/, '') : '',\n host: urlParsingNode.host,\n search: urlParsingNode.search ? urlParsingNode.search.replace(/^\\?/, '') : '',\n hash: urlParsingNode.hash ? urlParsingNode.hash.replace(/^#/, '') : '',\n hostname: urlParsingNode.hostname,\n port: urlParsingNode.port,\n pathname: (urlParsingNode.pathname.charAt(0) === '/') ?\n urlParsingNode.pathname :\n '/' + urlParsingNode.pathname\n };\n }\n\n originURL = resolveURL(window.location.href);\n\n /**\n * Determine if a URL shares the same origin as the current location\n *\n * @param {String} requestURL The URL to test\n * @returns {boolean} True if URL shares the same origin, otherwise false\n */\n return function isURLSameOrigin(requestURL) {\n var parsed = (utils.isString(requestURL)) ? resolveURL(requestURL) : requestURL;\n return (parsed.protocol === originURL.protocol &&\n parsed.host === originURL.host);\n };\n })() :\n\n // Non standard browser envs (web workers, react-native) lack needed support.\n (function nonStandardBrowserEnv() {\n return function isURLSameOrigin() {\n return true;\n };\n })()\n);\n\n\n//# sourceURL=webpack:///./node_modules/axios/lib/helpers/isURLSameOrigin.js?");
/***/ }),
/***/ "./node_modules/axios/lib/helpers/normalizeHeaderName.js":
/*!***************************************************************!*\
!*** ./node_modules/axios/lib/helpers/normalizeHeaderName.js ***!
\***************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
eval("\n\nvar utils = __webpack_require__(/*! ../utils */ \"./node_modules/axios/lib/utils.js\");\n\nmodule.exports = function normalizeHeaderName(headers, normalizedName) {\n utils.forEach(headers, function processHeader(value, name) {\n if (name !== normalizedName && name.toUpperCase() === normalizedName.toUpperCase()) {\n headers[normalizedName] = value;\n delete headers[name];\n }\n });\n};\n\n\n//# sourceURL=webpack:///./node_modules/axios/lib/helpers/normalizeHeaderName.js?");
/***/ }),
/***/ "./node_modules/axios/lib/helpers/parseHeaders.js":
/*!********************************************************!*\
!*** ./node_modules/axios/lib/helpers/parseHeaders.js ***!
\********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
eval("\n\nvar utils = __webpack_require__(/*! ./../utils */ \"./node_modules/axios/lib/utils.js\");\n\n// Headers whose duplicates are ignored by node\n// c.f. https://nodejs.org/api/http.html#http_message_headers\nvar ignoreDuplicateOf = [\n 'age', 'authorization', 'content-length', 'content-type', 'etag',\n 'expires', 'from', 'host', 'if-modified-since', 'if-unmodified-since',\n 'last-modified', 'location', 'max-forwards', 'proxy-authorization',\n 'referer', 'retry-after', 'user-agent'\n];\n\n/**\n * Parse headers into an object\n *\n * ```\n * Date: Wed, 27 Aug 2014 08:58:49 GMT\n * Content-Type: application/json\n * Connection: keep-alive\n * Transfer-Encoding: chunked\n * ```\n *\n * @param {String} headers Headers needing to be parsed\n * @returns {Object} Headers parsed into an object\n */\nmodule.exports = function parseHeaders(headers) {\n var parsed = {};\n var key;\n var val;\n var i;\n\n if (!headers) { return parsed; }\n\n utils.forEach(headers.split('\\n'), function parser(line) {\n i = line.indexOf(':');\n key = utils.trim(line.substr(0, i)).toLowerCase();\n val = utils.trim(line.substr(i + 1));\n\n if (key) {\n if (parsed[key] && ignoreDuplicateOf.indexOf(key) >= 0) {\n return;\n }\n if (key === 'set-cookie') {\n parsed[key] = (parsed[key] ? parsed[key] : []).concat([val]);\n } else {\n parsed[key] = parsed[key] ? parsed[key] + ', ' + val : val;\n }\n }\n });\n\n return parsed;\n};\n\n\n//# sourceURL=webpack:///./node_modules/axios/lib/helpers/parseHeaders.js?");
/***/ }),
/***/ "./node_modules/axios/lib/helpers/spread.js":
/*!**************************************************!*\
!*** ./node_modules/axios/lib/helpers/spread.js ***!
\**************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
eval("\n\n/**\n * Syntactic sugar for invoking a function and expanding an array for arguments.\n *\n * Common use case would be to use `Function.prototype.apply`.\n *\n * ```js\n * function f(x, y, z) {}\n * var args = [1, 2, 3];\n * f.apply(null, args);\n * ```\n *\n * With `spread` this example can be re-written.\n *\n * ```js\n * spread(function(x, y, z) {})([1, 2, 3]);\n * ```\n *\n * @param {Function} callback\n * @returns {Function}\n */\nmodule.exports = function spread(callback) {\n return function wrap(arr) {\n return callback.apply(null, arr);\n };\n};\n\n\n//# sourceURL=webpack:///./node_modules/axios/lib/helpers/spread.js?");
/***/ }),
/***/ "./node_modules/axios/lib/utils.js":
/*!*****************************************!*\
!*** ./node_modules/axios/lib/utils.js ***!
\*****************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
eval("\n\nvar bind = __webpack_require__(/*! ./helpers/bind */ \"./node_modules/axios/lib/helpers/bind.js\");\n\n/*global toString:true*/\n\n// utils is a library of generic helper functions non-specific to axios\n\nvar toString = Object.prototype.toString;\n\n/**\n * Determine if a value is an Array\n *\n * @param {Object} val The value to test\n * @returns {boolean} True if value is an Array, otherwise false\n */\nfunction isArray(val) {\n return toString.call(val) === '[object Array]';\n}\n\n/**\n * Determine if a value is undefined\n *\n * @param {Object} val The value to test\n * @returns {boolean} True if the value is undefined, otherwise false\n */\nfunction isUndefined(val) {\n return typeof val === 'undefined';\n}\n\n/**\n * Determine if a value is a Buffer\n *\n * @param {Object} val The value to test\n * @returns {boolean} True if value is a Buffer, otherwise false\n */\nfunction isBuffer(val) {\n return val !== null && !isUndefined(val) && val.constructor !== null && !isUndefined(val.constructor)\n && typeof val.constructor.isBuffer === 'function' && val.constructor.isBuffer(val);\n}\n\n/**\n * Determine if a value is an ArrayBuffer\n *\n * @param {Object} val The value to test\n * @returns {boolean} True if value is an ArrayBuffer, otherwise false\n */\nfunction isArrayBuffer(val) {\n return toString.call(val) === '[object ArrayBuffer]';\n}\n\n/**\n * Determine if a value is a FormData\n *\n * @param {Object} val The value to test\n * @returns {boolean} True if value is an FormData, otherwise false\n */\nfunction isFormData(val) {\n return (typeof FormData !== 'undefined') && (val instanceof FormData);\n}\n\n/**\n * Determine if a value is a view on an ArrayBuffer\n *\n * @param {Object} val The value to test\n * @returns {boolean} True if value is a view on an ArrayBuffer, otherwise false\n */\nfunction isArrayBufferView(val) {\n var result;\n if ((typeof ArrayBuffer !== 'undefined') && (ArrayBuffer.isView)) {\n result = ArrayBuffer.isView(val);\n } else {\n result = (val) && (val.buffer) && (val.buffer instanceof ArrayBuffer);\n }\n return result;\n}\n\n/**\n * Determine if a value is a String\n *\n * @param {Object} val The value to test\n * @returns {boolean} True if value is a String, otherwise false\n */\nfunction isString(val) {\n return typeof val === 'string';\n}\n\n/**\n * Determine if a value is a Number\n *\n * @param {Object} val The value to test\n * @returns {boolean} True if value is a Number, otherwise false\n */\nfunction isNumber(val) {\n return typeof val === 'number';\n}\n\n/**\n * Determine if a value is an Object\n *\n * @param {Object} val The value to test\n * @returns {boolean} True if value is an Object, otherwise false\n */\nfunction isObject(val) {\n return val !== null && typeof val === 'object';\n}\n\n/**\n * Determine if a value is a Date\n *\n * @param {Object} val The value to test\n * @returns {boolean} True if value is a Date, otherwise false\n */\nfunction isDate(val) {\n return toString.call(val) === '[object Date]';\n}\n\n/**\n * Determine if a value is a File\n *\n * @param {Object} val The value to test\n * @returns {boolean} True if value is a File, otherwise false\n */\nfunction isFile(val) {\n return toString.call(val) === '[object File]';\n}\n\n/**\n * Determine if a value is a Blob\n *\n * @param {Object} val The value to test\n * @returns {boolean} True if value is a Blob, otherwise false\n */\nfunction isBlob(val) {\n return toString.call(val) === '[object Blob]';\n}\n\n/**\n * Determine if a value is a Function\n *\n * @param {Object} val The value to test\n * @returns {boolean} True if value is a Function, otherwise false\n */\nfunction isFunction(val) {\n return toString.call(val) === '[object Function]';\n}\n\n/**\n * Determine if a value is a Stream\n *\n * @param {Object} val The value to test\n * @returns {boolean} True if value is a Stream, otherwise false\n */\nfunction isStream(val) {\n return isObject(val) && isFunction(val.pipe);\n}\n\n/**\n * Determine if a value is a URLSearchParams object\n *\n * @param {Object} val The value to test\n * @returns {boolean} True if value is a URLSearchParams object, otherwise false\n */\nfunction isURLSearchParams(val) {\n return typeof URLSearchParams !== 'undefined' && val instanceof URLSearchParams;\n}\n\n/**\n * Trim excess whitespace off the beginning and end of a string\n *\n * @param {String} str The String to trim\n * @returns {String} The String freed of excess whitespace\n */\nfunction trim(str) {\n return str.replace(/^\\s*/, '').replace(/\\s*$/, '');\n}\n\n/**\n * Determine if we're running in a standard browser environment\n *\n * This allows axios to run in a web worker, and react-native.\n * Both environments support XMLHttpRequest, but not fully standard globals.\n *\n * web workers:\n * typeof window -> undefined\n * typeof document -> undefined\n *\n * react-native:\n * navigator.product -> 'ReactNative'\n * nativescript\n * navigator.product -> 'NativeScript' or 'NS'\n */\nfunction isStandardBrowserEnv() {\n if (typeof navigator !== 'undefined' && (navigator.product === 'ReactNative' ||\n navigator.product === 'NativeScript' ||\n navigator.product === 'NS')) {\n return false;\n }\n return (\n typeof window !== 'undefined' &&\n typeof document !== 'undefined'\n );\n}\n\n/**\n * Iterate over an Array or an Object invoking a function for each item.\n *\n * If `obj` is an Array callback will be called passing\n * the value, index, and complete array for each item.\n *\n * If 'obj' is an Object callback will be called passing\n * the value, key, and complete object for each property.\n *\n * @param {Object|Array} obj The object to iterate\n * @param {Function} fn The callback to invoke for each item\n */\nfunction forEach(obj, fn) {\n // Don't bother if no value provided\n if (obj === null || typeof obj === 'undefined') {\n return;\n }\n\n // Force an array if not already something iterable\n if (typeof obj !== 'object') {\n /*eslint no-param-reassign:0*/\n obj = [obj];\n }\n\n if (isArray(obj)) {\n // Iterate over array values\n for (var i = 0, l = obj.length; i < l; i++) {\n fn.call(null, obj[i], i, obj);\n }\n } else {\n // Iterate over object keys\n for (var key in obj) {\n if (Object.prototype.hasOwnProperty.call(obj, key)) {\n fn.call(null, obj[key], key, obj);\n }\n }\n }\n}\n\n/**\n * Accepts varargs expecting each argument to be an object, then\n * immutably merges the properties of each object and returns result.\n *\n * When multiple objects contain the same key the later object in\n * the arguments list will take precedence.\n *\n * Example:\n *\n * ```js\n * var result = merge({foo: 123}, {foo: 456});\n * console.log(result.foo); // outputs 456\n * ```\n *\n * @param {Object} obj1 Object to merge\n * @returns {Object} Result of all merge properties\n */\nfunction merge(/* obj1, obj2, obj3, ... */) {\n var result = {};\n function assignValue(val, key) {\n if (typeof result[key] === 'object' && typeof val === 'object') {\n result[key] = merge(result[key], val);\n } else {\n result[key] = val;\n }\n }\n\n for (var i = 0, l = arguments.length; i < l; i++) {\n forEach(arguments[i], assignValue);\n }\n return result;\n}\n\n/**\n * Function equal to merge with the difference being that no reference\n * to original objects is kept.\n *\n * @see merge\n * @param {Object} obj1 Object to merge\n * @returns {Object} Result of all merge properties\n */\nfunction deepMerge(/* obj1, obj2, obj3, ... */) {\n var result = {};\n function assignValue(val, key) {\n if (typeof result[key] === 'object' && typeof val === 'object') {\n result[key] = deepMerge(result[key], val);\n } else if (typeof val === 'object') {\n result[key] = deepMerge({}, val);\n } else {\n result[key] = val;\n }\n }\n\n for (var i = 0, l = arguments.length; i < l; i++) {\n forEach(arguments[i], assignValue);\n }\n return result;\n}\n\n/**\n * Extends object a by mutably adding to it the properties of object b.\n *\n * @param {Object} a The object to be extended\n * @param {Object} b The object to copy properties from\n * @param {Object} thisArg The object to bind function to\n * @return {Object} The resulting value of object a\n */\nfunction extend(a, b, thisArg) {\n forEach(b, function assignValue(val, key) {\n if (thisArg && typeof val === 'function') {\n a[key] = bind(val, thisArg);\n } else {\n a[key] = val;\n }\n });\n return a;\n}\n\nmodule.exports = {\n isArray: isArray,\n isArrayBuffer: isArrayBuffer,\n isBuffer: isBuffer,\n isFormData: isFormData,\n isArrayBufferView: isArrayBufferView,\n isString: isString,\n isNumber: isNumber,\n isObject: isObject,\n isUndefined: isUndefined,\n isDate: isDate,\n isFile: isFile,\n isBlob: isBlob,\n isFunction: isFunction,\n isStream: isStream,\n isURLSearchParams: isURLSearchParams,\n isStandardBrowserEnv: isStandardBrowserEnv,\n forEach: forEach,\n merge: merge,\n deepMerge: deepMerge,\n extend: extend,\n trim: trim\n};\n\n\n//# sourceURL=webpack:///./node_modules/axios/lib/utils.js?");
/***/ }),
/***/ "./node_modules/bootstrap/dist/css/bootstrap.min.css":
/*!***********************************************************!*\
!*** ./node_modules/bootstrap/dist/css/bootstrap.min.css ***!
\***********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
eval("var api = __webpack_require__(/*! ../../../style-loader/dist/runtime/injectStylesIntoStyleTag.js */ \"./node_modules/style-loader/dist/runtime/injectStylesIntoStyleTag.js\");\n var content = __webpack_require__(/*! !../../../css-loader/dist/cjs.js!./bootstrap.min.css */ \"./node_modules/css-loader/dist/cjs.js!./node_modules/bootstrap/dist/css/bootstrap.min.css\");\n\n content = content.__esModule ? content.default : content;\n\n if (typeof content === 'string') {\n content = [[module.i, content, '']];\n }\n\nvar options = {};\n\noptions.insert = \"head\";\noptions.singleton = false;\n\nvar update = api(content, options);\n\n\n\nmodule.exports = content.locals || {};\n\n//# sourceURL=webpack:///./node_modules/bootstrap/dist/css/bootstrap.min.css?");
/***/ }),
/***/ "./node_modules/css-loader/dist/cjs.js!./node_modules/bootstrap/dist/css/bootstrap.min.css":
/*!*************************************************************************************************!*\
!*** ./node_modules/css-loader/dist/cjs.js!./node_modules/bootstrap/dist/css/bootstrap.min.css ***!
\*************************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
eval("// Imports\nvar ___CSS_LOADER_API_IMPORT___ = __webpack_require__(/*! ../../../css-loader/dist/runtime/api.js */ \"./node_modules/css-loader/dist/runtime/api.js\");\nexports = ___CSS_LOADER_API_IMPORT___(false);\n// Module\nexports.push([module.i, \"/*!\\n * Bootstrap v4.4.1 (https://getbootstrap.com/)\\n * Copyright 2011-2019 The Bootstrap Authors\\n * Copyright 2011-2019 Twitter, Inc.\\n * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)\\n */:root{--blue:#007bff;--indigo:#6610f2;--purple:#6f42c1;--pink:#e83e8c;--red:#dc3545;--orange:#fd7e14;--yellow:#ffc107;--green:#28a745;--teal:#20c997;--cyan:#17a2b8;--white:#fff;--gray:#6c757d;--gray-dark:#343a40;--primary:#007bff;--secondary:#6c757d;--success:#28a745;--info:#17a2b8;--warning:#ffc107;--danger:#dc3545;--light:#f8f9fa;--dark:#343a40;--breakpoint-xs:0;--breakpoint-sm:576px;--breakpoint-md:768px;--breakpoint-lg:992px;--breakpoint-xl:1200px;--font-family-sans-serif:-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-family-monospace:SFMono-Regular,Menlo,Monaco,Consolas,\\\"Liberation Mono\\\",\\\"Courier New\\\",monospace}*,::after,::before{box-sizing:border-box}html{font-family:sans-serif;line-height:1.15;-webkit-text-size-adjust:100%;-webkit-tap-highlight-color:transparent}article,aside,figcaption,figure,footer,header,hgroup,main,nav,section{display:block}body{margin: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;color:#212529;text-align:left;background-color:#fff}[tabindex=\\\"-1\\\"]:focus:not(:focus-visible){outline:0!important}hr{box-sizing:content-box;height:0;overflow:visible}h1,h2,h3,h4,h5,h6{margin-top:0;margin-bottom:.5rem}p{margin-top:0;margin-bottom:1rem}abbr[data-original-title],abbr[title]{text-decoration:underline;-webkit-text-decoration:underline dotted;text-decoration:underline dotted;cursor:help;border-bottom:0;-webkit-text-decoration-skip-ink:none;text-decoration-skip-ink:none}address{margin-bottom:1rem;font-style:normal;line-height:inherit}dl,ol,ul{margin-top:0;margin-bottom:1rem}ol ol,ol ul,ul ol,ul ul{margin-bottom:0}dt{font-weight:700}dd{margin-bottom:.5rem;margin-left:0}blockquote{margin:0 0 1rem}b,strong{font-weight:bolder}small{font-size:80%}sub,sup{position:relative;font-size:75%;line-height:0;vertical-align:baseline}sub{bottom:-.25em}sup{top:-.5em}a{color:#007bff;text-decoration:none;background-color:transparent}a:hover{color:#0056b3;text-decoration:underline}a:not([href]){color:inherit;text-decoration:none}a:not([href]):hover{color:inherit;text-decoration:none}code,kbd,pre,samp{font-family:SFMono-Regular,Menlo,Monaco,Consolas,\\\"Liberation Mono\\\",\\\"Courier New\\\",monospace;font-size:1em}pre{margin-top:0;margin-bottom:1rem;overflow:auto}figure{margin:0 0 1rem}img{vertical-align:middle;border-style:none}svg{overflow:hidden;vertical-align:middle}table{border-collapse:collapse}caption{padding-top:.75rem;padding-bottom:.75rem;color:#6c757d;text-align:left;caption-side:bottom}th{text-align:inherit}label{display:inline-block;margin-bottom:.5rem}button{border-radius:0}button:focus{outline:1px dotted;outline:5px auto -webkit-focus-ring-color}button,input,optgroup,select,textarea{margin:0;font-family:inherit;font-size:inherit;line-height:inherit}button,input{overflow:visible}button,select{text-transform:none}select{word-wrap:normal}[type=button],[type=reset],[type=submit],button{-webkit-appearance:button}[type=button]:not(:disabled),[type=reset]:not(:disabled),[type=submit]:not(:disabled),button:not(:disabled){cursor:pointer}[type=button]::-moz-focus-inner,[type=reset]::-moz-focus-inner,[type=submit]::-moz-focus-inner,button::-moz-focus-inner{padding:0;border-style:none}input[type=checkbox],input[type=radio]{box-sizing:border-box;padding:0}input[type=date],input[type=datetime-local],input[type=month],input[type=time]{-webkit-appearance:listbox}textarea{overflow:auto;resize:vertical}fieldset{min-width:0;padding:0;margin:0;border:0}legend{display:block;width:100%;max-width:100%;padding:0;margin-bottom:.5rem;font-size:1.5rem;line-height:inherit;color:inherit;white-space:normal}progress{vertical-align:baseline}[type=number]::-webkit-inner-spin-button,[type=number]::-webkit-outer-spin-button{height:auto}[type=search]{outline-offset:-2px;-webkit-appearance:none}[type=search]::-webkit-search-decoration{-webkit-appearance:none}::-webkit-file-upload-button{font:inherit;-webkit-appearance:button}output{display:inline-block}summary{display:list-item;cursor:pointer}template{display:none}[hidden]{display:none!important}.h1,.h2,.h3,.h4,.h5,.h6,h1,h2,h3,h4,h5,h6{margin-bottom:.5rem;font-weight:500;line-height:1.2}.h1,h1{font-size:2.5rem}.h2,h2{font-size:2rem}.h3,h3{font-size:1.75rem}.h4,h4{font-size:1.5rem}.h5,h5{font-size:1.25rem}.h6,h6{font-size:1rem}.lead{font-size:1.25rem;font-weight:300}.display-1{font-size:6rem;font-weight:300;line-height:1.2}.display-2{font-size:5.5rem;font-weight:300;line-height:1.2}.display-3{font-size:4.5rem;font-weight:300;line-height:1.2}.display-4{font-size:3.5rem;font-weight:300;line-height:1.2}hr{margin-top:1rem;margin-bottom:1rem;border:0;border-top:1px solid rgba(0,0,0,.1)}.small,small{font-size:80%;font-weight:400}.mark,mark{padding:.2em;background-color:#fcf8e3}.list-unstyled{padding-left:0;list-style:none}.list-inline{padding-left:0;list-style:none}.list-inline-item{display:inline-block}.list-inline-item:not(:last-child){margin-right:.5rem}.initialism{font-size:90%;text-transform:uppercase}.blockquote{margin-bottom:1rem;font-size:1.25rem}.blockquote-footer{display:block;font-size:80%;color:#6c757d}.blockquote-footer::before{content:\\\"\\\\2014\\\\00A0\\\"}.img-fluid{max-width:100%;height:auto}.img-thumbnail{padding:.25rem;background-color:#fff;border:1px solid #dee2e6;border-radius:.25rem;max-width:100%;height:auto}.figure{display:inline-block}.figure-img{margin-bottom:.5rem;line-height:1}.figure-caption{font-size:90%;color:#6c757d}code{font-size:87.5%;color:#e83e8c;word-wrap:break-word}a>code{color:inherit}kbd{padding:.2rem .4rem;font-size:87.5%;color:#fff;background-color:#212529;border-radius:.2rem}kbd kbd{padding:0;font-size:100%;font-weight:700}pre{display:block;font-size:87.5%;color:#212529}pre code{font-size:inherit;color:inherit;word-break:normal}.pre-scrollable{max-height:340px;overflow-y:scroll}.container{width:100%;padding-right:15px;padding-left:15px;margin-right:auto;margin-left:auto}@media (min-width:576px){.container{max-width:540px}}@media (min-width:768px){.container{max-width:720px}}@media (min-width:992px){.container{max-width:960px}}@media (min-width:1200px){.container{max-width:1140px}}.container-fluid,.container-lg,.container-md,.container-sm,.container-xl{width:100%;padding-right:15px;padding-left:15px;margin-right:auto;margin-left:auto}@media (min-width:576px){.container,.container-sm{max-width:540px}}@media (min-width:768px){.container,.container-md,.container-sm{max-width:720px}}@media (min-width:992px){.container,.container-lg,.container-md,.container-sm{max-width:960px}}@media (min-width:1200px){.container,.container-lg,.container-md,.container-sm,.container-xl{max-width:1140px}}.row{display:-ms-flexbox;display:flex;-ms-flex-wrap:wrap;flex-wrap:wrap;margin-right:-15px;margin-left:-15px}.no-gutters{margin-right:0;margin-left:0}.no-gutters>.col,.no-gutters>[class*=col-]{padding-right:0;padding-left:0}.col,.col-1,.col-10,.col-11,.col-12,.col-2,.col-3,.col-4,.col-5,.col-6,.col-7,.col-8,.col-9,.col-auto,.col-lg,.col-lg-1,.col-lg-10,.col-lg-11,.col-lg-12,.col-lg-2,.col-lg-3,.col-lg-4,.col-lg-5,.col-lg-6,.col-lg-7,.col-lg-8,.col-lg-9,.col-lg-auto,.col-md,.col-md-1,.col-md-10,.col-md-11,.col-md-12,.col-md-2,.col-md-3,.col-md-4,.col-md-5,.col-md-6,.col-md-7,.col-md-8,.col-md-9,.col-md-auto,.col-sm,.col-sm-1,.col-sm-10,.col-sm-11,.col-sm-12,.col-sm-2,.col-sm-3,.col-sm-4,.col-sm-5,.col-sm-6,.col-sm-7,.col-sm-8,.col-sm-9,.col-sm-auto,.col-xl,.col-xl-1,.col-xl-10,.col-xl-11,.col-xl-12,.col-xl-2,.col-xl-3,.col-xl-4,.col-xl-5,.col-xl-6,.col-xl-7,.col-xl-8,.col-xl-9,.col-xl-auto{position:relative;width:100%;padding-right:15px;padding-left:15px}.col{-ms-flex-preferred-size:0;flex-basis:0;-ms-flex-positive:1;flex-grow:1;max-width:100%}.row-cols-1>*{-ms-flex:0 0 100%;flex:0 0 100%;max-width:100%}.row-cols-2>*{-ms-flex:0 0 50%;flex:0 0 50%;max-width:50%}.row-cols-3>*{-ms-flex:0 0 33.333333%;flex:0 0 33.333333%;max-width:33.333333%}.row-cols-4>*{-ms-flex:0 0 25%;flex:0 0 25%;max-width:25%}.row-cols-5>*{-ms-flex:0 0 20%;flex:0 0 20%;max-width:20%}.row-cols-6>*{-ms-flex:0 0 16.666667%;flex:0 0 16.666667%;max-width:16.666667%}.col-auto{-ms-flex:0 0 auto;flex:0 0 auto;width:auto;max-width:100%}.col-1{-ms-flex:0 0 8.333333%;flex:0 0 8.333333%;max-width:8.333333%}.col-2{-ms-flex:0 0 16.666667%;flex:0 0 16.666667%;max-width:16.666667%}.col-3{-ms-flex:0 0 25%;flex:0 0 25%;max-width:25%}.col-4{-ms-flex:0 0 33.333333%;flex:0 0 33.333333%;max-width:33.333333%}.col-5{-ms-flex:0 0 41.666667%;flex:0 0 41.666667%;max-width:41.666667%}.col-6{-ms-flex:0 0 50%;flex:0 0 50%;max-width:50%}.col-7{-ms-flex:0 0 58.333333%;flex:0 0 58.333333%;max-width:58.333333%}.col-8{-ms-flex:0 0 66.666667%;flex:0 0 66.666667%;max-width:66.666667%}.col-9{-ms-flex:0 0 75%;flex:0 0 75%;max-width:75%}.col-10{-ms-flex:0 0 83.333333%;flex:0 0 83.333333%;max-width:83.333333%}.col-11{-ms-flex:0 0 91.666667%;flex:0 0 91.666667%;max-width:91.666667%}.col-12{-ms-flex:0 0 100%;flex:0 0 100%;max-width:100%}.order-first{-ms-flex-order:-1;order:-1}.order-last{-ms-flex-order:13;order:13}.order-0{-ms-flex-order:0;order:0}.order-1{-ms-flex-order:1;order:1}.order-2{-ms-flex-order:2;order:2}.order-3{-ms-flex-order:3;order:3}.order-4{-ms-flex-order:4;order:4}.order-5{-ms-flex-order:5;order:5}.order-6{-ms-flex-order:6;order:6}.order-7{-ms-flex-order:7;order:7}.order-8{-ms-flex-order:8;order:8}.order-9{-ms-flex-order:9;order:9}.order-10{-ms-flex-order:10;order:10}.order-11{-ms-flex-order:11;order:11}.order-12{-ms-flex-order:12;order:12}.offset-1{margin-left:8.333333%}.offset-2{margin-left:16.666667%}.offset-3{margin-left:25%}.offset-4{margin-left:33.333333%}.offset-5{margin-left:41.666667%}.offset-6{margin-left:50%}.offset-7{margin-left:58.333333%}.offset-8{margin-left:66.666667%}.offset-9{margin-left:75%}.offset-10{margin-left:83.333333%}.offset-11{margin-left:91.666667%}@media (min-width:576px){.col-sm{-ms-flex-preferred-size:0;flex-basis:0;-ms-flex-positive:1;flex-grow:1;max-width:100%}.row-cols-sm-1>*{-ms-flex:0 0 100%;flex:0 0 100%;max-width:100%}.row-cols-sm-2>*{-ms-flex:0 0 50%;flex:0 0 50%;max-width:50%}.row-cols-sm-3>*{-ms-flex:0 0 33.333333%;flex:0 0 33.333333%;max-width:33.333333%}.row-cols-sm-4>*{-ms-flex:0 0 25%;flex:0 0 25%;max-width:25%}.row-cols-sm-5>*{-ms-flex:0 0 20%;flex:0 0 20%;max-width:20%}.row-cols-sm-6>*{-ms-flex:0 0 16.666667%;flex:0 0 16.666667%;max-width:16.666667%}.col-sm-auto{-ms-flex:0 0 auto;flex:0 0 auto;width:auto;max-width:100%}.col-sm-1{-ms-flex:0 0 8.333333%;flex:0 0 8.333333%;max-width:8.333333%}.col-sm-2{-ms-flex:0 0 16.666667%;flex:0 0 16.666667%;max-width:16.666667%}.col-sm-3{-ms-flex:0 0 25%;flex:0 0 25%;max-width:25%}.col-sm-4{-ms-flex:0 0 33.333333%;flex:0 0 33.333333%;max-width:33.333333%}.col-sm-5{-ms-flex:0 0 41.666667%;flex:0 0 41.666667%;max-width:41.666667%}.col-sm-6{-ms-flex:0 0 50%;flex:0 0 50%;max-width:50%}.col-sm-7{-ms-flex:0 0 58.333333%;flex:0 0 58.333333%;max-width:58.333333%}.col-sm-8{-ms-flex:0 0 66.666667%;flex:0 0 66.666667%;max-width:66.666667%}.col-sm-9{-ms-flex:0 0 75%;flex:0 0 75%;max-width:75%}.col-sm-10{-ms-flex:0 0 83.333333%;flex:0 0 83.333333%;max-width:83.333333%}.col-sm-11{-ms-flex:0 0 91.666667%;flex:0 0 91.666667%;max-width:91.666667%}.col-sm-12{-ms-flex:0 0 100%;flex:0 0 100%;max-width:100%}.order-sm-first{-ms-flex-order:-1;order:-1}.order-sm-last{-ms-flex-order:13;order:13}.order-sm-0{-ms-flex-order:0;order:0}.order-sm-1{-ms-flex-order:1;order:1}.order-sm-2{-ms-flex-order:2;order:2}.order-sm-3{-ms-flex-order:3;order:3}.order-sm-4{-ms-flex-order:4;order:4}.order-sm-5{-ms-flex-order:5;order:5}.order-sm-6{-ms-flex-order:6;order:6}.order-sm-7{-ms-flex-order:7;order:7}.order-sm-8{-ms-flex-order:8;order:8}.order-sm-9{-ms-flex-order:9;order:9}.order-sm-10{-ms-flex-order:10;order:10}.order-sm-11{-ms-flex-order:11;order:11}.order-sm-12{-ms-flex-order:12;order:12}.offset-sm-0{margin-left:0}.offset-sm-1{margin-left:8.333333%}.offset-sm-2{margin-left:16.666667%}.offset-sm-3{margin-left:25%}.offset-sm-4{margin-left:33.333333%}.offset-sm-5{margin-left:41.666667%}.offset-sm-6{margin-left:50%}.offset-sm-7{margin-left:58.333333%}.offset-sm-8{margin-left:66.666667%}.offset-sm-9{margin-left:75%}.offset-sm-10{margin-left:83.333333%}.offset-sm-11{margin-left:91.666667%}}@media (min-width:768px){.col-md{-ms-flex-preferred-size:0;flex-basis:0;-ms-flex-positive:1;flex-grow:1;max-width:100%}.row-cols-md-1>*{-ms-flex:0 0 100%;flex:0 0 100%;max-width:100%}.row-cols-md-2>*{-ms-flex:0 0 50%;flex:0 0 50%;max-width:50%}.row-cols-md-3>*{-ms-flex:0 0 33.333333%;flex:0 0 33.333333%;max-width:33.333333%}.row-cols-md-4>*{-ms-flex:0 0 25%;flex:0 0 25%;max-width:25%}.row-cols-md-5>*{-ms-flex:0 0 20%;flex:0 0 20%;max-width:20%}.row-cols-md-6>*{-ms-flex:0 0 16.666667%;flex:0 0 16.666667%;max-width:16.666667%}.col-md-auto{-ms-flex:0 0 auto;flex:0 0 auto;width:auto;max-width:100%}.col-md-1{-ms-flex:0 0 8.333333%;flex:0 0 8.333333%;max-width:8.333333%}.col-md-2{-ms-flex:0 0 16.666667%;flex:0 0 16.666667%;max-width:16.666667%}.col-md-3{-ms-flex:0 0 25%;flex:0 0 25%;max-width:25%}.col-md-4{-ms-flex:0 0 33.333333%;flex:0 0 33.333333%;max-width:33.333333%}.col-md-5{-ms-flex:0 0 41.666667%;flex:0 0 41.666667%;max-width:41.666667%}.col-md-6{-ms-flex:0 0 50%;flex:0 0 50%;max-width:50%}.col-md-7{-ms-flex:0 0 58.333333%;flex:0 0 58.333333%;max-width:58.333333%}.col-md-8{-ms-flex:0 0 66.666667%;flex:0 0 66.666667%;max-width:66.666667%}.col-md-9{-ms-flex:0 0 75%;flex:0 0 75%;max-width:75%}.col-md-10{-ms-flex:0 0 83.333333%;flex:0 0 83.333333%;max-width:83.333333%}.col-md-11{-ms-flex:0 0 91.666667%;flex:0 0 91.666667%;max-width:91.666667%}.col-md-12{-ms-flex:0 0 100%;flex:0 0 100%;max-width:100%}.order-md-first{-ms-flex-order:-1;order:-1}.order-md-last{-ms-flex-order:13;order:13}.order-md-0{-ms-flex-order:0;order:0}.order-md-1{-ms-flex-order:1;order:1}.order-md-2{-ms-flex-order:2;order:2}.order-md-3{-ms-flex-order:3;order:3}.order-md-4{-ms-flex-order:4;order:4}.order-md-5{-ms-flex-order:5;order:5}.order-md-6{-ms-flex-order:6;order:6}.order-md-7{-ms-flex-order:7;order:7}.order-md-8{-ms-flex-order:8;order:8}.order-md-9{-ms-flex-order:9;order:9}.order-md-10{-ms-flex-order:10;order:10}.order-md-11{-ms-flex-order:11;order:11}.order-md-12{-ms-flex-order:12;order:12}.offset-md-0{margin-left:0}.offset-md-1{margin-left:8.333333%}.offset-md-2{margin-left:16.666667%}.offset-md-3{margin-left:25%}.offset-md-4{margin-left:33.333333%}.offset-md-5{margin-left:41.666667%}.offset-md-6{margin-left:50%}.offset-md-7{margin-left:58.333333%}.offset-md-8{margin-left:66.666667%}.offset-md-9{margin-left:75%}.offset-md-10{margin-left:83.333333%}.offset-md-11{margin-left:91.666667%}}@media (min-width:992px){.col-lg{-ms-flex-preferred-size:0;flex-basis:0;-ms-flex-positive:1;flex-grow:1;max-width:100%}.row-cols-lg-1>*{-ms-flex:0 0 100%;flex:0 0 100%;max-width:100%}.row-cols-lg-2>*{-ms-flex:0 0 50%;flex:0 0 50%;max-width:50%}.row-cols-lg-3>*{-ms-flex:0 0 33.333333%;flex:0 0 33.333333%;max-width:33.333333%}.row-cols-lg-4>*{-ms-flex:0 0 25%;flex:0 0 25%;max-width:25%}.row-cols-lg-5>*{-ms-flex:0 0 20%;flex:0 0 20%;max-width:20%}.row-cols-lg-6>*{-ms-flex:0 0 16.666667%;flex:0 0 16.666667%;max-width:16.666667%}.col-lg-auto{-ms-flex:0 0 auto;flex:0 0 auto;width:auto;max-width:100%}.col-lg-1{-ms-flex:0 0 8.333333%;flex:0 0 8.333333%;max-width:8.333333%}.col-lg-2{-ms-flex:0 0 16.666667%;flex:0 0 16.666667%;max-width:16.666667%}.col-lg-3{-ms-flex:0 0 25%;flex:0 0 25%;max-width:25%}.col-lg-4{-ms-flex:0 0 33.333333%;flex:0 0 33.333333%;max-width:33.333333%}.col-lg-5{-ms-flex:0 0 41.666667%;flex:0 0 41.666667%;max-width:41.666667%}.col-lg-6{-ms-flex:0 0 50%;flex:0 0 50%;max-width:50%}.col-lg-7{-ms-flex:0 0 58.333333%;flex:0 0 58.333333%;max-width:58.333333%}.col-lg-8{-ms-flex:0 0 66.666667%;flex:0 0 66.666667%;max-width:66.666667%}.col-lg-9{-ms-flex:0 0 75%;flex:0 0 75%;max-width:75%}.col-lg-10{-ms-flex:0 0 83.333333%;flex:0 0 83.333333%;max-width:83.333333%}.col-lg-11{-ms-flex:0 0 91.666667%;flex:0 0 91.666667%;max-width:91.666667%}.col-lg-12{-ms-flex:0 0 100%;flex:0 0 100%;max-width:100%}.order-lg-first{-ms-flex-order:-1;order:-1}.order-lg-last{-ms-flex-order:13;order:13}.order-lg-0{-ms-flex-order:0;order:0}.order-lg-1{-ms-flex-order:1;order:1}.order-lg-2{-ms-flex-order:2;order:2}.order-lg-3{-ms-flex-order:3;order:3}.order-lg-4{-ms-flex-order:4;order:4}.order-lg-5{-ms-flex-order:5;order:5}.order-lg-6{-ms-flex-order:6;order:6}.order-lg-7{-ms-flex-order:7;order:7}.order-lg-8{-ms-flex-order:8;order:8}.order-lg-9{-ms-flex-order:9;order:9}.order-lg-10{-ms-flex-order:10;order:10}.order-lg-11{-ms-flex-order:11;order:11}.order-lg-12{-ms-flex-order:12;order:12}.offset-lg-0{margin-left:0}.offset-lg-1{margin-left:8.333333%}.offset-lg-2{margin-left:16.666667%}.offset-lg-3{margin-left:25%}.offset-lg-4{margin-left:33.333333%}.offset-lg-5{margin-left:41.666667%}.offset-lg-6{margin-left:50%}.offset-lg-7{margin-left:58.333333%}.offset-lg-8{margin-left:66.666667%}.offset-lg-9{margin-left:75%}.offset-lg-10{margin-left:83.333333%}.offset-lg-11{margin-left:91.666667%}}@media (min-width:1200px){.col-xl{-ms-flex-preferred-size:0;flex-basis:0;-ms-flex-positive:1;flex-grow:1;max-width:100%}.row-cols-xl-1>*{-ms-flex:0 0 100%;flex:0 0 100%;max-width:100%}.row-cols-xl-2>*{-ms-flex:0 0 50%;flex:0 0 50%;max-width:50%}.row-cols-xl-3>*{-ms-flex:0 0 33.333333%;flex:0 0 33.333333%;max-width:33.333333%}.row-cols-xl-4>*{-ms-flex:0 0 25%;flex:0 0 25%;max-width:25%}.row-cols-xl-5>*{-ms-flex:0 0 20%;flex:0 0 20%;max-width:20%}.row-cols-xl-6>*{-ms-flex:0 0 16.666667%;flex:0 0 16.666667%;max-width:16.666667%}.col-xl-auto{-ms-flex:0 0 auto;flex:0 0 auto;width:auto;max-width:100%}.col-xl-1{-ms-flex:0 0 8.333333%;flex:0 0 8.333333%;max-width:8.333333%}.col-xl-2{-ms-flex:0 0 16.666667%;flex:0 0 16.666667%;max-width:16.666667%}.col-xl-3{-ms-flex:0 0 25%;flex:0 0 25%;max-width:25%}.col-xl-4{-ms-flex:0 0 33.333333%;flex:0 0 33.333333%;max-width:33.333333%}.col-xl-5{-ms-flex:0 0 41.666667%;flex:0 0 41.666667%;max-width:41.666667%}.col-xl-6{-ms-flex:0 0 50%;flex:0 0 50%;max-width:50%}.col-xl-7{-ms-flex:0 0 58.333333%;flex:0 0 58.333333%;max-width:58.333333%}.col-xl-8{-ms-flex:0 0 66.666667%;flex:0 0 66.666667%;max-width:66.666667%}.col-xl-9{-ms-flex:0 0 75%;flex:0 0 75%;max-width:75%}.col-xl-10{-ms-flex:0 0 83.333333%;flex:0 0 83.333333%;max-width:83.333333%}.col-xl-11{-ms-flex:0 0 91.666667%;flex:0 0 91.666667%;max-width:91.666667%}.col-xl-12{-ms-flex:0 0 100%;flex:0 0 100%;max-width:100%}.order-xl-first{-ms-flex-order:-1;order:-1}.order-xl-last{-ms-flex-order:13;order:13}.order-xl-0{-ms-flex-order:0;order:0}.order-xl-1{-ms-flex-order:1;order:1}.order-xl-2{-ms-flex-order:2;order:2}.order-xl-3{-ms-flex-order:3;order:3}.order-xl-4{-ms-flex-order:4;order:4}.order-xl-5{-ms-flex-order:5;order:5}.order-xl-6{-ms-flex-order:6;order:6}.order-xl-7{-ms-flex-order:7;order:7}.order-xl-8{-ms-flex-order:8;order:8}.order-xl-9{-ms-flex-order:9;order:9}.order-xl-10{-ms-flex-order:10;order:10}.order-xl-11{-ms-flex-order:11;order:11}.order-xl-12{-ms-flex-order:12;order:12}.offset-xl-0{margin-left:0}.offset-xl-1{margin-left:8.333333%}.offset-xl-2{margin-left:16.666667%}.offset-xl-3{margin-left:25%}.offset-xl-4{margin-left:33.333333%}.offset-xl-5{margin-left:41.666667%}.offset-xl-6{margin-left:50%}.offset-xl-7{margin-left:58.333333%}.offset-xl-8{margin-left:66.666667%}.offset-xl-9{margin-left:75%}.offset-xl-10{margin-left:83.333333%}.offset-xl-11{margin-left:91.666667%}}.table{width:100%;margin-bottom:1rem;color:#212529}.table td,.table th{padding:.75rem;vertical-align:top;border-top:1px solid #dee2e6}.table thead th{vertical-align:bottom;border-bottom:2px solid #dee2e6}.table tbody+tbody{border-top:2px solid #dee2e6}.table-sm td,.table-sm th{padding:.3rem}.table-bordered{border:1px solid #dee2e6}.table-bordered td,.table-bordered th{border:1px solid #dee2e6}.table-bordered thead td,.table-bordered thead th{border-bottom-width:2px}.table-borderless tbody+tbody,.table-borderless td,.table-borderless th,.table-borderless thead th{border:0}.table-striped tbody tr:nth-of-type(odd){background-color:rgba(0,0,0,.05)}.table-hover tbody tr:hover{color:#212529;background-color:rgba(0,0,0,.075)}.table-primary,.table-primary>td,.table-primary>th{background-color:#b8daff}.table-primary tbody+tbody,.table-primary td,.table-primary th,.table-primary thead th{border-color:#7abaff}.table-hover .table-primary:hover{background-color:#9fcdff}.table-hover .table-primary:hover>td,.table-hover .table-primary:hover>th{background-color:#9fcdff}.table-secondary,.table-secondary>td,.table-secondary>th{background-color:#d6d8db}.table-secondary tbody+tbody,.table-secondary td,.table-secondary th,.table-secondary thead th{border-color:#b3b7bb}.table-hover .table-secondary:hover{background-color:#c8cbcf}.table-hover .table-secondary:hover>td,.table-hover .table-secondary:hover>th{background-color:#c8cbcf}.table-success,.table-success>td,.table-success>th{background-color:#c3e6cb}.table-success tbody+tbody,.table-success td,.table-success th,.table-success thead th{border-color:#8fd19e}.table-hover .table-success:hover{background-color:#b1dfbb}.table-hover .table-success:hover>td,.table-hover .table-success:hover>th{background-color:#b1dfbb}.table-info,.table-info>td,.table-info>th{background-color:#bee5eb}.table-info tbody+tbody,.table-info td,.table-info th,.table-info thead th{border-color:#86cfda}.table-hover .table-info:hover{background-color:#abdde5}.table-hover .table-info:hover>td,.table-hover .table-info:hover>th{background-color:#abdde5}.table-warning,.table-warning>td,.table-warning>th{background-color:#ffeeba}.table-warning tbody+tbody,.table-warning td,.table-warning th,.table-warning thead th{border-color:#ffdf7e}.table-hover .table-warning:hover{background-color:#ffe8a1}.table-hover .table-warning:hover>td,.table-hover .table-warning:hover>th{background-color:#ffe8a1}.table-danger,.table-danger>td,.table-danger>th{background-color:#f5c6cb}.table-danger tbody+tbody,.table-danger td,.table-danger th,.table-danger thead th{border-color:#ed969e}.table-hover .table-danger:hover{background-color:#f1b0b7}.table-hover .table-danger:hover>td,.table-hover .table-danger:hover>th{background-color:#f1b0b7}.table-light,.table-light>td,.table-light>th{background-color:#fdfdfe}.table-light tbody+tbody,.table-light td,.table-light th,.table-light thead th{border-color:#fbfcfc}.table-hover .table-light:hover{background-color:#ececf6}.table-hover .table-light:hover>td,.table-hover .table-light:hover>th{background-color:#ececf6}.table-dark,.table-dark>td,.table-dark>th{background-color:#c6c8ca}.table-dark tbody+tbody,.table-dark td,.table-dark th,.table-dark thead th{border-color:#95999c}.table-hover .table-dark:hover{background-color:#b9bbbe}.table-hover .table-dark:hover>td,.table-hover .table-dark:hover>th{background-color:#b9bbbe}.table-active,.table-active>td,.table-active>th{background-color:rgba(0,0,0,.075)}.table-hover .table-active:hover{background-color:rgba(0,0,0,.075)}.table-hover .table-active:hover>td,.table-hover .table-active:hover>th{background-color:rgba(0,0,0,.075)}.table .thead-dark th{color:#fff;background-color:#343a40;border-color:#454d55}.table .thead-light th{color:#495057;background-color:#e9ecef;border-color:#dee2e6}.table-dark{color:#fff;background-color:#343a40}.table-dark td,.table-dark th,.table-dark thead th{border-color:#454d55}.table-dark.table-bordered{border:0}.table-dark.table-striped tbody tr:nth-of-type(odd){background-color:rgba(255,255,255,.05)}.table-dark.table-hover tbody tr:hover{color:#fff;background-color:rgba(255,255,255,.075)}@media (max-width:575.98px){.table-responsive-sm{display:block;width:100%;overflow-x:auto;-webkit-overflow-scrolling:touch}.table-responsive-sm>.table-bordered{border:0}}@media (max-width:767.98px){.table-responsive-md{display:block;width:100%;overflow-x:auto;-webkit-overflow-scrolling:touch}.table-responsive-md>.table-bordered{border:0}}@media (max-width:991.98px){.table-responsive-lg{display:block;width:100%;overflow-x:auto;-webkit-overflow-scrolling:touch}.table-responsive-lg>.table-bordered{border:0}}@media (max-width:1199.98px){.table-responsive-xl{display:block;width:100%;overflow-x:auto;-webkit-overflow-scrolling:touch}.table-responsive-xl>.table-bordered{border:0}}.table-responsive{display:block;width:100%;overflow-x:auto;-webkit-overflow-scrolling:touch}.table-responsive>.table-bordered{border:0}.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){.form-control{transition:none}}.form-control::-ms-expand{background-color:transparent;border:0}.form-control:-moz-focusring{color:transparent;text-shadow:0 0 0 #495057}.form-control:focus{color:#495057;background-color:#fff;border-color:#80bdff;outline:0;box-shadow:0 0 0 .2rem rgba(0,123,255,.25)}.form-control::-webkit-input-placeholder{color:#6c757d;opacity:1}.form-control::-moz-placeholder{color:#6c757d;opacity:1}.form-control:-ms-input-placeholder{color:#6c757d;opacity:1}.form-control::-ms-input-placeholder{color:#6c757d;opacity:1}.form-control::placeholder{color:#6c757d;opacity:1}.form-control:disabled,.form-control[readonly]{background-color:#e9ecef;opacity:1}select.form-control:focus::-ms-value{color:#495057;background-color:#fff}.form-control-file,.form-control-range{display:block;width:100%}.col-form-label{padding-top:calc(.375rem + 1px);padding-bottom:calc(.375rem + 1px);margin-bottom:0;font-size:inherit;line-height:1.5}.col-form-label-lg{padding-top:calc(.5rem + 1px);padding-bottom:calc(.5rem + 1px);font-size:1.25rem;line-height:1.5}.col-form-label-sm{padding-top:calc(.25rem + 1px);padding-bottom:calc(.25rem + 1px);font-size:.875rem;line-height:1.5}.form-control-plaintext{display:block;width:100%;padding:.375rem 0;margin-bottom:0;font-size:1rem;line-height:1.5;color:#212529;background-color:transparent;border:solid transparent;border-width:1px 0}.form-control-plaintext.form-control-lg,.form-control-plaintext.form-control-sm{padding-right:0;padding-left:0}.form-control-sm{height:calc(1.5em + .5rem + 2px);padding:.25rem .5rem;font-size:.875rem;line-height:1.5;border-radius:.2rem}.form-control-lg{height:calc(1.5em + 1rem + 2px);padding:.5rem 1rem;font-size:1.25rem;line-height:1.5;border-radius:.3rem}select.form-control[multiple],select.form-control[size]{height:auto}textarea.form-control{height:auto}.form-group{margin-bottom:1rem}.form-text{display:block;margin-top:.25rem}.form-row{display:-ms-flexbox;display:flex;-ms-flex-wrap:wrap;flex-wrap:wrap;margin-right:-5px;margin-left:-5px}.form-row>.col,.form-row>[class*=col-]{padding-right:5px;padding-left:5px}.form-check{position:relative;display:block;padding-left:1.25rem}.form-check-input{position:absolute;margin-top:.3rem;margin-left:-1.25rem}.form-check-input:disabled~.form-check-label,.form-check-input[disabled]~.form-check-label{color:#6c757d}.form-check-label{margin-bottom:0}.form-check-inline{display:-ms-inline-flexbox;display:inline-flex;-ms-flex-align:center;align-items:center;padding-left:0;margin-right:.75rem}.form-check-inline .form-check-input{position:static;margin-top:0;margin-right:.3125rem;margin-left:0}.valid-feedback{display:none;width:100%;margin-top:.25rem;font-size:80%;color:#28a745}.valid-tooltip{position:absolute;top:100%;z-index:5;display:none;max-width:100%;padding:.25rem .5rem;margin-top:.1rem;font-size:.875rem;line-height:1.5;color:#fff;background-color:rgba(40,167,69,.9);border-radius:.25rem}.is-valid~.valid-feedback,.is-valid~.valid-tooltip,.was-validated :valid~.valid-feedback,.was-validated :valid~.valid-tooltip{display:block}.form-control.is-valid,.was-validated .form-control:valid{border-color:#28a745;padding-right:calc(1.5em + .75rem);background-image:url(\\\"data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' width='8' height='8' viewBox='0 0 8 8'%3e%3cpath fill='%2328a745' d='M2.3 6.73L.6 4.53c-.4-1.04.46-1.4 1.1-.8l1.1 1.4 3.4-3.8c.6-.63 1.6-.27 1.2.7l-4 4.6c-.43.5-.8.4-1.1.1z'/%3e%3c/svg%3e\\\");background-repeat:no-repeat;background-position:right calc(.375em + .1875rem) center;background-size:calc(.75em + .375rem) calc(.75em + .375rem)}.form-control.is-valid:focus,.was-validated .form-control:valid:focus{border-color:#28a745;box-shadow:0 0 0 .2rem rgba(40,167,69,.25)}.was-validated textarea.form-control:valid,textarea.form-control.is-valid{padding-right:calc(1.5em + .75rem);background-position:top calc(.375em + .1875rem) right calc(.375em + .1875rem)}.custom-select.is-valid,.was-validated .custom-select:valid{border-color:#28a745;padding-right:calc(.75em + 2.3125rem);background:url(\\\"data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' width='4' height='5' viewBox='0 0 4 5'%3e%3cpath fill='%23343a40' d='M2 0L0 2h4zm0 5L0 3h4z'/%3e%3c/svg%3e\\\") no-repeat right .75rem center/8px 10px,url(\\\"data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' width='8' height='8' viewBox='0 0 8 8'%3e%3cpath fill='%2328a745' d='M2.3 6.73L.6 4.53c-.4-1.04.46-1.4 1.1-.8l1.1 1.4 3.4-3.8c.6-.63 1.6-.27 1.2.7l-4 4.6c-.43.5-.8.4-1.1.1z'/%3e%3c/svg%3e\\\") #fff no-repeat center right 1.75rem/calc(.75em + .375rem) calc(.75em + .375rem)}.custom-select.is-valid:focus,.was-validated .custom-select:valid:focus{border-color:#28a745;box-shadow:0 0 0 .2rem rgba(40,167,69,.25)}.form-check-input.is-valid~.form-check-label,.was-validated .form-check-input:valid~.form-check-label{color:#28a745}.form-check-input.is-valid~.valid-feedback,.form-check-input.is-valid~.valid-tooltip,.was-validated .form-check-input:valid~.valid-feedback,.was-validated .form-check-input:valid~.valid-tooltip{display:block}.custom-control-input.is-valid~.custom-control-label,.was-validated .custom-control-input:valid~.custom-control-label{color:#28a745}.custom-control-input.is-valid~.custom-control-label::before,.was-validated .custom-control-input:valid~.custom-control-label::before{border-color:#28a745}.custom-control-input.is-valid:checked~.custom-control-label::before,.was-validated .custom-control-input:valid:checked~.custom-control-label::before{border-color:#34ce57;background-color:#34ce57}.custom-control-input.is-valid:focus~.custom-control-label::before,.was-validated .custom-control-input:valid:focus~.custom-control-label::before{box-shadow:0 0 0 .2rem rgba(40,167,69,.25)}.custom-control-input.is-valid:focus:not(:checked)~.custom-control-label::before,.was-validated .custom-control-input:valid:focus:not(:checked)~.custom-control-label::before{border-color:#28a745}.custom-file-input.is-valid~.custom-file-label,.was-validated .custom-file-input:valid~.custom-file-label{border-color:#28a745}.custom-file-input.is-valid:focus~.custom-file-label,.was-validated .custom-file-input:valid:focus~.custom-file-label{border-color:#28a745;box-shadow:0 0 0 .2rem rgba(40,167,69,.25)}.invalid-feedback{display:none;width:100%;margin-top:.25rem;font-size:80%;color:#dc3545}.invalid-tooltip{position:absolute;top:100%;z-index:5;display:none;max-width:100%;padding:.25rem .5rem;margin-top:.1rem;font-size:.875rem;line-height:1.5;color:#fff;background-color:rgba(220,53,69,.9);border-radius:.25rem}.is-invalid~.invalid-feedback,.is-invalid~.invalid-tooltip,.was-validated :invalid~.invalid-feedback,.was-validated :invalid~.invalid-tooltip{display:block}.form-control.is-invalid,.was-validated .form-control:invalid{border-color:#dc3545;padding-right:calc(1.5em + .75rem);background-image:url(\\\"data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' width='12' height='12' fill='none' stroke='%23dc3545' viewBox='0 0 12 12'%3e%3ccircle cx='6' cy='6' r='4.5'/%3e%3cpath stroke-linejoin='round' d='M5.8 3.6h.4L6 6.5z'/%3e%3ccircle cx='6' cy='8.2' r='.6' fill='%23dc3545' stroke='none'/%3e%3c/svg%3e\\\");background-repeat:no-repeat;background-position:right calc(.375em + .1875rem) center;background-size:calc(.75em + .375rem) calc(.75em + .375rem)}.form-control.is-invalid:focus,.was-validated .form-control:invalid:focus{border-color:#dc3545;box-shadow:0 0 0 .2rem rgba(220,53,69,.25)}.was-validated textarea.form-control:invalid,textarea.form-control.is-invalid{padding-right:calc(1.5em + .75rem);background-position:top calc(.375em + .1875rem) right calc(.375em + .1875rem)}.custom-select.is-invalid,.was-validated .custom-select:invalid{border-color:#dc3545;padding-right:calc(.75em + 2.3125rem);background:url(\\\"data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' width='4' height='5' viewBox='0 0 4 5'%3e%3cpath fill='%23343a40' d='M2 0L0 2h4zm0 5L0 3h4z'/%3e%3c/svg%3e\\\") no-repeat right .75rem center/8px 10px,url(\\\"data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' width='12' height='12' fill='none' stroke='%23dc3545' viewBox='0 0 12 12'%3e%3ccircle cx='6' cy='6' r='4.5'/%3e%3cpath stroke-linejoin='round' d='M5.8 3.6h.4L6 6.5z'/%3e%3ccircle cx='6' cy='8.2' r='.6' fill='%23dc3545' stroke='none'/%3e%3c/svg%3e\\\") #fff no-repeat center right 1.75rem/calc(.75em + .375rem) calc(.75em + .375rem)}.custom-select.is-invalid:focus,.was-validated .custom-select:invalid:focus{border-color:#dc3545;box-shadow:0 0 0 .2rem rgba(220,53,69,.25)}.form-check-input.is-invalid~.form-check-label,.was-validated .form-check-input:invalid~.form-check-label{color:#dc3545}.form-check-input.is-invalid~.invalid-feedback,.form-check-input.is-invalid~.invalid-tooltip,.was-validated .form-check-input:invalid~.invalid-feedback,.was-validated .form-check-input:invalid~.invalid-tooltip{display:block}.custom-control-input.is-invalid~.custom-control-label,.was-validated .custom-control-input:invalid~.custom-control-label{color:#dc3545}.custom-control-input.is-invalid~.custom-control-label::before,.was-validated .custom-control-input:invalid~.custom-control-label::before{border-color:#dc3545}.custom-control-input.is-invalid:checked~.custom-control-label::before,.was-validated .custom-control-input:invalid:checked~.custom-control-label::before{border-color:#e4606d;background-color:#e4606d}.custom-control-input.is-invalid:focus~.custom-control-label::before,.was-validated .custom-control-input:invalid:focus~.custom-control-label::before{box-shadow:0 0 0 .2rem rgba(220,53,69,.25)}.custom-control-input.is-invalid:focus:not(:checked)~.custom-control-label::before,.was-validated .custom-control-input:invalid:focus:not(:checked)~.custom-control-label::before{border-color:#dc3545}.custom-file-input.is-invalid~.custom-file-label,.was-validated .custom-file-input:invalid~.custom-file-label{border-color:#dc3545}.custom-file-input.is-invalid:focus~.custom-file-label,.was-validated .custom-file-input:invalid:focus~.custom-file-label{border-color:#dc3545;box-shadow:0 0 0 .2rem rgba(220,53,69,.25)}.form-inline{display:-ms-flexbox;display:flex;-ms-flex-flow:row wrap;flex-flow:row wrap;-ms-flex-align:center;align-items:center}.form-inline .form-check{width:100%}@media (min-width:576px){.form-inline label{display:-ms-flexbox;display:flex;-ms-flex-align:center;align-items:center;-ms-flex-pack:center;justify-content:center;margin-bottom:0}.form-inline .form-group{display:-ms-flexbox;display:flex;-ms-flex:0 0 auto;flex:0 0 auto;-ms-flex-flow:row wrap;flex-flow:row wrap;-ms-flex-align:center;align-items:center;margin-bottom:0}.form-inline .form-control{display:inline-block;width:auto;vertical-align:middle}.form-inline .form-control-plaintext{display:inline-block}.form-inline .custom-select,.form-inline .input-group{width:auto}.form-inline .form-check{display:-ms-flexbox;display:flex;-ms-flex-align:center;align-items:center;-ms-flex-pack:center;justify-content:center;width:auto;padding-left:0}.form-inline .form-check-input{position:relative;-ms-flex-negative:0;flex-shrink:0;margin-top:0;margin-right:.25rem;margin-left:0}.form-inline .custom-control{-ms-flex-align:center;align-items:center;-ms-flex-pack:center;justify-content:center}.form-inline .custom-control-label{margin-bottom:0}}.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){.btn{transition:none}}.btn:hover{color:#212529;text-decoration:none}.btn.focus,.btn:focus{outline:0;box-shadow:0 0 0 .2rem rgba(0,123,255,.25)}.btn.disabled,.btn:disabled{opacity:.65}a.btn.disabled,fieldset:disabled a.btn{pointer-events:none}.btn-primary{color:#fff;background-color:#007bff;border-color:#007bff}.btn-primary:hover{color:#fff;background-color:#0069d9;border-color:#0062cc}.btn-primary.focus,.btn-primary:focus{color:#fff;background-color:#0069d9;border-color:#0062cc;box-shadow:0 0 0 .2rem rgba(38,143,255,.5)}.btn-primary.disabled,.btn-primary:disabled{color:#fff;background-color:#007bff;border-color:#007bff}.btn-primary:not(:disabled):not(.disabled).active,.btn-primary:not(:disabled):not(.disabled):active,.show>.btn-primary.dropdown-toggle{color:#fff;background-color:#0062cc;border-color:#005cbf}.btn-primary:not(:disabled):not(.disabled).active:focus,.btn-primary:not(:disabled):not(.disabled):active:focus,.show>.btn-primary.dropdown-toggle:focus{box-shadow:0 0 0 .2rem rgba(38,143,255,.5)}.btn-secondary{color:#fff;background-color:#6c757d;border-color:#6c757d}.btn-secondary:hover{color:#fff;background-color:#5a6268;border-color:#545b62}.btn-secondary.focus,.btn-secondary:focus{color:#fff;background-color:#5a6268;border-color:#545b62;box-shadow:0 0 0 .2rem rgba(130,138,145,.5)}.btn-secondary.disabled,.btn-secondary:disabled{color:#fff;background-color:#6c757d;border-color:#6c757d}.btn-secondary:not(:disabled):not(.disabled).active,.btn-secondary:not(:disabled):not(.disabled):active,.show>.btn-secondary.dropdown-toggle{color:#fff;background-color:#545b62;border-color:#4e555b}.btn-secondary:not(:disabled):not(.disabled).active:focus,.btn-secondary:not(:disabled):not(.disabled):active:focus,.show>.btn-secondary.dropdown-toggle:focus{box-shadow:0 0 0 .2rem rgba(130,138,145,.5)}.btn-success{color:#fff;background-color:#28a745;border-color:#28a745}.btn-success:hover{color:#fff;background-color:#218838;border-color:#1e7e34}.btn-success.focus,.btn-success:focus{color:#fff;background-color:#218838;border-color:#1e7e34;box-shadow:0 0 0 .2rem rgba(72,180,97,.5)}.btn-success.disabled,.btn-success:disabled{color:#fff;background-color:#28a745;border-color:#28a745}.btn-success:not(:disabled):not(.disabled).active,.btn-success:not(:disabled):not(.disabled):active,.show>.btn-success.dropdown-toggle{color:#fff;background-color:#1e7e34;border-color:#1c7430}.btn-success:not(:disabled):not(.disabled).active:focus,.btn-success:not(:disabled):not(.disabled):active:focus,.show>.btn-success.dropdown-toggle:focus{box-shadow:0 0 0 .2rem rgba(72,180,97,.5)}.btn-info{color:#fff;background-color:#17a2b8;border-color:#17a2b8}.btn-info:hover{color:#fff;background-color:#138496;border-color:#117a8b}.btn-info.focus,.btn-info:focus{color:#fff;background-color:#138496;border-color:#117a8b;box-shadow:0 0 0 .2rem rgba(58,176,195,.5)}.btn-info.disabled,.btn-info:disabled{color:#fff;background-color:#17a2b8;border-color:#17a2b8}.btn-info:not(:disabled):not(.disabled).active,.btn-info:not(:disabled):not(.disabled):active,.show>.btn-info.dropdown-toggle{color:#fff;background-color:#117a8b;border-color:#10707f}.btn-info:not(:disabled):not(.disabled).active:focus,.btn-info:not(:disabled):not(.disabled):active:focus,.show>.btn-info.dropdown-toggle:focus{box-shadow:0 0 0 .2rem rgba(58,176,195,.5)}.btn-warning{color:#212529;background-color:#ffc107;border-color:#ffc107}.btn-warning:hover{color:#212529;background-color:#e0a800;border-color:#d39e00}.btn-warning.focus,.btn-warning:focus{color:#212529;background-color:#e0a800;border-color:#d39e00;box-shadow:0 0 0 .2rem rgba(222,170,12,.5)}.btn-warning.disabled,.btn-warning:disabled{color:#212529;background-color:#ffc107;border-color:#ffc107}.btn-warning:not(:disabled):not(.disabled).active,.btn-warning:not(:disabled):not(.disabled):active,.show>.btn-warning.dropdown-toggle{color:#212529;background-color:#d39e00;border-color:#c69500}.btn-warning:not(:disabled):not(.disabled).active:focus,.btn-warning:not(:disabled):not(.disabled):active:focus,.show>.btn-warning.dropdown-toggle:focus{box-shadow:0 0 0 .2rem rgba(222,170,12,.5)}.btn-danger{color:#fff;background-color:#dc3545;border-color:#dc3545}.btn-danger:hover{color:#fff;background-color:#c82333;border-color:#bd2130}.btn-danger.focus,.btn-danger:focus{color:#fff;background-color:#c82333;border-color:#bd2130;box-shadow:0 0 0 .2rem rgba(225,83,97,.5)}.btn-danger.disabled,.btn-danger:disabled{color:#fff;background-color:#dc3545;border-color:#dc3545}.btn-danger:not(:disabled):not(.disabled).active,.btn-danger:not(:disabled):not(.disabled):active,.show>.btn-danger.dropdown-toggle{color:#fff;background-color:#bd2130;border-color:#b21f2d}.btn-danger:not(:disabled):not(.disabled).active:focus,.btn-danger:not(:disabled):not(.disabled):active:focus,.show>.btn-danger.dropdown-toggle:focus{box-shadow:0 0 0 .2rem rgba(225,83,97,.5)}.btn-light{color:#212529;background-color:#f8f9fa;border-color:#f8f9fa}.btn-light:hover{color:#212529;background-color:#e2e6ea;border-color:#dae0e5}.btn-light.focus,.btn-light:focus{color:#212529;background-color:#e2e6ea;border-color:#dae0e5;box-shadow:0 0 0 .2rem rgba(216,217,219,.5)}.btn-light.disabled,.btn-light:disabled{color:#212529;background-color:#f8f9fa;border-color:#f8f9fa}.btn-light:not(:disabled):not(.disabled).active,.btn-light:not(:disabled):not(.disabled):active,.show>.btn-light.dropdown-toggle{color:#212529;background-color:#dae0e5;border-color:#d3d9df}.btn-light:not(:disabled):not(.disabled).active:focus,.btn-light:not(:disabled):not(.disabled):active:focus,.show>.btn-light.dropdown-toggle:focus{box-shadow:0 0 0 .2rem rgba(216,217,219,.5)}.btn-dark{color:#fff;background-color:#343a40;border-color:#343a40}.btn-dark:hover{color:#fff;background-color:#23272b;border-color:#1d2124}.btn-dark.focus,.btn-dark:focus{color:#fff;background-color:#23272b;border-color:#1d2124;box-shadow:0 0 0 .2rem rgba(82,88,93,.5)}.btn-dark.disabled,.btn-dark:disabled{color:#fff;background-color:#343a40;border-color:#343a40}.btn-dark:not(:disabled):not(.disabled).active,.btn-dark:not(:disabled):not(.disabled):active,.show>.btn-dark.dropdown-toggle{color:#fff;background-color:#1d2124;border-color:#171a1d}.btn-dark:not(:disabled):not(.disabled).active:focus,.btn-dark:not(:disabled):not(.disabled):active:focus,.show>.btn-dark.dropdown-toggle:focus{box-shadow:0 0 0 .2rem rgba(82,88,93,.5)}.btn-outline-primary{color:#007bff;border-color:#007bff}.btn-outline-primary:hover{color:#fff;background-color:#007bff;border-color:#007bff}.btn-outline-primary.focus,.btn-outline-primary:focus{box-shadow:0 0 0 .2rem rgba(0,123,255,.5)}.btn-outline-primary.disabled,.btn-outline-primary:disabled{color:#007bff;background-color:transparent}.btn-outline-primary:not(:disabled):not(.disabled).active,.btn-outline-primary:not(:disabled):not(.disabled):active,.show>.btn-outline-primary.dropdown-toggle{color:#fff;background-color:#007bff;border-color:#007bff}.btn-outline-primary:not(:disabled):not(.disabled).active:focus,.btn-outline-primary:not(:disabled):not(.disabled):active:focus,.show>.btn-outline-primary.dropdown-toggle:focus{box-shadow:0 0 0 .2rem rgba(0,123,255,.5)}.btn-outline-secondary{color:#6c757d;border-color:#6c757d}.btn-outline-secondary:hover{color:#fff;background-color:#6c757d;border-color:#6c757d}.btn-outline-secondary.focus,.btn-outline-secondary:focus{box-shadow:0 0 0 .2rem rgba(108,117,125,.5)}.btn-outline-secondary.disabled,.btn-outline-secondary:disabled{color:#6c757d;background-color:transparent}.btn-outline-secondary:not(:disabled):not(.disabled).active,.btn-outline-secondary:not(:disabled):not(.disabled):active,.show>.btn-outline-secondary.dropdown-toggle{color:#fff;background-color:#6c757d;border-color:#6c757d}.btn-outline-secondary:not(:disabled):not(.disabled).active:focus,.btn-outline-secondary:not(:disabled):not(.disabled):active:focus,.show>.btn-outline-secondary.dropdown-toggle:focus{box-shadow:0 0 0 .2rem rgba(108,117,125,.5)}.btn-outline-success{color:#28a745;border-color:#28a745}.btn-outline-success:hover{color:#fff;background-color:#28a745;border-color:#28a745}.btn-outline-success.focus,.btn-outline-success:focus{box-shadow:0 0 0 .2rem rgba(40,167,69,.5)}.btn-outline-success.disabled,.btn-outline-success:disabled{color:#28a745;background-color:transparent}.btn-outline-success:not(:disabled):not(.disabled).active,.btn-outline-success:not(:disabled):not(.disabled):active,.show>.btn-outline-success.dropdown-toggle{color:#fff;background-color:#28a745;border-color:#28a745}.btn-outline-success:not(:disabled):not(.disabled).active:focus,.btn-outline-success:not(:disabled):not(.disabled):active:focus,.show>.btn-outline-success.dropdown-toggle:focus{box-shadow:0 0 0 .2rem rgba(40,167,69,.5)}.btn-outline-info{color:#17a2b8;border-color:#17a2b8}.btn-outline-info:hover{color:#fff;background-color:#17a2b8;border-color:#17a2b8}.btn-outline-info.focus,.btn-outline-info:focus{box-shadow:0 0 0 .2rem rgba(23,162,184,.5)}.btn-outline-info.disabled,.btn-outline-info:disabled{color:#17a2b8;background-color:transparent}.btn-outline-info:not(:disabled):not(.disabled).active,.btn-outline-info:not(:disabled):not(.disabled):active,.show>.btn-outline-info.dropdown-toggle{color:#fff;background-color:#17a2b8;border-color:#17a2b8}.btn-outline-info:not(:disabled):not(.disabled).active:focus,.btn-outline-info:not(:disabled):not(.disabled):active:focus,.show>.btn-outline-info.dropdown-toggle:focus{box-shadow:0 0 0 .2rem rgba(23,162,184,.5)}.btn-outline-warning{color:#ffc107;border-color:#ffc107}.btn-outline-warning:hover{color:#212529;background-color:#ffc107;border-color:#ffc107}.btn-outline-warning.focus,.btn-outline-warning:focus{box-shadow:0 0 0 .2rem rgba(255,193,7,.5)}.btn-outline-warning.disabled,.btn-outline-warning:disabled{color:#ffc107;background-color:transparent}.btn-outline-warning:not(:disabled):not(.disabled).active,.btn-outline-warning:not(:disabled):not(.disabled):active,.show>.btn-outline-warning.dropdown-toggle{color:#212529;background-color:#ffc107;border-color:#ffc107}.btn-outline-warning:not(:disabled):not(.disabled).active:focus,.btn-outline-warning:not(:disabled):not(.disabled):active:focus,.show>.btn-outline-warning.dropdown-toggle:focus{box-shadow:0 0 0 .2rem rgba(255,193,7,.5)}.btn-outline-danger{color:#dc3545;border-color:#dc3545}.btn-outline-danger:hover{color:#fff;background-color:#dc3545;border-color:#dc3545}.btn-outline-danger.focus,.btn-outline-danger:focus{box-shadow:0 0 0 .2rem rgba(220,53,69,.5)}.btn-outline-danger.disabled,.btn-outline-danger:disabled{color:#dc3545;background-color:transparent}.btn-outline-danger:not(:disabled):not(.disabled).active,.btn-outline-danger:not(:disabled):not(.disabled):active,.show>.btn-outline-danger.dropdown-toggle{color:#fff;background-color:#dc3545;border-color:#dc3545}.btn-outline-danger:not(:disabled):not(.disabled).active:focus,.btn-outline-danger:not(:disabled):not(.disabled):active:focus,.show>.btn-outline-danger.dropdown-toggle:focus{box-shadow:0 0 0 .2rem rgba(220,53,69,.5)}.btn-outline-light{color:#f8f9fa;border-color:#f8f9fa}.btn-outline-light:hover{color:#212529;background-color:#f8f9fa;border-color:#f8f9fa}.btn-outline-light.focus,.btn-outline-light:focus{box-shadow:0 0 0 .2rem rgba(248,249,250,.5)}.btn-outline-light.disabled,.btn-outline-light:disabled{color:#f8f9fa;background-color:transparent}.btn-outline-light:not(:disabled):not(.disabled).active,.btn-outline-light:not(:disabled):not(.disabled):active,.show>.btn-outline-light.dropdown-toggle{color:#212529;background-color:#f8f9fa;border-color:#f8f9fa}.btn-outline-light:not(:disabled):not(.disabled).active:focus,.btn-outline-light:not(:disabled):not(.disabled):active:focus,.show>.btn-outline-light.dropdown-toggle:focus{box-shadow:0 0 0 .2rem rgba(248,249,250,.5)}.btn-outline-dark{color:#343a40;border-color:#343a40}.btn-outline-dark:hover{color:#fff;background-color:#343a40;border-color:#343a40}.btn-outline-dark.focus,.btn-outline-dark:focus{box-shadow:0 0 0 .2rem rgba(52,58,64,.5)}.btn-outline-dark.disabled,.btn-outline-dark:disabled{color:#343a40;background-color:transparent}.btn-outline-dark:not(:disabled):not(.disabled).active,.btn-outline-dark:not(:disabled):not(.disabled):active,.show>.btn-outline-dark.dropdown-toggle{color:#fff;background-color:#343a40;border-color:#343a40}.btn-outline-dark:not(:disabled):not(.disabled).active:focus,.btn-outline-dark:not(:disabled):not(.disabled):active:focus,.show>.btn-outline-dark.dropdown-toggle:focus{box-shadow:0 0 0 .2rem rgba(52,58,64,.5)}.btn-link{font-weight:400;color:#007bff;text-decoration:none}.btn-link:hover{color:#0056b3;text-decoration:underline}.btn-link.focus,.btn-link:focus{text-decoration:underline;box-shadow:none}.btn-link.disabled,.btn-link:disabled{color:#6c757d;pointer-events:none}.btn-group-lg>.btn,.btn-lg{padding:.5rem 1rem;font-size:1.25rem;line-height:1.5;border-radius:.3rem}.btn-group-sm>.btn,.btn-sm{padding:.25rem .5rem;font-size:.875rem;line-height:1.5;border-radius:.2rem}.btn-block{display:block;width:100%}.btn-block+.btn-block{margin-top:.5rem}input[type=button].btn-block,input[type=reset].btn-block,input[type=submit].btn-block{width:100%}.fade{transition:opacity .15s linear}@media (prefers-reduced-motion:reduce){.fade{transition:none}}.fade:not(.show){opacity:0}.collapse:not(.show){display:none}.collapsing{position:relative;height:0;overflow:hidden;transition:height .35s ease}@media (prefers-reduced-motion:reduce){.collapsing{transition:none}}.dropdown,.dropleft,.dropright,.dropup{position:relative}.dropdown-toggle{white-space:nowrap}.dropdown-toggle::after{display:inline-block;margin-left:.255em;vertical-align:.255em;content:\\\"\\\";border-top:.3em solid;border-right:.3em solid transparent;border-bottom:0;border-left:.3em solid transparent}.dropdown-toggle:empty::after{margin-left:0}.dropdown-menu{position:absolute;top:100%;left:0;z-index:1000;display:none;float:left;min-width:10rem;padding:.5rem 0;margin:.125rem 0 0;font-size:1rem;color:#212529;text-align:left;list-style:none;background-color:#fff;background-clip:padding-box;border:1px solid rgba(0,0,0,.15);border-radius:.25rem}.dropdown-menu-left{right:auto;left:0}.dropdown-menu-right{right:0;left:auto}@media (min-width:576px){.dropdown-menu-sm-left{right:auto;left:0}.dropdown-menu-sm-right{right:0;left:auto}}@media (min-width:768px){.dropdown-menu-md-left{right:auto;left:0}.dropdown-menu-md-right{right:0;left:auto}}@media (min-width:992px){.dropdown-menu-lg-left{right:auto;left:0}.dropdown-menu-lg-right{right:0;left:auto}}@media (min-width:1200px){.dropdown-menu-xl-left{right:auto;left:0}.dropdown-menu-xl-right{right:0;left:auto}}.dropup .dropdown-menu{top:auto;bottom:100%;margin-top:0;margin-bottom:.125rem}.dropup .dropdown-toggle::after{display:inline-block;margin-left:.255em;vertical-align:.255em;content:\\\"\\\";border-top:0;border-right:.3em solid transparent;border-bottom:.3em solid;border-left:.3em solid transparent}.dropup .dropdown-toggle:empty::after{margin-left:0}.dropright .dropdown-menu{top:0;right:auto;left:100%;margin-top:0;margin-left:.125rem}.dropright .dropdown-toggle::after{display:inline-block;margin-left:.255em;vertical-align:.255em;content:\\\"\\\";border-top:.3em solid transparent;border-right:0;border-bottom:.3em solid transparent;border-left:.3em solid}.dropright .dropdown-toggle:empty::after{margin-left:0}.dropright .dropdown-toggle::after{vertical-align:0}.dropleft .dropdown-menu{top:0;right:100%;left:auto;margin-top:0;margin-right:.125rem}.dropleft .dropdown-toggle::after{display:inline-block;margin-left:.255em;vertical-align:.255em;content:\\\"\\\"}.dropleft .dropdown-toggle::after{display:none}.dropleft .dropdown-toggle::before{display:inline-block;margin-right:.255em;vertical-align:.255em;content:\\\"\\\";border-top:.3em solid transparent;border-right:.3em solid;border-bottom:.3em solid transparent}.dropleft .dropdown-toggle:empty::after{margin-left:0}.dropleft .dropdown-toggle::before{vertical-align:0}.dropdown-menu[x-placement^=bottom],.dropdown-menu[x-placement^=left],.dropdown-menu[x-placement^=right],.dropdown-menu[x-placement^=top]{right:auto;bottom:auto}.dropdown-divider{height:0;margin:.5rem 0;overflow:hidden;border-top:1px solid #e9ecef}.dropdown-item{display:block;width:100%;padding:.25rem 1.5rem;clear:both;font-weight:400;color:#212529;text-align:inherit;white-space:nowrap;background-color:transparent;border:0}.dropdown-item:focus,.dropdown-item:hover{color:#16181b;text-decoration:none;background-color:#f8f9fa}.dropdown-item.active,.dropdown-item:active{color:#fff;text-decoration:none;background-color:#007bff}.dropdown-item.disabled,.dropdown-item:disabled{color:#6c757d;pointer-events:none;background-color:transparent}.dropdown-menu.show{display:block}.dropdown-header{display:block;padding:.5rem 1.5rem;margin-bottom:0;font-size:.875rem;color:#6c757d;white-space:nowrap}.dropdown-item-text{display:block;padding:.25rem 1.5rem;color:#212529}.btn-group,.btn-group-vertical{position:relative;display:-ms-inline-flexbox;display:inline-flex;vertical-align:middle}.btn-group-vertical>.btn,.btn-group>.btn{position:relative;-ms-flex:1 1 auto;flex:1 1 auto}.btn-group-vertical>.btn:hover,.btn-group>.btn:hover{z-index:1}.btn-group-vertical>.btn.active,.btn-group-vertical>.btn:active,.btn-group-vertical>.btn:focus,.btn-group>.btn.active,.btn-group>.btn:active,.btn-group>.btn:focus{z-index:1}.btn-toolbar{display:-ms-flexbox;display:flex;-ms-flex-wrap:wrap;flex-wrap:wrap;-ms-flex-pack:start;justify-content:flex-start}.btn-toolbar .input-group{width:auto}.btn-group>.btn-group:not(:first-child),.btn-group>.btn:not(:first-child){margin-left:-1px}.btn-group>.btn-group:not(:last-child)>.btn,.btn-group>.btn:not(:last-child):not(.dropdown-toggle){border-top-right-radius:0;border-bottom-right-radius:0}.btn-group>.btn-group:not(:first-child)>.btn,.btn-group>.btn:not(:first-child){border-top-left-radius:0;border-bottom-left-radius:0}.dropdown-toggle-split{padding-right:.5625rem;padding-left:.5625rem}.dropdown-toggle-split::after,.dropright .dropdown-toggle-split::after,.dropup .dropdown-toggle-split::after{margin-left:0}.dropleft .dropdown-toggle-split::before{margin-right:0}.btn-group-sm>.btn+.dropdown-toggle-split,.btn-sm+.dropdown-toggle-split{padding-right:.375rem;padding-left:.375rem}.btn-group-lg>.btn+.dropdown-toggle-split,.btn-lg+.dropdown-toggle-split{padding-right:.75rem;padding-left:.75rem}.btn-group-vertical{-ms-flex-direction:column;flex-direction:column;-ms-flex-align:start;align-items:flex-start;-ms-flex-pack:center;justify-content:center}.btn-group-vertical>.btn,.btn-group-vertical>.btn-group{width:100%}.btn-group-vertical>.btn-group:not(:first-child),.btn-group-vertical>.btn:not(:first-child){margin-top:-1px}.btn-group-vertical>.btn-group:not(:last-child)>.btn,.btn-group-vertical>.btn:not(:last-child):not(.dropdown-toggle){border-bottom-right-radius:0;border-bottom-left-radius:0}.btn-group-vertical>.btn-group:not(:first-child)>.btn,.btn-group-vertical>.btn:not(:first-child){border-top-left-radius:0;border-top-right-radius:0}.btn-group-toggle>.btn,.btn-group-toggle>.btn-group>.btn{margin-bottom:0}.btn-group-toggle>.btn input[type=checkbox],.btn-group-toggle>.btn input[type=radio],.btn-group-toggle>.btn-group>.btn input[type=checkbox],.btn-group-toggle>.btn-group>.btn input[type=radio]{position:absolute;clip:rect(0,0,0,0);pointer-events:none}.input-group{position:relative;display:-ms-flexbox;display:flex;-ms-flex-wrap:wrap;flex-wrap:wrap;-ms-flex-align:stretch;align-items:stretch;width:100%}.input-group>.custom-file,.input-group>.custom-select,.input-group>.form-control,.input-group>.form-control-plaintext{position:relative;-ms-flex:1 1 0%;flex:1 1 0%;min-width:0;margin-bottom:0}.input-group>.custom-file+.custom-file,.input-group>.custom-file+.custom-select,.input-group>.custom-file+.form-control,.input-group>.custom-select+.custom-file,.input-group>.custom-select+.custom-select,.input-group>.custom-select+.form-control,.input-group>.form-control+.custom-file,.input-group>.form-control+.custom-select,.input-group>.form-control+.form-control,.input-group>.form-control-plaintext+.custom-file,.input-group>.form-control-plaintext+.custom-select,.input-group>.form-control-plaintext+.form-control{margin-left:-1px}.input-group>.custom-file .custom-file-input:focus~.custom-file-label,.input-group>.custom-select:focus,.input-group>.form-control:focus{z-index:3}.input-group>.custom-file .custom-file-input:focus{z-index:4}.input-group>.custom-select:not(:last-child),.input-group>.form-control:not(:last-child){border-top-right-radius:0;border-bottom-right-radius:0}.input-group>.custom-select:not(:first-child),.input-group>.form-control:not(:first-child){border-top-left-radius:0;border-bottom-left-radius:0}.input-group>.custom-file{display:-ms-flexbox;display:flex;-ms-flex-align:center;align-items:center}.input-group>.custom-file:not(:last-child) .custom-file-label,.input-group>.custom-file:not(:last-child) .custom-file-label::after{border-top-right-radius:0;border-bottom-right-radius:0}.input-group>.custom-file:not(:first-child) .custom-file-label{border-top-left-radius:0;border-bottom-left-radius:0}.input-group-append,.input-group-prepend{display:-ms-flexbox;display:flex}.input-group-append .btn,.input-group-prepend .btn{position:relative;z-index:2}.input-group-append .btn:focus,.input-group-prepend .btn:focus{z-index:3}.input-group-append .btn+.btn,.input-group-append .btn+.input-group-text,.input-group-append .input-group-text+.btn,.input-group-append .input-group-text+.input-group-text,.input-group-prepend .btn+.btn,.input-group-prepend .btn+.input-group-text,.input-group-prepend .input-group-text+.btn,.input-group-prepend .input-group-text+.input-group-text{margin-left:-1px}.input-group-prepend{margin-right:-1px}.input-group-append{margin-left:-1px}.input-group-text{display:-ms-flexbox;display:flex;-ms-flex-align:center;align-items:center;padding:.375rem .75rem;margin-bottom:0;font-size:1rem;font-weight:400;line-height:1.5;color:#495057;text-align:center;white-space:nowrap;background-color:#e9ecef;border:1px solid #ced4da;border-radius:.25rem}.input-group-text input[type=checkbox],.input-group-text input[type=radio]{margin-top:0}.input-group-lg>.custom-select,.input-group-lg>.form-control:not(textarea){height:calc(1.5em + 1rem + 2px)}.input-group-lg>.custom-select,.input-group-lg>.form-control,.input-group-lg>.input-group-append>.btn,.input-group-lg>.input-group-append>.input-group-text,.input-group-lg>.input-group-prepend>.btn,.input-group-lg>.input-group-prepend>.input-group-text{padding:.5rem 1rem;font-size:1.25rem;line-height:1.5;border-radius:.3rem}.input-group-sm>.custom-select,.input-group-sm>.form-control:not(textarea){height:calc(1.5em + .5rem + 2px)}.input-group-sm>.custom-select,.input-group-sm>.form-control,.input-group-sm>.input-group-append>.btn,.input-group-sm>.input-group-append>.input-group-text,.input-group-sm>.input-group-prepend>.btn,.input-group-sm>.input-group-prepend>.input-group-text{padding:.25rem .5rem;font-size:.875rem;line-height:1.5;border-radius:.2rem}.input-group-lg>.custom-select,.input-group-sm>.custom-select{padding-right:1.75rem}.input-group>.input-group-append:last-child>.btn:not(:last-child):not(.dropdown-toggle),.input-group>.input-group-append:last-child>.input-group-text:not(:last-child),.input-group>.input-group-append:not(:last-child)>.btn,.input-group>.input-group-append:not(:last-child)>.input-group-text,.input-group>.input-group-prepend>.btn,.input-group>.input-group-prepend>.input-group-text{border-top-right-radius:0;border-bottom-right-radius:0}.input-group>.input-group-append>.btn,.input-group>.input-group-append>.input-group-text,.input-group>.input-group-prepend:first-child>.btn:not(:first-child),.input-group>.input-group-prepend:first-child>.input-group-text:not(:first-child),.input-group>.input-group-prepend:not(:first-child)>.btn,.input-group>.input-group-prepend:not(:first-child)>.input-group-text{border-top-left-radius:0;border-bottom-left-radius:0}.custom-control{position:relative;display:block;min-height:1.5rem;padding-left:1.5rem}.custom-control-inline{display:-ms-inline-flexbox;display:inline-flex;margin-right:1rem}.custom-control-input{position:absolute;left:0;z-index:-1;width:1rem;height:1.25rem;opacity:0}.custom-control-input:checked~.custom-control-label::before{color:#fff;border-color:#007bff;background-color:#007bff}.custom-control-input:focus~.custom-control-label::before{box-shadow:0 0 0 .2rem rgba(0,123,255,.25)}.custom-control-input:focus:not(:checked)~.custom-control-label::before{border-color:#80bdff}.custom-control-input:not(:disabled):active~.custom-control-label::before{color:#fff;background-color:#b3d7ff;border-color:#b3d7ff}.custom-control-input:disabled~.custom-control-label,.custom-control-input[disabled]~.custom-control-label{color:#6c757d}.custom-control-input:disabled~.custom-control-label::before,.custom-control-input[disabled]~.custom-control-label::before{background-color:#e9ecef}.custom-control-label{position:relative;margin-bottom:0;vertical-align:top}.custom-control-label::before{position:absolute;top:.25rem;left:-1.5rem;display:block;width:1rem;height:1rem;pointer-events:none;content:\\\"\\\";background-color:#fff;border:#adb5bd solid 1px}.custom-control-label::after{position:absolute;top:.25rem;left:-1.5rem;display:block;width:1rem;height:1rem;content:\\\"\\\";background:no-repeat 50%/50% 50%}.custom-checkbox .custom-control-label::before{border-radius:.25rem}.custom-checkbox .custom-control-input:checked~.custom-control-label::after{background-image:url(\\\"data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' width='8' height='8' viewBox='0 0 8 8'%3e%3cpath fill='%23fff' d='M6.564.75l-3.59 3.612-1.538-1.55L0 4.26l2.974 2.99L8 2.193z'/%3e%3c/svg%3e\\\")}.custom-checkbox .custom-control-input:indeterminate~.custom-control-label::before{border-color:#007bff;background-color:#007bff}.custom-checkbox .custom-control-input:indeterminate~.custom-control-label::after{background-image:url(\\\"data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' width='4' height='4' viewBox='0 0 4 4'%3e%3cpath stroke='%23fff' d='M0 2h4'/%3e%3c/svg%3e\\\")}.custom-checkbox .custom-control-input:disabled:checked~.custom-control-label::before{background-color:rgba(0,123,255,.5)}.custom-checkbox .custom-control-input:disabled:indeterminate~.custom-control-label::before{background-color:rgba(0,123,255,.5)}.custom-radio .custom-control-label::before{border-radius:50%}.custom-radio .custom-control-input:checked~.custom-control-label::after{background-image:url(\\\"data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' width='12' height='12' viewBox='-4 -4 8 8'%3e%3ccircle r='3' fill='%23fff'/%3e%3c/svg%3e\\\")}.custom-radio .custom-control-input:disabled:checked~.custom-control-label::before{background-color:rgba(0,123,255,.5)}.custom-switch{padding-left:2.25rem}.custom-switch .custom-control-label::before{left:-2.25rem;width:1.75rem;pointer-events:all;border-radius:.5rem}.custom-switch .custom-control-label::after{top:calc(.25rem + 2px);left:calc(-2.25rem + 2px);width:calc(1rem - 4px);height:calc(1rem - 4px);background-color:#adb5bd;border-radius:.5rem;transition:background-color .15s ease-in-out,border-color .15s ease-in-out,box-shadow .15s ease-in-out,-webkit-transform .15s ease-in-out;transition:transform .15s ease-in-out,background-color .15s ease-in-out,border-color .15s ease-in-out,box-shadow .15s ease-in-out;transition:transform .15s ease-in-out,background-color .15s ease-in-out,border-color .15s ease-in-out,box-shadow .15s ease-in-out,-webkit-transform .15s ease-in-out}@media (prefers-reduced-motion:reduce){.custom-switch .custom-control-label::after{transition:none}}.custom-switch .custom-control-input:checked~.custom-control-label::after{background-color:#fff;-webkit-transform:translateX(.75rem);transform:translateX(.75rem)}.custom-switch .custom-control-input:disabled:checked~.custom-control-label::before{background-color:rgba(0,123,255,.5)}.custom-select{display:inline-block;width:100%;height:calc(1.5em + .75rem + 2px);padding:.375rem 1.75rem .375rem .75rem;font-size:1rem;font-weight:400;line-height:1.5;color:#495057;vertical-align:middle;background:#fff url(\\\"data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' width='4' height='5' viewBox='0 0 4 5'%3e%3cpath fill='%23343a40' d='M2 0L0 2h4zm0 5L0 3h4z'/%3e%3c/svg%3e\\\") no-repeat right .75rem center/8px 10px;border:1px solid #ced4da;border-radius:.25rem;-webkit-appearance:none;-moz-appearance:none;appearance:none}.custom-select:focus{border-color:#80bdff;outline:0;box-shadow:0 0 0 .2rem rgba(0,123,255,.25)}.custom-select:focus::-ms-value{color:#495057;background-color:#fff}.custom-select[multiple],.custom-select[size]:not([size=\\\"1\\\"]){height:auto;padding-right:.75rem;background-image:none}.custom-select:disabled{color:#6c757d;background-color:#e9ecef}.custom-select::-ms-expand{display:none}.custom-select:-moz-focusring{color:transparent;text-shadow:0 0 0 #495057}.custom-select-sm{height:calc(1.5em + .5rem + 2px);padding-top:.25rem;padding-bottom:.25rem;padding-left:.5rem;font-size:.875rem}.custom-select-lg{height:calc(1.5em + 1rem + 2px);padding-top:.5rem;padding-bottom:.5rem;padding-left:1rem;font-size:1.25rem}.custom-file{position:relative;display:inline-block;width:100%;height:calc(1.5em + .75rem + 2px);margin-bottom:0}.custom-file-input{position:relative;z-index:2;width:100%;height:calc(1.5em + .75rem + 2px);margin:0;opacity:0}.custom-file-input:focus~.custom-file-label{border-color:#80bdff;box-shadow:0 0 0 .2rem rgba(0,123,255,.25)}.custom-file-input:disabled~.custom-file-label,.custom-file-input[disabled]~.custom-file-label{background-color:#e9ecef}.custom-file-input:lang(en)~.custom-file-label::after{content:\\\"Browse\\\"}.custom-file-input~.custom-file-label[data-browse]::after{content:attr(data-browse)}.custom-file-label{position:absolute;top:0;right:0;left:0;z-index:1;height:calc(1.5em + .75rem + 2px);padding:.375rem .75rem;font-weight:400;line-height:1.5;color:#495057;background-color:#fff;border:1px solid #ced4da;border-radius:.25rem}.custom-file-label::after{position:absolute;top:0;right:0;bottom:0;z-index:3;display:block;height:calc(1.5em + .75rem);padding:.375rem .75rem;line-height:1.5;color:#495057;content:\\\"Browse\\\";background-color:#e9ecef;border-left:inherit;border-radius:0 .25rem .25rem 0}.custom-range{width:100%;height:1.4rem;padding:0;background-color:transparent;-webkit-appearance:none;-moz-appearance:none;appearance:none}.custom-range:focus{outline:0}.custom-range:focus::-webkit-slider-thumb{box-shadow:0 0 0 1px #fff,0 0 0 .2rem rgba(0,123,255,.25)}.custom-range:focus::-moz-range-thumb{box-shadow:0 0 0 1px #fff,0 0 0 .2rem rgba(0,123,255,.25)}.custom-range:focus::-ms-thumb{box-shadow:0 0 0 1px #fff,0 0 0 .2rem rgba(0,123,255,.25)}.custom-range::-moz-focus-outer{border:0}.custom-range::-webkit-slider-thumb{width:1rem;height:1rem;margin-top:-.25rem;background-color:#007bff;border:0;border-radius:1rem;-webkit-transition:background-color .15s ease-in-out,border-color .15s ease-in-out,box-shadow .15s ease-in-out;transition:background-color .15s ease-in-out,border-color .15s ease-in-out,box-shadow .15s ease-in-out;-webkit-appearance:none;appearance:none}@media (prefers-reduced-motion:reduce){.custom-range::-webkit-slider-thumb{-webkit-transition:none;transition:none}}.custom-range::-webkit-slider-thumb:active{background-color:#b3d7ff}.custom-range::-webkit-slider-runnable-track{width:100%;height:.5rem;color:transparent;cursor:pointer;background-color:#dee2e6;border-color:transparent;border-radius:1rem}.custom-range::-moz-range-thumb{width:1rem;height:1rem;background-color:#007bff;border:0;border-radius:1rem;-moz-transition:background-color .15s ease-in-out,border-color .15s ease-in-out,box-shadow .15s ease-in-out;transition:background-color .15s ease-in-out,border-color .15s ease-in-out,box-shadow .15s ease-in-out;-moz-appearance:none;appearance:none}@media (prefers-reduced-motion:reduce){.custom-range::-moz-range-thumb{-moz-transition:none;transition:none}}.custom-range::-moz-range-thumb:active{background-color:#b3d7ff}.custom-range::-moz-range-track{width:100%;height:.5rem;color:transparent;cursor:pointer;background-color:#dee2e6;border-color:transparent;border-radius:1rem}.custom-range::-ms-thumb{width:1rem;height:1rem;margin-top:0;margin-right:.2rem;margin-left:.2rem;background-color:#007bff;border:0;border-radius:1rem;-ms-transition:background-color .15s ease-in-out,border-color .15s ease-in-out,box-shadow .15s ease-in-out;transition:background-color .15s ease-in-out,border-color .15s ease-in-out,box-shadow .15s ease-in-out;appearance:none}@media (prefers-reduced-motion:reduce){.custom-range::-ms-thumb{-ms-transition:none;transition:none}}.custom-range::-ms-thumb:active{background-color:#b3d7ff}.custom-range::-ms-track{width:100%;height:.5rem;color:transparent;cursor:pointer;background-color:transparent;border-color:transparent;border-width:.5rem}.custom-range::-ms-fill-lower{background-color:#dee2e6;border-radius:1rem}.custom-range::-ms-fill-upper{margin-right:15px;background-color:#dee2e6;border-radius:1rem}.custom-range:disabled::-webkit-slider-thumb{background-color:#adb5bd}.custom-range:disabled::-webkit-slider-runnable-track{cursor:default}.custom-range:disabled::-moz-range-thumb{background-color:#adb5bd}.custom-range:disabled::-moz-range-track{cursor:default}.custom-range:disabled::-ms-thumb{background-color:#adb5bd}.custom-control-label::before,.custom-file-label,.custom-select{transition:background-color .15s ease-in-out,border-color .15s ease-in-out,box-shadow .15s ease-in-out}@media (prefers-reduced-motion:reduce){.custom-control-label::before,.custom-file-label,.custom-select{transition:none}}.nav{display:-ms-flexbox;display:flex;-ms-flex-wrap:wrap;flex-wrap:wrap;padding-left:0;margin-bottom:0;list-style:none}.nav-link{display:block;padding:.5rem 1rem}.nav-link:focus,.nav-link:hover{text-decoration:none}.nav-link.disabled{color:#6c757d;pointer-events:none;cursor:default}.nav-tabs{border-bottom:1px solid #dee2e6}.nav-tabs .nav-item{margin-bottom:-1px}.nav-tabs .nav-link{border:1px solid transparent;border-top-left-radius:.25rem;border-top-right-radius:.25rem}.nav-tabs .nav-link:focus,.nav-tabs .nav-link:hover{border-color:#e9ecef #e9ecef #dee2e6}.nav-tabs .nav-link.disabled{color:#6c757d;background-color:transparent;border-color:transparent}.nav-tabs .nav-item.show .nav-link,.nav-tabs .nav-link.active{color:#495057;background-color:#fff;border-color:#dee2e6 #dee2e6 #fff}.nav-tabs .dropdown-menu{margin-top:-1px;border-top-left-radius:0;border-top-right-radius:0}.nav-pills .nav-link{border-radius:.25rem}.nav-pills .nav-link.active,.nav-pills .show>.nav-link{color:#fff;background-color:#007bff}.nav-fill .nav-item{-ms-flex:1 1 auto;flex:1 1 auto;text-align:center}.nav-justified .nav-item{-ms-flex-preferred-size:0;flex-basis:0;-ms-flex-positive:1;flex-grow:1;text-align:center}.tab-content>.tab-pane{display:none}.tab-content>.active{display:block}.navbar{position:relative;display:-ms-flexbox;display:flex;-ms-flex-wrap:wrap;flex-wrap:wrap;-ms-flex-align:center;align-items:center;-ms-flex-pack:justify;justify-content:space-between;padding:.5rem 1rem}.navbar .container,.navbar .container-fluid,.navbar .container-lg,.navbar .container-md,.navbar .container-sm,.navbar .container-xl{display:-ms-flexbox;display:flex;-ms-flex-wrap:wrap;flex-wrap:wrap;-ms-flex-align:center;align-items:center;-ms-flex-pack:justify;justify-content:space-between}.navbar-brand{display:inline-block;padding-top:.3125rem;padding-bottom:.3125rem;margin-right:1rem;font-size:1.25rem;line-height:inherit;white-space:nowrap}.navbar-brand:focus,.navbar-brand:hover{text-decoration:none}.navbar-nav{display:-ms-flexbox;display:flex;-ms-flex-direction:column;flex-direction:column;padding-left:0;margin-bottom:0;list-style:none}.navbar-nav .nav-link{padding-right:0;padding-left:0}.navbar-nav .dropdown-menu{position:static;float:none}.navbar-text{display:inline-block;padding-top:.5rem;padding-bottom:.5rem}.navbar-collapse{-ms-flex-preferred-size:100%;flex-basis:100%;-ms-flex-positive:1;flex-grow:1;-ms-flex-align:center;align-items:center}.navbar-toggler{padding:.25rem .75rem;font-size:1.25rem;line-height:1;background-color:transparent;border:1px solid transparent;border-radius:.25rem}.navbar-toggler:focus,.navbar-toggler:hover{text-decoration:none}.navbar-toggler-icon{display:inline-block;width:1.5em;height:1.5em;vertical-align:middle;content:\\\"\\\";background:no-repeat center center;background-size:100% 100%}@media (max-width:575.98px){.navbar-expand-sm>.container,.navbar-expand-sm>.container-fluid,.navbar-expand-sm>.container-lg,.navbar-expand-sm>.container-md,.navbar-expand-sm>.container-sm,.navbar-expand-sm>.container-xl{padding-right:0;padding-left:0}}@media (min-width:576px){.navbar-expand-sm{-ms-flex-flow:row nowrap;flex-flow:row nowrap;-ms-flex-pack:start;justify-content:flex-start}.navbar-expand-sm .navbar-nav{-ms-flex-direction:row;flex-direction:row}.navbar-expand-sm .navbar-nav .dropdown-menu{position:absolute}.navbar-expand-sm .navbar-nav .nav-link{padding-right:.5rem;padding-left:.5rem}.navbar-expand-sm>.container,.navbar-expand-sm>.container-fluid,.navbar-expand-sm>.container-lg,.navbar-expand-sm>.container-md,.navbar-expand-sm>.container-sm,.navbar-expand-sm>.container-xl{-ms-flex-wrap:nowrap;flex-wrap:nowrap}.navbar-expand-sm .navbar-collapse{display:-ms-flexbox!important;display:flex!important;-ms-flex-preferred-size:auto;flex-basis:auto}.navbar-expand-sm .navbar-toggler{display:none}}@media (max-width:767.98px){.navbar-expand-md>.container,.navbar-expand-md>.container-fluid,.navbar-expand-md>.container-lg,.navbar-expand-md>.container-md,.navbar-expand-md>.container-sm,.navbar-expand-md>.container-xl{padding-right:0;padding-left:0}}@media (min-width:768px){.navbar-expand-md{-ms-flex-flow:row nowrap;flex-flow:row nowrap;-ms-flex-pack:start;justify-content:flex-start}.navbar-expand-md .navbar-nav{-ms-flex-direction:row;flex-direction:row}.navbar-expand-md .navbar-nav .dropdown-menu{position:absolute}.navbar-expand-md .navbar-nav .nav-link{padding-right:.5rem;padding-left:.5rem}.navbar-expand-md>.container,.navbar-expand-md>.container-fluid,.navbar-expand-md>.container-lg,.navbar-expand-md>.container-md,.navbar-expand-md>.container-sm,.navbar-expand-md>.container-xl{-ms-flex-wrap:nowrap;flex-wrap:nowrap}.navbar-expand-md .navbar-collapse{display:-ms-flexbox!important;display:flex!important;-ms-flex-preferred-size:auto;flex-basis:auto}.navbar-expand-md .navbar-toggler{display:none}}@media (max-width:991.98px){.navbar-expand-lg>.container,.navbar-expand-lg>.container-fluid,.navbar-expand-lg>.container-lg,.navbar-expand-lg>.container-md,.navbar-expand-lg>.container-sm,.navbar-expand-lg>.container-xl{padding-right:0;padding-left:0}}@media (min-width:992px){.navbar-expand-lg{-ms-flex-flow:row nowrap;flex-flow:row nowrap;-ms-flex-pack:start;justify-content:flex-start}.navbar-expand-lg .navbar-nav{-ms-flex-direction:row;flex-direction:row}.navbar-expand-lg .navbar-nav .dropdown-menu{position:absolute}.navbar-expand-lg .navbar-nav .nav-link{padding-right:.5rem;padding-left:.5rem}.navbar-expand-lg>.container,.navbar-expand-lg>.container-fluid,.navbar-expand-lg>.container-lg,.navbar-expand-lg>.container-md,.navbar-expand-lg>.container-sm,.navbar-expand-lg>.container-xl{-ms-flex-wrap:nowrap;flex-wrap:nowrap}.navbar-expand-lg .navbar-collapse{display:-ms-flexbox!important;display:flex!important;-ms-flex-preferred-size:auto;flex-basis:auto}.navbar-expand-lg .navbar-toggler{display:none}}@media (max-width:1199.98px){.navbar-expand-xl>.container,.navbar-expand-xl>.container-fluid,.navbar-expand-xl>.container-lg,.navbar-expand-xl>.container-md,.navbar-expand-xl>.container-sm,.navbar-expand-xl>.container-xl{padding-right:0;padding-left:0}}@media (min-width:1200px){.navbar-expand-xl{-ms-flex-flow:row nowrap;flex-flow:row nowrap;-ms-flex-pack:start;justify-content:flex-start}.navbar-expand-xl .navbar-nav{-ms-flex-direction:row;flex-direction:row}.navbar-expand-xl .navbar-nav .dropdown-menu{position:absolute}.navbar-expand-xl .navbar-nav .nav-link{padding-right:.5rem;padding-left:.5rem}.navbar-expand-xl>.container,.navbar-expand-xl>.container-fluid,.navbar-expand-xl>.container-lg,.navbar-expand-xl>.container-md,.navbar-expand-xl>.container-sm,.navbar-expand-xl>.container-xl{-ms-flex-wrap:nowrap;flex-wrap:nowrap}.navbar-expand-xl .navbar-collapse{display:-ms-flexbox!important;display:flex!important;-ms-flex-preferred-size:auto;flex-basis:auto}.navbar-expand-xl .navbar-toggler{display:none}}.navbar-expand{-ms-flex-flow:row nowrap;flex-flow:row nowrap;-ms-flex-pack:start;justify-content:flex-start}.navbar-expand>.container,.navbar-expand>.container-fluid,.navbar-expand>.container-lg,.navbar-expand>.container-md,.navbar-expand>.container-sm,.navbar-expand>.container-xl{padding-right:0;padding-left:0}.navbar-expand .navbar-nav{-ms-flex-direction:row;flex-direction:row}.navbar-expand .navbar-nav .dropdown-menu{position:absolute}.navbar-expand .navbar-nav .nav-link{padding-right:.5rem;padding-left:.5rem}.navbar-expand>.container,.navbar-expand>.container-fluid,.navbar-expand>.container-lg,.navbar-expand>.container-md,.navbar-expand>.container-sm,.navbar-expand>.container-xl{-ms-flex-wrap:nowrap;flex-wrap:nowrap}.navbar-expand .navbar-collapse{display:-ms-flexbox!important;display:flex!important;-ms-flex-preferred-size:auto;flex-basis:auto}.navbar-expand .navbar-toggler{display:none}.navbar-light .navbar-brand{color:rgba(0,0,0,.9)}.navbar-light .navbar-brand:focus,.navbar-light .navbar-brand:hover{color:rgba(0,0,0,.9)}.navbar-light .navbar-nav .nav-link{color:rgba(0,0,0,.5)}.navbar-light .navbar-nav .nav-link:focus,.navbar-light .navbar-nav .nav-link:hover{color:rgba(0,0,0,.7)}.navbar-light .navbar-nav .nav-link.disabled{color:rgba(0,0,0,.3)}.navbar-light .navbar-nav .active>.nav-link,.navbar-light .navbar-nav .nav-link.active,.navbar-light .navbar-nav .nav-link.show,.navbar-light .navbar-nav .show>.nav-link{color:rgba(0,0,0,.9)}.navbar-light .navbar-toggler{color:rgba(0,0,0,.5);border-color:rgba(0,0,0,.1)}.navbar-light .navbar-toggler-icon{background-image:url(\\\"data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' width='30' height='30' viewBox='0 0 30 30'%3e%3cpath stroke='rgba(0, 0, 0, 0.5)' stroke-linecap='round' stroke-miterlimit='10' stroke-width='2' d='M4 7h22M4 15h22M4 23h22'/%3e%3c/svg%3e\\\")}.navbar-light .navbar-text{color:rgba(0,0,0,.5)}.navbar-light .navbar-text a{color:rgba(0,0,0,.9)}.navbar-light .navbar-text a:focus,.navbar-light .navbar-text a:hover{color:rgba(0,0,0,.9)}.navbar-dark .navbar-brand{color:#fff}.navbar-dark .navbar-brand:focus,.navbar-dark .navbar-brand:hover{color:#fff}.navbar-dark .navbar-nav .nav-link{color:rgba(255,255,255,.5)}.navbar-dark .navbar-nav .nav-link:focus,.navbar-dark .navbar-nav .nav-link:hover{color:rgba(255,255,255,.75)}.navbar-dark .navbar-nav .nav-link.disabled{color:rgba(255,255,255,.25)}.navbar-dark .navbar-nav .active>.nav-link,.navbar-dark .navbar-nav .nav-link.active,.navbar-dark .navbar-nav .nav-link.show,.navbar-dark .navbar-nav .show>.nav-link{color:#fff}.navbar-dark .navbar-toggler{color:rgba(255,255,255,.5);border-color:rgba(255,255,255,.1)}.navbar-dark .navbar-toggler-icon{background-image:url(\\\"data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' width='30' height='30' viewBox='0 0 30 30'%3e%3cpath stroke='rgba(255, 255, 255, 0.5)' stroke-linecap='round' stroke-miterlimit='10' stroke-width='2' d='M4 7h22M4 15h22M4 23h22'/%3e%3c/svg%3e\\\")}.navbar-dark .navbar-text{color:rgba(255,255,255,.5)}.navbar-dark .navbar-text a{color:#fff}.navbar-dark .navbar-text a:focus,.navbar-dark .navbar-text a:hover{color:#fff}.card{position:relative;display:-ms-flexbox;display:flex;-ms-flex-direction:column;flex-direction:column;min-width:0;word-wrap:break-word;background-color:#fff;background-clip:border-box;border:1px solid rgba(0,0,0,.125);border-radius:.25rem}.card>hr{margin-right:0;margin-left:0}.card>.list-group:first-child .list-group-item:first-child{border-top-left-radius:.25rem;border-top-right-radius:.25rem}.card>.list-group:last-child .list-group-item:last-child{border-bottom-right-radius:.25rem;border-bottom-left-radius:.25rem}.card-body{-ms-flex:1 1 auto;flex:1 1 auto;min-height:1px;padding:1.25rem}.card-title{margin-bottom:.75rem}.card-subtitle{margin-top:-.375rem;margin-bottom:0}.card-text:last-child{margin-bottom:0}.card-link:hover{text-decoration:none}.card-link+.card-link{margin-left:1.25rem}.card-header{padding:.75rem 1.25rem;margin-bottom:0;background-color:rgba(0,0,0,.03);border-bottom:1px solid rgba(0,0,0,.125)}.card-header:first-child{border-radius:calc(.25rem - 1px) calc(.25rem - 1px) 0 0}.card-header+.list-group .list-group-item:first-child{border-top:0}.card-footer{padding:.75rem 1.25rem;background-color:rgba(0,0,0,.03);border-top:1px solid rgba(0,0,0,.125)}.card-footer:last-child{border-radius:0 0 calc(.25rem - 1px) calc(.25rem - 1px)}.card-header-tabs{margin-right:-.625rem;margin-bottom:-.75rem;margin-left:-.625rem;border-bottom:0}.card-header-pills{margin-right:-.625rem;margin-left:-.625rem}.card-img-overlay{position:absolute;top:0;right:0;bottom:0;left:0;padding:1.25rem}.card-img,.card-img-bottom,.card-img-top{-ms-flex-negative:0;flex-shrink:0;width:100%}.card-img,.card-img-top{border-top-left-radius:calc(.25rem - 1px);border-top-right-radius:calc(.25rem - 1px)}.card-img,.card-img-bottom{border-bottom-right-radius:calc(.25rem - 1px);border-bottom-left-radius:calc(.25rem - 1px)}.card-deck .card{margin-bottom:15px}@media (min-width:576px){.card-deck{display:-ms-flexbox;display:flex;-ms-flex-flow:row wrap;flex-flow:row wrap;margin-right:-15px;margin-left:-15px}.card-deck .card{-ms-flex:1 0 0%;flex:1 0 0%;margin-right:15px;margin-bottom:0;margin-left:15px}}.card-group>.card{margin-bottom:15px}@media (min-width:576px){.card-group{display:-ms-flexbox;display:flex;-ms-flex-flow:row wrap;flex-flow:row wrap}.card-group>.card{-ms-flex:1 0 0%;flex:1 0 0%;margin-bottom:0}.card-group>.card+.card{margin-left:0;border-left:0}.card-group>.card:not(:last-child){border-top-right-radius:0;border-bottom-right-radius:0}.card-group>.card:not(:last-child) .card-header,.card-group>.card:not(:last-child) .card-img-top{border-top-right-radius:0}.card-group>.card:not(:last-child) .card-footer,.card-group>.card:not(:last-child) .card-img-bottom{border-bottom-right-radius:0}.card-group>.card:not(:first-child){border-top-left-radius:0;border-bottom-left-radius:0}.card-group>.card:not(:first-child) .card-header,.card-group>.card:not(:first-child) .card-img-top{border-top-left-radius:0}.card-group>.card:not(:first-child) .card-footer,.card-group>.card:not(:first-child) .card-img-bottom{border-bottom-left-radius:0}}.card-columns .card{margin-bottom:.75rem}@media (min-width:576px){.card-columns{-webkit-column-count:3;-moz-column-count:3;column-count:3;-webkit-column-gap:1.25rem;-moz-column-gap:1.25rem;column-gap:1.25rem;orphans:1;widows:1}.card-columns .card{display:inline-block;width:100%}}.accordion>.card{overflow:hidden}.accordion>.card:not(:last-of-type){border-bottom:0;border-bottom-right-radius:0;border-bottom-left-radius:0}.accordion>.card:not(:first-of-type){border-top-left-radius:0;border-top-right-radius:0}.accordion>.card>.card-header{border-radius:0;margin-bottom:-1px}.breadcrumb{display:-ms-flexbox;display:flex;-ms-flex-wrap:wrap;flex-wrap:wrap;padding:.75rem 1rem;margin-bottom:1rem;list-style:none;background-color:#e9ecef;border-radius:.25rem}.breadcrumb-item+.breadcrumb-item{padding-left:.5rem}.breadcrumb-item+.breadcrumb-item::before{display:inline-block;padding-right:.5rem;color:#6c757d;content:\\\"/\\\"}.breadcrumb-item+.breadcrumb-item:hover::before{text-decoration:underline}.breadcrumb-item+.breadcrumb-item:hover::before{text-decoration:none}.breadcrumb-item.active{color:#6c757d}.pagination{display:-ms-flexbox;display:flex;padding-left:0;list-style:none;border-radius:.25rem}.page-link{position:relative;display:block;padding:.5rem .75rem;margin-left:-1px;line-height:1.25;color:#007bff;background-color:#fff;border:1px solid #dee2e6}.page-link:hover{z-index:2;color:#0056b3;text-decoration:none;background-color:#e9ecef;border-color:#dee2e6}.page-link:focus{z-index:3;outline:0;box-shadow:0 0 0 .2rem rgba(0,123,255,.25)}.page-item:first-child .page-link{margin-left:0;border-top-left-radius:.25rem;border-bottom-left-radius:.25rem}.page-item:last-child .page-link{border-top-right-radius:.25rem;border-bottom-right-radius:.25rem}.page-item.active .page-link{z-index:3;color:#fff;background-color:#007bff;border-color:#007bff}.page-item.disabled .page-link{color:#6c757d;pointer-events:none;cursor:auto;background-color:#fff;border-color:#dee2e6}.pagination-lg .page-link{padding:.75rem 1.5rem;font-size:1.25rem;line-height:1.5}.pagination-lg .page-item:first-child .page-link{border-top-left-radius:.3rem;border-bottom-left-radius:.3rem}.pagination-lg .page-item:last-child .page-link{border-top-right-radius:.3rem;border-bottom-right-radius:.3rem}.pagination-sm .page-link{padding:.25rem .5rem;font-size:.875rem;line-height:1.5}.pagination-sm .page-item:first-child .page-link{border-top-left-radius:.2rem;border-bottom-left-radius:.2rem}.pagination-sm .page-item:last-child .page-link{border-top-right-radius:.2rem;border-bottom-right-radius:.2rem}.badge{display:inline-block;padding:.25em .4em;font-size:75%;font-weight:700;line-height:1;text-align:center;white-space:nowrap;vertical-align:baseline;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){.badge{transition:none}}a.badge:focus,a.badge:hover{text-decoration:none}.badge:empty{display:none}.btn .badge{position:relative;top:-1px}.badge-pill{padding-right:.6em;padding-left:.6em;border-radius:10rem}.badge-primary{color:#fff;background-color:#007bff}a.badge-primary:focus,a.badge-primary:hover{color:#fff;background-color:#0062cc}a.badge-primary.focus,a.badge-primary:focus{outline:0;box-shadow:0 0 0 .2rem rgba(0,123,255,.5)}.badge-secondary{color:#fff;background-color:#6c757d}a.badge-secondary:focus,a.badge-secondary:hover{color:#fff;background-color:#545b62}a.badge-secondary.focus,a.badge-secondary:focus{outline:0;box-shadow:0 0 0 .2rem rgba(108,117,125,.5)}.badge-success{color:#fff;background-color:#28a745}a.badge-success:focus,a.badge-success:hover{color:#fff;background-color:#1e7e34}a.badge-success.focus,a.badge-success:focus{outline:0;box-shadow:0 0 0 .2rem rgba(40,167,69,.5)}.badge-info{color:#fff;background-color:#17a2b8}a.badge-info:focus,a.badge-info:hover{color:#fff;background-color:#117a8b}a.badge-info.focus,a.badge-info:focus{outline:0;box-shadow:0 0 0 .2rem rgba(23,162,184,.5)}.badge-warning{color:#212529;background-color:#ffc107}a.badge-warning:focus,a.badge-warning:hover{color:#212529;background-color:#d39e00}a.badge-warning.focus,a.badge-warning:focus{outline:0;box-shadow:0 0 0 .2rem rgba(255,193,7,.5)}.badge-danger{color:#fff;background-color:#dc3545}a.badge-danger:focus,a.badge-danger:hover{color:#fff;background-color:#bd2130}a.badge-danger.focus,a.badge-danger:focus{outline:0;box-shadow:0 0 0 .2rem rgba(220,53,69,.5)}.badge-light{color:#212529;background-color:#f8f9fa}a.badge-light:focus,a.badge-light:hover{color:#212529;background-color:#dae0e5}a.badge-light.focus,a.badge-light:focus{outline:0;box-shadow:0 0 0 .2rem rgba(248,249,250,.5)}.badge-dark{color:#fff;background-color:#343a40}a.badge-dark:focus,a.badge-dark:hover{color:#fff;background-color:#1d2124}a.badge-dark.focus,a.badge-dark:focus{outline:0;box-shadow:0 0 0 .2rem rgba(52,58,64,.5)}.jumbotron{padding:2rem 1rem;margin-bottom:2rem;background-color:#e9ecef;border-radius:.3rem}@media (min-width:576px){.jumbotron{padding:4rem 2rem}}.jumbotron-fluid{padding-right:0;padding-left:0;border-radius:0}.alert{position:relative;padding:.75rem 1.25rem;margin-bottom:1rem;border:1px solid transparent;border-radius:.25rem}.alert-heading{color:inherit}.alert-link{font-weight:700}.alert-dismissible{padding-right:4rem}.alert-dismissible .close{position:absolute;top:0;right:0;padding:.75rem 1.25rem;color:inherit}.alert-primary{color:#004085;background-color:#cce5ff;border-color:#b8daff}.alert-primary hr{border-top-color:#9fcdff}.alert-primary .alert-link{color:#002752}.alert-secondary{color:#383d41;background-color:#e2e3e5;border-color:#d6d8db}.alert-secondary hr{border-top-color:#c8cbcf}.alert-secondary .alert-link{color:#202326}.alert-success{color:#155724;background-color:#d4edda;border-color:#c3e6cb}.alert-success hr{border-top-color:#b1dfbb}.alert-success .alert-link{color:#0b2e13}.alert-info{color:#0c5460;background-color:#d1ecf1;border-color:#bee5eb}.alert-info hr{border-top-color:#abdde5}.alert-info .alert-link{color:#062c33}.alert-warning{color:#856404;background-color:#fff3cd;border-color:#ffeeba}.alert-warning hr{border-top-color:#ffe8a1}.alert-warning .alert-link{color:#533f03}.alert-danger{color:#721c24;background-color:#f8d7da;border-color:#f5c6cb}.alert-danger hr{border-top-color:#f1b0b7}.alert-danger .alert-link{color:#491217}.alert-light{color:#818182;background-color:#fefefe;border-color:#fdfdfe}.alert-light hr{border-top-color:#ececf6}.alert-light .alert-link{color:#686868}.alert-dark{color:#1b1e21;background-color:#d6d8d9;border-color:#c6c8ca}.alert-dark hr{border-top-color:#b9bbbe}.alert-dark .alert-link{color:#040505}@-webkit-keyframes progress-bar-stripes{from{background-position:1rem 0}to{background-position:0 0}}@keyframes progress-bar-stripes{from{background-position:1rem 0}to{background-position:0 0}}.progress{display:-ms-flexbox;display:flex;height:1rem;overflow:hidden;font-size:.75rem;background-color:#e9ecef;border-radius:.25rem}.progress-bar{display:-ms-flexbox;display:flex;-ms-flex-direction:column;flex-direction:column;-ms-flex-pack:center;justify-content:center;overflow:hidden;color:#fff;text-align:center;white-space:nowrap;background-color:#007bff;transition:width .6s ease}@media (prefers-reduced-motion:reduce){.progress-bar{transition:none}}.progress-bar-striped{background-image:linear-gradient(45deg,rgba(255,255,255,.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,.15) 50%,rgba(255,255,255,.15) 75%,transparent 75%,transparent);background-size:1rem 1rem}.progress-bar-animated{-webkit-animation:progress-bar-stripes 1s linear infinite;animation:progress-bar-stripes 1s linear infinite}@media (prefers-reduced-motion:reduce){.progress-bar-animated{-webkit-animation:none;animation:none}}.media{display:-ms-flexbox;display:flex;-ms-flex-align:start;align-items:flex-start}.media-body{-ms-flex:1;flex:1}.list-group{display:-ms-flexbox;display:flex;-ms-flex-direction:column;flex-direction:column;padding-left:0;margin-bottom:0}.list-group-item-action{width:100%;color:#495057;text-align:inherit}.list-group-item-action:focus,.list-group-item-action:hover{z-index:1;color:#495057;text-decoration:none;background-color:#f8f9fa}.list-group-item-action:active{color:#212529;background-color:#e9ecef}.list-group-item{position:relative;display:block;padding:.75rem 1.25rem;background-color:#fff;border:1px solid rgba(0,0,0,.125)}.list-group-item:first-child{border-top-left-radius:.25rem;border-top-right-radius:.25rem}.list-group-item:last-child{border-bottom-right-radius:.25rem;border-bottom-left-radius:.25rem}.list-group-item.disabled,.list-group-item:disabled{color:#6c757d;pointer-events:none;background-color:#fff}.list-group-item.active{z-index:2;color:#fff;background-color:#007bff;border-color:#007bff}.list-group-item+.list-group-item{border-top-width:0}.list-group-item+.list-group-item.active{margin-top:-1px;border-top-width:1px}.list-group-horizontal{-ms-flex-direction:row;flex-direction:row}.list-group-horizontal .list-group-item:first-child{border-bottom-left-radius:.25rem;border-top-right-radius:0}.list-group-horizontal .list-group-item:last-child{border-top-right-radius:.25rem;border-bottom-left-radius:0}.list-group-horizontal .list-group-item.active{margin-top:0}.list-group-horizontal .list-group-item+.list-group-item{border-top-width:1px;border-left-width:0}.list-group-horizontal .list-group-item+.list-group-item.active{margin-left:-1px;border-left-width:1px}@media (min-width:576px){.list-group-horizontal-sm{-ms-flex-direction:row;flex-direction:row}.list-group-horizontal-sm .list-group-item:first-child{border-bottom-left-radius:.25rem;border-top-right-radius:0}.list-group-horizontal-sm .list-group-item:last-child{border-top-right-radius:.25rem;border-bottom-left-radius:0}.list-group-horizontal-sm .list-group-item.active{margin-top:0}.list-group-horizontal-sm .list-group-item+.list-group-item{border-top-width:1px;border-left-width:0}.list-group-horizontal-sm .list-group-item+.list-group-item.active{margin-left:-1px;border-left-width:1px}}@media (min-width:768px){.list-group-horizontal-md{-ms-flex-direction:row;flex-direction:row}.list-group-horizontal-md .list-group-item:first-child{border-bottom-left-radius:.25rem;border-top-right-radius:0}.list-group-horizontal-md .list-group-item:last-child{border-top-right-radius:.25rem;border-bottom-left-radius:0}.list-group-horizontal-md .list-group-item.active{margin-top:0}.list-group-horizontal-md .list-group-item+.list-group-item{border-top-width:1px;border-left-width:0}.list-group-horizontal-md .list-group-item+.list-group-item.active{margin-left:-1px;border-left-width:1px}}@media (min-width:992px){.list-group-horizontal-lg{-ms-flex-direction:row;flex-direction:row}.list-group-horizontal-lg .list-group-item:first-child{border-bottom-left-radius:.25rem;border-top-right-radius:0}.list-group-horizontal-lg .list-group-item:last-child{border-top-right-radius:.25rem;border-bottom-left-radius:0}.list-group-horizontal-lg .list-group-item.active{margin-top:0}.list-group-horizontal-lg .list-group-item+.list-group-item{border-top-width:1px;border-left-width:0}.list-group-horizontal-lg .list-group-item+.list-group-item.active{margin-left:-1px;border-left-width:1px}}@media (min-width:1200px){.list-group-horizontal-xl{-ms-flex-direction:row;flex-direction:row}.list-group-horizontal-xl .list-group-item:first-child{border-bottom-left-radius:.25rem;border-top-right-radius:0}.list-group-horizontal-xl .list-group-item:last-child{border-top-right-radius:.25rem;border-bottom-left-radius:0}.list-group-horizontal-xl .list-group-item.active{margin-top:0}.list-group-horizontal-xl .list-group-item+.list-group-item{border-top-width:1px;border-left-width:0}.list-group-horizontal-xl .list-group-item+.list-group-item.active{margin-left:-1px;border-left-width:1px}}.list-group-flush .list-group-item{border-right-width:0;border-left-width:0;border-radius:0}.list-group-flush .list-group-item:first-child{border-top-width:0}.list-group-flush:last-child .list-group-item:last-child{border-bottom-width:0}.list-group-item-primary{color:#004085;background-color:#b8daff}.list-group-item-primary.list-group-item-action:focus,.list-group-item-primary.list-group-item-action:hover{color:#004085;background-color:#9fcdff}.list-group-item-primary.list-group-item-action.active{color:#fff;background-color:#004085;border-color:#004085}.list-group-item-secondary{color:#383d41;background-color:#d6d8db}.list-group-item-secondary.list-group-item-action:focus,.list-group-item-secondary.list-group-item-action:hover{color:#383d41;background-color:#c8cbcf}.list-group-item-secondary.list-group-item-action.active{color:#fff;background-color:#383d41;border-color:#383d41}.list-group-item-success{color:#155724;background-color:#c3e6cb}.list-group-item-success.list-group-item-action:focus,.list-group-item-success.list-group-item-action:hover{color:#155724;background-color:#b1dfbb}.list-group-item-success.list-group-item-action.active{color:#fff;background-color:#155724;border-color:#155724}.list-group-item-info{color:#0c5460;background-color:#bee5eb}.list-group-item-info.list-group-item-action:focus,.list-group-item-info.list-group-item-action:hover{color:#0c5460;background-color:#abdde5}.list-group-item-info.list-group-item-action.active{color:#fff;background-color:#0c5460;border-color:#0c5460}.list-group-item-warning{color:#856404;background-color:#ffeeba}.list-group-item-warning.list-group-item-action:focus,.list-group-item-warning.list-group-item-action:hover{color:#856404;background-color:#ffe8a1}.list-group-item-warning.list-group-item-action.active{color:#fff;background-color:#856404;border-color:#856404}.list-group-item-danger{color:#721c24;background-color:#f5c6cb}.list-group-item-danger.list-group-item-action:focus,.list-group-item-danger.list-group-item-action:hover{color:#721c24;background-color:#f1b0b7}.list-group-item-danger.list-group-item-action.active{color:#fff;background-color:#721c24;border-color:#721c24}.list-group-item-light{color:#818182;background-color:#fdfdfe}.list-group-item-light.list-group-item-action:focus,.list-group-item-light.list-group-item-action:hover{color:#818182;background-color:#ececf6}.list-group-item-light.list-group-item-action.active{color:#fff;background-color:#818182;border-color:#818182}.list-group-item-dark{color:#1b1e21;background-color:#c6c8ca}.list-group-item-dark.list-group-item-action:focus,.list-group-item-dark.list-group-item-action:hover{color:#1b1e21;background-color:#b9bbbe}.list-group-item-dark.list-group-item-action.active{color:#fff;background-color:#1b1e21;border-color:#1b1e21}.close{float:right;font-size:1.5rem;font-weight:700;line-height:1;color:#000;text-shadow:0 1px 0 #fff;opacity:.5}.close:hover{color:#000;text-decoration:none}.close:not(:disabled):not(.disabled):focus,.close:not(:disabled):not(.disabled):hover{opacity:.75}button.close{padding:0;background-color:transparent;border:0;-webkit-appearance:none;-moz-appearance:none;appearance:none}a.close.disabled{pointer-events:none}.toast{max-width:350px;overflow:hidden;font-size:.875rem;background-color:rgba(255,255,255,.85);background-clip:padding-box;border:1px solid rgba(0,0,0,.1);box-shadow:0 .25rem .75rem rgba(0,0,0,.1);-webkit-backdrop-filter:blur(10px);backdrop-filter:blur(10px);opacity:0;border-radius:.25rem}.toast:not(:last-child){margin-bottom:.75rem}.toast.showing{opacity:1}.toast.show{display:block;opacity:1}.toast.hide{display:none}.toast-header{display:-ms-flexbox;display:flex;-ms-flex-align:center;align-items:center;padding:.25rem .75rem;color:#6c757d;background-color:rgba(255,255,255,.85);background-clip:padding-box;border-bottom:1px solid rgba(0,0,0,.05)}.toast-body{padding:.75rem}.modal-open{overflow:hidden}.modal-open .modal{overflow-x:hidden;overflow-y:auto}.modal{position:fixed;top:0;left:0;z-index:1050;display:none;width:100%;height:100%;overflow:hidden;outline:0}.modal-dialog{position:relative;width:auto;margin:.5rem;pointer-events:none}.modal.fade .modal-dialog{transition:-webkit-transform .3s ease-out;transition:transform .3s ease-out;transition:transform .3s ease-out,-webkit-transform .3s ease-out;-webkit-transform:translate(0,-50px);transform:translate(0,-50px)}@media (prefers-reduced-motion:reduce){.modal.fade .modal-dialog{transition:none}}.modal.show .modal-dialog{-webkit-transform:none;transform:none}.modal.modal-static .modal-dialog{-webkit-transform:scale(1.02);transform:scale(1.02)}.modal-dialog-scrollable{display:-ms-flexbox;display:flex;max-height:calc(100% - 1rem)}.modal-dialog-scrollable .modal-content{max-height:calc(100vh - 1rem);overflow:hidden}.modal-dialog-scrollable .modal-footer,.modal-dialog-scrollable .modal-header{-ms-flex-negative:0;flex-shrink:0}.modal-dialog-scrollable .modal-body{overflow-y:auto}.modal-dialog-centered{display:-ms-flexbox;display:flex;-ms-flex-align:center;align-items:center;min-height:calc(100% - 1rem)}.modal-dialog-centered::before{display:block;height:calc(100vh - 1rem);content:\\\"\\\"}.modal-dialog-centered.modal-dialog-scrollable{-ms-flex-direction:column;flex-direction:column;-ms-flex-pack:center;justify-content:center;height:100%}.modal-dialog-centered.modal-dialog-scrollable .modal-content{max-height:none}.modal-dialog-centered.modal-dialog-scrollable::before{content:none}.modal-content{position:relative;display:-ms-flexbox;display:flex;-ms-flex-direction:column;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}.modal-backdrop{position:fixed;top:0;left:0;z-index:1040;width:100vw;height:100vh;background-color:#000}.modal-backdrop.fade{opacity:0}.modal-backdrop.show{opacity:.5}.modal-header{display:-ms-flexbox;display:flex;-ms-flex-align:start;align-items:flex-start;-ms-flex-pack:justify;justify-content:space-between;padding:1rem 1rem;border-bottom:1px solid #dee2e6;border-top-left-radius:calc(.3rem - 1px);border-top-right-radius:calc(.3rem - 1px)}.modal-header .close{padding:1rem 1rem;margin:-1rem -1rem -1rem auto}.modal-title{margin-bottom:0;line-height:1.5}.modal-body{position:relative;-ms-flex:1 1 auto;flex:1 1 auto;padding:1rem}.modal-footer{display:-ms-flexbox;display:flex;-ms-flex-wrap:wrap;flex-wrap:wrap;-ms-flex-align:center;align-items:center;-ms-flex-pack:end;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)}.modal-footer>*{margin:.25rem}.modal-scrollbar-measure{position:absolute;top:-9999px;width:50px;height:50px;overflow:scroll}@media (min-width:576px){.modal-dialog{max-width:500px;margin:1.75rem auto}.modal-dialog-scrollable{max-height:calc(100% - 3.5rem)}.modal-dialog-scrollable .modal-content{max-height:calc(100vh - 3.5rem)}.modal-dialog-centered{min-height:calc(100% - 3.5rem)}.modal-dialog-centered::before{height:calc(100vh - 3.5rem)}.modal-sm{max-width:300px}}@media (min-width:992px){.modal-lg,.modal-xl{max-width:800px}}@media (min-width:1200px){.modal-xl{max-width:1140px}}.tooltip{position:absolute;z-index:1070;display:block;margin: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-style:normal;font-weight:400;line-height:1.5;text-align:left;text-align:start;text-decoration:none;text-shadow:none;text-transform:none;letter-spacing:normal;word-break:normal;word-spacing:normal;white-space:normal;line-break:auto;font-size:.875rem;word-wrap:break-word;opacity:0}.tooltip.show{opacity:.9}.tooltip .arrow{position:absolute;display:block;width:.8rem;height:.4rem}.tooltip .arrow::before{position:absolute;content:\\\"\\\";border-color:transparent;border-style:solid}.bs-tooltip-auto[x-placement^=top],.bs-tooltip-top{padding:.4rem 0}.bs-tooltip-auto[x-placement^=top] .arrow,.bs-tooltip-top .arrow{bottom:0}.bs-tooltip-auto[x-placement^=top] .arrow::before,.bs-tooltip-top .arrow::before{top:0;border-width:.4rem .4rem 0;border-top-color:#000}.bs-tooltip-auto[x-placement^=right],.bs-tooltip-right{padding:0 .4rem}.bs-tooltip-auto[x-placement^=right] .arrow,.bs-tooltip-right .arrow{left:0;width:.4rem;height:.8rem}.bs-tooltip-auto[x-placement^=right] .arrow::before,.bs-tooltip-right .arrow::before{right:0;border-width:.4rem .4rem .4rem 0;border-right-color:#000}.bs-tooltip-auto[x-placement^=bottom],.bs-tooltip-bottom{padding:.4rem 0}.bs-tooltip-auto[x-placement^=bottom] .arrow,.bs-tooltip-bottom .arrow{top:0}.bs-tooltip-auto[x-placement^=bottom] .arrow::before,.bs-tooltip-bottom .arrow::before{bottom:0;border-width:0 .4rem .4rem;border-bottom-color:#000}.bs-tooltip-auto[x-placement^=left],.bs-tooltip-left{padding:0 .4rem}.bs-tooltip-auto[x-placement^=left] .arrow,.bs-tooltip-left .arrow{right:0;width:.4rem;height:.8rem}.bs-tooltip-auto[x-placement^=left] .arrow::before,.bs-tooltip-left .arrow::before{left:0;border-width:.4rem 0 .4rem .4rem;border-left-color:#000}.tooltip-inner{max-width:200px;padding:.25rem .5rem;color:#fff;text-align:center;background-color:#000;border-radius:.25rem}.popover{position:absolute;top:0;left:0;z-index:1060;display:block;max-width:276px;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-style:normal;font-weight:400;line-height:1.5;text-align:left;text-align:start;text-decoration:none;text-shadow:none;text-transform:none;letter-spacing:normal;word-break:normal;word-spacing:normal;white-space:normal;line-break:auto;font-size:.875rem;word-wrap:break-word;background-color:#fff;background-clip:padding-box;border:1px solid rgba(0,0,0,.2);border-radius:.3rem}.popover .arrow{position:absolute;display:block;width:1rem;height:.5rem;margin:0 .3rem}.popover .arrow::after,.popover .arrow::before{position:absolute;display:block;content:\\\"\\\";border-color:transparent;border-style:solid}.bs-popover-auto[x-placement^=top],.bs-popover-top{margin-bottom:.5rem}.bs-popover-auto[x-placement^=top]>.arrow,.bs-popover-top>.arrow{bottom:calc(-.5rem - 1px)}.bs-popover-auto[x-placement^=top]>.arrow::before,.bs-popover-top>.arrow::before{bottom:0;border-width:.5rem .5rem 0;border-top-color:rgba(0,0,0,.25)}.bs-popover-auto[x-placement^=top]>.arrow::after,.bs-popover-top>.arrow::after{bottom:1px;border-width:.5rem .5rem 0;border-top-color:#fff}.bs-popover-auto[x-placement^=right],.bs-popover-right{margin-left:.5rem}.bs-popover-auto[x-placement^=right]>.arrow,.bs-popover-right>.arrow{left:calc(-.5rem - 1px);width:.5rem;height:1rem;margin:.3rem 0}.bs-popover-auto[x-placement^=right]>.arrow::before,.bs-popover-right>.arrow::before{left:0;border-width:.5rem .5rem .5rem 0;border-right-color:rgba(0,0,0,.25)}.bs-popover-auto[x-placement^=right]>.arrow::after,.bs-popover-right>.arrow::after{left:1px;border-width:.5rem .5rem .5rem 0;border-right-color:#fff}.bs-popover-auto[x-placement^=bottom],.bs-popover-bottom{margin-top:.5rem}.bs-popover-auto[x-placement^=bottom]>.arrow,.bs-popover-bottom>.arrow{top:calc(-.5rem - 1px)}.bs-popover-auto[x-placement^=bottom]>.arrow::before,.bs-popover-bottom>.arrow::before{top:0;border-width:0 .5rem .5rem .5rem;border-bottom-color:rgba(0,0,0,.25)}.bs-popover-auto[x-placement^=bottom]>.arrow::after,.bs-popover-bottom>.arrow::after{top:1px;border-width:0 .5rem .5rem .5rem;border-bottom-color:#fff}.bs-popover-auto[x-placement^=bottom] .popover-header::before,.bs-popover-bottom .popover-header::before{position:absolute;top:0;left:50%;display:block;width:1rem;margin-left:-.5rem;content:\\\"\\\";border-bottom:1px solid #f7f7f7}.bs-popover-auto[x-placement^=left],.bs-popover-left{margin-right:.5rem}.bs-popover-auto[x-placement^=left]>.arrow,.bs-popover-left>.arrow{right:calc(-.5rem - 1px);width:.5rem;height:1rem;margin:.3rem 0}.bs-popover-auto[x-placement^=left]>.arrow::before,.bs-popover-left>.arrow::before{right:0;border-width:.5rem 0 .5rem .5rem;border-left-color:rgba(0,0,0,.25)}.bs-popover-auto[x-placement^=left]>.arrow::after,.bs-popover-left>.arrow::after{right:1px;border-width:.5rem 0 .5rem .5rem;border-left-color:#fff}.popover-header{padding:.5rem .75rem;margin-bottom:0;font-size:1rem;background-color:#f7f7f7;border-bottom:1px solid #ebebeb;border-top-left-radius:calc(.3rem - 1px);border-top-right-radius:calc(.3rem - 1px)}.popover-header:empty{display:none}.popover-body{padding:.5rem .75rem;color:#212529}.carousel{position:relative}.carousel.pointer-event{-ms-touch-action:pan-y;touch-action:pan-y}.carousel-inner{position:relative;width:100%;overflow:hidden}.carousel-inner::after{display:block;clear:both;content:\\\"\\\"}.carousel-item{position:relative;display:none;float:left;width:100%;margin-right:-100%;-webkit-backface-visibility:hidden;backface-visibility:hidden;transition:-webkit-transform .6s ease-in-out;transition:transform .6s ease-in-out;transition:transform .6s ease-in-out,-webkit-transform .6s ease-in-out}@media (prefers-reduced-motion:reduce){.carousel-item{transition:none}}.carousel-item-next,.carousel-item-prev,.carousel-item.active{display:block}.active.carousel-item-right,.carousel-item-next:not(.carousel-item-left){-webkit-transform:translateX(100%);transform:translateX(100%)}.active.carousel-item-left,.carousel-item-prev:not(.carousel-item-right){-webkit-transform:translateX(-100%);transform:translateX(-100%)}.carousel-fade .carousel-item{opacity:0;transition-property:opacity;-webkit-transform:none;transform:none}.carousel-fade .carousel-item-next.carousel-item-left,.carousel-fade .carousel-item-prev.carousel-item-right,.carousel-fade .carousel-item.active{z-index:1;opacity:1}.carousel-fade .active.carousel-item-left,.carousel-fade .active.carousel-item-right{z-index:0;opacity:0;transition:opacity 0s .6s}@media (prefers-reduced-motion:reduce){.carousel-fade .active.carousel-item-left,.carousel-fade .active.carousel-item-right{transition:none}}.carousel-control-next,.carousel-control-prev{position:absolute;top:0;bottom:0;z-index:1;display:-ms-flexbox;display:flex;-ms-flex-align:center;align-items:center;-ms-flex-pack:center;justify-content:center;width:15%;color:#fff;text-align:center;opacity:.5;transition:opacity .15s ease}@media (prefers-reduced-motion:reduce){.carousel-control-next,.carousel-control-prev{transition:none}}.carousel-control-next:focus,.carousel-control-next:hover,.carousel-control-prev:focus,.carousel-control-prev:hover{color:#fff;text-decoration:none;outline:0;opacity:.9}.carousel-control-prev{left:0}.carousel-control-next{right:0}.carousel-control-next-icon,.carousel-control-prev-icon{display:inline-block;width:20px;height:20px;background:no-repeat 50%/100% 100%}.carousel-control-prev-icon{background-image:url(\\\"data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' fill='%23fff' width='8' height='8' viewBox='0 0 8 8'%3e%3cpath d='M5.25 0l-4 4 4 4 1.5-1.5L4.25 4l2.5-2.5L5.25 0z'/%3e%3c/svg%3e\\\")}.carousel-control-next-icon{background-image:url(\\\"data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' fill='%23fff' width='8' height='8' viewBox='0 0 8 8'%3e%3cpath d='M2.75 0l-1.5 1.5L3.75 4l-2.5 2.5L2.75 8l4-4-4-4z'/%3e%3c/svg%3e\\\")}.carousel-indicators{position:absolute;right:0;bottom:0;left:0;z-index:15;display:-ms-flexbox;display:flex;-ms-flex-pack:center;justify-content:center;padding-left:0;margin-right:15%;margin-left:15%;list-style:none}.carousel-indicators li{box-sizing:content-box;-ms-flex:0 1 auto;flex:0 1 auto;width:30px;height:3px;margin-right:3px;margin-left:3px;text-indent:-999px;cursor:pointer;background-color:#fff;background-clip:padding-box;border-top:10px solid transparent;border-bottom:10px solid transparent;opacity:.5;transition:opacity .6s ease}@media (prefers-reduced-motion:reduce){.carousel-indicators li{transition:none}}.carousel-indicators .active{opacity:1}.carousel-caption{position:absolute;right:15%;bottom:20px;left:15%;z-index:10;padding-top:20px;padding-bottom:20px;color:#fff;text-align:center}@-webkit-keyframes spinner-border{to{-webkit-transform:rotate(360deg);transform:rotate(360deg)}}@keyframes spinner-border{to{-webkit-transform:rotate(360deg);transform:rotate(360deg)}}.spinner-border{display:inline-block;width:2rem;height:2rem;vertical-align:text-bottom;border:.25em solid currentColor;border-right-color:transparent;border-radius:50%;-webkit-animation:spinner-border .75s linear infinite;animation:spinner-border .75s linear infinite}.spinner-border-sm{width:1rem;height:1rem;border-width:.2em}@-webkit-keyframes spinner-grow{0%{-webkit-transform:scale(0);transform:scale(0)}50%{opacity:1}}@keyframes spinner-grow{0%{-webkit-transform:scale(0);transform:scale(0)}50%{opacity:1}}.spinner-grow{display:inline-block;width:2rem;height:2rem;vertical-align:text-bottom;background-color:currentColor;border-radius:50%;opacity:0;-webkit-animation:spinner-grow .75s linear infinite;animation:spinner-grow .75s linear infinite}.spinner-grow-sm{width:1rem;height:1rem}.align-baseline{vertical-align:baseline!important}.align-top{vertical-align:top!important}.align-middle{vertical-align:middle!important}.align-bottom{vertical-align:bottom!important}.align-text-bottom{vertical-align:text-bottom!important}.align-text-top{vertical-align:text-top!important}.bg-primary{background-color:#007bff!important}a.bg-primary:focus,a.bg-primary:hover,button.bg-primary:focus,button.bg-primary:hover{background-color:#0062cc!important}.bg-secondary{background-color:#6c757d!important}a.bg-secondary:focus,a.bg-secondary:hover,button.bg-secondary:focus,button.bg-secondary:hover{background-color:#545b62!important}.bg-success{background-color:#28a745!important}a.bg-success:focus,a.bg-success:hover,button.bg-success:focus,button.bg-success:hover{background-color:#1e7e34!important}.bg-info{background-color:#17a2b8!important}a.bg-info:focus,a.bg-info:hover,button.bg-info:focus,button.bg-info:hover{background-color:#117a8b!important}.bg-warning{background-color:#ffc107!important}a.bg-warning:focus,a.bg-warning:hover,button.bg-warning:focus,button.bg-warning:hover{background-color:#d39e00!important}.bg-danger{background-color:#dc3545!important}a.bg-danger:focus,a.bg-danger:hover,button.bg-danger:focus,button.bg-danger:hover{background-color:#bd2130!important}.bg-light{background-color:#f8f9fa!important}a.bg-light:focus,a.bg-light:hover,button.bg-light:focus,button.bg-light:hover{background-color:#dae0e5!important}.bg-dark{background-color:#343a40!important}a.bg-dark:focus,a.bg-dark:hover,button.bg-dark:focus,button.bg-dark:hover{background-color:#1d2124!important}.bg-white{background-color:#fff!important}.bg-transparent{background-color:transparent!important}.border{border:1px solid #dee2e6!important}.border-top{border-top:1px solid #dee2e6!important}.border-right{border-right:1px solid #dee2e6!important}.border-bottom{border-bottom:1px solid #dee2e6!important}.border-left{border-left:1px solid #dee2e6!important}.border-0{border:0!important}.border-top-0{border-top:0!important}.border-right-0{border-right:0!important}.border-bottom-0{border-bottom:0!important}.border-left-0{border-left:0!important}.border-primary{border-color:#007bff!important}.border-secondary{border-color:#6c757d!important}.border-success{border-color:#28a745!important}.border-info{border-color:#17a2b8!important}.border-warning{border-color:#ffc107!important}.border-danger{border-color:#dc3545!important}.border-light{border-color:#f8f9fa!important}.border-dark{border-color:#343a40!important}.border-white{border-color:#fff!important}.rounded-sm{border-radius:.2rem!important}.rounded{border-radius:.25rem!important}.rounded-top{border-top-left-radius:.25rem!important;border-top-right-radius:.25rem!important}.rounded-right{border-top-right-radius:.25rem!important;border-bottom-right-radius:.25rem!important}.rounded-bottom{border-bottom-right-radius:.25rem!important;border-bottom-left-radius:.25rem!important}.rounded-left{border-top-left-radius:.25rem!important;border-bottom-left-radius:.25rem!important}.rounded-lg{border-radius:.3rem!important}.rounded-circle{border-radius:50%!important}.rounded-pill{border-radius:50rem!important}.rounded-0{border-radius:0!important}.clearfix::after{display:block;clear:both;content:\\\"\\\"}.d-none{display:none!important}.d-inline{display:inline!important}.d-inline-block{display:inline-block!important}.d-block{display:block!important}.d-table{display:table!important}.d-table-row{display:table-row!important}.d-table-cell{display:table-cell!important}.d-flex{display:-ms-flexbox!important;display:flex!important}.d-inline-flex{display:-ms-inline-flexbox!important;display:inline-flex!important}@media (min-width:576px){.d-sm-none{display:none!important}.d-sm-inline{display:inline!important}.d-sm-inline-block{display:inline-block!important}.d-sm-block{display:block!important}.d-sm-table{display:table!important}.d-sm-table-row{display:table-row!important}.d-sm-table-cell{display:table-cell!important}.d-sm-flex{display:-ms-flexbox!important;display:flex!important}.d-sm-inline-flex{display:-ms-inline-flexbox!important;display:inline-flex!important}}@media (min-width:768px){.d-md-none{display:none!important}.d-md-inline{display:inline!important}.d-md-inline-block{display:inline-block!important}.d-md-block{display:block!important}.d-md-table{display:table!important}.d-md-table-row{display:table-row!important}.d-md-table-cell{display:table-cell!important}.d-md-flex{display:-ms-flexbox!important;display:flex!important}.d-md-inline-flex{display:-ms-inline-flexbox!important;display:inline-flex!important}}@media (min-width:992px){.d-lg-none{display:none!important}.d-lg-inline{display:inline!important}.d-lg-inline-block{display:inline-block!important}.d-lg-block{display:block!important}.d-lg-table{display:table!important}.d-lg-table-row{display:table-row!important}.d-lg-table-cell{display:table-cell!important}.d-lg-flex{display:-ms-flexbox!important;display:flex!important}.d-lg-inline-flex{display:-ms-inline-flexbox!important;display:inline-flex!important}}@media (min-width:1200px){.d-xl-none{display:none!important}.d-xl-inline{display:inline!important}.d-xl-inline-block{display:inline-block!important}.d-xl-block{display:block!important}.d-xl-table{display:table!important}.d-xl-table-row{display:table-row!important}.d-xl-table-cell{display:table-cell!important}.d-xl-flex{display:-ms-flexbox!important;display:flex!important}.d-xl-inline-flex{display:-ms-inline-flexbox!important;display:inline-flex!important}}@media print{.d-print-none{display:none!important}.d-print-inline{display:inline!important}.d-print-inline-block{display:inline-block!important}.d-print-block{display:block!important}.d-print-table{display:table!important}.d-print-table-row{display:table-row!important}.d-print-table-cell{display:table-cell!important}.d-print-flex{display:-ms-flexbox!important;display:flex!important}.d-print-inline-flex{display:-ms-inline-flexbox!important;display:inline-flex!important}}.embed-responsive{position:relative;display:block;width:100%;padding:0;overflow:hidden}.embed-responsive::before{display:block;content:\\\"\\\"}.embed-responsive .embed-responsive-item,.embed-responsive embed,.embed-responsive iframe,.embed-responsive object,.embed-responsive video{position:absolute;top:0;bottom:0;left:0;width:100%;height:100%;border:0}.embed-responsive-21by9::before{padding-top:42.857143%}.embed-responsive-16by9::before{padding-top:56.25%}.embed-responsive-4by3::before{padding-top:75%}.embed-responsive-1by1::before{padding-top:100%}.flex-row{-ms-flex-direction:row!important;flex-direction:row!important}.flex-column{-ms-flex-direction:column!important;flex-direction:column!important}.flex-row-reverse{-ms-flex-direction:row-reverse!important;flex-direction:row-reverse!important}.flex-column-reverse{-ms-flex-direction:column-reverse!important;flex-direction:column-reverse!important}.flex-wrap{-ms-flex-wrap:wrap!important;flex-wrap:wrap!important}.flex-nowrap{-ms-flex-wrap:nowrap!important;flex-wrap:nowrap!important}.flex-wrap-reverse{-ms-flex-wrap:wrap-reverse!important;flex-wrap:wrap-reverse!important}.flex-fill{-ms-flex:1 1 auto!important;flex:1 1 auto!important}.flex-grow-0{-ms-flex-positive:0!important;flex-grow:0!important}.flex-grow-1{-ms-flex-positive:1!important;flex-grow:1!important}.flex-shrink-0{-ms-flex-negative:0!important;flex-shrink:0!important}.flex-shrink-1{-ms-flex-negative:1!important;flex-shrink:1!important}.justify-content-start{-ms-flex-pack:start!important;justify-content:flex-start!important}.justify-content-end{-ms-flex-pack:end!important;justify-content:flex-end!important}.justify-content-center{-ms-flex-pack:center!important;justify-content:center!important}.justify-content-between{-ms-flex-pack:justify!important;justify-content:space-between!important}.justify-content-around{-ms-flex-pack:distribute!important;justify-content:space-around!important}.align-items-start{-ms-flex-align:start!important;align-items:flex-start!important}.align-items-end{-ms-flex-align:end!important;align-items:flex-end!important}.align-items-center{-ms-flex-align:center!important;align-items:center!important}.align-items-baseline{-ms-flex-align:baseline!important;align-items:baseline!important}.align-items-stretch{-ms-flex-align:stretch!important;align-items:stretch!important}.align-content-start{-ms-flex-line-pack:start!important;align-content:flex-start!important}.align-content-end{-ms-flex-line-pack:end!important;align-content:flex-end!important}.align-content-center{-ms-flex-line-pack:center!important;align-content:center!important}.align-content-between{-ms-flex-line-pack:justify!important;align-content:space-between!important}.align-content-around{-ms-flex-line-pack:distribute!important;align-content:space-around!important}.align-content-stretch{-ms-flex-line-pack:stretch!important;align-content:stretch!important}.align-self-auto{-ms-flex-item-align:auto!important;align-self:auto!important}.align-self-start{-ms-flex-item-align:start!important;align-self:flex-start!important}.align-self-end{-ms-flex-item-align:end!important;align-self:flex-end!important}.align-self-center{-ms-flex-item-align:center!important;align-self:center!important}.align-self-baseline{-ms-flex-item-align:baseline!important;align-self:baseline!important}.align-self-stretch{-ms-flex-item-align:stretch!important;align-self:stretch!important}@media (min-width:576px){.flex-sm-row{-ms-flex-direction:row!important;flex-direction:row!important}.flex-sm-column{-ms-flex-direction:column!important;flex-direction:column!important}.flex-sm-row-reverse{-ms-flex-direction:row-reverse!important;flex-direction:row-reverse!important}.flex-sm-column-reverse{-ms-flex-direction:column-reverse!important;flex-direction:column-reverse!important}.flex-sm-wrap{-ms-flex-wrap:wrap!important;flex-wrap:wrap!important}.flex-sm-nowrap{-ms-flex-wrap:nowrap!important;flex-wrap:nowrap!important}.flex-sm-wrap-reverse{-ms-flex-wrap:wrap-reverse!important;flex-wrap:wrap-reverse!important}.flex-sm-fill{-ms-flex:1 1 auto!important;flex:1 1 auto!important}.flex-sm-grow-0{-ms-flex-positive:0!important;flex-grow:0!important}.flex-sm-grow-1{-ms-flex-positive:1!important;flex-grow:1!important}.flex-sm-shrink-0{-ms-flex-negative:0!important;flex-shrink:0!important}.flex-sm-shrink-1{-ms-flex-negative:1!important;flex-shrink:1!important}.justify-content-sm-start{-ms-flex-pack:start!important;justify-content:flex-start!important}.justify-content-sm-end{-ms-flex-pack:end!important;justify-content:flex-end!important}.justify-content-sm-center{-ms-flex-pack:center!important;justify-content:center!important}.justify-content-sm-between{-ms-flex-pack:justify!important;justify-content:space-between!important}.justify-content-sm-around{-ms-flex-pack:distribute!important;justify-content:space-around!important}.align-items-sm-start{-ms-flex-align:start!important;align-items:flex-start!important}.align-items-sm-end{-ms-flex-align:end!important;align-items:flex-end!important}.align-items-sm-center{-ms-flex-align:center!important;align-items:center!important}.align-items-sm-baseline{-ms-flex-align:baseline!important;align-items:baseline!important}.align-items-sm-stretch{-ms-flex-align:stretch!important;align-items:stretch!important}.align-content-sm-start{-ms-flex-line-pack:start!important;align-content:flex-start!important}.align-content-sm-end{-ms-flex-line-pack:end!important;align-content:flex-end!important}.align-content-sm-center{-ms-flex-line-pack:center!important;align-content:center!important}.align-content-sm-between{-ms-flex-line-pack:justify!important;align-content:space-between!important}.align-content-sm-around{-ms-flex-line-pack:distribute!important;align-content:space-around!important}.align-content-sm-stretch{-ms-flex-line-pack:stretch!important;align-content:stretch!important}.align-self-sm-auto{-ms-flex-item-align:auto!important;align-self:auto!important}.align-self-sm-start{-ms-flex-item-align:start!important;align-self:flex-start!important}.align-self-sm-end{-ms-flex-item-align:end!important;align-self:flex-end!important}.align-self-sm-center{-ms-flex-item-align:center!important;align-self:center!important}.align-self-sm-baseline{-ms-flex-item-align:baseline!important;align-self:baseline!important}.align-self-sm-stretch{-ms-flex-item-align:stretch!important;align-self:stretch!important}}@media (min-width:768px){.flex-md-row{-ms-flex-direction:row!important;flex-direction:row!important}.flex-md-column{-ms-flex-direction:column!important;flex-direction:column!important}.flex-md-row-reverse{-ms-flex-direction:row-reverse!important;flex-direction:row-reverse!important}.flex-md-column-reverse{-ms-flex-direction:column-reverse!important;flex-direction:column-reverse!important}.flex-md-wrap{-ms-flex-wrap:wrap!important;flex-wrap:wrap!important}.flex-md-nowrap{-ms-flex-wrap:nowrap!important;flex-wrap:nowrap!important}.flex-md-wrap-reverse{-ms-flex-wrap:wrap-reverse!important;flex-wrap:wrap-reverse!important}.flex-md-fill{-ms-flex:1 1 auto!important;flex:1 1 auto!important}.flex-md-grow-0{-ms-flex-positive:0!important;flex-grow:0!important}.flex-md-grow-1{-ms-flex-positive:1!important;flex-grow:1!important}.flex-md-shrink-0{-ms-flex-negative:0!important;flex-shrink:0!important}.flex-md-shrink-1{-ms-flex-negative:1!important;flex-shrink:1!important}.justify-content-md-start{-ms-flex-pack:start!important;justify-content:flex-start!important}.justify-content-md-end{-ms-flex-pack:end!important;justify-content:flex-end!important}.justify-content-md-center{-ms-flex-pack:center!important;justify-content:center!important}.justify-content-md-between{-ms-flex-pack:justify!important;justify-content:space-between!important}.justify-content-md-around{-ms-flex-pack:distribute!important;justify-content:space-around!important}.align-items-md-start{-ms-flex-align:start!important;align-items:flex-start!important}.align-items-md-end{-ms-flex-align:end!important;align-items:flex-end!important}.align-items-md-center{-ms-flex-align:center!important;align-items:center!important}.align-items-md-baseline{-ms-flex-align:baseline!important;align-items:baseline!important}.align-items-md-stretch{-ms-flex-align:stretch!important;align-items:stretch!important}.align-content-md-start{-ms-flex-line-pack:start!important;align-content:flex-start!important}.align-content-md-end{-ms-flex-line-pack:end!important;align-content:flex-end!important}.align-content-md-center{-ms-flex-line-pack:center!important;align-content:center!important}.align-content-md-between{-ms-flex-line-pack:justify!important;align-content:space-between!important}.align-content-md-around{-ms-flex-line-pack:distribute!important;align-content:space-around!important}.align-content-md-stretch{-ms-flex-line-pack:stretch!important;align-content:stretch!important}.align-self-md-auto{-ms-flex-item-align:auto!important;align-self:auto!important}.align-self-md-start{-ms-flex-item-align:start!important;align-self:flex-start!important}.align-self-md-end{-ms-flex-item-align:end!important;align-self:flex-end!important}.align-self-md-center{-ms-flex-item-align:center!important;align-self:center!important}.align-self-md-baseline{-ms-flex-item-align:baseline!important;align-self:baseline!important}.align-self-md-stretch{-ms-flex-item-align:stretch!important;align-self:stretch!important}}@media (min-width:992px){.flex-lg-row{-ms-flex-direction:row!important;flex-direction:row!important}.flex-lg-column{-ms-flex-direction:column!important;flex-direction:column!important}.flex-lg-row-reverse{-ms-flex-direction:row-reverse!important;flex-direction:row-reverse!important}.flex-lg-column-reverse{-ms-flex-direction:column-reverse!important;flex-direction:column-reverse!important}.flex-lg-wrap{-ms-flex-wrap:wrap!important;flex-wrap:wrap!important}.flex-lg-nowrap{-ms-flex-wrap:nowrap!important;flex-wrap:nowrap!important}.flex-lg-wrap-reverse{-ms-flex-wrap:wrap-reverse!important;flex-wrap:wrap-reverse!important}.flex-lg-fill{-ms-flex:1 1 auto!important;flex:1 1 auto!important}.flex-lg-grow-0{-ms-flex-positive:0!important;flex-grow:0!important}.flex-lg-grow-1{-ms-flex-positive:1!important;flex-grow:1!important}.flex-lg-shrink-0{-ms-flex-negative:0!important;flex-shrink:0!important}.flex-lg-shrink-1{-ms-flex-negative:1!important;flex-shrink:1!important}.justify-content-lg-start{-ms-flex-pack:start!important;justify-content:flex-start!important}.justify-content-lg-end{-ms-flex-pack:end!important;justify-content:flex-end!important}.justify-content-lg-center{-ms-flex-pack:center!important;justify-content:center!important}.justify-content-lg-between{-ms-flex-pack:justify!important;justify-content:space-between!important}.justify-content-lg-around{-ms-flex-pack:distribute!important;justify-content:space-around!important}.align-items-lg-start{-ms-flex-align:start!important;align-items:flex-start!important}.align-items-lg-end{-ms-flex-align:end!important;align-items:flex-end!important}.align-items-lg-center{-ms-flex-align:center!important;align-items:center!important}.align-items-lg-baseline{-ms-flex-align:baseline!important;align-items:baseline!important}.align-items-lg-stretch{-ms-flex-align:stretch!important;align-items:stretch!important}.align-content-lg-start{-ms-flex-line-pack:start!important;align-content:flex-start!important}.align-content-lg-end{-ms-flex-line-pack:end!important;align-content:flex-end!important}.align-content-lg-center{-ms-flex-line-pack:center!important;align-content:center!important}.align-content-lg-between{-ms-flex-line-pack:justify!important;align-content:space-between!important}.align-content-lg-around{-ms-flex-line-pack:distribute!important;align-content:space-around!important}.align-content-lg-stretch{-ms-flex-line-pack:stretch!important;align-content:stretch!important}.align-self-lg-auto{-ms-flex-item-align:auto!important;align-self:auto!important}.align-self-lg-start{-ms-flex-item-align:start!important;align-self:flex-start!important}.align-self-lg-end{-ms-flex-item-align:end!important;align-self:flex-end!important}.align-self-lg-center{-ms-flex-item-align:center!important;align-self:center!important}.align-self-lg-baseline{-ms-flex-item-align:baseline!important;align-self:baseline!important}.align-self-lg-stretch{-ms-flex-item-align:stretch!important;align-self:stretch!important}}@media (min-width:1200px){.flex-xl-row{-ms-flex-direction:row!important;flex-direction:row!important}.flex-xl-column{-ms-flex-direction:column!important;flex-direction:column!important}.flex-xl-row-reverse{-ms-flex-direction:row-reverse!important;flex-direction:row-reverse!important}.flex-xl-column-reverse{-ms-flex-direction:column-reverse!important;flex-direction:column-reverse!important}.flex-xl-wrap{-ms-flex-wrap:wrap!important;flex-wrap:wrap!important}.flex-xl-nowrap{-ms-flex-wrap:nowrap!important;flex-wrap:nowrap!important}.flex-xl-wrap-reverse{-ms-flex-wrap:wrap-reverse!important;flex-wrap:wrap-reverse!important}.flex-xl-fill{-ms-flex:1 1 auto!important;flex:1 1 auto!important}.flex-xl-grow-0{-ms-flex-positive:0!important;flex-grow:0!important}.flex-xl-grow-1{-ms-flex-positive:1!important;flex-grow:1!important}.flex-xl-shrink-0{-ms-flex-negative:0!important;flex-shrink:0!important}.flex-xl-shrink-1{-ms-flex-negative:1!important;flex-shrink:1!important}.justify-content-xl-start{-ms-flex-pack:start!important;justify-content:flex-start!important}.justify-content-xl-end{-ms-flex-pack:end!important;justify-content:flex-end!important}.justify-content-xl-center{-ms-flex-pack:center!important;justify-content:center!important}.justify-content-xl-between{-ms-flex-pack:justify!important;justify-content:space-between!important}.justify-content-xl-around{-ms-flex-pack:distribute!important;justify-content:space-around!important}.align-items-xl-start{-ms-flex-align:start!important;align-items:flex-start!important}.align-items-xl-end{-ms-flex-align:end!important;align-items:flex-end!important}.align-items-xl-center{-ms-flex-align:center!important;align-items:center!important}.align-items-xl-baseline{-ms-flex-align:baseline!important;align-items:baseline!important}.align-items-xl-stretch{-ms-flex-align:stretch!important;align-items:stretch!important}.align-content-xl-start{-ms-flex-line-pack:start!important;align-content:flex-start!important}.align-content-xl-end{-ms-flex-line-pack:end!important;align-content:flex-end!important}.align-content-xl-center{-ms-flex-line-pack:center!important;align-content:center!important}.align-content-xl-between{-ms-flex-line-pack:justify!important;align-content:space-between!important}.align-content-xl-around{-ms-flex-line-pack:distribute!important;align-content:space-around!important}.align-content-xl-stretch{-ms-flex-line-pack:stretch!important;align-content:stretch!important}.align-self-xl-auto{-ms-flex-item-align:auto!important;align-self:auto!important}.align-self-xl-start{-ms-flex-item-align:start!important;align-self:flex-start!important}.align-self-xl-end{-ms-flex-item-align:end!important;align-self:flex-end!important}.align-self-xl-center{-ms-flex-item-align:center!important;align-self:center!important}.align-self-xl-baseline{-ms-flex-item-align:baseline!important;align-self:baseline!important}.align-self-xl-stretch{-ms-flex-item-align:stretch!important;align-self:stretch!important}}.float-left{float:left!important}.float-right{float:right!important}.float-none{float:none!important}@media (min-width:576px){.float-sm-left{float:left!important}.float-sm-right{float:right!important}.float-sm-none{float:none!important}}@media (min-width:768px){.float-md-left{float:left!important}.float-md-right{float:right!important}.float-md-none{float:none!important}}@media (min-width:992px){.float-lg-left{float:left!important}.float-lg-right{float:right!important}.float-lg-none{float:none!important}}@media (min-width:1200px){.float-xl-left{float:left!important}.float-xl-right{float:right!important}.float-xl-none{float:none!important}}.overflow-auto{overflow:auto!important}.overflow-hidden{overflow:hidden!important}.position-static{position:static!important}.position-relative{position:relative!important}.position-absolute{position:absolute!important}.position-fixed{position:fixed!important}.position-sticky{position:-webkit-sticky!important;position:sticky!important}.fixed-top{position:fixed;top:0;right:0;left:0;z-index:1030}.fixed-bottom{position:fixed;right:0;bottom:0;left:0;z-index:1030}@supports ((position:-webkit-sticky) or (position:sticky)){.sticky-top{position:-webkit-sticky;position:sticky;top:0;z-index:1020}}.sr-only{position:absolute;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip:rect(0,0,0,0);white-space:nowrap;border:0}.sr-only-focusable:active,.sr-only-focusable:focus{position:static;width:auto;height:auto;overflow:visible;clip:auto;white-space:normal}.shadow-sm{box-shadow:0 .125rem .25rem rgba(0,0,0,.075)!important}.shadow{box-shadow:0 .5rem 1rem rgba(0,0,0,.15)!important}.shadow-lg{box-shadow:0 1rem 3rem rgba(0,0,0,.175)!important}.shadow-none{box-shadow:none!important}.w-25{width:25%!important}.w-50{width:50%!important}.w-75{width:75%!important}.w-100{width:100%!important}.w-auto{width:auto!important}.h-25{height:25%!important}.h-50{height:50%!important}.h-75{height:75%!important}.h-100{height:100%!important}.h-auto{height:auto!important}.mw-100{max-width:100%!important}.mh-100{max-height:100%!important}.min-vw-100{min-width:100vw!important}.min-vh-100{min-height:100vh!important}.vw-100{width:100vw!important}.vh-100{height:100vh!important}.stretched-link::after{position:absolute;top:0;right:0;bottom:0;left:0;z-index:1;pointer-events:auto;content:\\\"\\\";background-color:rgba(0,0,0,0)}.m-0{margin:0!important}.mt-0,.my-0{margin-top:0!important}.mr-0,.mx-0{margin-right:0!important}.mb-0,.my-0{margin-bottom:0!important}.ml-0,.mx-0{margin-left:0!important}.m-1{margin:.25rem!important}.mt-1,.my-1{margin-top:.25rem!important}.mr-1,.mx-1{margin-right:.25rem!important}.mb-1,.my-1{margin-bottom:.25rem!important}.ml-1,.mx-1{margin-left:.25rem!important}.m-2{margin:.5rem!important}.mt-2,.my-2{margin-top:.5rem!important}.mr-2,.mx-2{margin-right:.5rem!important}.mb-2,.my-2{margin-bottom:.5rem!important}.ml-2,.mx-2{margin-left:.5rem!important}.m-3{margin:1rem!important}.mt-3,.my-3{margin-top:1rem!important}.mr-3,.mx-3{margin-right:1rem!important}.mb-3,.my-3{margin-bottom:1rem!important}.ml-3,.mx-3{margin-left:1rem!important}.m-4{margin:1.5rem!important}.mt-4,.my-4{margin-top:1.5rem!important}.mr-4,.mx-4{margin-right:1.5rem!important}.mb-4,.my-4{margin-bottom:1.5rem!important}.ml-4,.mx-4{margin-left:1.5rem!important}.m-5{margin:3rem!important}.mt-5,.my-5{margin-top:3rem!important}.mr-5,.mx-5{margin-right:3rem!important}.mb-5,.my-5{margin-bottom:3rem!important}.ml-5,.mx-5{margin-left:3rem!important}.p-0{padding:0!important}.pt-0,.py-0{padding-top:0!important}.pr-0,.px-0{padding-right:0!important}.pb-0,.py-0{padding-bottom:0!important}.pl-0,.px-0{padding-left:0!important}.p-1{padding:.25rem!important}.pt-1,.py-1{padding-top:.25rem!important}.pr-1,.px-1{padding-right:.25rem!important}.pb-1,.py-1{padding-bottom:.25rem!important}.pl-1,.px-1{padding-left:.25rem!important}.p-2{padding:.5rem!important}.pt-2,.py-2{padding-top:.5rem!important}.pr-2,.px-2{padding-right:.5rem!important}.pb-2,.py-2{padding-bottom:.5rem!important}.pl-2,.px-2{padding-left:.5rem!important}.p-3{padding:1rem!important}.pt-3,.py-3{padding-top:1rem!important}.pr-3,.px-3{padding-right:1rem!important}.pb-3,.py-3{padding-bottom:1rem!important}.pl-3,.px-3{padding-left:1rem!important}.p-4{padding:1.5rem!important}.pt-4,.py-4{padding-top:1.5rem!important}.pr-4,.px-4{padding-right:1.5rem!important}.pb-4,.py-4{padding-bottom:1.5rem!important}.pl-4,.px-4{padding-left:1.5rem!important}.p-5{padding:3rem!important}.pt-5,.py-5{padding-top:3rem!important}.pr-5,.px-5{padding-right:3rem!important}.pb-5,.py-5{padding-bottom:3rem!important}.pl-5,.px-5{padding-left:3rem!important}.m-n1{margin:-.25rem!important}.mt-n1,.my-n1{margin-top:-.25rem!important}.mr-n1,.mx-n1{margin-right:-.25rem!important}.mb-n1,.my-n1{margin-bottom:-.25rem!important}.ml-n1,.mx-n1{margin-left:-.25rem!important}.m-n2{margin:-.5rem!important}.mt-n2,.my-n2{margin-top:-.5rem!important}.mr-n2,.mx-n2{margin-right:-.5rem!important}.mb-n2,.my-n2{margin-bottom:-.5rem!important}.ml-n2,.mx-n2{margin-left:-.5rem!important}.m-n3{margin:-1rem!important}.mt-n3,.my-n3{margin-top:-1rem!important}.mr-n3,.mx-n3{margin-right:-1rem!important}.mb-n3,.my-n3{margin-bottom:-1rem!important}.ml-n3,.mx-n3{margin-left:-1rem!important}.m-n4{margin:-1.5rem!important}.mt-n4,.my-n4{margin-top:-1.5rem!important}.mr-n4,.mx-n4{margin-right:-1.5rem!important}.mb-n4,.my-n4{margin-bottom:-1.5rem!important}.ml-n4,.mx-n4{margin-left:-1.5rem!important}.m-n5{margin:-3rem!important}.mt-n5,.my-n5{margin-top:-3rem!important}.mr-n5,.mx-n5{margin-right:-3rem!important}.mb-n5,.my-n5{margin-bottom:-3rem!important}.ml-n5,.mx-n5{margin-left:-3rem!important}.m-auto{margin:auto!important}.mt-auto,.my-auto{margin-top:auto!important}.mr-auto,.mx-auto{margin-right:auto!important}.mb-auto,.my-auto{margin-bottom:auto!important}.ml-auto,.mx-auto{margin-left:auto!important}@media (min-width:576px){.m-sm-0{margin:0!important}.mt-sm-0,.my-sm-0{margin-top:0!important}.mr-sm-0,.mx-sm-0{margin-right:0!important}.mb-sm-0,.my-sm-0{margin-bottom:0!important}.ml-sm-0,.mx-sm-0{margin-left:0!important}.m-sm-1{margin:.25rem!important}.mt-sm-1,.my-sm-1{margin-top:.25rem!important}.mr-sm-1,.mx-sm-1{margin-right:.25rem!important}.mb-sm-1,.my-sm-1{margin-bottom:.25rem!important}.ml-sm-1,.mx-sm-1{margin-left:.25rem!important}.m-sm-2{margin:.5rem!important}.mt-sm-2,.my-sm-2{margin-top:.5rem!important}.mr-sm-2,.mx-sm-2{margin-right:.5rem!important}.mb-sm-2,.my-sm-2{margin-bottom:.5rem!important}.ml-sm-2,.mx-sm-2{margin-left:.5rem!important}.m-sm-3{margin:1rem!important}.mt-sm-3,.my-sm-3{margin-top:1rem!important}.mr-sm-3,.mx-sm-3{margin-right:1rem!important}.mb-sm-3,.my-sm-3{margin-bottom:1rem!important}.ml-sm-3,.mx-sm-3{margin-left:1rem!important}.m-sm-4{margin:1.5rem!important}.mt-sm-4,.my-sm-4{margin-top:1.5rem!important}.mr-sm-4,.mx-sm-4{margin-right:1.5rem!important}.mb-sm-4,.my-sm-4{margin-bottom:1.5rem!important}.ml-sm-4,.mx-sm-4{margin-left:1.5rem!important}.m-sm-5{margin:3rem!important}.mt-sm-5,.my-sm-5{margin-top:3rem!important}.mr-sm-5,.mx-sm-5{margin-right:3rem!important}.mb-sm-5,.my-sm-5{margin-bottom:3rem!important}.ml-sm-5,.mx-sm-5{margin-left:3rem!important}.p-sm-0{padding:0!important}.pt-sm-0,.py-sm-0{padding-top:0!important}.pr-sm-0,.px-sm-0{padding-right:0!important}.pb-sm-0,.py-sm-0{padding-bottom:0!important}.pl-sm-0,.px-sm-0{padding-left:0!important}.p-sm-1{padding:.25rem!important}.pt-sm-1,.py-sm-1{padding-top:.25rem!important}.pr-sm-1,.px-sm-1{padding-right:.25rem!important}.pb-sm-1,.py-sm-1{padding-bottom:.25rem!important}.pl-sm-1,.px-sm-1{padding-left:.25rem!important}.p-sm-2{padding:.5rem!important}.pt-sm-2,.py-sm-2{padding-top:.5rem!important}.pr-sm-2,.px-sm-2{padding-right:.5rem!important}.pb-sm-2,.py-sm-2{padding-bottom:.5rem!important}.pl-sm-2,.px-sm-2{padding-left:.5rem!important}.p-sm-3{padding:1rem!important}.pt-sm-3,.py-sm-3{padding-top:1rem!important}.pr-sm-3,.px-sm-3{padding-right:1rem!important}.pb-sm-3,.py-sm-3{padding-bottom:1rem!important}.pl-sm-3,.px-sm-3{padding-left:1rem!important}.p-sm-4{padding:1.5rem!important}.pt-sm-4,.py-sm-4{padding-top:1.5rem!important}.pr-sm-4,.px-sm-4{padding-right:1.5rem!important}.pb-sm-4,.py-sm-4{padding-bottom:1.5rem!important}.pl-sm-4,.px-sm-4{padding-left:1.5rem!important}.p-sm-5{padding:3rem!important}.pt-sm-5,.py-sm-5{padding-top:3rem!important}.pr-sm-5,.px-sm-5{padding-right:3rem!important}.pb-sm-5,.py-sm-5{padding-bottom:3rem!important}.pl-sm-5,.px-sm-5{padding-left:3rem!important}.m-sm-n1{margin:-.25rem!important}.mt-sm-n1,.my-sm-n1{margin-top:-.25rem!important}.mr-sm-n1,.mx-sm-n1{margin-right:-.25rem!important}.mb-sm-n1,.my-sm-n1{margin-bottom:-.25rem!important}.ml-sm-n1,.mx-sm-n1{margin-left:-.25rem!important}.m-sm-n2{margin:-.5rem!important}.mt-sm-n2,.my-sm-n2{margin-top:-.5rem!important}.mr-sm-n2,.mx-sm-n2{margin-right:-.5rem!important}.mb-sm-n2,.my-sm-n2{margin-bottom:-.5rem!important}.ml-sm-n2,.mx-sm-n2{margin-left:-.5rem!important}.m-sm-n3{margin:-1rem!important}.mt-sm-n3,.my-sm-n3{margin-top:-1rem!important}.mr-sm-n3,.mx-sm-n3{margin-right:-1rem!important}.mb-sm-n3,.my-sm-n3{margin-bottom:-1rem!important}.ml-sm-n3,.mx-sm-n3{margin-left:-1rem!important}.m-sm-n4{margin:-1.5rem!important}.mt-sm-n4,.my-sm-n4{margin-top:-1.5rem!important}.mr-sm-n4,.mx-sm-n4{margin-right:-1.5rem!important}.mb-sm-n4,.my-sm-n4{margin-bottom:-1.5rem!important}.ml-sm-n4,.mx-sm-n4{margin-left:-1.5rem!important}.m-sm-n5{margin:-3rem!important}.mt-sm-n5,.my-sm-n5{margin-top:-3rem!important}.mr-sm-n5,.mx-sm-n5{margin-right:-3rem!important}.mb-sm-n5,.my-sm-n5{margin-bottom:-3rem!important}.ml-sm-n5,.mx-sm-n5{margin-left:-3rem!important}.m-sm-auto{margin:auto!important}.mt-sm-auto,.my-sm-auto{margin-top:auto!important}.mr-sm-auto,.mx-sm-auto{margin-right:auto!important}.mb-sm-auto,.my-sm-auto{margin-bottom:auto!important}.ml-sm-auto,.mx-sm-auto{margin-left:auto!important}}@media (min-width:768px){.m-md-0{margin:0!important}.mt-md-0,.my-md-0{margin-top:0!important}.mr-md-0,.mx-md-0{margin-right:0!important}.mb-md-0,.my-md-0{margin-bottom:0!important}.ml-md-0,.mx-md-0{margin-left:0!important}.m-md-1{margin:.25rem!important}.mt-md-1,.my-md-1{margin-top:.25rem!important}.mr-md-1,.mx-md-1{margin-right:.25rem!important}.mb-md-1,.my-md-1{margin-bottom:.25rem!important}.ml-md-1,.mx-md-1{margin-left:.25rem!important}.m-md-2{margin:.5rem!important}.mt-md-2,.my-md-2{margin-top:.5rem!important}.mr-md-2,.mx-md-2{margin-right:.5rem!important}.mb-md-2,.my-md-2{margin-bottom:.5rem!important}.ml-md-2,.mx-md-2{margin-left:.5rem!important}.m-md-3{margin:1rem!important}.mt-md-3,.my-md-3{margin-top:1rem!important}.mr-md-3,.mx-md-3{margin-right:1rem!important}.mb-md-3,.my-md-3{margin-bottom:1rem!important}.ml-md-3,.mx-md-3{margin-left:1rem!important}.m-md-4{margin:1.5rem!important}.mt-md-4,.my-md-4{margin-top:1.5rem!important}.mr-md-4,.mx-md-4{margin-right:1.5rem!important}.mb-md-4,.my-md-4{margin-bottom:1.5rem!important}.ml-md-4,.mx-md-4{margin-left:1.5rem!important}.m-md-5{margin:3rem!important}.mt-md-5,.my-md-5{margin-top:3rem!important}.mr-md-5,.mx-md-5{margin-right:3rem!important}.mb-md-5,.my-md-5{margin-bottom:3rem!important}.ml-md-5,.mx-md-5{margin-left:3rem!important}.p-md-0{padding:0!important}.pt-md-0,.py-md-0{padding-top:0!important}.pr-md-0,.px-md-0{padding-right:0!important}.pb-md-0,.py-md-0{padding-bottom:0!important}.pl-md-0,.px-md-0{padding-left:0!important}.p-md-1{padding:.25rem!important}.pt-md-1,.py-md-1{padding-top:.25rem!important}.pr-md-1,.px-md-1{padding-right:.25rem!important}.pb-md-1,.py-md-1{padding-bottom:.25rem!important}.pl-md-1,.px-md-1{padding-left:.25rem!important}.p-md-2{padding:.5rem!important}.pt-md-2,.py-md-2{padding-top:.5rem!important}.pr-md-2,.px-md-2{padding-right:.5rem!important}.pb-md-2,.py-md-2{padding-bottom:.5rem!important}.pl-md-2,.px-md-2{padding-left:.5rem!important}.p-md-3{padding:1rem!important}.pt-md-3,.py-md-3{padding-top:1rem!important}.pr-md-3,.px-md-3{padding-right:1rem!important}.pb-md-3,.py-md-3{padding-bottom:1rem!important}.pl-md-3,.px-md-3{padding-left:1rem!important}.p-md-4{padding:1.5rem!important}.pt-md-4,.py-md-4{padding-top:1.5rem!important}.pr-md-4,.px-md-4{padding-right:1.5rem!important}.pb-md-4,.py-md-4{padding-bottom:1.5rem!important}.pl-md-4,.px-md-4{padding-left:1.5rem!important}.p-md-5{padding:3rem!important}.pt-md-5,.py-md-5{padding-top:3rem!important}.pr-md-5,.px-md-5{padding-right:3rem!important}.pb-md-5,.py-md-5{padding-bottom:3rem!important}.pl-md-5,.px-md-5{padding-left:3rem!important}.m-md-n1{margin:-.25rem!important}.mt-md-n1,.my-md-n1{margin-top:-.25rem!important}.mr-md-n1,.mx-md-n1{margin-right:-.25rem!important}.mb-md-n1,.my-md-n1{margin-bottom:-.25rem!important}.ml-md-n1,.mx-md-n1{margin-left:-.25rem!important}.m-md-n2{margin:-.5rem!important}.mt-md-n2,.my-md-n2{margin-top:-.5rem!important}.mr-md-n2,.mx-md-n2{margin-right:-.5rem!important}.mb-md-n2,.my-md-n2{margin-bottom:-.5rem!important}.ml-md-n2,.mx-md-n2{margin-left:-.5rem!important}.m-md-n3{margin:-1rem!important}.mt-md-n3,.my-md-n3{margin-top:-1rem!important}.mr-md-n3,.mx-md-n3{margin-right:-1rem!important}.mb-md-n3,.my-md-n3{margin-bottom:-1rem!important}.ml-md-n3,.mx-md-n3{margin-left:-1rem!important}.m-md-n4{margin:-1.5rem!important}.mt-md-n4,.my-md-n4{margin-top:-1.5rem!important}.mr-md-n4,.mx-md-n4{margin-right:-1.5rem!important}.mb-md-n4,.my-md-n4{margin-bottom:-1.5rem!important}.ml-md-n4,.mx-md-n4{margin-left:-1.5rem!important}.m-md-n5{margin:-3rem!important}.mt-md-n5,.my-md-n5{margin-top:-3rem!important}.mr-md-n5,.mx-md-n5{margin-right:-3rem!important}.mb-md-n5,.my-md-n5{margin-bottom:-3rem!important}.ml-md-n5,.mx-md-n5{margin-left:-3rem!important}.m-md-auto{margin:auto!important}.mt-md-auto,.my-md-auto{margin-top:auto!important}.mr-md-auto,.mx-md-auto{margin-right:auto!important}.mb-md-auto,.my-md-auto{margin-bottom:auto!important}.ml-md-auto,.mx-md-auto{margin-left:auto!important}}@media (min-width:992px){.m-lg-0{margin:0!important}.mt-lg-0,.my-lg-0{margin-top:0!important}.mr-lg-0,.mx-lg-0{margin-right:0!important}.mb-lg-0,.my-lg-0{margin-bottom:0!important}.ml-lg-0,.mx-lg-0{margin-left:0!important}.m-lg-1{margin:.25rem!important}.mt-lg-1,.my-lg-1{margin-top:.25rem!important}.mr-lg-1,.mx-lg-1{margin-right:.25rem!important}.mb-lg-1,.my-lg-1{margin-bottom:.25rem!important}.ml-lg-1,.mx-lg-1{margin-left:.25rem!important}.m-lg-2{margin:.5rem!important}.mt-lg-2,.my-lg-2{margin-top:.5rem!important}.mr-lg-2,.mx-lg-2{margin-right:.5rem!important}.mb-lg-2,.my-lg-2{margin-bottom:.5rem!important}.ml-lg-2,.mx-lg-2{margin-left:.5rem!important}.m-lg-3{margin:1rem!important}.mt-lg-3,.my-lg-3{margin-top:1rem!important}.mr-lg-3,.mx-lg-3{margin-right:1rem!important}.mb-lg-3,.my-lg-3{margin-bottom:1rem!important}.ml-lg-3,.mx-lg-3{margin-left:1rem!important}.m-lg-4{margin:1.5rem!important}.mt-lg-4,.my-lg-4{margin-top:1.5rem!important}.mr-lg-4,.mx-lg-4{margin-right:1.5rem!important}.mb-lg-4,.my-lg-4{margin-bottom:1.5rem!important}.ml-lg-4,.mx-lg-4{margin-left:1.5rem!important}.m-lg-5{margin:3rem!important}.mt-lg-5,.my-lg-5{margin-top:3rem!important}.mr-lg-5,.mx-lg-5{margin-right:3rem!important}.mb-lg-5,.my-lg-5{margin-bottom:3rem!important}.ml-lg-5,.mx-lg-5{margin-left:3rem!important}.p-lg-0{padding:0!important}.pt-lg-0,.py-lg-0{padding-top:0!important}.pr-lg-0,.px-lg-0{padding-right:0!important}.pb-lg-0,.py-lg-0{padding-bottom:0!important}.pl-lg-0,.px-lg-0{padding-left:0!important}.p-lg-1{padding:.25rem!important}.pt-lg-1,.py-lg-1{padding-top:.25rem!important}.pr-lg-1,.px-lg-1{padding-right:.25rem!important}.pb-lg-1,.py-lg-1{padding-bottom:.25rem!important}.pl-lg-1,.px-lg-1{padding-left:.25rem!important}.p-lg-2{padding:.5rem!important}.pt-lg-2,.py-lg-2{padding-top:.5rem!important}.pr-lg-2,.px-lg-2{padding-right:.5rem!important}.pb-lg-2,.py-lg-2{padding-bottom:.5rem!important}.pl-lg-2,.px-lg-2{padding-left:.5rem!important}.p-lg-3{padding:1rem!important}.pt-lg-3,.py-lg-3{padding-top:1rem!important}.pr-lg-3,.px-lg-3{padding-right:1rem!important}.pb-lg-3,.py-lg-3{padding-bottom:1rem!important}.pl-lg-3,.px-lg-3{padding-left:1rem!important}.p-lg-4{padding:1.5rem!important}.pt-lg-4,.py-lg-4{padding-top:1.5rem!important}.pr-lg-4,.px-lg-4{padding-right:1.5rem!important}.pb-lg-4,.py-lg-4{padding-bottom:1.5rem!important}.pl-lg-4,.px-lg-4{padding-left:1.5rem!important}.p-lg-5{padding:3rem!important}.pt-lg-5,.py-lg-5{padding-top:3rem!important}.pr-lg-5,.px-lg-5{padding-right:3rem!important}.pb-lg-5,.py-lg-5{padding-bottom:3rem!important}.pl-lg-5,.px-lg-5{padding-left:3rem!important}.m-lg-n1{margin:-.25rem!important}.mt-lg-n1,.my-lg-n1{margin-top:-.25rem!important}.mr-lg-n1,.mx-lg-n1{margin-right:-.25rem!important}.mb-lg-n1,.my-lg-n1{margin-bottom:-.25rem!important}.ml-lg-n1,.mx-lg-n1{margin-left:-.25rem!important}.m-lg-n2{margin:-.5rem!important}.mt-lg-n2,.my-lg-n2{margin-top:-.5rem!important}.mr-lg-n2,.mx-lg-n2{margin-right:-.5rem!important}.mb-lg-n2,.my-lg-n2{margin-bottom:-.5rem!important}.ml-lg-n2,.mx-lg-n2{margin-left:-.5rem!important}.m-lg-n3{margin:-1rem!important}.mt-lg-n3,.my-lg-n3{margin-top:-1rem!important}.mr-lg-n3,.mx-lg-n3{margin-right:-1rem!important}.mb-lg-n3,.my-lg-n3{margin-bottom:-1rem!important}.ml-lg-n3,.mx-lg-n3{margin-left:-1rem!important}.m-lg-n4{margin:-1.5rem!important}.mt-lg-n4,.my-lg-n4{margin-top:-1.5rem!important}.mr-lg-n4,.mx-lg-n4{margin-right:-1.5rem!important}.mb-lg-n4,.my-lg-n4{margin-bottom:-1.5rem!important}.ml-lg-n4,.mx-lg-n4{margin-left:-1.5rem!important}.m-lg-n5{margin:-3rem!important}.mt-lg-n5,.my-lg-n5{margin-top:-3rem!important}.mr-lg-n5,.mx-lg-n5{margin-right:-3rem!important}.mb-lg-n5,.my-lg-n5{margin-bottom:-3rem!important}.ml-lg-n5,.mx-lg-n5{margin-left:-3rem!important}.m-lg-auto{margin:auto!important}.mt-lg-auto,.my-lg-auto{margin-top:auto!important}.mr-lg-auto,.mx-lg-auto{margin-right:auto!important}.mb-lg-auto,.my-lg-auto{margin-bottom:auto!important}.ml-lg-auto,.mx-lg-auto{margin-left:auto!important}}@media (min-width:1200px){.m-xl-0{margin:0!important}.mt-xl-0,.my-xl-0{margin-top:0!important}.mr-xl-0,.mx-xl-0{margin-right:0!important}.mb-xl-0,.my-xl-0{margin-bottom:0!important}.ml-xl-0,.mx-xl-0{margin-left:0!important}.m-xl-1{margin:.25rem!important}.mt-xl-1,.my-xl-1{margin-top:.25rem!important}.mr-xl-1,.mx-xl-1{margin-right:.25rem!important}.mb-xl-1,.my-xl-1{margin-bottom:.25rem!important}.ml-xl-1,.mx-xl-1{margin-left:.25rem!important}.m-xl-2{margin:.5rem!important}.mt-xl-2,.my-xl-2{margin-top:.5rem!important}.mr-xl-2,.mx-xl-2{margin-right:.5rem!important}.mb-xl-2,.my-xl-2{margin-bottom:.5rem!important}.ml-xl-2,.mx-xl-2{margin-left:.5rem!important}.m-xl-3{margin:1rem!important}.mt-xl-3,.my-xl-3{margin-top:1rem!important}.mr-xl-3,.mx-xl-3{margin-right:1rem!important}.mb-xl-3,.my-xl-3{margin-bottom:1rem!important}.ml-xl-3,.mx-xl-3{margin-left:1rem!important}.m-xl-4{margin:1.5rem!important}.mt-xl-4,.my-xl-4{margin-top:1.5rem!important}.mr-xl-4,.mx-xl-4{margin-right:1.5rem!important}.mb-xl-4,.my-xl-4{margin-bottom:1.5rem!important}.ml-xl-4,.mx-xl-4{margin-left:1.5rem!important}.m-xl-5{margin:3rem!important}.mt-xl-5,.my-xl-5{margin-top:3rem!important}.mr-xl-5,.mx-xl-5{margin-right:3rem!important}.mb-xl-5,.my-xl-5{margin-bottom:3rem!important}.ml-xl-5,.mx-xl-5{margin-left:3rem!important}.p-xl-0{padding:0!important}.pt-xl-0,.py-xl-0{padding-top:0!important}.pr-xl-0,.px-xl-0{padding-right:0!important}.pb-xl-0,.py-xl-0{padding-bottom:0!important}.pl-xl-0,.px-xl-0{padding-left:0!important}.p-xl-1{padding:.25rem!important}.pt-xl-1,.py-xl-1{padding-top:.25rem!important}.pr-xl-1,.px-xl-1{padding-right:.25rem!important}.pb-xl-1,.py-xl-1{padding-bottom:.25rem!important}.pl-xl-1,.px-xl-1{padding-left:.25rem!important}.p-xl-2{padding:.5rem!important}.pt-xl-2,.py-xl-2{padding-top:.5rem!important}.pr-xl-2,.px-xl-2{padding-right:.5rem!important}.pb-xl-2,.py-xl-2{padding-bottom:.5rem!important}.pl-xl-2,.px-xl-2{padding-left:.5rem!important}.p-xl-3{padding:1rem!important}.pt-xl-3,.py-xl-3{padding-top:1rem!important}.pr-xl-3,.px-xl-3{padding-right:1rem!important}.pb-xl-3,.py-xl-3{padding-bottom:1rem!important}.pl-xl-3,.px-xl-3{padding-left:1rem!important}.p-xl-4{padding:1.5rem!important}.pt-xl-4,.py-xl-4{padding-top:1.5rem!important}.pr-xl-4,.px-xl-4{padding-right:1.5rem!important}.pb-xl-4,.py-xl-4{padding-bottom:1.5rem!important}.pl-xl-4,.px-xl-4{padding-left:1.5rem!important}.p-xl-5{padding:3rem!important}.pt-xl-5,.py-xl-5{padding-top:3rem!important}.pr-xl-5,.px-xl-5{padding-right:3rem!important}.pb-xl-5,.py-xl-5{padding-bottom:3rem!important}.pl-xl-5,.px-xl-5{padding-left:3rem!important}.m-xl-n1{margin:-.25rem!important}.mt-xl-n1,.my-xl-n1{margin-top:-.25rem!important}.mr-xl-n1,.mx-xl-n1{margin-right:-.25rem!important}.mb-xl-n1,.my-xl-n1{margin-bottom:-.25rem!important}.ml-xl-n1,.mx-xl-n1{margin-left:-.25rem!important}.m-xl-n2{margin:-.5rem!important}.mt-xl-n2,.my-xl-n2{margin-top:-.5rem!important}.mr-xl-n2,.mx-xl-n2{margin-right:-.5rem!important}.mb-xl-n2,.my-xl-n2{margin-bottom:-.5rem!important}.ml-xl-n2,.mx-xl-n2{margin-left:-.5rem!important}.m-xl-n3{margin:-1rem!important}.mt-xl-n3,.my-xl-n3{margin-top:-1rem!important}.mr-xl-n3,.mx-xl-n3{margin-right:-1rem!important}.mb-xl-n3,.my-xl-n3{margin-bottom:-1rem!important}.ml-xl-n3,.mx-xl-n3{margin-left:-1rem!important}.m-xl-n4{margin:-1.5rem!important}.mt-xl-n4,.my-xl-n4{margin-top:-1.5rem!important}.mr-xl-n4,.mx-xl-n4{margin-right:-1.5rem!important}.mb-xl-n4,.my-xl-n4{margin-bottom:-1.5rem!important}.ml-xl-n4,.mx-xl-n4{margin-left:-1.5rem!important}.m-xl-n5{margin:-3rem!important}.mt-xl-n5,.my-xl-n5{margin-top:-3rem!important}.mr-xl-n5,.mx-xl-n5{margin-right:-3rem!important}.mb-xl-n5,.my-xl-n5{margin-bottom:-3rem!important}.ml-xl-n5,.mx-xl-n5{margin-left:-3rem!important}.m-xl-auto{margin:auto!important}.mt-xl-auto,.my-xl-auto{margin-top:auto!important}.mr-xl-auto,.mx-xl-auto{margin-right:auto!important}.mb-xl-auto,.my-xl-auto{margin-bottom:auto!important}.ml-xl-auto,.mx-xl-auto{margin-left:auto!important}}.text-monospace{font-family:SFMono-Regular,Menlo,Monaco,Consolas,\\\"Liberation Mono\\\",\\\"Courier New\\\",monospace!important}.text-justify{text-align:justify!important}.text-wrap{white-space:normal!important}.text-nowrap{white-space:nowrap!important}.text-truncate{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.text-left{text-align:left!important}.text-right{text-align:right!important}.text-center{text-align:center!important}@media (min-width:576px){.text-sm-left{text-align:left!important}.text-sm-right{text-align:right!important}.text-sm-center{text-align:center!important}}@media (min-width:768px){.text-md-left{text-align:left!important}.text-md-right{text-align:right!important}.text-md-center{text-align:center!important}}@media (min-width:992px){.text-lg-left{text-align:left!important}.text-lg-right{text-align:right!important}.text-lg-center{text-align:center!important}}@media (min-width:1200px){.text-xl-left{text-align:left!important}.text-xl-right{text-align:right!important}.text-xl-center{text-align:center!important}}.text-lowercase{text-transform:lowercase!important}.text-uppercase{text-transform:uppercase!important}.text-capitalize{text-transform:capitalize!important}.font-weight-light{font-weight:300!important}.font-weight-lighter{font-weight:lighter!important}.font-weight-normal{font-weight:400!important}.font-weight-bold{font-weight:700!important}.font-weight-bolder{font-weight:bolder!important}.font-italic{font-style:italic!important}.text-white{color:#fff!important}.text-primary{color:#007bff!important}a.text-primary:focus,a.text-primary:hover{color:#0056b3!important}.text-secondary{color:#6c757d!important}a.text-secondary:focus,a.text-secondary:hover{color:#494f54!important}.text-success{color:#28a745!important}a.text-success:focus,a.text-success:hover{color:#19692c!important}.text-info{color:#17a2b8!important}a.text-info:focus,a.text-info:hover{color:#0f6674!important}.text-warning{color:#ffc107!important}a.text-warning:focus,a.text-warning:hover{color:#ba8b00!important}.text-danger{color:#dc3545!important}a.text-danger:focus,a.text-danger:hover{color:#a71d2a!important}.text-light{color:#f8f9fa!important}a.text-light:focus,a.text-light:hover{color:#cbd3da!important}.text-dark{color:#343a40!important}a.text-dark:focus,a.text-dark:hover{color:#121416!important}.text-body{color:#212529!important}.text-muted{color:#6c757d!important}.text-black-50{color:rgba(0,0,0,.5)!important}.text-white-50{color:rgba(255,255,255,.5)!important}.text-hide{font:0/0 a;color:transparent;text-shadow:none;background-color:transparent;border:0}.text-decoration-none{text-decoration:none!important}.text-break{word-break:break-word!important;overflow-wrap:break-word!important}.text-reset{color:inherit!important}.visible{visibility:visible!important}.invisible{visibility:hidden!important}@media print{*,::after,::before{text-shadow:none!important;box-shadow:none!important}a:not(.btn){text-decoration:underline}abbr[title]::after{content:\\\" (\\\" attr(title) \\\")\\\"}pre{white-space:pre-wrap!important}blockquote,pre{border:1px solid #adb5bd;page-break-inside:avoid}thead{display:table-header-group}img,tr{page-break-inside:avoid}h2,h3,p{orphans:3;widows:3}h2,h3{page-break-after:avoid}@page{size:a3}body{min-width:992px!important}.container{min-width:992px!important}.navbar{display:none}.badge{border:1px solid #000}.table{border-collapse:collapse!important}.table td,.table th{background-color:#fff!important}.table-bordered td,.table-bordered th{border:1px solid #dee2e6!important}.table-dark{color:inherit}.table-dark tbody+tbody,.table-dark td,.table-dark th,.table-dark thead th{border-color:#dee2e6}.table .thead-dark th{color:inherit;border-color:#dee2e6}}\", \"\"]);\n// Exports\nmodule.exports = exports;\n\n\n//# sourceURL=webpack:///./node_modules/bootstrap/dist/css/bootstrap.min.css?./node_modules/css-loader/dist/cjs.js");
/***/ }),
/***/ "./node_modules/css-loader/dist/cjs.js!./src/App.css":
/*!***********************************************************!*\
!*** ./node_modules/css-loader/dist/cjs.js!./src/App.css ***!
\***********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
eval("// Imports\nvar ___CSS_LOADER_API_IMPORT___ = __webpack_require__(/*! ../node_modules/css-loader/dist/runtime/api.js */ \"./node_modules/css-loader/dist/runtime/api.js\");\nexports = ___CSS_LOADER_API_IMPORT___(false);\n// Module\nexports.push([module.i, \"label {\\n display: block;\\n margin-top: 10px;\\n }\\n \\n .card-container.card {\\n max-width: 350px !important;\\n padding: 40px 40px;\\n }\\n \\n .card {\\n background-color: #f7f7f7;\\n padding: 20px 25px 30px;\\n margin: 0 auto 25px;\\n margin-top: 50px;\\n -moz-border-radius: 2px;\\n -webkit-border-radius: 2px;\\n border-radius: 2px;\\n -moz-box-shadow: 0px 2px 2px rgba(0, 0, 0, 0.3);\\n -webkit-box-shadow: 0px 2px 2px rgba(0, 0, 0, 0.3);\\n box-shadow: 0px 2px 2px rgba(0, 0, 0, 0.3);\\n }\\n \\n .profile-img-card {\\n width: 96px;\\n height: 96px;\\n margin: 0 auto 10px;\\n display: block;\\n -moz-border-radius: 50%;\\n -webkit-border-radius: 50%;\\n border-radius: 50%;\\n }\", \"\"]);\n// Exports\nmodule.exports = exports;\n\n\n//# sourceURL=webpack:///./src/App.css?./node_modules/css-loader/dist/cjs.js");
/***/ }),
/***/ "./node_modules/css-loader/dist/runtime/api.js":
/*!*****************************************************!*\
!*** ./node_modules/css-loader/dist/runtime/api.js ***!
\*****************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
eval("\n\n/*\n MIT License http://www.opensource.org/licenses/mit-license.php\n Author Tobias Koppers @sokra\n*/\n// css base code, injected by the css-loader\n// eslint-disable-next-line func-names\nmodule.exports = function (useSourceMap) {\n var list = []; // return the list of modules as css string\n\n list.toString = function toString() {\n return this.map(function (item) {\n var content = cssWithMappingToString(item, useSourceMap);\n\n if (item[2]) {\n return \"@media \".concat(item[2], \" {\").concat(content, \"}\");\n }\n\n return content;\n }).join('');\n }; // import a list of modules into the list\n // eslint-disable-next-line func-names\n\n\n list.i = function (modules, mediaQuery, dedupe) {\n if (typeof modules === 'string') {\n // eslint-disable-next-line no-param-reassign\n modules = [[null, modules, '']];\n }\n\n var alreadyImportedModules = {};\n\n if (dedupe) {\n for (var i = 0; i < this.length; i++) {\n // eslint-disable-next-line prefer-destructuring\n var id = this[i][0];\n\n if (id != null) {\n alreadyImportedModules[id] = true;\n }\n }\n }\n\n for (var _i = 0; _i < modules.length; _i++) {\n var item = [].concat(modules[_i]);\n\n if (dedupe && alreadyImportedModules[item[0]]) {\n // eslint-disable-next-line no-continue\n continue;\n }\n\n if (mediaQuery) {\n if (!item[2]) {\n item[2] = mediaQuery;\n } else {\n item[2] = \"\".concat(mediaQuery, \" and \").concat(item[2]);\n }\n }\n\n list.push(item);\n }\n };\n\n return list;\n};\n\nfunction cssWithMappingToString(item, useSourceMap) {\n var content = item[1] || ''; // eslint-disable-next-line prefer-destructuring\n\n var cssMapping = item[3];\n\n if (!cssMapping) {\n return content;\n }\n\n if (useSourceMap && typeof btoa === 'function') {\n var sourceMapping = toComment(cssMapping);\n var sourceURLs = cssMapping.sources.map(function (source) {\n return \"/*# sourceURL=\".concat(cssMapping.sourceRoot || '').concat(source, \" */\");\n });\n return [content].concat(sourceURLs).concat([sourceMapping]).join('\\n');\n }\n\n return [content].join('\\n');\n} // Adapted from convert-source-map (MIT)\n\n\nfunction toComment(sourceMap) {\n // eslint-disable-next-line no-undef\n var base64 = btoa(unescape(encodeURIComponent(JSON.stringify(sourceMap))));\n var data = \"sourceMappingURL=data:application/json;charset=utf-8;base64,\".concat(base64);\n return \"/*# \".concat(data, \" */\");\n}\n\n//# sourceURL=webpack:///./node_modules/css-loader/dist/runtime/api.js?");
/***/ }),
/***/ "./node_modules/gud/index.js":
/*!***********************************!*\
!*** ./node_modules/gud/index.js ***!
\***********************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
eval("/* WEBPACK VAR INJECTION */(function(global) {// @flow\n\n\nvar key = '__global_unique_id__';\n\nmodule.exports = function() {\n return global[key] = (global[key] || 0) + 1;\n};\n\n/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./../webpack/buildin/global.js */ \"./node_modules/webpack/buildin/global.js\")))\n\n//# sourceURL=webpack:///./node_modules/gud/index.js?");
/***/ }),
/***/ "./node_modules/history/esm/history.js":
/*!*********************************************!*\
!*** ./node_modules/history/esm/history.js ***!
\*********************************************/
/*! exports provided: createBrowserHistory, createHashHistory, createMemoryHistory, createLocation, locationsAreEqual, parsePath, createPath */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"createBrowserHistory\", function() { return createBrowserHistory; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"createHashHistory\", function() { return createHashHistory; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"createMemoryHistory\", function() { return createMemoryHistory; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"createLocation\", function() { return createLocation; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"locationsAreEqual\", function() { return locationsAreEqual; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"parsePath\", function() { return parsePath; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"createPath\", function() { return createPath; });\n/* harmony import */ var _babel_runtime_helpers_esm_extends__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @babel/runtime/helpers/esm/extends */ \"./node_modules/@babel/runtime/helpers/esm/extends.js\");\n/* harmony import */ var resolve_pathname__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! resolve-pathname */ \"./node_modules/resolve-pathname/esm/resolve-pathname.js\");\n/* harmony import */ var value_equal__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! value-equal */ \"./node_modules/value-equal/esm/value-equal.js\");\n/* harmony import */ var tiny_warning__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! tiny-warning */ \"./node_modules/tiny-warning/dist/tiny-warning.esm.js\");\n/* harmony import */ var tiny_invariant__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! tiny-invariant */ \"./node_modules/tiny-invariant/dist/tiny-invariant.esm.js\");\n\n\n\n\n\n\nfunction addLeadingSlash(path) {\n return path.charAt(0) === '/' ? path : '/' + path;\n}\nfunction stripLeadingSlash(path) {\n return path.charAt(0) === '/' ? path.substr(1) : path;\n}\nfunction hasBasename(path, prefix) {\n return path.toLowerCase().indexOf(prefix.toLowerCase()) === 0 && '/?#'.indexOf(path.charAt(prefix.length)) !== -1;\n}\nfunction stripBasename(path, prefix) {\n return hasBasename(path, prefix) ? path.substr(prefix.length) : path;\n}\nfunction stripTrailingSlash(path) {\n return path.charAt(path.length - 1) === '/' ? path.slice(0, -1) : path;\n}\nfunction parsePath(path) {\n var pathname = path || '/';\n var search = '';\n var hash = '';\n var hashIndex = pathname.indexOf('#');\n\n if (hashIndex !== -1) {\n hash = pathname.substr(hashIndex);\n pathname = pathname.substr(0, hashIndex);\n }\n\n var searchIndex = pathname.indexOf('?');\n\n if (searchIndex !== -1) {\n search = pathname.substr(searchIndex);\n pathname = pathname.substr(0, searchIndex);\n }\n\n return {\n pathname: pathname,\n search: search === '?' ? '' : search,\n hash: hash === '#' ? '' : hash\n };\n}\nfunction createPath(location) {\n var pathname = location.pathname,\n search = location.search,\n hash = location.hash;\n var path = pathname || '/';\n if (search && search !== '?') path += search.charAt(0) === '?' ? search : \"?\" + search;\n if (hash && hash !== '#') path += hash.charAt(0) === '#' ? hash : \"#\" + hash;\n return path;\n}\n\nfunction createLocation(path, state, key, currentLocation) {\n var location;\n\n if (typeof path === 'string') {\n // Two-arg form: push(path, state)\n location = parsePath(path);\n location.state = state;\n } else {\n // One-arg form: push(location)\n location = Object(_babel_runtime_helpers_esm_extends__WEBPACK_IMPORTED_MODULE_0__[\"default\"])({}, path);\n if (location.pathname === undefined) location.pathname = '';\n\n if (location.search) {\n if (location.search.charAt(0) !== '?') location.search = '?' + location.search;\n } else {\n location.search = '';\n }\n\n if (location.hash) {\n if (location.hash.charAt(0) !== '#') location.hash = '#' + location.hash;\n } else {\n location.hash = '';\n }\n\n if (state !== undefined && location.state === undefined) location.state = state;\n }\n\n try {\n location.pathname = decodeURI(location.pathname);\n } catch (e) {\n if (e instanceof URIError) {\n throw new URIError('Pathname \"' + location.pathname + '\" could not be decoded. ' + 'This is likely caused by an invalid percent-encoding.');\n } else {\n throw e;\n }\n }\n\n if (key) location.key = key;\n\n if (currentLocation) {\n // Resolve incomplete/relative pathname relative to current location.\n if (!location.pathname) {\n location.pathname = currentLocation.pathname;\n } else if (location.pathname.charAt(0) !== '/') {\n location.pathname = Object(resolve_pathname__WEBPACK_IMPORTED_MODULE_1__[\"default\"])(location.pathname, currentLocation.pathname);\n }\n } else {\n // When there is no prior location and pathname is empty, set it to /\n if (!location.pathname) {\n location.pathname = '/';\n }\n }\n\n return location;\n}\nfunction locationsAreEqual(a, b) {\n return a.pathname === b.pathname && a.search === b.search && a.hash === b.hash && a.key === b.key && Object(value_equal__WEBPACK_IMPORTED_MODULE_2__[\"default\"])(a.state, b.state);\n}\n\nfunction createTransitionManager() {\n var prompt = null;\n\n function setPrompt(nextPrompt) {\n true ? Object(tiny_warning__WEBPACK_IMPORTED_MODULE_3__[\"default\"])(prompt == null, 'A history supports only one prompt at a time') : undefined;\n prompt = nextPrompt;\n return function () {\n if (prompt === nextPrompt) prompt = null;\n };\n }\n\n function confirmTransitionTo(location, action, getUserConfirmation, callback) {\n // TODO: If another transition starts while we're still confirming\n // the previous one, we may end up in a weird state. Figure out the\n // best way to handle this.\n if (prompt != null) {\n var result = typeof prompt === 'function' ? prompt(location, action) : prompt;\n\n if (typeof result === 'string') {\n if (typeof getUserConfirmation === 'function') {\n getUserConfirmation(result, callback);\n } else {\n true ? Object(tiny_warning__WEBPACK_IMPORTED_MODULE_3__[\"default\"])(false, 'A history needs a getUserConfirmation function in order to use a prompt message') : undefined;\n callback(true);\n }\n } else {\n // Return false from a transition hook to cancel the transition.\n callback(result !== false);\n }\n } else {\n callback(true);\n }\n }\n\n var listeners = [];\n\n function appendListener(fn) {\n var isActive = true;\n\n function listener() {\n if (isActive) fn.apply(void 0, arguments);\n }\n\n listeners.push(listener);\n return function () {\n isActive = false;\n listeners = listeners.filter(function (item) {\n return item !== listener;\n });\n };\n }\n\n function notifyListeners() {\n for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {\n args[_key] = arguments[_key];\n }\n\n listeners.forEach(function (listener) {\n return listener.apply(void 0, args);\n });\n }\n\n return {\n setPrompt: setPrompt,\n confirmTransitionTo: confirmTransitionTo,\n appendListener: appendListener,\n notifyListeners: notifyListeners\n };\n}\n\nvar canUseDOM = !!(typeof window !== 'undefined' && window.document && window.document.createElement);\nfunction getConfirmation(message, callback) {\n callback(window.confirm(message)); // eslint-disable-line no-alert\n}\n/**\n * Returns true if the HTML5 history API is supported. Taken from Modernizr.\n *\n * https://github.com/Modernizr/Modernizr/blob/master/LICENSE\n * https://github.com/Modernizr/Modernizr/blob/master/feature-detects/history.js\n * changed to avoid false negatives for Windows Phones: https://github.com/reactjs/react-router/issues/586\n */\n\nfunction supportsHistory() {\n var ua = window.navigator.userAgent;\n if ((ua.indexOf('Android 2.') !== -1 || ua.indexOf('Android 4.0') !== -1) && ua.indexOf('Mobile Safari') !== -1 && ua.indexOf('Chrome') === -1 && ua.indexOf('Windows Phone') === -1) return false;\n return window.history && 'pushState' in window.history;\n}\n/**\n * Returns true if browser fires popstate on hash change.\n * IE10 and IE11 do not.\n */\n\nfunction supportsPopStateOnHashChange() {\n return window.navigator.userAgent.indexOf('Trident') === -1;\n}\n/**\n * Returns false if using go(n) with hash history causes a full page reload.\n */\n\nfunction supportsGoWithoutReloadUsingHash() {\n return window.navigator.userAgent.indexOf('Firefox') === -1;\n}\n/**\n * Returns true if a given popstate event is an extraneous WebKit event.\n * Accounts for the fact that Chrome on iOS fires real popstate events\n * containing undefined state when pressing the back button.\n */\n\nfunction isExtraneousPopstateEvent(event) {\n return event.state === undefined && navigator.userAgent.indexOf('CriOS') === -1;\n}\n\nvar PopStateEvent = 'popstate';\nvar HashChangeEvent = 'hashchange';\n\nfunction getHistoryState() {\n try {\n return window.history.state || {};\n } catch (e) {\n // IE 11 sometimes throws when accessing window.history.state\n // See https://github.com/ReactTraining/history/pull/289\n return {};\n }\n}\n/**\n * Creates a history object that uses the HTML5 history API including\n * pushState, replaceState, and the popstate event.\n */\n\n\nfunction createBrowserHistory(props) {\n if (props === void 0) {\n props = {};\n }\n\n !canUseDOM ? true ? Object(tiny_invariant__WEBPACK_IMPORTED_MODULE_4__[\"default\"])(false, 'Browser history needs a DOM') : undefined : void 0;\n var globalHistory = window.history;\n var canUseHistory = supportsHistory();\n var needsHashChangeListener = !supportsPopStateOnHashChange();\n var _props = props,\n _props$forceRefresh = _props.forceRefresh,\n forceRefresh = _props$forceRefresh === void 0 ? false : _props$forceRefresh,\n _props$getUserConfirm = _props.getUserConfirmation,\n getUserConfirmation = _props$getUserConfirm === void 0 ? getConfirmation : _props$getUserConfirm,\n _props$keyLength = _props.keyLength,\n keyLength = _props$keyLength === void 0 ? 6 : _props$keyLength;\n var basename = props.basename ? stripTrailingSlash(addLeadingSlash(props.basename)) : '';\n\n function getDOMLocation(historyState) {\n var _ref = historyState || {},\n key = _ref.key,\n state = _ref.state;\n\n var _window$location = window.location,\n pathname = _window$location.pathname,\n search = _window$location.search,\n hash = _window$location.hash;\n var path = pathname + search + hash;\n true ? Object(tiny_warning__WEBPACK_IMPORTED_MODULE_3__[\"default\"])(!basename || hasBasename(path, basename), 'You are attempting to use a basename on a page whose URL path does not begin ' + 'with the basename. Expected path \"' + path + '\" to begin with \"' + basename + '\".') : undefined;\n if (basename) path = stripBasename(path, basename);\n return createLocation(path, state, key);\n }\n\n function createKey() {\n return Math.random().toString(36).substr(2, keyLength);\n }\n\n var transitionManager = createTransitionManager();\n\n function setState(nextState) {\n Object(_babel_runtime_helpers_esm_extends__WEBPACK_IMPORTED_MODULE_0__[\"default\"])(history, nextState);\n\n history.length = globalHistory.length;\n transitionManager.notifyListeners(history.location, history.action);\n }\n\n function handlePopState(event) {\n // Ignore extraneous popstate events in WebKit.\n if (isExtraneousPopstateEvent(event)) return;\n handlePop(getDOMLocation(event.state));\n }\n\n function handleHashChange() {\n handlePop(getDOMLocation(getHistoryState()));\n }\n\n var forceNextPop = false;\n\n function handlePop(location) {\n if (forceNextPop) {\n forceNextPop = false;\n setState();\n } else {\n var action = 'POP';\n transitionManager.confirmTransitionTo(location, action, getUserConfirmation, function (ok) {\n if (ok) {\n setState({\n action: action,\n location: location\n });\n } else {\n revertPop(location);\n }\n });\n }\n }\n\n function revertPop(fromLocation) {\n var toLocation = history.location; // TODO: We could probably make this more reliable by\n // keeping a list of keys we've seen in sessionStorage.\n // Instead, we just default to 0 for keys we don't know.\n\n var toIndex = allKeys.indexOf(toLocation.key);\n if (toIndex === -1) toIndex = 0;\n var fromIndex = allKeys.indexOf(fromLocation.key);\n if (fromIndex === -1) fromIndex = 0;\n var delta = toIndex - fromIndex;\n\n if (delta) {\n forceNextPop = true;\n go(delta);\n }\n }\n\n var initialLocation = getDOMLocation(getHistoryState());\n var allKeys = [initialLocation.key]; // Public interface\n\n function createHref(location) {\n return basename + createPath(location);\n }\n\n function push(path, state) {\n true ? Object(tiny_warning__WEBPACK_IMPORTED_MODULE_3__[\"default\"])(!(typeof path === 'object' && path.state !== undefined && state !== undefined), 'You should avoid providing a 2nd state argument to push when the 1st ' + 'argument is a location-like object that already has state; it is ignored') : undefined;\n var action = 'PUSH';\n var location = createLocation(path, state, createKey(), history.location);\n transitionManager.confirmTransitionTo(location, action, getUserConfirmation, function (ok) {\n if (!ok) return;\n var href = createHref(location);\n var key = location.key,\n state = location.state;\n\n if (canUseHistory) {\n globalHistory.pushState({\n key: key,\n state: state\n }, null, href);\n\n if (forceRefresh) {\n window.location.href = href;\n } else {\n var prevIndex = allKeys.indexOf(history.location.key);\n var nextKeys = allKeys.slice(0, prevIndex + 1);\n nextKeys.push(location.key);\n allKeys = nextKeys;\n setState({\n action: action,\n location: location\n });\n }\n } else {\n true ? Object(tiny_warning__WEBPACK_IMPORTED_MODULE_3__[\"default\"])(state === undefined, 'Browser history cannot push state in browsers that do not support HTML5 history') : undefined;\n window.location.href = href;\n }\n });\n }\n\n function replace(path, state) {\n true ? Object(tiny_warning__WEBPACK_IMPORTED_MODULE_3__[\"default\"])(!(typeof path === 'object' && path.state !== undefined && state !== undefined), 'You should avoid providing a 2nd state argument to replace when the 1st ' + 'argument is a location-like object that already has state; it is ignored') : undefined;\n var action = 'REPLACE';\n var location = createLocation(path, state, createKey(), history.location);\n transitionManager.confirmTransitionTo(location, action, getUserConfirmation, function (ok) {\n if (!ok) return;\n var href = createHref(location);\n var key = location.key,\n state = location.state;\n\n if (canUseHistory) {\n globalHistory.replaceState({\n key: key,\n state: state\n }, null, href);\n\n if (forceRefresh) {\n window.location.replace(href);\n } else {\n var prevIndex = allKeys.indexOf(history.location.key);\n if (prevIndex !== -1) allKeys[prevIndex] = location.key;\n setState({\n action: action,\n location: location\n });\n }\n } else {\n true ? Object(tiny_warning__WEBPACK_IMPORTED_MODULE_3__[\"default\"])(state === undefined, 'Browser history cannot replace state in browsers that do not support HTML5 history') : undefined;\n window.location.replace(href);\n }\n });\n }\n\n function go(n) {\n globalHistory.go(n);\n }\n\n function goBack() {\n go(-1);\n }\n\n function goForward() {\n go(1);\n }\n\n var listenerCount = 0;\n\n function checkDOMListeners(delta) {\n listenerCount += delta;\n\n if (listenerCount === 1 && delta === 1) {\n window.addEventListener(PopStateEvent, handlePopState);\n if (needsHashChangeListener) window.addEventListener(HashChangeEvent, handleHashChange);\n } else if (listenerCount === 0) {\n window.removeEventListener(PopStateEvent, handlePopState);\n if (needsHashChangeListener) window.removeEventListener(HashChangeEvent, handleHashChange);\n }\n }\n\n var isBlocked = false;\n\n function block(prompt) {\n if (prompt === void 0) {\n prompt = false;\n }\n\n var unblock = transitionManager.setPrompt(prompt);\n\n if (!isBlocked) {\n checkDOMListeners(1);\n isBlocked = true;\n }\n\n return function () {\n if (isBlocked) {\n isBlocked = false;\n checkDOMListeners(-1);\n }\n\n return unblock();\n };\n }\n\n function listen(listener) {\n var unlisten = transitionManager.appendListener(listener);\n checkDOMListeners(1);\n return function () {\n checkDOMListeners(-1);\n unlisten();\n };\n }\n\n var history = {\n length: globalHistory.length,\n action: 'POP',\n location: initialLocation,\n createHref: createHref,\n push: push,\n replace: replace,\n go: go,\n goBack: goBack,\n goForward: goForward,\n block: block,\n listen: listen\n };\n return history;\n}\n\nvar HashChangeEvent$1 = 'hashchange';\nvar HashPathCoders = {\n hashbang: {\n encodePath: function encodePath(path) {\n return path.charAt(0) === '!' ? path : '!/' + stripLeadingSlash(path);\n },\n decodePath: function decodePath(path) {\n return path.charAt(0) === '!' ? path.substr(1) : path;\n }\n },\n noslash: {\n encodePath: stripLeadingSlash,\n decodePath: addLeadingSlash\n },\n slash: {\n encodePath: addLeadingSlash,\n decodePath: addLeadingSlash\n }\n};\n\nfunction stripHash(url) {\n var hashIndex = url.indexOf('#');\n return hashIndex === -1 ? url : url.slice(0, hashIndex);\n}\n\nfunction getHashPath() {\n // We can't use window.location.hash here because it's not\n // consistent across browsers - Firefox will pre-decode it!\n var href = window.location.href;\n var hashIndex = href.indexOf('#');\n return hashIndex === -1 ? '' : href.substring(hashIndex + 1);\n}\n\nfunction pushHashPath(path) {\n window.location.hash = path;\n}\n\nfunction replaceHashPath(path) {\n window.location.replace(stripHash(window.location.href) + '#' + path);\n}\n\nfunction createHashHistory(props) {\n if (props === void 0) {\n props = {};\n }\n\n !canUseDOM ? true ? Object(tiny_invariant__WEBPACK_IMPORTED_MODULE_4__[\"default\"])(false, 'Hash history needs a DOM') : undefined : void 0;\n var globalHistory = window.history;\n var canGoWithoutReload = supportsGoWithoutReloadUsingHash();\n var _props = props,\n _props$getUserConfirm = _props.getUserConfirmation,\n getUserConfirmation = _props$getUserConfirm === void 0 ? getConfirmation : _props$getUserConfirm,\n _props$hashType = _props.hashType,\n hashType = _props$hashType === void 0 ? 'slash' : _props$hashType;\n var basename = props.basename ? stripTrailingSlash(addLeadingSlash(props.basename)) : '';\n var _HashPathCoders$hashT = HashPathCoders[hashType],\n encodePath = _HashPathCoders$hashT.encodePath,\n decodePath = _HashPathCoders$hashT.decodePath;\n\n function getDOMLocation() {\n var path = decodePath(getHashPath());\n true ? Object(tiny_warning__WEBPACK_IMPORTED_MODULE_3__[\"default\"])(!basename || hasBasename(path, basename), 'You are attempting to use a basename on a page whose URL path does not begin ' + 'with the basename. Expected path \"' + path + '\" to begin with \"' + basename + '\".') : undefined;\n if (basename) path = stripBasename(path, basename);\n return createLocation(path);\n }\n\n var transitionManager = createTransitionManager();\n\n function setState(nextState) {\n Object(_babel_runtime_helpers_esm_extends__WEBPACK_IMPORTED_MODULE_0__[\"default\"])(history, nextState);\n\n history.length = globalHistory.length;\n transitionManager.notifyListeners(history.location, history.action);\n }\n\n var forceNextPop = false;\n var ignorePath = null;\n\n function locationsAreEqual$$1(a, b) {\n return a.pathname === b.pathname && a.search === b.search && a.hash === b.hash;\n }\n\n function handleHashChange() {\n var path = getHashPath();\n var encodedPath = encodePath(path);\n\n if (path !== encodedPath) {\n // Ensure we always have a properly-encoded hash.\n replaceHashPath(encodedPath);\n } else {\n var location = getDOMLocation();\n var prevLocation = history.location;\n if (!forceNextPop && locationsAreEqual$$1(prevLocation, location)) return; // A hashchange doesn't always == location change.\n\n if (ignorePath === createPath(location)) return; // Ignore this change; we already setState in push/replace.\n\n ignorePath = null;\n handlePop(location);\n }\n }\n\n function handlePop(location) {\n if (forceNextPop) {\n forceNextPop = false;\n setState();\n } else {\n var action = 'POP';\n transitionManager.confirmTransitionTo(location, action, getUserConfirmation, function (ok) {\n if (ok) {\n setState({\n action: action,\n location: location\n });\n } else {\n revertPop(location);\n }\n });\n }\n }\n\n function revertPop(fromLocation) {\n var toLocation = history.location; // TODO: We could probably make this more reliable by\n // keeping a list of paths we've seen in sessionStorage.\n // Instead, we just default to 0 for paths we don't know.\n\n var toIndex = allPaths.lastIndexOf(createPath(toLocation));\n if (toIndex === -1) toIndex = 0;\n var fromIndex = allPaths.lastIndexOf(createPath(fromLocation));\n if (fromIndex === -1) fromIndex = 0;\n var delta = toIndex - fromIndex;\n\n if (delta) {\n forceNextPop = true;\n go(delta);\n }\n } // Ensure the hash is encoded properly before doing anything else.\n\n\n var path = getHashPath();\n var encodedPath = encodePath(path);\n if (path !== encodedPath) replaceHashPath(encodedPath);\n var initialLocation = getDOMLocation();\n var allPaths = [createPath(initialLocation)]; // Public interface\n\n function createHref(location) {\n var baseTag = document.querySelector('base');\n var href = '';\n\n if (baseTag && baseTag.getAttribute('href')) {\n href = stripHash(window.location.href);\n }\n\n return href + '#' + encodePath(basename + createPath(location));\n }\n\n function push(path, state) {\n true ? Object(tiny_warning__WEBPACK_IMPORTED_MODULE_3__[\"default\"])(state === undefined, 'Hash history cannot push state; it is ignored') : undefined;\n var action = 'PUSH';\n var location = createLocation(path, undefined, undefined, history.location);\n transitionManager.confirmTransitionTo(location, action, getUserConfirmation, function (ok) {\n if (!ok) return;\n var path = createPath(location);\n var encodedPath = encodePath(basename + path);\n var hashChanged = getHashPath() !== encodedPath;\n\n if (hashChanged) {\n // We cannot tell if a hashchange was caused by a PUSH, so we'd\n // rather setState here and ignore the hashchange. The caveat here\n // is that other hash histories in the page will consider it a POP.\n ignorePath = path;\n pushHashPath(encodedPath);\n var prevIndex = allPaths.lastIndexOf(createPath(history.location));\n var nextPaths = allPaths.slice(0, prevIndex + 1);\n nextPaths.push(path);\n allPaths = nextPaths;\n setState({\n action: action,\n location: location\n });\n } else {\n true ? Object(tiny_warning__WEBPACK_IMPORTED_MODULE_3__[\"default\"])(false, 'Hash history cannot PUSH the same path; a new entry will not be added to the history stack') : undefined;\n setState();\n }\n });\n }\n\n function replace(path, state) {\n true ? Object(tiny_warning__WEBPACK_IMPORTED_MODULE_3__[\"default\"])(state === undefined, 'Hash history cannot replace state; it is ignored') : undefined;\n var action = 'REPLACE';\n var location = createLocation(path, undefined, undefined, history.location);\n transitionManager.confirmTransitionTo(location, action, getUserConfirmation, function (ok) {\n if (!ok) return;\n var path = createPath(location);\n var encodedPath = encodePath(basename + path);\n var hashChanged = getHashPath() !== encodedPath;\n\n if (hashChanged) {\n // We cannot tell if a hashchange was caused by a REPLACE, so we'd\n // rather setState here and ignore the hashchange. The caveat here\n // is that other hash histories in the page will consider it a POP.\n ignorePath = path;\n replaceHashPath(encodedPath);\n }\n\n var prevIndex = allPaths.indexOf(createPath(history.location));\n if (prevIndex !== -1) allPaths[prevIndex] = path;\n setState({\n action: action,\n location: location\n });\n });\n }\n\n function go(n) {\n true ? Object(tiny_warning__WEBPACK_IMPORTED_MODULE_3__[\"default\"])(canGoWithoutReload, 'Hash history go(n) causes a full page reload in this browser') : undefined;\n globalHistory.go(n);\n }\n\n function goBack() {\n go(-1);\n }\n\n function goForward() {\n go(1);\n }\n\n var listenerCount = 0;\n\n function checkDOMListeners(delta) {\n listenerCount += delta;\n\n if (listenerCount === 1 && delta === 1) {\n window.addEventListener(HashChangeEvent$1, handleHashChange);\n } else if (listenerCount === 0) {\n window.removeEventListener(HashChangeEvent$1, handleHashChange);\n }\n }\n\n var isBlocked = false;\n\n function block(prompt) {\n if (prompt === void 0) {\n prompt = false;\n }\n\n var unblock = transitionManager.setPrompt(prompt);\n\n if (!isBlocked) {\n checkDOMListeners(1);\n isBlocked = true;\n }\n\n return function () {\n if (isBlocked) {\n isBlocked = false;\n checkDOMListeners(-1);\n }\n\n return unblock();\n };\n }\n\n function listen(listener) {\n var unlisten = transitionManager.appendListener(listener);\n checkDOMListeners(1);\n return function () {\n checkDOMListeners(-1);\n unlisten();\n };\n }\n\n var history = {\n length: globalHistory.length,\n action: 'POP',\n location: initialLocation,\n createHref: createHref,\n push: push,\n replace: replace,\n go: go,\n goBack: goBack,\n goForward: goForward,\n block: block,\n listen: listen\n };\n return history;\n}\n\nfunction clamp(n, lowerBound, upperBound) {\n return Math.min(Math.max(n, lowerBound), upperBound);\n}\n/**\n * Creates a history object that stores locations in memory.\n */\n\n\nfunction createMemoryHistory(props) {\n if (props === void 0) {\n props = {};\n }\n\n var _props = props,\n getUserConfirmation = _props.getUserConfirmation,\n _props$initialEntries = _props.initialEntries,\n initialEntries = _props$initialEntries === void 0 ? ['/'] : _props$initialEntries,\n _props$initialIndex = _props.initialIndex,\n initialIndex = _props$initialIndex === void 0 ? 0 : _props$initialIndex,\n _props$keyLength = _props.keyLength,\n keyLength = _props$keyLength === void 0 ? 6 : _props$keyLength;\n var transitionManager = createTransitionManager();\n\n function setState(nextState) {\n Object(_babel_runtime_helpers_esm_extends__WEBPACK_IMPORTED_MODULE_0__[\"default\"])(history, nextState);\n\n history.length = history.entries.length;\n transitionManager.notifyListeners(history.location, history.action);\n }\n\n function createKey() {\n return Math.random().toString(36).substr(2, keyLength);\n }\n\n var index = clamp(initialIndex, 0, initialEntries.length - 1);\n var entries = initialEntries.map(function (entry) {\n return typeof entry === 'string' ? createLocation(entry, undefined, createKey()) : createLocation(entry, undefined, entry.key || createKey());\n }); // Public interface\n\n var createHref = createPath;\n\n function push(path, state) {\n true ? Object(tiny_warning__WEBPACK_IMPORTED_MODULE_3__[\"default\"])(!(typeof path === 'object' && path.state !== undefined && state !== undefined), 'You should avoid providing a 2nd state argument to push when the 1st ' + 'argument is a location-like object that already has state; it is ignored') : undefined;\n var action = 'PUSH';\n var location = createLocation(path, state, createKey(), history.location);\n transitionManager.confirmTransitionTo(location, action, getUserConfirmation, function (ok) {\n if (!ok) return;\n var prevIndex = history.index;\n var nextIndex = prevIndex + 1;\n var nextEntries = history.entries.slice(0);\n\n if (nextEntries.length > nextIndex) {\n nextEntries.splice(nextIndex, nextEntries.length - nextIndex, location);\n } else {\n nextEntries.push(location);\n }\n\n setState({\n action: action,\n location: location,\n index: nextIndex,\n entries: nextEntries\n });\n });\n }\n\n function replace(path, state) {\n true ? Object(tiny_warning__WEBPACK_IMPORTED_MODULE_3__[\"default\"])(!(typeof path === 'object' && path.state !== undefined && state !== undefined), 'You should avoid providing a 2nd state argument to replace when the 1st ' + 'argument is a location-like object that already has state; it is ignored') : undefined;\n var action = 'REPLACE';\n var location = createLocation(path, state, createKey(), history.location);\n transitionManager.confirmTransitionTo(location, action, getUserConfirmation, function (ok) {\n if (!ok) return;\n history.entries[history.index] = location;\n setState({\n action: action,\n location: location\n });\n });\n }\n\n function go(n) {\n var nextIndex = clamp(history.index + n, 0, history.entries.length - 1);\n var action = 'POP';\n var location = history.entries[nextIndex];\n transitionManager.confirmTransitionTo(location, action, getUserConfirmation, function (ok) {\n if (ok) {\n setState({\n action: action,\n location: location,\n index: nextIndex\n });\n } else {\n // Mimic the behavior of DOM histories by\n // causing a render after a cancelled POP.\n setState();\n }\n });\n }\n\n function goBack() {\n go(-1);\n }\n\n function goForward() {\n go(1);\n }\n\n function canGo(n) {\n var nextIndex = history.index + n;\n return nextIndex >= 0 && nextIndex < history.entries.length;\n }\n\n function block(prompt) {\n if (prompt === void 0) {\n prompt = false;\n }\n\n return transitionManager.setPrompt(prompt);\n }\n\n function listen(listener) {\n return transitionManager.appendListener(listener);\n }\n\n var history = {\n length: entries.length,\n action: 'POP',\n location: entries[index],\n index: index,\n entries: entries,\n createHref: createHref,\n push: push,\n replace: replace,\n go: go,\n goBack: goBack,\n goForward: goForward,\n canGo: canGo,\n block: block,\n listen: listen\n };\n return history;\n}\n\n\n\n\n//# sourceURL=webpack:///./node_modules/history/esm/history.js?");
/***/ }),
/***/ "./node_modules/hoist-non-react-statics/dist/hoist-non-react-statics.cjs.js":
/*!**********************************************************************************!*\
!*** ./node_modules/hoist-non-react-statics/dist/hoist-non-react-statics.cjs.js ***!
\**********************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
eval("\n\nvar reactIs = __webpack_require__(/*! react-is */ \"./node_modules/react-is/index.js\");\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\n\n//# sourceURL=webpack:///./node_modules/hoist-non-react-statics/dist/hoist-non-react-statics.cjs.js?");
/***/ }),
/***/ "./node_modules/lodash.omit/index.js":
/*!*******************************************!*\
!*** ./node_modules/lodash.omit/index.js ***!
\*******************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
eval("/* WEBPACK VAR INJECTION */(function(global) {/**\n * lodash (Custom Build) <https://lodash.com/>\n * Build: `lodash modularize exports=\"npm\" -o ./`\n * Copyright jQuery Foundation and other contributors <https://jquery.org/>\n * Released under MIT license <https://lodash.com/license>\n * Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE>\n * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors\n */\n\n/** Used as the size to enable large array optimizations. */\nvar LARGE_ARRAY_SIZE = 200;\n\n/** Used to stand-in for `undefined` hash values. */\nvar HASH_UNDEFINED = '__lodash_hash_undefined__';\n\n/** Used as references for various `Number` constants. */\nvar INFINITY = 1 / 0,\n MAX_SAFE_INTEGER = 9007199254740991;\n\n/** `Object#toString` result references. */\nvar argsTag = '[object Arguments]',\n funcTag = '[object Function]',\n genTag = '[object GeneratorFunction]',\n symbolTag = '[object Symbol]';\n\n/**\n * Used to match `RegExp`\n * [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns).\n */\nvar reRegExpChar = /[\\\\^$.*+?()[\\]{}|]/g;\n\n/** Used to detect host constructors (Safari). */\nvar reIsHostCtor = /^\\[object .+?Constructor\\]$/;\n\n/** Used to detect unsigned integer values. */\nvar reIsUint = /^(?:0|[1-9]\\d*)$/;\n\n/** Detect free variable `global` from Node.js. */\nvar freeGlobal = typeof global == 'object' && global && global.Object === Object && global;\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\n/**\n * A faster alternative to `Function#apply`, this function invokes `func`\n * with the `this` binding of `thisArg` and the arguments of `args`.\n *\n * @private\n * @param {Function} func The function to invoke.\n * @param {*} thisArg The `this` binding of `func`.\n * @param {Array} args The arguments to invoke `func` with.\n * @returns {*} Returns the result of `func`.\n */\nfunction apply(func, thisArg, args) {\n switch (args.length) {\n case 0: return func.call(thisArg);\n case 1: return func.call(thisArg, args[0]);\n case 2: return func.call(thisArg, args[0], args[1]);\n case 3: return func.call(thisArg, args[0], args[1], args[2]);\n }\n return func.apply(thisArg, args);\n}\n\n/**\n * A specialized version of `_.includes` for arrays without support for\n * specifying an index to search from.\n *\n * @private\n * @param {Array} [array] The array to inspect.\n * @param {*} target The value to search for.\n * @returns {boolean} Returns `true` if `target` is found, else `false`.\n */\nfunction arrayIncludes(array, value) {\n var length = array ? array.length : 0;\n return !!length && baseIndexOf(array, value, 0) > -1;\n}\n\n/**\n * This function is like `arrayIncludes` except that it accepts a comparator.\n *\n * @private\n * @param {Array} [array] The array to inspect.\n * @param {*} target The value to search for.\n * @param {Function} comparator The comparator invoked per element.\n * @returns {boolean} Returns `true` if `target` is found, else `false`.\n */\nfunction arrayIncludesWith(array, value, comparator) {\n var index = -1,\n length = array ? array.length : 0;\n\n while (++index < length) {\n if (comparator(value, array[index])) {\n return true;\n }\n }\n return false;\n}\n\n/**\n * A specialized version of `_.map` for arrays without support for iteratee\n * shorthands.\n *\n * @private\n * @param {Array} [array] The array to iterate over.\n * @param {Function} iteratee The function invoked per iteration.\n * @returns {Array} Returns the new mapped array.\n */\nfunction arrayMap(array, iteratee) {\n var index = -1,\n length = array ? array.length : 0,\n result = Array(length);\n\n while (++index < length) {\n result[index] = iteratee(array[index], index, array);\n }\n return result;\n}\n\n/**\n * Appends the elements of `values` to `array`.\n *\n * @private\n * @param {Array} array The array to modify.\n * @param {Array} values The values to append.\n * @returns {Array} Returns `array`.\n */\nfunction arrayPush(array, values) {\n var index = -1,\n length = values.length,\n offset = array.length;\n\n while (++index < length) {\n array[offset + index] = values[index];\n }\n return array;\n}\n\n/**\n * The base implementation of `_.findIndex` and `_.findLastIndex` without\n * support for iteratee shorthands.\n *\n * @private\n * @param {Array} array The array to inspect.\n * @param {Function} predicate The function invoked per iteration.\n * @param {number} fromIndex The index to search from.\n * @param {boolean} [fromRight] Specify iterating from right to left.\n * @returns {number} Returns the index of the matched value, else `-1`.\n */\nfunction baseFindIndex(array, predicate, fromIndex, fromRight) {\n var length = array.length,\n index = fromIndex + (fromRight ? 1 : -1);\n\n while ((fromRight ? index-- : ++index < length)) {\n if (predicate(array[index], index, array)) {\n return index;\n }\n }\n return -1;\n}\n\n/**\n * The base implementation of `_.indexOf` without `fromIndex` bounds checks.\n *\n * @private\n * @param {Array} array The array to inspect.\n * @param {*} value The value to search for.\n * @param {number} fromIndex The index to search from.\n * @returns {number} Returns the index of the matched value, else `-1`.\n */\nfunction baseIndexOf(array, value, fromIndex) {\n if (value !== value) {\n return baseFindIndex(array, baseIsNaN, fromIndex);\n }\n var index = fromIndex - 1,\n length = array.length;\n\n while (++index < length) {\n if (array[index] === value) {\n return index;\n }\n }\n return -1;\n}\n\n/**\n * The base implementation of `_.isNaN` without support for number objects.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is `NaN`, else `false`.\n */\nfunction baseIsNaN(value) {\n return value !== value;\n}\n\n/**\n * The base implementation of `_.times` without support for iteratee shorthands\n * or max array length checks.\n *\n * @private\n * @param {number} n The number of times to invoke `iteratee`.\n * @param {Function} iteratee The function invoked per iteration.\n * @returns {Array} Returns the array of results.\n */\nfunction baseTimes(n, iteratee) {\n var index = -1,\n result = Array(n);\n\n while (++index < n) {\n result[index] = iteratee(index);\n }\n return result;\n}\n\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\n/**\n * Checks if a cache value for `key` exists.\n *\n * @private\n * @param {Object} cache The cache to query.\n * @param {string} key The key of the entry to check.\n * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.\n */\nfunction cacheHas(cache, key) {\n return cache.has(key);\n}\n\n/**\n * Gets the value at `key` of `object`.\n *\n * @private\n * @param {Object} [object] The object to query.\n * @param {string} key The key of the property to get.\n * @returns {*} Returns the property value.\n */\nfunction getValue(object, key) {\n return object == null ? undefined : object[key];\n}\n\n/**\n * Checks if `value` is a host object in IE < 9.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a host object, else `false`.\n */\nfunction isHostObject(value) {\n // Many host objects are `Object` objects that can coerce to strings\n // despite having improperly defined `toString` methods.\n var result = false;\n if (value != null && typeof value.toString != 'function') {\n try {\n result = !!(value + '');\n } catch (e) {}\n }\n return result;\n}\n\n/**\n * Creates a unary function that invokes `func` with its argument transformed.\n *\n * @private\n * @param {Function} func The function to wrap.\n * @param {Function} transform The argument transform.\n * @returns {Function} Returns the new function.\n */\nfunction overArg(func, transform) {\n return function(arg) {\n return func(transform(arg));\n };\n}\n\n/** Used for built-in method references. */\nvar arrayProto = Array.prototype,\n funcProto = Function.prototype,\n objectProto = Object.prototype;\n\n/** Used to detect overreaching core-js shims. */\nvar coreJsData = root['__core-js_shared__'];\n\n/** Used to detect methods masquerading as native. */\nvar maskSrcKey = (function() {\n var uid = /[^.]+$/.exec(coreJsData && coreJsData.keys && coreJsData.keys.IE_PROTO || '');\n return uid ? ('Symbol(src)_1.' + uid) : '';\n}());\n\n/** Used to resolve the decompiled source of functions. */\nvar funcToString = funcProto.toString;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\n\n/**\n * Used to resolve the\n * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)\n * of values.\n */\nvar objectToString = objectProto.toString;\n\n/** Used to detect if a method is native. */\nvar reIsNative = RegExp('^' +\n funcToString.call(hasOwnProperty).replace(reRegExpChar, '\\\\$&')\n .replace(/hasOwnProperty|(function).*?(?=\\\\\\()| for .+?(?=\\\\\\])/g, '$1.*?') + '$'\n);\n\n/** Built-in value references. */\nvar Symbol = root.Symbol,\n getPrototype = overArg(Object.getPrototypeOf, Object),\n propertyIsEnumerable = objectProto.propertyIsEnumerable,\n splice = arrayProto.splice,\n spreadableSymbol = Symbol ? Symbol.isConcatSpreadable : undefined;\n\n/* Built-in method references for those with the same name as other `lodash` methods. */\nvar nativeGetSymbols = Object.getOwnPropertySymbols,\n nativeMax = Math.max;\n\n/* Built-in method references that are verified to be native. */\nvar Map = getNative(root, 'Map'),\n nativeCreate = getNative(Object, 'create');\n\n/**\n * Creates a hash object.\n *\n * @private\n * @constructor\n * @param {Array} [entries] The key-value pairs to cache.\n */\nfunction Hash(entries) {\n var index = -1,\n length = entries ? entries.length : 0;\n\n this.clear();\n while (++index < length) {\n var entry = entries[index];\n this.set(entry[0], entry[1]);\n }\n}\n\n/**\n * Removes all key-value entries from the hash.\n *\n * @private\n * @name clear\n * @memberOf Hash\n */\nfunction hashClear() {\n this.__data__ = nativeCreate ? nativeCreate(null) : {};\n}\n\n/**\n * Removes `key` and its value from the hash.\n *\n * @private\n * @name delete\n * @memberOf Hash\n * @param {Object} hash The hash to modify.\n * @param {string} key The key of the value to remove.\n * @returns {boolean} Returns `true` if the entry was removed, else `false`.\n */\nfunction hashDelete(key) {\n return this.has(key) && delete this.__data__[key];\n}\n\n/**\n * Gets the hash value for `key`.\n *\n * @private\n * @name get\n * @memberOf Hash\n * @param {string} key The key of the value to get.\n * @returns {*} Returns the entry value.\n */\nfunction hashGet(key) {\n var data = this.__data__;\n if (nativeCreate) {\n var result = data[key];\n return result === HASH_UNDEFINED ? undefined : result;\n }\n return hasOwnProperty.call(data, key) ? data[key] : undefined;\n}\n\n/**\n * Checks if a hash value for `key` exists.\n *\n * @private\n * @name has\n * @memberOf Hash\n * @param {string} key The key of the entry to check.\n * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.\n */\nfunction hashHas(key) {\n var data = this.__data__;\n return nativeCreate ? data[key] !== undefined : hasOwnProperty.call(data, key);\n}\n\n/**\n * Sets the hash `key` to `value`.\n *\n * @private\n * @name set\n * @memberOf Hash\n * @param {string} key The key of the value to set.\n * @param {*} value The value to set.\n * @returns {Object} Returns the hash instance.\n */\nfunction hashSet(key, value) {\n var data = this.__data__;\n data[key] = (nativeCreate && value === undefined) ? HASH_UNDEFINED : value;\n return this;\n}\n\n// Add methods to `Hash`.\nHash.prototype.clear = hashClear;\nHash.prototype['delete'] = hashDelete;\nHash.prototype.get = hashGet;\nHash.prototype.has = hashHas;\nHash.prototype.set = hashSet;\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 ? entries.length : 0;\n\n this.clear();\n while (++index < length) {\n var entry = entries[index];\n this.set(entry[0], entry[1]);\n }\n}\n\n/**\n * Removes all key-value entries from the list cache.\n *\n * @private\n * @name clear\n * @memberOf ListCache\n */\nfunction listCacheClear() {\n this.__data__ = [];\n}\n\n/**\n * Removes `key` and its value from the list cache.\n *\n * @private\n * @name delete\n * @memberOf ListCache\n * @param {string} key The key of the value to remove.\n * @returns {boolean} Returns `true` if the entry was removed, else `false`.\n */\nfunction listCacheDelete(key) {\n var data = this.__data__,\n index = assocIndexOf(data, key);\n\n if (index < 0) {\n return false;\n }\n var lastIndex = data.length - 1;\n if (index == lastIndex) {\n data.pop();\n } else {\n splice.call(data, index, 1);\n }\n return true;\n}\n\n/**\n * Gets the list cache value for `key`.\n *\n * @private\n * @name get\n * @memberOf ListCache\n * @param {string} key The key of the value to get.\n * @returns {*} Returns the entry value.\n */\nfunction listCacheGet(key) {\n var data = this.__data__,\n index = assocIndexOf(data, key);\n\n return index < 0 ? undefined : data[index][1];\n}\n\n/**\n * Checks if a list cache value for `key` exists.\n *\n * @private\n * @name has\n * @memberOf ListCache\n * @param {string} key The key of the entry to check.\n * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.\n */\nfunction listCacheHas(key) {\n return assocIndexOf(this.__data__, key) > -1;\n}\n\n/**\n * Sets the list cache `key` to `value`.\n *\n * @private\n * @name set\n * @memberOf ListCache\n * @param {string} key The key of the value to set.\n * @param {*} value The value to set.\n * @returns {Object} Returns the list cache instance.\n */\nfunction listCacheSet(key, value) {\n var data = this.__data__,\n index = assocIndexOf(data, key);\n\n if (index < 0) {\n data.push([key, value]);\n } else {\n data[index][1] = value;\n }\n return this;\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\n/**\n * Creates a map cache object to store key-value pairs.\n *\n * @private\n * @constructor\n * @param {Array} [entries] The key-value pairs to cache.\n */\nfunction MapCache(entries) {\n var index = -1,\n length = entries ? entries.length : 0;\n\n this.clear();\n while (++index < length) {\n var entry = entries[index];\n this.set(entry[0], entry[1]);\n }\n}\n\n/**\n * Removes all key-value entries from the map.\n *\n * @private\n * @name clear\n * @memberOf MapCache\n */\nfunction mapCacheClear() {\n this.__data__ = {\n 'hash': new Hash,\n 'map': new (Map || ListCache),\n 'string': new Hash\n };\n}\n\n/**\n * Removes `key` and its value from the map.\n *\n * @private\n * @name delete\n * @memberOf MapCache\n * @param {string} key The key of the value to remove.\n * @returns {boolean} Returns `true` if the entry was removed, else `false`.\n */\nfunction mapCacheDelete(key) {\n return getMapData(this, key)['delete'](key);\n}\n\n/**\n * Gets the map value for `key`.\n *\n * @private\n * @name get\n * @memberOf MapCache\n * @param {string} key The key of the value to get.\n * @returns {*} Returns the entry value.\n */\nfunction mapCacheGet(key) {\n return getMapData(this, key).get(key);\n}\n\n/**\n * Checks if a map value for `key` exists.\n *\n * @private\n * @name has\n * @memberOf MapCache\n * @param {string} key The key of the entry to check.\n * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.\n */\nfunction mapCacheHas(key) {\n return getMapData(this, key).has(key);\n}\n\n/**\n * Sets the map `key` to `value`.\n *\n * @private\n * @name set\n * @memberOf MapCache\n * @param {string} key The key of the value to set.\n * @param {*} value The value to set.\n * @returns {Object} Returns the map cache instance.\n */\nfunction mapCacheSet(key, value) {\n getMapData(this, key).set(key, value);\n return this;\n}\n\n// Add methods to `MapCache`.\nMapCache.prototype.clear = mapCacheClear;\nMapCache.prototype['delete'] = mapCacheDelete;\nMapCache.prototype.get = mapCacheGet;\nMapCache.prototype.has = mapCacheHas;\nMapCache.prototype.set = mapCacheSet;\n\n/**\n *\n * Creates an array cache object to store unique values.\n *\n * @private\n * @constructor\n * @param {Array} [values] The values to cache.\n */\nfunction SetCache(values) {\n var index = -1,\n length = values ? values.length : 0;\n\n this.__data__ = new MapCache;\n while (++index < length) {\n this.add(values[index]);\n }\n}\n\n/**\n * Adds `value` to the array cache.\n *\n * @private\n * @name add\n * @memberOf SetCache\n * @alias push\n * @param {*} value The value to cache.\n * @returns {Object} Returns the cache instance.\n */\nfunction setCacheAdd(value) {\n this.__data__.set(value, HASH_UNDEFINED);\n return this;\n}\n\n/**\n * Checks if `value` is in the array cache.\n *\n * @private\n * @name has\n * @memberOf SetCache\n * @param {*} value The value to search for.\n * @returns {number} Returns `true` if `value` is found, else `false`.\n */\nfunction setCacheHas(value) {\n return this.__data__.has(value);\n}\n\n// Add methods to `SetCache`.\nSetCache.prototype.add = SetCache.prototype.push = setCacheAdd;\nSetCache.prototype.has = setCacheHas;\n\n/**\n * Creates an array of the enumerable property names of the array-like `value`.\n *\n * @private\n * @param {*} value The value to query.\n * @param {boolean} inherited Specify returning inherited property names.\n * @returns {Array} Returns the array of property names.\n */\nfunction arrayLikeKeys(value, inherited) {\n // Safari 8.1 makes `arguments.callee` enumerable in strict mode.\n // Safari 9 makes `arguments.length` enumerable in strict mode.\n var result = (isArray(value) || isArguments(value))\n ? baseTimes(value.length, String)\n : [];\n\n var length = result.length,\n skipIndexes = !!length;\n\n for (var key in value) {\n if ((inherited || hasOwnProperty.call(value, key)) &&\n !(skipIndexes && (key == 'length' || isIndex(key, length)))) {\n result.push(key);\n }\n }\n return result;\n}\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\n/**\n * The base implementation of methods like `_.difference` without support\n * for excluding multiple arrays or iteratee shorthands.\n *\n * @private\n * @param {Array} array The array to inspect.\n * @param {Array} values The values to exclude.\n * @param {Function} [iteratee] The iteratee invoked per element.\n * @param {Function} [comparator] The comparator invoked per element.\n * @returns {Array} Returns the new array of filtered values.\n */\nfunction baseDifference(array, values, iteratee, comparator) {\n var index = -1,\n includes = arrayIncludes,\n isCommon = true,\n length = array.length,\n result = [],\n valuesLength = values.length;\n\n if (!length) {\n return result;\n }\n if (iteratee) {\n values = arrayMap(values, baseUnary(iteratee));\n }\n if (comparator) {\n includes = arrayIncludesWith;\n isCommon = false;\n }\n else if (values.length >= LARGE_ARRAY_SIZE) {\n includes = cacheHas;\n isCommon = false;\n values = new SetCache(values);\n }\n outer:\n while (++index < length) {\n var value = array[index],\n computed = iteratee ? iteratee(value) : value;\n\n value = (comparator || value !== 0) ? value : 0;\n if (isCommon && computed === computed) {\n var valuesIndex = valuesLength;\n while (valuesIndex--) {\n if (values[valuesIndex] === computed) {\n continue outer;\n }\n }\n result.push(value);\n }\n else if (!includes(values, computed, comparator)) {\n result.push(value);\n }\n }\n return result;\n}\n\n/**\n * The base implementation of `_.flatten` with support for restricting flattening.\n *\n * @private\n * @param {Array} array The array to flatten.\n * @param {number} depth The maximum recursion depth.\n * @param {boolean} [predicate=isFlattenable] The function invoked per iteration.\n * @param {boolean} [isStrict] Restrict to values that pass `predicate` checks.\n * @param {Array} [result=[]] The initial result value.\n * @returns {Array} Returns the new flattened array.\n */\nfunction baseFlatten(array, depth, predicate, isStrict, result) {\n var index = -1,\n length = array.length;\n\n predicate || (predicate = isFlattenable);\n result || (result = []);\n\n while (++index < length) {\n var value = array[index];\n if (depth > 0 && predicate(value)) {\n if (depth > 1) {\n // Recursively flatten arrays (susceptible to call stack limits).\n baseFlatten(value, depth - 1, predicate, isStrict, result);\n } else {\n arrayPush(result, value);\n }\n } else if (!isStrict) {\n result[result.length] = value;\n }\n }\n return result;\n}\n\n/**\n * The base implementation of `getAllKeys` and `getAllKeysIn` which uses\n * `keysFunc` and `symbolsFunc` to get the enumerable property names and\n * symbols of `object`.\n *\n * @private\n * @param {Object} object The object to query.\n * @param {Function} keysFunc The function to get the keys of `object`.\n * @param {Function} symbolsFunc The function to get the symbols of `object`.\n * @returns {Array} Returns the array of property names and symbols.\n */\nfunction baseGetAllKeys(object, keysFunc, symbolsFunc) {\n var result = keysFunc(object);\n return isArray(object) ? result : arrayPush(result, symbolsFunc(object));\n}\n\n/**\n * The base implementation of `_.isNative` without bad shim checks.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a native function,\n * else `false`.\n */\nfunction baseIsNative(value) {\n if (!isObject(value) || isMasked(value)) {\n return false;\n }\n var pattern = (isFunction(value) || isHostObject(value)) ? reIsNative : reIsHostCtor;\n return pattern.test(toSource(value));\n}\n\n/**\n * The base implementation of `_.keysIn` which doesn't treat sparse arrays as dense.\n *\n * @private\n * @param {Object} object The object to query.\n * @returns {Array} Returns the array of property names.\n */\nfunction baseKeysIn(object) {\n if (!isObject(object)) {\n return nativeKeysIn(object);\n }\n var isProto = isPrototype(object),\n result = [];\n\n for (var key in object) {\n if (!(key == 'constructor' && (isProto || !hasOwnProperty.call(object, key)))) {\n result.push(key);\n }\n }\n return result;\n}\n\n/**\n * The base implementation of `_.pick` without support for individual\n * property identifiers.\n *\n * @private\n * @param {Object} object The source object.\n * @param {string[]} props The property identifiers to pick.\n * @returns {Object} Returns the new object.\n */\nfunction basePick(object, props) {\n object = Object(object);\n return basePickBy(object, props, function(value, key) {\n return key in object;\n });\n}\n\n/**\n * The base implementation of `_.pickBy` without support for iteratee shorthands.\n *\n * @private\n * @param {Object} object The source object.\n * @param {string[]} props The property identifiers to pick from.\n * @param {Function} predicate The function invoked per property.\n * @returns {Object} Returns the new object.\n */\nfunction basePickBy(object, props, predicate) {\n var index = -1,\n length = props.length,\n result = {};\n\n while (++index < length) {\n var key = props[index],\n value = object[key];\n\n if (predicate(value, key)) {\n result[key] = value;\n }\n }\n return result;\n}\n\n/**\n * The base implementation of `_.rest` which doesn't validate or coerce arguments.\n *\n * @private\n * @param {Function} func The function to apply a rest parameter to.\n * @param {number} [start=func.length-1] The start position of the rest parameter.\n * @returns {Function} Returns the new function.\n */\nfunction baseRest(func, start) {\n start = nativeMax(start === undefined ? (func.length - 1) : start, 0);\n return function() {\n var args = arguments,\n index = -1,\n length = nativeMax(args.length - start, 0),\n array = Array(length);\n\n while (++index < length) {\n array[index] = args[start + index];\n }\n index = -1;\n var otherArgs = Array(start + 1);\n while (++index < start) {\n otherArgs[index] = args[index];\n }\n otherArgs[start] = array;\n return apply(func, this, otherArgs);\n };\n}\n\n/**\n * Creates an array of own and inherited enumerable property names and\n * symbols of `object`.\n *\n * @private\n * @param {Object} object The object to query.\n * @returns {Array} Returns the array of property names and symbols.\n */\nfunction getAllKeysIn(object) {\n return baseGetAllKeys(object, keysIn, getSymbolsIn);\n}\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\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\n/**\n * Creates an array of the own enumerable symbol properties of `object`.\n *\n * @private\n * @param {Object} object The object to query.\n * @returns {Array} Returns the array of symbols.\n */\nvar getSymbols = nativeGetSymbols ? overArg(nativeGetSymbols, Object) : stubArray;\n\n/**\n * Creates an array of the own and inherited enumerable symbol properties\n * of `object`.\n *\n * @private\n * @param {Object} object The object to query.\n * @returns {Array} Returns the array of symbols.\n */\nvar getSymbolsIn = !nativeGetSymbols ? stubArray : function(object) {\n var result = [];\n while (object) {\n arrayPush(result, getSymbols(object));\n object = getPrototype(object);\n }\n return result;\n};\n\n/**\n * Checks if `value` is a flattenable `arguments` object or array.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is flattenable, else `false`.\n */\nfunction isFlattenable(value) {\n return isArray(value) || isArguments(value) ||\n !!(spreadableSymbol && value && value[spreadableSymbol]);\n}\n\n/**\n * Checks if `value` is a valid array-like index.\n *\n * @private\n * @param {*} value The value to check.\n * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index.\n * @returns {boolean} Returns `true` if `value` is a valid index, else `false`.\n */\nfunction isIndex(value, length) {\n length = length == null ? MAX_SAFE_INTEGER : length;\n return !!length &&\n (typeof value == 'number' || reIsUint.test(value)) &&\n (value > -1 && value % 1 == 0 && value < length);\n}\n\n/**\n * Checks if `value` is suitable for use as unique object key.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is suitable, else `false`.\n */\nfunction isKeyable(value) {\n var type = typeof value;\n return (type == 'string' || type == 'number' || type == 'symbol' || type == 'boolean')\n ? (value !== '__proto__')\n : (value === null);\n}\n\n/**\n * Checks if `func` has its source masked.\n *\n * @private\n * @param {Function} func The function to check.\n * @returns {boolean} Returns `true` if `func` is masked, else `false`.\n */\nfunction isMasked(func) {\n return !!maskSrcKey && (maskSrcKey in func);\n}\n\n/**\n * Checks if `value` is likely a prototype object.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a prototype, else `false`.\n */\nfunction isPrototype(value) {\n var Ctor = value && value.constructor,\n proto = (typeof Ctor == 'function' && Ctor.prototype) || objectProto;\n\n return value === proto;\n}\n\n/**\n * This function is like\n * [`Object.keys`](http://ecma-international.org/ecma-262/7.0/#sec-object.keys)\n * except that it includes inherited enumerable properties.\n *\n * @private\n * @param {Object} object The object to query.\n * @returns {Array} Returns the array of property names.\n */\nfunction nativeKeysIn(object) {\n var result = [];\n if (object != null) {\n for (var key in Object(object)) {\n result.push(key);\n }\n }\n return result;\n}\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\n/**\n * Converts `func` to its source code.\n *\n * @private\n * @param {Function} func The function to process.\n * @returns {string} Returns the source code.\n */\nfunction toSource(func) {\n if (func != null) {\n try {\n return funcToString.call(func);\n } catch (e) {}\n try {\n return (func + '');\n } catch (e) {}\n }\n return '';\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\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 */\nfunction isArguments(value) {\n // Safari 8.1 makes `arguments.callee` enumerable in strict mode.\n return isArrayLikeObject(value) && hasOwnProperty.call(value, 'callee') &&\n (!propertyIsEnumerable.call(value, 'callee') || objectToString.call(value) == argsTag);\n}\n\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\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\n/**\n * This method is like `_.isArrayLike` except that it also checks if `value`\n * is an 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 an array-like object,\n * else `false`.\n * @example\n *\n * _.isArrayLikeObject([1, 2, 3]);\n * // => true\n *\n * _.isArrayLikeObject(document.body.children);\n * // => true\n *\n * _.isArrayLikeObject('abc');\n * // => false\n *\n * _.isArrayLikeObject(_.noop);\n * // => false\n */\nfunction isArrayLikeObject(value) {\n return isObjectLike(value) && isArrayLike(value);\n}\n\n/**\n * Checks if `value` is classified as a `Function` 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 a function, else `false`.\n * @example\n *\n * _.isFunction(_);\n * // => true\n *\n * _.isFunction(/abc/);\n * // => false\n */\nfunction isFunction(value) {\n // The use of `Object#toString` avoids issues with the `typeof` operator\n // in Safari 8-9 which returns 'object' for typed array and other constructors.\n var tag = isObject(value) ? objectToString.call(value) : '';\n return tag == funcTag || tag == genTag;\n}\n\n/**\n * Checks if `value` is a valid array-like length.\n *\n * **Note:** This method is loosely based on\n * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength).\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 valid length, else `false`.\n * @example\n *\n * _.isLength(3);\n * // => true\n *\n * _.isLength(Number.MIN_VALUE);\n * // => false\n *\n * _.isLength(Infinity);\n * // => false\n *\n * _.isLength('3');\n * // => false\n */\nfunction isLength(value) {\n return typeof value == 'number' &&\n value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER;\n}\n\n/**\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 && (type == 'object' || type == 'function');\n}\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 && typeof value == 'object';\n}\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) && objectToString.call(value) == symbolTag);\n}\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\n/**\n * The opposite of `_.pick`; this method creates an object composed of the\n * own and inherited enumerable string keyed properties of `object` that are\n * not omitted.\n *\n * @static\n * @since 0.1.0\n * @memberOf _\n * @category Object\n * @param {Object} object The source object.\n * @param {...(string|string[])} [props] The property identifiers to omit.\n * @returns {Object} Returns the new object.\n * @example\n *\n * var object = { 'a': 1, 'b': '2', 'c': 3 };\n *\n * _.omit(object, ['a', 'c']);\n * // => { 'b': '2' }\n */\nvar omit = baseRest(function(object, props) {\n if (object == null) {\n return {};\n }\n props = arrayMap(baseFlatten(props, 1), toKey);\n return basePick(object, baseDifference(getAllKeysIn(object), props));\n});\n\n/**\n * This method returns a new empty array.\n *\n * @static\n * @memberOf _\n * @since 4.13.0\n * @category Util\n * @returns {Array} Returns the new empty array.\n * @example\n *\n * var arrays = _.times(2, _.stubArray);\n *\n * console.log(arrays);\n * // => [[], []]\n *\n * console.log(arrays[0] === arrays[1]);\n * // => false\n */\nfunction stubArray() {\n return [];\n}\n\nmodule.exports = omit;\n\n/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./../webpack/buildin/global.js */ \"./node_modules/webpack/buildin/global.js\")))\n\n//# sourceURL=webpack:///./node_modules/lodash.omit/index.js?");
/***/ }),
/***/ "./node_modules/mini-create-react-context/dist/esm/index.js":
/*!******************************************************************!*\
!*** ./node_modules/mini-create-react-context/dist/esm/index.js ***!
\******************************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
eval("__webpack_require__.r(__webpack_exports__);\n/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! react */ \"./node_modules/react/index.js\");\n/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);\n/* harmony import */ var _babel_runtime_helpers_inheritsLoose__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @babel/runtime/helpers/inheritsLoose */ \"./node_modules/@babel/runtime/helpers/inheritsLoose.js\");\n/* harmony import */ var _babel_runtime_helpers_inheritsLoose__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_inheritsLoose__WEBPACK_IMPORTED_MODULE_1__);\n/* harmony import */ var prop_types__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! prop-types */ \"./node_modules/prop-types/index.js\");\n/* harmony import */ var prop_types__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(prop_types__WEBPACK_IMPORTED_MODULE_2__);\n/* harmony import */ var gud__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! gud */ \"./node_modules/gud/index.js\");\n/* harmony import */ var gud__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(gud__WEBPACK_IMPORTED_MODULE_3__);\n/* harmony import */ var tiny_warning__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! tiny-warning */ \"./node_modules/tiny-warning/dist/tiny-warning.esm.js\");\n\n\n\n\n\n\nvar MAX_SIGNED_31_BIT_INT = 1073741823;\n\nfunction objectIs(x, y) {\n if (x === y) {\n return x !== 0 || 1 / x === 1 / y;\n } else {\n return x !== x && y !== y;\n }\n}\n\nfunction createEventEmitter(value) {\n var handlers = [];\n return {\n on: function on(handler) {\n handlers.push(handler);\n },\n off: function off(handler) {\n handlers = handlers.filter(function (h) {\n return h !== handler;\n });\n },\n get: function get() {\n return value;\n },\n set: function set(newValue, changedBits) {\n value = newValue;\n handlers.forEach(function (handler) {\n return handler(value, changedBits);\n });\n }\n };\n}\n\nfunction onlyChild(children) {\n return Array.isArray(children) ? children[0] : children;\n}\n\nfunction createReactContext(defaultValue, calculateChangedBits) {\n var _Provider$childContex, _Consumer$contextType;\n\n var contextProp = '__create-react-context-' + gud__WEBPACK_IMPORTED_MODULE_3___default()() + '__';\n\n var Provider =\n /*#__PURE__*/\n function (_Component) {\n _babel_runtime_helpers_inheritsLoose__WEBPACK_IMPORTED_MODULE_1___default()(Provider, _Component);\n\n function Provider() {\n var _this;\n\n _this = _Component.apply(this, arguments) || this;\n _this.emitter = createEventEmitter(_this.props.value);\n return _this;\n }\n\n var _proto = Provider.prototype;\n\n _proto.getChildContext = function getChildContext() {\n var _ref;\n\n return _ref = {}, _ref[contextProp] = this.emitter, _ref;\n };\n\n _proto.componentWillReceiveProps = function componentWillReceiveProps(nextProps) {\n if (this.props.value !== nextProps.value) {\n var oldValue = this.props.value;\n var newValue = nextProps.value;\n var changedBits;\n\n if (objectIs(oldValue, newValue)) {\n changedBits = 0;\n } else {\n changedBits = typeof calculateChangedBits === 'function' ? calculateChangedBits(oldValue, newValue) : MAX_SIGNED_31_BIT_INT;\n\n if (true) {\n Object(tiny_warning__WEBPACK_IMPORTED_MODULE_4__[\"default\"])((changedBits & MAX_SIGNED_31_BIT_INT) === changedBits, 'calculateChangedBits: Expected the return value to be a ' + '31-bit integer. Instead received: ' + changedBits);\n }\n\n changedBits |= 0;\n\n if (changedBits !== 0) {\n this.emitter.set(nextProps.value, changedBits);\n }\n }\n }\n };\n\n _proto.render = function render() {\n return this.props.children;\n };\n\n return Provider;\n }(react__WEBPACK_IMPORTED_MODULE_0__[\"Component\"]);\n\n Provider.childContextTypes = (_Provider$childContex = {}, _Provider$childContex[contextProp] = prop_types__WEBPACK_IMPORTED_MODULE_2___default.a.object.isRequired, _Provider$childContex);\n\n var Consumer =\n /*#__PURE__*/\n function (_Component2) {\n _babel_runtime_helpers_inheritsLoose__WEBPACK_IMPORTED_MODULE_1___default()(Consumer, _Component2);\n\n function Consumer() {\n var _this2;\n\n _this2 = _Component2.apply(this, arguments) || this;\n _this2.state = {\n value: _this2.getValue()\n };\n\n _this2.onUpdate = function (newValue, changedBits) {\n var observedBits = _this2.observedBits | 0;\n\n if ((observedBits & changedBits) !== 0) {\n _this2.setState({\n value: _this2.getValue()\n });\n }\n };\n\n return _this2;\n }\n\n var _proto2 = Consumer.prototype;\n\n _proto2.componentWillReceiveProps = function componentWillReceiveProps(nextProps) {\n var observedBits = nextProps.observedBits;\n this.observedBits = observedBits === undefined || observedBits === null ? MAX_SIGNED_31_BIT_INT : observedBits;\n };\n\n _proto2.componentDidMount = function componentDidMount() {\n if (this.context[contextProp]) {\n this.context[contextProp].on(this.onUpdate);\n }\n\n var observedBits = this.props.observedBits;\n this.observedBits = observedBits === undefined || observedBits === null ? MAX_SIGNED_31_BIT_INT : observedBits;\n };\n\n _proto2.componentWillUnmount = function componentWillUnmount() {\n if (this.context[contextProp]) {\n this.context[contextProp].off(this.onUpdate);\n }\n };\n\n _proto2.getValue = function getValue() {\n if (this.context[contextProp]) {\n return this.context[contextProp].get();\n } else {\n return defaultValue;\n }\n };\n\n _proto2.render = function render() {\n return onlyChild(this.props.children)(this.state.value);\n };\n\n return Consumer;\n }(react__WEBPACK_IMPORTED_MODULE_0__[\"Component\"]);\n\n Consumer.contextTypes = (_Consumer$contextType = {}, _Consumer$contextType[contextProp] = prop_types__WEBPACK_IMPORTED_MODULE_2___default.a.object, _Consumer$contextType);\n return {\n Provider: Provider,\n Consumer: Consumer\n };\n}\n\nvar index = react__WEBPACK_IMPORTED_MODULE_0___default.a.createContext || createReactContext;\n\n/* harmony default export */ __webpack_exports__[\"default\"] = (index);\n\n\n//# sourceURL=webpack:///./node_modules/mini-create-react-context/dist/esm/index.js?");
/***/ }),
/***/ "./node_modules/object-assign/index.js":
/*!*********************************************!*\
!*** ./node_modules/object-assign/index.js ***!
\*********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
eval("/*\nobject-assign\n(c) Sindre Sorhus\n@license MIT\n*/\n\n\n/* eslint-disable no-unused-vars */\nvar getOwnPropertySymbols = Object.getOwnPropertySymbols;\nvar hasOwnProperty = Object.prototype.hasOwnProperty;\nvar propIsEnumerable = Object.prototype.propertyIsEnumerable;\n\nfunction toObject(val) {\n\tif (val === null || val === undefined) {\n\t\tthrow new TypeError('Object.assign cannot be called with null or undefined');\n\t}\n\n\treturn Object(val);\n}\n\nfunction shouldUseNative() {\n\ttry {\n\t\tif (!Object.assign) {\n\t\t\treturn false;\n\t\t}\n\n\t\t// Detect buggy property enumeration order in older V8 versions.\n\n\t\t// https://bugs.chromium.org/p/v8/issues/detail?id=4118\n\t\tvar test1 = new String('abc'); // eslint-disable-line no-new-wrappers\n\t\ttest1[5] = 'de';\n\t\tif (Object.getOwnPropertyNames(test1)[0] === '5') {\n\t\t\treturn false;\n\t\t}\n\n\t\t// https://bugs.chromium.org/p/v8/issues/detail?id=3056\n\t\tvar test2 = {};\n\t\tfor (var i = 0; i < 10; i++) {\n\t\t\ttest2['_' + String.fromCharCode(i)] = i;\n\t\t}\n\t\tvar order2 = Object.getOwnPropertyNames(test2).map(function (n) {\n\t\t\treturn test2[n];\n\t\t});\n\t\tif (order2.join('') !== '0123456789') {\n\t\t\treturn false;\n\t\t}\n\n\t\t// https://bugs.chromium.org/p/v8/issues/detail?id=3056\n\t\tvar test3 = {};\n\t\t'abcdefghijklmnopqrst'.split('').forEach(function (letter) {\n\t\t\ttest3[letter] = letter;\n\t\t});\n\t\tif (Object.keys(Object.assign({}, test3)).join('') !==\n\t\t\t\t'abcdefghijklmnopqrst') {\n\t\t\treturn false;\n\t\t}\n\n\t\treturn true;\n\t} catch (err) {\n\t\t// We don't expect any of the above to throw, but better to be safe.\n\t\treturn false;\n\t}\n}\n\nmodule.exports = shouldUseNative() ? Object.assign : function (target, source) {\n\tvar from;\n\tvar to = toObject(target);\n\tvar symbols;\n\n\tfor (var s = 1; s < arguments.length; s++) {\n\t\tfrom = Object(arguments[s]);\n\n\t\tfor (var key in from) {\n\t\t\tif (hasOwnProperty.call(from, key)) {\n\t\t\t\tto[key] = from[key];\n\t\t\t}\n\t\t}\n\n\t\tif (getOwnPropertySymbols) {\n\t\t\tsymbols = getOwnPropertySymbols(from);\n\t\t\tfor (var i = 0; i < symbols.length; i++) {\n\t\t\t\tif (propIsEnumerable.call(from, symbols[i])) {\n\t\t\t\t\tto[symbols[i]] = from[symbols[i]];\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn to;\n};\n\n\n//# sourceURL=webpack:///./node_modules/object-assign/index.js?");
/***/ }),
/***/ "./node_modules/process/browser.js":
/*!*****************************************!*\
!*** ./node_modules/process/browser.js ***!
\*****************************************/
/*! no static exports found */
/***/ (function(module, exports) {
eval("// 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\n\n//# sourceURL=webpack:///./node_modules/process/browser.js?");
/***/ }),
/***/ "./node_modules/prop-types/checkPropTypes.js":
/*!***************************************************!*\
!*** ./node_modules/prop-types/checkPropTypes.js ***!
\***************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
eval("/**\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\n\n\nvar printWarning = function() {};\n\nif (true) {\n var ReactPropTypesSecret = __webpack_require__(/*! ./lib/ReactPropTypesSecret */ \"./node_modules/prop-types/lib/ReactPropTypesSecret.js\");\n var loggedTypeFailures = {};\n var has = Function.call.bind(Object.prototype.hasOwnProperty);\n\n printWarning = function(text) {\n var message = 'Warning: ' + text;\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\n/**\n * Assert that the values match with the type specs.\n * Error messages are memorized and will only be shown once.\n *\n * @param {object} typeSpecs Map of name to a ReactPropType\n * @param {object} values Runtime values that need to be type-checked\n * @param {string} location e.g. \"prop\", \"context\", \"child context\"\n * @param {string} componentName Name of the component for error messages.\n * @param {?Function} getStack Returns the component stack.\n * @private\n */\nfunction checkPropTypes(typeSpecs, values, location, componentName, getStack) {\n if (true) {\n for (var typeSpecName in typeSpecs) {\n if (has(typeSpecs, typeSpecName)) {\n var error;\n // Prop type validation may throw. In case they do, we don't want to\n // fail the render phase where it didn't fail before. So we log it.\n // After these have been cleaned up, we'll let them throw.\n try {\n // This is intentionally an invariant that gets caught. It's the same\n // behavior as without this statement except with a better message.\n if (typeof typeSpecs[typeSpecName] !== 'function') {\n var err = Error(\n (componentName || 'React class') + ': ' + location + ' type `' + typeSpecName + '` is invalid; ' +\n 'it must be a function, usually from the `prop-types` package, but received `' + typeof typeSpecs[typeSpecName] + '`.'\n );\n err.name = 'Invariant Violation';\n throw err;\n }\n error = typeSpecs[typeSpecName](values, typeSpecName, componentName, location, null, ReactPropTypesSecret);\n } catch (ex) {\n error = ex;\n }\n if (error && !(error instanceof Error)) {\n printWarning(\n (componentName || 'React class') + ': type specification of ' +\n location + ' `' + typeSpecName + '` is invalid; the type checker ' +\n 'function must return `null` or an `Error` but returned a ' + typeof error + '. ' +\n 'You may have forgotten to pass an argument to the type checker ' +\n 'creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and ' +\n 'shape all require an argument).'\n );\n }\n if (error instanceof Error && !(error.message in loggedTypeFailures)) {\n // Only monitor this failure once because there tends to be a lot of the\n // same error.\n loggedTypeFailures[error.message] = true;\n\n var stack = getStack ? getStack() : '';\n\n printWarning(\n 'Failed ' + location + ' type: ' + error.message + (stack != null ? stack : '')\n );\n }\n }\n }\n }\n}\n\n/**\n * Resets warning cache when testing.\n *\n * @private\n */\ncheckPropTypes.resetWarningCache = function() {\n if (true) {\n loggedTypeFailures = {};\n }\n}\n\nmodule.exports = checkPropTypes;\n\n\n//# sourceURL=webpack:///./node_modules/prop-types/checkPropTypes.js?");
/***/ }),
/***/ "./node_modules/prop-types/factoryWithTypeCheckers.js":
/*!************************************************************!*\
!*** ./node_modules/prop-types/factoryWithTypeCheckers.js ***!
\************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
eval("/**\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\n\n\nvar ReactIs = __webpack_require__(/*! react-is */ \"./node_modules/react-is/index.js\");\nvar assign = __webpack_require__(/*! object-assign */ \"./node_modules/object-assign/index.js\");\n\nvar ReactPropTypesSecret = __webpack_require__(/*! ./lib/ReactPropTypesSecret */ \"./node_modules/prop-types/lib/ReactPropTypesSecret.js\");\nvar checkPropTypes = __webpack_require__(/*! ./checkPropTypes */ \"./node_modules/prop-types/checkPropTypes.js\");\n\nvar has = Function.call.bind(Object.prototype.hasOwnProperty);\nvar printWarning = function() {};\n\nif (true) {\n printWarning = function(text) {\n var message = 'Warning: ' + text;\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\nfunction emptyFunctionThatReturnsNull() {\n return null;\n}\n\nmodule.exports = function(isValidElement, throwOnDirectAccess) {\n /* global Symbol */\n var ITERATOR_SYMBOL = typeof Symbol === 'function' && Symbol.iterator;\n var FAUX_ITERATOR_SYMBOL = '@@iterator'; // Before Symbol spec.\n\n /**\n * Returns the iterator method function contained on the iterable object.\n *\n * Be sure to invoke the function with the iterable as context:\n *\n * var iteratorFn = getIteratorFn(myIterable);\n * if (iteratorFn) {\n * var iterator = iteratorFn.call(myIterable);\n * ...\n * }\n *\n * @param {?object} maybeIterable\n * @return {?function}\n */\n function getIteratorFn(maybeIterable) {\n var iteratorFn = maybeIterable && (ITERATOR_SYMBOL && maybeIterable[ITERATOR_SYMBOL] || maybeIterable[FAUX_ITERATOR_SYMBOL]);\n if (typeof iteratorFn === 'function') {\n return iteratorFn;\n }\n }\n\n /**\n * Collection of methods that allow declaration and validation of props that are\n * supplied to React components. Example usage:\n *\n * var Props = require('ReactPropTypes');\n * var MyArticle = React.createClass({\n * propTypes: {\n * // An optional string prop named \"description\".\n * description: Props.string,\n *\n * // A required enum prop named \"category\".\n * category: Props.oneOf(['News','Photos']).isRequired,\n *\n * // A prop named \"dialog\" that requires an instance of Dialog.\n * dialog: Props.instanceOf(Dialog).isRequired\n * },\n * render: function() { ... }\n * });\n *\n * A more formal specification of how these methods are used:\n *\n * type := array|bool|func|object|number|string|oneOf([...])|instanceOf(...)\n * decl := ReactPropTypes.{type}(.isRequired)?\n *\n * Each and every declaration produces a function with the same signature. This\n * allows the creation of custom validation functions. For example:\n *\n * var MyLink = React.createClass({\n * propTypes: {\n * // An optional string or URI prop named \"href\".\n * href: function(props, propName, componentName) {\n * var propValue = props[propName];\n * if (propValue != null && typeof propValue !== 'string' &&\n * !(propValue instanceof URI)) {\n * return new Error(\n * 'Expected a string or an URI for ' + propName + ' in ' +\n * componentName\n * );\n * }\n * }\n * },\n * render: function() {...}\n * });\n *\n * @internal\n */\n\n var ANONYMOUS = '<<anonymous>>';\n\n // Important!\n // Keep this list in sync with production version in `./factoryWithThrowingShims.js`.\n var ReactPropTypes = {\n array: createPrimitiveTypeChecker('array'),\n bool: createPrimitiveTypeChecker('boolean'),\n func: createPrimitiveTypeChecker('function'),\n number: createPrimitiveTypeChecker('number'),\n object: createPrimitiveTypeChecker('object'),\n string: createPrimitiveTypeChecker('string'),\n symbol: createPrimitiveTypeChecker('symbol'),\n\n any: createAnyTypeChecker(),\n arrayOf: createArrayOfTypeChecker,\n element: createElementTypeChecker(),\n elementType: createElementTypeTypeChecker(),\n instanceOf: createInstanceTypeChecker,\n node: createNodeChecker(),\n objectOf: createObjectOfTypeChecker,\n oneOf: createEnumTypeChecker,\n oneOfType: createUnionTypeChecker,\n shape: createShapeTypeChecker,\n exact: createStrictShapeTypeChecker,\n };\n\n /**\n * inlined Object.is polyfill to avoid requiring consumers ship their own\n * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is\n */\n /*eslint-disable no-self-compare*/\n function is(x, y) {\n // SameValue algorithm\n if (x === y) {\n // Steps 1-5, 7-10\n // Steps 6.b-6.e: +0 != -0\n return x !== 0 || 1 / x === 1 / y;\n } else {\n // Step 6.a: NaN == NaN\n return x !== x && y !== y;\n }\n }\n /*eslint-enable no-self-compare*/\n\n /**\n * We use an Error-like object for backward compatibility as people may call\n * PropTypes directly and inspect their output. However, we don't use real\n * Errors anymore. We don't inspect their stack anyway, and creating them\n * is prohibitively expensive if they are created too often, such as what\n * happens in oneOfType() for any type before the one that matched.\n */\n function PropTypeError(message) {\n this.message = message;\n this.stack = '';\n }\n // Make `instanceof Error` still work for returned errors.\n PropTypeError.prototype = Error.prototype;\n\n function createChainableTypeChecker(validate) {\n if (true) {\n var manualPropTypeCallCache = {};\n var manualPropTypeWarningCount = 0;\n }\n function checkType(isRequired, props, propName, componentName, location, propFullName, secret) {\n componentName = componentName || ANONYMOUS;\n propFullName = propFullName || propName;\n\n if (secret !== ReactPropTypesSecret) {\n if (throwOnDirectAccess) {\n // New behavior only for users of `prop-types` package\n var err = new Error(\n 'Calling PropTypes validators directly is not supported by the `prop-types` package. ' +\n 'Use `PropTypes.checkPropTypes()` to call them. ' +\n 'Read more at http://fb.me/use-check-prop-types'\n );\n err.name = 'Invariant Violation';\n throw err;\n } else if ( true && typeof console !== 'undefined') {\n // Old behavior for people using React.PropTypes\n var cacheKey = componentName + ':' + propName;\n if (\n !manualPropTypeCallCache[cacheKey] &&\n // Avoid spamming the console because they are often not actionable except for lib authors\n manualPropTypeWarningCount < 3\n ) {\n printWarning(\n 'You are manually calling a React.PropTypes validation ' +\n 'function for the `' + propFullName + '` prop on `' + componentName + '`. This is deprecated ' +\n 'and will throw in the standalone `prop-types` package. ' +\n 'You may be seeing this warning due to a third-party PropTypes ' +\n 'library. See https://fb.me/react-warning-dont-call-proptypes ' + 'for details.'\n );\n manualPropTypeCallCache[cacheKey] = true;\n manualPropTypeWarningCount++;\n }\n }\n }\n if (props[propName] == null) {\n if (isRequired) {\n if (props[propName] === null) {\n return new PropTypeError('The ' + location + ' `' + propFullName + '` is marked as required ' + ('in `' + componentName + '`, but its value is `null`.'));\n }\n return new PropTypeError('The ' + location + ' `' + propFullName + '` is marked as required in ' + ('`' + componentName + '`, but its value is `undefined`.'));\n }\n return null;\n } else {\n return validate(props, propName, componentName, location, propFullName);\n }\n }\n\n var chainedCheckType = checkType.bind(null, false);\n chainedCheckType.isRequired = checkType.bind(null, true);\n\n return chainedCheckType;\n }\n\n function createPrimitiveTypeChecker(expectedType) {\n function validate(props, propName, componentName, location, propFullName, secret) {\n var propValue = props[propName];\n var propType = getPropType(propValue);\n if (propType !== expectedType) {\n // `propValue` being instance of, say, date/regexp, pass the 'object'\n // check, but we can offer a more precise error message here rather than\n // 'of type `object`'.\n var preciseType = getPreciseType(propValue);\n\n return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type ' + ('`' + preciseType + '` supplied to `' + componentName + '`, expected ') + ('`' + expectedType + '`.'));\n }\n return null;\n }\n return createChainableTypeChecker(validate);\n }\n\n function createAnyTypeChecker() {\n return createChainableTypeChecker(emptyFunctionThatReturnsNull);\n }\n\n function createArrayOfTypeChecker(typeChecker) {\n function validate(props, propName, componentName, location, propFullName) {\n if (typeof typeChecker !== 'function') {\n return new PropTypeError('Property `' + propFullName + '` of component `' + componentName + '` has invalid PropType notation inside arrayOf.');\n }\n var propValue = props[propName];\n if (!Array.isArray(propValue)) {\n var propType = getPropType(propValue);\n return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type ' + ('`' + propType + '` supplied to `' + componentName + '`, expected an array.'));\n }\n for (var i = 0; i < propValue.length; i++) {\n var error = typeChecker(propValue, i, componentName, location, propFullName + '[' + i + ']', ReactPropTypesSecret);\n if (error instanceof Error) {\n return error;\n }\n }\n return null;\n }\n return createChainableTypeChecker(validate);\n }\n\n function createElementTypeChecker() {\n function validate(props, propName, componentName, location, propFullName) {\n var propValue = props[propName];\n if (!isValidElement(propValue)) {\n var propType = getPropType(propValue);\n return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type ' + ('`' + propType + '` supplied to `' + componentName + '`, expected a single ReactElement.'));\n }\n return null;\n }\n return createChainableTypeChecker(validate);\n }\n\n function createElementTypeTypeChecker() {\n function validate(props, propName, componentName, location, propFullName) {\n var propValue = props[propName];\n if (!ReactIs.isValidElementType(propValue)) {\n var propType = getPropType(propValue);\n return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type ' + ('`' + propType + '` supplied to `' + componentName + '`, expected a single ReactElement type.'));\n }\n return null;\n }\n return createChainableTypeChecker(validate);\n }\n\n function createInstanceTypeChecker(expectedClass) {\n function validate(props, propName, componentName, location, propFullName) {\n if (!(props[propName] instanceof expectedClass)) {\n var expectedClassName = expectedClass.name || ANONYMOUS;\n var actualClassName = getClassName(props[propName]);\n return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type ' + ('`' + actualClassName + '` supplied to `' + componentName + '`, expected ') + ('instance of `' + expectedClassName + '`.'));\n }\n return null;\n }\n return createChainableTypeChecker(validate);\n }\n\n function createEnumTypeChecker(expectedValues) {\n if (!Array.isArray(expectedValues)) {\n if (true) {\n if (arguments.length > 1) {\n printWarning(\n 'Invalid arguments supplied to oneOf, expected an array, got ' + arguments.length + ' arguments. ' +\n 'A common mistake is to write oneOf(x, y, z) instead of oneOf([x, y, z]).'\n );\n } else {\n printWarning('Invalid argument supplied to oneOf, expected an array.');\n }\n }\n return emptyFunctionThatReturnsNull;\n }\n\n function validate(props, propName, componentName, location, propFullName) {\n var propValue = props[propName];\n for (var i = 0; i < expectedValues.length; i++) {\n if (is(propValue, expectedValues[i])) {\n return null;\n }\n }\n\n var valuesString = JSON.stringify(expectedValues, function replacer(key, value) {\n var type = getPreciseType(value);\n if (type === 'symbol') {\n return String(value);\n }\n return value;\n });\n return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of value `' + String(propValue) + '` ' + ('supplied to `' + componentName + '`, expected one of ' + valuesString + '.'));\n }\n return createChainableTypeChecker(validate);\n }\n\n function createObjectOfTypeChecker(typeChecker) {\n function validate(props, propName, componentName, location, propFullName) {\n if (typeof typeChecker !== 'function') {\n return new PropTypeError('Property `' + propFullName + '` of component `' + componentName + '` has invalid PropType notation inside objectOf.');\n }\n var propValue = props[propName];\n var propType = getPropType(propValue);\n if (propType !== 'object') {\n return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type ' + ('`' + propType + '` supplied to `' + componentName + '`, expected an object.'));\n }\n for (var key in propValue) {\n if (has(propValue, key)) {\n var error = typeChecker(propValue, key, componentName, location, propFullName + '.' + key, ReactPropTypesSecret);\n if (error instanceof Error) {\n return error;\n }\n }\n }\n return null;\n }\n return createChainableTypeChecker(validate);\n }\n\n function createUnionTypeChecker(arrayOfTypeCheckers) {\n if (!Array.isArray(arrayOfTypeCheckers)) {\n true ? printWarning('Invalid argument supplied to oneOfType, expected an instance of array.') : undefined;\n return emptyFunctionThatReturnsNull;\n }\n\n for (var i = 0; i < arrayOfTypeCheckers.length; i++) {\n var checker = arrayOfTypeCheckers[i];\n if (typeof checker !== 'function') {\n printWarning(\n 'Invalid argument supplied to oneOfType. Expected an array of check functions, but ' +\n 'received ' + getPostfixForTypeWarning(checker) + ' at index ' + i + '.'\n );\n return emptyFunctionThatReturnsNull;\n }\n }\n\n function validate(props, propName, componentName, location, propFullName) {\n for (var i = 0; i < arrayOfTypeCheckers.length; i++) {\n var checker = arrayOfTypeCheckers[i];\n if (checker(props, propName, componentName, location, propFullName, ReactPropTypesSecret) == null) {\n return null;\n }\n }\n\n return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` supplied to ' + ('`' + componentName + '`.'));\n }\n return createChainableTypeChecker(validate);\n }\n\n function createNodeChecker() {\n function validate(props, propName, componentName, location, propFullName) {\n if (!isNode(props[propName])) {\n return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` supplied to ' + ('`' + componentName + '`, expected a ReactNode.'));\n }\n return null;\n }\n return createChainableTypeChecker(validate);\n }\n\n function createShapeTypeChecker(shapeTypes) {\n function validate(props, propName, componentName, location, propFullName) {\n var propValue = props[propName];\n var propType = getPropType(propValue);\n if (propType !== 'object') {\n return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type `' + propType + '` ' + ('supplied to `' + componentName + '`, expected `object`.'));\n }\n for (var key in shapeTypes) {\n var checker = shapeTypes[key];\n if (!checker) {\n continue;\n }\n var error = checker(propValue, key, componentName, location, propFullName + '.' + key, ReactPropTypesSecret);\n if (error) {\n return error;\n }\n }\n return null;\n }\n return createChainableTypeChecker(validate);\n }\n\n function createStrictShapeTypeChecker(shapeTypes) {\n function validate(props, propName, componentName, location, propFullName) {\n var propValue = props[propName];\n var propType = getPropType(propValue);\n if (propType !== 'object') {\n return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type `' + propType + '` ' + ('supplied to `' + componentName + '`, expected `object`.'));\n }\n // We need to check all keys in case some are required but missing from\n // props.\n var allKeys = assign({}, props[propName], shapeTypes);\n for (var key in allKeys) {\n var checker = shapeTypes[key];\n if (!checker) {\n return new PropTypeError(\n 'Invalid ' + location + ' `' + propFullName + '` key `' + key + '` supplied to `' + componentName + '`.' +\n '\\nBad object: ' + JSON.stringify(props[propName], null, ' ') +\n '\\nValid keys: ' + JSON.stringify(Object.keys(shapeTypes), null, ' ')\n );\n }\n var error = checker(propValue, key, componentName, location, propFullName + '.' + key, ReactPropTypesSecret);\n if (error) {\n return error;\n }\n }\n return null;\n }\n\n return createChainableTypeChecker(validate);\n }\n\n function isNode(propValue) {\n switch (typeof propValue) {\n case 'number':\n case 'string':\n case 'undefined':\n return true;\n case 'boolean':\n return !propValue;\n case 'object':\n if (Array.isArray(propValue)) {\n return propValue.every(isNode);\n }\n if (propValue === null || isValidElement(propValue)) {\n return true;\n }\n\n var iteratorFn = getIteratorFn(propValue);\n if (iteratorFn) {\n var iterator = iteratorFn.call(propValue);\n var step;\n if (iteratorFn !== propValue.entries) {\n while (!(step = iterator.next()).done) {\n if (!isNode(step.value)) {\n return false;\n }\n }\n } else {\n // Iterator will provide entry [k,v] tuples rather than values.\n while (!(step = iterator.next()).done) {\n var entry = step.value;\n if (entry) {\n if (!isNode(entry[1])) {\n return false;\n }\n }\n }\n }\n } else {\n return false;\n }\n\n return true;\n default:\n return false;\n }\n }\n\n function isSymbol(propType, propValue) {\n // Native Symbol.\n if (propType === 'symbol') {\n return true;\n }\n\n // falsy value can't be a Symbol\n if (!propValue) {\n return false;\n }\n\n // 19.4.3.5 Symbol.prototype[@@toStringTag] === 'Symbol'\n if (propValue['@@toStringTag'] === 'Symbol') {\n return true;\n }\n\n // Fallback for non-spec compliant Symbols which are polyfilled.\n if (typeof Symbol === 'function' && propValue instanceof Symbol) {\n return true;\n }\n\n return false;\n }\n\n // Equivalent of `typeof` but with special handling for array and regexp.\n function getPropType(propValue) {\n var propType = typeof propValue;\n if (Array.isArray(propValue)) {\n return 'array';\n }\n if (propValue instanceof RegExp) {\n // Old webkits (at least until Android 4.0) return 'function' rather than\n // 'object' for typeof a RegExp. We'll normalize this here so that /bla/\n // passes PropTypes.object.\n return 'object';\n }\n if (isSymbol(propType, propValue)) {\n return 'symbol';\n }\n return propType;\n }\n\n // This handles more types than `getPropType`. Only used for error messages.\n // See `createPrimitiveTypeChecker`.\n function getPreciseType(propValue) {\n if (typeof propValue === 'undefined' || propValue === null) {\n return '' + propValue;\n }\n var propType = getPropType(propValue);\n if (propType === 'object') {\n if (propValue instanceof Date) {\n return 'date';\n } else if (propValue instanceof RegExp) {\n return 'regexp';\n }\n }\n return propType;\n }\n\n // Returns a string that is postfixed to a warning about an invalid type.\n // For example, \"undefined\" or \"of type array\"\n function getPostfixForTypeWarning(value) {\n var type = getPreciseType(value);\n switch (type) {\n case 'array':\n case 'object':\n return 'an ' + type;\n case 'boolean':\n case 'date':\n case 'regexp':\n return 'a ' + type;\n default:\n return type;\n }\n }\n\n // Returns class name of the object, if any.\n function getClassName(propValue) {\n if (!propValue.constructor || !propValue.constructor.name) {\n return ANONYMOUS;\n }\n return propValue.constructor.name;\n }\n\n ReactPropTypes.checkPropTypes = checkPropTypes;\n ReactPropTypes.resetWarningCache = checkPropTypes.resetWarningCache;\n ReactPropTypes.PropTypes = ReactPropTypes;\n\n return ReactPropTypes;\n};\n\n\n//# sourceURL=webpack:///./node_modules/prop-types/factoryWithTypeCheckers.js?");
/***/ }),
/***/ "./node_modules/prop-types/index.js":
/*!******************************************!*\
!*** ./node_modules/prop-types/index.js ***!
\******************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
eval("/**\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\nif (true) {\n var ReactIs = __webpack_require__(/*! react-is */ \"./node_modules/react-is/index.js\");\n\n // By explicitly using `prop-types` you are opting into new development behavior.\n // http://fb.me/prop-types-in-prod\n var throwOnDirectAccess = true;\n module.exports = __webpack_require__(/*! ./factoryWithTypeCheckers */ \"./node_modules/prop-types/factoryWithTypeCheckers.js\")(ReactIs.isElement, throwOnDirectAccess);\n} else {}\n\n\n//# sourceURL=webpack:///./node_modules/prop-types/index.js?");
/***/ }),
/***/ "./node_modules/prop-types/lib/ReactPropTypesSecret.js":
/*!*************************************************************!*\
!*** ./node_modules/prop-types/lib/ReactPropTypesSecret.js ***!
\*************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
eval("/**\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\n\n\nvar ReactPropTypesSecret = 'SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED';\n\nmodule.exports = ReactPropTypesSecret;\n\n\n//# sourceURL=webpack:///./node_modules/prop-types/lib/ReactPropTypesSecret.js?");
/***/ }),
/***/ "./node_modules/react-dom/cjs/react-dom.development.js":
/*!*************************************************************!*\
!*** ./node_modules/react-dom/cjs/react-dom.development.js ***!
\*************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
eval("/** @license React v16.13.1\n * react-dom.development.js\n *\n * Copyright (c) Facebook, Inc. and its affiliates.\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\n\n\n\nif (true) {\n (function() {\n'use strict';\n\nvar React = __webpack_require__(/*! react */ \"./node_modules/react/index.js\");\nvar _assign = __webpack_require__(/*! object-assign */ \"./node_modules/object-assign/index.js\");\nvar Scheduler = __webpack_require__(/*! scheduler */ \"./node_modules/scheduler/index.js\");\nvar checkPropTypes = __webpack_require__(/*! prop-types/checkPropTypes */ \"./node_modules/prop-types/checkPropTypes.js\");\nvar tracing = __webpack_require__(/*! scheduler/tracing */ \"./node_modules/scheduler/tracing.js\");\n\nvar ReactSharedInternals = React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED; // Prevent newer renderers from RTE when used with older react package versions.\n// Current owner and dispatcher used to share the same ref,\n// but PR #14548 split them out to better support the react-debug-tools package.\n\nif (!ReactSharedInternals.hasOwnProperty('ReactCurrentDispatcher')) {\n ReactSharedInternals.ReactCurrentDispatcher = {\n current: null\n };\n}\n\nif (!ReactSharedInternals.hasOwnProperty('ReactCurrentBatchConfig')) {\n ReactSharedInternals.ReactCurrentBatchConfig = {\n suspense: null\n };\n}\n\n// by calls to these methods by a Babel plugin.\n//\n// In PROD (or in packages without access to React internals),\n// they are left as they are instead.\n\nfunction warn(format) {\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 printWarning('warn', format, args);\n }\n}\nfunction error(format) {\n {\n for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {\n args[_key2 - 1] = arguments[_key2];\n }\n\n printWarning('error', format, args);\n }\n}\n\nfunction printWarning(level, format, args) {\n // When changing this logic, you might want to also\n // update consoleWithStackDev.www.js as well.\n {\n var hasExistingStack = args.length > 0 && typeof args[args.length - 1] === 'string' && args[args.length - 1].indexOf('\\n in') === 0;\n\n if (!hasExistingStack) {\n var ReactDebugCurrentFrame = ReactSharedInternals.ReactDebugCurrentFrame;\n var stack = ReactDebugCurrentFrame.getStackAddendum();\n\n if (stack !== '') {\n format += '%s';\n args = args.concat([stack]);\n }\n }\n\n var argsWithFormat = args.map(function (item) {\n return '' + item;\n }); // Careful: RN currently depends on this prefix\n\n argsWithFormat.unshift('Warning: ' + format); // We intentionally don't use spread (or .apply) directly because it\n // breaks IE9: https://github.com/facebook/react/issues/13610\n // eslint-disable-next-line react-internal/no-production-logging\n\n Function.prototype.apply.call(console[level], console, argsWithFormat);\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 var argIndex = 0;\n var message = 'Warning: ' + format.replace(/%s/g, function () {\n return args[argIndex++];\n });\n throw new Error(message);\n } catch (x) {}\n }\n}\n\nif (!React) {\n {\n throw Error( \"ReactDOM was loaded before React. Make sure you load the React package before loading ReactDOM.\" );\n }\n}\n\nvar invokeGuardedCallbackImpl = function (name, func, context, a, b, c, d, e, f) {\n var funcArgs = Array.prototype.slice.call(arguments, 3);\n\n try {\n func.apply(context, funcArgs);\n } catch (error) {\n this.onError(error);\n }\n};\n\n{\n // In DEV mode, we swap out invokeGuardedCallback for a special version\n // that plays more nicely with the browser's DevTools. The idea is to preserve\n // \"Pause on exceptions\" behavior. Because React wraps all user-provided\n // functions in invokeGuardedCallback, and the production version of\n // invokeGuardedCallback uses a try-catch, all user exceptions are treated\n // like caught exceptions, and the DevTools won't pause unless the developer\n // takes the extra step of enabling pause on caught exceptions. This is\n // unintuitive, though, because even though React has caught the error, from\n // the developer's perspective, the error is uncaught.\n //\n // To preserve the expected \"Pause on exceptions\" behavior, we don't use a\n // try-catch in DEV. Instead, we synchronously dispatch a fake event to a fake\n // DOM node, and call the user-provided callback from inside an event handler\n // for that fake event. If the callback throws, the error is \"captured\" using\n // a global event handler. But because the error happens in a different\n // event loop context, it does not interrupt the normal program flow.\n // Effectively, this gives us try-catch behavior without actually using\n // try-catch. Neat!\n // Check that the browser supports the APIs we need to implement our special\n // DEV version of invokeGuardedCallback\n if (typeof window !== 'undefined' && typeof window.dispatchEvent === 'function' && typeof document !== 'undefined' && typeof document.createEvent === 'function') {\n var fakeNode = document.createElement('react');\n\n var invokeGuardedCallbackDev = function (name, func, context, a, b, c, d, e, f) {\n // If document doesn't exist we know for sure we will crash in this method\n // when we call document.createEvent(). However this can cause confusing\n // errors: https://github.com/facebookincubator/create-react-app/issues/3482\n // So we preemptively throw with a better message instead.\n if (!(typeof document !== 'undefined')) {\n {\n throw Error( \"The `document` global was defined when React was initialized, but is not defined anymore. This can happen in a test environment if a component schedules an update from an asynchronous callback, but the test has already finished running. To solve this, you can either unmount the component at the end of your test (and ensure that any asynchronous operations get canceled in `componentWillUnmount`), or you can change the test itself to be asynchronous.\" );\n }\n }\n\n var evt = document.createEvent('Event'); // Keeps track of whether the user-provided callback threw an error. We\n // set this to true at the beginning, then set it to false right after\n // calling the function. If the function errors, `didError` will never be\n // set to false. This strategy works even if the browser is flaky and\n // fails to call our global error handler, because it doesn't rely on\n // the error event at all.\n\n var didError = true; // Keeps track of the value of window.event so that we can reset it\n // during the callback to let user code access window.event in the\n // browsers that support it.\n\n var windowEvent = window.event; // Keeps track of the descriptor of window.event to restore it after event\n // dispatching: https://github.com/facebook/react/issues/13688\n\n var windowEventDescriptor = Object.getOwnPropertyDescriptor(window, 'event'); // Create an event handler for our fake event. We will synchronously\n // dispatch our fake event using `dispatchEvent`. Inside the handler, we\n // call the user-provided callback.\n\n var funcArgs = Array.prototype.slice.call(arguments, 3);\n\n function callCallback() {\n // We immediately remove the callback from event listeners so that\n // nested `invokeGuardedCallback` calls do not clash. Otherwise, a\n // nested call would trigger the fake event handlers of any call higher\n // in the stack.\n fakeNode.removeEventListener(evtType, callCallback, false); // We check for window.hasOwnProperty('event') to prevent the\n // window.event assignment in both IE <= 10 as they throw an error\n // \"Member not found\" in strict mode, and in Firefox which does not\n // support window.event.\n\n if (typeof window.event !== 'undefined' && window.hasOwnProperty('event')) {\n window.event = windowEvent;\n }\n\n func.apply(context, funcArgs);\n didError = false;\n } // Create a global error event handler. We use this to capture the value\n // that was thrown. It's possible that this error handler will fire more\n // than once; for example, if non-React code also calls `dispatchEvent`\n // and a handler for that event throws. We should be resilient to most of\n // those cases. Even if our error event handler fires more than once, the\n // last error event is always used. If the callback actually does error,\n // we know that the last error event is the correct one, because it's not\n // possible for anything else to have happened in between our callback\n // erroring and the code that follows the `dispatchEvent` call below. If\n // the callback doesn't error, but the error event was fired, we know to\n // ignore it because `didError` will be false, as described above.\n\n\n var error; // Use this to track whether the error event is ever called.\n\n var didSetError = false;\n var isCrossOriginError = false;\n\n function handleWindowError(event) {\n error = event.error;\n didSetError = true;\n\n if (error === null && event.colno === 0 && event.lineno === 0) {\n isCrossOriginError = true;\n }\n\n if (event.defaultPrevented) {\n // Some other error handler has prevented default.\n // Browsers silence the error report if this happens.\n // We'll remember this to later decide whether to log it or not.\n if (error != null && typeof error === 'object') {\n try {\n error._suppressLogging = true;\n } catch (inner) {// Ignore.\n }\n }\n }\n } // Create a fake event type.\n\n\n var evtType = \"react-\" + (name ? name : 'invokeguardedcallback'); // Attach our event handlers\n\n window.addEventListener('error', handleWindowError);\n fakeNode.addEventListener(evtType, callCallback, false); // Synchronously dispatch our fake event. If the user-provided function\n // errors, it will trigger our global error handler.\n\n evt.initEvent(evtType, false, false);\n fakeNode.dispatchEvent(evt);\n\n if (windowEventDescriptor) {\n Object.defineProperty(window, 'event', windowEventDescriptor);\n }\n\n if (didError) {\n if (!didSetError) {\n // The callback errored, but the error event never fired.\n error = new Error('An error was thrown inside one of your components, but React ' + \"doesn't know what it was. This is likely due to browser \" + 'flakiness. React does its best to preserve the \"Pause on ' + 'exceptions\" behavior of the DevTools, which requires some ' + \"DEV-mode only tricks. It's possible that these don't work in \" + 'your browser. Try triggering the error in production mode, ' + 'or switching to a modern browser. If you suspect that this is ' + 'actually an issue with React, please file an issue.');\n } else if (isCrossOriginError) {\n error = new Error(\"A cross-origin error was thrown. React doesn't have access to \" + 'the actual error object in development. ' + 'See https://fb.me/react-crossorigin-error for more information.');\n }\n\n this.onError(error);\n } // Remove our event listeners\n\n\n window.removeEventListener('error', handleWindowError);\n };\n\n invokeGuardedCallbackImpl = invokeGuardedCallbackDev;\n }\n}\n\nvar invokeGuardedCallbackImpl$1 = invokeGuardedCallbackImpl;\n\nvar hasError = false;\nvar caughtError = null; // Used by event system to capture/rethrow the first error.\n\nvar hasRethrowError = false;\nvar rethrowError = null;\nvar reporter = {\n onError: function (error) {\n hasError = true;\n caughtError = error;\n }\n};\n/**\n * Call a function while guarding against errors that happens within it.\n * Returns an error if it throws, otherwise null.\n *\n * In production, this is implemented using a try-catch. The reason we don't\n * use a try-catch directly is so that we can swap out a different\n * implementation in DEV mode.\n *\n * @param {String} name of the guard to use for logging or debugging\n * @param {Function} func The function to invoke\n * @param {*} context The context to use when calling the function\n * @param {...*} args Arguments for function\n */\n\nfunction invokeGuardedCallback(name, func, context, a, b, c, d, e, f) {\n hasError = false;\n caughtError = null;\n invokeGuardedCallbackImpl$1.apply(reporter, arguments);\n}\n/**\n * Same as invokeGuardedCallback, but instead of returning an error, it stores\n * it in a global so it can be rethrown by `rethrowCaughtError` later.\n * TODO: See if caughtError and rethrowError can be unified.\n *\n * @param {String} name of the guard to use for logging or debugging\n * @param {Function} func The function to invoke\n * @param {*} context The context to use when calling the function\n * @param {...*} args Arguments for function\n */\n\nfunction invokeGuardedCallbackAndCatchFirstError(name, func, context, a, b, c, d, e, f) {\n invokeGuardedCallback.apply(this, arguments);\n\n if (hasError) {\n var error = clearCaughtError();\n\n if (!hasRethrowError) {\n hasRethrowError = true;\n rethrowError = error;\n }\n }\n}\n/**\n * During execution of guarded functions we will capture the first error which\n * we will rethrow to be handled by the top level error handler.\n */\n\nfunction rethrowCaughtError() {\n if (hasRethrowError) {\n var error = rethrowError;\n hasRethrowError = false;\n rethrowError = null;\n throw error;\n }\n}\nfunction hasCaughtError() {\n return hasError;\n}\nfunction clearCaughtError() {\n if (hasError) {\n var error = caughtError;\n hasError = false;\n caughtError = null;\n return error;\n } else {\n {\n {\n throw Error( \"clearCaughtError was called but no error was captured. This error is likely caused by a bug in React. Please file an issue.\" );\n }\n }\n }\n}\n\nvar getFiberCurrentPropsFromNode = null;\nvar getInstanceFromNode = null;\nvar getNodeFromInstance = null;\nfunction setComponentTree(getFiberCurrentPropsFromNodeImpl, getInstanceFromNodeImpl, getNodeFromInstanceImpl) {\n getFiberCurrentPropsFromNode = getFiberCurrentPropsFromNodeImpl;\n getInstanceFromNode = getInstanceFromNodeImpl;\n getNodeFromInstance = getNodeFromInstanceImpl;\n\n {\n if (!getNodeFromInstance || !getInstanceFromNode) {\n error('EventPluginUtils.setComponentTree(...): Injected ' + 'module is missing getNodeFromInstance or getInstanceFromNode.');\n }\n }\n}\nvar validateEventDispatches;\n\n{\n validateEventDispatches = function (event) {\n var dispatchListeners = event._dispatchListeners;\n var dispatchInstances = event._dispatchInstances;\n var listenersIsArr = Array.isArray(dispatchListeners);\n var listenersLen = listenersIsArr ? dispatchListeners.length : dispatchListeners ? 1 : 0;\n var instancesIsArr = Array.isArray(dispatchInstances);\n var instancesLen = instancesIsArr ? dispatchInstances.length : dispatchInstances ? 1 : 0;\n\n if (instancesIsArr !== listenersIsArr || instancesLen !== listenersLen) {\n error('EventPluginUtils: Invalid `event`.');\n }\n };\n}\n/**\n * Dispatch the event to the listener.\n * @param {SyntheticEvent} event SyntheticEvent to handle\n * @param {function} listener Application-level callback\n * @param {*} inst Internal component instance\n */\n\n\nfunction executeDispatch(event, listener, inst) {\n var type = event.type || 'unknown-event';\n event.currentTarget = getNodeFromInstance(inst);\n invokeGuardedCallbackAndCatchFirstError(type, listener, undefined, event);\n event.currentTarget = null;\n}\n/**\n * Standard/simple iteration through an event's collected dispatches.\n */\n\nfunction executeDispatchesInOrder(event) {\n var dispatchListeners = event._dispatchListeners;\n var dispatchInstances = event._dispatchInstances;\n\n {\n validateEventDispatches(event);\n }\n\n if (Array.isArray(dispatchListeners)) {\n for (var i = 0; i < dispatchListeners.length; i++) {\n if (event.isPropagationStopped()) {\n break;\n } // Listeners and Instances are two parallel arrays that are always in sync.\n\n\n executeDispatch(event, dispatchListeners[i], dispatchInstances[i]);\n }\n } else if (dispatchListeners) {\n executeDispatch(event, dispatchListeners, dispatchInstances);\n }\n\n event._dispatchListeners = null;\n event._dispatchInstances = null;\n}\n\nvar FunctionComponent = 0;\nvar ClassComponent = 1;\nvar IndeterminateComponent = 2; // Before we know whether it is function or class\n\nvar HostRoot = 3; // Root of a host tree. Could be nested inside another node.\n\nvar HostPortal = 4; // A subtree. Could be an entry point to a different renderer.\n\nvar HostComponent = 5;\nvar HostText = 6;\nvar Fragment = 7;\nvar Mode = 8;\nvar ContextConsumer = 9;\nvar ContextProvider = 10;\nvar ForwardRef = 11;\nvar Profiler = 12;\nvar SuspenseComponent = 13;\nvar MemoComponent = 14;\nvar SimpleMemoComponent = 15;\nvar LazyComponent = 16;\nvar IncompleteClassComponent = 17;\nvar DehydratedFragment = 18;\nvar SuspenseListComponent = 19;\nvar FundamentalComponent = 20;\nvar ScopeComponent = 21;\nvar Block = 22;\n\n/**\n * Injectable ordering of event plugins.\n */\nvar eventPluginOrder = null;\n/**\n * Injectable mapping from names to event plugin modules.\n */\n\nvar namesToPlugins = {};\n/**\n * Recomputes the plugin list using the injected plugins and plugin ordering.\n *\n * @private\n */\n\nfunction recomputePluginOrdering() {\n if (!eventPluginOrder) {\n // Wait until an `eventPluginOrder` is injected.\n return;\n }\n\n for (var pluginName in namesToPlugins) {\n var pluginModule = namesToPlugins[pluginName];\n var pluginIndex = eventPluginOrder.indexOf(pluginName);\n\n if (!(pluginIndex > -1)) {\n {\n throw Error( \"EventPluginRegistry: Cannot inject event plugins that do not exist in the plugin ordering, `\" + pluginName + \"`.\" );\n }\n }\n\n if (plugins[pluginIndex]) {\n continue;\n }\n\n if (!pluginModule.extractEvents) {\n {\n throw Error( \"EventPluginRegistry: Event plugins must implement an `extractEvents` method, but `\" + pluginName + \"` does not.\" );\n }\n }\n\n plugins[pluginIndex] = pluginModule;\n var publishedEvents = pluginModule.eventTypes;\n\n for (var eventName in publishedEvents) {\n if (!publishEventForPlugin(publishedEvents[eventName], pluginModule, eventName)) {\n {\n throw Error( \"EventPluginRegistry: Failed to publish event `\" + eventName + \"` for plugin `\" + pluginName + \"`.\" );\n }\n }\n }\n }\n}\n/**\n * Publishes an event so that it can be dispatched by the supplied plugin.\n *\n * @param {object} dispatchConfig Dispatch configuration for the event.\n * @param {object} PluginModule Plugin publishing the event.\n * @return {boolean} True if the event was successfully published.\n * @private\n */\n\n\nfunction publishEventForPlugin(dispatchConfig, pluginModule, eventName) {\n if (!!eventNameDispatchConfigs.hasOwnProperty(eventName)) {\n {\n throw Error( \"EventPluginRegistry: More than one plugin attempted to publish the same event name, `\" + eventName + \"`.\" );\n }\n }\n\n eventNameDispatchConfigs[eventName] = dispatchConfig;\n var phasedRegistrationNames = dispatchConfig.phasedRegistrationNames;\n\n if (phasedRegistrationNames) {\n for (var phaseName in phasedRegistrationNames) {\n if (phasedRegistrationNames.hasOwnProperty(phaseName)) {\n var phasedRegistrationName = phasedRegistrationNames[phaseName];\n publishRegistrationName(phasedRegistrationName, pluginModule, eventName);\n }\n }\n\n return true;\n } else if (dispatchConfig.registrationName) {\n publishRegistrationName(dispatchConfig.registrationName, pluginModule, eventName);\n return true;\n }\n\n return false;\n}\n/**\n * Publishes a registration name that is used to identify dispatched events.\n *\n * @param {string} registrationName Registration name to add.\n * @param {object} PluginModule Plugin publishing the event.\n * @private\n */\n\n\nfunction publishRegistrationName(registrationName, pluginModule, eventName) {\n if (!!registrationNameModules[registrationName]) {\n {\n throw Error( \"EventPluginRegistry: More than one plugin attempted to publish the same registration name, `\" + registrationName + \"`.\" );\n }\n }\n\n registrationNameModules[registrationName] = pluginModule;\n registrationNameDependencies[registrationName] = pluginModule.eventTypes[eventName].dependencies;\n\n {\n var lowerCasedName = registrationName.toLowerCase();\n possibleRegistrationNames[lowerCasedName] = registrationName;\n\n if (registrationName === 'onDoubleClick') {\n possibleRegistrationNames.ondblclick = registrationName;\n }\n }\n}\n/**\n * Registers plugins so that they can extract and dispatch events.\n */\n\n/**\n * Ordered list of injected plugins.\n */\n\n\nvar plugins = [];\n/**\n * Mapping from event name to dispatch config\n */\n\nvar eventNameDispatchConfigs = {};\n/**\n * Mapping from registration name to plugin module\n */\n\nvar registrationNameModules = {};\n/**\n * Mapping from registration name to event name\n */\n\nvar registrationNameDependencies = {};\n/**\n * Mapping from lowercase registration names to the properly cased version,\n * used to warn in the case of missing event handlers. Available\n * only in true.\n * @type {Object}\n */\n\nvar possibleRegistrationNames = {} ; // Trust the developer to only use possibleRegistrationNames in true\n\n/**\n * Injects an ordering of plugins (by plugin name). This allows the ordering\n * to be decoupled from injection of the actual plugins so that ordering is\n * always deterministic regardless of packaging, on-the-fly injection, etc.\n *\n * @param {array} InjectedEventPluginOrder\n * @internal\n */\n\nfunction injectEventPluginOrder(injectedEventPluginOrder) {\n if (!!eventPluginOrder) {\n {\n throw Error( \"EventPluginRegistry: Cannot inject event plugin ordering more than once. You are likely trying to load more than one copy of React.\" );\n }\n } // Clone the ordering so it cannot be dynamically mutated.\n\n\n eventPluginOrder = Array.prototype.slice.call(injectedEventPluginOrder);\n recomputePluginOrdering();\n}\n/**\n * Injects plugins to be used by plugin event system. The plugin names must be\n * in the ordering injected by `injectEventPluginOrder`.\n *\n * Plugins can be injected as part of page initialization or on-the-fly.\n *\n * @param {object} injectedNamesToPlugins Map from names to plugin modules.\n * @internal\n */\n\nfunction injectEventPluginsByName(injectedNamesToPlugins) {\n var isOrderingDirty = false;\n\n for (var pluginName in injectedNamesToPlugins) {\n if (!injectedNamesToPlugins.hasOwnProperty(pluginName)) {\n continue;\n }\n\n var pluginModule = injectedNamesToPlugins[pluginName];\n\n if (!namesToPlugins.hasOwnProperty(pluginName) || namesToPlugins[pluginName] !== pluginModule) {\n if (!!namesToPlugins[pluginName]) {\n {\n throw Error( \"EventPluginRegistry: Cannot inject two different event plugins using the same name, `\" + pluginName + \"`.\" );\n }\n }\n\n namesToPlugins[pluginName] = pluginModule;\n isOrderingDirty = true;\n }\n }\n\n if (isOrderingDirty) {\n recomputePluginOrdering();\n }\n}\n\nvar canUseDOM = !!(typeof window !== 'undefined' && typeof window.document !== 'undefined' && typeof window.document.createElement !== 'undefined');\n\nvar PLUGIN_EVENT_SYSTEM = 1;\nvar IS_REPLAYED = 1 << 5;\nvar IS_FIRST_ANCESTOR = 1 << 6;\n\nvar restoreImpl = null;\nvar restoreTarget = null;\nvar restoreQueue = null;\n\nfunction restoreStateOfTarget(target) {\n // We perform this translation at the end of the event loop so that we\n // always receive the correct fiber here\n var internalInstance = getInstanceFromNode(target);\n\n if (!internalInstance) {\n // Unmounted\n return;\n }\n\n if (!(typeof restoreImpl === 'function')) {\n {\n throw Error( \"setRestoreImplementation() needs to be called to handle a target for controlled events. This error is likely caused by a bug in React. Please file an issue.\" );\n }\n }\n\n var stateNode = internalInstance.stateNode; // Guard against Fiber being unmounted.\n\n if (stateNode) {\n var _props = getFiberCurrentPropsFromNode(stateNode);\n\n restoreImpl(internalInstance.stateNode, internalInstance.type, _props);\n }\n}\n\nfunction setRestoreImplementation(impl) {\n restoreImpl = impl;\n}\nfunction enqueueStateRestore(target) {\n if (restoreTarget) {\n if (restoreQueue) {\n restoreQueue.push(target);\n } else {\n restoreQueue = [target];\n }\n } else {\n restoreTarget = target;\n }\n}\nfunction needsStateRestore() {\n return restoreTarget !== null || restoreQueue !== null;\n}\nfunction restoreStateIfNeeded() {\n if (!restoreTarget) {\n return;\n }\n\n var target = restoreTarget;\n var queuedTargets = restoreQueue;\n restoreTarget = null;\n restoreQueue = null;\n restoreStateOfTarget(target);\n\n if (queuedTargets) {\n for (var i = 0; i < queuedTargets.length; i++) {\n restoreStateOfTarget(queuedTargets[i]);\n }\n }\n}\n\nvar enableProfilerTimer = true; // Trace which interactions trigger each commit.\n\nvar enableDeprecatedFlareAPI = false; // Experimental Host Component support.\n\nvar enableFundamentalAPI = false; // Experimental Scope support.\nvar warnAboutStringRefs = false;\n\n// the renderer. Such as when we're dispatching events or if third party\n// libraries need to call batchedUpdates. Eventually, this API will go away when\n// everything is batched by default. We'll then have a similar API to opt-out of\n// scheduled work and instead do synchronous work.\n// Defaults\n\nvar batchedUpdatesImpl = function (fn, bookkeeping) {\n return fn(bookkeeping);\n};\n\nvar discreteUpdatesImpl = function (fn, a, b, c, d) {\n return fn(a, b, c, d);\n};\n\nvar flushDiscreteUpdatesImpl = function () {};\n\nvar batchedEventUpdatesImpl = batchedUpdatesImpl;\nvar isInsideEventHandler = false;\nvar isBatchingEventUpdates = false;\n\nfunction finishEventHandler() {\n // Here we wait until all updates have propagated, which is important\n // when using controlled components within layers:\n // https://github.com/facebook/react/issues/1698\n // Then we restore state of any controlled component.\n var controlledComponentsHavePendingUpdates = needsStateRestore();\n\n if (controlledComponentsHavePendingUpdates) {\n // If a controlled event was fired, we may need to restore the state of\n // the DOM node back to the controlled value. This is necessary when React\n // bails out of the update without touching the DOM.\n flushDiscreteUpdatesImpl();\n restoreStateIfNeeded();\n }\n}\n\nfunction batchedUpdates(fn, bookkeeping) {\n if (isInsideEventHandler) {\n // If we are currently inside another batch, we need to wait until it\n // fully completes before restoring state.\n return fn(bookkeeping);\n }\n\n isInsideEventHandler = true;\n\n try {\n return batchedUpdatesImpl(fn, bookkeeping);\n } finally {\n isInsideEventHandler = false;\n finishEventHandler();\n }\n}\nfunction batchedEventUpdates(fn, a, b) {\n if (isBatchingEventUpdates) {\n // If we are currently inside another batch, we need to wait until it\n // fully completes before restoring state.\n return fn(a, b);\n }\n\n isBatchingEventUpdates = true;\n\n try {\n return batchedEventUpdatesImpl(fn, a, b);\n } finally {\n isBatchingEventUpdates = false;\n finishEventHandler();\n }\n} // This is for the React Flare event system\nfunction discreteUpdates(fn, a, b, c, d) {\n var prevIsInsideEventHandler = isInsideEventHandler;\n isInsideEventHandler = true;\n\n try {\n return discreteUpdatesImpl(fn, a, b, c, d);\n } finally {\n isInsideEventHandler = prevIsInsideEventHandler;\n\n if (!isInsideEventHandler) {\n finishEventHandler();\n }\n }\n}\nfunction flushDiscreteUpdatesIfNeeded(timeStamp) {\n // event.timeStamp isn't overly reliable due to inconsistencies in\n // how different browsers have historically provided the time stamp.\n // Some browsers provide high-resolution time stamps for all events,\n // some provide low-resolution time stamps for all events. FF < 52\n // even mixes both time stamps together. Some browsers even report\n // negative time stamps or time stamps that are 0 (iOS9) in some cases.\n // Given we are only comparing two time stamps with equality (!==),\n // we are safe from the resolution differences. If the time stamp is 0\n // we bail-out of preventing the flush, which can affect semantics,\n // such as if an earlier flush removes or adds event listeners that\n // are fired in the subsequent flush. However, this is the same\n // behaviour as we had before this change, so the risks are low.\n if (!isInsideEventHandler && (!enableDeprecatedFlareAPI )) {\n flushDiscreteUpdatesImpl();\n }\n}\nfunction setBatchingImplementation(_batchedUpdatesImpl, _discreteUpdatesImpl, _flushDiscreteUpdatesImpl, _batchedEventUpdatesImpl) {\n batchedUpdatesImpl = _batchedUpdatesImpl;\n discreteUpdatesImpl = _discreteUpdatesImpl;\n flushDiscreteUpdatesImpl = _flushDiscreteUpdatesImpl;\n batchedEventUpdatesImpl = _batchedEventUpdatesImpl;\n}\n\nvar DiscreteEvent = 0;\nvar UserBlockingEvent = 1;\nvar ContinuousEvent = 2;\n\n// A reserved attribute.\n// It is handled by React separately and shouldn't be written to the DOM.\nvar RESERVED = 0; // A simple string attribute.\n// Attributes that aren't in the whitelist are presumed to have this type.\n\nvar STRING = 1; // A string attribute that accepts booleans in React. In HTML, these are called\n// \"enumerated\" attributes with \"true\" and \"false\" as possible values.\n// When true, it should be set to a \"true\" string.\n// When false, it should be set to a \"false\" string.\n\nvar BOOLEANISH_STRING = 2; // A real boolean attribute.\n// When true, it should be present (set either to an empty string or its name).\n// When false, it should be omitted.\n\nvar BOOLEAN = 3; // An attribute that can be used as a flag as well as with a value.\n// When true, it should be present (set either to an empty string or its name).\n// When false, it should be omitted.\n// For any other value, should be present with that value.\n\nvar OVERLOADED_BOOLEAN = 4; // An attribute that must be numeric or parse as a numeric.\n// When falsy, it should be removed.\n\nvar NUMERIC = 5; // An attribute that must be positive numeric or parse as a positive numeric.\n// When falsy, it should be removed.\n\nvar POSITIVE_NUMERIC = 6;\n\n/* eslint-disable max-len */\nvar ATTRIBUTE_NAME_START_CHAR = \":A-Z_a-z\\\\u00C0-\\\\u00D6\\\\u00D8-\\\\u00F6\\\\u00F8-\\\\u02FF\\\\u0370-\\\\u037D\\\\u037F-\\\\u1FFF\\\\u200C-\\\\u200D\\\\u2070-\\\\u218F\\\\u2C00-\\\\u2FEF\\\\u3001-\\\\uD7FF\\\\uF900-\\\\uFDCF\\\\uFDF0-\\\\uFFFD\";\n/* eslint-enable max-len */\n\nvar ATTRIBUTE_NAME_CHAR = ATTRIBUTE_NAME_START_CHAR + \"\\\\-.0-9\\\\u00B7\\\\u0300-\\\\u036F\\\\u203F-\\\\u2040\";\nvar ROOT_ATTRIBUTE_NAME = 'data-reactroot';\nvar VALID_ATTRIBUTE_NAME_REGEX = new RegExp('^[' + ATTRIBUTE_NAME_START_CHAR + '][' + ATTRIBUTE_NAME_CHAR + ']*$');\nvar hasOwnProperty = Object.prototype.hasOwnProperty;\nvar illegalAttributeNameCache = {};\nvar validatedAttributeNameCache = {};\nfunction isAttributeNameSafe(attributeName) {\n if (hasOwnProperty.call(validatedAttributeNameCache, attributeName)) {\n return true;\n }\n\n if (hasOwnProperty.call(illegalAttributeNameCache, attributeName)) {\n return false;\n }\n\n if (VALID_ATTRIBUTE_NAME_REGEX.test(attributeName)) {\n validatedAttributeNameCache[attributeName] = true;\n return true;\n }\n\n illegalAttributeNameCache[attributeName] = true;\n\n {\n error('Invalid attribute name: `%s`', attributeName);\n }\n\n return false;\n}\nfunction shouldIgnoreAttribute(name, propertyInfo, isCustomComponentTag) {\n if (propertyInfo !== null) {\n return propertyInfo.type === RESERVED;\n }\n\n if (isCustomComponentTag) {\n return false;\n }\n\n if (name.length > 2 && (name[0] === 'o' || name[0] === 'O') && (name[1] === 'n' || name[1] === 'N')) {\n return true;\n }\n\n return false;\n}\nfunction shouldRemoveAttributeWithWarning(name, value, propertyInfo, isCustomComponentTag) {\n if (propertyInfo !== null && propertyInfo.type === RESERVED) {\n return false;\n }\n\n switch (typeof value) {\n case 'function': // $FlowIssue symbol is perfectly valid here\n\n case 'symbol':\n // eslint-disable-line\n return true;\n\n case 'boolean':\n {\n if (isCustomComponentTag) {\n return false;\n }\n\n if (propertyInfo !== null) {\n return !propertyInfo.acceptsBooleans;\n } else {\n var prefix = name.toLowerCase().slice(0, 5);\n return prefix !== 'data-' && prefix !== 'aria-';\n }\n }\n\n default:\n return false;\n }\n}\nfunction shouldRemoveAttribute(name, value, propertyInfo, isCustomComponentTag) {\n if (value === null || typeof value === 'undefined') {\n return true;\n }\n\n if (shouldRemoveAttributeWithWarning(name, value, propertyInfo, isCustomComponentTag)) {\n return true;\n }\n\n if (isCustomComponentTag) {\n return false;\n }\n\n if (propertyInfo !== null) {\n switch (propertyInfo.type) {\n case BOOLEAN:\n return !value;\n\n case OVERLOADED_BOOLEAN:\n return value === false;\n\n case NUMERIC:\n return isNaN(value);\n\n case POSITIVE_NUMERIC:\n return isNaN(value) || value < 1;\n }\n }\n\n return false;\n}\nfunction getPropertyInfo(name) {\n return properties.hasOwnProperty(name) ? properties[name] : null;\n}\n\nfunction PropertyInfoRecord(name, type, mustUseProperty, attributeName, attributeNamespace, sanitizeURL) {\n this.acceptsBooleans = type === BOOLEANISH_STRING || type === BOOLEAN || type === OVERLOADED_BOOLEAN;\n this.attributeName = attributeName;\n this.attributeNamespace = attributeNamespace;\n this.mustUseProperty = mustUseProperty;\n this.propertyName = name;\n this.type = type;\n this.sanitizeURL = sanitizeURL;\n} // When adding attributes to this list, be sure to also add them to\n// the `possibleStandardNames` module to ensure casing and incorrect\n// name warnings.\n\n\nvar properties = {}; // These props are reserved by React. They shouldn't be written to the DOM.\n\nvar reservedProps = ['children', 'dangerouslySetInnerHTML', // TODO: This prevents the assignment of defaultValue to regular\n// elements (not just inputs). Now that ReactDOMInput assigns to the\n// defaultValue property -- do we need this?\n'defaultValue', 'defaultChecked', 'innerHTML', 'suppressContentEditableWarning', 'suppressHydrationWarning', 'style'];\n\nreservedProps.forEach(function (name) {\n properties[name] = new PropertyInfoRecord(name, RESERVED, false, // mustUseProperty\n name, // attributeName\n null, // attributeNamespace\n false);\n}); // A few React string attributes have a different name.\n// This is a mapping from React prop names to the attribute names.\n\n[['acceptCharset', 'accept-charset'], ['className', 'class'], ['htmlFor', 'for'], ['httpEquiv', 'http-equiv']].forEach(function (_ref) {\n var name = _ref[0],\n attributeName = _ref[1];\n properties[name] = new PropertyInfoRecord(name, STRING, false, // mustUseProperty\n attributeName, // attributeName\n null, // attributeNamespace\n false);\n}); // These are \"enumerated\" HTML attributes that accept \"true\" and \"false\".\n// In React, we let users pass `true` and `false` even though technically\n// these aren't boolean attributes (they are coerced to strings).\n\n['contentEditable', 'draggable', 'spellCheck', 'value'].forEach(function (name) {\n properties[name] = new PropertyInfoRecord(name, BOOLEANISH_STRING, false, // mustUseProperty\n name.toLowerCase(), // attributeName\n null, // attributeNamespace\n false);\n}); // These are \"enumerated\" SVG attributes that accept \"true\" and \"false\".\n// In React, we let users pass `true` and `false` even though technically\n// these aren't boolean attributes (they are coerced to strings).\n// Since these are SVG attributes, their attribute names are case-sensitive.\n\n['autoReverse', 'externalResourcesRequired', 'focusable', 'preserveAlpha'].forEach(function (name) {\n properties[name] = new PropertyInfoRecord(name, BOOLEANISH_STRING, false, // mustUseProperty\n name, // attributeName\n null, // attributeNamespace\n false);\n}); // These are HTML boolean attributes.\n\n['allowFullScreen', 'async', // Note: there is a special case that prevents it from being written to the DOM\n// on the client side because the browsers are inconsistent. Instead we call focus().\n'autoFocus', 'autoPlay', 'controls', 'default', 'defer', 'disabled', 'disablePictureInPicture', 'formNoValidate', 'hidden', 'loop', 'noModule', 'noValidate', 'open', 'playsInline', 'readOnly', 'required', 'reversed', 'scoped', 'seamless', // Microdata\n'itemScope'].forEach(function (name) {\n properties[name] = new PropertyInfoRecord(name, BOOLEAN, false, // mustUseProperty\n name.toLowerCase(), // attributeName\n null, // attributeNamespace\n false);\n}); // These are the few React props that we set as DOM properties\n// rather than attributes. These are all booleans.\n\n['checked', // Note: `option.selected` is not updated if `select.multiple` is\n// disabled with `removeAttribute`. We have special logic for handling this.\n'multiple', 'muted', 'selected' // NOTE: if you add a camelCased prop to this list,\n// you'll need to set attributeName to name.toLowerCase()\n// instead in the assignment below.\n].forEach(function (name) {\n properties[name] = new PropertyInfoRecord(name, BOOLEAN, true, // mustUseProperty\n name, // attributeName\n null, // attributeNamespace\n false);\n}); // These are HTML attributes that are \"overloaded booleans\": they behave like\n// booleans, but can also accept a string value.\n\n['capture', 'download' // NOTE: if you add a camelCased prop to this list,\n// you'll need to set attributeName to name.toLowerCase()\n// instead in the assignment below.\n].forEach(function (name) {\n properties[name] = new PropertyInfoRecord(name, OVERLOADED_BOOLEAN, false, // mustUseProperty\n name, // attributeName\n null, // attributeNamespace\n false);\n}); // These are HTML attributes that must be positive numbers.\n\n['cols', 'rows', 'size', 'span' // NOTE: if you add a camelCased prop to this list,\n// you'll need to set attributeName to name.toLowerCase()\n// instead in the assignment below.\n].forEach(function (name) {\n properties[name] = new PropertyInfoRecord(name, POSITIVE_NUMERIC, false, // mustUseProperty\n name, // attributeName\n null, // attributeNamespace\n false);\n}); // These are HTML attributes that must be numbers.\n\n['rowSpan', 'start'].forEach(function (name) {\n properties[name] = new PropertyInfoRecord(name, NUMERIC, false, // mustUseProperty\n name.toLowerCase(), // attributeName\n null, // attributeNamespace\n false);\n});\nvar CAMELIZE = /[\\-\\:]([a-z])/g;\n\nvar capitalize = function (token) {\n return token[1].toUpperCase();\n}; // This is a list of all SVG attributes that need special casing, namespacing,\n// or boolean value assignment. Regular attributes that just accept strings\n// and have the same names are omitted, just like in the HTML whitelist.\n// Some of these attributes can be hard to find. This list was created by\n// scraping the MDN documentation.\n\n\n['accent-height', 'alignment-baseline', 'arabic-form', 'baseline-shift', 'cap-height', 'clip-path', 'clip-rule', 'color-interpolation', 'color-interpolation-filters', 'color-profile', 'color-rendering', 'dominant-baseline', 'enable-background', 'fill-opacity', 'fill-rule', 'flood-color', 'flood-opacity', 'font-family', 'font-size', 'font-size-adjust', 'font-stretch', 'font-style', 'font-variant', 'font-weight', 'glyph-name', 'glyph-orientation-horizontal', 'glyph-orientation-vertical', 'horiz-adv-x', 'horiz-origin-x', 'image-rendering', 'letter-spacing', 'lighting-color', 'marker-end', 'marker-mid', 'marker-start', 'overline-position', 'overline-thickness', 'paint-order', 'panose-1', 'pointer-events', 'rendering-intent', 'shape-rendering', 'stop-color', 'stop-opacity', 'strikethrough-position', 'strikethrough-thickness', 'stroke-dasharray', 'stroke-dashoffset', 'stroke-linecap', 'stroke-linejoin', 'stroke-miterlimit', 'stroke-opacity', 'stroke-width', 'text-anchor', 'text-decoration', 'text-rendering', 'underline-position', 'underline-thickness', 'unicode-bidi', 'unicode-range', 'units-per-em', 'v-alphabetic', 'v-hanging', 'v-ideographic', 'v-mathematical', 'vector-effect', 'vert-adv-y', 'vert-origin-x', 'vert-origin-y', 'word-spacing', 'writing-mode', 'xmlns:xlink', 'x-height' // NOTE: if you add a camelCased prop to this list,\n// you'll need to set attributeName to name.toLowerCase()\n// instead in the assignment below.\n].forEach(function (attributeName) {\n var name = attributeName.replace(CAMELIZE, capitalize);\n properties[name] = new PropertyInfoRecord(name, STRING, false, // mustUseProperty\n attributeName, null, // attributeNamespace\n false);\n}); // String SVG attributes with the xlink namespace.\n\n['xlink:actuate', 'xlink:arcrole', 'xlink:role', 'xlink:show', 'xlink:title', 'xlink:type' // NOTE: if you add a camelCased prop to this list,\n// you'll need to set attributeName to name.toLowerCase()\n// instead in the assignment below.\n].forEach(function (attributeName) {\n var name = attributeName.replace(CAMELIZE, capitalize);\n properties[name] = new PropertyInfoRecord(name, STRING, false, // mustUseProperty\n attributeName, 'http://www.w3.org/1999/xlink', false);\n}); // String SVG attributes with the xml namespace.\n\n['xml:base', 'xml:lang', 'xml:space' // NOTE: if you add a camelCased prop to this list,\n// you'll need to set attributeName to name.toLowerCase()\n// instead in the assignment below.\n].forEach(function (attributeName) {\n var name = attributeName.replace(CAMELIZE, capitalize);\n properties[name] = new PropertyInfoRecord(name, STRING, false, // mustUseProperty\n attributeName, 'http://www.w3.org/XML/1998/namespace', false);\n}); // These attribute exists both in HTML and SVG.\n// The attribute name is case-sensitive in SVG so we can't just use\n// the React name like we do for attributes that exist only in HTML.\n\n['tabIndex', 'crossOrigin'].forEach(function (attributeName) {\n properties[attributeName] = new PropertyInfoRecord(attributeName, STRING, false, // mustUseProperty\n attributeName.toLowerCase(), // attributeName\n null, // attributeNamespace\n false);\n}); // These attributes accept URLs. These must not allow javascript: URLS.\n// These will also need to accept Trusted Types object in the future.\n\nvar xlinkHref = 'xlinkHref';\nproperties[xlinkHref] = new PropertyInfoRecord('xlinkHref', STRING, false, // mustUseProperty\n'xlink:href', 'http://www.w3.org/1999/xlink', true);\n['src', 'href', 'action', 'formAction'].forEach(function (attributeName) {\n properties[attributeName] = new PropertyInfoRecord(attributeName, STRING, false, // mustUseProperty\n attributeName.toLowerCase(), // attributeName\n null, // attributeNamespace\n true);\n});\n\nvar ReactDebugCurrentFrame = null;\n\n{\n ReactDebugCurrentFrame = ReactSharedInternals.ReactDebugCurrentFrame;\n} // A javascript: URL can contain leading C0 control or \\u0020 SPACE,\n// and any newline or tab are filtered out as if they're not part of the URL.\n// https://url.spec.whatwg.org/#url-parsing\n// Tab or newline are defined as \\r\\n\\t:\n// https://infra.spec.whatwg.org/#ascii-tab-or-newline\n// A C0 control is a code point in the range \\u0000 NULL to \\u001F\n// INFORMATION SEPARATOR ONE, inclusive:\n// https://infra.spec.whatwg.org/#c0-control-or-space\n\n/* eslint-disable max-len */\n\n\nvar isJavaScriptProtocol = /^[\\u0000-\\u001F ]*j[\\r\\n\\t]*a[\\r\\n\\t]*v[\\r\\n\\t]*a[\\r\\n\\t]*s[\\r\\n\\t]*c[\\r\\n\\t]*r[\\r\\n\\t]*i[\\r\\n\\t]*p[\\r\\n\\t]*t[\\r\\n\\t]*\\:/i;\nvar didWarn = false;\n\nfunction sanitizeURL(url) {\n {\n if (!didWarn && isJavaScriptProtocol.test(url)) {\n didWarn = true;\n\n error('A future version of React will block javascript: URLs as a security precaution. ' + 'Use event handlers instead if you can. If you need to generate unsafe HTML try ' + 'using dangerouslySetInnerHTML instead. React was passed %s.', JSON.stringify(url));\n }\n }\n}\n\n/**\n * Get the value for a property on a node. Only used in DEV for SSR validation.\n * The \"expected\" argument is used as a hint of what the expected value is.\n * Some properties have multiple equivalent values.\n */\nfunction getValueForProperty(node, name, expected, propertyInfo) {\n {\n if (propertyInfo.mustUseProperty) {\n var propertyName = propertyInfo.propertyName;\n return node[propertyName];\n } else {\n if ( propertyInfo.sanitizeURL) {\n // If we haven't fully disabled javascript: URLs, and if\n // the hydration is successful of a javascript: URL, we\n // still want to warn on the client.\n sanitizeURL('' + expected);\n }\n\n var attributeName = propertyInfo.attributeName;\n var stringValue = null;\n\n if (propertyInfo.type === OVERLOADED_BOOLEAN) {\n if (node.hasAttribute(attributeName)) {\n var value = node.getAttribute(attributeName);\n\n if (value === '') {\n return true;\n }\n\n if (shouldRemoveAttribute(name, expected, propertyInfo, false)) {\n return value;\n }\n\n if (value === '' + expected) {\n return expected;\n }\n\n return value;\n }\n } else if (node.hasAttribute(attributeName)) {\n if (shouldRemoveAttribute(name, expected, propertyInfo, false)) {\n // We had an attribute but shouldn't have had one, so read it\n // for the error message.\n return node.getAttribute(attributeName);\n }\n\n if (propertyInfo.type === BOOLEAN) {\n // If this was a boolean, it doesn't matter what the value is\n // the fact that we have it is the same as the expected.\n return expected;\n } // Even if this property uses a namespace we use getAttribute\n // because we assume its namespaced name is the same as our config.\n // To use getAttributeNS we need the local name which we don't have\n // in our config atm.\n\n\n stringValue = node.getAttribute(attributeName);\n }\n\n if (shouldRemoveAttribute(name, expected, propertyInfo, false)) {\n return stringValue === null ? expected : stringValue;\n } else if (stringValue === '' + expected) {\n return expected;\n } else {\n return stringValue;\n }\n }\n }\n}\n/**\n * Get the value for a attribute on a node. Only used in DEV for SSR validation.\n * The third argument is used as a hint of what the expected value is. Some\n * attributes have multiple equivalent values.\n */\n\nfunction getValueForAttribute(node, name, expected) {\n {\n if (!isAttributeNameSafe(name)) {\n return;\n }\n\n if (!node.hasAttribute(name)) {\n return expected === undefined ? undefined : null;\n }\n\n var value = node.getAttribute(name);\n\n if (value === '' + expected) {\n return expected;\n }\n\n return value;\n }\n}\n/**\n * Sets the value for a property on a node.\n *\n * @param {DOMElement} node\n * @param {string} name\n * @param {*} value\n */\n\nfunction setValueForProperty(node, name, value, isCustomComponentTag) {\n var propertyInfo = getPropertyInfo(name);\n\n if (shouldIgnoreAttribute(name, propertyInfo, isCustomComponentTag)) {\n return;\n }\n\n if (shouldRemoveAttribute(name, value, propertyInfo, isCustomComponentTag)) {\n value = null;\n } // If the prop isn't in the special list, treat it as a simple attribute.\n\n\n if (isCustomComponentTag || propertyInfo === null) {\n if (isAttributeNameSafe(name)) {\n var _attributeName = name;\n\n if (value === null) {\n node.removeAttribute(_attributeName);\n } else {\n node.setAttribute(_attributeName, '' + value);\n }\n }\n\n return;\n }\n\n var mustUseProperty = propertyInfo.mustUseProperty;\n\n if (mustUseProperty) {\n var propertyName = propertyInfo.propertyName;\n\n if (value === null) {\n var type = propertyInfo.type;\n node[propertyName] = type === BOOLEAN ? false : '';\n } else {\n // Contrary to `setAttribute`, object properties are properly\n // `toString`ed by IE8/9.\n node[propertyName] = value;\n }\n\n return;\n } // The rest are treated as attributes with special cases.\n\n\n var attributeName = propertyInfo.attributeName,\n attributeNamespace = propertyInfo.attributeNamespace;\n\n if (value === null) {\n node.removeAttribute(attributeName);\n } else {\n var _type = propertyInfo.type;\n var attributeValue;\n\n if (_type === BOOLEAN || _type === OVERLOADED_BOOLEAN && value === true) {\n // If attribute type is boolean, we know for sure it won't be an execution sink\n // and we won't require Trusted Type here.\n attributeValue = '';\n } else {\n // `setAttribute` with objects becomes only `[object]` in IE8/9,\n // ('' + value) makes it output the correct toString()-value.\n {\n attributeValue = '' + value;\n }\n\n if (propertyInfo.sanitizeURL) {\n sanitizeURL(attributeValue.toString());\n }\n }\n\n if (attributeNamespace) {\n node.setAttributeNS(attributeNamespace, attributeName, attributeValue);\n } else {\n node.setAttribute(attributeName, attributeValue);\n }\n }\n}\n\nvar BEFORE_SLASH_RE = /^(.*)[\\\\\\/]/;\nfunction describeComponentFrame (name, source, ownerName) {\n var sourceInfo = '';\n\n if (source) {\n var path = source.fileName;\n var fileName = path.replace(BEFORE_SLASH_RE, '');\n\n {\n // In DEV, include code for a common special case:\n // prefer \"folder/index.js\" instead of just \"index.js\".\n if (/^index\\./.test(fileName)) {\n var match = path.match(BEFORE_SLASH_RE);\n\n if (match) {\n var pathBeforeSlash = match[1];\n\n if (pathBeforeSlash) {\n var folderName = pathBeforeSlash.replace(BEFORE_SLASH_RE, '');\n fileName = folderName + '/' + fileName;\n }\n }\n }\n }\n\n sourceInfo = ' (at ' + fileName + ':' + source.lineNumber + ')';\n } else if (ownerName) {\n sourceInfo = ' (created by ' + ownerName + ')';\n }\n\n return '\\n in ' + (name || 'Unknown') + sourceInfo;\n}\n\n// The Symbol used to tag the ReactElement-like types. If there is no native Symbol\n// nor polyfill, then a plain number is used for performance.\nvar hasSymbol = typeof Symbol === 'function' && Symbol.for;\nvar REACT_ELEMENT_TYPE = hasSymbol ? Symbol.for('react.element') : 0xeac7;\nvar REACT_PORTAL_TYPE = hasSymbol ? Symbol.for('react.portal') : 0xeaca;\nvar REACT_FRAGMENT_TYPE = hasSymbol ? Symbol.for('react.fragment') : 0xeacb;\nvar REACT_STRICT_MODE_TYPE = hasSymbol ? Symbol.for('react.strict_mode') : 0xeacc;\nvar REACT_PROFILER_TYPE = hasSymbol ? Symbol.for('react.profiler') : 0xead2;\nvar REACT_PROVIDER_TYPE = hasSymbol ? Symbol.for('react.provider') : 0xeacd;\nvar REACT_CONTEXT_TYPE = hasSymbol ? Symbol.for('react.context') : 0xeace; // TODO: We don't use AsyncMode or ConcurrentMode anymore. They were temporary\nvar REACT_CONCURRENT_MODE_TYPE = hasSymbol ? Symbol.for('react.concurrent_mode') : 0xeacf;\nvar REACT_FORWARD_REF_TYPE = hasSymbol ? Symbol.for('react.forward_ref') : 0xead0;\nvar REACT_SUSPENSE_TYPE = hasSymbol ? Symbol.for('react.suspense') : 0xead1;\nvar REACT_SUSPENSE_LIST_TYPE = hasSymbol ? Symbol.for('react.suspense_list') : 0xead8;\nvar REACT_MEMO_TYPE = hasSymbol ? Symbol.for('react.memo') : 0xead3;\nvar REACT_LAZY_TYPE = hasSymbol ? Symbol.for('react.lazy') : 0xead4;\nvar REACT_BLOCK_TYPE = hasSymbol ? Symbol.for('react.block') : 0xead9;\nvar MAYBE_ITERATOR_SYMBOL = typeof Symbol === 'function' && Symbol.iterator;\nvar FAUX_ITERATOR_SYMBOL = '@@iterator';\nfunction getIteratorFn(maybeIterable) {\n if (maybeIterable === null || typeof maybeIterable !== 'object') {\n return null;\n }\n\n var maybeIterator = MAYBE_ITERATOR_SYMBOL && maybeIterable[MAYBE_ITERATOR_SYMBOL] || maybeIterable[FAUX_ITERATOR_SYMBOL];\n\n if (typeof maybeIterator === 'function') {\n return maybeIterator;\n }\n\n return null;\n}\n\nvar Uninitialized = -1;\nvar Pending = 0;\nvar Resolved = 1;\nvar Rejected = 2;\nfunction refineResolvedLazyComponent(lazyComponent) {\n return lazyComponent._status === Resolved ? lazyComponent._result : null;\n}\nfunction initializeLazyComponentType(lazyComponent) {\n if (lazyComponent._status === Uninitialized) {\n lazyComponent._status = Pending;\n var ctor = lazyComponent._ctor;\n var thenable = ctor();\n lazyComponent._result = thenable;\n thenable.then(function (moduleObject) {\n if (lazyComponent._status === Pending) {\n var defaultExport = moduleObject.default;\n\n {\n if (defaultExport === undefined) {\n error('lazy: Expected the result of a dynamic import() call. ' + 'Instead received: %s\\n\\nYour code should look like: \\n ' + \"const MyComponent = lazy(() => import('./MyComponent'))\", moduleObject);\n }\n }\n\n lazyComponent._status = Resolved;\n lazyComponent._result = defaultExport;\n }\n }, function (error) {\n if (lazyComponent._status === Pending) {\n lazyComponent._status = Rejected;\n lazyComponent._result = error;\n }\n });\n }\n}\n\nfunction getWrappedName(outerType, innerType, wrapperName) {\n var functionName = innerType.displayName || innerType.name || '';\n return outerType.displayName || (functionName !== '' ? wrapperName + \"(\" + functionName + \")\" : wrapperName);\n}\n\nfunction getComponentName(type) {\n if (type == null) {\n // Host root, text node or just invalid type.\n return null;\n }\n\n {\n if (typeof type.tag === 'number') {\n error('Received an unexpected object in getComponentName(). ' + 'This is likely a bug in React. Please file an issue.');\n }\n }\n\n if (typeof type === 'function') {\n return type.displayName || type.name || null;\n }\n\n if (typeof type === 'string') {\n return type;\n }\n\n switch (type) {\n case REACT_FRAGMENT_TYPE:\n return 'Fragment';\n\n case REACT_PORTAL_TYPE:\n return 'Portal';\n\n case REACT_PROFILER_TYPE:\n return \"Profiler\";\n\n case REACT_STRICT_MODE_TYPE:\n return 'StrictMode';\n\n case REACT_SUSPENSE_TYPE:\n return 'Suspense';\n\n case REACT_SUSPENSE_LIST_TYPE:\n return 'SuspenseList';\n }\n\n if (typeof type === 'object') {\n switch (type.$$typeof) {\n case REACT_CONTEXT_TYPE:\n return 'Context.Consumer';\n\n case REACT_PROVIDER_TYPE:\n return 'Context.Provider';\n\n case REACT_FORWARD_REF_TYPE:\n return getWrappedName(type, type.render, 'ForwardRef');\n\n case REACT_MEMO_TYPE:\n return getComponentName(type.type);\n\n case REACT_BLOCK_TYPE:\n return getComponentName(type.render);\n\n case REACT_LAZY_TYPE:\n {\n var thenable = type;\n var resolvedThenable = refineResolvedLazyComponent(thenable);\n\n if (resolvedThenable) {\n return getComponentName(resolvedThenable);\n }\n\n break;\n }\n }\n }\n\n return null;\n}\n\nvar ReactDebugCurrentFrame$1 = ReactSharedInternals.ReactDebugCurrentFrame;\n\nfunction describeFiber(fiber) {\n switch (fiber.tag) {\n case HostRoot:\n case HostPortal:\n case HostText:\n case Fragment:\n case ContextProvider:\n case ContextConsumer:\n return '';\n\n default:\n var owner = fiber._debugOwner;\n var source = fiber._debugSource;\n var name = getComponentName(fiber.type);\n var ownerName = null;\n\n if (owner) {\n ownerName = getComponentName(owner.type);\n }\n\n return describeComponentFrame(name, source, ownerName);\n }\n}\n\nfunction getStackByFiberInDevAndProd(workInProgress) {\n var info = '';\n var node = workInProgress;\n\n do {\n info += describeFiber(node);\n node = node.return;\n } while (node);\n\n return info;\n}\nvar current = null;\nvar isRendering = false;\nfunction getCurrentFiberOwnerNameInDevOrNull() {\n {\n if (current === null) {\n return null;\n }\n\n var owner = current._debugOwner;\n\n if (owner !== null && typeof owner !== 'undefined') {\n return getComponentName(owner.type);\n }\n }\n\n return null;\n}\nfunction getCurrentFiberStackInDev() {\n {\n if (current === null) {\n return '';\n } // Safe because if current fiber exists, we are reconciling,\n // and it is guaranteed to be the work-in-progress version.\n\n\n return getStackByFiberInDevAndProd(current);\n }\n}\nfunction resetCurrentFiber() {\n {\n ReactDebugCurrentFrame$1.getCurrentStack = null;\n current = null;\n isRendering = false;\n }\n}\nfunction setCurrentFiber(fiber) {\n {\n ReactDebugCurrentFrame$1.getCurrentStack = getCurrentFiberStackInDev;\n current = fiber;\n isRendering = false;\n }\n}\nfunction setIsRendering(rendering) {\n {\n isRendering = rendering;\n }\n}\n\n// Flow does not allow string concatenation of most non-string types. To work\n// around this limitation, we use an opaque type that can only be obtained by\n// passing the value through getToStringValue first.\nfunction toString(value) {\n return '' + value;\n}\nfunction getToStringValue(value) {\n switch (typeof value) {\n case 'boolean':\n case 'number':\n case 'object':\n case 'string':\n case 'undefined':\n return value;\n\n default:\n // function, symbol are assigned as empty strings\n return '';\n }\n}\n\nvar ReactDebugCurrentFrame$2 = null;\nvar ReactControlledValuePropTypes = {\n checkPropTypes: null\n};\n\n{\n ReactDebugCurrentFrame$2 = ReactSharedInternals.ReactDebugCurrentFrame;\n var hasReadOnlyValue = {\n button: true,\n checkbox: true,\n image: true,\n hidden: true,\n radio: true,\n reset: true,\n submit: true\n };\n var propTypes = {\n value: function (props, propName, componentName) {\n if (hasReadOnlyValue[props.type] || props.onChange || props.readOnly || props.disabled || props[propName] == null || enableDeprecatedFlareAPI ) {\n return null;\n }\n\n return new Error('You provided a `value` prop to a form field without an ' + '`onChange` handler. This will render a read-only field. If ' + 'the field should be mutable use `defaultValue`. Otherwise, ' + 'set either `onChange` or `readOnly`.');\n },\n checked: function (props, propName, componentName) {\n if (props.onChange || props.readOnly || props.disabled || props[propName] == null || enableDeprecatedFlareAPI ) {\n return null;\n }\n\n return new Error('You provided a `checked` prop to a form field without an ' + '`onChange` handler. This will render a read-only field. If ' + 'the field should be mutable use `defaultChecked`. Otherwise, ' + 'set either `onChange` or `readOnly`.');\n }\n };\n /**\n * Provide a linked `value` attribute for controlled forms. You should not use\n * this outside of the ReactDOM controlled form components.\n */\n\n ReactControlledValuePropTypes.checkPropTypes = function (tagName, props) {\n checkPropTypes(propTypes, props, 'prop', tagName, ReactDebugCurrentFrame$2.getStackAddendum);\n };\n}\n\nfunction isCheckable(elem) {\n var type = elem.type;\n var nodeName = elem.nodeName;\n return nodeName && nodeName.toLowerCase() === 'input' && (type === 'checkbox' || type === 'radio');\n}\n\nfunction getTracker(node) {\n return node._valueTracker;\n}\n\nfunction detachTracker(node) {\n node._valueTracker = null;\n}\n\nfunction getValueFromNode(node) {\n var value = '';\n\n if (!node) {\n return value;\n }\n\n if (isCheckable(node)) {\n value = node.checked ? 'true' : 'false';\n } else {\n value = node.value;\n }\n\n return value;\n}\n\nfunction trackValueOnNode(node) {\n var valueField = isCheckable(node) ? 'checked' : 'value';\n var descriptor = Object.getOwnPropertyDescriptor(node.constructor.prototype, valueField);\n var currentValue = '' + node[valueField]; // if someone has already defined a value or Safari, then bail\n // and don't track value will cause over reporting of changes,\n // but it's better then a hard failure\n // (needed for certain tests that spyOn input values and Safari)\n\n if (node.hasOwnProperty(valueField) || typeof descriptor === 'undefined' || typeof descriptor.get !== 'function' || typeof descriptor.set !== 'function') {\n return;\n }\n\n var get = descriptor.get,\n set = descriptor.set;\n Object.defineProperty(node, valueField, {\n configurable: true,\n get: function () {\n return get.call(this);\n },\n set: function (value) {\n currentValue = '' + value;\n set.call(this, value);\n }\n }); // We could've passed this the first time\n // but it triggers a bug in IE11 and Edge 14/15.\n // Calling defineProperty() again should be equivalent.\n // https://github.com/facebook/react/issues/11768\n\n Object.defineProperty(node, valueField, {\n enumerable: descriptor.enumerable\n });\n var tracker = {\n getValue: function () {\n return currentValue;\n },\n setValue: function (value) {\n currentValue = '' + value;\n },\n stopTracking: function () {\n detachTracker(node);\n delete node[valueField];\n }\n };\n return tracker;\n}\n\nfunction track(node) {\n if (getTracker(node)) {\n return;\n } // TODO: Once it's just Fiber we can move this to node._wrapperState\n\n\n node._valueTracker = trackValueOnNode(node);\n}\nfunction updateValueIfChanged(node) {\n if (!node) {\n return false;\n }\n\n var tracker = getTracker(node); // if there is no tracker at this point it's unlikely\n // that trying again will succeed\n\n if (!tracker) {\n return true;\n }\n\n var lastValue = tracker.getValue();\n var nextValue = getValueFromNode(node);\n\n if (nextValue !== lastValue) {\n tracker.setValue(nextValue);\n return true;\n }\n\n return false;\n}\n\nvar didWarnValueDefaultValue = false;\nvar didWarnCheckedDefaultChecked = false;\nvar didWarnControlledToUncontrolled = false;\nvar didWarnUncontrolledToControlled = false;\n\nfunction isControlled(props) {\n var usesChecked = props.type === 'checkbox' || props.type === 'radio';\n return usesChecked ? props.checked != null : props.value != null;\n}\n/**\n * Implements an <input> host component that allows setting these optional\n * props: `checked`, `value`, `defaultChecked`, and `defaultValue`.\n *\n * If `checked` or `value` are not supplied (or null/undefined), user actions\n * that affect the checked state or value will trigger updates to the element.\n *\n * If they are supplied (and not null/undefined), the rendered element will not\n * trigger updates to the element. Instead, the props must change in order for\n * the rendered element to be updated.\n *\n * The rendered element will be initialized as unchecked (or `defaultChecked`)\n * with an empty value (or `defaultValue`).\n *\n * See http://www.w3.org/TR/2012/WD-html5-20121025/the-input-element.html\n */\n\n\nfunction getHostProps(element, props) {\n var node = element;\n var checked = props.checked;\n\n var hostProps = _assign({}, props, {\n defaultChecked: undefined,\n defaultValue: undefined,\n value: undefined,\n checked: checked != null ? checked : node._wrapperState.initialChecked\n });\n\n return hostProps;\n}\nfunction initWrapperState(element, props) {\n {\n ReactControlledValuePropTypes.checkPropTypes('input', props);\n\n if (props.checked !== undefined && props.defaultChecked !== undefined && !didWarnCheckedDefaultChecked) {\n error('%s contains an input of type %s with both checked and defaultChecked props. ' + 'Input elements must be either controlled or uncontrolled ' + '(specify either the checked prop, or the defaultChecked prop, but not ' + 'both). Decide between using a controlled or uncontrolled input ' + 'element and remove one of these props. More info: ' + 'https://fb.me/react-controlled-components', getCurrentFiberOwnerNameInDevOrNull() || 'A component', props.type);\n\n didWarnCheckedDefaultChecked = true;\n }\n\n if (props.value !== undefined && props.defaultValue !== undefined && !didWarnValueDefaultValue) {\n error('%s contains an input of type %s with both value and defaultValue props. ' + 'Input elements must be either controlled or uncontrolled ' + '(specify either the value prop, or the defaultValue prop, but not ' + 'both). Decide between using a controlled or uncontrolled input ' + 'element and remove one of these props. More info: ' + 'https://fb.me/react-controlled-components', getCurrentFiberOwnerNameInDevOrNull() || 'A component', props.type);\n\n didWarnValueDefaultValue = true;\n }\n }\n\n var node = element;\n var defaultValue = props.defaultValue == null ? '' : props.defaultValue;\n node._wrapperState = {\n initialChecked: props.checked != null ? props.checked : props.defaultChecked,\n initialValue: getToStringValue(props.value != null ? props.value : defaultValue),\n controlled: isControlled(props)\n };\n}\nfunction updateChecked(element, props) {\n var node = element;\n var checked = props.checked;\n\n if (checked != null) {\n setValueForProperty(node, 'checked', checked, false);\n }\n}\nfunction updateWrapper(element, props) {\n var node = element;\n\n {\n var controlled = isControlled(props);\n\n if (!node._wrapperState.controlled && controlled && !didWarnUncontrolledToControlled) {\n error('A component is changing an uncontrolled input of type %s to be controlled. ' + 'Input elements should not switch from uncontrolled to controlled (or vice versa). ' + 'Decide between using a controlled or uncontrolled input ' + 'element for the lifetime of the component. More info: https://fb.me/react-controlled-components', props.type);\n\n didWarnUncontrolledToControlled = true;\n }\n\n if (node._wrapperState.controlled && !controlled && !didWarnControlledToUncontrolled) {\n error('A component is changing a controlled input of type %s to be uncontrolled. ' + 'Input elements should not switch from controlled to uncontrolled (or vice versa). ' + 'Decide between using a controlled or uncontrolled input ' + 'element for the lifetime of the component. More info: https://fb.me/react-controlled-components', props.type);\n\n didWarnControlledToUncontrolled = true;\n }\n }\n\n updateChecked(element, props);\n var value = getToStringValue(props.value);\n var type = props.type;\n\n if (value != null) {\n if (type === 'number') {\n if (value === 0 && node.value === '' || // We explicitly want to coerce to number here if possible.\n // eslint-disable-next-line\n node.value != value) {\n node.value = toString(value);\n }\n } else if (node.value !== toString(value)) {\n node.value = toString(value);\n }\n } else if (type === 'submit' || type === 'reset') {\n // Submit/reset inputs need the attribute removed completely to avoid\n // blank-text buttons.\n node.removeAttribute('value');\n return;\n }\n\n {\n // When syncing the value attribute, the value comes from a cascade of\n // properties:\n // 1. The value React property\n // 2. The defaultValue React property\n // 3. Otherwise there should be no change\n if (props.hasOwnProperty('value')) {\n setDefaultValue(node, props.type, value);\n } else if (props.hasOwnProperty('defaultValue')) {\n setDefaultValue(node, props.type, getToStringValue(props.defaultValue));\n }\n }\n\n {\n // When syncing the checked attribute, it only changes when it needs\n // to be removed, such as transitioning from a checkbox into a text input\n if (props.checked == null && props.defaultChecked != null) {\n node.defaultChecked = !!props.defaultChecked;\n }\n }\n}\nfunction postMountWrapper(element, props, isHydrating) {\n var node = element; // Do not assign value if it is already set. This prevents user text input\n // from being lost during SSR hydration.\n\n if (props.hasOwnProperty('value') || props.hasOwnProperty('defaultValue')) {\n var type = props.type;\n var isButton = type === 'submit' || type === 'reset'; // Avoid setting value attribute on submit/reset inputs as it overrides the\n // default value provided by the browser. See: #12872\n\n if (isButton && (props.value === undefined || props.value === null)) {\n return;\n }\n\n var initialValue = toString(node._wrapperState.initialValue); // Do not assign value if it is already set. This prevents user text input\n // from being lost during SSR hydration.\n\n if (!isHydrating) {\n {\n // When syncing the value attribute, the value property should use\n // the wrapperState._initialValue property. This uses:\n //\n // 1. The value React property when present\n // 2. The defaultValue React property when present\n // 3. An empty string\n if (initialValue !== node.value) {\n node.value = initialValue;\n }\n }\n }\n\n {\n // Otherwise, the value attribute is synchronized to the property,\n // so we assign defaultValue to the same thing as the value property\n // assignment step above.\n node.defaultValue = initialValue;\n }\n } // Normally, we'd just do `node.checked = node.checked` upon initial mount, less this bug\n // this is needed to work around a chrome bug where setting defaultChecked\n // will sometimes influence the value of checked (even after detachment).\n // Reference: https://bugs.chromium.org/p/chromium/issues/detail?id=608416\n // We need to temporarily unset name to avoid disrupting radio button groups.\n\n\n var name = node.name;\n\n if (name !== '') {\n node.name = '';\n }\n\n {\n // When syncing the checked attribute, both the checked property and\n // attribute are assigned at the same time using defaultChecked. This uses:\n //\n // 1. The checked React property when present\n // 2. The defaultChecked React property when present\n // 3. Otherwise, false\n node.defaultChecked = !node.defaultChecked;\n node.defaultChecked = !!node._wrapperState.initialChecked;\n }\n\n if (name !== '') {\n node.name = name;\n }\n}\nfunction restoreControlledState(element, props) {\n var node = element;\n updateWrapper(node, props);\n updateNamedCousins(node, props);\n}\n\nfunction updateNamedCousins(rootNode, props) {\n var name = props.name;\n\n if (props.type === 'radio' && name != null) {\n var queryRoot = rootNode;\n\n while (queryRoot.parentNode) {\n queryRoot = queryRoot.parentNode;\n } // If `rootNode.form` was non-null, then we could try `form.elements`,\n // but that sometimes behaves strangely in IE8. We could also try using\n // `form.getElementsByName`, but that will only return direct children\n // and won't include inputs that use the HTML5 `form=` attribute. Since\n // the input might not even be in a form. It might not even be in the\n // document. Let's just use the local `querySelectorAll` to ensure we don't\n // miss anything.\n\n\n var group = queryRoot.querySelectorAll('input[name=' + JSON.stringify('' + name) + '][type=\"radio\"]');\n\n for (var i = 0; i < group.length; i++) {\n var otherNode = group[i];\n\n if (otherNode === rootNode || otherNode.form !== rootNode.form) {\n continue;\n } // This will throw if radio buttons rendered by different copies of React\n // and the same name are rendered into the same form (same as #1939).\n // That's probably okay; we don't support it just as we don't support\n // mixing React radio buttons with non-React ones.\n\n\n var otherProps = getFiberCurrentPropsFromNode$1(otherNode);\n\n if (!otherProps) {\n {\n throw Error( \"ReactDOMInput: Mixing React and non-React radio inputs with the same `name` is not supported.\" );\n }\n } // We need update the tracked value on the named cousin since the value\n // was changed but the input saw no event or value set\n\n\n updateValueIfChanged(otherNode); // If this is a controlled radio button group, forcing the input that\n // was previously checked to update will cause it to be come re-checked\n // as appropriate.\n\n updateWrapper(otherNode, otherProps);\n }\n }\n} // In Chrome, assigning defaultValue to certain input types triggers input validation.\n// For number inputs, the display value loses trailing decimal points. For email inputs,\n// Chrome raises \"The specified value <x> is not a valid email address\".\n//\n// Here we check to see if the defaultValue has actually changed, avoiding these problems\n// when the user is inputting text\n//\n// https://github.com/facebook/react/issues/7253\n\n\nfunction setDefaultValue(node, type, value) {\n if ( // Focused number inputs synchronize on blur. See ChangeEventPlugin.js\n type !== 'number' || node.ownerDocument.activeElement !== node) {\n if (value == null) {\n node.defaultValue = toString(node._wrapperState.initialValue);\n } else if (node.defaultValue !== toString(value)) {\n node.defaultValue = toString(value);\n }\n }\n}\n\nvar didWarnSelectedSetOnOption = false;\nvar didWarnInvalidChild = false;\n\nfunction flattenChildren(children) {\n var content = ''; // Flatten children. We'll warn if they are invalid\n // during validateProps() which runs for hydration too.\n // Note that this would throw on non-element objects.\n // Elements are stringified (which is normally irrelevant\n // but matters for <fbt>).\n\n React.Children.forEach(children, function (child) {\n if (child == null) {\n return;\n }\n\n content += child; // Note: we don't warn about invalid children here.\n // Instead, this is done separately below so that\n // it happens during the hydration codepath too.\n });\n return content;\n}\n/**\n * Implements an <option> host component that warns when `selected` is set.\n */\n\n\nfunction validateProps(element, props) {\n {\n // This mirrors the codepath above, but runs for hydration too.\n // Warn about invalid children here so that client and hydration are consistent.\n // TODO: this seems like it could cause a DEV-only throw for hydration\n // if children contains a non-element object. We should try to avoid that.\n if (typeof props.children === 'object' && props.children !== null) {\n React.Children.forEach(props.children, function (child) {\n if (child == null) {\n return;\n }\n\n if (typeof child === 'string' || typeof child === 'number') {\n return;\n }\n\n if (typeof child.type !== 'string') {\n return;\n }\n\n if (!didWarnInvalidChild) {\n didWarnInvalidChild = true;\n\n error('Only strings and numbers are supported as <option> children.');\n }\n });\n } // TODO: Remove support for `selected` in <option>.\n\n\n if (props.selected != null && !didWarnSelectedSetOnOption) {\n error('Use the `defaultValue` or `value` props on <select> instead of ' + 'setting `selected` on <option>.');\n\n didWarnSelectedSetOnOption = true;\n }\n }\n}\nfunction postMountWrapper$1(element, props) {\n // value=\"\" should make a value attribute (#6219)\n if (props.value != null) {\n element.setAttribute('value', toString(getToStringValue(props.value)));\n }\n}\nfunction getHostProps$1(element, props) {\n var hostProps = _assign({\n children: undefined\n }, props);\n\n var content = flattenChildren(props.children);\n\n if (content) {\n hostProps.children = content;\n }\n\n return hostProps;\n}\n\nvar didWarnValueDefaultValue$1;\n\n{\n didWarnValueDefaultValue$1 = false;\n}\n\nfunction getDeclarationErrorAddendum() {\n var ownerName = getCurrentFiberOwnerNameInDevOrNull();\n\n if (ownerName) {\n return '\\n\\nCheck the render method of `' + ownerName + '`.';\n }\n\n return '';\n}\n\nvar valuePropNames = ['value', 'defaultValue'];\n/**\n * Validation function for `value` and `defaultValue`.\n */\n\nfunction checkSelectPropTypes(props) {\n {\n ReactControlledValuePropTypes.checkPropTypes('select', props);\n\n for (var i = 0; i < valuePropNames.length; i++) {\n var propName = valuePropNames[i];\n\n if (props[propName] == null) {\n continue;\n }\n\n var isArray = Array.isArray(props[propName]);\n\n if (props.multiple && !isArray) {\n error('The `%s` prop supplied to <select> must be an array if ' + '`multiple` is true.%s', propName, getDeclarationErrorAddendum());\n } else if (!props.multiple && isArray) {\n error('The `%s` prop supplied to <select> must be a scalar ' + 'value if `multiple` is false.%s', propName, getDeclarationErrorAddendum());\n }\n }\n }\n}\n\nfunction updateOptions(node, multiple, propValue, setDefaultSelected) {\n var options = node.options;\n\n if (multiple) {\n var selectedValues = propValue;\n var selectedValue = {};\n\n for (var i = 0; i < selectedValues.length; i++) {\n // Prefix to avoid chaos with special keys.\n selectedValue['$' + selectedValues[i]] = true;\n }\n\n for (var _i = 0; _i < options.length; _i++) {\n var selected = selectedValue.hasOwnProperty('$' + options[_i].value);\n\n if (options[_i].selected !== selected) {\n options[_i].selected = selected;\n }\n\n if (selected && setDefaultSelected) {\n options[_i].defaultSelected = true;\n }\n }\n } else {\n // Do not set `select.value` as exact behavior isn't consistent across all\n // browsers for all cases.\n var _selectedValue = toString(getToStringValue(propValue));\n\n var defaultSelected = null;\n\n for (var _i2 = 0; _i2 < options.length; _i2++) {\n if (options[_i2].value === _selectedValue) {\n options[_i2].selected = true;\n\n if (setDefaultSelected) {\n options[_i2].defaultSelected = true;\n }\n\n return;\n }\n\n if (defaultSelected === null && !options[_i2].disabled) {\n defaultSelected = options[_i2];\n }\n }\n\n if (defaultSelected !== null) {\n defaultSelected.selected = true;\n }\n }\n}\n/**\n * Implements a <select> host component that allows optionally setting the\n * props `value` and `defaultValue`. If `multiple` is false, the prop must be a\n * stringable. If `multiple` is true, the prop must be an array of stringables.\n *\n * If `value` is not supplied (or null/undefined), user actions that change the\n * selected option will trigger updates to the rendered options.\n *\n * If it is supplied (and not null/undefined), the rendered options will not\n * update in response to user actions. Instead, the `value` prop must change in\n * order for the rendered options to update.\n *\n * If `defaultValue` is provided, any options with the supplied values will be\n * selected.\n */\n\n\nfunction getHostProps$2(element, props) {\n return _assign({}, props, {\n value: undefined\n });\n}\nfunction initWrapperState$1(element, props) {\n var node = element;\n\n {\n checkSelectPropTypes(props);\n }\n\n node._wrapperState = {\n wasMultiple: !!props.multiple\n };\n\n {\n if (props.value !== undefined && props.defaultValue !== undefined && !didWarnValueDefaultValue$1) {\n error('Select elements must be either controlled or uncontrolled ' + '(specify either the value prop, or the defaultValue prop, but not ' + 'both). Decide between using a controlled or uncontrolled select ' + 'element and remove one of these props. More info: ' + 'https://fb.me/react-controlled-components');\n\n didWarnValueDefaultValue$1 = true;\n }\n }\n}\nfunction postMountWrapper$2(element, props) {\n var node = element;\n node.multiple = !!props.multiple;\n var value = props.value;\n\n if (value != null) {\n updateOptions(node, !!props.multiple, value, false);\n } else if (props.defaultValue != null) {\n updateOptions(node, !!props.multiple, props.defaultValue, true);\n }\n}\nfunction postUpdateWrapper(element, props) {\n var node = element;\n var wasMultiple = node._wrapperState.wasMultiple;\n node._wrapperState.wasMultiple = !!props.multiple;\n var value = props.value;\n\n if (value != null) {\n updateOptions(node, !!props.multiple, value, false);\n } else if (wasMultiple !== !!props.multiple) {\n // For simplicity, reapply `defaultValue` if `multiple` is toggled.\n if (props.defaultValue != null) {\n updateOptions(node, !!props.multiple, props.defaultValue, true);\n } else {\n // Revert the select back to its default unselected state.\n updateOptions(node, !!props.multiple, props.multiple ? [] : '', false);\n }\n }\n}\nfunction restoreControlledState$1(element, props) {\n var node = element;\n var value = props.value;\n\n if (value != null) {\n updateOptions(node, !!props.multiple, value, false);\n }\n}\n\nvar didWarnValDefaultVal = false;\n\n/**\n * Implements a <textarea> host component that allows setting `value`, and\n * `defaultValue`. This differs from the traditional DOM API because value is\n * usually set as PCDATA children.\n *\n * If `value` is not supplied (or null/undefined), user actions that affect the\n * value will trigger updates to the element.\n *\n * If `value` is supplied (and not null/undefined), the rendered element will\n * not trigger updates to the element. Instead, the `value` prop must change in\n * order for the rendered element to be updated.\n *\n * The rendered element will be initialized with an empty value, the prop\n * `defaultValue` if specified, or the children content (deprecated).\n */\nfunction getHostProps$3(element, props) {\n var node = element;\n\n if (!(props.dangerouslySetInnerHTML == null)) {\n {\n throw Error( \"`dangerouslySetInnerHTML` does not make sense on <textarea>.\" );\n }\n } // Always set children to the same thing. In IE9, the selection range will\n // get reset if `textContent` is mutated. We could add a check in setTextContent\n // to only set the value if/when the value differs from the node value (which would\n // completely solve this IE9 bug), but Sebastian+Sophie seemed to like this\n // solution. The value can be a boolean or object so that's why it's forced\n // to be a string.\n\n\n var hostProps = _assign({}, props, {\n value: undefined,\n defaultValue: undefined,\n children: toString(node._wrapperState.initialValue)\n });\n\n return hostProps;\n}\nfunction initWrapperState$2(element, props) {\n var node = element;\n\n {\n ReactControlledValuePropTypes.checkPropTypes('textarea', props);\n\n if (props.value !== undefined && props.defaultValue !== undefined && !didWarnValDefaultVal) {\n error('%s contains a textarea with both value and defaultValue props. ' + 'Textarea elements must be either controlled or uncontrolled ' + '(specify either the value prop, or the defaultValue prop, but not ' + 'both). Decide between using a controlled or uncontrolled textarea ' + 'and remove one of these props. More info: ' + 'https://fb.me/react-controlled-components', getCurrentFiberOwnerNameInDevOrNull() || 'A component');\n\n didWarnValDefaultVal = true;\n }\n }\n\n var initialValue = props.value; // Only bother fetching default value if we're going to use it\n\n if (initialValue == null) {\n var children = props.children,\n defaultValue = props.defaultValue;\n\n if (children != null) {\n {\n error('Use the `defaultValue` or `value` props instead of setting ' + 'children on <textarea>.');\n }\n\n {\n if (!(defaultValue == null)) {\n {\n throw Error( \"If you supply `defaultValue` on a <textarea>, do not pass children.\" );\n }\n }\n\n if (Array.isArray(children)) {\n if (!(children.length <= 1)) {\n {\n throw Error( \"<textarea> can only have at most one child.\" );\n }\n }\n\n children = children[0];\n }\n\n defaultValue = children;\n }\n }\n\n if (defaultValue == null) {\n defaultValue = '';\n }\n\n initialValue = defaultValue;\n }\n\n node._wrapperState = {\n initialValue: getToStringValue(initialValue)\n };\n}\nfunction updateWrapper$1(element, props) {\n var node = element;\n var value = getToStringValue(props.value);\n var defaultValue = getToStringValue(props.defaultValue);\n\n if (value != null) {\n // Cast `value` to a string to ensure the value is set correctly. While\n // browsers typically do this as necessary, jsdom doesn't.\n var newValue = toString(value); // To avoid side effects (such as losing text selection), only set value if changed\n\n if (newValue !== node.value) {\n node.value = newValue;\n }\n\n if (props.defaultValue == null && node.defaultValue !== newValue) {\n node.defaultValue = newValue;\n }\n }\n\n if (defaultValue != null) {\n node.defaultValue = toString(defaultValue);\n }\n}\nfunction postMountWrapper$3(element, props) {\n var node = element; // This is in postMount because we need access to the DOM node, which is not\n // available until after the component has mounted.\n\n var textContent = node.textContent; // Only set node.value if textContent is equal to the expected\n // initial value. In IE10/IE11 there is a bug where the placeholder attribute\n // will populate textContent as well.\n // https://developer.microsoft.com/microsoft-edge/platform/issues/101525/\n\n if (textContent === node._wrapperState.initialValue) {\n if (textContent !== '' && textContent !== null) {\n node.value = textContent;\n }\n }\n}\nfunction restoreControlledState$2(element, props) {\n // DOM component is still mounted; update\n updateWrapper$1(element, props);\n}\n\nvar HTML_NAMESPACE = 'http://www.w3.org/1999/xhtml';\nvar MATH_NAMESPACE = 'http://www.w3.org/1998/Math/MathML';\nvar SVG_NAMESPACE = 'http://www.w3.org/2000/svg';\nvar Namespaces = {\n html: HTML_NAMESPACE,\n mathml: MATH_NAMESPACE,\n svg: SVG_NAMESPACE\n}; // Assumes there is no parent namespace.\n\nfunction getIntrinsicNamespace(type) {\n switch (type) {\n case 'svg':\n return SVG_NAMESPACE;\n\n case 'math':\n return MATH_NAMESPACE;\n\n default:\n return HTML_NAMESPACE;\n }\n}\nfunction getChildNamespace(parentNamespace, type) {\n if (parentNamespace == null || parentNamespace === HTML_NAMESPACE) {\n // No (or default) parent namespace: potential entry point.\n return getIntrinsicNamespace(type);\n }\n\n if (parentNamespace === SVG_NAMESPACE && type === 'foreignObject') {\n // We're leaving SVG.\n return HTML_NAMESPACE;\n } // By default, pass namespace below.\n\n\n return parentNamespace;\n}\n\n/* globals MSApp */\n\n/**\n * Create a function which has 'unsafe' privileges (required by windows8 apps)\n */\nvar createMicrosoftUnsafeLocalFunction = function (func) {\n if (typeof MSApp !== 'undefined' && MSApp.execUnsafeLocalFunction) {\n return function (arg0, arg1, arg2, arg3) {\n MSApp.execUnsafeLocalFunction(function () {\n return func(arg0, arg1, arg2, arg3);\n });\n };\n } else {\n return func;\n }\n};\n\nvar reusableSVGContainer;\n/**\n * Set the innerHTML property of a node\n *\n * @param {DOMElement} node\n * @param {string} html\n * @internal\n */\n\nvar setInnerHTML = createMicrosoftUnsafeLocalFunction(function (node, html) {\n if (node.namespaceURI === Namespaces.svg) {\n\n if (!('innerHTML' in node)) {\n // IE does not have innerHTML for SVG nodes, so instead we inject the\n // new markup in a temp node and then move the child nodes across into\n // the target node\n reusableSVGContainer = reusableSVGContainer || document.createElement('div');\n reusableSVGContainer.innerHTML = '<svg>' + html.valueOf().toString() + '</svg>';\n var svgNode = reusableSVGContainer.firstChild;\n\n while (node.firstChild) {\n node.removeChild(node.firstChild);\n }\n\n while (svgNode.firstChild) {\n node.appendChild(svgNode.firstChild);\n }\n\n return;\n }\n }\n\n node.innerHTML = html;\n});\n\n/**\n * HTML nodeType values that represent the type of the node\n */\nvar ELEMENT_NODE = 1;\nvar TEXT_NODE = 3;\nvar COMMENT_NODE = 8;\nvar DOCUMENT_NODE = 9;\nvar DOCUMENT_FRAGMENT_NODE = 11;\n\n/**\n * Set the textContent property of a node. For text updates, it's faster\n * to set the `nodeValue` of the Text node directly instead of using\n * `.textContent` which will remove the existing node and create a new one.\n *\n * @param {DOMElement} node\n * @param {string} text\n * @internal\n */\n\nvar setTextContent = function (node, text) {\n if (text) {\n var firstChild = node.firstChild;\n\n if (firstChild && firstChild === node.lastChild && firstChild.nodeType === TEXT_NODE) {\n firstChild.nodeValue = text;\n return;\n }\n }\n\n node.textContent = text;\n};\n\n// Do not use the below two methods directly!\n// Instead use constants exported from DOMTopLevelEventTypes in ReactDOM.\n// (It is the only module that is allowed to access these methods.)\nfunction unsafeCastStringToDOMTopLevelType(topLevelType) {\n return topLevelType;\n}\nfunction unsafeCastDOMTopLevelTypeToString(topLevelType) {\n return topLevelType;\n}\n\n/**\n * Generate a mapping of standard vendor prefixes using the defined style property and event name.\n *\n * @param {string} styleProp\n * @param {string} eventName\n * @returns {object}\n */\n\nfunction makePrefixMap(styleProp, eventName) {\n var prefixes = {};\n prefixes[styleProp.toLowerCase()] = eventName.toLowerCase();\n prefixes['Webkit' + styleProp] = 'webkit' + eventName;\n prefixes['Moz' + styleProp] = 'moz' + eventName;\n return prefixes;\n}\n/**\n * A list of event names to a configurable list of vendor prefixes.\n */\n\n\nvar vendorPrefixes = {\n animationend: makePrefixMap('Animation', 'AnimationEnd'),\n animationiteration: makePrefixMap('Animation', 'AnimationIteration'),\n animationstart: makePrefixMap('Animation', 'AnimationStart'),\n transitionend: makePrefixMap('Transition', 'TransitionEnd')\n};\n/**\n * Event names that have already been detected and prefixed (if applicable).\n */\n\nvar prefixedEventNames = {};\n/**\n * Element to check for prefixes on.\n */\n\nvar style = {};\n/**\n * Bootstrap if a DOM exists.\n */\n\nif (canUseDOM) {\n style = document.createElement('div').style; // On some platforms, in particular some releases of Android 4.x,\n // the un-prefixed \"animation\" and \"transition\" properties are defined on the\n // style object but the events that fire will still be prefixed, so we need\n // to check if the un-prefixed events are usable, and if not remove them from the map.\n\n if (!('AnimationEvent' in window)) {\n delete vendorPrefixes.animationend.animation;\n delete vendorPrefixes.animationiteration.animation;\n delete vendorPrefixes.animationstart.animation;\n } // Same as above\n\n\n if (!('TransitionEvent' in window)) {\n delete vendorPrefixes.transitionend.transition;\n }\n}\n/**\n * Attempts to determine the correct vendor prefixed event name.\n *\n * @param {string} eventName\n * @returns {string}\n */\n\n\nfunction getVendorPrefixedEventName(eventName) {\n if (prefixedEventNames[eventName]) {\n return prefixedEventNames[eventName];\n } else if (!vendorPrefixes[eventName]) {\n return eventName;\n }\n\n var prefixMap = vendorPrefixes[eventName];\n\n for (var styleProp in prefixMap) {\n if (prefixMap.hasOwnProperty(styleProp) && styleProp in style) {\n return prefixedEventNames[eventName] = prefixMap[styleProp];\n }\n }\n\n return eventName;\n}\n\n/**\n * To identify top level events in ReactDOM, we use constants defined by this\n * module. This is the only module that uses the unsafe* methods to express\n * that the constants actually correspond to the browser event names. This lets\n * us save some bundle size by avoiding a top level type -> event name map.\n * The rest of ReactDOM code should import top level types from this file.\n */\n\nvar TOP_ABORT = unsafeCastStringToDOMTopLevelType('abort');\nvar TOP_ANIMATION_END = unsafeCastStringToDOMTopLevelType(getVendorPrefixedEventName('animationend'));\nvar TOP_ANIMATION_ITERATION = unsafeCastStringToDOMTopLevelType(getVendorPrefixedEventName('animationiteration'));\nvar TOP_ANIMATION_START = unsafeCastStringToDOMTopLevelType(getVendorPrefixedEventName('animationstart'));\nvar TOP_BLUR = unsafeCastStringToDOMTopLevelType('blur');\nvar TOP_CAN_PLAY = unsafeCastStringToDOMTopLevelType('canplay');\nvar TOP_CAN_PLAY_THROUGH = unsafeCastStringToDOMTopLevelType('canplaythrough');\nvar TOP_CANCEL = unsafeCastStringToDOMTopLevelType('cancel');\nvar TOP_CHANGE = unsafeCastStringToDOMTopLevelType('change');\nvar TOP_CLICK = unsafeCastStringToDOMTopLevelType('click');\nvar TOP_CLOSE = unsafeCastStringToDOMTopLevelType('close');\nvar TOP_COMPOSITION_END = unsafeCastStringToDOMTopLevelType('compositionend');\nvar TOP_COMPOSITION_START = unsafeCastStringToDOMTopLevelType('compositionstart');\nvar TOP_COMPOSITION_UPDATE = unsafeCastStringToDOMTopLevelType('compositionupdate');\nvar TOP_CONTEXT_MENU = unsafeCastStringToDOMTopLevelType('contextmenu');\nvar TOP_COPY = unsafeCastStringToDOMTopLevelType('copy');\nvar TOP_CUT = unsafeCastStringToDOMTopLevelType('cut');\nvar TOP_DOUBLE_CLICK = unsafeCastStringToDOMTopLevelType('dblclick');\nvar TOP_AUX_CLICK = unsafeCastStringToDOMTopLevelType('auxclick');\nvar TOP_DRAG = unsafeCastStringToDOMTopLevelType('drag');\nvar TOP_DRAG_END = unsafeCastStringToDOMTopLevelType('dragend');\nvar TOP_DRAG_ENTER = unsafeCastStringToDOMTopLevelType('dragenter');\nvar TOP_DRAG_EXIT = unsafeCastStringToDOMTopLevelType('dragexit');\nvar TOP_DRAG_LEAVE = unsafeCastStringToDOMTopLevelType('dragleave');\nvar TOP_DRAG_OVER = unsafeCastStringToDOMTopLevelType('dragover');\nvar TOP_DRAG_START = unsafeCastStringToDOMTopLevelType('dragstart');\nvar TOP_DROP = unsafeCastStringToDOMTopLevelType('drop');\nvar TOP_DURATION_CHANGE = unsafeCastStringToDOMTopLevelType('durationchange');\nvar TOP_EMPTIED = unsafeCastStringToDOMTopLevelType('emptied');\nvar TOP_ENCRYPTED = unsafeCastStringToDOMTopLevelType('encrypted');\nvar TOP_ENDED = unsafeCastStringToDOMTopLevelType('ended');\nvar TOP_ERROR = unsafeCastStringToDOMTopLevelType('error');\nvar TOP_FOCUS = unsafeCastStringToDOMTopLevelType('focus');\nvar TOP_GOT_POINTER_CAPTURE = unsafeCastStringToDOMTopLevelType('gotpointercapture');\nvar TOP_INPUT = unsafeCastStringToDOMTopLevelType('input');\nvar TOP_INVALID = unsafeCastStringToDOMTopLevelType('invalid');\nvar TOP_KEY_DOWN = unsafeCastStringToDOMTopLevelType('keydown');\nvar TOP_KEY_PRESS = unsafeCastStringToDOMTopLevelType('keypress');\nvar TOP_KEY_UP = unsafeCastStringToDOMTopLevelType('keyup');\nvar TOP_LOAD = unsafeCastStringToDOMTopLevelType('load');\nvar TOP_LOAD_START = unsafeCastStringToDOMTopLevelType('loadstart');\nvar TOP_LOADED_DATA = unsafeCastStringToDOMTopLevelType('loadeddata');\nvar TOP_LOADED_METADATA = unsafeCastStringToDOMTopLevelType('loadedmetadata');\nvar TOP_LOST_POINTER_CAPTURE = unsafeCastStringToDOMTopLevelType('lostpointercapture');\nvar TOP_MOUSE_DOWN = unsafeCastStringToDOMTopLevelType('mousedown');\nvar TOP_MOUSE_MOVE = unsafeCastStringToDOMTopLevelType('mousemove');\nvar TOP_MOUSE_OUT = unsafeCastStringToDOMTopLevelType('mouseout');\nvar TOP_MOUSE_OVER = unsafeCastStringToDOMTopLevelType('mouseover');\nvar TOP_MOUSE_UP = unsafeCastStringToDOMTopLevelType('mouseup');\nvar TOP_PASTE = unsafeCastStringToDOMTopLevelType('paste');\nvar TOP_PAUSE = unsafeCastStringToDOMTopLevelType('pause');\nvar TOP_PLAY = unsafeCastStringToDOMTopLevelType('play');\nvar TOP_PLAYING = unsafeCastStringToDOMTopLevelType('playing');\nvar TOP_POINTER_CANCEL = unsafeCastStringToDOMTopLevelType('pointercancel');\nvar TOP_POINTER_DOWN = unsafeCastStringToDOMTopLevelType('pointerdown');\nvar TOP_POINTER_MOVE = unsafeCastStringToDOMTopLevelType('pointermove');\nvar TOP_POINTER_OUT = unsafeCastStringToDOMTopLevelType('pointerout');\nvar TOP_POINTER_OVER = unsafeCastStringToDOMTopLevelType('pointerover');\nvar TOP_POINTER_UP = unsafeCastStringToDOMTopLevelType('pointerup');\nvar TOP_PROGRESS = unsafeCastStringToDOMTopLevelType('progress');\nvar TOP_RATE_CHANGE = unsafeCastStringToDOMTopLevelType('ratechange');\nvar TOP_RESET = unsafeCastStringToDOMTopLevelType('reset');\nvar TOP_SCROLL = unsafeCastStringToDOMTopLevelType('scroll');\nvar TOP_SEEKED = unsafeCastStringToDOMTopLevelType('seeked');\nvar TOP_SEEKING = unsafeCastStringToDOMTopLevelType('seeking');\nvar TOP_SELECTION_CHANGE = unsafeCastStringToDOMTopLevelType('selectionchange');\nvar TOP_STALLED = unsafeCastStringToDOMTopLevelType('stalled');\nvar TOP_SUBMIT = unsafeCastStringToDOMTopLevelType('submit');\nvar TOP_SUSPEND = unsafeCastStringToDOMTopLevelType('suspend');\nvar TOP_TEXT_INPUT = unsafeCastStringToDOMTopLevelType('textInput');\nvar TOP_TIME_UPDATE = unsafeCastStringToDOMTopLevelType('timeupdate');\nvar TOP_TOGGLE = unsafeCastStringToDOMTopLevelType('toggle');\nvar TOP_TOUCH_CANCEL = unsafeCastStringToDOMTopLevelType('touchcancel');\nvar TOP_TOUCH_END = unsafeCastStringToDOMTopLevelType('touchend');\nvar TOP_TOUCH_MOVE = unsafeCastStringToDOMTopLevelType('touchmove');\nvar TOP_TOUCH_START = unsafeCastStringToDOMTopLevelType('touchstart');\nvar TOP_TRANSITION_END = unsafeCastStringToDOMTopLevelType(getVendorPrefixedEventName('transitionend'));\nvar TOP_VOLUME_CHANGE = unsafeCastStringToDOMTopLevelType('volumechange');\nvar TOP_WAITING = unsafeCastStringToDOMTopLevelType('waiting');\nvar TOP_WHEEL = unsafeCastStringToDOMTopLevelType('wheel'); // List of events that need to be individually attached to media elements.\n// Note that events in this list will *not* be listened to at the top level\n// unless they're explicitly whitelisted in `ReactBrowserEventEmitter.listenTo`.\n\nvar mediaEventTypes = [TOP_ABORT, TOP_CAN_PLAY, TOP_CAN_PLAY_THROUGH, TOP_DURATION_CHANGE, TOP_EMPTIED, TOP_ENCRYPTED, TOP_ENDED, TOP_ERROR, TOP_LOADED_DATA, TOP_LOADED_METADATA, TOP_LOAD_START, TOP_PAUSE, TOP_PLAY, TOP_PLAYING, TOP_PROGRESS, TOP_RATE_CHANGE, TOP_SEEKED, TOP_SEEKING, TOP_STALLED, TOP_SUSPEND, TOP_TIME_UPDATE, TOP_VOLUME_CHANGE, TOP_WAITING];\nfunction getRawEventName(topLevelType) {\n return unsafeCastDOMTopLevelTypeToString(topLevelType);\n}\n\nvar PossiblyWeakMap = typeof WeakMap === 'function' ? WeakMap : Map; // prettier-ignore\n\nvar elementListenerMap = new PossiblyWeakMap();\nfunction getListenerMapForElement(element) {\n var listenerMap = elementListenerMap.get(element);\n\n if (listenerMap === undefined) {\n listenerMap = new Map();\n elementListenerMap.set(element, listenerMap);\n }\n\n return listenerMap;\n}\n\n/**\n * `ReactInstanceMap` maintains a mapping from a public facing stateful\n * instance (key) and the internal representation (value). This allows public\n * methods to accept the user facing instance as an argument and map them back\n * to internal methods.\n *\n * Note that this module is currently shared and assumed to be stateless.\n * If this becomes an actual Map, that will break.\n */\nfunction get(key) {\n return key._reactInternalFiber;\n}\nfunction has(key) {\n return key._reactInternalFiber !== undefined;\n}\nfunction set(key, value) {\n key._reactInternalFiber = value;\n}\n\n// Don't change these two values. They're used by React Dev Tools.\nvar NoEffect =\n/* */\n0;\nvar PerformedWork =\n/* */\n1; // You can change the rest (and add more).\n\nvar Placement =\n/* */\n2;\nvar Update =\n/* */\n4;\nvar PlacementAndUpdate =\n/* */\n6;\nvar Deletion =\n/* */\n8;\nvar ContentReset =\n/* */\n16;\nvar Callback =\n/* */\n32;\nvar DidCapture =\n/* */\n64;\nvar Ref =\n/* */\n128;\nvar Snapshot =\n/* */\n256;\nvar Passive =\n/* */\n512;\nvar Hydrating =\n/* */\n1024;\nvar HydratingAndUpdate =\n/* */\n1028; // Passive & Update & Callback & Ref & Snapshot\n\nvar LifecycleEffectMask =\n/* */\n932; // Union of all host effects\n\nvar HostEffectMask =\n/* */\n2047;\nvar Incomplete =\n/* */\n2048;\nvar ShouldCapture =\n/* */\n4096;\n\nvar ReactCurrentOwner = ReactSharedInternals.ReactCurrentOwner;\nfunction getNearestMountedFiber(fiber) {\n var node = fiber;\n var nearestMounted = fiber;\n\n if (!fiber.alternate) {\n // If there is no alternate, this might be a new tree that isn't inserted\n // yet. If it is, then it will have a pending insertion effect on it.\n var nextNode = node;\n\n do {\n node = nextNode;\n\n if ((node.effectTag & (Placement | Hydrating)) !== NoEffect) {\n // This is an insertion or in-progress hydration. The nearest possible\n // mounted fiber is the parent but we need to continue to figure out\n // if that one is still mounted.\n nearestMounted = node.return;\n }\n\n nextNode = node.return;\n } while (nextNode);\n } else {\n while (node.return) {\n node = node.return;\n }\n }\n\n if (node.tag === HostRoot) {\n // TODO: Check if this was a nested HostRoot when used with\n // renderContainerIntoSubtree.\n return nearestMounted;\n } // If we didn't hit the root, that means that we're in an disconnected tree\n // that has been unmounted.\n\n\n return null;\n}\nfunction getSuspenseInstanceFromFiber(fiber) {\n if (fiber.tag === SuspenseComponent) {\n var suspenseState = fiber.memoizedState;\n\n if (suspenseState === null) {\n var current = fiber.alternate;\n\n if (current !== null) {\n suspenseState = current.memoizedState;\n }\n }\n\n if (suspenseState !== null) {\n return suspenseState.dehydrated;\n }\n }\n\n return null;\n}\nfunction getContainerFromFiber(fiber) {\n return fiber.tag === HostRoot ? fiber.stateNode.containerInfo : null;\n}\nfunction isFiberMounted(fiber) {\n return getNearestMountedFiber(fiber) === fiber;\n}\nfunction isMounted(component) {\n {\n var owner = ReactCurrentOwner.current;\n\n if (owner !== null && owner.tag === ClassComponent) {\n var ownerFiber = owner;\n var instance = ownerFiber.stateNode;\n\n if (!instance._warnedAboutRefsInRender) {\n error('%s is accessing isMounted inside its render() function. ' + 'render() should be a pure function of props and state. It should ' + 'never access something that requires stale data from the previous ' + 'render, such as refs. Move this logic to componentDidMount and ' + 'componentDidUpdate instead.', getComponentName(ownerFiber.type) || 'A component');\n }\n\n instance._warnedAboutRefsInRender = true;\n }\n }\n\n var fiber = get(component);\n\n if (!fiber) {\n return false;\n }\n\n return getNearestMountedFiber(fiber) === fiber;\n}\n\nfunction assertIsMounted(fiber) {\n if (!(getNearestMountedFiber(fiber) === fiber)) {\n {\n throw Error( \"Unable to find node on an unmounted component.\" );\n }\n }\n}\n\nfunction findCurrentFiberUsingSlowPath(fiber) {\n var alternate = fiber.alternate;\n\n if (!alternate) {\n // If there is no alternate, then we only need to check if it is mounted.\n var nearestMounted = getNearestMountedFiber(fiber);\n\n if (!(nearestMounted !== null)) {\n {\n throw Error( \"Unable to find node on an unmounted component.\" );\n }\n }\n\n if (nearestMounted !== fiber) {\n return null;\n }\n\n return fiber;\n } // If we have two possible branches, we'll walk backwards up to the root\n // to see what path the root points to. On the way we may hit one of the\n // special cases and we'll deal with them.\n\n\n var a = fiber;\n var b = alternate;\n\n while (true) {\n var parentA = a.return;\n\n if (parentA === null) {\n // We're at the root.\n break;\n }\n\n var parentB = parentA.alternate;\n\n if (parentB === null) {\n // There is no alternate. This is an unusual case. Currently, it only\n // happens when a Suspense component is hidden. An extra fragment fiber\n // is inserted in between the Suspense fiber and its children. Skip\n // over this extra fragment fiber and proceed to the next parent.\n var nextParent = parentA.return;\n\n if (nextParent !== null) {\n a = b = nextParent;\n continue;\n } // If there's no parent, we're at the root.\n\n\n break;\n } // If both copies of the parent fiber point to the same child, we can\n // assume that the child is current. This happens when we bailout on low\n // priority: the bailed out fiber's child reuses the current child.\n\n\n if (parentA.child === parentB.child) {\n var child = parentA.child;\n\n while (child) {\n if (child === a) {\n // We've determined that A is the current branch.\n assertIsMounted(parentA);\n return fiber;\n }\n\n if (child === b) {\n // We've determined that B is the current branch.\n assertIsMounted(parentA);\n return alternate;\n }\n\n child = child.sibling;\n } // We should never have an alternate for any mounting node. So the only\n // way this could possibly happen is if this was unmounted, if at all.\n\n\n {\n {\n throw Error( \"Unable to find node on an unmounted component.\" );\n }\n }\n }\n\n if (a.return !== b.return) {\n // The return pointer of A and the return pointer of B point to different\n // fibers. We assume that return pointers never criss-cross, so A must\n // belong to the child set of A.return, and B must belong to the child\n // set of B.return.\n a = parentA;\n b = parentB;\n } else {\n // The return pointers point to the same fiber. We'll have to use the\n // default, slow path: scan the child sets of each parent alternate to see\n // which child belongs to which set.\n //\n // Search parent A's child set\n var didFindChild = false;\n var _child = parentA.child;\n\n while (_child) {\n if (_child === a) {\n didFindChild = true;\n a = parentA;\n b = parentB;\n break;\n }\n\n if (_child === b) {\n didFindChild = true;\n b = parentA;\n a = parentB;\n break;\n }\n\n _child = _child.sibling;\n }\n\n if (!didFindChild) {\n // Search parent B's child set\n _child = parentB.child;\n\n while (_child) {\n if (_child === a) {\n didFindChild = true;\n a = parentB;\n b = parentA;\n break;\n }\n\n if (_child === b) {\n didFindChild = true;\n b = parentB;\n a = parentA;\n break;\n }\n\n _child = _child.sibling;\n }\n\n if (!didFindChild) {\n {\n throw Error( \"Child was not found in either parent set. This indicates a bug in React related to the return pointer. Please file an issue.\" );\n }\n }\n }\n }\n\n if (!(a.alternate === b)) {\n {\n throw Error( \"Return fibers should always be each others' alternates. This error is likely caused by a bug in React. Please file an issue.\" );\n }\n }\n } // If the root is not a host container, we're in a disconnected tree. I.e.\n // unmounted.\n\n\n if (!(a.tag === HostRoot)) {\n {\n throw Error( \"Unable to find node on an unmounted component.\" );\n }\n }\n\n if (a.stateNode.current === a) {\n // We've determined that A is the current branch.\n return fiber;\n } // Otherwise B has to be current branch.\n\n\n return alternate;\n}\nfunction findCurrentHostFiber(parent) {\n var currentParent = findCurrentFiberUsingSlowPath(parent);\n\n if (!currentParent) {\n return null;\n } // Next we'll drill down this component to find the first HostComponent/Text.\n\n\n var node = currentParent;\n\n while (true) {\n if (node.tag === HostComponent || node.tag === HostText) {\n return node;\n } else if (node.child) {\n node.child.return = node;\n node = node.child;\n continue;\n }\n\n if (node === currentParent) {\n return null;\n }\n\n while (!node.sibling) {\n if (!node.return || node.return === currentParent) {\n return null;\n }\n\n node = node.return;\n }\n\n node.sibling.return = node.return;\n node = node.sibling;\n } // Flow needs the return null here, but ESLint complains about it.\n // eslint-disable-next-line no-unreachable\n\n\n return null;\n}\nfunction findCurrentHostFiberWithNoPortals(parent) {\n var currentParent = findCurrentFiberUsingSlowPath(parent);\n\n if (!currentParent) {\n return null;\n } // Next we'll drill down this component to find the first HostComponent/Text.\n\n\n var node = currentParent;\n\n while (true) {\n if (node.tag === HostComponent || node.tag === HostText || enableFundamentalAPI ) {\n return node;\n } else if (node.child && node.tag !== HostPortal) {\n node.child.return = node;\n node = node.child;\n continue;\n }\n\n if (node === currentParent) {\n return null;\n }\n\n while (!node.sibling) {\n if (!node.return || node.return === currentParent) {\n return null;\n }\n\n node = node.return;\n }\n\n node.sibling.return = node.return;\n node = node.sibling;\n } // Flow needs the return null here, but ESLint complains about it.\n // eslint-disable-next-line no-unreachable\n\n\n return null;\n}\n\n/**\n * Accumulates items that must not be null or undefined into the first one. This\n * is used to conserve memory by avoiding array allocations, and thus sacrifices\n * API cleanness. Since `current` can be null before being passed in and not\n * null after this function, make sure to assign it back to `current`:\n *\n * `a = accumulateInto(a, b);`\n *\n * This API should be sparingly used. Try `accumulate` for something cleaner.\n *\n * @return {*|array<*>} An accumulation of items.\n */\n\nfunction accumulateInto(current, next) {\n if (!(next != null)) {\n {\n throw Error( \"accumulateInto(...): Accumulated items must not be null or undefined.\" );\n }\n }\n\n if (current == null) {\n return next;\n } // Both are not empty. Warning: Never call x.concat(y) when you are not\n // certain that x is an Array (x could be a string with concat method).\n\n\n if (Array.isArray(current)) {\n if (Array.isArray(next)) {\n current.push.apply(current, next);\n return current;\n }\n\n current.push(next);\n return current;\n }\n\n if (Array.isArray(next)) {\n // A bit too dangerous to mutate `next`.\n return [current].concat(next);\n }\n\n return [current, next];\n}\n\n/**\n * @param {array} arr an \"accumulation\" of items which is either an Array or\n * a single item. Useful when paired with the `accumulate` module. This is a\n * simple utility that allows us to reason about a collection of items, but\n * handling the case when there is exactly one item (and we do not need to\n * allocate an array).\n * @param {function} cb Callback invoked with each element or a collection.\n * @param {?} [scope] Scope used as `this` in a callback.\n */\nfunction forEachAccumulated(arr, cb, scope) {\n if (Array.isArray(arr)) {\n arr.forEach(cb, scope);\n } else if (arr) {\n cb.call(scope, arr);\n }\n}\n\n/**\n * Internal queue of events that have accumulated their dispatches and are\n * waiting to have their dispatches executed.\n */\n\nvar eventQueue = null;\n/**\n * Dispatches an event and releases it back into the pool, unless persistent.\n *\n * @param {?object} event Synthetic event to be dispatched.\n * @private\n */\n\nvar executeDispatchesAndRelease = function (event) {\n if (event) {\n executeDispatchesInOrder(event);\n\n if (!event.isPersistent()) {\n event.constructor.release(event);\n }\n }\n};\n\nvar executeDispatchesAndReleaseTopLevel = function (e) {\n return executeDispatchesAndRelease(e);\n};\n\nfunction runEventsInBatch(events) {\n if (events !== null) {\n eventQueue = accumulateInto(eventQueue, events);\n } // Set `eventQueue` to null before processing it so that we can tell if more\n // events get enqueued while processing.\n\n\n var processingEventQueue = eventQueue;\n eventQueue = null;\n\n if (!processingEventQueue) {\n return;\n }\n\n forEachAccumulated(processingEventQueue, executeDispatchesAndReleaseTopLevel);\n\n if (!!eventQueue) {\n {\n throw Error( \"processEventQueue(): Additional events were enqueued while processing an event queue. Support for this has not yet been implemented.\" );\n }\n } // This would be a good time to rethrow if any of the event handlers threw.\n\n\n rethrowCaughtError();\n}\n\n/**\n * Gets the target node from a native browser event by accounting for\n * inconsistencies in browser DOM APIs.\n *\n * @param {object} nativeEvent Native browser event.\n * @return {DOMEventTarget} Target node.\n */\n\nfunction getEventTarget(nativeEvent) {\n // Fallback to nativeEvent.srcElement for IE9\n // https://github.com/facebook/react/issues/12506\n var target = nativeEvent.target || nativeEvent.srcElement || window; // Normalize SVG <use> element events #4963\n\n if (target.correspondingUseElement) {\n target = target.correspondingUseElement;\n } // Safari may fire events on text nodes (Node.TEXT_NODE is 3).\n // @see http://www.quirksmode.org/js/events_properties.html\n\n\n return target.nodeType === TEXT_NODE ? target.parentNode : target;\n}\n\n/**\n * Checks if an event is supported in the current execution environment.\n *\n * NOTE: This will not work correctly for non-generic events such as `change`,\n * `reset`, `load`, `error`, and `select`.\n *\n * Borrows from Modernizr.\n *\n * @param {string} eventNameSuffix Event name, e.g. \"click\".\n * @return {boolean} True if the event is supported.\n * @internal\n * @license Modernizr 3.0.0pre (Custom Build) | MIT\n */\n\nfunction isEventSupported(eventNameSuffix) {\n if (!canUseDOM) {\n return false;\n }\n\n var eventName = 'on' + eventNameSuffix;\n var isSupported = eventName in document;\n\n if (!isSupported) {\n var element = document.createElement('div');\n element.setAttribute(eventName, 'return;');\n isSupported = typeof element[eventName] === 'function';\n }\n\n return isSupported;\n}\n\n/**\n * Summary of `DOMEventPluginSystem` event handling:\n *\n * - Top-level delegation is used to trap most native browser events. This\n * may only occur in the main thread and is the responsibility of\n * ReactDOMEventListener, which is injected and can therefore support\n * pluggable event sources. This is the only work that occurs in the main\n * thread.\n *\n * - We normalize and de-duplicate events to account for browser quirks. This\n * may be done in the worker thread.\n *\n * - Forward these native events (with the associated top-level type used to\n * trap it) to `EventPluginRegistry`, which in turn will ask plugins if they want\n * to extract any synthetic events.\n *\n * - The `EventPluginRegistry` will then process each event by annotating them with\n * \"dispatches\", a sequence of listeners and IDs that care about that event.\n *\n * - The `EventPluginRegistry` then dispatches the events.\n *\n * Overview of React and the event system:\n *\n * +------------+ .\n * | DOM | .\n * +------------+ .\n * | .\n * v .\n * +------------+ .\n * | ReactEvent | .\n * | Listener | .\n * +------------+ . +-----------+\n * | . +--------+|SimpleEvent|\n * | . | |Plugin |\n * +-----|------+ . v +-----------+\n * | | | . +--------------+ +------------+\n * | +-----------.--->|PluginRegistry| | Event |\n * | | . | | +-----------+ | Propagators|\n * | ReactEvent | . | | |TapEvent | |------------|\n * | Emitter | . | |<---+|Plugin | |other plugin|\n * | | . | | +-----------+ | utilities |\n * | +-----------.--->| | +------------+\n * | | | . +--------------+\n * +-----|------+ . ^ +-----------+\n * | . | |Enter/Leave|\n * + . +-------+|Plugin |\n * +-------------+ . +-----------+\n * | application | .\n * |-------------| .\n * | | .\n * | | .\n * +-------------+ .\n * .\n * React Core . General Purpose Event Plugin System\n */\n\nvar CALLBACK_BOOKKEEPING_POOL_SIZE = 10;\nvar callbackBookkeepingPool = [];\n\nfunction releaseTopLevelCallbackBookKeeping(instance) {\n instance.topLevelType = null;\n instance.nativeEvent = null;\n instance.targetInst = null;\n instance.ancestors.length = 0;\n\n if (callbackBookkeepingPool.length < CALLBACK_BOOKKEEPING_POOL_SIZE) {\n callbackBookkeepingPool.push(instance);\n }\n} // Used to store ancestor hierarchy in top level callback\n\n\nfunction getTopLevelCallbackBookKeeping(topLevelType, nativeEvent, targetInst, eventSystemFlags) {\n if (callbackBookkeepingPool.length) {\n var instance = callbackBookkeepingPool.pop();\n instance.topLevelType = topLevelType;\n instance.eventSystemFlags = eventSystemFlags;\n instance.nativeEvent = nativeEvent;\n instance.targetInst = targetInst;\n return instance;\n }\n\n return {\n topLevelType: topLevelType,\n eventSystemFlags: eventSystemFlags,\n nativeEvent: nativeEvent,\n targetInst: targetInst,\n ancestors: []\n };\n}\n/**\n * Find the deepest React component completely containing the root of the\n * passed-in instance (for use when entire React trees are nested within each\n * other). If React trees are not nested, returns null.\n */\n\n\nfunction findRootContainerNode(inst) {\n if (inst.tag === HostRoot) {\n return inst.stateNode.containerInfo;\n } // TODO: It may be a good idea to cache this to prevent unnecessary DOM\n // traversal, but caching is difficult to do correctly without using a\n // mutation observer to listen for all DOM changes.\n\n\n while (inst.return) {\n inst = inst.return;\n }\n\n if (inst.tag !== HostRoot) {\n // This can happen if we're in a detached tree.\n return null;\n }\n\n return inst.stateNode.containerInfo;\n}\n/**\n * Allows registered plugins an opportunity to extract events from top-level\n * native browser events.\n *\n * @return {*} An accumulation of synthetic events.\n * @internal\n */\n\n\nfunction extractPluginEvents(topLevelType, targetInst, nativeEvent, nativeEventTarget, eventSystemFlags) {\n var events = null;\n\n for (var i = 0; i < plugins.length; i++) {\n // Not every plugin in the ordering may be loaded at runtime.\n var possiblePlugin = plugins[i];\n\n if (possiblePlugin) {\n var extractedEvents = possiblePlugin.extractEvents(topLevelType, targetInst, nativeEvent, nativeEventTarget, eventSystemFlags);\n\n if (extractedEvents) {\n events = accumulateInto(events, extractedEvents);\n }\n }\n }\n\n return events;\n}\n\nfunction runExtractedPluginEventsInBatch(topLevelType, targetInst, nativeEvent, nativeEventTarget, eventSystemFlags) {\n var events = extractPluginEvents(topLevelType, targetInst, nativeEvent, nativeEventTarget, eventSystemFlags);\n runEventsInBatch(events);\n}\n\nfunction handleTopLevel(bookKeeping) {\n var targetInst = bookKeeping.targetInst; // Loop through the hierarchy, in case there's any nested components.\n // It's important that we build the array of ancestors before calling any\n // event handlers, because event handlers can modify the DOM, leading to\n // inconsistencies with ReactMount's node cache. See #1105.\n\n var ancestor = targetInst;\n\n do {\n if (!ancestor) {\n var ancestors = bookKeeping.ancestors;\n ancestors.push(ancestor);\n break;\n }\n\n var root = findRootContainerNode(ancestor);\n\n if (!root) {\n break;\n }\n\n var tag = ancestor.tag;\n\n if (tag === HostComponent || tag === HostText) {\n bookKeeping.ancestors.push(ancestor);\n }\n\n ancestor = getClosestInstanceFromNode(root);\n } while (ancestor);\n\n for (var i = 0; i < bookKeeping.ancestors.length; i++) {\n targetInst = bookKeeping.ancestors[i];\n var eventTarget = getEventTarget(bookKeeping.nativeEvent);\n var topLevelType = bookKeeping.topLevelType;\n var nativeEvent = bookKeeping.nativeEvent;\n var eventSystemFlags = bookKeeping.eventSystemFlags; // If this is the first ancestor, we mark it on the system flags\n\n if (i === 0) {\n eventSystemFlags |= IS_FIRST_ANCESTOR;\n }\n\n runExtractedPluginEventsInBatch(topLevelType, targetInst, nativeEvent, eventTarget, eventSystemFlags);\n }\n}\n\nfunction dispatchEventForLegacyPluginEventSystem(topLevelType, eventSystemFlags, nativeEvent, targetInst) {\n var bookKeeping = getTopLevelCallbackBookKeeping(topLevelType, nativeEvent, targetInst, eventSystemFlags);\n\n try {\n // Event queue being processed in the same cycle allows\n // `preventDefault`.\n batchedEventUpdates(handleTopLevel, bookKeeping);\n } finally {\n releaseTopLevelCallbackBookKeeping(bookKeeping);\n }\n}\n/**\n * We listen for bubbled touch events on the document object.\n *\n * Firefox v8.01 (and possibly others) exhibited strange behavior when\n * mounting `onmousemove` events at some node that was not the document\n * element. The symptoms were that if your mouse is not moving over something\n * contained within that mount point (for example on the background) the\n * top-level listeners for `onmousemove` won't be called. However, if you\n * register the `mousemove` on the document object, then it will of course\n * catch all `mousemove`s. This along with iOS quirks, justifies restricting\n * top-level listeners to the document object only, at least for these\n * movement types of events and possibly all events.\n *\n * @see http://www.quirksmode.org/blog/archives/2010/09/click_event_del.html\n *\n * Also, `keyup`/`keypress`/`keydown` do not bubble to the window on IE, but\n * they bubble to document.\n *\n * @param {string} registrationName Name of listener (e.g. `onClick`).\n * @param {object} mountAt Container where to mount the listener\n */\n\nfunction legacyListenToEvent(registrationName, mountAt) {\n var listenerMap = getListenerMapForElement(mountAt);\n var dependencies = registrationNameDependencies[registrationName];\n\n for (var i = 0; i < dependencies.length; i++) {\n var dependency = dependencies[i];\n legacyListenToTopLevelEvent(dependency, mountAt, listenerMap);\n }\n}\nfunction legacyListenToTopLevelEvent(topLevelType, mountAt, listenerMap) {\n if (!listenerMap.has(topLevelType)) {\n switch (topLevelType) {\n case TOP_SCROLL:\n trapCapturedEvent(TOP_SCROLL, mountAt);\n break;\n\n case TOP_FOCUS:\n case TOP_BLUR:\n trapCapturedEvent(TOP_FOCUS, mountAt);\n trapCapturedEvent(TOP_BLUR, mountAt); // We set the flag for a single dependency later in this function,\n // but this ensures we mark both as attached rather than just one.\n\n listenerMap.set(TOP_BLUR, null);\n listenerMap.set(TOP_FOCUS, null);\n break;\n\n case TOP_CANCEL:\n case TOP_CLOSE:\n if (isEventSupported(getRawEventName(topLevelType))) {\n trapCapturedEvent(topLevelType, mountAt);\n }\n\n break;\n\n case TOP_INVALID:\n case TOP_SUBMIT:\n case TOP_RESET:\n // We listen to them on the target DOM elements.\n // Some of them bubble so we don't want them to fire twice.\n break;\n\n default:\n // By default, listen on the top level to all non-media events.\n // Media events don't bubble so adding the listener wouldn't do anything.\n var isMediaEvent = mediaEventTypes.indexOf(topLevelType) !== -1;\n\n if (!isMediaEvent) {\n trapBubbledEvent(topLevelType, mountAt);\n }\n\n break;\n }\n\n listenerMap.set(topLevelType, null);\n }\n}\nfunction isListeningToAllDependencies(registrationName, mountAt) {\n var listenerMap = getListenerMapForElement(mountAt);\n var dependencies = registrationNameDependencies[registrationName];\n\n for (var i = 0; i < dependencies.length; i++) {\n var dependency = dependencies[i];\n\n if (!listenerMap.has(dependency)) {\n return false;\n }\n }\n\n return true;\n}\n\nvar attemptUserBlockingHydration;\nfunction setAttemptUserBlockingHydration(fn) {\n attemptUserBlockingHydration = fn;\n}\nvar attemptContinuousHydration;\nfunction setAttemptContinuousHydration(fn) {\n attemptContinuousHydration = fn;\n}\nvar attemptHydrationAtCurrentPriority;\nfunction setAttemptHydrationAtCurrentPriority(fn) {\n attemptHydrationAtCurrentPriority = fn;\n} // TODO: Upgrade this definition once we're on a newer version of Flow that\nvar hasScheduledReplayAttempt = false; // The queue of discrete events to be replayed.\n\nvar queuedDiscreteEvents = []; // Indicates if any continuous event targets are non-null for early bailout.\n// if the last target was dehydrated.\n\nvar queuedFocus = null;\nvar queuedDrag = null;\nvar queuedMouse = null; // For pointer events there can be one latest event per pointerId.\n\nvar queuedPointers = new Map();\nvar queuedPointerCaptures = new Map(); // We could consider replaying selectionchange and touchmoves too.\n\nvar queuedExplicitHydrationTargets = [];\nfunction hasQueuedDiscreteEvents() {\n return queuedDiscreteEvents.length > 0;\n}\nvar discreteReplayableEvents = [TOP_MOUSE_DOWN, TOP_MOUSE_UP, TOP_TOUCH_CANCEL, TOP_TOUCH_END, TOP_TOUCH_START, TOP_AUX_CLICK, TOP_DOUBLE_CLICK, TOP_POINTER_CANCEL, TOP_POINTER_DOWN, TOP_POINTER_UP, TOP_DRAG_END, TOP_DRAG_START, TOP_DROP, TOP_COMPOSITION_END, TOP_COMPOSITION_START, TOP_KEY_DOWN, TOP_KEY_PRESS, TOP_KEY_UP, TOP_INPUT, TOP_TEXT_INPUT, TOP_CLOSE, TOP_CANCEL, TOP_COPY, TOP_CUT, TOP_PASTE, TOP_CLICK, TOP_CHANGE, TOP_CONTEXT_MENU, TOP_RESET, TOP_SUBMIT];\nvar continuousReplayableEvents = [TOP_FOCUS, TOP_BLUR, TOP_DRAG_ENTER, TOP_DRAG_LEAVE, TOP_MOUSE_OVER, TOP_MOUSE_OUT, TOP_POINTER_OVER, TOP_POINTER_OUT, TOP_GOT_POINTER_CAPTURE, TOP_LOST_POINTER_CAPTURE];\nfunction isReplayableDiscreteEvent(eventType) {\n return discreteReplayableEvents.indexOf(eventType) > -1;\n}\n\nfunction trapReplayableEventForDocument(topLevelType, document, listenerMap) {\n legacyListenToTopLevelEvent(topLevelType, document, listenerMap);\n}\n\nfunction eagerlyTrapReplayableEvents(container, document) {\n var listenerMapForDoc = getListenerMapForElement(document); // Discrete\n\n discreteReplayableEvents.forEach(function (topLevelType) {\n trapReplayableEventForDocument(topLevelType, document, listenerMapForDoc);\n }); // Continuous\n\n continuousReplayableEvents.forEach(function (topLevelType) {\n trapReplayableEventForDocument(topLevelType, document, listenerMapForDoc);\n });\n}\n\nfunction createQueuedReplayableEvent(blockedOn, topLevelType, eventSystemFlags, container, nativeEvent) {\n return {\n blockedOn: blockedOn,\n topLevelType: topLevelType,\n eventSystemFlags: eventSystemFlags | IS_REPLAYED,\n nativeEvent: nativeEvent,\n container: container\n };\n}\n\nfunction queueDiscreteEvent(blockedOn, topLevelType, eventSystemFlags, container, nativeEvent) {\n var queuedEvent = createQueuedReplayableEvent(blockedOn, topLevelType, eventSystemFlags, container, nativeEvent);\n queuedDiscreteEvents.push(queuedEvent);\n} // Resets the replaying for this type of continuous event to no event.\n\nfunction clearIfContinuousEvent(topLevelType, nativeEvent) {\n switch (topLevelType) {\n case TOP_FOCUS:\n case TOP_BLUR:\n queuedFocus = null;\n break;\n\n case TOP_DRAG_ENTER:\n case TOP_DRAG_LEAVE:\n queuedDrag = null;\n break;\n\n case TOP_MOUSE_OVER:\n case TOP_MOUSE_OUT:\n queuedMouse = null;\n break;\n\n case TOP_POINTER_OVER:\n case TOP_POINTER_OUT:\n {\n var pointerId = nativeEvent.pointerId;\n queuedPointers.delete(pointerId);\n break;\n }\n\n case TOP_GOT_POINTER_CAPTURE:\n case TOP_LOST_POINTER_CAPTURE:\n {\n var _pointerId = nativeEvent.pointerId;\n queuedPointerCaptures.delete(_pointerId);\n break;\n }\n }\n}\n\nfunction accumulateOrCreateContinuousQueuedReplayableEvent(existingQueuedEvent, blockedOn, topLevelType, eventSystemFlags, container, nativeEvent) {\n if (existingQueuedEvent === null || existingQueuedEvent.nativeEvent !== nativeEvent) {\n var queuedEvent = createQueuedReplayableEvent(blockedOn, topLevelType, eventSystemFlags, container, nativeEvent);\n\n if (blockedOn !== null) {\n var _fiber2 = getInstanceFromNode$1(blockedOn);\n\n if (_fiber2 !== null) {\n // Attempt to increase the priority of this target.\n attemptContinuousHydration(_fiber2);\n }\n }\n\n return queuedEvent;\n } // If we have already queued this exact event, then it's because\n // the different event systems have different DOM event listeners.\n // We can accumulate the flags and store a single event to be\n // replayed.\n\n\n existingQueuedEvent.eventSystemFlags |= eventSystemFlags;\n return existingQueuedEvent;\n}\n\nfunction queueIfContinuousEvent(blockedOn, topLevelType, eventSystemFlags, container, nativeEvent) {\n // These set relatedTarget to null because the replayed event will be treated as if we\n // moved from outside the window (no target) onto the target once it hydrates.\n // Instead of mutating we could clone the event.\n switch (topLevelType) {\n case TOP_FOCUS:\n {\n var focusEvent = nativeEvent;\n queuedFocus = accumulateOrCreateContinuousQueuedReplayableEvent(queuedFocus, blockedOn, topLevelType, eventSystemFlags, container, focusEvent);\n return true;\n }\n\n case TOP_DRAG_ENTER:\n {\n var dragEvent = nativeEvent;\n queuedDrag = accumulateOrCreateContinuousQueuedReplayableEvent(queuedDrag, blockedOn, topLevelType, eventSystemFlags, container, dragEvent);\n return true;\n }\n\n case TOP_MOUSE_OVER:\n {\n var mouseEvent = nativeEvent;\n queuedMouse = accumulateOrCreateContinuousQueuedReplayableEvent(queuedMouse, blockedOn, topLevelType, eventSystemFlags, container, mouseEvent);\n return true;\n }\n\n case TOP_POINTER_OVER:\n {\n var pointerEvent = nativeEvent;\n var pointerId = pointerEvent.pointerId;\n queuedPointers.set(pointerId, accumulateOrCreateContinuousQueuedReplayableEvent(queuedPointers.get(pointerId) || null, blockedOn, topLevelType, eventSystemFlags, container, pointerEvent));\n return true;\n }\n\n case TOP_GOT_POINTER_CAPTURE:\n {\n var _pointerEvent = nativeEvent;\n var _pointerId2 = _pointerEvent.pointerId;\n queuedPointerCaptures.set(_pointerId2, accumulateOrCreateContinuousQueuedReplayableEvent(queuedPointerCaptures.get(_pointerId2) || null, blockedOn, topLevelType, eventSystemFlags, container, _pointerEvent));\n return true;\n }\n }\n\n return false;\n} // Check if this target is unblocked. Returns true if it's unblocked.\n\nfunction attemptExplicitHydrationTarget(queuedTarget) {\n // TODO: This function shares a lot of logic with attemptToDispatchEvent.\n // Try to unify them. It's a bit tricky since it would require two return\n // values.\n var targetInst = getClosestInstanceFromNode(queuedTarget.target);\n\n if (targetInst !== null) {\n var nearestMounted = getNearestMountedFiber(targetInst);\n\n if (nearestMounted !== null) {\n var tag = nearestMounted.tag;\n\n if (tag === SuspenseComponent) {\n var instance = getSuspenseInstanceFromFiber(nearestMounted);\n\n if (instance !== null) {\n // We're blocked on hydrating this boundary.\n // Increase its priority.\n queuedTarget.blockedOn = instance;\n Scheduler.unstable_runWithPriority(queuedTarget.priority, function () {\n attemptHydrationAtCurrentPriority(nearestMounted);\n });\n return;\n }\n } else if (tag === HostRoot) {\n var root = nearestMounted.stateNode;\n\n if (root.hydrate) {\n queuedTarget.blockedOn = getContainerFromFiber(nearestMounted); // We don't currently have a way to increase the priority of\n // a root other than sync.\n\n return;\n }\n }\n }\n }\n\n queuedTarget.blockedOn = null;\n}\n\nfunction attemptReplayContinuousQueuedEvent(queuedEvent) {\n if (queuedEvent.blockedOn !== null) {\n return false;\n }\n\n var nextBlockedOn = attemptToDispatchEvent(queuedEvent.topLevelType, queuedEvent.eventSystemFlags, queuedEvent.container, queuedEvent.nativeEvent);\n\n if (nextBlockedOn !== null) {\n // We're still blocked. Try again later.\n var _fiber3 = getInstanceFromNode$1(nextBlockedOn);\n\n if (_fiber3 !== null) {\n attemptContinuousHydration(_fiber3);\n }\n\n queuedEvent.blockedOn = nextBlockedOn;\n return false;\n }\n\n return true;\n}\n\nfunction attemptReplayContinuousQueuedEventInMap(queuedEvent, key, map) {\n if (attemptReplayContinuousQueuedEvent(queuedEvent)) {\n map.delete(key);\n }\n}\n\nfunction replayUnblockedEvents() {\n hasScheduledReplayAttempt = false; // First replay discrete events.\n\n while (queuedDiscreteEvents.length > 0) {\n var nextDiscreteEvent = queuedDiscreteEvents[0];\n\n if (nextDiscreteEvent.blockedOn !== null) {\n // We're still blocked.\n // Increase the priority of this boundary to unblock\n // the next discrete event.\n var _fiber4 = getInstanceFromNode$1(nextDiscreteEvent.blockedOn);\n\n if (_fiber4 !== null) {\n attemptUserBlockingHydration(_fiber4);\n }\n\n break;\n }\n\n var nextBlockedOn = attemptToDispatchEvent(nextDiscreteEvent.topLevelType, nextDiscreteEvent.eventSystemFlags, nextDiscreteEvent.container, nextDiscreteEvent.nativeEvent);\n\n if (nextBlockedOn !== null) {\n // We're still blocked. Try again later.\n nextDiscreteEvent.blockedOn = nextBlockedOn;\n } else {\n // We've successfully replayed the first event. Let's try the next one.\n queuedDiscreteEvents.shift();\n }\n } // Next replay any continuous events.\n\n\n if (queuedFocus !== null && attemptReplayContinuousQueuedEvent(queuedFocus)) {\n queuedFocus = null;\n }\n\n if (queuedDrag !== null && attemptReplayContinuousQueuedEvent(queuedDrag)) {\n queuedDrag = null;\n }\n\n if (queuedMouse !== null && attemptReplayContinuousQueuedEvent(queuedMouse)) {\n queuedMouse = null;\n }\n\n queuedPointers.forEach(attemptReplayContinuousQueuedEventInMap);\n queuedPointerCaptures.forEach(attemptReplayContinuousQueuedEventInMap);\n}\n\nfunction scheduleCallbackIfUnblocked(queuedEvent, unblocked) {\n if (queuedEvent.blockedOn === unblocked) {\n queuedEvent.blockedOn = null;\n\n if (!hasScheduledReplayAttempt) {\n hasScheduledReplayAttempt = true; // Schedule a callback to attempt replaying as many events as are\n // now unblocked. This first might not actually be unblocked yet.\n // We could check it early to avoid scheduling an unnecessary callback.\n\n Scheduler.unstable_scheduleCallback(Scheduler.unstable_NormalPriority, replayUnblockedEvents);\n }\n }\n}\n\nfunction retryIfBlockedOn(unblocked) {\n // Mark anything that was blocked on this as no longer blocked\n // and eligible for a replay.\n if (queuedDiscreteEvents.length > 0) {\n scheduleCallbackIfUnblocked(queuedDiscreteEvents[0], unblocked); // This is a exponential search for each boundary that commits. I think it's\n // worth it because we expect very few discrete events to queue up and once\n // we are actually fully unblocked it will be fast to replay them.\n\n for (var i = 1; i < queuedDiscreteEvents.length; i++) {\n var queuedEvent = queuedDiscreteEvents[i];\n\n if (queuedEvent.blockedOn === unblocked) {\n queuedEvent.blockedOn = null;\n }\n }\n }\n\n if (queuedFocus !== null) {\n scheduleCallbackIfUnblocked(queuedFocus, unblocked);\n }\n\n if (queuedDrag !== null) {\n scheduleCallbackIfUnblocked(queuedDrag, unblocked);\n }\n\n if (queuedMouse !== null) {\n scheduleCallbackIfUnblocked(queuedMouse, unblocked);\n }\n\n var unblock = function (queuedEvent) {\n return scheduleCallbackIfUnblocked(queuedEvent, unblocked);\n };\n\n queuedPointers.forEach(unblock);\n queuedPointerCaptures.forEach(unblock);\n\n for (var _i = 0; _i < queuedExplicitHydrationTargets.length; _i++) {\n var queuedTarget = queuedExplicitHydrationTargets[_i];\n\n if (queuedTarget.blockedOn === unblocked) {\n queuedTarget.blockedOn = null;\n }\n }\n\n while (queuedExplicitHydrationTargets.length > 0) {\n var nextExplicitTarget = queuedExplicitHydrationTargets[0];\n\n if (nextExplicitTarget.blockedOn !== null) {\n // We're still blocked.\n break;\n } else {\n attemptExplicitHydrationTarget(nextExplicitTarget);\n\n if (nextExplicitTarget.blockedOn === null) {\n // We're unblocked.\n queuedExplicitHydrationTargets.shift();\n }\n }\n }\n}\n\nfunction addEventBubbleListener(element, eventType, listener) {\n element.addEventListener(eventType, listener, false);\n}\nfunction addEventCaptureListener(element, eventType, listener) {\n element.addEventListener(eventType, listener, true);\n}\n\n// do it in two places, which duplicates logic\n// and increases the bundle size, we do it all\n// here once. If we remove or refactor the\n// SimpleEventPlugin, we should also remove or\n// update the below line.\n\nvar simpleEventPluginEventTypes = {};\nvar topLevelEventsToDispatchConfig = new Map();\nvar eventPriorities = new Map(); // We store most of the events in this module in pairs of two strings so we can re-use\n// the code required to apply the same logic for event prioritization and that of the\n// SimpleEventPlugin. This complicates things slightly, but the aim is to reduce code\n// duplication (for which there would be quite a bit). For the events that are not needed\n// for the SimpleEventPlugin (otherDiscreteEvents) we process them separately as an\n// array of top level events.\n// Lastly, we ignore prettier so we can keep the formatting sane.\n// prettier-ignore\n\nvar discreteEventPairsForSimpleEventPlugin = [TOP_BLUR, 'blur', TOP_CANCEL, 'cancel', TOP_CLICK, 'click', TOP_CLOSE, 'close', TOP_CONTEXT_MENU, 'contextMenu', TOP_COPY, 'copy', TOP_CUT, 'cut', TOP_AUX_CLICK, 'auxClick', TOP_DOUBLE_CLICK, 'doubleClick', TOP_DRAG_END, 'dragEnd', TOP_DRAG_START, 'dragStart', TOP_DROP, 'drop', TOP_FOCUS, 'focus', TOP_INPUT, 'input', TOP_INVALID, 'invalid', TOP_KEY_DOWN, 'keyDown', TOP_KEY_PRESS, 'keyPress', TOP_KEY_UP, 'keyUp', TOP_MOUSE_DOWN, 'mouseDown', TOP_MOUSE_UP, 'mouseUp', TOP_PASTE, 'paste', TOP_PAUSE, 'pause', TOP_PLAY, 'play', TOP_POINTER_CANCEL, 'pointerCancel', TOP_POINTER_DOWN, 'pointerDown', TOP_POINTER_UP, 'pointerUp', TOP_RATE_CHANGE, 'rateChange', TOP_RESET, 'reset', TOP_SEEKED, 'seeked', TOP_SUBMIT, 'submit', TOP_TOUCH_CANCEL, 'touchCancel', TOP_TOUCH_END, 'touchEnd', TOP_TOUCH_START, 'touchStart', TOP_VOLUME_CHANGE, 'volumeChange'];\nvar otherDiscreteEvents = [TOP_CHANGE, TOP_SELECTION_CHANGE, TOP_TEXT_INPUT, TOP_COMPOSITION_START, TOP_COMPOSITION_END, TOP_COMPOSITION_UPDATE]; // prettier-ignore\n\nvar userBlockingPairsForSimpleEventPlugin = [TOP_DRAG, 'drag', TOP_DRAG_ENTER, 'dragEnter', TOP_DRAG_EXIT, 'dragExit', TOP_DRAG_LEAVE, 'dragLeave', TOP_DRAG_OVER, 'dragOver', TOP_MOUSE_MOVE, 'mouseMove', TOP_MOUSE_OUT, 'mouseOut', TOP_MOUSE_OVER, 'mouseOver', TOP_POINTER_MOVE, 'pointerMove', TOP_POINTER_OUT, 'pointerOut', TOP_POINTER_OVER, 'pointerOver', TOP_SCROLL, 'scroll', TOP_TOGGLE, 'toggle', TOP_TOUCH_MOVE, 'touchMove', TOP_WHEEL, 'wheel']; // prettier-ignore\n\nvar continuousPairsForSimpleEventPlugin = [TOP_ABORT, 'abort', TOP_ANIMATION_END, 'animationEnd', TOP_ANIMATION_ITERATION, 'animationIteration', TOP_ANIMATION_START, 'animationStart', TOP_CAN_PLAY, 'canPlay', TOP_CAN_PLAY_THROUGH, 'canPlayThrough', TOP_DURATION_CHANGE, 'durationChange', TOP_EMPTIED, 'emptied', TOP_ENCRYPTED, 'encrypted', TOP_ENDED, 'ended', TOP_ERROR, 'error', TOP_GOT_POINTER_CAPTURE, 'gotPointerCapture', TOP_LOAD, 'load', TOP_LOADED_DATA, 'loadedData', TOP_LOADED_METADATA, 'loadedMetadata', TOP_LOAD_START, 'loadStart', TOP_LOST_POINTER_CAPTURE, 'lostPointerCapture', TOP_PLAYING, 'playing', TOP_PROGRESS, 'progress', TOP_SEEKING, 'seeking', TOP_STALLED, 'stalled', TOP_SUSPEND, 'suspend', TOP_TIME_UPDATE, 'timeUpdate', TOP_TRANSITION_END, 'transitionEnd', TOP_WAITING, 'waiting'];\n/**\n * Turns\n * ['abort', ...]\n * into\n * eventTypes = {\n * 'abort': {\n * phasedRegistrationNames: {\n * bubbled: 'onAbort',\n * captured: 'onAbortCapture',\n * },\n * dependencies: [TOP_ABORT],\n * },\n * ...\n * };\n * topLevelEventsToDispatchConfig = new Map([\n * [TOP_ABORT, { sameConfig }],\n * ]);\n */\n\nfunction processSimpleEventPluginPairsByPriority(eventTypes, priority) {\n // As the event types are in pairs of two, we need to iterate\n // through in twos. The events are in pairs of two to save code\n // and improve init perf of processing this array, as it will\n // result in far fewer object allocations and property accesses\n // if we only use three arrays to process all the categories of\n // instead of tuples.\n for (var i = 0; i < eventTypes.length; i += 2) {\n var topEvent = eventTypes[i];\n var event = eventTypes[i + 1];\n var capitalizedEvent = event[0].toUpperCase() + event.slice(1);\n var onEvent = 'on' + capitalizedEvent;\n var config = {\n phasedRegistrationNames: {\n bubbled: onEvent,\n captured: onEvent + 'Capture'\n },\n dependencies: [topEvent],\n eventPriority: priority\n };\n eventPriorities.set(topEvent, priority);\n topLevelEventsToDispatchConfig.set(topEvent, config);\n simpleEventPluginEventTypes[event] = config;\n }\n}\n\nfunction processTopEventPairsByPriority(eventTypes, priority) {\n for (var i = 0; i < eventTypes.length; i++) {\n eventPriorities.set(eventTypes[i], priority);\n }\n} // SimpleEventPlugin\n\n\nprocessSimpleEventPluginPairsByPriority(discreteEventPairsForSimpleEventPlugin, DiscreteEvent);\nprocessSimpleEventPluginPairsByPriority(userBlockingPairsForSimpleEventPlugin, UserBlockingEvent);\nprocessSimpleEventPluginPairsByPriority(continuousPairsForSimpleEventPlugin, ContinuousEvent); // Not used by SimpleEventPlugin\n\nprocessTopEventPairsByPriority(otherDiscreteEvents, DiscreteEvent);\nfunction getEventPriorityForPluginSystem(topLevelType) {\n var priority = eventPriorities.get(topLevelType); // Default to a ContinuousEvent. Note: we might\n // want to warn if we can't detect the priority\n // for the event.\n\n return priority === undefined ? ContinuousEvent : priority;\n}\n\n// Intentionally not named imports because Rollup would use dynamic dispatch for\nvar UserBlockingPriority = Scheduler.unstable_UserBlockingPriority,\n runWithPriority = Scheduler.unstable_runWithPriority; // TODO: can we stop exporting these?\n\nvar _enabled = true;\nfunction setEnabled(enabled) {\n _enabled = !!enabled;\n}\nfunction isEnabled() {\n return _enabled;\n}\nfunction trapBubbledEvent(topLevelType, element) {\n trapEventForPluginEventSystem(element, topLevelType, false);\n}\nfunction trapCapturedEvent(topLevelType, element) {\n trapEventForPluginEventSystem(element, topLevelType, true);\n}\n\nfunction trapEventForPluginEventSystem(container, topLevelType, capture) {\n var listener;\n\n switch (getEventPriorityForPluginSystem(topLevelType)) {\n case DiscreteEvent:\n listener = dispatchDiscreteEvent.bind(null, topLevelType, PLUGIN_EVENT_SYSTEM, container);\n break;\n\n case UserBlockingEvent:\n listener = dispatchUserBlockingUpdate.bind(null, topLevelType, PLUGIN_EVENT_SYSTEM, container);\n break;\n\n case ContinuousEvent:\n default:\n listener = dispatchEvent.bind(null, topLevelType, PLUGIN_EVENT_SYSTEM, container);\n break;\n }\n\n var rawEventName = getRawEventName(topLevelType);\n\n if (capture) {\n addEventCaptureListener(container, rawEventName, listener);\n } else {\n addEventBubbleListener(container, rawEventName, listener);\n }\n}\n\nfunction dispatchDiscreteEvent(topLevelType, eventSystemFlags, container, nativeEvent) {\n flushDiscreteUpdatesIfNeeded(nativeEvent.timeStamp);\n discreteUpdates(dispatchEvent, topLevelType, eventSystemFlags, container, nativeEvent);\n}\n\nfunction dispatchUserBlockingUpdate(topLevelType, eventSystemFlags, container, nativeEvent) {\n runWithPriority(UserBlockingPriority, dispatchEvent.bind(null, topLevelType, eventSystemFlags, container, nativeEvent));\n}\n\nfunction dispatchEvent(topLevelType, eventSystemFlags, container, nativeEvent) {\n if (!_enabled) {\n return;\n }\n\n if (hasQueuedDiscreteEvents() && isReplayableDiscreteEvent(topLevelType)) {\n // If we already have a queue of discrete events, and this is another discrete\n // event, then we can't dispatch it regardless of its target, since they\n // need to dispatch in order.\n queueDiscreteEvent(null, // Flags that we're not actually blocked on anything as far as we know.\n topLevelType, eventSystemFlags, container, nativeEvent);\n return;\n }\n\n var blockedOn = attemptToDispatchEvent(topLevelType, eventSystemFlags, container, nativeEvent);\n\n if (blockedOn === null) {\n // We successfully dispatched this event.\n clearIfContinuousEvent(topLevelType, nativeEvent);\n return;\n }\n\n if (isReplayableDiscreteEvent(topLevelType)) {\n // This this to be replayed later once the target is available.\n queueDiscreteEvent(blockedOn, topLevelType, eventSystemFlags, container, nativeEvent);\n return;\n }\n\n if (queueIfContinuousEvent(blockedOn, topLevelType, eventSystemFlags, container, nativeEvent)) {\n return;\n } // We need to clear only if we didn't queue because\n // queueing is accummulative.\n\n\n clearIfContinuousEvent(topLevelType, nativeEvent); // This is not replayable so we'll invoke it but without a target,\n // in case the event system needs to trace it.\n\n {\n dispatchEventForLegacyPluginEventSystem(topLevelType, eventSystemFlags, nativeEvent, null);\n }\n} // Attempt dispatching an event. Returns a SuspenseInstance or Container if it's blocked.\n\nfunction attemptToDispatchEvent(topLevelType, eventSystemFlags, container, nativeEvent) {\n // TODO: Warn if _enabled is false.\n var nativeEventTarget = getEventTarget(nativeEvent);\n var targetInst = getClosestInstanceFromNode(nativeEventTarget);\n\n if (targetInst !== null) {\n var nearestMounted = getNearestMountedFiber(targetInst);\n\n if (nearestMounted === null) {\n // This tree has been unmounted already. Dispatch without a target.\n targetInst = null;\n } else {\n var tag = nearestMounted.tag;\n\n if (tag === SuspenseComponent) {\n var instance = getSuspenseInstanceFromFiber(nearestMounted);\n\n if (instance !== null) {\n // Queue the event to be replayed later. Abort dispatching since we\n // don't want this event dispatched twice through the event system.\n // TODO: If this is the first discrete event in the queue. Schedule an increased\n // priority for this boundary.\n return instance;\n } // This shouldn't happen, something went wrong but to avoid blocking\n // the whole system, dispatch the event without a target.\n // TODO: Warn.\n\n\n targetInst = null;\n } else if (tag === HostRoot) {\n var root = nearestMounted.stateNode;\n\n if (root.hydrate) {\n // If this happens during a replay something went wrong and it might block\n // the whole system.\n return getContainerFromFiber(nearestMounted);\n }\n\n targetInst = null;\n } else if (nearestMounted !== targetInst) {\n // If we get an event (ex: img onload) before committing that\n // component's mount, ignore it for now (that is, treat it as if it was an\n // event on a non-React tree). We might also consider queueing events and\n // dispatching them after the mount.\n targetInst = null;\n }\n }\n }\n\n {\n dispatchEventForLegacyPluginEventSystem(topLevelType, eventSystemFlags, nativeEvent, targetInst);\n } // We're not blocked on anything.\n\n\n return null;\n}\n\n// List derived from Gecko source code:\n// https://github.com/mozilla/gecko-dev/blob/4e638efc71/layout/style/test/property_database.js\nvar shorthandToLonghand = {\n animation: ['animationDelay', 'animationDirection', 'animationDuration', 'animationFillMode', 'animationIterationCount', 'animationName', 'animationPlayState', 'animationTimingFunction'],\n background: ['backgroundAttachment', 'backgroundClip', 'backgroundColor', 'backgroundImage', 'backgroundOrigin', 'backgroundPositionX', 'backgroundPositionY', 'backgroundRepeat', 'backgroundSize'],\n backgroundPosition: ['backgroundPositionX', 'backgroundPositionY'],\n border: ['borderBottomColor', 'borderBottomStyle', 'borderBottomWidth', 'borderImageOutset', 'borderImageRepeat', 'borderImageSlice', 'borderImageSource', 'borderImageWidth', 'borderLeftColor', 'borderLeftStyle', 'borderLeftWidth', 'borderRightColor', 'borderRightStyle', 'borderRightWidth', 'borderTopColor', 'borderTopStyle', 'borderTopWidth'],\n borderBlockEnd: ['borderBlockEndColor', 'borderBlockEndStyle', 'borderBlockEndWidth'],\n borderBlockStart: ['borderBlockStartColor', 'borderBlockStartStyle', 'borderBlockStartWidth'],\n borderBottom: ['borderBottomColor', 'borderBottomStyle', 'borderBottomWidth'],\n borderColor: ['borderBottomColor', 'borderLeftColor', 'borderRightColor', 'borderTopColor'],\n borderImage: ['borderImageOutset', 'borderImageRepeat', 'borderImageSlice', 'borderImageSource', 'borderImageWidth'],\n borderInlineEnd: ['borderInlineEndColor', 'borderInlineEndStyle', 'borderInlineEndWidth'],\n borderInlineStart: ['borderInlineStartColor', 'borderInlineStartStyle', 'borderInlineStartWidth'],\n borderLeft: ['borderLeftColor', 'borderLeftStyle', 'borderLeftWidth'],\n borderRadius: ['borderBottomLeftRadius', 'borderBottomRightRadius', 'borderTopLeftRadius', 'borderTopRightRadius'],\n borderRight: ['borderRightColor', 'borderRightStyle', 'borderRightWidth'],\n borderStyle: ['borderBottomStyle', 'borderLeftStyle', 'borderRightStyle', 'borderTopStyle'],\n borderTop: ['borderTopColor', 'borderTopStyle', 'borderTopWidth'],\n borderWidth: ['borderBottomWidth', 'borderLeftWidth', 'borderRightWidth', 'borderTopWidth'],\n columnRule: ['columnRuleColor', 'columnRuleStyle', 'columnRuleWidth'],\n columns: ['columnCount', 'columnWidth'],\n flex: ['flexBasis', 'flexGrow', 'flexShrink'],\n flexFlow: ['flexDirection', 'flexWrap'],\n font: ['fontFamily', 'fontFeatureSettings', 'fontKerning', 'fontLanguageOverride', 'fontSize', 'fontSizeAdjust', 'fontStretch', 'fontStyle', 'fontVariant', 'fontVariantAlternates', 'fontVariantCaps', 'fontVariantEastAsian', 'fontVariantLigatures', 'fontVariantNumeric', 'fontVariantPosition', 'fontWeight', 'lineHeight'],\n fontVariant: ['fontVariantAlternates', 'fontVariantCaps', 'fontVariantEastAsian', 'fontVariantLigatures', 'fontVariantNumeric', 'fontVariantPosition'],\n gap: ['columnGap', 'rowGap'],\n grid: ['gridAutoColumns', 'gridAutoFlow', 'gridAutoRows', 'gridTemplateAreas', 'gridTemplateColumns', 'gridTemplateRows'],\n gridArea: ['gridColumnEnd', 'gridColumnStart', 'gridRowEnd', 'gridRowStart'],\n gridColumn: ['gridColumnEnd', 'gridColumnStart'],\n gridColumnGap: ['columnGap'],\n gridGap: ['columnGap', 'rowGap'],\n gridRow: ['gridRowEnd', 'gridRowStart'],\n gridRowGap: ['rowGap'],\n gridTemplate: ['gridTemplateAreas', 'gridTemplateColumns', 'gridTemplateRows'],\n listStyle: ['listStyleImage', 'listStylePosition', 'listStyleType'],\n margin: ['marginBottom', 'marginLeft', 'marginRight', 'marginTop'],\n marker: ['markerEnd', 'markerMid', 'markerStart'],\n mask: ['maskClip', 'maskComposite', 'maskImage', 'maskMode', 'maskOrigin', 'maskPositionX', 'maskPositionY', 'maskRepeat', 'maskSize'],\n maskPosition: ['maskPositionX', 'maskPositionY'],\n outline: ['outlineColor', 'outlineStyle', 'outlineWidth'],\n overflow: ['overflowX', 'overflowY'],\n padding: ['paddingBottom', 'paddingLeft', 'paddingRight', 'paddingTop'],\n placeContent: ['alignContent', 'justifyContent'],\n placeItems: ['alignItems', 'justifyItems'],\n placeSelf: ['alignSelf', 'justifySelf'],\n textDecoration: ['textDecorationColor', 'textDecorationLine', 'textDecorationStyle'],\n textEmphasis: ['textEmphasisColor', 'textEmphasisStyle'],\n transition: ['transitionDelay', 'transitionDuration', 'transitionProperty', 'transitionTimingFunction'],\n wordWrap: ['overflowWrap']\n};\n\n/**\n * CSS properties which accept numbers but are not in units of \"px\".\n */\nvar isUnitlessNumber = {\n animationIterationCount: true,\n borderImageOutset: true,\n borderImageSlice: true,\n borderImageWidth: true,\n boxFlex: true,\n boxFlexGroup: true,\n boxOrdinalGroup: true,\n columnCount: true,\n columns: true,\n flex: true,\n flexGrow: true,\n flexPositive: true,\n flexShrink: true,\n flexNegative: true,\n flexOrder: true,\n gridArea: true,\n gridRow: true,\n gridRowEnd: true,\n gridRowSpan: true,\n gridRowStart: true,\n gridColumn: true,\n gridColumnEnd: true,\n gridColumnSpan: true,\n gridColumnStart: true,\n fontWeight: true,\n lineClamp: true,\n lineHeight: true,\n opacity: true,\n order: true,\n orphans: true,\n tabSize: true,\n widows: true,\n zIndex: true,\n zoom: true,\n // SVG-related properties\n fillOpacity: true,\n floodOpacity: true,\n stopOpacity: true,\n strokeDasharray: true,\n strokeDashoffset: true,\n strokeMiterlimit: true,\n strokeOpacity: true,\n strokeWidth: true\n};\n/**\n * @param {string} prefix vendor-specific prefix, eg: Webkit\n * @param {string} key style name, eg: transitionDuration\n * @return {string} style name prefixed with `prefix`, properly camelCased, eg:\n * WebkitTransitionDuration\n */\n\nfunction prefixKey(prefix, key) {\n return prefix + key.charAt(0).toUpperCase() + key.substring(1);\n}\n/**\n * Support style names that may come passed in prefixed by adding permutations\n * of vendor prefixes.\n */\n\n\nvar prefixes = ['Webkit', 'ms', 'Moz', 'O']; // Using Object.keys here, or else the vanilla for-in loop makes IE8 go into an\n// infinite loop, because it iterates over the newly added props too.\n\nObject.keys(isUnitlessNumber).forEach(function (prop) {\n prefixes.forEach(function (prefix) {\n isUnitlessNumber[prefixKey(prefix, prop)] = isUnitlessNumber[prop];\n });\n});\n\n/**\n * Convert a value into the proper css writable value. The style name `name`\n * should be logical (no hyphens), as specified\n * in `CSSProperty.isUnitlessNumber`.\n *\n * @param {string} name CSS property name such as `topMargin`.\n * @param {*} value CSS property value such as `10px`.\n * @return {string} Normalized style value with dimensions applied.\n */\n\nfunction dangerousStyleValue(name, value, isCustomProperty) {\n // Note that we've removed escapeTextForBrowser() calls here since the\n // whole string will be escaped when the attribute is injected into\n // the markup. If you provide unsafe user data here they can inject\n // arbitrary CSS which may be problematic (I couldn't repro this):\n // https://www.owasp.org/index.php/XSS_Filter_Evasion_Cheat_Sheet\n // http://www.thespanner.co.uk/2007/11/26/ultimate-xss-css-injection/\n // This is not an XSS hole but instead a potential CSS injection issue\n // which has lead to a greater discussion about how we're going to\n // trust URLs moving forward. See #2115901\n var isEmpty = value == null || typeof value === 'boolean' || value === '';\n\n if (isEmpty) {\n return '';\n }\n\n if (!isCustomProperty && typeof value === 'number' && value !== 0 && !(isUnitlessNumber.hasOwnProperty(name) && isUnitlessNumber[name])) {\n return value + 'px'; // Presumes implicit 'px' suffix for unitless numbers\n }\n\n return ('' + value).trim();\n}\n\nvar uppercasePattern = /([A-Z])/g;\nvar msPattern = /^ms-/;\n/**\n * Hyphenates a camelcased CSS property name, for example:\n *\n * > hyphenateStyleName('backgroundColor')\n * < \"background-color\"\n * > hyphenateStyleName('MozTransition')\n * < \"-moz-transition\"\n * > hyphenateStyleName('msTransition')\n * < \"-ms-transition\"\n *\n * As Modernizr suggests (http://modernizr.com/docs/#prefixed), an `ms` prefix\n * is converted to `-ms-`.\n */\n\nfunction hyphenateStyleName(name) {\n return name.replace(uppercasePattern, '-$1').toLowerCase().replace(msPattern, '-ms-');\n}\n\nvar warnValidStyle = function () {};\n\n{\n // 'msTransform' is correct, but the other prefixes should be capitalized\n var badVendoredStyleNamePattern = /^(?:webkit|moz|o)[A-Z]/;\n var msPattern$1 = /^-ms-/;\n var hyphenPattern = /-(.)/g; // style values shouldn't contain a semicolon\n\n var badStyleValueWithSemicolonPattern = /;\\s*$/;\n var warnedStyleNames = {};\n var warnedStyleValues = {};\n var warnedForNaNValue = false;\n var warnedForInfinityValue = false;\n\n var camelize = function (string) {\n return string.replace(hyphenPattern, function (_, character) {\n return character.toUpperCase();\n });\n };\n\n var warnHyphenatedStyleName = function (name) {\n if (warnedStyleNames.hasOwnProperty(name) && warnedStyleNames[name]) {\n return;\n }\n\n warnedStyleNames[name] = true;\n\n error('Unsupported style property %s. Did you mean %s?', name, // As Andi Smith suggests\n // (http://www.andismith.com/blog/2012/02/modernizr-prefixed/), an `-ms` prefix\n // is converted to lowercase `ms`.\n camelize(name.replace(msPattern$1, 'ms-')));\n };\n\n var warnBadVendoredStyleName = function (name) {\n if (warnedStyleNames.hasOwnProperty(name) && warnedStyleNames[name]) {\n return;\n }\n\n warnedStyleNames[name] = true;\n\n error('Unsupported vendor-prefixed style property %s. Did you mean %s?', name, name.charAt(0).toUpperCase() + name.slice(1));\n };\n\n var warnStyleValueWithSemicolon = function (name, value) {\n if (warnedStyleValues.hasOwnProperty(value) && warnedStyleValues[value]) {\n return;\n }\n\n warnedStyleValues[value] = true;\n\n error(\"Style property values shouldn't contain a semicolon. \" + 'Try \"%s: %s\" instead.', name, value.replace(badStyleValueWithSemicolonPattern, ''));\n };\n\n var warnStyleValueIsNaN = function (name, value) {\n if (warnedForNaNValue) {\n return;\n }\n\n warnedForNaNValue = true;\n\n error('`NaN` is an invalid value for the `%s` css style property.', name);\n };\n\n var warnStyleValueIsInfinity = function (name, value) {\n if (warnedForInfinityValue) {\n return;\n }\n\n warnedForInfinityValue = true;\n\n error('`Infinity` is an invalid value for the `%s` css style property.', name);\n };\n\n warnValidStyle = function (name, value) {\n if (name.indexOf('-') > -1) {\n warnHyphenatedStyleName(name);\n } else if (badVendoredStyleNamePattern.test(name)) {\n warnBadVendoredStyleName(name);\n } else if (badStyleValueWithSemicolonPattern.test(value)) {\n warnStyleValueWithSemicolon(name, value);\n }\n\n if (typeof value === 'number') {\n if (isNaN(value)) {\n warnStyleValueIsNaN(name, value);\n } else if (!isFinite(value)) {\n warnStyleValueIsInfinity(name, value);\n }\n }\n };\n}\n\nvar warnValidStyle$1 = warnValidStyle;\n\n/**\n * Operations for dealing with CSS properties.\n */\n\n/**\n * This creates a string that is expected to be equivalent to the style\n * attribute generated by server-side rendering. It by-passes warnings and\n * security checks so it's not safe to use this value for anything other than\n * comparison. It is only used in DEV for SSR validation.\n */\n\nfunction createDangerousStringForStyles(styles) {\n {\n var serialized = '';\n var delimiter = '';\n\n for (var styleName in styles) {\n if (!styles.hasOwnProperty(styleName)) {\n continue;\n }\n\n var styleValue = styles[styleName];\n\n if (styleValue != null) {\n var isCustomProperty = styleName.indexOf('--') === 0;\n serialized += delimiter + (isCustomProperty ? styleName : hyphenateStyleName(styleName)) + ':';\n serialized += dangerousStyleValue(styleName, styleValue, isCustomProperty);\n delimiter = ';';\n }\n }\n\n return serialized || null;\n }\n}\n/**\n * Sets the value for multiple styles on a node. If a value is specified as\n * '' (empty string), the corresponding style property will be unset.\n *\n * @param {DOMElement} node\n * @param {object} styles\n */\n\nfunction setValueForStyles(node, styles) {\n var style = node.style;\n\n for (var styleName in styles) {\n if (!styles.hasOwnProperty(styleName)) {\n continue;\n }\n\n var isCustomProperty = styleName.indexOf('--') === 0;\n\n {\n if (!isCustomProperty) {\n warnValidStyle$1(styleName, styles[styleName]);\n }\n }\n\n var styleValue = dangerousStyleValue(styleName, styles[styleName], isCustomProperty);\n\n if (styleName === 'float') {\n styleName = 'cssFloat';\n }\n\n if (isCustomProperty) {\n style.setProperty(styleName, styleValue);\n } else {\n style[styleName] = styleValue;\n }\n }\n}\n\nfunction isValueEmpty(value) {\n return value == null || typeof value === 'boolean' || value === '';\n}\n/**\n * Given {color: 'red', overflow: 'hidden'} returns {\n * color: 'color',\n * overflowX: 'overflow',\n * overflowY: 'overflow',\n * }. This can be read as \"the overflowY property was set by the overflow\n * shorthand\". That is, the values are the property that each was derived from.\n */\n\n\nfunction expandShorthandMap(styles) {\n var expanded = {};\n\n for (var key in styles) {\n var longhands = shorthandToLonghand[key] || [key];\n\n for (var i = 0; i < longhands.length; i++) {\n expanded[longhands[i]] = key;\n }\n }\n\n return expanded;\n}\n/**\n * When mixing shorthand and longhand property names, we warn during updates if\n * we expect an incorrect result to occur. In particular, we warn for:\n *\n * Updating a shorthand property (longhand gets overwritten):\n * {font: 'foo', fontVariant: 'bar'} -> {font: 'baz', fontVariant: 'bar'}\n * becomes .style.font = 'baz'\n * Removing a shorthand property (longhand gets lost too):\n * {font: 'foo', fontVariant: 'bar'} -> {fontVariant: 'bar'}\n * becomes .style.font = ''\n * Removing a longhand property (should revert to shorthand; doesn't):\n * {font: 'foo', fontVariant: 'bar'} -> {font: 'foo'}\n * becomes .style.fontVariant = ''\n */\n\n\nfunction validateShorthandPropertyCollisionInDev(styleUpdates, nextStyles) {\n {\n\n if (!nextStyles) {\n return;\n }\n\n var expandedUpdates = expandShorthandMap(styleUpdates);\n var expandedStyles = expandShorthandMap(nextStyles);\n var warnedAbout = {};\n\n for (var key in expandedUpdates) {\n var originalKey = expandedUpdates[key];\n var correctOriginalKey = expandedStyles[key];\n\n if (correctOriginalKey && originalKey !== correctOriginalKey) {\n var warningKey = originalKey + ',' + correctOriginalKey;\n\n if (warnedAbout[warningKey]) {\n continue;\n }\n\n warnedAbout[warningKey] = true;\n\n error('%s a style property during rerender (%s) when a ' + 'conflicting property is set (%s) can lead to styling bugs. To ' + \"avoid this, don't mix shorthand and non-shorthand properties \" + 'for the same value; instead, replace the shorthand with ' + 'separate values.', isValueEmpty(styleUpdates[originalKey]) ? 'Removing' : 'Updating', originalKey, correctOriginalKey);\n }\n }\n }\n}\n\n// For HTML, certain tags should omit their close tag. We keep a whitelist for\n// those special-case tags.\nvar omittedCloseTags = {\n area: true,\n base: true,\n br: true,\n col: true,\n embed: true,\n hr: true,\n img: true,\n input: true,\n keygen: true,\n link: true,\n meta: true,\n param: true,\n source: true,\n track: true,\n wbr: true // NOTE: menuitem's close tag should be omitted, but that causes problems.\n\n};\n\n// `omittedCloseTags` except that `menuitem` should still have its closing tag.\n\nvar voidElementTags = _assign({\n menuitem: true\n}, omittedCloseTags);\n\nvar HTML = '__html';\nvar ReactDebugCurrentFrame$3 = null;\n\n{\n ReactDebugCurrentFrame$3 = ReactSharedInternals.ReactDebugCurrentFrame;\n}\n\nfunction assertValidProps(tag, props) {\n if (!props) {\n return;\n } // Note the use of `==` which checks for null or undefined.\n\n\n if (voidElementTags[tag]) {\n if (!(props.children == null && props.dangerouslySetInnerHTML == null)) {\n {\n throw Error( tag + \" is a void element tag and must neither have `children` nor use `dangerouslySetInnerHTML`.\" + ( ReactDebugCurrentFrame$3.getStackAddendum() ) );\n }\n }\n }\n\n if (props.dangerouslySetInnerHTML != null) {\n if (!(props.children == null)) {\n {\n throw Error( \"Can only set one of `children` or `props.dangerouslySetInnerHTML`.\" );\n }\n }\n\n if (!(typeof props.dangerouslySetInnerHTML === 'object' && HTML in props.dangerouslySetInnerHTML)) {\n {\n throw Error( \"`props.dangerouslySetInnerHTML` must be in the form `{__html: ...}`. Please visit https://fb.me/react-invariant-dangerously-set-inner-html for more information.\" );\n }\n }\n }\n\n {\n if (!props.suppressContentEditableWarning && props.contentEditable && props.children != null) {\n error('A component is `contentEditable` and contains `children` managed by ' + 'React. It is now your responsibility to guarantee that none of ' + 'those nodes are unexpectedly modified or duplicated. This is ' + 'probably not intentional.');\n }\n }\n\n if (!(props.style == null || typeof props.style === 'object')) {\n {\n throw Error( \"The `style` prop expects a mapping from style properties to values, not a string. For example, style={{marginRight: spacing + 'em'}} when using JSX.\" + ( ReactDebugCurrentFrame$3.getStackAddendum() ) );\n }\n }\n}\n\nfunction isCustomComponent(tagName, props) {\n if (tagName.indexOf('-') === -1) {\n return typeof props.is === 'string';\n }\n\n switch (tagName) {\n // These are reserved SVG and MathML elements.\n // We don't mind this whitelist too much because we expect it to never grow.\n // The alternative is to track the namespace in a few places which is convoluted.\n // https://w3c.github.io/webcomponents/spec/custom/#custom-elements-core-concepts\n case 'annotation-xml':\n case 'color-profile':\n case 'font-face':\n case 'font-face-src':\n case 'font-face-uri':\n case 'font-face-format':\n case 'font-face-name':\n case 'missing-glyph':\n return false;\n\n default:\n return true;\n }\n}\n\n// When adding attributes to the HTML or SVG whitelist, be sure to\n// also add them to this module to ensure casing and incorrect name\n// warnings.\nvar possibleStandardNames = {\n // HTML\n accept: 'accept',\n acceptcharset: 'acceptCharset',\n 'accept-charset': 'acceptCharset',\n accesskey: 'accessKey',\n action: 'action',\n allowfullscreen: 'allowFullScreen',\n alt: 'alt',\n as: 'as',\n async: 'async',\n autocapitalize: 'autoCapitalize',\n autocomplete: 'autoComplete',\n autocorrect: 'autoCorrect',\n autofocus: 'autoFocus',\n autoplay: 'autoPlay',\n autosave: 'autoSave',\n capture: 'capture',\n cellpadding: 'cellPadding',\n cellspacing: 'cellSpacing',\n challenge: 'challenge',\n charset: 'charSet',\n checked: 'checked',\n children: 'children',\n cite: 'cite',\n class: 'className',\n classid: 'classID',\n classname: 'className',\n cols: 'cols',\n colspan: 'colSpan',\n content: 'content',\n contenteditable: 'contentEditable',\n contextmenu: 'contextMenu',\n controls: 'controls',\n controlslist: 'controlsList',\n coords: 'coords',\n crossorigin: 'crossOrigin',\n dangerouslysetinnerhtml: 'dangerouslySetInnerHTML',\n data: 'data',\n datetime: 'dateTime',\n default: 'default',\n defaultchecked: 'defaultChecked',\n defaultvalue: 'defaultValue',\n defer: 'defer',\n dir: 'dir',\n disabled: 'disabled',\n disablepictureinpicture: 'disablePictureInPicture',\n download: 'download',\n draggable: 'draggable',\n enctype: 'encType',\n for: 'htmlFor',\n form: 'form',\n formmethod: 'formMethod',\n formaction: 'formAction',\n formenctype: 'formEncType',\n formnovalidate: 'formNoValidate',\n formtarget: 'formTarget',\n frameborder: 'frameBorder',\n headers: 'headers',\n height: 'height',\n hidden: 'hidden',\n high: 'high',\n href: 'href',\n hreflang: 'hrefLang',\n htmlfor: 'htmlFor',\n httpequiv: 'httpEquiv',\n 'http-equiv': 'httpEquiv',\n icon: 'icon',\n id: 'id',\n innerhtml: 'innerHTML',\n inputmode: 'inputMode',\n integrity: 'integrity',\n is: 'is',\n itemid: 'itemID',\n itemprop: 'itemProp',\n itemref: 'itemRef',\n itemscope: 'itemScope',\n itemtype: 'itemType',\n keyparams: 'keyParams',\n keytype: 'keyType',\n kind: 'kind',\n label: 'label',\n lang: 'lang',\n list: 'list',\n loop: 'loop',\n low: 'low',\n manifest: 'manifest',\n marginwidth: 'marginWidth',\n marginheight: 'marginHeight',\n max: 'max',\n maxlength: 'maxLength',\n media: 'media',\n mediagroup: 'mediaGroup',\n method: 'method',\n min: 'min',\n minlength: 'minLength',\n multiple: 'multiple',\n muted: 'muted',\n name: 'name',\n nomodule: 'noModule',\n nonce: 'nonce',\n novalidate: 'noValidate',\n open: 'open',\n optimum: 'optimum',\n pattern: 'pattern',\n placeholder: 'placeholder',\n playsinline: 'playsInline',\n poster: 'poster',\n preload: 'preload',\n profile: 'profile',\n radiogroup: 'radioGroup',\n readonly: 'readOnly',\n referrerpolicy: 'referrerPolicy',\n rel: 'rel',\n required: 'required',\n reversed: 'reversed',\n role: 'role',\n rows: 'rows',\n rowspan: 'rowSpan',\n sandbox: 'sandbox',\n scope: 'scope',\n scoped: 'scoped',\n scrolling: 'scrolling',\n seamless: 'seamless',\n selected: 'selected',\n shape: 'shape',\n size: 'size',\n sizes: 'sizes',\n span: 'span',\n spellcheck: 'spellCheck',\n src: 'src',\n srcdoc: 'srcDoc',\n srclang: 'srcLang',\n srcset: 'srcSet',\n start: 'start',\n step: 'step',\n style: 'style',\n summary: 'summary',\n tabindex: 'tabIndex',\n target: 'target',\n title: 'title',\n type: 'type',\n usemap: 'useMap',\n value: 'value',\n width: 'width',\n wmode: 'wmode',\n wrap: 'wrap',\n // SVG\n about: 'about',\n accentheight: 'accentHeight',\n 'accent-height': 'accentHeight',\n accumulate: 'accumulate',\n additive: 'additive',\n alignmentbaseline: 'alignmentBaseline',\n 'alignment-baseline': 'alignmentBaseline',\n allowreorder: 'allowReorder',\n alphabetic: 'alphabetic',\n amplitude: 'amplitude',\n arabicform: 'arabicForm',\n 'arabic-form': 'arabicForm',\n ascent: 'ascent',\n attributename: 'attributeName',\n attributetype: 'attributeType',\n autoreverse: 'autoReverse',\n azimuth: 'azimuth',\n basefrequency: 'baseFrequency',\n baselineshift: 'baselineShift',\n 'baseline-shift': 'baselineShift',\n baseprofile: 'baseProfile',\n bbox: 'bbox',\n begin: 'begin',\n bias: 'bias',\n by: 'by',\n calcmode: 'calcMode',\n capheight: 'capHeight',\n 'cap-height': 'capHeight',\n clip: 'clip',\n clippath: 'clipPath',\n 'clip-path': 'clipPath',\n clippathunits: 'clipPathUnits',\n cliprule: 'clipRule',\n 'clip-rule': 'clipRule',\n color: 'color',\n colorinterpolation: 'colorInterpolation',\n 'color-interpolation': 'colorInterpolation',\n colorinterpolationfilters: 'colorInterpolationFilters',\n 'color-interpolation-filters': 'colorInterpolationFilters',\n colorprofile: 'colorProfile',\n 'color-profile': 'colorProfile',\n colorrendering: 'colorRendering',\n 'color-rendering': 'colorRendering',\n contentscripttype: 'contentScriptType',\n contentstyletype: 'contentStyleType',\n cursor: 'cursor',\n cx: 'cx',\n cy: 'cy',\n d: 'd',\n datatype: 'datatype',\n decelerate: 'decelerate',\n descent: 'descent',\n diffuseconstant: 'diffuseConstant',\n direction: 'direction',\n display: 'display',\n divisor: 'divisor',\n dominantbaseline: 'dominantBaseline',\n 'dominant-baseline': 'dominantBaseline',\n dur: 'dur',\n dx: 'dx',\n dy: 'dy',\n edgemode: 'edgeMode',\n elevation: 'elevation',\n enablebackground: 'enableBackground',\n 'enable-background': 'enableBackground',\n end: 'end',\n exponent: 'exponent',\n externalresourcesrequired: 'externalResourcesRequired',\n fill: 'fill',\n fillopacity: 'fillOpacity',\n 'fill-opacity': 'fillOpacity',\n fillrule: 'fillRule',\n 'fill-rule': 'fillRule',\n filter: 'filter',\n filterres: 'filterRes',\n filterunits: 'filterUnits',\n floodopacity: 'floodOpacity',\n 'flood-opacity': 'floodOpacity',\n floodcolor: 'floodColor',\n 'flood-color': 'floodColor',\n focusable: 'focusable',\n fontfamily: 'fontFamily',\n 'font-family': 'fontFamily',\n fontsize: 'fontSize',\n 'font-size': 'fontSize',\n fontsizeadjust: 'fontSizeAdjust',\n 'font-size-adjust': 'fontSizeAdjust',\n fontstretch: 'fontStretch',\n 'font-stretch': 'fontStretch',\n fontstyle: 'fontStyle',\n 'font-style': 'fontStyle',\n fontvariant: 'fontVariant',\n 'font-variant': 'fontVariant',\n fontweight: 'fontWeight',\n 'font-weight': 'fontWeight',\n format: 'format',\n from: 'from',\n fx: 'fx',\n fy: 'fy',\n g1: 'g1',\n g2: 'g2',\n glyphname: 'glyphName',\n 'glyph-name': 'glyphName',\n glyphorientationhorizontal: 'glyphOrientationHorizontal',\n 'glyph-orientation-horizontal': 'glyphOrientationHorizontal',\n glyphorientationvertical: 'glyphOrientationVertical',\n 'glyph-orientation-vertical': 'glyphOrientationVertical',\n glyphref: 'glyphRef',\n gradienttransform: 'gradientTransform',\n gradientunits: 'gradientUnits',\n hanging: 'hanging',\n horizadvx: 'horizAdvX',\n 'horiz-adv-x': 'horizAdvX',\n horizoriginx: 'horizOriginX',\n 'horiz-origin-x': 'horizOriginX',\n ideographic: 'ideographic',\n imagerendering: 'imageRendering',\n 'image-rendering': 'imageRendering',\n in2: 'in2',\n in: 'in',\n inlist: 'inlist',\n intercept: 'intercept',\n k1: 'k1',\n k2: 'k2',\n k3: 'k3',\n k4: 'k4',\n k: 'k',\n kernelmatrix: 'kernelMatrix',\n kernelunitlength: 'kernelUnitLength',\n kerning: 'kerning',\n keypoints: 'keyPoints',\n keysplines: 'keySplines',\n keytimes: 'keyTimes',\n lengthadjust: 'lengthAdjust',\n letterspacing: 'letterSpacing',\n 'letter-spacing': 'letterSpacing',\n lightingcolor: 'lightingColor',\n 'lighting-color': 'lightingColor',\n limitingconeangle: 'limitingConeAngle',\n local: 'local',\n markerend: 'markerEnd',\n 'marker-end': 'markerEnd',\n markerheight: 'markerHeight',\n markermid: 'markerMid',\n 'marker-mid': 'markerMid',\n markerstart: 'markerStart',\n 'marker-start': 'markerStart',\n markerunits: 'markerUnits',\n markerwidth: 'markerWidth',\n mask: 'mask',\n maskcontentunits: 'maskContentUnits',\n maskunits: 'maskUnits',\n mathematical: 'mathematical',\n mode: 'mode',\n numoctaves: 'numOctaves',\n offset: 'offset',\n opacity: 'opacity',\n operator: 'operator',\n order: 'order',\n orient: 'orient',\n orientation: 'orientation',\n origin: 'origin',\n overflow: 'overflow',\n overlineposition: 'overlinePosition',\n 'overline-position': 'overlinePosition',\n overlinethickness: 'overlineThickness',\n 'overline-thickness': 'overlineThickness',\n paintorder: 'paintOrder',\n 'paint-order': 'paintOrder',\n panose1: 'panose1',\n 'panose-1': 'panose1',\n pathlength: 'pathLength',\n patterncontentunits: 'patternContentUnits',\n patterntransform: 'patternTransform',\n patternunits: 'patternUnits',\n pointerevents: 'pointerEvents',\n 'pointer-events': 'pointerEvents',\n points: 'points',\n pointsatx: 'pointsAtX',\n pointsaty: 'pointsAtY',\n pointsatz: 'pointsAtZ',\n prefix: 'prefix',\n preservealpha: 'preserveAlpha',\n preserveaspectratio: 'preserveAspectRatio',\n primitiveunits: 'primitiveUnits',\n property: 'property',\n r: 'r',\n radius: 'radius',\n refx: 'refX',\n refy: 'refY',\n renderingintent: 'renderingIntent',\n 'rendering-intent': 'renderingIntent',\n repeatcount: 'repeatCount',\n repeatdur: 'repeatDur',\n requiredextensions: 'requiredExtensions',\n requiredfeatures: 'requiredFeatures',\n resource: 'resource',\n restart: 'restart',\n result: 'result',\n results: 'results',\n rotate: 'rotate',\n rx: 'rx',\n ry: 'ry',\n scale: 'scale',\n security: 'security',\n seed: 'seed',\n shaperendering: 'shapeRendering',\n 'shape-rendering': 'shapeRendering',\n slope: 'slope',\n spacing: 'spacing',\n specularconstant: 'specularConstant',\n specularexponent: 'specularExponent',\n speed: 'speed',\n spreadmethod: 'spreadMethod',\n startoffset: 'startOffset',\n stddeviation: 'stdDeviation',\n stemh: 'stemh',\n stemv: 'stemv',\n stitchtiles: 'stitchTiles',\n stopcolor: 'stopColor',\n 'stop-color': 'stopColor',\n stopopacity: 'stopOpacity',\n 'stop-opacity': 'stopOpacity',\n strikethroughposition: 'strikethroughPosition',\n 'strikethrough-position': 'strikethroughPosition',\n strikethroughthickness: 'strikethroughThickness',\n 'strikethrough-thickness': 'strikethroughThickness',\n string: 'string',\n stroke: 'stroke',\n strokedasharray: 'strokeDasharray',\n 'stroke-dasharray': 'strokeDasharray',\n strokedashoffset: 'strokeDashoffset',\n 'stroke-dashoffset': 'strokeDashoffset',\n strokelinecap: 'strokeLinecap',\n 'stroke-linecap': 'strokeLinecap',\n strokelinejoin: 'strokeLinejoin',\n 'stroke-linejoin': 'strokeLinejoin',\n strokemiterlimit: 'strokeMiterlimit',\n 'stroke-miterlimit': 'strokeMiterlimit',\n strokewidth: 'strokeWidth',\n 'stroke-width': 'strokeWidth',\n strokeopacity: 'strokeOpacity',\n 'stroke-opacity': 'strokeOpacity',\n suppresscontenteditablewarning: 'suppressContentEditableWarning',\n suppresshydrationwarning: 'suppressHydrationWarning',\n surfacescale: 'surfaceScale',\n systemlanguage: 'systemLanguage',\n tablevalues: 'tableValues',\n targetx: 'targetX',\n targety: 'targetY',\n textanchor: 'textAnchor',\n 'text-anchor': 'textAnchor',\n textdecoration: 'textDecoration',\n 'text-decoration': 'textDecoration',\n textlength: 'textLength',\n textrendering: 'textRendering',\n 'text-rendering': 'textRendering',\n to: 'to',\n transform: 'transform',\n typeof: 'typeof',\n u1: 'u1',\n u2: 'u2',\n underlineposition: 'underlinePosition',\n 'underline-position': 'underlinePosition',\n underlinethickness: 'underlineThickness',\n 'underline-thickness': 'underlineThickness',\n unicode: 'unicode',\n unicodebidi: 'unicodeBidi',\n 'unicode-bidi': 'unicodeBidi',\n unicoderange: 'unicodeRange',\n 'unicode-range': 'unicodeRange',\n unitsperem: 'unitsPerEm',\n 'units-per-em': 'unitsPerEm',\n unselectable: 'unselectable',\n valphabetic: 'vAlphabetic',\n 'v-alphabetic': 'vAlphabetic',\n values: 'values',\n vectoreffect: 'vectorEffect',\n 'vector-effect': 'vectorEffect',\n version: 'version',\n vertadvy: 'vertAdvY',\n 'vert-adv-y': 'vertAdvY',\n vertoriginx: 'vertOriginX',\n 'vert-origin-x': 'vertOriginX',\n vertoriginy: 'vertOriginY',\n 'vert-origin-y': 'vertOriginY',\n vhanging: 'vHanging',\n 'v-hanging': 'vHanging',\n videographic: 'vIdeographic',\n 'v-ideographic': 'vIdeographic',\n viewbox: 'viewBox',\n viewtarget: 'viewTarget',\n visibility: 'visibility',\n vmathematical: 'vMathematical',\n 'v-mathematical': 'vMathematical',\n vocab: 'vocab',\n widths: 'widths',\n wordspacing: 'wordSpacing',\n 'word-spacing': 'wordSpacing',\n writingmode: 'writingMode',\n 'writing-mode': 'writingMode',\n x1: 'x1',\n x2: 'x2',\n x: 'x',\n xchannelselector: 'xChannelSelector',\n xheight: 'xHeight',\n 'x-height': 'xHeight',\n xlinkactuate: 'xlinkActuate',\n 'xlink:actuate': 'xlinkActuate',\n xlinkarcrole: 'xlinkArcrole',\n 'xlink:arcrole': 'xlinkArcrole',\n xlinkhref: 'xlinkHref',\n 'xlink:href': 'xlinkHref',\n xlinkrole: 'xlinkRole',\n 'xlink:role': 'xlinkRole',\n xlinkshow: 'xlinkShow',\n 'xlink:show': 'xlinkShow',\n xlinktitle: 'xlinkTitle',\n 'xlink:title': 'xlinkTitle',\n xlinktype: 'xlinkType',\n 'xlink:type': 'xlinkType',\n xmlbase: 'xmlBase',\n 'xml:base': 'xmlBase',\n xmllang: 'xmlLang',\n 'xml:lang': 'xmlLang',\n xmlns: 'xmlns',\n 'xml:space': 'xmlSpace',\n xmlnsxlink: 'xmlnsXlink',\n 'xmlns:xlink': 'xmlnsXlink',\n xmlspace: 'xmlSpace',\n y1: 'y1',\n y2: 'y2',\n y: 'y',\n ychannelselector: 'yChannelSelector',\n z: 'z',\n zoomandpan: 'zoomAndPan'\n};\n\nvar ariaProperties = {\n 'aria-current': 0,\n // state\n 'aria-details': 0,\n 'aria-disabled': 0,\n // state\n 'aria-hidden': 0,\n // state\n 'aria-invalid': 0,\n // state\n 'aria-keyshortcuts': 0,\n 'aria-label': 0,\n 'aria-roledescription': 0,\n // Widget Attributes\n 'aria-autocomplete': 0,\n 'aria-checked': 0,\n 'aria-expanded': 0,\n 'aria-haspopup': 0,\n 'aria-level': 0,\n 'aria-modal': 0,\n 'aria-multiline': 0,\n 'aria-multiselectable': 0,\n 'aria-orientation': 0,\n 'aria-placeholder': 0,\n 'aria-pressed': 0,\n 'aria-readonly': 0,\n 'aria-required': 0,\n 'aria-selected': 0,\n 'aria-sort': 0,\n 'aria-valuemax': 0,\n 'aria-valuemin': 0,\n 'aria-valuenow': 0,\n 'aria-valuetext': 0,\n // Live Region Attributes\n 'aria-atomic': 0,\n 'aria-busy': 0,\n 'aria-live': 0,\n 'aria-relevant': 0,\n // Drag-and-Drop Attributes\n 'aria-dropeffect': 0,\n 'aria-grabbed': 0,\n // Relationship Attributes\n 'aria-activedescendant': 0,\n 'aria-colcount': 0,\n 'aria-colindex': 0,\n 'aria-colspan': 0,\n 'aria-controls': 0,\n 'aria-describedby': 0,\n 'aria-errormessage': 0,\n 'aria-flowto': 0,\n 'aria-labelledby': 0,\n 'aria-owns': 0,\n 'aria-posinset': 0,\n 'aria-rowcount': 0,\n 'aria-rowindex': 0,\n 'aria-rowspan': 0,\n 'aria-setsize': 0\n};\n\nvar warnedProperties = {};\nvar rARIA = new RegExp('^(aria)-[' + ATTRIBUTE_NAME_CHAR + ']*$');\nvar rARIACamel = new RegExp('^(aria)[A-Z][' + ATTRIBUTE_NAME_CHAR + ']*$');\nvar hasOwnProperty$1 = Object.prototype.hasOwnProperty;\n\nfunction validateProperty(tagName, name) {\n {\n if (hasOwnProperty$1.call(warnedProperties, name) && warnedProperties[name]) {\n return true;\n }\n\n if (rARIACamel.test(name)) {\n var ariaName = 'aria-' + name.slice(4).toLowerCase();\n var correctName = ariaProperties.hasOwnProperty(ariaName) ? ariaName : null; // If this is an aria-* attribute, but is not listed in the known DOM\n // DOM properties, then it is an invalid aria-* attribute.\n\n if (correctName == null) {\n error('Invalid ARIA attribute `%s`. ARIA attributes follow the pattern aria-* and must be lowercase.', name);\n\n warnedProperties[name] = true;\n return true;\n } // aria-* attributes should be lowercase; suggest the lowercase version.\n\n\n if (name !== correctName) {\n error('Invalid ARIA attribute `%s`. Did you mean `%s`?', name, correctName);\n\n warnedProperties[name] = true;\n return true;\n }\n }\n\n if (rARIA.test(name)) {\n var lowerCasedName = name.toLowerCase();\n var standardName = ariaProperties.hasOwnProperty(lowerCasedName) ? lowerCasedName : null; // If this is an aria-* attribute, but is not listed in the known DOM\n // DOM properties, then it is an invalid aria-* attribute.\n\n if (standardName == null) {\n warnedProperties[name] = true;\n return false;\n } // aria-* attributes should be lowercase; suggest the lowercase version.\n\n\n if (name !== standardName) {\n error('Unknown ARIA attribute `%s`. Did you mean `%s`?', name, standardName);\n\n warnedProperties[name] = true;\n return true;\n }\n }\n }\n\n return true;\n}\n\nfunction warnInvalidARIAProps(type, props) {\n {\n var invalidProps = [];\n\n for (var key in props) {\n var isValid = validateProperty(type, key);\n\n if (!isValid) {\n invalidProps.push(key);\n }\n }\n\n var unknownPropString = invalidProps.map(function (prop) {\n return '`' + prop + '`';\n }).join(', ');\n\n if (invalidProps.length === 1) {\n error('Invalid aria prop %s on <%s> tag. ' + 'For details, see https://fb.me/invalid-aria-prop', unknownPropString, type);\n } else if (invalidProps.length > 1) {\n error('Invalid aria props %s on <%s> tag. ' + 'For details, see https://fb.me/invalid-aria-prop', unknownPropString, type);\n }\n }\n}\n\nfunction validateProperties(type, props) {\n if (isCustomComponent(type, props)) {\n return;\n }\n\n warnInvalidARIAProps(type, props);\n}\n\nvar didWarnValueNull = false;\nfunction validateProperties$1(type, props) {\n {\n if (type !== 'input' && type !== 'textarea' && type !== 'select') {\n return;\n }\n\n if (props != null && props.value === null && !didWarnValueNull) {\n didWarnValueNull = true;\n\n if (type === 'select' && props.multiple) {\n error('`value` prop on `%s` should not be null. ' + 'Consider using an empty array when `multiple` is set to `true` ' + 'to clear the component or `undefined` for uncontrolled components.', type);\n } else {\n error('`value` prop on `%s` should not be null. ' + 'Consider using an empty string to clear the component or `undefined` ' + 'for uncontrolled components.', type);\n }\n }\n }\n}\n\nvar validateProperty$1 = function () {};\n\n{\n var warnedProperties$1 = {};\n var _hasOwnProperty = Object.prototype.hasOwnProperty;\n var EVENT_NAME_REGEX = /^on./;\n var INVALID_EVENT_NAME_REGEX = /^on[^A-Z]/;\n var rARIA$1 = new RegExp('^(aria)-[' + ATTRIBUTE_NAME_CHAR + ']*$');\n var rARIACamel$1 = new RegExp('^(aria)[A-Z][' + ATTRIBUTE_NAME_CHAR + ']*$');\n\n validateProperty$1 = function (tagName, name, value, canUseEventSystem) {\n if (_hasOwnProperty.call(warnedProperties$1, name) && warnedProperties$1[name]) {\n return true;\n }\n\n var lowerCasedName = name.toLowerCase();\n\n if (lowerCasedName === 'onfocusin' || lowerCasedName === 'onfocusout') {\n error('React uses onFocus and onBlur instead of onFocusIn and onFocusOut. ' + 'All React events are normalized to bubble, so onFocusIn and onFocusOut ' + 'are not needed/supported by React.');\n\n warnedProperties$1[name] = true;\n return true;\n } // We can't rely on the event system being injected on the server.\n\n\n if (canUseEventSystem) {\n if (registrationNameModules.hasOwnProperty(name)) {\n return true;\n }\n\n var registrationName = possibleRegistrationNames.hasOwnProperty(lowerCasedName) ? possibleRegistrationNames[lowerCasedName] : null;\n\n if (registrationName != null) {\n error('Invalid event handler property `%s`. Did you mean `%s`?', name, registrationName);\n\n warnedProperties$1[name] = true;\n return true;\n }\n\n if (EVENT_NAME_REGEX.test(name)) {\n error('Unknown event handler property `%s`. It will be ignored.', name);\n\n warnedProperties$1[name] = true;\n return true;\n }\n } else if (EVENT_NAME_REGEX.test(name)) {\n // If no event plugins have been injected, we are in a server environment.\n // So we can't tell if the event name is correct for sure, but we can filter\n // out known bad ones like `onclick`. We can't suggest a specific replacement though.\n if (INVALID_EVENT_NAME_REGEX.test(name)) {\n error('Invalid event handler property `%s`. ' + 'React events use the camelCase naming convention, for example `onClick`.', name);\n }\n\n warnedProperties$1[name] = true;\n return true;\n } // Let the ARIA attribute hook validate ARIA attributes\n\n\n if (rARIA$1.test(name) || rARIACamel$1.test(name)) {\n return true;\n }\n\n if (lowerCasedName === 'innerhtml') {\n error('Directly setting property `innerHTML` is not permitted. ' + 'For more information, lookup documentation on `dangerouslySetInnerHTML`.');\n\n warnedProperties$1[name] = true;\n return true;\n }\n\n if (lowerCasedName === 'aria') {\n error('The `aria` attribute is reserved for future use in React. ' + 'Pass individual `aria-` attributes instead.');\n\n warnedProperties$1[name] = true;\n return true;\n }\n\n if (lowerCasedName === 'is' && value !== null && value !== undefined && typeof value !== 'string') {\n error('Received a `%s` for a string attribute `is`. If this is expected, cast ' + 'the value to a string.', typeof value);\n\n warnedProperties$1[name] = true;\n return true;\n }\n\n if (typeof value === 'number' && isNaN(value)) {\n error('Received NaN for the `%s` attribute. If this is expected, cast ' + 'the value to a string.', name);\n\n warnedProperties$1[name] = true;\n return true;\n }\n\n var propertyInfo = getPropertyInfo(name);\n var isReserved = propertyInfo !== null && propertyInfo.type === RESERVED; // Known attributes should match the casing specified in the property config.\n\n if (possibleStandardNames.hasOwnProperty(lowerCasedName)) {\n var standardName = possibleStandardNames[lowerCasedName];\n\n if (standardName !== name) {\n error('Invalid DOM property `%s`. Did you mean `%s`?', name, standardName);\n\n warnedProperties$1[name] = true;\n return true;\n }\n } else if (!isReserved && name !== lowerCasedName) {\n // Unknown attributes should have lowercase casing since that's how they\n // will be cased anyway with server rendering.\n error('React does not recognize the `%s` prop on a DOM element. If you ' + 'intentionally want it to appear in the DOM as a custom ' + 'attribute, spell it as lowercase `%s` instead. ' + 'If you accidentally passed it from a parent component, remove ' + 'it from the DOM element.', name, lowerCasedName);\n\n warnedProperties$1[name] = true;\n return true;\n }\n\n if (typeof value === 'boolean' && shouldRemoveAttributeWithWarning(name, value, propertyInfo, false)) {\n if (value) {\n error('Received `%s` for a non-boolean attribute `%s`.\\n\\n' + 'If you want to write it to the DOM, pass a string instead: ' + '%s=\"%s\" or %s={value.toString()}.', value, name, name, value, name);\n } else {\n error('Received `%s` for a non-boolean attribute `%s`.\\n\\n' + 'If you want to write it to the DOM, pass a string instead: ' + '%s=\"%s\" or %s={value.toString()}.\\n\\n' + 'If you used to conditionally omit it with %s={condition && value}, ' + 'pass %s={condition ? value : undefined} instead.', value, name, name, value, name, name, name);\n }\n\n warnedProperties$1[name] = true;\n return true;\n } // Now that we've validated casing, do not validate\n // data types for reserved props\n\n\n if (isReserved) {\n return true;\n } // Warn when a known attribute is a bad type\n\n\n if (shouldRemoveAttributeWithWarning(name, value, propertyInfo, false)) {\n warnedProperties$1[name] = true;\n return false;\n } // Warn when passing the strings 'false' or 'true' into a boolean prop\n\n\n if ((value === 'false' || value === 'true') && propertyInfo !== null && propertyInfo.type === BOOLEAN) {\n error('Received the string `%s` for the boolean attribute `%s`. ' + '%s ' + 'Did you mean %s={%s}?', value, name, value === 'false' ? 'The browser will interpret it as a truthy value.' : 'Although this works, it will not work as expected if you pass the string \"false\".', name, value);\n\n warnedProperties$1[name] = true;\n return true;\n }\n\n return true;\n };\n}\n\nvar warnUnknownProperties = function (type, props, canUseEventSystem) {\n {\n var unknownProps = [];\n\n for (var key in props) {\n var isValid = validateProperty$1(type, key, props[key], canUseEventSystem);\n\n if (!isValid) {\n unknownProps.push(key);\n }\n }\n\n var unknownPropString = unknownProps.map(function (prop) {\n return '`' + prop + '`';\n }).join(', ');\n\n if (unknownProps.length === 1) {\n error('Invalid value for prop %s on <%s> tag. Either remove it from the element, ' + 'or pass a string or number value to keep it in the DOM. ' + 'For details, see https://fb.me/react-attribute-behavior', unknownPropString, type);\n } else if (unknownProps.length > 1) {\n error('Invalid values for props %s on <%s> tag. Either remove them from the element, ' + 'or pass a string or number value to keep them in the DOM. ' + 'For details, see https://fb.me/react-attribute-behavior', unknownPropString, type);\n }\n }\n};\n\nfunction validateProperties$2(type, props, canUseEventSystem) {\n if (isCustomComponent(type, props)) {\n return;\n }\n\n warnUnknownProperties(type, props, canUseEventSystem);\n}\n\nvar didWarnInvalidHydration = false;\nvar DANGEROUSLY_SET_INNER_HTML = 'dangerouslySetInnerHTML';\nvar SUPPRESS_CONTENT_EDITABLE_WARNING = 'suppressContentEditableWarning';\nvar SUPPRESS_HYDRATION_WARNING = 'suppressHydrationWarning';\nvar AUTOFOCUS = 'autoFocus';\nvar CHILDREN = 'children';\nvar STYLE = 'style';\nvar HTML$1 = '__html';\nvar HTML_NAMESPACE$1 = Namespaces.html;\nvar warnedUnknownTags;\nvar suppressHydrationWarning;\nvar validatePropertiesInDevelopment;\nvar warnForTextDifference;\nvar warnForPropDifference;\nvar warnForExtraAttributes;\nvar warnForInvalidEventListener;\nvar canDiffStyleForHydrationWarning;\nvar normalizeMarkupForTextOrAttribute;\nvar normalizeHTML;\n\n{\n warnedUnknownTags = {\n // Chrome is the only major browser not shipping <time>. But as of July\n // 2017 it intends to ship it due to widespread usage. We intentionally\n // *don't* warn for <time> even if it's unrecognized by Chrome because\n // it soon will be, and many apps have been using it anyway.\n time: true,\n // There are working polyfills for <dialog>. Let people use it.\n dialog: true,\n // Electron ships a custom <webview> tag to display external web content in\n // an isolated frame and process.\n // This tag is not present in non Electron environments such as JSDom which\n // is often used for testing purposes.\n // @see https://electronjs.org/docs/api/webview-tag\n webview: true\n };\n\n validatePropertiesInDevelopment = function (type, props) {\n validateProperties(type, props);\n validateProperties$1(type, props);\n validateProperties$2(type, props,\n /* canUseEventSystem */\n true);\n }; // IE 11 parses & normalizes the style attribute as opposed to other\n // browsers. It adds spaces and sorts the properties in some\n // non-alphabetical order. Handling that would require sorting CSS\n // properties in the client & server versions or applying\n // `expectedStyle` to a temporary DOM node to read its `style` attribute\n // normalized. Since it only affects IE, we're skipping style warnings\n // in that browser completely in favor of doing all that work.\n // See https://github.com/facebook/react/issues/11807\n\n\n canDiffStyleForHydrationWarning = canUseDOM && !document.documentMode; // HTML parsing normalizes CR and CRLF to LF.\n // It also can turn \\u0000 into \\uFFFD inside attributes.\n // https://www.w3.org/TR/html5/single-page.html#preprocessing-the-input-stream\n // If we have a mismatch, it might be caused by that.\n // We will still patch up in this case but not fire the warning.\n\n var NORMALIZE_NEWLINES_REGEX = /\\r\\n?/g;\n var NORMALIZE_NULL_AND_REPLACEMENT_REGEX = /\\u0000|\\uFFFD/g;\n\n normalizeMarkupForTextOrAttribute = function (markup) {\n var markupString = typeof markup === 'string' ? markup : '' + markup;\n return markupString.replace(NORMALIZE_NEWLINES_REGEX, '\\n').replace(NORMALIZE_NULL_AND_REPLACEMENT_REGEX, '');\n };\n\n warnForTextDifference = function (serverText, clientText) {\n if (didWarnInvalidHydration) {\n return;\n }\n\n var normalizedClientText = normalizeMarkupForTextOrAttribute(clientText);\n var normalizedServerText = normalizeMarkupForTextOrAttribute(serverText);\n\n if (normalizedServerText === normalizedClientText) {\n return;\n }\n\n didWarnInvalidHydration = true;\n\n error('Text content did not match. Server: \"%s\" Client: \"%s\"', normalizedServerText, normalizedClientText);\n };\n\n warnForPropDifference = function (propName, serverValue, clientValue) {\n if (didWarnInvalidHydration) {\n return;\n }\n\n var normalizedClientValue = normalizeMarkupForTextOrAttribute(clientValue);\n var normalizedServerValue = normalizeMarkupForTextOrAttribute(serverValue);\n\n if (normalizedServerValue === normalizedClientValue) {\n return;\n }\n\n didWarnInvalidHydration = true;\n\n error('Prop `%s` did not match. Server: %s Client: %s', propName, JSON.stringify(normalizedServerValue), JSON.stringify(normalizedClientValue));\n };\n\n warnForExtraAttributes = function (attributeNames) {\n if (didWarnInvalidHydration) {\n return;\n }\n\n didWarnInvalidHydration = true;\n var names = [];\n attributeNames.forEach(function (name) {\n names.push(name);\n });\n\n error('Extra attributes from the server: %s', names);\n };\n\n warnForInvalidEventListener = function (registrationName, listener) {\n if (listener === false) {\n error('Expected `%s` listener to be a function, instead got `false`.\\n\\n' + 'If you used to conditionally omit it with %s={condition && value}, ' + 'pass %s={condition ? value : undefined} instead.', registrationName, registrationName, registrationName);\n } else {\n error('Expected `%s` listener to be a function, instead got a value of `%s` type.', registrationName, typeof listener);\n }\n }; // Parse the HTML and read it back to normalize the HTML string so that it\n // can be used for comparison.\n\n\n normalizeHTML = function (parent, html) {\n // We could have created a separate document here to avoid\n // re-initializing custom elements if they exist. But this breaks\n // how <noscript> is being handled. So we use the same document.\n // See the discussion in https://github.com/facebook/react/pull/11157.\n var testElement = parent.namespaceURI === HTML_NAMESPACE$1 ? parent.ownerDocument.createElement(parent.tagName) : parent.ownerDocument.createElementNS(parent.namespaceURI, parent.tagName);\n testElement.innerHTML = html;\n return testElement.innerHTML;\n };\n}\n\nfunction ensureListeningTo(rootContainerElement, registrationName) {\n var isDocumentOrFragment = rootContainerElement.nodeType === DOCUMENT_NODE || rootContainerElement.nodeType === DOCUMENT_FRAGMENT_NODE;\n var doc = isDocumentOrFragment ? rootContainerElement : rootContainerElement.ownerDocument;\n legacyListenToEvent(registrationName, doc);\n}\n\nfunction getOwnerDocumentFromRootContainer(rootContainerElement) {\n return rootContainerElement.nodeType === DOCUMENT_NODE ? rootContainerElement : rootContainerElement.ownerDocument;\n}\n\nfunction noop() {}\n\nfunction trapClickOnNonInteractiveElement(node) {\n // Mobile Safari does not fire properly bubble click events on\n // non-interactive elements, which means delegated click listeners do not\n // fire. The workaround for this bug involves attaching an empty click\n // listener on the target node.\n // http://www.quirksmode.org/blog/archives/2010/09/click_event_del.html\n // Just set it using the onclick property so that we don't have to manage any\n // bookkeeping for it. Not sure if we need to clear it when the listener is\n // removed.\n // TODO: Only do this for the relevant Safaris maybe?\n node.onclick = noop;\n}\n\nfunction setInitialDOMProperties(tag, domElement, rootContainerElement, nextProps, isCustomComponentTag) {\n for (var propKey in nextProps) {\n if (!nextProps.hasOwnProperty(propKey)) {\n continue;\n }\n\n var nextProp = nextProps[propKey];\n\n if (propKey === STYLE) {\n {\n if (nextProp) {\n // Freeze the next style object so that we can assume it won't be\n // mutated. We have already warned for this in the past.\n Object.freeze(nextProp);\n }\n } // Relies on `updateStylesByID` not mutating `styleUpdates`.\n\n\n setValueForStyles(domElement, nextProp);\n } else if (propKey === DANGEROUSLY_SET_INNER_HTML) {\n var nextHtml = nextProp ? nextProp[HTML$1] : undefined;\n\n if (nextHtml != null) {\n setInnerHTML(domElement, nextHtml);\n }\n } else if (propKey === CHILDREN) {\n if (typeof nextProp === 'string') {\n // Avoid setting initial textContent when the text is empty. In IE11 setting\n // textContent on a <textarea> will cause the placeholder to not\n // show within the <textarea> until it has been focused and blurred again.\n // https://github.com/facebook/react/issues/6731#issuecomment-254874553\n var canSetTextContent = tag !== 'textarea' || nextProp !== '';\n\n if (canSetTextContent) {\n setTextContent(domElement, nextProp);\n }\n } else if (typeof nextProp === 'number') {\n setTextContent(domElement, '' + nextProp);\n }\n } else if ( propKey === SUPPRESS_CONTENT_EDITABLE_WARNING || propKey === SUPPRESS_HYDRATION_WARNING) ; else if (propKey === AUTOFOCUS) ; else if (registrationNameModules.hasOwnProperty(propKey)) {\n if (nextProp != null) {\n if ( typeof nextProp !== 'function') {\n warnForInvalidEventListener(propKey, nextProp);\n }\n\n ensureListeningTo(rootContainerElement, propKey);\n }\n } else if (nextProp != null) {\n setValueForProperty(domElement, propKey, nextProp, isCustomComponentTag);\n }\n }\n}\n\nfunction updateDOMProperties(domElement, updatePayload, wasCustomComponentTag, isCustomComponentTag) {\n // TODO: Handle wasCustomComponentTag\n for (var i = 0; i < updatePayload.length; i += 2) {\n var propKey = updatePayload[i];\n var propValue = updatePayload[i + 1];\n\n if (propKey === STYLE) {\n setValueForStyles(domElement, propValue);\n } else if (propKey === DANGEROUSLY_SET_INNER_HTML) {\n setInnerHTML(domElement, propValue);\n } else if (propKey === CHILDREN) {\n setTextContent(domElement, propValue);\n } else {\n setValueForProperty(domElement, propKey, propValue, isCustomComponentTag);\n }\n }\n}\n\nfunction createElement(type, props, rootContainerElement, parentNamespace) {\n var isCustomComponentTag; // We create tags in the namespace of their parent container, except HTML\n // tags get no namespace.\n\n var ownerDocument = getOwnerDocumentFromRootContainer(rootContainerElement);\n var domElement;\n var namespaceURI = parentNamespace;\n\n if (namespaceURI === HTML_NAMESPACE$1) {\n namespaceURI = getIntrinsicNamespace(type);\n }\n\n if (namespaceURI === HTML_NAMESPACE$1) {\n {\n isCustomComponentTag = isCustomComponent(type, props); // Should this check be gated by parent namespace? Not sure we want to\n // allow <SVG> or <mATH>.\n\n if (!isCustomComponentTag && type !== type.toLowerCase()) {\n error('<%s /> is using incorrect casing. ' + 'Use PascalCase for React components, ' + 'or lowercase for HTML elements.', type);\n }\n }\n\n if (type === 'script') {\n // Create the script via .innerHTML so its \"parser-inserted\" flag is\n // set to true and it does not execute\n var div = ownerDocument.createElement('div');\n\n div.innerHTML = '<script><' + '/script>'; // eslint-disable-line\n // This is guaranteed to yield a script element.\n\n var firstChild = div.firstChild;\n domElement = div.removeChild(firstChild);\n } else if (typeof props.is === 'string') {\n // $FlowIssue `createElement` should be updated for Web Components\n domElement = ownerDocument.createElement(type, {\n is: props.is\n });\n } else {\n // Separate else branch instead of using `props.is || undefined` above because of a Firefox bug.\n // See discussion in https://github.com/facebook/react/pull/6896\n // and discussion in https://bugzilla.mozilla.org/show_bug.cgi?id=1276240\n domElement = ownerDocument.createElement(type); // Normally attributes are assigned in `setInitialDOMProperties`, however the `multiple` and `size`\n // attributes on `select`s needs to be added before `option`s are inserted.\n // This prevents:\n // - a bug where the `select` does not scroll to the correct option because singular\n // `select` elements automatically pick the first item #13222\n // - a bug where the `select` set the first item as selected despite the `size` attribute #14239\n // See https://github.com/facebook/react/issues/13222\n // and https://github.com/facebook/react/issues/14239\n\n if (type === 'select') {\n var node = domElement;\n\n if (props.multiple) {\n node.multiple = true;\n } else if (props.size) {\n // Setting a size greater than 1 causes a select to behave like `multiple=true`, where\n // it is possible that no option is selected.\n //\n // This is only necessary when a select in \"single selection mode\".\n node.size = props.size;\n }\n }\n }\n } else {\n domElement = ownerDocument.createElementNS(namespaceURI, type);\n }\n\n {\n if (namespaceURI === HTML_NAMESPACE$1) {\n if (!isCustomComponentTag && Object.prototype.toString.call(domElement) === '[object HTMLUnknownElement]' && !Object.prototype.hasOwnProperty.call(warnedUnknownTags, type)) {\n warnedUnknownTags[type] = true;\n\n error('The tag <%s> is unrecognized in this browser. ' + 'If you meant to render a React component, start its name with ' + 'an uppercase letter.', type);\n }\n }\n }\n\n return domElement;\n}\nfunction createTextNode(text, rootContainerElement) {\n return getOwnerDocumentFromRootContainer(rootContainerElement).createTextNode(text);\n}\nfunction setInitialProperties(domElement, tag, rawProps, rootContainerElement) {\n var isCustomComponentTag = isCustomComponent(tag, rawProps);\n\n {\n validatePropertiesInDevelopment(tag, rawProps);\n } // TODO: Make sure that we check isMounted before firing any of these events.\n\n\n var props;\n\n switch (tag) {\n case 'iframe':\n case 'object':\n case 'embed':\n trapBubbledEvent(TOP_LOAD, domElement);\n props = rawProps;\n break;\n\n case 'video':\n case 'audio':\n // Create listener for each media event\n for (var i = 0; i < mediaEventTypes.length; i++) {\n trapBubbledEvent(mediaEventTypes[i], domElement);\n }\n\n props = rawProps;\n break;\n\n case 'source':\n trapBubbledEvent(TOP_ERROR, domElement);\n props = rawProps;\n break;\n\n case 'img':\n case 'image':\n case 'link':\n trapBubbledEvent(TOP_ERROR, domElement);\n trapBubbledEvent(TOP_LOAD, domElement);\n props = rawProps;\n break;\n\n case 'form':\n trapBubbledEvent(TOP_RESET, domElement);\n trapBubbledEvent(TOP_SUBMIT, domElement);\n props = rawProps;\n break;\n\n case 'details':\n trapBubbledEvent(TOP_TOGGLE, domElement);\n props = rawProps;\n break;\n\n case 'input':\n initWrapperState(domElement, rawProps);\n props = getHostProps(domElement, rawProps);\n trapBubbledEvent(TOP_INVALID, domElement); // For controlled components we always need to ensure we're listening\n // to onChange. Even if there is no listener.\n\n ensureListeningTo(rootContainerElement, 'onChange');\n break;\n\n case 'option':\n validateProps(domElement, rawProps);\n props = getHostProps$1(domElement, rawProps);\n break;\n\n case 'select':\n initWrapperState$1(domElement, rawProps);\n props = getHostProps$2(domElement, rawProps);\n trapBubbledEvent(TOP_INVALID, domElement); // For controlled components we always need to ensure we're listening\n // to onChange. Even if there is no listener.\n\n ensureListeningTo(rootContainerElement, 'onChange');\n break;\n\n case 'textarea':\n initWrapperState$2(domElement, rawProps);\n props = getHostProps$3(domElement, rawProps);\n trapBubbledEvent(TOP_INVALID, domElement); // For controlled components we always need to ensure we're listening\n // to onChange. Even if there is no listener.\n\n ensureListeningTo(rootContainerElement, 'onChange');\n break;\n\n default:\n props = rawProps;\n }\n\n assertValidProps(tag, props);\n setInitialDOMProperties(tag, domElement, rootContainerElement, props, isCustomComponentTag);\n\n switch (tag) {\n case 'input':\n // TODO: Make sure we check if this is still unmounted or do any clean\n // up necessary since we never stop tracking anymore.\n track(domElement);\n postMountWrapper(domElement, rawProps, false);\n break;\n\n case 'textarea':\n // TODO: Make sure we check if this is still unmounted or do any clean\n // up necessary since we never stop tracking anymore.\n track(domElement);\n postMountWrapper$3(domElement);\n break;\n\n case 'option':\n postMountWrapper$1(domElement, rawProps);\n break;\n\n case 'select':\n postMountWrapper$2(domElement, rawProps);\n break;\n\n default:\n if (typeof props.onClick === 'function') {\n // TODO: This cast may not be sound for SVG, MathML or custom elements.\n trapClickOnNonInteractiveElement(domElement);\n }\n\n break;\n }\n} // Calculate the diff between the two objects.\n\nfunction diffProperties(domElement, tag, lastRawProps, nextRawProps, rootContainerElement) {\n {\n validatePropertiesInDevelopment(tag, nextRawProps);\n }\n\n var updatePayload = null;\n var lastProps;\n var nextProps;\n\n switch (tag) {\n case 'input':\n lastProps = getHostProps(domElement, lastRawProps);\n nextProps = getHostProps(domElement, nextRawProps);\n updatePayload = [];\n break;\n\n case 'option':\n lastProps = getHostProps$1(domElement, lastRawProps);\n nextProps = getHostProps$1(domElement, nextRawProps);\n updatePayload = [];\n break;\n\n case 'select':\n lastProps = getHostProps$2(domElement, lastRawProps);\n nextProps = getHostProps$2(domElement, nextRawProps);\n updatePayload = [];\n break;\n\n case 'textarea':\n lastProps = getHostProps$3(domElement, lastRawProps);\n nextProps = getHostProps$3(domElement, nextRawProps);\n updatePayload = [];\n break;\n\n default:\n lastProps = lastRawProps;\n nextProps = nextRawProps;\n\n if (typeof lastProps.onClick !== 'function' && typeof nextProps.onClick === 'function') {\n // TODO: This cast may not be sound for SVG, MathML or custom elements.\n trapClickOnNonInteractiveElement(domElement);\n }\n\n break;\n }\n\n assertValidProps(tag, nextProps);\n var propKey;\n var styleName;\n var styleUpdates = null;\n\n for (propKey in lastProps) {\n if (nextProps.hasOwnProperty(propKey) || !lastProps.hasOwnProperty(propKey) || lastProps[propKey] == null) {\n continue;\n }\n\n if (propKey === STYLE) {\n var lastStyle = lastProps[propKey];\n\n for (styleName in lastStyle) {\n if (lastStyle.hasOwnProperty(styleName)) {\n if (!styleUpdates) {\n styleUpdates = {};\n }\n\n styleUpdates[styleName] = '';\n }\n }\n } else if (propKey === DANGEROUSLY_SET_INNER_HTML || propKey === CHILDREN) ; else if ( propKey === SUPPRESS_CONTENT_EDITABLE_WARNING || propKey === SUPPRESS_HYDRATION_WARNING) ; else if (propKey === AUTOFOCUS) ; else if (registrationNameModules.hasOwnProperty(propKey)) {\n // This is a special case. If any listener updates we need to ensure\n // that the \"current\" fiber pointer gets updated so we need a commit\n // to update this element.\n if (!updatePayload) {\n updatePayload = [];\n }\n } else {\n // For all other deleted properties we add it to the queue. We use\n // the whitelist in the commit phase instead.\n (updatePayload = updatePayload || []).push(propKey, null);\n }\n }\n\n for (propKey in nextProps) {\n var nextProp = nextProps[propKey];\n var lastProp = lastProps != null ? lastProps[propKey] : undefined;\n\n if (!nextProps.hasOwnProperty(propKey) || nextProp === lastProp || nextProp == null && lastProp == null) {\n continue;\n }\n\n if (propKey === STYLE) {\n {\n if (nextProp) {\n // Freeze the next style object so that we can assume it won't be\n // mutated. We have already warned for this in the past.\n Object.freeze(nextProp);\n }\n }\n\n if (lastProp) {\n // Unset styles on `lastProp` but not on `nextProp`.\n for (styleName in lastProp) {\n if (lastProp.hasOwnProperty(styleName) && (!nextProp || !nextProp.hasOwnProperty(styleName))) {\n if (!styleUpdates) {\n styleUpdates = {};\n }\n\n styleUpdates[styleName] = '';\n }\n } // Update styles that changed since `lastProp`.\n\n\n for (styleName in nextProp) {\n if (nextProp.hasOwnProperty(styleName) && lastProp[styleName] !== nextProp[styleName]) {\n if (!styleUpdates) {\n styleUpdates = {};\n }\n\n styleUpdates[styleName] = nextProp[styleName];\n }\n }\n } else {\n // Relies on `updateStylesByID` not mutating `styleUpdates`.\n if (!styleUpdates) {\n if (!updatePayload) {\n updatePayload = [];\n }\n\n updatePayload.push(propKey, styleUpdates);\n }\n\n styleUpdates = nextProp;\n }\n } else if (propKey === DANGEROUSLY_SET_INNER_HTML) {\n var nextHtml = nextProp ? nextProp[HTML$1] : undefined;\n var lastHtml = lastProp ? lastProp[HTML$1] : undefined;\n\n if (nextHtml != null) {\n if (lastHtml !== nextHtml) {\n (updatePayload = updatePayload || []).push(propKey, nextHtml);\n }\n }\n } else if (propKey === CHILDREN) {\n if (lastProp !== nextProp && (typeof nextProp === 'string' || typeof nextProp === 'number')) {\n (updatePayload = updatePayload || []).push(propKey, '' + nextProp);\n }\n } else if ( propKey === SUPPRESS_CONTENT_EDITABLE_WARNING || propKey === SUPPRESS_HYDRATION_WARNING) ; else if (registrationNameModules.hasOwnProperty(propKey)) {\n if (nextProp != null) {\n // We eagerly listen to this even though we haven't committed yet.\n if ( typeof nextProp !== 'function') {\n warnForInvalidEventListener(propKey, nextProp);\n }\n\n ensureListeningTo(rootContainerElement, propKey);\n }\n\n if (!updatePayload && lastProp !== nextProp) {\n // This is a special case. If any listener updates we need to ensure\n // that the \"current\" props pointer gets updated so we need a commit\n // to update this element.\n updatePayload = [];\n }\n } else {\n // For any other property we always add it to the queue and then we\n // filter it out using the whitelist during the commit.\n (updatePayload = updatePayload || []).push(propKey, nextProp);\n }\n }\n\n if (styleUpdates) {\n {\n validateShorthandPropertyCollisionInDev(styleUpdates, nextProps[STYLE]);\n }\n\n (updatePayload = updatePayload || []).push(STYLE, styleUpdates);\n }\n\n return updatePayload;\n} // Apply the diff.\n\nfunction updateProperties(domElement, updatePayload, tag, lastRawProps, nextRawProps) {\n // Update checked *before* name.\n // In the middle of an update, it is possible to have multiple checked.\n // When a checked radio tries to change name, browser makes another radio's checked false.\n if (tag === 'input' && nextRawProps.type === 'radio' && nextRawProps.name != null) {\n updateChecked(domElement, nextRawProps);\n }\n\n var wasCustomComponentTag = isCustomComponent(tag, lastRawProps);\n var isCustomComponentTag = isCustomComponent(tag, nextRawProps); // Apply the diff.\n\n updateDOMProperties(domElement, updatePayload, wasCustomComponentTag, isCustomComponentTag); // TODO: Ensure that an update gets scheduled if any of the special props\n // changed.\n\n switch (tag) {\n case 'input':\n // Update the wrapper around inputs *after* updating props. This has to\n // happen after `updateDOMProperties`. Otherwise HTML5 input validations\n // raise warnings and prevent the new value from being assigned.\n updateWrapper(domElement, nextRawProps);\n break;\n\n case 'textarea':\n updateWrapper$1(domElement, nextRawProps);\n break;\n\n case 'select':\n // <select> value update needs to occur after <option> children\n // reconciliation\n postUpdateWrapper(domElement, nextRawProps);\n break;\n }\n}\n\nfunction getPossibleStandardName(propName) {\n {\n var lowerCasedName = propName.toLowerCase();\n\n if (!possibleStandardNames.hasOwnProperty(lowerCasedName)) {\n return null;\n }\n\n return possibleStandardNames[lowerCasedName] || null;\n }\n}\n\nfunction diffHydratedProperties(domElement, tag, rawProps, parentNamespace, rootContainerElement) {\n var isCustomComponentTag;\n var extraAttributeNames;\n\n {\n suppressHydrationWarning = rawProps[SUPPRESS_HYDRATION_WARNING] === true;\n isCustomComponentTag = isCustomComponent(tag, rawProps);\n validatePropertiesInDevelopment(tag, rawProps);\n } // TODO: Make sure that we check isMounted before firing any of these events.\n\n\n switch (tag) {\n case 'iframe':\n case 'object':\n case 'embed':\n trapBubbledEvent(TOP_LOAD, domElement);\n break;\n\n case 'video':\n case 'audio':\n // Create listener for each media event\n for (var i = 0; i < mediaEventTypes.length; i++) {\n trapBubbledEvent(mediaEventTypes[i], domElement);\n }\n\n break;\n\n case 'source':\n trapBubbledEvent(TOP_ERROR, domElement);\n break;\n\n case 'img':\n case 'image':\n case 'link':\n trapBubbledEvent(TOP_ERROR, domElement);\n trapBubbledEvent(TOP_LOAD, domElement);\n break;\n\n case 'form':\n trapBubbledEvent(TOP_RESET, domElement);\n trapBubbledEvent(TOP_SUBMIT, domElement);\n break;\n\n case 'details':\n trapBubbledEvent(TOP_TOGGLE, domElement);\n break;\n\n case 'input':\n initWrapperState(domElement, rawProps);\n trapBubbledEvent(TOP_INVALID, domElement); // For controlled components we always need to ensure we're listening\n // to onChange. Even if there is no listener.\n\n ensureListeningTo(rootContainerElement, 'onChange');\n break;\n\n case 'option':\n validateProps(domElement, rawProps);\n break;\n\n case 'select':\n initWrapperState$1(domElement, rawProps);\n trapBubbledEvent(TOP_INVALID, domElement); // For controlled components we always need to ensure we're listening\n // to onChange. Even if there is no listener.\n\n ensureListeningTo(rootContainerElement, 'onChange');\n break;\n\n case 'textarea':\n initWrapperState$2(domElement, rawProps);\n trapBubbledEvent(TOP_INVALID, domElement); // For controlled components we always need to ensure we're listening\n // to onChange. Even if there is no listener.\n\n ensureListeningTo(rootContainerElement, 'onChange');\n break;\n }\n\n assertValidProps(tag, rawProps);\n\n {\n extraAttributeNames = new Set();\n var attributes = domElement.attributes;\n\n for (var _i = 0; _i < attributes.length; _i++) {\n var name = attributes[_i].name.toLowerCase();\n\n switch (name) {\n // Built-in SSR attribute is whitelisted\n case 'data-reactroot':\n break;\n // Controlled attributes are not validated\n // TODO: Only ignore them on controlled tags.\n\n case 'value':\n break;\n\n case 'checked':\n break;\n\n case 'selected':\n break;\n\n default:\n // Intentionally use the original name.\n // See discussion in https://github.com/facebook/react/pull/10676.\n extraAttributeNames.add(attributes[_i].name);\n }\n }\n }\n\n var updatePayload = null;\n\n for (var propKey in rawProps) {\n if (!rawProps.hasOwnProperty(propKey)) {\n continue;\n }\n\n var nextProp = rawProps[propKey];\n\n if (propKey === CHILDREN) {\n // For text content children we compare against textContent. This\n // might match additional HTML that is hidden when we read it using\n // textContent. E.g. \"foo\" will match \"f<span>oo</span>\" but that still\n // satisfies our requirement. Our requirement is not to produce perfect\n // HTML and attributes. Ideally we should preserve structure but it's\n // ok not to if the visible content is still enough to indicate what\n // even listeners these nodes might be wired up to.\n // TODO: Warn if there is more than a single textNode as a child.\n // TODO: Should we use domElement.firstChild.nodeValue to compare?\n if (typeof nextProp === 'string') {\n if (domElement.textContent !== nextProp) {\n if ( !suppressHydrationWarning) {\n warnForTextDifference(domElement.textContent, nextProp);\n }\n\n updatePayload = [CHILDREN, nextProp];\n }\n } else if (typeof nextProp === 'number') {\n if (domElement.textContent !== '' + nextProp) {\n if ( !suppressHydrationWarning) {\n warnForTextDifference(domElement.textContent, nextProp);\n }\n\n updatePayload = [CHILDREN, '' + nextProp];\n }\n }\n } else if (registrationNameModules.hasOwnProperty(propKey)) {\n if (nextProp != null) {\n if ( typeof nextProp !== 'function') {\n warnForInvalidEventListener(propKey, nextProp);\n }\n\n ensureListeningTo(rootContainerElement, propKey);\n }\n } else if ( // Convince Flow we've calculated it (it's DEV-only in this method.)\n typeof isCustomComponentTag === 'boolean') {\n // Validate that the properties correspond to their expected values.\n var serverValue = void 0;\n var propertyInfo = getPropertyInfo(propKey);\n\n if (suppressHydrationWarning) ; else if ( propKey === SUPPRESS_CONTENT_EDITABLE_WARNING || propKey === SUPPRESS_HYDRATION_WARNING || // Controlled attributes are not validated\n // TODO: Only ignore them on controlled tags.\n propKey === 'value' || propKey === 'checked' || propKey === 'selected') ; else if (propKey === DANGEROUSLY_SET_INNER_HTML) {\n var serverHTML = domElement.innerHTML;\n var nextHtml = nextProp ? nextProp[HTML$1] : undefined;\n var expectedHTML = normalizeHTML(domElement, nextHtml != null ? nextHtml : '');\n\n if (expectedHTML !== serverHTML) {\n warnForPropDifference(propKey, serverHTML, expectedHTML);\n }\n } else if (propKey === STYLE) {\n // $FlowFixMe - Should be inferred as not undefined.\n extraAttributeNames.delete(propKey);\n\n if (canDiffStyleForHydrationWarning) {\n var expectedStyle = createDangerousStringForStyles(nextProp);\n serverValue = domElement.getAttribute('style');\n\n if (expectedStyle !== serverValue) {\n warnForPropDifference(propKey, serverValue, expectedStyle);\n }\n }\n } else if (isCustomComponentTag) {\n // $FlowFixMe - Should be inferred as not undefined.\n extraAttributeNames.delete(propKey.toLowerCase());\n serverValue = getValueForAttribute(domElement, propKey, nextProp);\n\n if (nextProp !== serverValue) {\n warnForPropDifference(propKey, serverValue, nextProp);\n }\n } else if (!shouldIgnoreAttribute(propKey, propertyInfo, isCustomComponentTag) && !shouldRemoveAttribute(propKey, nextProp, propertyInfo, isCustomComponentTag)) {\n var isMismatchDueToBadCasing = false;\n\n if (propertyInfo !== null) {\n // $FlowFixMe - Should be inferred as not undefined.\n extraAttributeNames.delete(propertyInfo.attributeName);\n serverValue = getValueForProperty(domElement, propKey, nextProp, propertyInfo);\n } else {\n var ownNamespace = parentNamespace;\n\n if (ownNamespace === HTML_NAMESPACE$1) {\n ownNamespace = getIntrinsicNamespace(tag);\n }\n\n if (ownNamespace === HTML_NAMESPACE$1) {\n // $FlowFixMe - Should be inferred as not undefined.\n extraAttributeNames.delete(propKey.toLowerCase());\n } else {\n var standardName = getPossibleStandardName(propKey);\n\n if (standardName !== null && standardName !== propKey) {\n // If an SVG prop is supplied with bad casing, it will\n // be successfully parsed from HTML, but will produce a mismatch\n // (and would be incorrectly rendered on the client).\n // However, we already warn about bad casing elsewhere.\n // So we'll skip the misleading extra mismatch warning in this case.\n isMismatchDueToBadCasing = true; // $FlowFixMe - Should be inferred as not undefined.\n\n extraAttributeNames.delete(standardName);\n } // $FlowFixMe - Should be inferred as not undefined.\n\n\n extraAttributeNames.delete(propKey);\n }\n\n serverValue = getValueForAttribute(domElement, propKey, nextProp);\n }\n\n if (nextProp !== serverValue && !isMismatchDueToBadCasing) {\n warnForPropDifference(propKey, serverValue, nextProp);\n }\n }\n }\n }\n\n {\n // $FlowFixMe - Should be inferred as not undefined.\n if (extraAttributeNames.size > 0 && !suppressHydrationWarning) {\n // $FlowFixMe - Should be inferred as not undefined.\n warnForExtraAttributes(extraAttributeNames);\n }\n }\n\n switch (tag) {\n case 'input':\n // TODO: Make sure we check if this is still unmounted or do any clean\n // up necessary since we never stop tracking anymore.\n track(domElement);\n postMountWrapper(domElement, rawProps, true);\n break;\n\n case 'textarea':\n // TODO: Make sure we check if this is still unmounted or do any clean\n // up necessary since we never stop tracking anymore.\n track(domElement);\n postMountWrapper$3(domElement);\n break;\n\n case 'select':\n case 'option':\n // For input and textarea we current always set the value property at\n // post mount to force it to diverge from attributes. However, for\n // option and select we don't quite do the same thing and select\n // is not resilient to the DOM state changing so we don't do that here.\n // TODO: Consider not doing this for input and textarea.\n break;\n\n default:\n if (typeof rawProps.onClick === 'function') {\n // TODO: This cast may not be sound for SVG, MathML or custom elements.\n trapClickOnNonInteractiveElement(domElement);\n }\n\n break;\n }\n\n return updatePayload;\n}\nfunction diffHydratedText(textNode, text) {\n var isDifferent = textNode.nodeValue !== text;\n return isDifferent;\n}\nfunction warnForUnmatchedText(textNode, text) {\n {\n warnForTextDifference(textNode.nodeValue, text);\n }\n}\nfunction warnForDeletedHydratableElement(parentNode, child) {\n {\n if (didWarnInvalidHydration) {\n return;\n }\n\n didWarnInvalidHydration = true;\n\n error('Did not expect server HTML to contain a <%s> in <%s>.', child.nodeName.toLowerCase(), parentNode.nodeName.toLowerCase());\n }\n}\nfunction warnForDeletedHydratableText(parentNode, child) {\n {\n if (didWarnInvalidHydration) {\n return;\n }\n\n didWarnInvalidHydration = true;\n\n error('Did not expect server HTML to contain the text node \"%s\" in <%s>.', child.nodeValue, parentNode.nodeName.toLowerCase());\n }\n}\nfunction warnForInsertedHydratedElement(parentNode, tag, props) {\n {\n if (didWarnInvalidHydration) {\n return;\n }\n\n didWarnInvalidHydration = true;\n\n error('Expected server HTML to contain a matching <%s> in <%s>.', tag, parentNode.nodeName.toLowerCase());\n }\n}\nfunction warnForInsertedHydratedText(parentNode, text) {\n {\n if (text === '') {\n // We expect to insert empty text nodes since they're not represented in\n // the HTML.\n // TODO: Remove this special case if we can just avoid inserting empty\n // text nodes.\n return;\n }\n\n if (didWarnInvalidHydration) {\n return;\n }\n\n didWarnInvalidHydration = true;\n\n error('Expected server HTML to contain a matching text node for \"%s\" in <%s>.', text, parentNode.nodeName.toLowerCase());\n }\n}\nfunction restoreControlledState$3(domElement, tag, props) {\n switch (tag) {\n case 'input':\n restoreControlledState(domElement, props);\n return;\n\n case 'textarea':\n restoreControlledState$2(domElement, props);\n return;\n\n case 'select':\n restoreControlledState$1(domElement, props);\n return;\n }\n}\n\nfunction getActiveElement(doc) {\n doc = doc || (typeof document !== 'undefined' ? document : undefined);\n\n if (typeof doc === 'undefined') {\n return null;\n }\n\n try {\n return doc.activeElement || doc.body;\n } catch (e) {\n return doc.body;\n }\n}\n\n/**\n * Given any node return the first leaf node without children.\n *\n * @param {DOMElement|DOMTextNode} node\n * @return {DOMElement|DOMTextNode}\n */\n\nfunction getLeafNode(node) {\n while (node && node.firstChild) {\n node = node.firstChild;\n }\n\n return node;\n}\n/**\n * Get the next sibling within a container. This will walk up the\n * DOM if a node's siblings have been exhausted.\n *\n * @param {DOMElement|DOMTextNode} node\n * @return {?DOMElement|DOMTextNode}\n */\n\n\nfunction getSiblingNode(node) {\n while (node) {\n if (node.nextSibling) {\n return node.nextSibling;\n }\n\n node = node.parentNode;\n }\n}\n/**\n * Get object describing the nodes which contain characters at offset.\n *\n * @param {DOMElement|DOMTextNode} root\n * @param {number} offset\n * @return {?object}\n */\n\n\nfunction getNodeForCharacterOffset(root, offset) {\n var node = getLeafNode(root);\n var nodeStart = 0;\n var nodeEnd = 0;\n\n while (node) {\n if (node.nodeType === TEXT_NODE) {\n nodeEnd = nodeStart + node.textContent.length;\n\n if (nodeStart <= offset && nodeEnd >= offset) {\n return {\n node: node,\n offset: offset - nodeStart\n };\n }\n\n nodeStart = nodeEnd;\n }\n\n node = getLeafNode(getSiblingNode(node));\n }\n}\n\n/**\n * @param {DOMElement} outerNode\n * @return {?object}\n */\n\nfunction getOffsets(outerNode) {\n var ownerDocument = outerNode.ownerDocument;\n var win = ownerDocument && ownerDocument.defaultView || window;\n var selection = win.getSelection && win.getSelection();\n\n if (!selection || selection.rangeCount === 0) {\n return null;\n }\n\n var anchorNode = selection.anchorNode,\n anchorOffset = selection.anchorOffset,\n focusNode = selection.focusNode,\n focusOffset = selection.focusOffset; // In Firefox, anchorNode and focusNode can be \"anonymous divs\", e.g. the\n // up/down buttons on an <input type=\"number\">. Anonymous divs do not seem to\n // expose properties, triggering a \"Permission denied error\" if any of its\n // properties are accessed. The only seemingly possible way to avoid erroring\n // is to access a property that typically works for non-anonymous divs and\n // catch any error that may otherwise arise. See\n // https://bugzilla.mozilla.org/show_bug.cgi?id=208427\n\n try {\n /* eslint-disable no-unused-expressions */\n anchorNode.nodeType;\n focusNode.nodeType;\n /* eslint-enable no-unused-expressions */\n } catch (e) {\n return null;\n }\n\n return getModernOffsetsFromPoints(outerNode, anchorNode, anchorOffset, focusNode, focusOffset);\n}\n/**\n * Returns {start, end} where `start` is the character/codepoint index of\n * (anchorNode, anchorOffset) within the textContent of `outerNode`, and\n * `end` is the index of (focusNode, focusOffset).\n *\n * Returns null if you pass in garbage input but we should probably just crash.\n *\n * Exported only for testing.\n */\n\nfunction getModernOffsetsFromPoints(outerNode, anchorNode, anchorOffset, focusNode, focusOffset) {\n var length = 0;\n var start = -1;\n var end = -1;\n var indexWithinAnchor = 0;\n var indexWithinFocus = 0;\n var node = outerNode;\n var parentNode = null;\n\n outer: while (true) {\n var next = null;\n\n while (true) {\n if (node === anchorNode && (anchorOffset === 0 || node.nodeType === TEXT_NODE)) {\n start = length + anchorOffset;\n }\n\n if (node === focusNode && (focusOffset === 0 || node.nodeType === TEXT_NODE)) {\n end = length + focusOffset;\n }\n\n if (node.nodeType === TEXT_NODE) {\n length += node.nodeValue.length;\n }\n\n if ((next = node.firstChild) === null) {\n break;\n } // Moving from `node` to its first child `next`.\n\n\n parentNode = node;\n node = next;\n }\n\n while (true) {\n if (node === outerNode) {\n // If `outerNode` has children, this is always the second time visiting\n // it. If it has no children, this is still the first loop, and the only\n // valid selection is anchorNode and focusNode both equal to this node\n // and both offsets 0, in which case we will have handled above.\n break outer;\n }\n\n if (parentNode === anchorNode && ++indexWithinAnchor === anchorOffset) {\n start = length;\n }\n\n if (parentNode === focusNode && ++indexWithinFocus === focusOffset) {\n end = length;\n }\n\n if ((next = node.nextSibling) !== null) {\n break;\n }\n\n node = parentNode;\n parentNode = node.parentNode;\n } // Moving from `node` to its next sibling `next`.\n\n\n node = next;\n }\n\n if (start === -1 || end === -1) {\n // This should never happen. (Would happen if the anchor/focus nodes aren't\n // actually inside the passed-in node.)\n return null;\n }\n\n return {\n start: start,\n end: end\n };\n}\n/**\n * In modern non-IE browsers, we can support both forward and backward\n * selections.\n *\n * Note: IE10+ supports the Selection object, but it does not support\n * the `extend` method, which means that even in modern IE, it's not possible\n * to programmatically create a backward selection. Thus, for all IE\n * versions, we use the old IE API to create our selections.\n *\n * @param {DOMElement|DOMTextNode} node\n * @param {object} offsets\n */\n\nfunction setOffsets(node, offsets) {\n var doc = node.ownerDocument || document;\n var win = doc && doc.defaultView || window; // Edge fails with \"Object expected\" in some scenarios.\n // (For instance: TinyMCE editor used in a list component that supports pasting to add more,\n // fails when pasting 100+ items)\n\n if (!win.getSelection) {\n return;\n }\n\n var selection = win.getSelection();\n var length = node.textContent.length;\n var start = Math.min(offsets.start, length);\n var end = offsets.end === undefined ? start : Math.min(offsets.end, length); // IE 11 uses modern selection, but doesn't support the extend method.\n // Flip backward selections, so we can set with a single range.\n\n if (!selection.extend && start > end) {\n var temp = end;\n end = start;\n start = temp;\n }\n\n var startMarker = getNodeForCharacterOffset(node, start);\n var endMarker = getNodeForCharacterOffset(node, end);\n\n if (startMarker && endMarker) {\n if (selection.rangeCount === 1 && selection.anchorNode === startMarker.node && selection.anchorOffset === startMarker.offset && selection.focusNode === endMarker.node && selection.focusOffset === endMarker.offset) {\n return;\n }\n\n var range = doc.createRange();\n range.setStart(startMarker.node, startMarker.offset);\n selection.removeAllRanges();\n\n if (start > end) {\n selection.addRange(range);\n selection.extend(endMarker.node, endMarker.offset);\n } else {\n range.setEnd(endMarker.node, endMarker.offset);\n selection.addRange(range);\n }\n }\n}\n\nfunction isTextNode(node) {\n return node && node.nodeType === TEXT_NODE;\n}\n\nfunction containsNode(outerNode, innerNode) {\n if (!outerNode || !innerNode) {\n return false;\n } else if (outerNode === innerNode) {\n return true;\n } else if (isTextNode(outerNode)) {\n return false;\n } else if (isTextNode(innerNode)) {\n return containsNode(outerNode, innerNode.parentNode);\n } else if ('contains' in outerNode) {\n return outerNode.contains(innerNode);\n } else if (outerNode.compareDocumentPosition) {\n return !!(outerNode.compareDocumentPosition(innerNode) & 16);\n } else {\n return false;\n }\n}\n\nfunction isInDocument(node) {\n return node && node.ownerDocument && containsNode(node.ownerDocument.documentElement, node);\n}\n\nfunction isSameOriginFrame(iframe) {\n try {\n // Accessing the contentDocument of a HTMLIframeElement can cause the browser\n // to throw, e.g. if it has a cross-origin src attribute.\n // Safari will show an error in the console when the access results in \"Blocked a frame with origin\". e.g:\n // iframe.contentDocument.defaultView;\n // A safety way is to access one of the cross origin properties: Window or Location\n // Which might result in \"SecurityError\" DOM Exception and it is compatible to Safari.\n // https://html.spec.whatwg.org/multipage/browsers.html#integration-with-idl\n return typeof iframe.contentWindow.location.href === 'string';\n } catch (err) {\n return false;\n }\n}\n\nfunction getActiveElementDeep() {\n var win = window;\n var element = getActiveElement();\n\n while (element instanceof win.HTMLIFrameElement) {\n if (isSameOriginFrame(element)) {\n win = element.contentWindow;\n } else {\n return element;\n }\n\n element = getActiveElement(win.document);\n }\n\n return element;\n}\n/**\n * @ReactInputSelection: React input selection module. Based on Selection.js,\n * but modified to be suitable for react and has a couple of bug fixes (doesn't\n * assume buttons have range selections allowed).\n * Input selection module for React.\n */\n\n/**\n * @hasSelectionCapabilities: we get the element types that support selection\n * from https://html.spec.whatwg.org/#do-not-apply, looking at `selectionStart`\n * and `selectionEnd` rows.\n */\n\n\nfunction hasSelectionCapabilities(elem) {\n var nodeName = elem && elem.nodeName && elem.nodeName.toLowerCase();\n return nodeName && (nodeName === 'input' && (elem.type === 'text' || elem.type === 'search' || elem.type === 'tel' || elem.type === 'url' || elem.type === 'password') || nodeName === 'textarea' || elem.contentEditable === 'true');\n}\nfunction getSelectionInformation() {\n var focusedElem = getActiveElementDeep();\n return {\n // Used by Flare\n activeElementDetached: null,\n focusedElem: focusedElem,\n selectionRange: hasSelectionCapabilities(focusedElem) ? getSelection(focusedElem) : null\n };\n}\n/**\n * @restoreSelection: If any selection information was potentially lost,\n * restore it. This is useful when performing operations that could remove dom\n * nodes and place them back in, resulting in focus being lost.\n */\n\nfunction restoreSelection(priorSelectionInformation) {\n var curFocusedElem = getActiveElementDeep();\n var priorFocusedElem = priorSelectionInformation.focusedElem;\n var priorSelectionRange = priorSelectionInformation.selectionRange;\n\n if (curFocusedElem !== priorFocusedElem && isInDocument(priorFocusedElem)) {\n if (priorSelectionRange !== null && hasSelectionCapabilities(priorFocusedElem)) {\n setSelection(priorFocusedElem, priorSelectionRange);\n } // Focusing a node can change the scroll position, which is undesirable\n\n\n var ancestors = [];\n var ancestor = priorFocusedElem;\n\n while (ancestor = ancestor.parentNode) {\n if (ancestor.nodeType === ELEMENT_NODE) {\n ancestors.push({\n element: ancestor,\n left: ancestor.scrollLeft,\n top: ancestor.scrollTop\n });\n }\n }\n\n if (typeof priorFocusedElem.focus === 'function') {\n priorFocusedElem.focus();\n }\n\n for (var i = 0; i < ancestors.length; i++) {\n var info = ancestors[i];\n info.element.scrollLeft = info.left;\n info.element.scrollTop = info.top;\n }\n }\n}\n/**\n * @getSelection: Gets the selection bounds of a focused textarea, input or\n * contentEditable node.\n * -@input: Look up selection bounds of this input\n * -@return {start: selectionStart, end: selectionEnd}\n */\n\nfunction getSelection(input) {\n var selection;\n\n if ('selectionStart' in input) {\n // Modern browser with input or textarea.\n selection = {\n start: input.selectionStart,\n end: input.selectionEnd\n };\n } else {\n // Content editable or old IE textarea.\n selection = getOffsets(input);\n }\n\n return selection || {\n start: 0,\n end: 0\n };\n}\n/**\n * @setSelection: Sets the selection bounds of a textarea or input and focuses\n * the input.\n * -@input Set selection bounds of this input or textarea\n * -@offsets Object of same form that is returned from get*\n */\n\nfunction setSelection(input, offsets) {\n var start = offsets.start,\n end = offsets.end;\n\n if (end === undefined) {\n end = start;\n }\n\n if ('selectionStart' in input) {\n input.selectionStart = start;\n input.selectionEnd = Math.min(end, input.value.length);\n } else {\n setOffsets(input, offsets);\n }\n}\n\nvar validateDOMNesting = function () {};\n\nvar updatedAncestorInfo = function () {};\n\n{\n // This validation code was written based on the HTML5 parsing spec:\n // https://html.spec.whatwg.org/multipage/syntax.html#has-an-element-in-scope\n //\n // Note: this does not catch all invalid nesting, nor does it try to (as it's\n // not clear what practical benefit doing so provides); instead, we warn only\n // for cases where the parser will give a parse tree differing from what React\n // intended. For example, <b><div></div></b> is invalid but we don't warn\n // because it still parses correctly; we do warn for other cases like nested\n // <p> tags where the beginning of the second element implicitly closes the\n // first, causing a confusing mess.\n // https://html.spec.whatwg.org/multipage/syntax.html#special\n var specialTags = ['address', 'applet', 'area', 'article', 'aside', 'base', 'basefont', 'bgsound', 'blockquote', 'body', 'br', 'button', 'caption', 'center', 'col', 'colgroup', 'dd', 'details', 'dir', 'div', 'dl', 'dt', 'embed', 'fieldset', 'figcaption', 'figure', 'footer', 'form', 'frame', 'frameset', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'head', 'header', 'hgroup', 'hr', 'html', 'iframe', 'img', 'input', 'isindex', 'li', 'link', 'listing', 'main', 'marquee', 'menu', 'menuitem', 'meta', 'nav', 'noembed', 'noframes', 'noscript', 'object', 'ol', 'p', 'param', 'plaintext', 'pre', 'script', 'section', 'select', 'source', 'style', 'summary', 'table', 'tbody', 'td', 'template', 'textarea', 'tfoot', 'th', 'thead', 'title', 'tr', 'track', 'ul', 'wbr', 'xmp']; // https://html.spec.whatwg.org/multipage/syntax.html#has-an-element-in-scope\n\n var inScopeTags = ['applet', 'caption', 'html', 'table', 'td', 'th', 'marquee', 'object', 'template', // https://html.spec.whatwg.org/multipage/syntax.html#html-integration-point\n // TODO: Distinguish by namespace here -- for <title>, including it here\n // errs on the side of fewer warnings\n 'foreignObject', 'desc', 'title']; // https://html.spec.whatwg.org/multipage/syntax.html#has-an-element-in-button-scope\n\n var buttonScopeTags = inScopeTags.concat(['button']); // https://html.spec.whatwg.org/multipage/syntax.html#generate-implied-end-tags\n\n var impliedEndTags = ['dd', 'dt', 'li', 'option', 'optgroup', 'p', 'rp', 'rt'];\n var emptyAncestorInfo = {\n current: null,\n formTag: null,\n aTagInScope: null,\n buttonTagInScope: null,\n nobrTagInScope: null,\n pTagInButtonScope: null,\n listItemTagAutoclosing: null,\n dlItemTagAutoclosing: null\n };\n\n updatedAncestorInfo = function (oldInfo, tag) {\n var ancestorInfo = _assign({}, oldInfo || emptyAncestorInfo);\n\n var info = {\n tag: tag\n };\n\n if (inScopeTags.indexOf(tag) !== -1) {\n ancestorInfo.aTagInScope = null;\n ancestorInfo.buttonTagInScope = null;\n ancestorInfo.nobrTagInScope = null;\n }\n\n if (buttonScopeTags.indexOf(tag) !== -1) {\n ancestorInfo.pTagInButtonScope = null;\n } // See rules for 'li', 'dd', 'dt' start tags in\n // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-inbody\n\n\n if (specialTags.indexOf(tag) !== -1 && tag !== 'address' && tag !== 'div' && tag !== 'p') {\n ancestorInfo.listItemTagAutoclosing = null;\n ancestorInfo.dlItemTagAutoclosing = null;\n }\n\n ancestorInfo.current = info;\n\n if (tag === 'form') {\n ancestorInfo.formTag = info;\n }\n\n if (tag === 'a') {\n ancestorInfo.aTagInScope = info;\n }\n\n if (tag === 'button') {\n ancestorInfo.buttonTagInScope = info;\n }\n\n if (tag === 'nobr') {\n ancestorInfo.nobrTagInScope = info;\n }\n\n if (tag === 'p') {\n ancestorInfo.pTagInButtonScope = info;\n }\n\n if (tag === 'li') {\n ancestorInfo.listItemTagAutoclosing = info;\n }\n\n if (tag === 'dd' || tag === 'dt') {\n ancestorInfo.dlItemTagAutoclosing = info;\n }\n\n return ancestorInfo;\n };\n /**\n * Returns whether\n */\n\n\n var isTagValidWithParent = function (tag, parentTag) {\n // First, let's check if we're in an unusual parsing mode...\n switch (parentTag) {\n // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-inselect\n case 'select':\n return tag === 'option' || tag === 'optgroup' || tag === '#text';\n\n case 'optgroup':\n return tag === 'option' || tag === '#text';\n // Strictly speaking, seeing an <option> doesn't mean we're in a <select>\n // but\n\n case 'option':\n return tag === '#text';\n // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-intd\n // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-incaption\n // No special behavior since these rules fall back to \"in body\" mode for\n // all except special table nodes which cause bad parsing behavior anyway.\n // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-intr\n\n case 'tr':\n return tag === 'th' || tag === 'td' || tag === 'style' || tag === 'script' || tag === 'template';\n // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-intbody\n\n case 'tbody':\n case 'thead':\n case 'tfoot':\n return tag === 'tr' || tag === 'style' || tag === 'script' || tag === 'template';\n // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-incolgroup\n\n case 'colgroup':\n return tag === 'col' || tag === 'template';\n // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-intable\n\n case 'table':\n return tag === 'caption' || tag === 'colgroup' || tag === 'tbody' || tag === 'tfoot' || tag === 'thead' || tag === 'style' || tag === 'script' || tag === 'template';\n // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-inhead\n\n case 'head':\n return tag === 'base' || tag === 'basefont' || tag === 'bgsound' || tag === 'link' || tag === 'meta' || tag === 'title' || tag === 'noscript' || tag === 'noframes' || tag === 'style' || tag === 'script' || tag === 'template';\n // https://html.spec.whatwg.org/multipage/semantics.html#the-html-element\n\n case 'html':\n return tag === 'head' || tag === 'body' || tag === 'frameset';\n\n case 'frameset':\n return tag === 'frame';\n\n case '#document':\n return tag === 'html';\n } // Probably in the \"in body\" parsing mode, so we outlaw only tag combos\n // where the parsing rules cause implicit opens or closes to be added.\n // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-inbody\n\n\n switch (tag) {\n case 'h1':\n case 'h2':\n case 'h3':\n case 'h4':\n case 'h5':\n case 'h6':\n return parentTag !== 'h1' && parentTag !== 'h2' && parentTag !== 'h3' && parentTag !== 'h4' && parentTag !== 'h5' && parentTag !== 'h6';\n\n case 'rp':\n case 'rt':\n return impliedEndTags.indexOf(parentTag) === -1;\n\n case 'body':\n case 'caption':\n case 'col':\n case 'colgroup':\n case 'frameset':\n case 'frame':\n case 'head':\n case 'html':\n case 'tbody':\n case 'td':\n case 'tfoot':\n case 'th':\n case 'thead':\n case 'tr':\n // These tags are only valid with a few parents that have special child\n // parsing rules -- if we're down here, then none of those matched and\n // so we allow it only if we don't know what the parent is, as all other\n // cases are invalid.\n return parentTag == null;\n }\n\n return true;\n };\n /**\n * Returns whether\n */\n\n\n var findInvalidAncestorForTag = function (tag, ancestorInfo) {\n switch (tag) {\n case 'address':\n case 'article':\n case 'aside':\n case 'blockquote':\n case 'center':\n case 'details':\n case 'dialog':\n case 'dir':\n case 'div':\n case 'dl':\n case 'fieldset':\n case 'figcaption':\n case 'figure':\n case 'footer':\n case 'header':\n case 'hgroup':\n case 'main':\n case 'menu':\n case 'nav':\n case 'ol':\n case 'p':\n case 'section':\n case 'summary':\n case 'ul':\n case 'pre':\n case 'listing':\n case 'table':\n case 'hr':\n case 'xmp':\n case 'h1':\n case 'h2':\n case 'h3':\n case 'h4':\n case 'h5':\n case 'h6':\n return ancestorInfo.pTagInButtonScope;\n\n case 'form':\n return ancestorInfo.formTag || ancestorInfo.pTagInButtonScope;\n\n case 'li':\n return ancestorInfo.listItemTagAutoclosing;\n\n case 'dd':\n case 'dt':\n return ancestorInfo.dlItemTagAutoclosing;\n\n case 'button':\n return ancestorInfo.buttonTagInScope;\n\n case 'a':\n // Spec says something about storing a list of markers, but it sounds\n // equivalent to this check.\n return ancestorInfo.aTagInScope;\n\n case 'nobr':\n return ancestorInfo.nobrTagInScope;\n }\n\n return null;\n };\n\n var didWarn$1 = {};\n\n validateDOMNesting = function (childTag, childText, ancestorInfo) {\n ancestorInfo = ancestorInfo || emptyAncestorInfo;\n var parentInfo = ancestorInfo.current;\n var parentTag = parentInfo && parentInfo.tag;\n\n if (childText != null) {\n if (childTag != null) {\n error('validateDOMNesting: when childText is passed, childTag should be null');\n }\n\n childTag = '#text';\n }\n\n var invalidParent = isTagValidWithParent(childTag, parentTag) ? null : parentInfo;\n var invalidAncestor = invalidParent ? null : findInvalidAncestorForTag(childTag, ancestorInfo);\n var invalidParentOrAncestor = invalidParent || invalidAncestor;\n\n if (!invalidParentOrAncestor) {\n return;\n }\n\n var ancestorTag = invalidParentOrAncestor.tag;\n var addendum = getCurrentFiberStackInDev();\n var warnKey = !!invalidParent + '|' + childTag + '|' + ancestorTag + '|' + addendum;\n\n if (didWarn$1[warnKey]) {\n return;\n }\n\n didWarn$1[warnKey] = true;\n var tagDisplayName = childTag;\n var whitespaceInfo = '';\n\n if (childTag === '#text') {\n if (/\\S/.test(childText)) {\n tagDisplayName = 'Text nodes';\n } else {\n tagDisplayName = 'Whitespace text nodes';\n whitespaceInfo = \" Make sure you don't have any extra whitespace between tags on \" + 'each line of your source code.';\n }\n } else {\n tagDisplayName = '<' + childTag + '>';\n }\n\n if (invalidParent) {\n var info = '';\n\n if (ancestorTag === 'table' && childTag === 'tr') {\n info += ' Add a <tbody>, <thead> or <tfoot> to your code to match the DOM tree generated by ' + 'the browser.';\n }\n\n error('validateDOMNesting(...): %s cannot appear as a child of <%s>.%s%s', tagDisplayName, ancestorTag, whitespaceInfo, info);\n } else {\n error('validateDOMNesting(...): %s cannot appear as a descendant of ' + '<%s>.', tagDisplayName, ancestorTag);\n }\n };\n}\n\nvar SUPPRESS_HYDRATION_WARNING$1;\n\n{\n SUPPRESS_HYDRATION_WARNING$1 = 'suppressHydrationWarning';\n}\n\nvar SUSPENSE_START_DATA = '$';\nvar SUSPENSE_END_DATA = '/$';\nvar SUSPENSE_PENDING_START_DATA = '$?';\nvar SUSPENSE_FALLBACK_START_DATA = '$!';\nvar STYLE$1 = 'style';\nvar eventsEnabled = null;\nvar selectionInformation = null;\n\nfunction shouldAutoFocusHostComponent(type, props) {\n switch (type) {\n case 'button':\n case 'input':\n case 'select':\n case 'textarea':\n return !!props.autoFocus;\n }\n\n return false;\n}\nfunction getRootHostContext(rootContainerInstance) {\n var type;\n var namespace;\n var nodeType = rootContainerInstance.nodeType;\n\n switch (nodeType) {\n case DOCUMENT_NODE:\n case DOCUMENT_FRAGMENT_NODE:\n {\n type = nodeType === DOCUMENT_NODE ? '#document' : '#fragment';\n var root = rootContainerInstance.documentElement;\n namespace = root ? root.namespaceURI : getChildNamespace(null, '');\n break;\n }\n\n default:\n {\n var container = nodeType === COMMENT_NODE ? rootContainerInstance.parentNode : rootContainerInstance;\n var ownNamespace = container.namespaceURI || null;\n type = container.tagName;\n namespace = getChildNamespace(ownNamespace, type);\n break;\n }\n }\n\n {\n var validatedTag = type.toLowerCase();\n var ancestorInfo = updatedAncestorInfo(null, validatedTag);\n return {\n namespace: namespace,\n ancestorInfo: ancestorInfo\n };\n }\n}\nfunction getChildHostContext(parentHostContext, type, rootContainerInstance) {\n {\n var parentHostContextDev = parentHostContext;\n var namespace = getChildNamespace(parentHostContextDev.namespace, type);\n var ancestorInfo = updatedAncestorInfo(parentHostContextDev.ancestorInfo, type);\n return {\n namespace: namespace,\n ancestorInfo: ancestorInfo\n };\n }\n}\nfunction getPublicInstance(instance) {\n return instance;\n}\nfunction prepareForCommit(containerInfo) {\n eventsEnabled = isEnabled();\n selectionInformation = getSelectionInformation();\n setEnabled(false);\n}\nfunction resetAfterCommit(containerInfo) {\n restoreSelection(selectionInformation);\n setEnabled(eventsEnabled);\n eventsEnabled = null;\n\n selectionInformation = null;\n}\nfunction createInstance(type, props, rootContainerInstance, hostContext, internalInstanceHandle) {\n var parentNamespace;\n\n {\n // TODO: take namespace into account when validating.\n var hostContextDev = hostContext;\n validateDOMNesting(type, null, hostContextDev.ancestorInfo);\n\n if (typeof props.children === 'string' || typeof props.children === 'number') {\n var string = '' + props.children;\n var ownAncestorInfo = updatedAncestorInfo(hostContextDev.ancestorInfo, type);\n validateDOMNesting(null, string, ownAncestorInfo);\n }\n\n parentNamespace = hostContextDev.namespace;\n }\n\n var domElement = createElement(type, props, rootContainerInstance, parentNamespace);\n precacheFiberNode(internalInstanceHandle, domElement);\n updateFiberProps(domElement, props);\n return domElement;\n}\nfunction appendInitialChild(parentInstance, child) {\n parentInstance.appendChild(child);\n}\nfunction finalizeInitialChildren(domElement, type, props, rootContainerInstance, hostContext) {\n setInitialProperties(domElement, type, props, rootContainerInstance);\n return shouldAutoFocusHostComponent(type, props);\n}\nfunction prepareUpdate(domElement, type, oldProps, newProps, rootContainerInstance, hostContext) {\n {\n var hostContextDev = hostContext;\n\n if (typeof newProps.children !== typeof oldProps.children && (typeof newProps.children === 'string' || typeof newProps.children === 'number')) {\n var string = '' + newProps.children;\n var ownAncestorInfo = updatedAncestorInfo(hostContextDev.ancestorInfo, type);\n validateDOMNesting(null, string, ownAncestorInfo);\n }\n }\n\n return diffProperties(domElement, type, oldProps, newProps, rootContainerInstance);\n}\nfunction shouldSetTextContent(type, props) {\n return type === 'textarea' || type === 'option' || type === 'noscript' || typeof props.children === 'string' || typeof props.children === 'number' || typeof props.dangerouslySetInnerHTML === 'object' && props.dangerouslySetInnerHTML !== null && props.dangerouslySetInnerHTML.__html != null;\n}\nfunction shouldDeprioritizeSubtree(type, props) {\n return !!props.hidden;\n}\nfunction createTextInstance(text, rootContainerInstance, hostContext, internalInstanceHandle) {\n {\n var hostContextDev = hostContext;\n validateDOMNesting(null, text, hostContextDev.ancestorInfo);\n }\n\n var textNode = createTextNode(text, rootContainerInstance);\n precacheFiberNode(internalInstanceHandle, textNode);\n return textNode;\n}\n// if a component just imports ReactDOM (e.g. for findDOMNode).\n// Some environments might not have setTimeout or clearTimeout.\n\nvar scheduleTimeout = typeof setTimeout === 'function' ? setTimeout : undefined;\nvar cancelTimeout = typeof clearTimeout === 'function' ? clearTimeout : undefined;\nvar noTimeout = -1; // -------------------\nfunction commitMount(domElement, type, newProps, internalInstanceHandle) {\n // Despite the naming that might imply otherwise, this method only\n // fires if there is an `Update` effect scheduled during mounting.\n // This happens if `finalizeInitialChildren` returns `true` (which it\n // does to implement the `autoFocus` attribute on the client). But\n // there are also other cases when this might happen (such as patching\n // up text content during hydration mismatch). So we'll check this again.\n if (shouldAutoFocusHostComponent(type, newProps)) {\n domElement.focus();\n }\n}\nfunction commitUpdate(domElement, updatePayload, type, oldProps, newProps, internalInstanceHandle) {\n // Update the props handle so that we know which props are the ones with\n // with current event handlers.\n updateFiberProps(domElement, newProps); // Apply the diff to the DOM node.\n\n updateProperties(domElement, updatePayload, type, oldProps, newProps);\n}\nfunction resetTextContent(domElement) {\n setTextContent(domElement, '');\n}\nfunction commitTextUpdate(textInstance, oldText, newText) {\n textInstance.nodeValue = newText;\n}\nfunction appendChild(parentInstance, child) {\n parentInstance.appendChild(child);\n}\nfunction appendChildToContainer(container, child) {\n var parentNode;\n\n if (container.nodeType === COMMENT_NODE) {\n parentNode = container.parentNode;\n parentNode.insertBefore(child, container);\n } else {\n parentNode = container;\n parentNode.appendChild(child);\n } // This container might be used for a portal.\n // If something inside a portal is clicked, that click should bubble\n // through the React tree. However, on Mobile Safari the click would\n // never bubble through the *DOM* tree unless an ancestor with onclick\n // event exists. So we wouldn't see it and dispatch it.\n // This is why we ensure that non React root containers have inline onclick\n // defined.\n // https://github.com/facebook/react/issues/11918\n\n\n var reactRootContainer = container._reactRootContainer;\n\n if ((reactRootContainer === null || reactRootContainer === undefined) && parentNode.onclick === null) {\n // TODO: This cast may not be sound for SVG, MathML or custom elements.\n trapClickOnNonInteractiveElement(parentNode);\n }\n}\nfunction insertBefore(parentInstance, child, beforeChild) {\n parentInstance.insertBefore(child, beforeChild);\n}\nfunction insertInContainerBefore(container, child, beforeChild) {\n if (container.nodeType === COMMENT_NODE) {\n container.parentNode.insertBefore(child, beforeChild);\n } else {\n container.insertBefore(child, beforeChild);\n }\n}\nfunction removeChild(parentInstance, child) {\n parentInstance.removeChild(child);\n}\nfunction removeChildFromContainer(container, child) {\n if (container.nodeType === COMMENT_NODE) {\n container.parentNode.removeChild(child);\n } else {\n container.removeChild(child);\n }\n}\n\nfunction hideInstance(instance) {\n // pass host context to this method?\n\n\n instance = instance;\n var style = instance.style;\n\n if (typeof style.setProperty === 'function') {\n style.setProperty('display', 'none', 'important');\n } else {\n style.display = 'none';\n }\n}\nfunction hideTextInstance(textInstance) {\n textInstance.nodeValue = '';\n}\nfunction unhideInstance(instance, props) {\n instance = instance;\n var styleProp = props[STYLE$1];\n var display = styleProp !== undefined && styleProp !== null && styleProp.hasOwnProperty('display') ? styleProp.display : null;\n instance.style.display = dangerousStyleValue('display', display);\n}\nfunction unhideTextInstance(textInstance, text) {\n textInstance.nodeValue = text;\n} // -------------------\nfunction canHydrateInstance(instance, type, props) {\n if (instance.nodeType !== ELEMENT_NODE || type.toLowerCase() !== instance.nodeName.toLowerCase()) {\n return null;\n } // This has now been refined to an element node.\n\n\n return instance;\n}\nfunction canHydrateTextInstance(instance, text) {\n if (text === '' || instance.nodeType !== TEXT_NODE) {\n // Empty strings are not parsed by HTML so there won't be a correct match here.\n return null;\n } // This has now been refined to a text node.\n\n\n return instance;\n}\nfunction isSuspenseInstancePending(instance) {\n return instance.data === SUSPENSE_PENDING_START_DATA;\n}\nfunction isSuspenseInstanceFallback(instance) {\n return instance.data === SUSPENSE_FALLBACK_START_DATA;\n}\n\nfunction getNextHydratable(node) {\n // Skip non-hydratable nodes.\n for (; node != null; node = node.nextSibling) {\n var nodeType = node.nodeType;\n\n if (nodeType === ELEMENT_NODE || nodeType === TEXT_NODE) {\n break;\n }\n }\n\n return node;\n}\n\nfunction getNextHydratableSibling(instance) {\n return getNextHydratable(instance.nextSibling);\n}\nfunction getFirstHydratableChild(parentInstance) {\n return getNextHydratable(parentInstance.firstChild);\n}\nfunction hydrateInstance(instance, type, props, rootContainerInstance, hostContext, internalInstanceHandle) {\n precacheFiberNode(internalInstanceHandle, instance); // TODO: Possibly defer this until the commit phase where all the events\n // get attached.\n\n updateFiberProps(instance, props);\n var parentNamespace;\n\n {\n var hostContextDev = hostContext;\n parentNamespace = hostContextDev.namespace;\n }\n\n return diffHydratedProperties(instance, type, props, parentNamespace, rootContainerInstance);\n}\nfunction hydrateTextInstance(textInstance, text, internalInstanceHandle) {\n precacheFiberNode(internalInstanceHandle, textInstance);\n return diffHydratedText(textInstance, text);\n}\nfunction getNextHydratableInstanceAfterSuspenseInstance(suspenseInstance) {\n var node = suspenseInstance.nextSibling; // Skip past all nodes within this suspense boundary.\n // There might be nested nodes so we need to keep track of how\n // deep we are and only break out when we're back on top.\n\n var depth = 0;\n\n while (node) {\n if (node.nodeType === COMMENT_NODE) {\n var data = node.data;\n\n if (data === SUSPENSE_END_DATA) {\n if (depth === 0) {\n return getNextHydratableSibling(node);\n } else {\n depth--;\n }\n } else if (data === SUSPENSE_START_DATA || data === SUSPENSE_FALLBACK_START_DATA || data === SUSPENSE_PENDING_START_DATA) {\n depth++;\n }\n }\n\n node = node.nextSibling;\n } // TODO: Warn, we didn't find the end comment boundary.\n\n\n return null;\n} // Returns the SuspenseInstance if this node is a direct child of a\n// SuspenseInstance. I.e. if its previous sibling is a Comment with\n// SUSPENSE_x_START_DATA. Otherwise, null.\n\nfunction getParentSuspenseInstance(targetInstance) {\n var node = targetInstance.previousSibling; // Skip past all nodes within this suspense boundary.\n // There might be nested nodes so we need to keep track of how\n // deep we are and only break out when we're back on top.\n\n var depth = 0;\n\n while (node) {\n if (node.nodeType === COMMENT_NODE) {\n var data = node.data;\n\n if (data === SUSPENSE_START_DATA || data === SUSPENSE_FALLBACK_START_DATA || data === SUSPENSE_PENDING_START_DATA) {\n if (depth === 0) {\n return node;\n } else {\n depth--;\n }\n } else if (data === SUSPENSE_END_DATA) {\n depth++;\n }\n }\n\n node = node.previousSibling;\n }\n\n return null;\n}\nfunction commitHydratedContainer(container) {\n // Retry if any event replaying was blocked on this.\n retryIfBlockedOn(container);\n}\nfunction commitHydratedSuspenseInstance(suspenseInstance) {\n // Retry if any event replaying was blocked on this.\n retryIfBlockedOn(suspenseInstance);\n}\nfunction didNotMatchHydratedContainerTextInstance(parentContainer, textInstance, text) {\n {\n warnForUnmatchedText(textInstance, text);\n }\n}\nfunction didNotMatchHydratedTextInstance(parentType, parentProps, parentInstance, textInstance, text) {\n if ( parentProps[SUPPRESS_HYDRATION_WARNING$1] !== true) {\n warnForUnmatchedText(textInstance, text);\n }\n}\nfunction didNotHydrateContainerInstance(parentContainer, instance) {\n {\n if (instance.nodeType === ELEMENT_NODE) {\n warnForDeletedHydratableElement(parentContainer, instance);\n } else if (instance.nodeType === COMMENT_NODE) ; else {\n warnForDeletedHydratableText(parentContainer, instance);\n }\n }\n}\nfunction didNotHydrateInstance(parentType, parentProps, parentInstance, instance) {\n if ( parentProps[SUPPRESS_HYDRATION_WARNING$1] !== true) {\n if (instance.nodeType === ELEMENT_NODE) {\n warnForDeletedHydratableElement(parentInstance, instance);\n } else if (instance.nodeType === COMMENT_NODE) ; else {\n warnForDeletedHydratableText(parentInstance, instance);\n }\n }\n}\nfunction didNotFindHydratableContainerInstance(parentContainer, type, props) {\n {\n warnForInsertedHydratedElement(parentContainer, type);\n }\n}\nfunction didNotFindHydratableContainerTextInstance(parentContainer, text) {\n {\n warnForInsertedHydratedText(parentContainer, text);\n }\n}\nfunction didNotFindHydratableInstance(parentType, parentProps, parentInstance, type, props) {\n if ( parentProps[SUPPRESS_HYDRATION_WARNING$1] !== true) {\n warnForInsertedHydratedElement(parentInstance, type);\n }\n}\nfunction didNotFindHydratableTextInstance(parentType, parentProps, parentInstance, text) {\n if ( parentProps[SUPPRESS_HYDRATION_WARNING$1] !== true) {\n warnForInsertedHydratedText(parentInstance, text);\n }\n}\nfunction didNotFindHydratableSuspenseInstance(parentType, parentProps, parentInstance) {\n if ( parentProps[SUPPRESS_HYDRATION_WARNING$1] !== true) ;\n}\n\nvar randomKey = Math.random().toString(36).slice(2);\nvar internalInstanceKey = '__reactInternalInstance$' + randomKey;\nvar internalEventHandlersKey = '__reactEventHandlers$' + randomKey;\nvar internalContainerInstanceKey = '__reactContainere$' + randomKey;\nfunction precacheFiberNode(hostInst, node) {\n node[internalInstanceKey] = hostInst;\n}\nfunction markContainerAsRoot(hostRoot, node) {\n node[internalContainerInstanceKey] = hostRoot;\n}\nfunction unmarkContainerAsRoot(node) {\n node[internalContainerInstanceKey] = null;\n}\nfunction isContainerMarkedAsRoot(node) {\n return !!node[internalContainerInstanceKey];\n} // Given a DOM node, return the closest HostComponent or HostText fiber ancestor.\n// If the target node is part of a hydrated or not yet rendered subtree, then\n// this may also return a SuspenseComponent or HostRoot to indicate that.\n// Conceptually the HostRoot fiber is a child of the Container node. So if you\n// pass the Container node as the targetNode, you will not actually get the\n// HostRoot back. To get to the HostRoot, you need to pass a child of it.\n// The same thing applies to Suspense boundaries.\n\nfunction getClosestInstanceFromNode(targetNode) {\n var targetInst = targetNode[internalInstanceKey];\n\n if (targetInst) {\n // Don't return HostRoot or SuspenseComponent here.\n return targetInst;\n } // If the direct event target isn't a React owned DOM node, we need to look\n // to see if one of its parents is a React owned DOM node.\n\n\n var parentNode = targetNode.parentNode;\n\n while (parentNode) {\n // We'll check if this is a container root that could include\n // React nodes in the future. We need to check this first because\n // if we're a child of a dehydrated container, we need to first\n // find that inner container before moving on to finding the parent\n // instance. Note that we don't check this field on the targetNode\n // itself because the fibers are conceptually between the container\n // node and the first child. It isn't surrounding the container node.\n // If it's not a container, we check if it's an instance.\n targetInst = parentNode[internalContainerInstanceKey] || parentNode[internalInstanceKey];\n\n if (targetInst) {\n // Since this wasn't the direct target of the event, we might have\n // stepped past dehydrated DOM nodes to get here. However they could\n // also have been non-React nodes. We need to answer which one.\n // If we the instance doesn't have any children, then there can't be\n // a nested suspense boundary within it. So we can use this as a fast\n // bailout. Most of the time, when people add non-React children to\n // the tree, it is using a ref to a child-less DOM node.\n // Normally we'd only need to check one of the fibers because if it\n // has ever gone from having children to deleting them or vice versa\n // it would have deleted the dehydrated boundary nested inside already.\n // However, since the HostRoot starts out with an alternate it might\n // have one on the alternate so we need to check in case this was a\n // root.\n var alternate = targetInst.alternate;\n\n if (targetInst.child !== null || alternate !== null && alternate.child !== null) {\n // Next we need to figure out if the node that skipped past is\n // nested within a dehydrated boundary and if so, which one.\n var suspenseInstance = getParentSuspenseInstance(targetNode);\n\n while (suspenseInstance !== null) {\n // We found a suspense instance. That means that we haven't\n // hydrated it yet. Even though we leave the comments in the\n // DOM after hydrating, and there are boundaries in the DOM\n // that could already be hydrated, we wouldn't have found them\n // through this pass since if the target is hydrated it would\n // have had an internalInstanceKey on it.\n // Let's get the fiber associated with the SuspenseComponent\n // as the deepest instance.\n var targetSuspenseInst = suspenseInstance[internalInstanceKey];\n\n if (targetSuspenseInst) {\n return targetSuspenseInst;\n } // If we don't find a Fiber on the comment, it might be because\n // we haven't gotten to hydrate it yet. There might still be a\n // parent boundary that hasn't above this one so we need to find\n // the outer most that is known.\n\n\n suspenseInstance = getParentSuspenseInstance(suspenseInstance); // If we don't find one, then that should mean that the parent\n // host component also hasn't hydrated yet. We can return it\n // below since it will bail out on the isMounted check later.\n }\n }\n\n return targetInst;\n }\n\n targetNode = parentNode;\n parentNode = targetNode.parentNode;\n }\n\n return null;\n}\n/**\n * Given a DOM node, return the ReactDOMComponent or ReactDOMTextComponent\n * instance, or null if the node was not rendered by this React.\n */\n\nfunction getInstanceFromNode$1(node) {\n var inst = node[internalInstanceKey] || node[internalContainerInstanceKey];\n\n if (inst) {\n if (inst.tag === HostComponent || inst.tag === HostText || inst.tag === SuspenseComponent || inst.tag === HostRoot) {\n return inst;\n } else {\n return null;\n }\n }\n\n return null;\n}\n/**\n * Given a ReactDOMComponent or ReactDOMTextComponent, return the corresponding\n * DOM node.\n */\n\nfunction getNodeFromInstance$1(inst) {\n if (inst.tag === HostComponent || inst.tag === HostText) {\n // In Fiber this, is just the state node right now. We assume it will be\n // a host component or host text.\n return inst.stateNode;\n } // Without this first invariant, passing a non-DOM-component triggers the next\n // invariant for a missing parent, which is super confusing.\n\n\n {\n {\n throw Error( \"getNodeFromInstance: Invalid argument.\" );\n }\n }\n}\nfunction getFiberCurrentPropsFromNode$1(node) {\n return node[internalEventHandlersKey] || null;\n}\nfunction updateFiberProps(node, props) {\n node[internalEventHandlersKey] = props;\n}\n\nfunction getParent(inst) {\n do {\n inst = inst.return; // TODO: If this is a HostRoot we might want to bail out.\n // That is depending on if we want nested subtrees (layers) to bubble\n // events to their parent. We could also go through parentNode on the\n // host node but that wouldn't work for React Native and doesn't let us\n // do the portal feature.\n } while (inst && inst.tag !== HostComponent);\n\n if (inst) {\n return inst;\n }\n\n return null;\n}\n/**\n * Return the lowest common ancestor of A and B, or null if they are in\n * different trees.\n */\n\n\nfunction getLowestCommonAncestor(instA, instB) {\n var depthA = 0;\n\n for (var tempA = instA; tempA; tempA = getParent(tempA)) {\n depthA++;\n }\n\n var depthB = 0;\n\n for (var tempB = instB; tempB; tempB = getParent(tempB)) {\n depthB++;\n } // If A is deeper, crawl up.\n\n\n while (depthA - depthB > 0) {\n instA = getParent(instA);\n depthA--;\n } // If B is deeper, crawl up.\n\n\n while (depthB - depthA > 0) {\n instB = getParent(instB);\n depthB--;\n } // Walk in lockstep until we find a match.\n\n\n var depth = depthA;\n\n while (depth--) {\n if (instA === instB || instA === instB.alternate) {\n return instA;\n }\n\n instA = getParent(instA);\n instB = getParent(instB);\n }\n\n return null;\n}\n/**\n * Simulates the traversal of a two-phase, capture/bubble event dispatch.\n */\n\nfunction traverseTwoPhase(inst, fn, arg) {\n var path = [];\n\n while (inst) {\n path.push(inst);\n inst = getParent(inst);\n }\n\n var i;\n\n for (i = path.length; i-- > 0;) {\n fn(path[i], 'captured', arg);\n }\n\n for (i = 0; i < path.length; i++) {\n fn(path[i], 'bubbled', arg);\n }\n}\n/**\n * Traverses the ID hierarchy and invokes the supplied `cb` on any IDs that\n * should would receive a `mouseEnter` or `mouseLeave` event.\n *\n * Does not invoke the callback on the nearest common ancestor because nothing\n * \"entered\" or \"left\" that element.\n */\n\nfunction traverseEnterLeave(from, to, fn, argFrom, argTo) {\n var common = from && to ? getLowestCommonAncestor(from, to) : null;\n var pathFrom = [];\n\n while (true) {\n if (!from) {\n break;\n }\n\n if (from === common) {\n break;\n }\n\n var alternate = from.alternate;\n\n if (alternate !== null && alternate === common) {\n break;\n }\n\n pathFrom.push(from);\n from = getParent(from);\n }\n\n var pathTo = [];\n\n while (true) {\n if (!to) {\n break;\n }\n\n if (to === common) {\n break;\n }\n\n var _alternate = to.alternate;\n\n if (_alternate !== null && _alternate === common) {\n break;\n }\n\n pathTo.push(to);\n to = getParent(to);\n }\n\n for (var i = 0; i < pathFrom.length; i++) {\n fn(pathFrom[i], 'bubbled', argFrom);\n }\n\n for (var _i = pathTo.length; _i-- > 0;) {\n fn(pathTo[_i], 'captured', argTo);\n }\n}\n\nfunction isInteractive(tag) {\n return tag === 'button' || tag === 'input' || tag === 'select' || tag === 'textarea';\n}\n\nfunction shouldPreventMouseEvent(name, type, props) {\n switch (name) {\n case 'onClick':\n case 'onClickCapture':\n case 'onDoubleClick':\n case 'onDoubleClickCapture':\n case 'onMouseDown':\n case 'onMouseDownCapture':\n case 'onMouseMove':\n case 'onMouseMoveCapture':\n case 'onMouseUp':\n case 'onMouseUpCapture':\n case 'onMouseEnter':\n return !!(props.disabled && isInteractive(type));\n\n default:\n return false;\n }\n}\n/**\n * @param {object} inst The instance, which is the source of events.\n * @param {string} registrationName Name of listener (e.g. `onClick`).\n * @return {?function} The stored callback.\n */\n\n\nfunction getListener(inst, registrationName) {\n var listener; // TODO: shouldPreventMouseEvent is DOM-specific and definitely should not\n // live here; needs to be moved to a better place soon\n\n var stateNode = inst.stateNode;\n\n if (!stateNode) {\n // Work in progress (ex: onload events in incremental mode).\n return null;\n }\n\n var props = getFiberCurrentPropsFromNode(stateNode);\n\n if (!props) {\n // Work in progress.\n return null;\n }\n\n listener = props[registrationName];\n\n if (shouldPreventMouseEvent(registrationName, inst.type, props)) {\n return null;\n }\n\n if (!(!listener || typeof listener === 'function')) {\n {\n throw Error( \"Expected `\" + registrationName + \"` listener to be a function, instead got a value of `\" + typeof listener + \"` type.\" );\n }\n }\n\n return listener;\n}\n\n/**\n * Some event types have a notion of different registration names for different\n * \"phases\" of propagation. This finds listeners by a given phase.\n */\nfunction listenerAtPhase(inst, event, propagationPhase) {\n var registrationName = event.dispatchConfig.phasedRegistrationNames[propagationPhase];\n return getListener(inst, registrationName);\n}\n/**\n * A small set of propagation patterns, each of which will accept a small amount\n * of information, and generate a set of \"dispatch ready event objects\" - which\n * are sets of events that have already been annotated with a set of dispatched\n * listener functions/ids. The API is designed this way to discourage these\n * propagation strategies from actually executing the dispatches, since we\n * always want to collect the entire set of dispatches before executing even a\n * single one.\n */\n\n/**\n * Tags a `SyntheticEvent` with dispatched listeners. Creating this function\n * here, allows us to not have to bind or create functions for each event.\n * Mutating the event's members allows us to not have to create a wrapping\n * \"dispatch\" object that pairs the event with the listener.\n */\n\n\nfunction accumulateDirectionalDispatches(inst, phase, event) {\n {\n if (!inst) {\n error('Dispatching inst must not be null');\n }\n }\n\n var listener = listenerAtPhase(inst, event, phase);\n\n if (listener) {\n event._dispatchListeners = accumulateInto(event._dispatchListeners, listener);\n event._dispatchInstances = accumulateInto(event._dispatchInstances, inst);\n }\n}\n/**\n * Collect dispatches (must be entirely collected before dispatching - see unit\n * tests). Lazily allocate the array to conserve memory. We must loop through\n * each event and perform the traversal for each one. We cannot perform a\n * single traversal for the entire collection of events because each event may\n * have a different target.\n */\n\n\nfunction accumulateTwoPhaseDispatchesSingle(event) {\n if (event && event.dispatchConfig.phasedRegistrationNames) {\n traverseTwoPhase(event._targetInst, accumulateDirectionalDispatches, event);\n }\n}\n/**\n * Accumulates without regard to direction, does not look for phased\n * registration names. Same as `accumulateDirectDispatchesSingle` but without\n * requiring that the `dispatchMarker` be the same as the dispatched ID.\n */\n\n\nfunction accumulateDispatches(inst, ignoredDirection, event) {\n if (inst && event && event.dispatchConfig.registrationName) {\n var registrationName = event.dispatchConfig.registrationName;\n var listener = getListener(inst, registrationName);\n\n if (listener) {\n event._dispatchListeners = accumulateInto(event._dispatchListeners, listener);\n event._dispatchInstances = accumulateInto(event._dispatchInstances, inst);\n }\n }\n}\n/**\n * Accumulates dispatches on an `SyntheticEvent`, but only for the\n * `dispatchMarker`.\n * @param {SyntheticEvent} event\n */\n\n\nfunction accumulateDirectDispatchesSingle(event) {\n if (event && event.dispatchConfig.registrationName) {\n accumulateDispatches(event._targetInst, null, event);\n }\n}\n\nfunction accumulateTwoPhaseDispatches(events) {\n forEachAccumulated(events, accumulateTwoPhaseDispatchesSingle);\n}\nfunction accumulateEnterLeaveDispatches(leave, enter, from, to) {\n traverseEnterLeave(from, to, accumulateDispatches, leave, enter);\n}\nfunction accumulateDirectDispatches(events) {\n forEachAccumulated(events, accumulateDirectDispatchesSingle);\n}\n\n/**\n * These variables store information about text content of a target node,\n * allowing comparison of content before and after a given event.\n *\n * Identify the node where selection currently begins, then observe\n * both its text content and its current position in the DOM. Since the\n * browser may natively replace the target node during composition, we can\n * use its position to find its replacement.\n *\n *\n */\nvar root = null;\nvar startText = null;\nvar fallbackText = null;\nfunction initialize(nativeEventTarget) {\n root = nativeEventTarget;\n startText = getText();\n return true;\n}\nfunction reset() {\n root = null;\n startText = null;\n fallbackText = null;\n}\nfunction getData() {\n if (fallbackText) {\n return fallbackText;\n }\n\n var start;\n var startValue = startText;\n var startLength = startValue.length;\n var end;\n var endValue = getText();\n var endLength = endValue.length;\n\n for (start = 0; start < startLength; start++) {\n if (startValue[start] !== endValue[start]) {\n break;\n }\n }\n\n var minEnd = startLength - start;\n\n for (end = 1; end <= minEnd; end++) {\n if (startValue[startLength - end] !== endValue[endLength - end]) {\n break;\n }\n }\n\n var sliceTail = end > 1 ? 1 - end : undefined;\n fallbackText = endValue.slice(start, sliceTail);\n return fallbackText;\n}\nfunction getText() {\n if ('value' in root) {\n return root.value;\n }\n\n return root.textContent;\n}\n\nvar EVENT_POOL_SIZE = 10;\n/**\n * @interface Event\n * @see http://www.w3.org/TR/DOM-Level-3-Events/\n */\n\nvar EventInterface = {\n type: null,\n target: null,\n // currentTarget is set when dispatching; no use in copying it here\n currentTarget: function () {\n return null;\n },\n eventPhase: null,\n bubbles: null,\n cancelable: null,\n timeStamp: function (event) {\n return event.timeStamp || Date.now();\n },\n defaultPrevented: null,\n isTrusted: null\n};\n\nfunction functionThatReturnsTrue() {\n return true;\n}\n\nfunction functionThatReturnsFalse() {\n return false;\n}\n/**\n * Synthetic events are dispatched by event plugins, typically in response to a\n * top-level event delegation handler.\n *\n * These systems should generally use pooling to reduce the frequency of garbage\n * collection. The system should check `isPersistent` to determine whether the\n * event should be released into the pool after being dispatched. Users that\n * need a persisted event should invoke `persist`.\n *\n * Synthetic events (and subclasses) implement the DOM Level 3 Events API by\n * normalizing browser quirks. Subclasses do not necessarily have to implement a\n * DOM interface; custom application-specific events can also subclass this.\n *\n * @param {object} dispatchConfig Configuration used to dispatch this event.\n * @param {*} targetInst Marker identifying the event target.\n * @param {object} nativeEvent Native browser event.\n * @param {DOMEventTarget} nativeEventTarget Target node.\n */\n\n\nfunction SyntheticEvent(dispatchConfig, targetInst, nativeEvent, nativeEventTarget) {\n {\n // these have a getter/setter for warnings\n delete this.nativeEvent;\n delete this.preventDefault;\n delete this.stopPropagation;\n delete this.isDefaultPrevented;\n delete this.isPropagationStopped;\n }\n\n this.dispatchConfig = dispatchConfig;\n this._targetInst = targetInst;\n this.nativeEvent = nativeEvent;\n var Interface = this.constructor.Interface;\n\n for (var propName in Interface) {\n if (!Interface.hasOwnProperty(propName)) {\n continue;\n }\n\n {\n delete this[propName]; // this has a getter/setter for warnings\n }\n\n var normalize = Interface[propName];\n\n if (normalize) {\n this[propName] = normalize(nativeEvent);\n } else {\n if (propName === 'target') {\n this.target = nativeEventTarget;\n } else {\n this[propName] = nativeEvent[propName];\n }\n }\n }\n\n var defaultPrevented = nativeEvent.defaultPrevented != null ? nativeEvent.defaultPrevented : nativeEvent.returnValue === false;\n\n if (defaultPrevented) {\n this.isDefaultPrevented = functionThatReturnsTrue;\n } else {\n this.isDefaultPrevented = functionThatReturnsFalse;\n }\n\n this.isPropagationStopped = functionThatReturnsFalse;\n return this;\n}\n\n_assign(SyntheticEvent.prototype, {\n preventDefault: function () {\n this.defaultPrevented = true;\n var event = this.nativeEvent;\n\n if (!event) {\n return;\n }\n\n if (event.preventDefault) {\n event.preventDefault();\n } else if (typeof event.returnValue !== 'unknown') {\n event.returnValue = false;\n }\n\n this.isDefaultPrevented = functionThatReturnsTrue;\n },\n stopPropagation: function () {\n var event = this.nativeEvent;\n\n if (!event) {\n return;\n }\n\n if (event.stopPropagation) {\n event.stopPropagation();\n } else if (typeof event.cancelBubble !== 'unknown') {\n // The ChangeEventPlugin registers a \"propertychange\" event for\n // IE. This event does not support bubbling or cancelling, and\n // any references to cancelBubble throw \"Member not found\". A\n // typeof check of \"unknown\" circumvents this issue (and is also\n // IE specific).\n event.cancelBubble = true;\n }\n\n this.isPropagationStopped = functionThatReturnsTrue;\n },\n\n /**\n * We release all dispatched `SyntheticEvent`s after each event loop, adding\n * them back into the pool. This allows a way to hold onto a reference that\n * won't be added back into the pool.\n */\n persist: function () {\n this.isPersistent = functionThatReturnsTrue;\n },\n\n /**\n * Checks if this event should be released back into the pool.\n *\n * @return {boolean} True if this should not be released, false otherwise.\n */\n isPersistent: functionThatReturnsFalse,\n\n /**\n * `PooledClass` looks for `destructor` on each instance it releases.\n */\n destructor: function () {\n var Interface = this.constructor.Interface;\n\n for (var propName in Interface) {\n {\n Object.defineProperty(this, propName, getPooledWarningPropertyDefinition(propName, Interface[propName]));\n }\n }\n\n this.dispatchConfig = null;\n this._targetInst = null;\n this.nativeEvent = null;\n this.isDefaultPrevented = functionThatReturnsFalse;\n this.isPropagationStopped = functionThatReturnsFalse;\n this._dispatchListeners = null;\n this._dispatchInstances = null;\n\n {\n Object.defineProperty(this, 'nativeEvent', getPooledWarningPropertyDefinition('nativeEvent', null));\n Object.defineProperty(this, 'isDefaultPrevented', getPooledWarningPropertyDefinition('isDefaultPrevented', functionThatReturnsFalse));\n Object.defineProperty(this, 'isPropagationStopped', getPooledWarningPropertyDefinition('isPropagationStopped', functionThatReturnsFalse));\n Object.defineProperty(this, 'preventDefault', getPooledWarningPropertyDefinition('preventDefault', function () {}));\n Object.defineProperty(this, 'stopPropagation', getPooledWarningPropertyDefinition('stopPropagation', function () {}));\n }\n }\n});\n\nSyntheticEvent.Interface = EventInterface;\n/**\n * Helper to reduce boilerplate when creating subclasses.\n */\n\nSyntheticEvent.extend = function (Interface) {\n var Super = this;\n\n var E = function () {};\n\n E.prototype = Super.prototype;\n var prototype = new E();\n\n function Class() {\n return Super.apply(this, arguments);\n }\n\n _assign(prototype, Class.prototype);\n\n Class.prototype = prototype;\n Class.prototype.constructor = Class;\n Class.Interface = _assign({}, Super.Interface, Interface);\n Class.extend = Super.extend;\n addEventPoolingTo(Class);\n return Class;\n};\n\naddEventPoolingTo(SyntheticEvent);\n/**\n * Helper to nullify syntheticEvent instance properties when destructing\n *\n * @param {String} propName\n * @param {?object} getVal\n * @return {object} defineProperty object\n */\n\nfunction getPooledWarningPropertyDefinition(propName, getVal) {\n var isFunction = typeof getVal === 'function';\n return {\n configurable: true,\n set: set,\n get: get\n };\n\n function set(val) {\n var action = isFunction ? 'setting the method' : 'setting the property';\n warn(action, 'This is effectively a no-op');\n return val;\n }\n\n function get() {\n var action = isFunction ? 'accessing the method' : 'accessing the property';\n var result = isFunction ? 'This is a no-op function' : 'This is set to null';\n warn(action, result);\n return getVal;\n }\n\n function warn(action, result) {\n {\n error(\"This synthetic event is reused for performance reasons. If you're seeing this, \" + \"you're %s `%s` on a released/nullified synthetic event. %s. \" + 'If you must keep the original synthetic event around, use event.persist(). ' + 'See https://fb.me/react-event-pooling for more information.', action, propName, result);\n }\n }\n}\n\nfunction getPooledEvent(dispatchConfig, targetInst, nativeEvent, nativeInst) {\n var EventConstructor = this;\n\n if (EventConstructor.eventPool.length) {\n var instance = EventConstructor.eventPool.pop();\n EventConstructor.call(instance, dispatchConfig, targetInst, nativeEvent, nativeInst);\n return instance;\n }\n\n return new EventConstructor(dispatchConfig, targetInst, nativeEvent, nativeInst);\n}\n\nfunction releasePooledEvent(event) {\n var EventConstructor = this;\n\n if (!(event instanceof EventConstructor)) {\n {\n throw Error( \"Trying to release an event instance into a pool of a different type.\" );\n }\n }\n\n event.destructor();\n\n if (EventConstructor.eventPool.length < EVENT_POOL_SIZE) {\n EventConstructor.eventPool.push(event);\n }\n}\n\nfunction addEventPoolingTo(EventConstructor) {\n EventConstructor.eventPool = [];\n EventConstructor.getPooled = getPooledEvent;\n EventConstructor.release = releasePooledEvent;\n}\n\n/**\n * @interface Event\n * @see http://www.w3.org/TR/DOM-Level-3-Events/#events-compositionevents\n */\n\nvar SyntheticCompositionEvent = SyntheticEvent.extend({\n data: null\n});\n\n/**\n * @interface Event\n * @see http://www.w3.org/TR/2013/WD-DOM-Level-3-Events-20131105\n * /#events-inputevents\n */\n\nvar SyntheticInputEvent = SyntheticEvent.extend({\n data: null\n});\n\nvar END_KEYCODES = [9, 13, 27, 32]; // Tab, Return, Esc, Space\n\nvar START_KEYCODE = 229;\nvar canUseCompositionEvent = canUseDOM && 'CompositionEvent' in window;\nvar documentMode = null;\n\nif (canUseDOM && 'documentMode' in document) {\n documentMode = document.documentMode;\n} // Webkit offers a very useful `textInput` event that can be used to\n// directly represent `beforeInput`. The IE `textinput` event is not as\n// useful, so we don't use it.\n\n\nvar canUseTextInputEvent = canUseDOM && 'TextEvent' in window && !documentMode; // In IE9+, we have access to composition events, but the data supplied\n// by the native compositionend event may be incorrect. Japanese ideographic\n// spaces, for instance (\\u3000) are not recorded correctly.\n\nvar useFallbackCompositionData = canUseDOM && (!canUseCompositionEvent || documentMode && documentMode > 8 && documentMode <= 11);\nvar SPACEBAR_CODE = 32;\nvar SPACEBAR_CHAR = String.fromCharCode(SPACEBAR_CODE); // Events and their corresponding property names.\n\nvar eventTypes = {\n beforeInput: {\n phasedRegistrationNames: {\n bubbled: 'onBeforeInput',\n captured: 'onBeforeInputCapture'\n },\n dependencies: [TOP_COMPOSITION_END, TOP_KEY_PRESS, TOP_TEXT_INPUT, TOP_PASTE]\n },\n compositionEnd: {\n phasedRegistrationNames: {\n bubbled: 'onCompositionEnd',\n captured: 'onCompositionEndCapture'\n },\n dependencies: [TOP_BLUR, TOP_COMPOSITION_END, TOP_KEY_DOWN, TOP_KEY_PRESS, TOP_KEY_UP, TOP_MOUSE_DOWN]\n },\n compositionStart: {\n phasedRegistrationNames: {\n bubbled: 'onCompositionStart',\n captured: 'onCompositionStartCapture'\n },\n dependencies: [TOP_BLUR, TOP_COMPOSITION_START, TOP_KEY_DOWN, TOP_KEY_PRESS, TOP_KEY_UP, TOP_MOUSE_DOWN]\n },\n compositionUpdate: {\n phasedRegistrationNames: {\n bubbled: 'onCompositionUpdate',\n captured: 'onCompositionUpdateCapture'\n },\n dependencies: [TOP_BLUR, TOP_COMPOSITION_UPDATE, TOP_KEY_DOWN, TOP_KEY_PRESS, TOP_KEY_UP, TOP_MOUSE_DOWN]\n }\n}; // Track whether we've ever handled a keypress on the space key.\n\nvar hasSpaceKeypress = false;\n/**\n * Return whether a native keypress event is assumed to be a command.\n * This is required because Firefox fires `keypress` events for key commands\n * (cut, copy, select-all, etc.) even though no character is inserted.\n */\n\nfunction isKeypressCommand(nativeEvent) {\n return (nativeEvent.ctrlKey || nativeEvent.altKey || nativeEvent.metaKey) && // ctrlKey && altKey is equivalent to AltGr, and is not a command.\n !(nativeEvent.ctrlKey && nativeEvent.altKey);\n}\n/**\n * Translate native top level events into event types.\n *\n * @param {string} topLevelType\n * @return {object}\n */\n\n\nfunction getCompositionEventType(topLevelType) {\n switch (topLevelType) {\n case TOP_COMPOSITION_START:\n return eventTypes.compositionStart;\n\n case TOP_COMPOSITION_END:\n return eventTypes.compositionEnd;\n\n case TOP_COMPOSITION_UPDATE:\n return eventTypes.compositionUpdate;\n }\n}\n/**\n * Does our fallback best-guess model think this event signifies that\n * composition has begun?\n *\n * @param {string} topLevelType\n * @param {object} nativeEvent\n * @return {boolean}\n */\n\n\nfunction isFallbackCompositionStart(topLevelType, nativeEvent) {\n return topLevelType === TOP_KEY_DOWN && nativeEvent.keyCode === START_KEYCODE;\n}\n/**\n * Does our fallback mode think that this event is the end of composition?\n *\n * @param {string} topLevelType\n * @param {object} nativeEvent\n * @return {boolean}\n */\n\n\nfunction isFallbackCompositionEnd(topLevelType, nativeEvent) {\n switch (topLevelType) {\n case TOP_KEY_UP:\n // Command keys insert or clear IME input.\n return END_KEYCODES.indexOf(nativeEvent.keyCode) !== -1;\n\n case TOP_KEY_DOWN:\n // Expect IME keyCode on each keydown. If we get any other\n // code we must have exited earlier.\n return nativeEvent.keyCode !== START_KEYCODE;\n\n case TOP_KEY_PRESS:\n case TOP_MOUSE_DOWN:\n case TOP_BLUR:\n // Events are not possible without cancelling IME.\n return true;\n\n default:\n return false;\n }\n}\n/**\n * Google Input Tools provides composition data via a CustomEvent,\n * with the `data` property populated in the `detail` object. If this\n * is available on the event object, use it. If not, this is a plain\n * composition event and we have nothing special to extract.\n *\n * @param {object} nativeEvent\n * @return {?string}\n */\n\n\nfunction getDataFromCustomEvent(nativeEvent) {\n var detail = nativeEvent.detail;\n\n if (typeof detail === 'object' && 'data' in detail) {\n return detail.data;\n }\n\n return null;\n}\n/**\n * Check if a composition event was triggered by Korean IME.\n * Our fallback mode does not work well with IE's Korean IME,\n * so just use native composition events when Korean IME is used.\n * Although CompositionEvent.locale property is deprecated,\n * it is available in IE, where our fallback mode is enabled.\n *\n * @param {object} nativeEvent\n * @return {boolean}\n */\n\n\nfunction isUsingKoreanIME(nativeEvent) {\n return nativeEvent.locale === 'ko';\n} // Track the current IME composition status, if any.\n\n\nvar isComposing = false;\n/**\n * @return {?object} A SyntheticCompositionEvent.\n */\n\nfunction extractCompositionEvent(topLevelType, targetInst, nativeEvent, nativeEventTarget) {\n var eventType;\n var fallbackData;\n\n if (canUseCompositionEvent) {\n eventType = getCompositionEventType(topLevelType);\n } else if (!isComposing) {\n if (isFallbackCompositionStart(topLevelType, nativeEvent)) {\n eventType = eventTypes.compositionStart;\n }\n } else if (isFallbackCompositionEnd(topLevelType, nativeEvent)) {\n eventType = eventTypes.compositionEnd;\n }\n\n if (!eventType) {\n return null;\n }\n\n if (useFallbackCompositionData && !isUsingKoreanIME(nativeEvent)) {\n // The current composition is stored statically and must not be\n // overwritten while composition continues.\n if (!isComposing && eventType === eventTypes.compositionStart) {\n isComposing = initialize(nativeEventTarget);\n } else if (eventType === eventTypes.compositionEnd) {\n if (isComposing) {\n fallbackData = getData();\n }\n }\n }\n\n var event = SyntheticCompositionEvent.getPooled(eventType, targetInst, nativeEvent, nativeEventTarget);\n\n if (fallbackData) {\n // Inject data generated from fallback path into the synthetic event.\n // This matches the property of native CompositionEventInterface.\n event.data = fallbackData;\n } else {\n var customData = getDataFromCustomEvent(nativeEvent);\n\n if (customData !== null) {\n event.data = customData;\n }\n }\n\n accumulateTwoPhaseDispatches(event);\n return event;\n}\n/**\n * @param {TopLevelType} topLevelType Number from `TopLevelType`.\n * @param {object} nativeEvent Native browser event.\n * @return {?string} The string corresponding to this `beforeInput` event.\n */\n\n\nfunction getNativeBeforeInputChars(topLevelType, nativeEvent) {\n switch (topLevelType) {\n case TOP_COMPOSITION_END:\n return getDataFromCustomEvent(nativeEvent);\n\n case TOP_KEY_PRESS:\n /**\n * If native `textInput` events are available, our goal is to make\n * use of them. However, there is a special case: the spacebar key.\n * In Webkit, preventing default on a spacebar `textInput` event\n * cancels character insertion, but it *also* causes the browser\n * to fall back to its default spacebar behavior of scrolling the\n * page.\n *\n * Tracking at:\n * https://code.google.com/p/chromium/issues/detail?id=355103\n *\n * To avoid this issue, use the keypress event as if no `textInput`\n * event is available.\n */\n var which = nativeEvent.which;\n\n if (which !== SPACEBAR_CODE) {\n return null;\n }\n\n hasSpaceKeypress = true;\n return SPACEBAR_CHAR;\n\n case TOP_TEXT_INPUT:\n // Record the characters to be added to the DOM.\n var chars = nativeEvent.data; // If it's a spacebar character, assume that we have already handled\n // it at the keypress level and bail immediately. Android Chrome\n // doesn't give us keycodes, so we need to ignore it.\n\n if (chars === SPACEBAR_CHAR && hasSpaceKeypress) {\n return null;\n }\n\n return chars;\n\n default:\n // For other native event types, do nothing.\n return null;\n }\n}\n/**\n * For browsers that do not provide the `textInput` event, extract the\n * appropriate string to use for SyntheticInputEvent.\n *\n * @param {number} topLevelType Number from `TopLevelEventTypes`.\n * @param {object} nativeEvent Native browser event.\n * @return {?string} The fallback string for this `beforeInput` event.\n */\n\n\nfunction getFallbackBeforeInputChars(topLevelType, nativeEvent) {\n // If we are currently composing (IME) and using a fallback to do so,\n // try to extract the composed characters from the fallback object.\n // If composition event is available, we extract a string only at\n // compositionevent, otherwise extract it at fallback events.\n if (isComposing) {\n if (topLevelType === TOP_COMPOSITION_END || !canUseCompositionEvent && isFallbackCompositionEnd(topLevelType, nativeEvent)) {\n var chars = getData();\n reset();\n isComposing = false;\n return chars;\n }\n\n return null;\n }\n\n switch (topLevelType) {\n case TOP_PASTE:\n // If a paste event occurs after a keypress, throw out the input\n // chars. Paste events should not lead to BeforeInput events.\n return null;\n\n case TOP_KEY_PRESS:\n /**\n * As of v27, Firefox may fire keypress events even when no character\n * will be inserted. A few possibilities:\n *\n * - `which` is `0`. Arrow keys, Esc key, etc.\n *\n * - `which` is the pressed key code, but no char is available.\n * Ex: 'AltGr + d` in Polish. There is no modified character for\n * this key combination and no character is inserted into the\n * document, but FF fires the keypress for char code `100` anyway.\n * No `input` event will occur.\n *\n * - `which` is the pressed key code, but a command combination is\n * being used. Ex: `Cmd+C`. No character is inserted, and no\n * `input` event will occur.\n */\n if (!isKeypressCommand(nativeEvent)) {\n // IE fires the `keypress` event when a user types an emoji via\n // Touch keyboard of Windows. In such a case, the `char` property\n // holds an emoji character like `\\uD83D\\uDE0A`. Because its length\n // is 2, the property `which` does not represent an emoji correctly.\n // In such a case, we directly return the `char` property instead of\n // using `which`.\n if (nativeEvent.char && nativeEvent.char.length > 1) {\n return nativeEvent.char;\n } else if (nativeEvent.which) {\n return String.fromCharCode(nativeEvent.which);\n }\n }\n\n return null;\n\n case TOP_COMPOSITION_END:\n return useFallbackCompositionData && !isUsingKoreanIME(nativeEvent) ? null : nativeEvent.data;\n\n default:\n return null;\n }\n}\n/**\n * Extract a SyntheticInputEvent for `beforeInput`, based on either native\n * `textInput` or fallback behavior.\n *\n * @return {?object} A SyntheticInputEvent.\n */\n\n\nfunction extractBeforeInputEvent(topLevelType, targetInst, nativeEvent, nativeEventTarget) {\n var chars;\n\n if (canUseTextInputEvent) {\n chars = getNativeBeforeInputChars(topLevelType, nativeEvent);\n } else {\n chars = getFallbackBeforeInputChars(topLevelType, nativeEvent);\n } // If no characters are being inserted, no BeforeInput event should\n // be fired.\n\n\n if (!chars) {\n return null;\n }\n\n var event = SyntheticInputEvent.getPooled(eventTypes.beforeInput, targetInst, nativeEvent, nativeEventTarget);\n event.data = chars;\n accumulateTwoPhaseDispatches(event);\n return event;\n}\n/**\n * Create an `onBeforeInput` event to match\n * http://www.w3.org/TR/2013/WD-DOM-Level-3-Events-20131105/#events-inputevents.\n *\n * This event plugin is based on the native `textInput` event\n * available in Chrome, Safari, Opera, and IE. This event fires after\n * `onKeyPress` and `onCompositionEnd`, but before `onInput`.\n *\n * `beforeInput` is spec'd but not implemented in any browsers, and\n * the `input` event does not provide any useful information about what has\n * actually been added, contrary to the spec. Thus, `textInput` is the best\n * available event to identify the characters that have actually been inserted\n * into the target node.\n *\n * This plugin is also responsible for emitting `composition` events, thus\n * allowing us to share composition fallback code for both `beforeInput` and\n * `composition` event types.\n */\n\n\nvar BeforeInputEventPlugin = {\n eventTypes: eventTypes,\n extractEvents: function (topLevelType, targetInst, nativeEvent, nativeEventTarget, eventSystemFlags) {\n var composition = extractCompositionEvent(topLevelType, targetInst, nativeEvent, nativeEventTarget);\n var beforeInput = extractBeforeInputEvent(topLevelType, targetInst, nativeEvent, nativeEventTarget);\n\n if (composition === null) {\n return beforeInput;\n }\n\n if (beforeInput === null) {\n return composition;\n }\n\n return [composition, beforeInput];\n }\n};\n\n/**\n * @see http://www.whatwg.org/specs/web-apps/current-work/multipage/the-input-element.html#input-type-attr-summary\n */\nvar supportedInputTypes = {\n color: true,\n date: true,\n datetime: true,\n 'datetime-local': true,\n email: true,\n month: true,\n number: true,\n password: true,\n range: true,\n search: true,\n tel: true,\n text: true,\n time: true,\n url: true,\n week: true\n};\n\nfunction isTextInputElement(elem) {\n var nodeName = elem && elem.nodeName && elem.nodeName.toLowerCase();\n\n if (nodeName === 'input') {\n return !!supportedInputTypes[elem.type];\n }\n\n if (nodeName === 'textarea') {\n return true;\n }\n\n return false;\n}\n\nvar eventTypes$1 = {\n change: {\n phasedRegistrationNames: {\n bubbled: 'onChange',\n captured: 'onChangeCapture'\n },\n dependencies: [TOP_BLUR, TOP_CHANGE, TOP_CLICK, TOP_FOCUS, TOP_INPUT, TOP_KEY_DOWN, TOP_KEY_UP, TOP_SELECTION_CHANGE]\n }\n};\n\nfunction createAndAccumulateChangeEvent(inst, nativeEvent, target) {\n var event = SyntheticEvent.getPooled(eventTypes$1.change, inst, nativeEvent, target);\n event.type = 'change'; // Flag this event loop as needing state restore.\n\n enqueueStateRestore(target);\n accumulateTwoPhaseDispatches(event);\n return event;\n}\n/**\n * For IE shims\n */\n\n\nvar activeElement = null;\nvar activeElementInst = null;\n/**\n * SECTION: handle `change` event\n */\n\nfunction shouldUseChangeEvent(elem) {\n var nodeName = elem.nodeName && elem.nodeName.toLowerCase();\n return nodeName === 'select' || nodeName === 'input' && elem.type === 'file';\n}\n\nfunction manualDispatchChangeEvent(nativeEvent) {\n var event = createAndAccumulateChangeEvent(activeElementInst, nativeEvent, getEventTarget(nativeEvent)); // If change and propertychange bubbled, we'd just bind to it like all the\n // other events and have it go through ReactBrowserEventEmitter. Since it\n // doesn't, we manually listen for the events and so we have to enqueue and\n // process the abstract event manually.\n //\n // Batching is necessary here in order to ensure that all event handlers run\n // before the next rerender (including event handlers attached to ancestor\n // elements instead of directly on the input). Without this, controlled\n // components don't work properly in conjunction with event bubbling because\n // the component is rerendered and the value reverted before all the event\n // handlers can run. See https://github.com/facebook/react/issues/708.\n\n batchedUpdates(runEventInBatch, event);\n}\n\nfunction runEventInBatch(event) {\n runEventsInBatch(event);\n}\n\nfunction getInstIfValueChanged(targetInst) {\n var targetNode = getNodeFromInstance$1(targetInst);\n\n if (updateValueIfChanged(targetNode)) {\n return targetInst;\n }\n}\n\nfunction getTargetInstForChangeEvent(topLevelType, targetInst) {\n if (topLevelType === TOP_CHANGE) {\n return targetInst;\n }\n}\n/**\n * SECTION: handle `input` event\n */\n\n\nvar isInputEventSupported = false;\n\nif (canUseDOM) {\n // IE9 claims to support the input event but fails to trigger it when\n // deleting text, so we ignore its input events.\n isInputEventSupported = isEventSupported('input') && (!document.documentMode || document.documentMode > 9);\n}\n/**\n * (For IE <=9) Starts tracking propertychange events on the passed-in element\n * and override the value property so that we can distinguish user events from\n * value changes in JS.\n */\n\n\nfunction startWatchingForValueChange(target, targetInst) {\n activeElement = target;\n activeElementInst = targetInst;\n activeElement.attachEvent('onpropertychange', handlePropertyChange);\n}\n/**\n * (For IE <=9) Removes the event listeners from the currently-tracked element,\n * if any exists.\n */\n\n\nfunction stopWatchingForValueChange() {\n if (!activeElement) {\n return;\n }\n\n activeElement.detachEvent('onpropertychange', handlePropertyChange);\n activeElement = null;\n activeElementInst = null;\n}\n/**\n * (For IE <=9) Handles a propertychange event, sending a `change` event if\n * the value of the active element has changed.\n */\n\n\nfunction handlePropertyChange(nativeEvent) {\n if (nativeEvent.propertyName !== 'value') {\n return;\n }\n\n if (getInstIfValueChanged(activeElementInst)) {\n manualDispatchChangeEvent(nativeEvent);\n }\n}\n\nfunction handleEventsForInputEventPolyfill(topLevelType, target, targetInst) {\n if (topLevelType === TOP_FOCUS) {\n // In IE9, propertychange fires for most input events but is buggy and\n // doesn't fire when text is deleted, but conveniently, selectionchange\n // appears to fire in all of the remaining cases so we catch those and\n // forward the event if the value has changed\n // In either case, we don't want to call the event handler if the value\n // is changed from JS so we redefine a setter for `.value` that updates\n // our activeElementValue variable, allowing us to ignore those changes\n //\n // stopWatching() should be a noop here but we call it just in case we\n // missed a blur event somehow.\n stopWatchingForValueChange();\n startWatchingForValueChange(target, targetInst);\n } else if (topLevelType === TOP_BLUR) {\n stopWatchingForValueChange();\n }\n} // For IE8 and IE9.\n\n\nfunction getTargetInstForInputEventPolyfill(topLevelType, targetInst) {\n if (topLevelType === TOP_SELECTION_CHANGE || topLevelType === TOP_KEY_UP || topLevelType === TOP_KEY_DOWN) {\n // On the selectionchange event, the target is just document which isn't\n // helpful for us so just check activeElement instead.\n //\n // 99% of the time, keydown and keyup aren't necessary. IE8 fails to fire\n // propertychange on the first input event after setting `value` from a\n // script and fires only keydown, keypress, keyup. Catching keyup usually\n // gets it and catching keydown lets us fire an event for the first\n // keystroke if user does a key repeat (it'll be a little delayed: right\n // before the second keystroke). Other input methods (e.g., paste) seem to\n // fire selectionchange normally.\n return getInstIfValueChanged(activeElementInst);\n }\n}\n/**\n * SECTION: handle `click` event\n */\n\n\nfunction shouldUseClickEvent(elem) {\n // Use the `click` event to detect changes to checkbox and radio inputs.\n // This approach works across all browsers, whereas `change` does not fire\n // until `blur` in IE8.\n var nodeName = elem.nodeName;\n return nodeName && nodeName.toLowerCase() === 'input' && (elem.type === 'checkbox' || elem.type === 'radio');\n}\n\nfunction getTargetInstForClickEvent(topLevelType, targetInst) {\n if (topLevelType === TOP_CLICK) {\n return getInstIfValueChanged(targetInst);\n }\n}\n\nfunction getTargetInstForInputOrChangeEvent(topLevelType, targetInst) {\n if (topLevelType === TOP_INPUT || topLevelType === TOP_CHANGE) {\n return getInstIfValueChanged(targetInst);\n }\n}\n\nfunction handleControlledInputBlur(node) {\n var state = node._wrapperState;\n\n if (!state || !state.controlled || node.type !== 'number') {\n return;\n }\n\n {\n // If controlled, assign the value attribute to the current value on blur\n setDefaultValue(node, 'number', node.value);\n }\n}\n/**\n * This plugin creates an `onChange` event that normalizes change events\n * across form elements. This event fires at a time when it's possible to\n * change the element's value without seeing a flicker.\n *\n * Supported elements are:\n * - input (see `isTextInputElement`)\n * - textarea\n * - select\n */\n\n\nvar ChangeEventPlugin = {\n eventTypes: eventTypes$1,\n _isInputEventSupported: isInputEventSupported,\n extractEvents: function (topLevelType, targetInst, nativeEvent, nativeEventTarget, eventSystemFlags) {\n var targetNode = targetInst ? getNodeFromInstance$1(targetInst) : window;\n var getTargetInstFunc, handleEventFunc;\n\n if (shouldUseChangeEvent(targetNode)) {\n getTargetInstFunc = getTargetInstForChangeEvent;\n } else if (isTextInputElement(targetNode)) {\n if (isInputEventSupported) {\n getTargetInstFunc = getTargetInstForInputOrChangeEvent;\n } else {\n getTargetInstFunc = getTargetInstForInputEventPolyfill;\n handleEventFunc = handleEventsForInputEventPolyfill;\n }\n } else if (shouldUseClickEvent(targetNode)) {\n getTargetInstFunc = getTargetInstForClickEvent;\n }\n\n if (getTargetInstFunc) {\n var inst = getTargetInstFunc(topLevelType, targetInst);\n\n if (inst) {\n var event = createAndAccumulateChangeEvent(inst, nativeEvent, nativeEventTarget);\n return event;\n }\n }\n\n if (handleEventFunc) {\n handleEventFunc(topLevelType, targetNode, targetInst);\n } // When blurring, set the value attribute for number inputs\n\n\n if (topLevelType === TOP_BLUR) {\n handleControlledInputBlur(targetNode);\n }\n }\n};\n\nvar SyntheticUIEvent = SyntheticEvent.extend({\n view: null,\n detail: null\n});\n\n/**\n * Translation from modifier key to the associated property in the event.\n * @see http://www.w3.org/TR/DOM-Level-3-Events/#keys-Modifiers\n */\nvar modifierKeyToProp = {\n Alt: 'altKey',\n Control: 'ctrlKey',\n Meta: 'metaKey',\n Shift: 'shiftKey'\n}; // Older browsers (Safari <= 10, iOS Safari <= 10.2) do not support\n// getModifierState. If getModifierState is not supported, we map it to a set of\n// modifier keys exposed by the event. In this case, Lock-keys are not supported.\n\nfunction modifierStateGetter(keyArg) {\n var syntheticEvent = this;\n var nativeEvent = syntheticEvent.nativeEvent;\n\n if (nativeEvent.getModifierState) {\n return nativeEvent.getModifierState(keyArg);\n }\n\n var keyProp = modifierKeyToProp[keyArg];\n return keyProp ? !!nativeEvent[keyProp] : false;\n}\n\nfunction getEventModifierState(nativeEvent) {\n return modifierStateGetter;\n}\n\nvar previousScreenX = 0;\nvar previousScreenY = 0; // Use flags to signal movementX/Y has already been set\n\nvar isMovementXSet = false;\nvar isMovementYSet = false;\n/**\n * @interface MouseEvent\n * @see http://www.w3.org/TR/DOM-Level-3-Events/\n */\n\nvar SyntheticMouseEvent = SyntheticUIEvent.extend({\n screenX: null,\n screenY: null,\n clientX: null,\n clientY: null,\n pageX: null,\n pageY: null,\n ctrlKey: null,\n shiftKey: null,\n altKey: null,\n metaKey: null,\n getModifierState: getEventModifierState,\n button: null,\n buttons: null,\n relatedTarget: function (event) {\n return event.relatedTarget || (event.fromElement === event.srcElement ? event.toElement : event.fromElement);\n },\n movementX: function (event) {\n if ('movementX' in event) {\n return event.movementX;\n }\n\n var screenX = previousScreenX;\n previousScreenX = event.screenX;\n\n if (!isMovementXSet) {\n isMovementXSet = true;\n return 0;\n }\n\n return event.type === 'mousemove' ? event.screenX - screenX : 0;\n },\n movementY: function (event) {\n if ('movementY' in event) {\n return event.movementY;\n }\n\n var screenY = previousScreenY;\n previousScreenY = event.screenY;\n\n if (!isMovementYSet) {\n isMovementYSet = true;\n return 0;\n }\n\n return event.type === 'mousemove' ? event.screenY - screenY : 0;\n }\n});\n\n/**\n * @interface PointerEvent\n * @see http://www.w3.org/TR/pointerevents/\n */\n\nvar SyntheticPointerEvent = SyntheticMouseEvent.extend({\n pointerId: null,\n width: null,\n height: null,\n pressure: null,\n tangentialPressure: null,\n tiltX: null,\n tiltY: null,\n twist: null,\n pointerType: null,\n isPrimary: null\n});\n\nvar eventTypes$2 = {\n mouseEnter: {\n registrationName: 'onMouseEnter',\n dependencies: [TOP_MOUSE_OUT, TOP_MOUSE_OVER]\n },\n mouseLeave: {\n registrationName: 'onMouseLeave',\n dependencies: [TOP_MOUSE_OUT, TOP_MOUSE_OVER]\n },\n pointerEnter: {\n registrationName: 'onPointerEnter',\n dependencies: [TOP_POINTER_OUT, TOP_POINTER_OVER]\n },\n pointerLeave: {\n registrationName: 'onPointerLeave',\n dependencies: [TOP_POINTER_OUT, TOP_POINTER_OVER]\n }\n};\nvar EnterLeaveEventPlugin = {\n eventTypes: eventTypes$2,\n\n /**\n * For almost every interaction we care about, there will be both a top-level\n * `mouseover` and `mouseout` event that occurs. Only use `mouseout` so that\n * we do not extract duplicate events. However, moving the mouse into the\n * browser from outside will not fire a `mouseout` event. In this case, we use\n * the `mouseover` top-level event.\n */\n extractEvents: function (topLevelType, targetInst, nativeEvent, nativeEventTarget, eventSystemFlags) {\n var isOverEvent = topLevelType === TOP_MOUSE_OVER || topLevelType === TOP_POINTER_OVER;\n var isOutEvent = topLevelType === TOP_MOUSE_OUT || topLevelType === TOP_POINTER_OUT;\n\n if (isOverEvent && (eventSystemFlags & IS_REPLAYED) === 0 && (nativeEvent.relatedTarget || nativeEvent.fromElement)) {\n // If this is an over event with a target, then we've already dispatched\n // the event in the out event of the other target. If this is replayed,\n // then it's because we couldn't dispatch against this target previously\n // so we have to do it now instead.\n return null;\n }\n\n if (!isOutEvent && !isOverEvent) {\n // Must not be a mouse or pointer in or out - ignoring.\n return null;\n }\n\n var win;\n\n if (nativeEventTarget.window === nativeEventTarget) {\n // `nativeEventTarget` is probably a window object.\n win = nativeEventTarget;\n } else {\n // TODO: Figure out why `ownerDocument` is sometimes undefined in IE8.\n var doc = nativeEventTarget.ownerDocument;\n\n if (doc) {\n win = doc.defaultView || doc.parentWindow;\n } else {\n win = window;\n }\n }\n\n var from;\n var to;\n\n if (isOutEvent) {\n from = targetInst;\n var related = nativeEvent.relatedTarget || nativeEvent.toElement;\n to = related ? getClosestInstanceFromNode(related) : null;\n\n if (to !== null) {\n var nearestMounted = getNearestMountedFiber(to);\n\n if (to !== nearestMounted || to.tag !== HostComponent && to.tag !== HostText) {\n to = null;\n }\n }\n } else {\n // Moving to a node from outside the window.\n from = null;\n to = targetInst;\n }\n\n if (from === to) {\n // Nothing pertains to our managed components.\n return null;\n }\n\n var eventInterface, leaveEventType, enterEventType, eventTypePrefix;\n\n if (topLevelType === TOP_MOUSE_OUT || topLevelType === TOP_MOUSE_OVER) {\n eventInterface = SyntheticMouseEvent;\n leaveEventType = eventTypes$2.mouseLeave;\n enterEventType = eventTypes$2.mouseEnter;\n eventTypePrefix = 'mouse';\n } else if (topLevelType === TOP_POINTER_OUT || topLevelType === TOP_POINTER_OVER) {\n eventInterface = SyntheticPointerEvent;\n leaveEventType = eventTypes$2.pointerLeave;\n enterEventType = eventTypes$2.pointerEnter;\n eventTypePrefix = 'pointer';\n }\n\n var fromNode = from == null ? win : getNodeFromInstance$1(from);\n var toNode = to == null ? win : getNodeFromInstance$1(to);\n var leave = eventInterface.getPooled(leaveEventType, from, nativeEvent, nativeEventTarget);\n leave.type = eventTypePrefix + 'leave';\n leave.target = fromNode;\n leave.relatedTarget = toNode;\n var enter = eventInterface.getPooled(enterEventType, to, nativeEvent, nativeEventTarget);\n enter.type = eventTypePrefix + 'enter';\n enter.target = toNode;\n enter.relatedTarget = fromNode;\n accumulateEnterLeaveDispatches(leave, enter, from, to); // If we are not processing the first ancestor, then we\n // should not process the same nativeEvent again, as we\n // will have already processed it in the first ancestor.\n\n if ((eventSystemFlags & IS_FIRST_ANCESTOR) === 0) {\n return [leave];\n }\n\n return [leave, enter];\n }\n};\n\n/**\n * inlined Object.is polyfill to avoid requiring consumers ship their own\n * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is\n */\nfunction is(x, y) {\n return x === y && (x !== 0 || 1 / x === 1 / y) || x !== x && y !== y // eslint-disable-line no-self-compare\n ;\n}\n\nvar objectIs = typeof Object.is === 'function' ? Object.is : is;\n\nvar hasOwnProperty$2 = Object.prototype.hasOwnProperty;\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 * Returns true when the values of all keys are strictly equal.\n */\n\nfunction shallowEqual(objA, objB) {\n if (objectIs(objA, objB)) {\n return true;\n }\n\n if (typeof objA !== 'object' || objA === null || typeof objB !== 'object' || objB === null) {\n return false;\n }\n\n var keysA = Object.keys(objA);\n var keysB = Object.keys(objB);\n\n if (keysA.length !== keysB.length) {\n return false;\n } // Test for A's keys different from B.\n\n\n for (var i = 0; i < keysA.length; i++) {\n if (!hasOwnProperty$2.call(objB, keysA[i]) || !objectIs(objA[keysA[i]], objB[keysA[i]])) {\n return false;\n }\n }\n\n return true;\n}\n\nvar skipSelectionChangeEvent = canUseDOM && 'documentMode' in document && document.documentMode <= 11;\nvar eventTypes$3 = {\n select: {\n phasedRegistrationNames: {\n bubbled: 'onSelect',\n captured: 'onSelectCapture'\n },\n dependencies: [TOP_BLUR, TOP_CONTEXT_MENU, TOP_DRAG_END, TOP_FOCUS, TOP_KEY_DOWN, TOP_KEY_UP, TOP_MOUSE_DOWN, TOP_MOUSE_UP, TOP_SELECTION_CHANGE]\n }\n};\nvar activeElement$1 = null;\nvar activeElementInst$1 = null;\nvar lastSelection = null;\nvar mouseDown = false;\n/**\n * Get an object which is a unique representation of the current selection.\n *\n * The return value will not be consistent across nodes or browsers, but\n * two identical selections on the same node will return identical objects.\n *\n * @param {DOMElement} node\n * @return {object}\n */\n\nfunction getSelection$1(node) {\n if ('selectionStart' in node && hasSelectionCapabilities(node)) {\n return {\n start: node.selectionStart,\n end: node.selectionEnd\n };\n } else {\n var win = node.ownerDocument && node.ownerDocument.defaultView || window;\n var selection = win.getSelection();\n return {\n anchorNode: selection.anchorNode,\n anchorOffset: selection.anchorOffset,\n focusNode: selection.focusNode,\n focusOffset: selection.focusOffset\n };\n }\n}\n/**\n * Get document associated with the event target.\n *\n * @param {object} nativeEventTarget\n * @return {Document}\n */\n\n\nfunction getEventTargetDocument(eventTarget) {\n return eventTarget.window === eventTarget ? eventTarget.document : eventTarget.nodeType === DOCUMENT_NODE ? eventTarget : eventTarget.ownerDocument;\n}\n/**\n * Poll selection to see whether it's changed.\n *\n * @param {object} nativeEvent\n * @param {object} nativeEventTarget\n * @return {?SyntheticEvent}\n */\n\n\nfunction constructSelectEvent(nativeEvent, nativeEventTarget) {\n // Ensure we have the right element, and that the user is not dragging a\n // selection (this matches native `select` event behavior). In HTML5, select\n // fires only on input and textarea thus if there's no focused element we\n // won't dispatch.\n var doc = getEventTargetDocument(nativeEventTarget);\n\n if (mouseDown || activeElement$1 == null || activeElement$1 !== getActiveElement(doc)) {\n return null;\n } // Only fire when selection has actually changed.\n\n\n var currentSelection = getSelection$1(activeElement$1);\n\n if (!lastSelection || !shallowEqual(lastSelection, currentSelection)) {\n lastSelection = currentSelection;\n var syntheticEvent = SyntheticEvent.getPooled(eventTypes$3.select, activeElementInst$1, nativeEvent, nativeEventTarget);\n syntheticEvent.type = 'select';\n syntheticEvent.target = activeElement$1;\n accumulateTwoPhaseDispatches(syntheticEvent);\n return syntheticEvent;\n }\n\n return null;\n}\n/**\n * This plugin creates an `onSelect` event that normalizes select events\n * across form elements.\n *\n * Supported elements are:\n * - input (see `isTextInputElement`)\n * - textarea\n * - contentEditable\n *\n * This differs from native browser implementations in the following ways:\n * - Fires on contentEditable fields as well as inputs.\n * - Fires for collapsed selection.\n * - Fires after user input.\n */\n\n\nvar SelectEventPlugin = {\n eventTypes: eventTypes$3,\n extractEvents: function (topLevelType, targetInst, nativeEvent, nativeEventTarget, eventSystemFlags, container) {\n var containerOrDoc = container || getEventTargetDocument(nativeEventTarget); // Track whether all listeners exists for this plugin. If none exist, we do\n // not extract events. See #3639.\n\n if (!containerOrDoc || !isListeningToAllDependencies('onSelect', containerOrDoc)) {\n return null;\n }\n\n var targetNode = targetInst ? getNodeFromInstance$1(targetInst) : window;\n\n switch (topLevelType) {\n // Track the input node that has focus.\n case TOP_FOCUS:\n if (isTextInputElement(targetNode) || targetNode.contentEditable === 'true') {\n activeElement$1 = targetNode;\n activeElementInst$1 = targetInst;\n lastSelection = null;\n }\n\n break;\n\n case TOP_BLUR:\n activeElement$1 = null;\n activeElementInst$1 = null;\n lastSelection = null;\n break;\n // Don't fire the event while the user is dragging. This matches the\n // semantics of the native select event.\n\n case TOP_MOUSE_DOWN:\n mouseDown = true;\n break;\n\n case TOP_CONTEXT_MENU:\n case TOP_MOUSE_UP:\n case TOP_DRAG_END:\n mouseDown = false;\n return constructSelectEvent(nativeEvent, nativeEventTarget);\n // Chrome and IE fire non-standard event when selection is changed (and\n // sometimes when it hasn't). IE's event fires out of order with respect\n // to key and input events on deletion, so we discard it.\n //\n // Firefox doesn't support selectionchange, so check selection status\n // after each key entry. The selection changes after keydown and before\n // keyup, but we check on keydown as well in the case of holding down a\n // key, when multiple keydown events are fired but only one keyup is.\n // This is also our approach for IE handling, for the reason above.\n\n case TOP_SELECTION_CHANGE:\n if (skipSelectionChangeEvent) {\n break;\n }\n\n // falls through\n\n case TOP_KEY_DOWN:\n case TOP_KEY_UP:\n return constructSelectEvent(nativeEvent, nativeEventTarget);\n }\n\n return null;\n }\n};\n\n/**\n * @interface Event\n * @see http://www.w3.org/TR/css3-animations/#AnimationEvent-interface\n * @see https://developer.mozilla.org/en-US/docs/Web/API/AnimationEvent\n */\n\nvar SyntheticAnimationEvent = SyntheticEvent.extend({\n animationName: null,\n elapsedTime: null,\n pseudoElement: null\n});\n\n/**\n * @interface Event\n * @see http://www.w3.org/TR/clipboard-apis/\n */\n\nvar SyntheticClipboardEvent = SyntheticEvent.extend({\n clipboardData: function (event) {\n return 'clipboardData' in event ? event.clipboardData : window.clipboardData;\n }\n});\n\n/**\n * @interface FocusEvent\n * @see http://www.w3.org/TR/DOM-Level-3-Events/\n */\n\nvar SyntheticFocusEvent = SyntheticUIEvent.extend({\n relatedTarget: null\n});\n\n/**\n * `charCode` represents the actual \"character code\" and is safe to use with\n * `String.fromCharCode`. As such, only keys that correspond to printable\n * characters produce a valid `charCode`, the only exception to this is Enter.\n * The Tab-key is considered non-printable and does not have a `charCode`,\n * presumably because it does not produce a tab-character in browsers.\n *\n * @param {object} nativeEvent Native browser event.\n * @return {number} Normalized `charCode` property.\n */\nfunction getEventCharCode(nativeEvent) {\n var charCode;\n var keyCode = nativeEvent.keyCode;\n\n if ('charCode' in nativeEvent) {\n charCode = nativeEvent.charCode; // FF does not set `charCode` for the Enter-key, check against `keyCode`.\n\n if (charCode === 0 && keyCode === 13) {\n charCode = 13;\n }\n } else {\n // IE8 does not implement `charCode`, but `keyCode` has the correct value.\n charCode = keyCode;\n } // IE and Edge (on Windows) and Chrome / Safari (on Windows and Linux)\n // report Enter as charCode 10 when ctrl is pressed.\n\n\n if (charCode === 10) {\n charCode = 13;\n } // Some non-printable keys are reported in `charCode`/`keyCode`, discard them.\n // Must not discard the (non-)printable Enter-key.\n\n\n if (charCode >= 32 || charCode === 13) {\n return charCode;\n }\n\n return 0;\n}\n\n/**\n * Normalization of deprecated HTML5 `key` values\n * @see https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent#Key_names\n */\n\nvar normalizeKey = {\n Esc: 'Escape',\n Spacebar: ' ',\n Left: 'ArrowLeft',\n Up: 'ArrowUp',\n Right: 'ArrowRight',\n Down: 'ArrowDown',\n Del: 'Delete',\n Win: 'OS',\n Menu: 'ContextMenu',\n Apps: 'ContextMenu',\n Scroll: 'ScrollLock',\n MozPrintableKey: 'Unidentified'\n};\n/**\n * Translation from legacy `keyCode` to HTML5 `key`\n * Only special keys supported, all others depend on keyboard layout or browser\n * @see https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent#Key_names\n */\n\nvar translateToKey = {\n '8': 'Backspace',\n '9': 'Tab',\n '12': 'Clear',\n '13': 'Enter',\n '16': 'Shift',\n '17': 'Control',\n '18': 'Alt',\n '19': 'Pause',\n '20': 'CapsLock',\n '27': 'Escape',\n '32': ' ',\n '33': 'PageUp',\n '34': 'PageDown',\n '35': 'End',\n '36': 'Home',\n '37': 'ArrowLeft',\n '38': 'ArrowUp',\n '39': 'ArrowRight',\n '40': 'ArrowDown',\n '45': 'Insert',\n '46': 'Delete',\n '112': 'F1',\n '113': 'F2',\n '114': 'F3',\n '115': 'F4',\n '116': 'F5',\n '117': 'F6',\n '118': 'F7',\n '119': 'F8',\n '120': 'F9',\n '121': 'F10',\n '122': 'F11',\n '123': 'F12',\n '144': 'NumLock',\n '145': 'ScrollLock',\n '224': 'Meta'\n};\n/**\n * @param {object} nativeEvent Native browser event.\n * @return {string} Normalized `key` property.\n */\n\nfunction getEventKey(nativeEvent) {\n if (nativeEvent.key) {\n // Normalize inconsistent values reported by browsers due to\n // implementations of a working draft specification.\n // FireFox implements `key` but returns `MozPrintableKey` for all\n // printable characters (normalized to `Unidentified`), ignore it.\n var key = normalizeKey[nativeEvent.key] || nativeEvent.key;\n\n if (key !== 'Unidentified') {\n return key;\n }\n } // Browser does not implement `key`, polyfill as much of it as we can.\n\n\n if (nativeEvent.type === 'keypress') {\n var charCode = getEventCharCode(nativeEvent); // The enter-key is technically both printable and non-printable and can\n // thus be captured by `keypress`, no other non-printable key should.\n\n return charCode === 13 ? 'Enter' : String.fromCharCode(charCode);\n }\n\n if (nativeEvent.type === 'keydown' || nativeEvent.type === 'keyup') {\n // While user keyboard layout determines the actual meaning of each\n // `keyCode` value, almost all function keys have a universal value.\n return translateToKey[nativeEvent.keyCode] || 'Unidentified';\n }\n\n return '';\n}\n\n/**\n * @interface KeyboardEvent\n * @see http://www.w3.org/TR/DOM-Level-3-Events/\n */\n\nvar SyntheticKeyboardEvent = SyntheticUIEvent.extend({\n key: getEventKey,\n location: null,\n ctrlKey: null,\n shiftKey: null,\n altKey: null,\n metaKey: null,\n repeat: null,\n locale: null,\n getModifierState: getEventModifierState,\n // Legacy Interface\n charCode: function (event) {\n // `charCode` is the result of a KeyPress event and represents the value of\n // the actual printable character.\n // KeyPress is deprecated, but its replacement is not yet final and not\n // implemented in any major browser. Only KeyPress has charCode.\n if (event.type === 'keypress') {\n return getEventCharCode(event);\n }\n\n return 0;\n },\n keyCode: function (event) {\n // `keyCode` is the result of a KeyDown/Up event and represents the value of\n // physical keyboard key.\n // The actual meaning of the value depends on the users' keyboard layout\n // which cannot be detected. Assuming that it is a US keyboard layout\n // provides a surprisingly accurate mapping for US and European users.\n // Due to this, it is left to the user to implement at this time.\n if (event.type === 'keydown' || event.type === 'keyup') {\n return event.keyCode;\n }\n\n return 0;\n },\n which: function (event) {\n // `which` is an alias for either `keyCode` or `charCode` depending on the\n // type of the event.\n if (event.type === 'keypress') {\n return getEventCharCode(event);\n }\n\n if (event.type === 'keydown' || event.type === 'keyup') {\n return event.keyCode;\n }\n\n return 0;\n }\n});\n\n/**\n * @interface DragEvent\n * @see http://www.w3.org/TR/DOM-Level-3-Events/\n */\n\nvar SyntheticDragEvent = SyntheticMouseEvent.extend({\n dataTransfer: null\n});\n\n/**\n * @interface TouchEvent\n * @see http://www.w3.org/TR/touch-events/\n */\n\nvar SyntheticTouchEvent = SyntheticUIEvent.extend({\n touches: null,\n targetTouches: null,\n changedTouches: null,\n altKey: null,\n metaKey: null,\n ctrlKey: null,\n shiftKey: null,\n getModifierState: getEventModifierState\n});\n\n/**\n * @interface Event\n * @see http://www.w3.org/TR/2009/WD-css3-transitions-20090320/#transition-events-\n * @see https://developer.mozilla.org/en-US/docs/Web/API/TransitionEvent\n */\n\nvar SyntheticTransitionEvent = SyntheticEvent.extend({\n propertyName: null,\n elapsedTime: null,\n pseudoElement: null\n});\n\n/**\n * @interface WheelEvent\n * @see http://www.w3.org/TR/DOM-Level-3-Events/\n */\n\nvar SyntheticWheelEvent = SyntheticMouseEvent.extend({\n deltaX: function (event) {\n return 'deltaX' in event ? event.deltaX : // Fallback to `wheelDeltaX` for Webkit and normalize (right is positive).\n 'wheelDeltaX' in event ? -event.wheelDeltaX : 0;\n },\n deltaY: function (event) {\n return 'deltaY' in event ? event.deltaY : // Fallback to `wheelDeltaY` for Webkit and normalize (down is positive).\n 'wheelDeltaY' in event ? -event.wheelDeltaY : // Fallback to `wheelDelta` for IE<9 and normalize (down is positive).\n 'wheelDelta' in event ? -event.wheelDelta : 0;\n },\n deltaZ: null,\n // Browsers without \"deltaMode\" is reporting in raw wheel delta where one\n // notch on the scroll is always +/- 120, roughly equivalent to pixels.\n // A good approximation of DOM_DELTA_LINE (1) is 5% of viewport size or\n // ~40 pixels, for DOM_DELTA_SCREEN (2) it is 87.5% of viewport size.\n deltaMode: null\n});\n\nvar knownHTMLTopLevelTypes = [TOP_ABORT, TOP_CANCEL, TOP_CAN_PLAY, TOP_CAN_PLAY_THROUGH, TOP_CLOSE, TOP_DURATION_CHANGE, TOP_EMPTIED, TOP_ENCRYPTED, TOP_ENDED, TOP_ERROR, TOP_INPUT, TOP_INVALID, TOP_LOAD, TOP_LOADED_DATA, TOP_LOADED_METADATA, TOP_LOAD_START, TOP_PAUSE, TOP_PLAY, TOP_PLAYING, TOP_PROGRESS, TOP_RATE_CHANGE, TOP_RESET, TOP_SEEKED, TOP_SEEKING, TOP_STALLED, TOP_SUBMIT, TOP_SUSPEND, TOP_TIME_UPDATE, TOP_TOGGLE, TOP_VOLUME_CHANGE, TOP_WAITING];\nvar SimpleEventPlugin = {\n // simpleEventPluginEventTypes gets populated from\n // the DOMEventProperties module.\n eventTypes: simpleEventPluginEventTypes,\n extractEvents: function (topLevelType, targetInst, nativeEvent, nativeEventTarget, eventSystemFlags) {\n var dispatchConfig = topLevelEventsToDispatchConfig.get(topLevelType);\n\n if (!dispatchConfig) {\n return null;\n }\n\n var EventConstructor;\n\n switch (topLevelType) {\n case TOP_KEY_PRESS:\n // Firefox creates a keypress event for function keys too. This removes\n // the unwanted keypress events. Enter is however both printable and\n // non-printable. One would expect Tab to be as well (but it isn't).\n if (getEventCharCode(nativeEvent) === 0) {\n return null;\n }\n\n /* falls through */\n\n case TOP_KEY_DOWN:\n case TOP_KEY_UP:\n EventConstructor = SyntheticKeyboardEvent;\n break;\n\n case TOP_BLUR:\n case TOP_FOCUS:\n EventConstructor = SyntheticFocusEvent;\n break;\n\n case TOP_CLICK:\n // Firefox creates a click event on right mouse clicks. This removes the\n // unwanted click events.\n if (nativeEvent.button === 2) {\n return null;\n }\n\n /* falls through */\n\n case TOP_AUX_CLICK:\n case TOP_DOUBLE_CLICK:\n case TOP_MOUSE_DOWN:\n case TOP_MOUSE_MOVE:\n case TOP_MOUSE_UP: // TODO: Disabled elements should not respond to mouse events\n\n /* falls through */\n\n case TOP_MOUSE_OUT:\n case TOP_MOUSE_OVER:\n case TOP_CONTEXT_MENU:\n EventConstructor = SyntheticMouseEvent;\n break;\n\n case TOP_DRAG:\n case TOP_DRAG_END:\n case TOP_DRAG_ENTER:\n case TOP_DRAG_EXIT:\n case TOP_DRAG_LEAVE:\n case TOP_DRAG_OVER:\n case TOP_DRAG_START:\n case TOP_DROP:\n EventConstructor = SyntheticDragEvent;\n break;\n\n case TOP_TOUCH_CANCEL:\n case TOP_TOUCH_END:\n case TOP_TOUCH_MOVE:\n case TOP_TOUCH_START:\n EventConstructor = SyntheticTouchEvent;\n break;\n\n case TOP_ANIMATION_END:\n case TOP_ANIMATION_ITERATION:\n case TOP_ANIMATION_START:\n EventConstructor = SyntheticAnimationEvent;\n break;\n\n case TOP_TRANSITION_END:\n EventConstructor = SyntheticTransitionEvent;\n break;\n\n case TOP_SCROLL:\n EventConstructor = SyntheticUIEvent;\n break;\n\n case TOP_WHEEL:\n EventConstructor = SyntheticWheelEvent;\n break;\n\n case TOP_COPY:\n case TOP_CUT:\n case TOP_PASTE:\n EventConstructor = SyntheticClipboardEvent;\n break;\n\n case TOP_GOT_POINTER_CAPTURE:\n case TOP_LOST_POINTER_CAPTURE:\n case TOP_POINTER_CANCEL:\n case TOP_POINTER_DOWN:\n case TOP_POINTER_MOVE:\n case TOP_POINTER_OUT:\n case TOP_POINTER_OVER:\n case TOP_POINTER_UP:\n EventConstructor = SyntheticPointerEvent;\n break;\n\n default:\n {\n if (knownHTMLTopLevelTypes.indexOf(topLevelType) === -1) {\n error('SimpleEventPlugin: Unhandled event type, `%s`. This warning ' + 'is likely caused by a bug in React. Please file an issue.', topLevelType);\n }\n } // HTML Events\n // @see http://www.w3.org/TR/html5/index.html#events-0\n\n\n EventConstructor = SyntheticEvent;\n break;\n }\n\n var event = EventConstructor.getPooled(dispatchConfig, targetInst, nativeEvent, nativeEventTarget);\n accumulateTwoPhaseDispatches(event);\n return event;\n }\n};\n\n/**\n * Specifies a deterministic ordering of `EventPlugin`s. A convenient way to\n * reason about plugins, without having to package every one of them. This\n * is better than having plugins be ordered in the same order that they\n * are injected because that ordering would be influenced by the packaging order.\n * `ResponderEventPlugin` must occur before `SimpleEventPlugin` so that\n * preventing default on events is convenient in `SimpleEventPlugin` handlers.\n */\n\nvar DOMEventPluginOrder = ['ResponderEventPlugin', 'SimpleEventPlugin', 'EnterLeaveEventPlugin', 'ChangeEventPlugin', 'SelectEventPlugin', 'BeforeInputEventPlugin'];\n/**\n * Inject modules for resolving DOM hierarchy and plugin ordering.\n */\n\ninjectEventPluginOrder(DOMEventPluginOrder);\nsetComponentTree(getFiberCurrentPropsFromNode$1, getInstanceFromNode$1, getNodeFromInstance$1);\n/**\n * Some important event plugins included by default (without having to require\n * them).\n */\n\ninjectEventPluginsByName({\n SimpleEventPlugin: SimpleEventPlugin,\n EnterLeaveEventPlugin: EnterLeaveEventPlugin,\n ChangeEventPlugin: ChangeEventPlugin,\n SelectEventPlugin: SelectEventPlugin,\n BeforeInputEventPlugin: BeforeInputEventPlugin\n});\n\n// Prefix measurements so that it's possible to filter them.\n// Longer prefixes are hard to read in DevTools.\nvar reactEmoji = \"\\u269B\";\nvar warningEmoji = \"\\u26D4\";\nvar supportsUserTiming = typeof performance !== 'undefined' && typeof performance.mark === 'function' && typeof performance.clearMarks === 'function' && typeof performance.measure === 'function' && typeof performance.clearMeasures === 'function'; // Keep track of current fiber so that we know the path to unwind on pause.\n// TODO: this looks the same as nextUnitOfWork in scheduler. Can we unify them?\n\nvar currentFiber = null; // If we're in the middle of user code, which fiber and method is it?\n// Reusing `currentFiber` would be confusing for this because user code fiber\n// can change during commit phase too, but we don't need to unwind it (since\n// lifecycles in the commit phase don't resemble a tree).\n\nvar currentPhase = null;\nvar currentPhaseFiber = null; // Did lifecycle hook schedule an update? This is often a performance problem,\n// so we will keep track of it, and include it in the report.\n// Track commits caused by cascading updates.\n\nvar isCommitting = false;\nvar hasScheduledUpdateInCurrentCommit = false;\nvar hasScheduledUpdateInCurrentPhase = false;\nvar commitCountInCurrentWorkLoop = 0;\nvar effectCountInCurrentCommit = 0;\n// to avoid stretch the commit phase with measurement overhead.\n\nvar labelsInCurrentCommit = new Set();\n\nvar formatMarkName = function (markName) {\n return reactEmoji + \" \" + markName;\n};\n\nvar formatLabel = function (label, warning) {\n var prefix = warning ? warningEmoji + \" \" : reactEmoji + \" \";\n var suffix = warning ? \" Warning: \" + warning : '';\n return \"\" + prefix + label + suffix;\n};\n\nvar beginMark = function (markName) {\n performance.mark(formatMarkName(markName));\n};\n\nvar clearMark = function (markName) {\n performance.clearMarks(formatMarkName(markName));\n};\n\nvar endMark = function (label, markName, warning) {\n var formattedMarkName = formatMarkName(markName);\n var formattedLabel = formatLabel(label, warning);\n\n try {\n performance.measure(formattedLabel, formattedMarkName);\n } catch (err) {} // If previous mark was missing for some reason, this will throw.\n // This could only happen if React crashed in an unexpected place earlier.\n // Don't pile on with more errors.\n // Clear marks immediately to avoid growing buffer.\n\n\n performance.clearMarks(formattedMarkName);\n performance.clearMeasures(formattedLabel);\n};\n\nvar getFiberMarkName = function (label, debugID) {\n return label + \" (#\" + debugID + \")\";\n};\n\nvar getFiberLabel = function (componentName, isMounted, phase) {\n if (phase === null) {\n // These are composite component total time measurements.\n return componentName + \" [\" + (isMounted ? 'update' : 'mount') + \"]\";\n } else {\n // Composite component methods.\n return componentName + \".\" + phase;\n }\n};\n\nvar beginFiberMark = function (fiber, phase) {\n var componentName = getComponentName(fiber.type) || 'Unknown';\n var debugID = fiber._debugID;\n var isMounted = fiber.alternate !== null;\n var label = getFiberLabel(componentName, isMounted, phase);\n\n if (isCommitting && labelsInCurrentCommit.has(label)) {\n // During the commit phase, we don't show duplicate labels because\n // there is a fixed overhead for every measurement, and we don't\n // want to stretch the commit phase beyond necessary.\n return false;\n }\n\n labelsInCurrentCommit.add(label);\n var markName = getFiberMarkName(label, debugID);\n beginMark(markName);\n return true;\n};\n\nvar clearFiberMark = function (fiber, phase) {\n var componentName = getComponentName(fiber.type) || 'Unknown';\n var debugID = fiber._debugID;\n var isMounted = fiber.alternate !== null;\n var label = getFiberLabel(componentName, isMounted, phase);\n var markName = getFiberMarkName(label, debugID);\n clearMark(markName);\n};\n\nvar endFiberMark = function (fiber, phase, warning) {\n var componentName = getComponentName(fiber.type) || 'Unknown';\n var debugID = fiber._debugID;\n var isMounted = fiber.alternate !== null;\n var label = getFiberLabel(componentName, isMounted, phase);\n var markName = getFiberMarkName(label, debugID);\n endMark(label, markName, warning);\n};\n\nvar shouldIgnoreFiber = function (fiber) {\n // Host components should be skipped in the timeline.\n // We could check typeof fiber.type, but does this work with RN?\n switch (fiber.tag) {\n case HostRoot:\n case HostComponent:\n case HostText:\n case HostPortal:\n case Fragment:\n case ContextProvider:\n case ContextConsumer:\n case Mode:\n return true;\n\n default:\n return false;\n }\n};\n\nvar clearPendingPhaseMeasurement = function () {\n if (currentPhase !== null && currentPhaseFiber !== null) {\n clearFiberMark(currentPhaseFiber, currentPhase);\n }\n\n currentPhaseFiber = null;\n currentPhase = null;\n hasScheduledUpdateInCurrentPhase = false;\n};\n\nvar pauseTimers = function () {\n // Stops all currently active measurements so that they can be resumed\n // if we continue in a later deferred loop from the same unit of work.\n var fiber = currentFiber;\n\n while (fiber) {\n if (fiber._debugIsCurrentlyTiming) {\n endFiberMark(fiber, null, null);\n }\n\n fiber = fiber.return;\n }\n};\n\nvar resumeTimersRecursively = function (fiber) {\n if (fiber.return !== null) {\n resumeTimersRecursively(fiber.return);\n }\n\n if (fiber._debugIsCurrentlyTiming) {\n beginFiberMark(fiber, null);\n }\n};\n\nvar resumeTimers = function () {\n // Resumes all measurements that were active during the last deferred loop.\n if (currentFiber !== null) {\n resumeTimersRecursively(currentFiber);\n }\n};\n\nfunction recordEffect() {\n {\n effectCountInCurrentCommit++;\n }\n}\nfunction recordScheduleUpdate() {\n {\n if (isCommitting) {\n hasScheduledUpdateInCurrentCommit = true;\n }\n\n if (currentPhase !== null && currentPhase !== 'componentWillMount' && currentPhase !== 'componentWillReceiveProps') {\n hasScheduledUpdateInCurrentPhase = true;\n }\n }\n}\nfunction startWorkTimer(fiber) {\n {\n if (!supportsUserTiming || shouldIgnoreFiber(fiber)) {\n return;\n } // If we pause, this is the fiber to unwind from.\n\n\n currentFiber = fiber;\n\n if (!beginFiberMark(fiber, null)) {\n return;\n }\n\n fiber._debugIsCurrentlyTiming = true;\n }\n}\nfunction cancelWorkTimer(fiber) {\n {\n if (!supportsUserTiming || shouldIgnoreFiber(fiber)) {\n return;\n } // Remember we shouldn't complete measurement for this fiber.\n // Otherwise flamechart will be deep even for small updates.\n\n\n fiber._debugIsCurrentlyTiming = false;\n clearFiberMark(fiber, null);\n }\n}\nfunction stopWorkTimer(fiber) {\n {\n if (!supportsUserTiming || shouldIgnoreFiber(fiber)) {\n return;\n } // If we pause, its parent is the fiber to unwind from.\n\n\n currentFiber = fiber.return;\n\n if (!fiber._debugIsCurrentlyTiming) {\n return;\n }\n\n fiber._debugIsCurrentlyTiming = false;\n endFiberMark(fiber, null, null);\n }\n}\nfunction stopFailedWorkTimer(fiber) {\n {\n if (!supportsUserTiming || shouldIgnoreFiber(fiber)) {\n return;\n } // If we pause, its parent is the fiber to unwind from.\n\n\n currentFiber = fiber.return;\n\n if (!fiber._debugIsCurrentlyTiming) {\n return;\n }\n\n fiber._debugIsCurrentlyTiming = false;\n var warning = fiber.tag === SuspenseComponent ? 'Rendering was suspended' : 'An error was thrown inside this error boundary';\n endFiberMark(fiber, null, warning);\n }\n}\nfunction startPhaseTimer(fiber, phase) {\n {\n if (!supportsUserTiming) {\n return;\n }\n\n clearPendingPhaseMeasurement();\n\n if (!beginFiberMark(fiber, phase)) {\n return;\n }\n\n currentPhaseFiber = fiber;\n currentPhase = phase;\n }\n}\nfunction stopPhaseTimer() {\n {\n if (!supportsUserTiming) {\n return;\n }\n\n if (currentPhase !== null && currentPhaseFiber !== null) {\n var warning = hasScheduledUpdateInCurrentPhase ? 'Scheduled a cascading update' : null;\n endFiberMark(currentPhaseFiber, currentPhase, warning);\n }\n\n currentPhase = null;\n currentPhaseFiber = null;\n }\n}\nfunction startWorkLoopTimer(nextUnitOfWork) {\n {\n currentFiber = nextUnitOfWork;\n\n if (!supportsUserTiming) {\n return;\n }\n\n commitCountInCurrentWorkLoop = 0; // This is top level call.\n // Any other measurements are performed within.\n\n beginMark('(React Tree Reconciliation)'); // Resume any measurements that were in progress during the last loop.\n\n resumeTimers();\n }\n}\nfunction stopWorkLoopTimer(interruptedBy, didCompleteRoot) {\n {\n if (!supportsUserTiming) {\n return;\n }\n\n var warning = null;\n\n if (interruptedBy !== null) {\n if (interruptedBy.tag === HostRoot) {\n warning = 'A top-level update interrupted the previous render';\n } else {\n var componentName = getComponentName(interruptedBy.type) || 'Unknown';\n warning = \"An update to \" + componentName + \" interrupted the previous render\";\n }\n } else if (commitCountInCurrentWorkLoop > 1) {\n warning = 'There were cascading updates';\n }\n\n commitCountInCurrentWorkLoop = 0;\n var label = didCompleteRoot ? '(React Tree Reconciliation: Completed Root)' : '(React Tree Reconciliation: Yielded)'; // Pause any measurements until the next loop.\n\n pauseTimers();\n endMark(label, '(React Tree Reconciliation)', warning);\n }\n}\nfunction startCommitTimer() {\n {\n if (!supportsUserTiming) {\n return;\n }\n\n isCommitting = true;\n hasScheduledUpdateInCurrentCommit = false;\n labelsInCurrentCommit.clear();\n beginMark('(Committing Changes)');\n }\n}\nfunction stopCommitTimer() {\n {\n if (!supportsUserTiming) {\n return;\n }\n\n var warning = null;\n\n if (hasScheduledUpdateInCurrentCommit) {\n warning = 'Lifecycle hook scheduled a cascading update';\n } else if (commitCountInCurrentWorkLoop > 0) {\n warning = 'Caused by a cascading update in earlier commit';\n }\n\n hasScheduledUpdateInCurrentCommit = false;\n commitCountInCurrentWorkLoop++;\n isCommitting = false;\n labelsInCurrentCommit.clear();\n endMark('(Committing Changes)', '(Committing Changes)', warning);\n }\n}\nfunction startCommitSnapshotEffectsTimer() {\n {\n if (!supportsUserTiming) {\n return;\n }\n\n effectCountInCurrentCommit = 0;\n beginMark('(Committing Snapshot Effects)');\n }\n}\nfunction stopCommitSnapshotEffectsTimer() {\n {\n if (!supportsUserTiming) {\n return;\n }\n\n var count = effectCountInCurrentCommit;\n effectCountInCurrentCommit = 0;\n endMark(\"(Committing Snapshot Effects: \" + count + \" Total)\", '(Committing Snapshot Effects)', null);\n }\n}\nfunction startCommitHostEffectsTimer() {\n {\n if (!supportsUserTiming) {\n return;\n }\n\n effectCountInCurrentCommit = 0;\n beginMark('(Committing Host Effects)');\n }\n}\nfunction stopCommitHostEffectsTimer() {\n {\n if (!supportsUserTiming) {\n return;\n }\n\n var count = effectCountInCurrentCommit;\n effectCountInCurrentCommit = 0;\n endMark(\"(Committing Host Effects: \" + count + \" Total)\", '(Committing Host Effects)', null);\n }\n}\nfunction startCommitLifeCyclesTimer() {\n {\n if (!supportsUserTiming) {\n return;\n }\n\n effectCountInCurrentCommit = 0;\n beginMark('(Calling Lifecycle Methods)');\n }\n}\nfunction stopCommitLifeCyclesTimer() {\n {\n if (!supportsUserTiming) {\n return;\n }\n\n var count = effectCountInCurrentCommit;\n effectCountInCurrentCommit = 0;\n endMark(\"(Calling Lifecycle Methods: \" + count + \" Total)\", '(Calling Lifecycle Methods)', null);\n }\n}\n\nvar valueStack = [];\nvar fiberStack;\n\n{\n fiberStack = [];\n}\n\nvar index = -1;\n\nfunction createCursor(defaultValue) {\n return {\n current: defaultValue\n };\n}\n\nfunction pop(cursor, fiber) {\n if (index < 0) {\n {\n error('Unexpected pop.');\n }\n\n return;\n }\n\n {\n if (fiber !== fiberStack[index]) {\n error('Unexpected Fiber popped.');\n }\n }\n\n cursor.current = valueStack[index];\n valueStack[index] = null;\n\n {\n fiberStack[index] = null;\n }\n\n index--;\n}\n\nfunction push(cursor, value, fiber) {\n index++;\n valueStack[index] = cursor.current;\n\n {\n fiberStack[index] = fiber;\n }\n\n cursor.current = value;\n}\n\nvar warnedAboutMissingGetChildContext;\n\n{\n warnedAboutMissingGetChildContext = {};\n}\n\nvar emptyContextObject = {};\n\n{\n Object.freeze(emptyContextObject);\n} // A cursor to the current merged context object on the stack.\n\n\nvar contextStackCursor = createCursor(emptyContextObject); // A cursor to a boolean indicating whether the context has changed.\n\nvar didPerformWorkStackCursor = createCursor(false); // Keep track of the previous context object that was on the stack.\n// We use this to get access to the parent context after we have already\n// pushed the next context provider, and now need to merge their contexts.\n\nvar previousContext = emptyContextObject;\n\nfunction getUnmaskedContext(workInProgress, Component, didPushOwnContextIfProvider) {\n {\n if (didPushOwnContextIfProvider && isContextProvider(Component)) {\n // If the fiber is a context provider itself, when we read its context\n // we may have already pushed its own child context on the stack. A context\n // provider should not \"see\" its own child context. Therefore we read the\n // previous (parent) context instead for a context provider.\n return previousContext;\n }\n\n return contextStackCursor.current;\n }\n}\n\nfunction cacheContext(workInProgress, unmaskedContext, maskedContext) {\n {\n var instance = workInProgress.stateNode;\n instance.__reactInternalMemoizedUnmaskedChildContext = unmaskedContext;\n instance.__reactInternalMemoizedMaskedChildContext = maskedContext;\n }\n}\n\nfunction getMaskedContext(workInProgress, unmaskedContext) {\n {\n var type = workInProgress.type;\n var contextTypes = type.contextTypes;\n\n if (!contextTypes) {\n return emptyContextObject;\n } // Avoid recreating masked context unless unmasked context has changed.\n // Failing to do this will result in unnecessary calls to componentWillReceiveProps.\n // This may trigger infinite loops if componentWillReceiveProps calls setState.\n\n\n var instance = workInProgress.stateNode;\n\n if (instance && instance.__reactInternalMemoizedUnmaskedChildContext === unmaskedContext) {\n return instance.__reactInternalMemoizedMaskedChildContext;\n }\n\n var context = {};\n\n for (var key in contextTypes) {\n context[key] = unmaskedContext[key];\n }\n\n {\n var name = getComponentName(type) || 'Unknown';\n checkPropTypes(contextTypes, context, 'context', name, getCurrentFiberStackInDev);\n } // Cache unmasked context so we can avoid recreating masked context unless necessary.\n // Context is created before the class component is instantiated so check for instance.\n\n\n if (instance) {\n cacheContext(workInProgress, unmaskedContext, context);\n }\n\n return context;\n }\n}\n\nfunction hasContextChanged() {\n {\n return didPerformWorkStackCursor.current;\n }\n}\n\nfunction isContextProvider(type) {\n {\n var childContextTypes = type.childContextTypes;\n return childContextTypes !== null && childContextTypes !== undefined;\n }\n}\n\nfunction popContext(fiber) {\n {\n pop(didPerformWorkStackCursor, fiber);\n pop(contextStackCursor, fiber);\n }\n}\n\nfunction popTopLevelContextObject(fiber) {\n {\n pop(didPerformWorkStackCursor, fiber);\n pop(contextStackCursor, fiber);\n }\n}\n\nfunction pushTopLevelContextObject(fiber, context, didChange) {\n {\n if (!(contextStackCursor.current === emptyContextObject)) {\n {\n throw Error( \"Unexpected context found on stack. This error is likely caused by a bug in React. Please file an issue.\" );\n }\n }\n\n push(contextStackCursor, context, fiber);\n push(didPerformWorkStackCursor, didChange, fiber);\n }\n}\n\nfunction processChildContext(fiber, type, parentContext) {\n {\n var instance = fiber.stateNode;\n var childContextTypes = type.childContextTypes; // TODO (bvaughn) Replace this behavior with an invariant() in the future.\n // It has only been added in Fiber to match the (unintentional) behavior in Stack.\n\n if (typeof instance.getChildContext !== 'function') {\n {\n var componentName = getComponentName(type) || 'Unknown';\n\n if (!warnedAboutMissingGetChildContext[componentName]) {\n warnedAboutMissingGetChildContext[componentName] = true;\n\n error('%s.childContextTypes is specified but there is no getChildContext() method ' + 'on the instance. You can either define getChildContext() on %s or remove ' + 'childContextTypes from it.', componentName, componentName);\n }\n }\n\n return parentContext;\n }\n\n var childContext;\n startPhaseTimer(fiber, 'getChildContext');\n childContext = instance.getChildContext();\n stopPhaseTimer();\n\n for (var contextKey in childContext) {\n if (!(contextKey in childContextTypes)) {\n {\n throw Error( (getComponentName(type) || 'Unknown') + \".getChildContext(): key \\\"\" + contextKey + \"\\\" is not defined in childContextTypes.\" );\n }\n }\n }\n\n {\n var name = getComponentName(type) || 'Unknown';\n checkPropTypes(childContextTypes, childContext, 'child context', name, // In practice, there is one case in which we won't get a stack. It's when\n // somebody calls unstable_renderSubtreeIntoContainer() and we process\n // context from the parent component instance. The stack will be missing\n // because it's outside of the reconciliation, and so the pointer has not\n // been set. This is rare and doesn't matter. We'll also remove that API.\n getCurrentFiberStackInDev);\n }\n\n return _assign({}, parentContext, {}, childContext);\n }\n}\n\nfunction pushContextProvider(workInProgress) {\n {\n var instance = workInProgress.stateNode; // We push the context as early as possible to ensure stack integrity.\n // If the instance does not exist yet, we will push null at first,\n // and replace it on the stack later when invalidating the context.\n\n var memoizedMergedChildContext = instance && instance.__reactInternalMemoizedMergedChildContext || emptyContextObject; // Remember the parent context so we can merge with it later.\n // Inherit the parent's did-perform-work value to avoid inadvertently blocking updates.\n\n previousContext = contextStackCursor.current;\n push(contextStackCursor, memoizedMergedChildContext, workInProgress);\n push(didPerformWorkStackCursor, didPerformWorkStackCursor.current, workInProgress);\n return true;\n }\n}\n\nfunction invalidateContextProvider(workInProgress, type, didChange) {\n {\n var instance = workInProgress.stateNode;\n\n if (!instance) {\n {\n throw Error( \"Expected to have an instance by this point. This error is likely caused by a bug in React. Please file an issue.\" );\n }\n }\n\n if (didChange) {\n // Merge parent and own context.\n // Skip this if we're not updating due to sCU.\n // This avoids unnecessarily recomputing memoized values.\n var mergedContext = processChildContext(workInProgress, type, previousContext);\n instance.__reactInternalMemoizedMergedChildContext = mergedContext; // Replace the old (or empty) context with the new one.\n // It is important to unwind the context in the reverse order.\n\n pop(didPerformWorkStackCursor, workInProgress);\n pop(contextStackCursor, workInProgress); // Now push the new context and mark that it has changed.\n\n push(contextStackCursor, mergedContext, workInProgress);\n push(didPerformWorkStackCursor, didChange, workInProgress);\n } else {\n pop(didPerformWorkStackCursor, workInProgress);\n push(didPerformWorkStackCursor, didChange, workInProgress);\n }\n }\n}\n\nfunction findCurrentUnmaskedContext(fiber) {\n {\n // Currently this is only used with renderSubtreeIntoContainer; not sure if it\n // makes sense elsewhere\n if (!(isFiberMounted(fiber) && fiber.tag === ClassComponent)) {\n {\n throw Error( \"Expected subtree parent to be a mounted class component. This error is likely caused by a bug in React. Please file an issue.\" );\n }\n }\n\n var node = fiber;\n\n do {\n switch (node.tag) {\n case HostRoot:\n return node.stateNode.context;\n\n case ClassComponent:\n {\n var Component = node.type;\n\n if (isContextProvider(Component)) {\n return node.stateNode.__reactInternalMemoizedMergedChildContext;\n }\n\n break;\n }\n }\n\n node = node.return;\n } while (node !== null);\n\n {\n {\n throw Error( \"Found unexpected detached subtree parent. This error is likely caused by a bug in React. Please file an issue.\" );\n }\n }\n }\n}\n\nvar LegacyRoot = 0;\nvar BlockingRoot = 1;\nvar ConcurrentRoot = 2;\n\nvar Scheduler_runWithPriority = Scheduler.unstable_runWithPriority,\n Scheduler_scheduleCallback = Scheduler.unstable_scheduleCallback,\n Scheduler_cancelCallback = Scheduler.unstable_cancelCallback,\n Scheduler_shouldYield = Scheduler.unstable_shouldYield,\n Scheduler_requestPaint = Scheduler.unstable_requestPaint,\n Scheduler_now = Scheduler.unstable_now,\n Scheduler_getCurrentPriorityLevel = Scheduler.unstable_getCurrentPriorityLevel,\n Scheduler_ImmediatePriority = Scheduler.unstable_ImmediatePriority,\n Scheduler_UserBlockingPriority = Scheduler.unstable_UserBlockingPriority,\n Scheduler_NormalPriority = Scheduler.unstable_NormalPriority,\n Scheduler_LowPriority = Scheduler.unstable_LowPriority,\n Scheduler_IdlePriority = Scheduler.unstable_IdlePriority;\n\n{\n // Provide explicit error message when production+profiling bundle of e.g.\n // react-dom is used with production (non-profiling) bundle of\n // scheduler/tracing\n if (!(tracing.__interactionsRef != null && tracing.__interactionsRef.current != null)) {\n {\n throw Error( \"It is not supported to run the profiling version of a renderer (for example, `react-dom/profiling`) without also replacing the `scheduler/tracing` module with `scheduler/tracing-profiling`. Your bundler might have a setting for aliasing both modules. Learn more at http://fb.me/react-profiling\" );\n }\n }\n}\n\nvar fakeCallbackNode = {}; // Except for NoPriority, these correspond to Scheduler priorities. We use\n// ascending numbers so we can compare them like numbers. They start at 90 to\n// avoid clashing with Scheduler's priorities.\n\nvar ImmediatePriority = 99;\nvar UserBlockingPriority$1 = 98;\nvar NormalPriority = 97;\nvar LowPriority = 96;\nvar IdlePriority = 95; // NoPriority is the absence of priority. Also React-only.\n\nvar NoPriority = 90;\nvar shouldYield = Scheduler_shouldYield;\nvar requestPaint = // Fall back gracefully if we're running an older version of Scheduler.\nScheduler_requestPaint !== undefined ? Scheduler_requestPaint : function () {};\nvar syncQueue = null;\nvar immediateQueueCallbackNode = null;\nvar isFlushingSyncQueue = false;\nvar initialTimeMs = Scheduler_now(); // If the initial timestamp is reasonably small, use Scheduler's `now` directly.\n// This will be the case for modern browsers that support `performance.now`. In\n// older browsers, Scheduler falls back to `Date.now`, which returns a Unix\n// timestamp. In that case, subtract the module initialization time to simulate\n// the behavior of performance.now and keep our times small enough to fit\n// within 32 bits.\n// TODO: Consider lifting this into Scheduler.\n\nvar now = initialTimeMs < 10000 ? Scheduler_now : function () {\n return Scheduler_now() - initialTimeMs;\n};\nfunction getCurrentPriorityLevel() {\n switch (Scheduler_getCurrentPriorityLevel()) {\n case Scheduler_ImmediatePriority:\n return ImmediatePriority;\n\n case Scheduler_UserBlockingPriority:\n return UserBlockingPriority$1;\n\n case Scheduler_NormalPriority:\n return NormalPriority;\n\n case Scheduler_LowPriority:\n return LowPriority;\n\n case Scheduler_IdlePriority:\n return IdlePriority;\n\n default:\n {\n {\n throw Error( \"Unknown priority level.\" );\n }\n }\n\n }\n}\n\nfunction reactPriorityToSchedulerPriority(reactPriorityLevel) {\n switch (reactPriorityLevel) {\n case ImmediatePriority:\n return Scheduler_ImmediatePriority;\n\n case UserBlockingPriority$1:\n return Scheduler_UserBlockingPriority;\n\n case NormalPriority:\n return Scheduler_NormalPriority;\n\n case LowPriority:\n return Scheduler_LowPriority;\n\n case IdlePriority:\n return Scheduler_IdlePriority;\n\n default:\n {\n {\n throw Error( \"Unknown priority level.\" );\n }\n }\n\n }\n}\n\nfunction runWithPriority$1(reactPriorityLevel, fn) {\n var priorityLevel = reactPriorityToSchedulerPriority(reactPriorityLevel);\n return Scheduler_runWithPriority(priorityLevel, fn);\n}\nfunction scheduleCallback(reactPriorityLevel, callback, options) {\n var priorityLevel = reactPriorityToSchedulerPriority(reactPriorityLevel);\n return Scheduler_scheduleCallback(priorityLevel, callback, options);\n}\nfunction scheduleSyncCallback(callback) {\n // Push this callback into an internal queue. We'll flush these either in\n // the next tick, or earlier if something calls `flushSyncCallbackQueue`.\n if (syncQueue === null) {\n syncQueue = [callback]; // Flush the queue in the next tick, at the earliest.\n\n immediateQueueCallbackNode = Scheduler_scheduleCallback(Scheduler_ImmediatePriority, flushSyncCallbackQueueImpl);\n } else {\n // Push onto existing queue. Don't need to schedule a callback because\n // we already scheduled one when we created the queue.\n syncQueue.push(callback);\n }\n\n return fakeCallbackNode;\n}\nfunction cancelCallback(callbackNode) {\n if (callbackNode !== fakeCallbackNode) {\n Scheduler_cancelCallback(callbackNode);\n }\n}\nfunction flushSyncCallbackQueue() {\n if (immediateQueueCallbackNode !== null) {\n var node = immediateQueueCallbackNode;\n immediateQueueCallbackNode = null;\n Scheduler_cancelCallback(node);\n }\n\n flushSyncCallbackQueueImpl();\n}\n\nfunction flushSyncCallbackQueueImpl() {\n if (!isFlushingSyncQueue && syncQueue !== null) {\n // Prevent re-entrancy.\n isFlushingSyncQueue = true;\n var i = 0;\n\n try {\n var _isSync = true;\n var queue = syncQueue;\n runWithPriority$1(ImmediatePriority, function () {\n for (; i < queue.length; i++) {\n var callback = queue[i];\n\n do {\n callback = callback(_isSync);\n } while (callback !== null);\n }\n });\n syncQueue = null;\n } catch (error) {\n // If something throws, leave the remaining callbacks on the queue.\n if (syncQueue !== null) {\n syncQueue = syncQueue.slice(i + 1);\n } // Resume flushing in the next tick\n\n\n Scheduler_scheduleCallback(Scheduler_ImmediatePriority, flushSyncCallbackQueue);\n throw error;\n } finally {\n isFlushingSyncQueue = false;\n }\n }\n}\n\nvar NoMode = 0;\nvar StrictMode = 1; // TODO: Remove BlockingMode and ConcurrentMode by reading from the root\n// tag instead\n\nvar BlockingMode = 2;\nvar ConcurrentMode = 4;\nvar ProfileMode = 8;\n\n// Max 31 bit integer. The max integer size in V8 for 32-bit systems.\n// Math.pow(2, 30) - 1\n// 0b111111111111111111111111111111\nvar MAX_SIGNED_31_BIT_INT = 1073741823;\n\nvar NoWork = 0; // TODO: Think of a better name for Never. The key difference with Idle is that\n// Never work can be committed in an inconsistent state without tearing the UI.\n// The main example is offscreen content, like a hidden subtree. So one possible\n// name is Offscreen. However, it also includes dehydrated Suspense boundaries,\n// which are inconsistent in the sense that they haven't finished yet, but\n// aren't visibly inconsistent because the server rendered HTML matches what the\n// hydrated tree would look like.\n\nvar Never = 1; // Idle is slightly higher priority than Never. It must completely finish in\n// order to be consistent.\n\nvar Idle = 2; // Continuous Hydration is slightly higher than Idle and is used to increase\n// priority of hover targets.\n\nvar ContinuousHydration = 3;\nvar Sync = MAX_SIGNED_31_BIT_INT;\nvar Batched = Sync - 1;\nvar UNIT_SIZE = 10;\nvar MAGIC_NUMBER_OFFSET = Batched - 1; // 1 unit of expiration time represents 10ms.\n\nfunction msToExpirationTime(ms) {\n // Always subtract from the offset so that we don't clash with the magic number for NoWork.\n return MAGIC_NUMBER_OFFSET - (ms / UNIT_SIZE | 0);\n}\nfunction expirationTimeToMs(expirationTime) {\n return (MAGIC_NUMBER_OFFSET - expirationTime) * UNIT_SIZE;\n}\n\nfunction ceiling(num, precision) {\n return ((num / precision | 0) + 1) * precision;\n}\n\nfunction computeExpirationBucket(currentTime, expirationInMs, bucketSizeMs) {\n return MAGIC_NUMBER_OFFSET - ceiling(MAGIC_NUMBER_OFFSET - currentTime + expirationInMs / UNIT_SIZE, bucketSizeMs / UNIT_SIZE);\n} // TODO: This corresponds to Scheduler's NormalPriority, not LowPriority. Update\n// the names to reflect.\n\n\nvar LOW_PRIORITY_EXPIRATION = 5000;\nvar LOW_PRIORITY_BATCH_SIZE = 250;\nfunction computeAsyncExpiration(currentTime) {\n return computeExpirationBucket(currentTime, LOW_PRIORITY_EXPIRATION, LOW_PRIORITY_BATCH_SIZE);\n}\nfunction computeSuspenseExpiration(currentTime, timeoutMs) {\n // TODO: Should we warn if timeoutMs is lower than the normal pri expiration time?\n return computeExpirationBucket(currentTime, timeoutMs, LOW_PRIORITY_BATCH_SIZE);\n} // We intentionally set a higher expiration time for interactive updates in\n// dev than in production.\n//\n// If the main thread is being blocked so long that you hit the expiration,\n// it's a problem that could be solved with better scheduling.\n//\n// People will be more likely to notice this and fix it with the long\n// expiration time in development.\n//\n// In production we opt for better UX at the risk of masking scheduling\n// problems, by expiring fast.\n\nvar HIGH_PRIORITY_EXPIRATION = 500 ;\nvar HIGH_PRIORITY_BATCH_SIZE = 100;\nfunction computeInteractiveExpiration(currentTime) {\n return computeExpirationBucket(currentTime, HIGH_PRIORITY_EXPIRATION, HIGH_PRIORITY_BATCH_SIZE);\n}\nfunction inferPriorityFromExpirationTime(currentTime, expirationTime) {\n if (expirationTime === Sync) {\n return ImmediatePriority;\n }\n\n if (expirationTime === Never || expirationTime === Idle) {\n return IdlePriority;\n }\n\n var msUntil = expirationTimeToMs(expirationTime) - expirationTimeToMs(currentTime);\n\n if (msUntil <= 0) {\n return ImmediatePriority;\n }\n\n if (msUntil <= HIGH_PRIORITY_EXPIRATION + HIGH_PRIORITY_BATCH_SIZE) {\n return UserBlockingPriority$1;\n }\n\n if (msUntil <= LOW_PRIORITY_EXPIRATION + LOW_PRIORITY_BATCH_SIZE) {\n return NormalPriority;\n } // TODO: Handle LowPriority\n // Assume anything lower has idle priority\n\n\n return IdlePriority;\n}\n\nvar ReactStrictModeWarnings = {\n recordUnsafeLifecycleWarnings: function (fiber, instance) {},\n flushPendingUnsafeLifecycleWarnings: function () {},\n recordLegacyContextWarning: function (fiber, instance) {},\n flushLegacyContextWarning: function () {},\n discardPendingWarnings: function () {}\n};\n\n{\n var findStrictRoot = function (fiber) {\n var maybeStrictRoot = null;\n var node = fiber;\n\n while (node !== null) {\n if (node.mode & StrictMode) {\n maybeStrictRoot = node;\n }\n\n node = node.return;\n }\n\n return maybeStrictRoot;\n };\n\n var setToSortedString = function (set) {\n var array = [];\n set.forEach(function (value) {\n array.push(value);\n });\n return array.sort().join(', ');\n };\n\n var pendingComponentWillMountWarnings = [];\n var pendingUNSAFE_ComponentWillMountWarnings = [];\n var pendingComponentWillReceivePropsWarnings = [];\n var pendingUNSAFE_ComponentWillReceivePropsWarnings = [];\n var pendingComponentWillUpdateWarnings = [];\n var pendingUNSAFE_ComponentWillUpdateWarnings = []; // Tracks components we have already warned about.\n\n var didWarnAboutUnsafeLifecycles = new Set();\n\n ReactStrictModeWarnings.recordUnsafeLifecycleWarnings = function (fiber, instance) {\n // Dedup strategy: Warn once per component.\n if (didWarnAboutUnsafeLifecycles.has(fiber.type)) {\n return;\n }\n\n if (typeof instance.componentWillMount === 'function' && // Don't warn about react-lifecycles-compat polyfilled components.\n instance.componentWillMount.__suppressDeprecationWarning !== true) {\n pendingComponentWillMountWarnings.push(fiber);\n }\n\n if (fiber.mode & StrictMode && typeof instance.UNSAFE_componentWillMount === 'function') {\n pendingUNSAFE_ComponentWillMountWarnings.push(fiber);\n }\n\n if (typeof instance.componentWillReceiveProps === 'function' && instance.componentWillReceiveProps.__suppressDeprecationWarning !== true) {\n pendingComponentWillReceivePropsWarnings.push(fiber);\n }\n\n if (fiber.mode & StrictMode && typeof instance.UNSAFE_componentWillReceiveProps === 'function') {\n pendingUNSAFE_ComponentWillReceivePropsWarnings.push(fiber);\n }\n\n if (typeof instance.componentWillUpdate === 'function' && instance.componentWillUpdate.__suppressDeprecationWarning !== true) {\n pendingComponentWillUpdateWarnings.push(fiber);\n }\n\n if (fiber.mode & StrictMode && typeof instance.UNSAFE_componentWillUpdate === 'function') {\n pendingUNSAFE_ComponentWillUpdateWarnings.push(fiber);\n }\n };\n\n ReactStrictModeWarnings.flushPendingUnsafeLifecycleWarnings = function () {\n // We do an initial pass to gather component names\n var componentWillMountUniqueNames = new Set();\n\n if (pendingComponentWillMountWarnings.length > 0) {\n pendingComponentWillMountWarnings.forEach(function (fiber) {\n componentWillMountUniqueNames.add(getComponentName(fiber.type) || 'Component');\n didWarnAboutUnsafeLifecycles.add(fiber.type);\n });\n pendingComponentWillMountWarnings = [];\n }\n\n var UNSAFE_componentWillMountUniqueNames = new Set();\n\n if (pendingUNSAFE_ComponentWillMountWarnings.length > 0) {\n pendingUNSAFE_ComponentWillMountWarnings.forEach(function (fiber) {\n UNSAFE_componentWillMountUniqueNames.add(getComponentName(fiber.type) || 'Component');\n didWarnAboutUnsafeLifecycles.add(fiber.type);\n });\n pendingUNSAFE_ComponentWillMountWarnings = [];\n }\n\n var componentWillReceivePropsUniqueNames = new Set();\n\n if (pendingComponentWillReceivePropsWarnings.length > 0) {\n pendingComponentWillReceivePropsWarnings.forEach(function (fiber) {\n componentWillReceivePropsUniqueNames.add(getComponentName(fiber.type) || 'Component');\n didWarnAboutUnsafeLifecycles.add(fiber.type);\n });\n pendingComponentWillReceivePropsWarnings = [];\n }\n\n var UNSAFE_componentWillReceivePropsUniqueNames = new Set();\n\n if (pendingUNSAFE_ComponentWillReceivePropsWarnings.length > 0) {\n pendingUNSAFE_ComponentWillReceivePropsWarnings.forEach(function (fiber) {\n UNSAFE_componentWillReceivePropsUniqueNames.add(getComponentName(fiber.type) || 'Component');\n didWarnAboutUnsafeLifecycles.add(fiber.type);\n });\n pendingUNSAFE_ComponentWillReceivePropsWarnings = [];\n }\n\n var componentWillUpdateUniqueNames = new Set();\n\n if (pendingComponentWillUpdateWarnings.length > 0) {\n pendingComponentWillUpdateWarnings.forEach(function (fiber) {\n componentWillUpdateUniqueNames.add(getComponentName(fiber.type) || 'Component');\n didWarnAboutUnsafeLifecycles.add(fiber.type);\n });\n pendingComponentWillUpdateWarnings = [];\n }\n\n var UNSAFE_componentWillUpdateUniqueNames = new Set();\n\n if (pendingUNSAFE_ComponentWillUpdateWarnings.length > 0) {\n pendingUNSAFE_ComponentWillUpdateWarnings.forEach(function (fiber) {\n UNSAFE_componentWillUpdateUniqueNames.add(getComponentName(fiber.type) || 'Component');\n didWarnAboutUnsafeLifecycles.add(fiber.type);\n });\n pendingUNSAFE_ComponentWillUpdateWarnings = [];\n } // Finally, we flush all the warnings\n // UNSAFE_ ones before the deprecated ones, since they'll be 'louder'\n\n\n if (UNSAFE_componentWillMountUniqueNames.size > 0) {\n var sortedNames = setToSortedString(UNSAFE_componentWillMountUniqueNames);\n\n error('Using UNSAFE_componentWillMount in strict mode is not recommended and may indicate bugs in your code. ' + 'See https://fb.me/react-unsafe-component-lifecycles for details.\\n\\n' + '* Move code with side effects to componentDidMount, and set initial state in the constructor.\\n' + '\\nPlease update the following components: %s', sortedNames);\n }\n\n if (UNSAFE_componentWillReceivePropsUniqueNames.size > 0) {\n var _sortedNames = setToSortedString(UNSAFE_componentWillReceivePropsUniqueNames);\n\n error('Using UNSAFE_componentWillReceiveProps in strict mode is not recommended ' + 'and may indicate bugs in your code. ' + 'See https://fb.me/react-unsafe-component-lifecycles for details.\\n\\n' + '* Move data fetching code or side effects to componentDidUpdate.\\n' + \"* If you're updating state whenever props change, \" + 'refactor your code to use memoization techniques or move it to ' + 'static getDerivedStateFromProps. Learn more at: https://fb.me/react-derived-state\\n' + '\\nPlease update the following components: %s', _sortedNames);\n }\n\n if (UNSAFE_componentWillUpdateUniqueNames.size > 0) {\n var _sortedNames2 = setToSortedString(UNSAFE_componentWillUpdateUniqueNames);\n\n error('Using UNSAFE_componentWillUpdate in strict mode is not recommended ' + 'and may indicate bugs in your code. ' + 'See https://fb.me/react-unsafe-component-lifecycles for details.\\n\\n' + '* Move data fetching code or side effects to componentDidUpdate.\\n' + '\\nPlease update the following components: %s', _sortedNames2);\n }\n\n if (componentWillMountUniqueNames.size > 0) {\n var _sortedNames3 = setToSortedString(componentWillMountUniqueNames);\n\n warn('componentWillMount has been renamed, and is not recommended for use. ' + 'See https://fb.me/react-unsafe-component-lifecycles for details.\\n\\n' + '* Move code with side effects to componentDidMount, and set initial state in the constructor.\\n' + '* Rename componentWillMount to UNSAFE_componentWillMount to suppress ' + 'this warning in non-strict mode. In React 17.x, only the UNSAFE_ name will work. ' + 'To rename all deprecated lifecycles to their new names, you can run ' + '`npx react-codemod rename-unsafe-lifecycles` in your project source folder.\\n' + '\\nPlease update the following components: %s', _sortedNames3);\n }\n\n if (componentWillReceivePropsUniqueNames.size > 0) {\n var _sortedNames4 = setToSortedString(componentWillReceivePropsUniqueNames);\n\n warn('componentWillReceiveProps has been renamed, and is not recommended for use. ' + 'See https://fb.me/react-unsafe-component-lifecycles for details.\\n\\n' + '* Move data fetching code or side effects to componentDidUpdate.\\n' + \"* If you're updating state whenever props change, refactor your \" + 'code to use memoization techniques or move it to ' + 'static getDerivedStateFromProps. Learn more at: https://fb.me/react-derived-state\\n' + '* Rename componentWillReceiveProps to UNSAFE_componentWillReceiveProps to suppress ' + 'this warning in non-strict mode. In React 17.x, only the UNSAFE_ name will work. ' + 'To rename all deprecated lifecycles to their new names, you can run ' + '`npx react-codemod rename-unsafe-lifecycles` in your project source folder.\\n' + '\\nPlease update the following components: %s', _sortedNames4);\n }\n\n if (componentWillUpdateUniqueNames.size > 0) {\n var _sortedNames5 = setToSortedString(componentWillUpdateUniqueNames);\n\n warn('componentWillUpdate has been renamed, and is not recommended for use. ' + 'See https://fb.me/react-unsafe-component-lifecycles for details.\\n\\n' + '* Move data fetching code or side effects to componentDidUpdate.\\n' + '* Rename componentWillUpdate to UNSAFE_componentWillUpdate to suppress ' + 'this warning in non-strict mode. In React 17.x, only the UNSAFE_ name will work. ' + 'To rename all deprecated lifecycles to their new names, you can run ' + '`npx react-codemod rename-unsafe-lifecycles` in your project source folder.\\n' + '\\nPlease update the following components: %s', _sortedNames5);\n }\n };\n\n var pendingLegacyContextWarning = new Map(); // Tracks components we have already warned about.\n\n var didWarnAboutLegacyContext = new Set();\n\n ReactStrictModeWarnings.recordLegacyContextWarning = function (fiber, instance) {\n var strictRoot = findStrictRoot(fiber);\n\n if (strictRoot === null) {\n error('Expected to find a StrictMode component in a strict mode tree. ' + 'This error is likely caused by a bug in React. Please file an issue.');\n\n return;\n } // Dedup strategy: Warn once per component.\n\n\n if (didWarnAboutLegacyContext.has(fiber.type)) {\n return;\n }\n\n var warningsForRoot = pendingLegacyContextWarning.get(strictRoot);\n\n if (fiber.type.contextTypes != null || fiber.type.childContextTypes != null || instance !== null && typeof instance.getChildContext === 'function') {\n if (warningsForRoot === undefined) {\n warningsForRoot = [];\n pendingLegacyContextWarning.set(strictRoot, warningsForRoot);\n }\n\n warningsForRoot.push(fiber);\n }\n };\n\n ReactStrictModeWarnings.flushLegacyContextWarning = function () {\n pendingLegacyContextWarning.forEach(function (fiberArray, strictRoot) {\n if (fiberArray.length === 0) {\n return;\n }\n\n var firstFiber = fiberArray[0];\n var uniqueNames = new Set();\n fiberArray.forEach(function (fiber) {\n uniqueNames.add(getComponentName(fiber.type) || 'Component');\n didWarnAboutLegacyContext.add(fiber.type);\n });\n var sortedNames = setToSortedString(uniqueNames);\n var firstComponentStack = getStackByFiberInDevAndProd(firstFiber);\n\n error('Legacy context API has been detected within a strict-mode tree.' + '\\n\\nThe old API will be supported in all 16.x releases, but applications ' + 'using it should migrate to the new version.' + '\\n\\nPlease update the following components: %s' + '\\n\\nLearn more about this warning here: https://fb.me/react-legacy-context' + '%s', sortedNames, firstComponentStack);\n });\n };\n\n ReactStrictModeWarnings.discardPendingWarnings = function () {\n pendingComponentWillMountWarnings = [];\n pendingUNSAFE_ComponentWillMountWarnings = [];\n pendingComponentWillReceivePropsWarnings = [];\n pendingUNSAFE_ComponentWillReceivePropsWarnings = [];\n pendingComponentWillUpdateWarnings = [];\n pendingUNSAFE_ComponentWillUpdateWarnings = [];\n pendingLegacyContextWarning = new Map();\n };\n}\n\nvar resolveFamily = null; // $FlowFixMe Flow gets confused by a WeakSet feature check below.\n\nvar failedBoundaries = null;\nvar setRefreshHandler = function (handler) {\n {\n resolveFamily = handler;\n }\n};\nfunction resolveFunctionForHotReloading(type) {\n {\n if (resolveFamily === null) {\n // Hot reloading is disabled.\n return type;\n }\n\n var family = resolveFamily(type);\n\n if (family === undefined) {\n return type;\n } // Use the latest known implementation.\n\n\n return family.current;\n }\n}\nfunction resolveClassForHotReloading(type) {\n // No implementation differences.\n return resolveFunctionForHotReloading(type);\n}\nfunction resolveForwardRefForHotReloading(type) {\n {\n if (resolveFamily === null) {\n // Hot reloading is disabled.\n return type;\n }\n\n var family = resolveFamily(type);\n\n if (family === undefined) {\n // Check if we're dealing with a real forwardRef. Don't want to crash early.\n if (type !== null && type !== undefined && typeof type.render === 'function') {\n // ForwardRef is special because its resolved .type is an object,\n // but it's possible that we only have its inner render function in the map.\n // If that inner render function is different, we'll build a new forwardRef type.\n var currentRender = resolveFunctionForHotReloading(type.render);\n\n if (type.render !== currentRender) {\n var syntheticType = {\n $$typeof: REACT_FORWARD_REF_TYPE,\n render: currentRender\n };\n\n if (type.displayName !== undefined) {\n syntheticType.displayName = type.displayName;\n }\n\n return syntheticType;\n }\n }\n\n return type;\n } // Use the latest known implementation.\n\n\n return family.current;\n }\n}\nfunction isCompatibleFamilyForHotReloading(fiber, element) {\n {\n if (resolveFamily === null) {\n // Hot reloading is disabled.\n return false;\n }\n\n var prevType = fiber.elementType;\n var nextType = element.type; // If we got here, we know types aren't === equal.\n\n var needsCompareFamilies = false;\n var $$typeofNextType = typeof nextType === 'object' && nextType !== null ? nextType.$$typeof : null;\n\n switch (fiber.tag) {\n case ClassComponent:\n {\n if (typeof nextType === 'function') {\n needsCompareFamilies = true;\n }\n\n break;\n }\n\n case FunctionComponent:\n {\n if (typeof nextType === 'function') {\n needsCompareFamilies = true;\n } else if ($$typeofNextType === REACT_LAZY_TYPE) {\n // We don't know the inner type yet.\n // We're going to assume that the lazy inner type is stable,\n // and so it is sufficient to avoid reconciling it away.\n // We're not going to unwrap or actually use the new lazy type.\n needsCompareFamilies = true;\n }\n\n break;\n }\n\n case ForwardRef:\n {\n if ($$typeofNextType === REACT_FORWARD_REF_TYPE) {\n needsCompareFamilies = true;\n } else if ($$typeofNextType === REACT_LAZY_TYPE) {\n needsCompareFamilies = true;\n }\n\n break;\n }\n\n case MemoComponent:\n case SimpleMemoComponent:\n {\n if ($$typeofNextType === REACT_MEMO_TYPE) {\n // TODO: if it was but can no longer be simple,\n // we shouldn't set this.\n needsCompareFamilies = true;\n } else if ($$typeofNextType === REACT_LAZY_TYPE) {\n needsCompareFamilies = true;\n }\n\n break;\n }\n\n default:\n return false;\n } // Check if both types have a family and it's the same one.\n\n\n if (needsCompareFamilies) {\n // Note: memo() and forwardRef() we'll compare outer rather than inner type.\n // This means both of them need to be registered to preserve state.\n // If we unwrapped and compared the inner types for wrappers instead,\n // then we would risk falsely saying two separate memo(Foo)\n // calls are equivalent because they wrap the same Foo function.\n var prevFamily = resolveFamily(prevType);\n\n if (prevFamily !== undefined && prevFamily === resolveFamily(nextType)) {\n return true;\n }\n }\n\n return false;\n }\n}\nfunction markFailedErrorBoundaryForHotReloading(fiber) {\n {\n if (resolveFamily === null) {\n // Hot reloading is disabled.\n return;\n }\n\n if (typeof WeakSet !== 'function') {\n return;\n }\n\n if (failedBoundaries === null) {\n failedBoundaries = new WeakSet();\n }\n\n failedBoundaries.add(fiber);\n }\n}\nvar scheduleRefresh = function (root, update) {\n {\n if (resolveFamily === null) {\n // Hot reloading is disabled.\n return;\n }\n\n var staleFamilies = update.staleFamilies,\n updatedFamilies = update.updatedFamilies;\n flushPassiveEffects();\n flushSync(function () {\n scheduleFibersWithFamiliesRecursively(root.current, updatedFamilies, staleFamilies);\n });\n }\n};\nvar scheduleRoot = function (root, element) {\n {\n if (root.context !== emptyContextObject) {\n // Super edge case: root has a legacy _renderSubtree context\n // but we don't know the parentComponent so we can't pass it.\n // Just ignore. We'll delete this with _renderSubtree code path later.\n return;\n }\n\n flushPassiveEffects();\n syncUpdates(function () {\n updateContainer(element, root, null, null);\n });\n }\n};\n\nfunction scheduleFibersWithFamiliesRecursively(fiber, updatedFamilies, staleFamilies) {\n {\n var alternate = fiber.alternate,\n child = fiber.child,\n sibling = fiber.sibling,\n tag = fiber.tag,\n type = fiber.type;\n var candidateType = null;\n\n switch (tag) {\n case FunctionComponent:\n case SimpleMemoComponent:\n case ClassComponent:\n candidateType = type;\n break;\n\n case ForwardRef:\n candidateType = type.render;\n break;\n }\n\n if (resolveFamily === null) {\n throw new Error('Expected resolveFamily to be set during hot reload.');\n }\n\n var needsRender = false;\n var needsRemount = false;\n\n if (candidateType !== null) {\n var family = resolveFamily(candidateType);\n\n if (family !== undefined) {\n if (staleFamilies.has(family)) {\n needsRemount = true;\n } else if (updatedFamilies.has(family)) {\n if (tag === ClassComponent) {\n needsRemount = true;\n } else {\n needsRender = true;\n }\n }\n }\n }\n\n if (failedBoundaries !== null) {\n if (failedBoundaries.has(fiber) || alternate !== null && failedBoundaries.has(alternate)) {\n needsRemount = true;\n }\n }\n\n if (needsRemount) {\n fiber._debugNeedsRemount = true;\n }\n\n if (needsRemount || needsRender) {\n scheduleWork(fiber, Sync);\n }\n\n if (child !== null && !needsRemount) {\n scheduleFibersWithFamiliesRecursively(child, updatedFamilies, staleFamilies);\n }\n\n if (sibling !== null) {\n scheduleFibersWithFamiliesRecursively(sibling, updatedFamilies, staleFamilies);\n }\n }\n}\n\nvar findHostInstancesForRefresh = function (root, families) {\n {\n var hostInstances = new Set();\n var types = new Set(families.map(function (family) {\n return family.current;\n }));\n findHostInstancesForMatchingFibersRecursively(root.current, types, hostInstances);\n return hostInstances;\n }\n};\n\nfunction findHostInstancesForMatchingFibersRecursively(fiber, types, hostInstances) {\n {\n var child = fiber.child,\n sibling = fiber.sibling,\n tag = fiber.tag,\n type = fiber.type;\n var candidateType = null;\n\n switch (tag) {\n case FunctionComponent:\n case SimpleMemoComponent:\n case ClassComponent:\n candidateType = type;\n break;\n\n case ForwardRef:\n candidateType = type.render;\n break;\n }\n\n var didMatch = false;\n\n if (candidateType !== null) {\n if (types.has(candidateType)) {\n didMatch = true;\n }\n }\n\n if (didMatch) {\n // We have a match. This only drills down to the closest host components.\n // There's no need to search deeper because for the purpose of giving\n // visual feedback, \"flashing\" outermost parent rectangles is sufficient.\n findHostInstancesForFiberShallowly(fiber, hostInstances);\n } else {\n // If there's no match, maybe there will be one further down in the child tree.\n if (child !== null) {\n findHostInstancesForMatchingFibersRecursively(child, types, hostInstances);\n }\n }\n\n if (sibling !== null) {\n findHostInstancesForMatchingFibersRecursively(sibling, types, hostInstances);\n }\n }\n}\n\nfunction findHostInstancesForFiberShallowly(fiber, hostInstances) {\n {\n var foundHostInstances = findChildHostInstancesForFiberShallowly(fiber, hostInstances);\n\n if (foundHostInstances) {\n return;\n } // If we didn't find any host children, fallback to closest host parent.\n\n\n var node = fiber;\n\n while (true) {\n switch (node.tag) {\n case HostComponent:\n hostInstances.add(node.stateNode);\n return;\n\n case HostPortal:\n hostInstances.add(node.stateNode.containerInfo);\n return;\n\n case HostRoot:\n hostInstances.add(node.stateNode.containerInfo);\n return;\n }\n\n if (node.return === null) {\n throw new Error('Expected to reach root first.');\n }\n\n node = node.return;\n }\n }\n}\n\nfunction findChildHostInstancesForFiberShallowly(fiber, hostInstances) {\n {\n var node = fiber;\n var foundHostInstances = false;\n\n while (true) {\n if (node.tag === HostComponent) {\n // We got a match.\n foundHostInstances = true;\n hostInstances.add(node.stateNode); // There may still be more, so keep searching.\n } else if (node.child !== null) {\n node.child.return = node;\n node = node.child;\n continue;\n }\n\n if (node === fiber) {\n return foundHostInstances;\n }\n\n while (node.sibling === null) {\n if (node.return === null || node.return === fiber) {\n return foundHostInstances;\n }\n\n node = node.return;\n }\n\n node.sibling.return = node.return;\n node = node.sibling;\n }\n }\n\n return false;\n}\n\nfunction resolveDefaultProps(Component, baseProps) {\n if (Component && Component.defaultProps) {\n // Resolve default props. Taken from ReactElement\n var props = _assign({}, baseProps);\n\n var defaultProps = Component.defaultProps;\n\n for (var propName in defaultProps) {\n if (props[propName] === undefined) {\n props[propName] = defaultProps[propName];\n }\n }\n\n return props;\n }\n\n return baseProps;\n}\nfunction readLazyComponentType(lazyComponent) {\n initializeLazyComponentType(lazyComponent);\n\n if (lazyComponent._status !== Resolved) {\n throw lazyComponent._result;\n }\n\n return lazyComponent._result;\n}\n\nvar valueCursor = createCursor(null);\nvar rendererSigil;\n\n{\n // Use this to detect multiple renderers using the same context\n rendererSigil = {};\n}\n\nvar currentlyRenderingFiber = null;\nvar lastContextDependency = null;\nvar lastContextWithAllBitsObserved = null;\nvar isDisallowedContextReadInDEV = false;\nfunction resetContextDependencies() {\n // This is called right before React yields execution, to ensure `readContext`\n // cannot be called outside the render phase.\n currentlyRenderingFiber = null;\n lastContextDependency = null;\n lastContextWithAllBitsObserved = null;\n\n {\n isDisallowedContextReadInDEV = false;\n }\n}\nfunction enterDisallowedContextReadInDEV() {\n {\n isDisallowedContextReadInDEV = true;\n }\n}\nfunction exitDisallowedContextReadInDEV() {\n {\n isDisallowedContextReadInDEV = false;\n }\n}\nfunction pushProvider(providerFiber, nextValue) {\n var context = providerFiber.type._context;\n\n {\n push(valueCursor, context._currentValue, providerFiber);\n context._currentValue = nextValue;\n\n {\n if (context._currentRenderer !== undefined && context._currentRenderer !== null && context._currentRenderer !== rendererSigil) {\n error('Detected multiple renderers concurrently rendering the ' + 'same context provider. This is currently unsupported.');\n }\n\n context._currentRenderer = rendererSigil;\n }\n }\n}\nfunction popProvider(providerFiber) {\n var currentValue = valueCursor.current;\n pop(valueCursor, providerFiber);\n var context = providerFiber.type._context;\n\n {\n context._currentValue = currentValue;\n }\n}\nfunction calculateChangedBits(context, newValue, oldValue) {\n if (objectIs(oldValue, newValue)) {\n // No change\n return 0;\n } else {\n var changedBits = typeof context._calculateChangedBits === 'function' ? context._calculateChangedBits(oldValue, newValue) : MAX_SIGNED_31_BIT_INT;\n\n {\n if ((changedBits & MAX_SIGNED_31_BIT_INT) !== changedBits) {\n error('calculateChangedBits: Expected the return value to be a ' + '31-bit integer. Instead received: %s', changedBits);\n }\n }\n\n return changedBits | 0;\n }\n}\nfunction scheduleWorkOnParentPath(parent, renderExpirationTime) {\n // Update the child expiration time of all the ancestors, including\n // the alternates.\n var node = parent;\n\n while (node !== null) {\n var alternate = node.alternate;\n\n if (node.childExpirationTime < renderExpirationTime) {\n node.childExpirationTime = renderExpirationTime;\n\n if (alternate !== null && alternate.childExpirationTime < renderExpirationTime) {\n alternate.childExpirationTime = renderExpirationTime;\n }\n } else if (alternate !== null && alternate.childExpirationTime < renderExpirationTime) {\n alternate.childExpirationTime = renderExpirationTime;\n } else {\n // Neither alternate was updated, which means the rest of the\n // ancestor path already has sufficient priority.\n break;\n }\n\n node = node.return;\n }\n}\nfunction propagateContextChange(workInProgress, context, changedBits, renderExpirationTime) {\n var fiber = workInProgress.child;\n\n if (fiber !== null) {\n // Set the return pointer of the child to the work-in-progress fiber.\n fiber.return = workInProgress;\n }\n\n while (fiber !== null) {\n var nextFiber = void 0; // Visit this fiber.\n\n var list = fiber.dependencies;\n\n if (list !== null) {\n nextFiber = fiber.child;\n var dependency = list.firstContext;\n\n while (dependency !== null) {\n // Check if the context matches.\n if (dependency.context === context && (dependency.observedBits & changedBits) !== 0) {\n // Match! Schedule an update on this fiber.\n if (fiber.tag === ClassComponent) {\n // Schedule a force update on the work-in-progress.\n var update = createUpdate(renderExpirationTime, null);\n update.tag = ForceUpdate; // TODO: Because we don't have a work-in-progress, this will add the\n // update to the current fiber, too, which means it will persist even if\n // this render is thrown away. Since it's a race condition, not sure it's\n // worth fixing.\n\n enqueueUpdate(fiber, update);\n }\n\n if (fiber.expirationTime < renderExpirationTime) {\n fiber.expirationTime = renderExpirationTime;\n }\n\n var alternate = fiber.alternate;\n\n if (alternate !== null && alternate.expirationTime < renderExpirationTime) {\n alternate.expirationTime = renderExpirationTime;\n }\n\n scheduleWorkOnParentPath(fiber.return, renderExpirationTime); // Mark the expiration time on the list, too.\n\n if (list.expirationTime < renderExpirationTime) {\n list.expirationTime = renderExpirationTime;\n } // Since we already found a match, we can stop traversing the\n // dependency list.\n\n\n break;\n }\n\n dependency = dependency.next;\n }\n } else if (fiber.tag === ContextProvider) {\n // Don't scan deeper if this is a matching provider\n nextFiber = fiber.type === workInProgress.type ? null : fiber.child;\n } else {\n // Traverse down.\n nextFiber = fiber.child;\n }\n\n if (nextFiber !== null) {\n // Set the return pointer of the child to the work-in-progress fiber.\n nextFiber.return = fiber;\n } else {\n // No child. Traverse to next sibling.\n nextFiber = fiber;\n\n while (nextFiber !== null) {\n if (nextFiber === workInProgress) {\n // We're back to the root of this subtree. Exit.\n nextFiber = null;\n break;\n }\n\n var sibling = nextFiber.sibling;\n\n if (sibling !== null) {\n // Set the return pointer of the sibling to the work-in-progress fiber.\n sibling.return = nextFiber.return;\n nextFiber = sibling;\n break;\n } // No more siblings. Traverse up.\n\n\n nextFiber = nextFiber.return;\n }\n }\n\n fiber = nextFiber;\n }\n}\nfunction prepareToReadContext(workInProgress, renderExpirationTime) {\n currentlyRenderingFiber = workInProgress;\n lastContextDependency = null;\n lastContextWithAllBitsObserved = null;\n var dependencies = workInProgress.dependencies;\n\n if (dependencies !== null) {\n var firstContext = dependencies.firstContext;\n\n if (firstContext !== null) {\n if (dependencies.expirationTime >= renderExpirationTime) {\n // Context list has a pending update. Mark that this fiber performed work.\n markWorkInProgressReceivedUpdate();\n } // Reset the work-in-progress list\n\n\n dependencies.firstContext = null;\n }\n }\n}\nfunction readContext(context, observedBits) {\n {\n // This warning would fire if you read context inside a Hook like useMemo.\n // Unlike the class check below, it's not enforced in production for perf.\n if (isDisallowedContextReadInDEV) {\n error('Context can only be read while React is rendering. ' + 'In classes, you can read it in the render method or getDerivedStateFromProps. ' + 'In function components, you can read it directly in the function body, but not ' + 'inside Hooks like useReducer() or useMemo().');\n }\n }\n\n if (lastContextWithAllBitsObserved === context) ; else if (observedBits === false || observedBits === 0) ; else {\n var resolvedObservedBits; // Avoid deopting on observable arguments or heterogeneous types.\n\n if (typeof observedBits !== 'number' || observedBits === MAX_SIGNED_31_BIT_INT) {\n // Observe all updates.\n lastContextWithAllBitsObserved = context;\n resolvedObservedBits = MAX_SIGNED_31_BIT_INT;\n } else {\n resolvedObservedBits = observedBits;\n }\n\n var contextItem = {\n context: context,\n observedBits: resolvedObservedBits,\n next: null\n };\n\n if (lastContextDependency === null) {\n if (!(currentlyRenderingFiber !== null)) {\n {\n throw Error( \"Context can only be read while React is rendering. In classes, you can read it in the render method or getDerivedStateFromProps. In function components, you can read it directly in the function body, but not inside Hooks like useReducer() or useMemo().\" );\n }\n } // This is the first dependency for this component. Create a new list.\n\n\n lastContextDependency = contextItem;\n currentlyRenderingFiber.dependencies = {\n expirationTime: NoWork,\n firstContext: contextItem,\n responders: null\n };\n } else {\n // Append a new context item.\n lastContextDependency = lastContextDependency.next = contextItem;\n }\n }\n\n return context._currentValue ;\n}\n\nvar UpdateState = 0;\nvar ReplaceState = 1;\nvar ForceUpdate = 2;\nvar CaptureUpdate = 3; // Global state that is reset at the beginning of calling `processUpdateQueue`.\n// It should only be read right after calling `processUpdateQueue`, via\n// `checkHasForceUpdateAfterProcessing`.\n\nvar hasForceUpdate = false;\nvar didWarnUpdateInsideUpdate;\nvar currentlyProcessingQueue;\n\n{\n didWarnUpdateInsideUpdate = false;\n currentlyProcessingQueue = null;\n}\n\nfunction initializeUpdateQueue(fiber) {\n var queue = {\n baseState: fiber.memoizedState,\n baseQueue: null,\n shared: {\n pending: null\n },\n effects: null\n };\n fiber.updateQueue = queue;\n}\nfunction cloneUpdateQueue(current, workInProgress) {\n // Clone the update queue from current. Unless it's already a clone.\n var queue = workInProgress.updateQueue;\n var currentQueue = current.updateQueue;\n\n if (queue === currentQueue) {\n var clone = {\n baseState: currentQueue.baseState,\n baseQueue: currentQueue.baseQueue,\n shared: currentQueue.shared,\n effects: currentQueue.effects\n };\n workInProgress.updateQueue = clone;\n }\n}\nfunction createUpdate(expirationTime, suspenseConfig) {\n var update = {\n expirationTime: expirationTime,\n suspenseConfig: suspenseConfig,\n tag: UpdateState,\n payload: null,\n callback: null,\n next: null\n };\n update.next = update;\n\n {\n update.priority = getCurrentPriorityLevel();\n }\n\n return update;\n}\nfunction enqueueUpdate(fiber, update) {\n var updateQueue = fiber.updateQueue;\n\n if (updateQueue === null) {\n // Only occurs if the fiber has been unmounted.\n return;\n }\n\n var sharedQueue = updateQueue.shared;\n var pending = sharedQueue.pending;\n\n if (pending === null) {\n // This is the first update. Create a circular list.\n update.next = update;\n } else {\n update.next = pending.next;\n pending.next = update;\n }\n\n sharedQueue.pending = update;\n\n {\n if (currentlyProcessingQueue === sharedQueue && !didWarnUpdateInsideUpdate) {\n error('An update (setState, replaceState, or forceUpdate) was scheduled ' + 'from inside an update function. Update functions should be pure, ' + 'with zero side-effects. Consider using componentDidUpdate or a ' + 'callback.');\n\n didWarnUpdateInsideUpdate = true;\n }\n }\n}\nfunction enqueueCapturedUpdate(workInProgress, update) {\n var current = workInProgress.alternate;\n\n if (current !== null) {\n // Ensure the work-in-progress queue is a clone\n cloneUpdateQueue(current, workInProgress);\n } // Captured updates go only on the work-in-progress queue.\n\n\n var queue = workInProgress.updateQueue; // Append the update to the end of the list.\n\n var last = queue.baseQueue;\n\n if (last === null) {\n queue.baseQueue = update.next = update;\n update.next = update;\n } else {\n update.next = last.next;\n last.next = update;\n }\n}\n\nfunction getStateFromUpdate(workInProgress, queue, update, prevState, nextProps, instance) {\n switch (update.tag) {\n case ReplaceState:\n {\n var payload = update.payload;\n\n if (typeof payload === 'function') {\n // Updater function\n {\n enterDisallowedContextReadInDEV();\n\n if ( workInProgress.mode & StrictMode) {\n payload.call(instance, prevState, nextProps);\n }\n }\n\n var nextState = payload.call(instance, prevState, nextProps);\n\n {\n exitDisallowedContextReadInDEV();\n }\n\n return nextState;\n } // State object\n\n\n return payload;\n }\n\n case CaptureUpdate:\n {\n workInProgress.effectTag = workInProgress.effectTag & ~ShouldCapture | DidCapture;\n }\n // Intentional fallthrough\n\n case UpdateState:\n {\n var _payload = update.payload;\n var partialState;\n\n if (typeof _payload === 'function') {\n // Updater function\n {\n enterDisallowedContextReadInDEV();\n\n if ( workInProgress.mode & StrictMode) {\n _payload.call(instance, prevState, nextProps);\n }\n }\n\n partialState = _payload.call(instance, prevState, nextProps);\n\n {\n exitDisallowedContextReadInDEV();\n }\n } else {\n // Partial state object\n partialState = _payload;\n }\n\n if (partialState === null || partialState === undefined) {\n // Null and undefined are treated as no-ops.\n return prevState;\n } // Merge the partial state and the previous state.\n\n\n return _assign({}, prevState, partialState);\n }\n\n case ForceUpdate:\n {\n hasForceUpdate = true;\n return prevState;\n }\n }\n\n return prevState;\n}\n\nfunction processUpdateQueue(workInProgress, props, instance, renderExpirationTime) {\n // This is always non-null on a ClassComponent or HostRoot\n var queue = workInProgress.updateQueue;\n hasForceUpdate = false;\n\n {\n currentlyProcessingQueue = queue.shared;\n } // The last rebase update that is NOT part of the base state.\n\n\n var baseQueue = queue.baseQueue; // The last pending update that hasn't been processed yet.\n\n var pendingQueue = queue.shared.pending;\n\n if (pendingQueue !== null) {\n // We have new updates that haven't been processed yet.\n // We'll add them to the base queue.\n if (baseQueue !== null) {\n // Merge the pending queue and the base queue.\n var baseFirst = baseQueue.next;\n var pendingFirst = pendingQueue.next;\n baseQueue.next = pendingFirst;\n pendingQueue.next = baseFirst;\n }\n\n baseQueue = pendingQueue;\n queue.shared.pending = null; // TODO: Pass `current` as argument\n\n var current = workInProgress.alternate;\n\n if (current !== null) {\n var currentQueue = current.updateQueue;\n\n if (currentQueue !== null) {\n currentQueue.baseQueue = pendingQueue;\n }\n }\n } // These values may change as we process the queue.\n\n\n if (baseQueue !== null) {\n var first = baseQueue.next; // Iterate through the list of updates to compute the result.\n\n var newState = queue.baseState;\n var newExpirationTime = NoWork;\n var newBaseState = null;\n var newBaseQueueFirst = null;\n var newBaseQueueLast = null;\n\n if (first !== null) {\n var update = first;\n\n do {\n var updateExpirationTime = update.expirationTime;\n\n if (updateExpirationTime < renderExpirationTime) {\n // Priority is insufficient. Skip this update. If this is the first\n // skipped update, the previous update/state is the new base\n // update/state.\n var clone = {\n expirationTime: update.expirationTime,\n suspenseConfig: update.suspenseConfig,\n tag: update.tag,\n payload: update.payload,\n callback: update.callback,\n next: null\n };\n\n if (newBaseQueueLast === null) {\n newBaseQueueFirst = newBaseQueueLast = clone;\n newBaseState = newState;\n } else {\n newBaseQueueLast = newBaseQueueLast.next = clone;\n } // Update the remaining priority in the queue.\n\n\n if (updateExpirationTime > newExpirationTime) {\n newExpirationTime = updateExpirationTime;\n }\n } else {\n // This update does have sufficient priority.\n if (newBaseQueueLast !== null) {\n var _clone = {\n expirationTime: Sync,\n // This update is going to be committed so we never want uncommit it.\n suspenseConfig: update.suspenseConfig,\n tag: update.tag,\n payload: update.payload,\n callback: update.callback,\n next: null\n };\n newBaseQueueLast = newBaseQueueLast.next = _clone;\n } // Mark the event time of this update as relevant to this render pass.\n // TODO: This should ideally use the true event time of this update rather than\n // its priority which is a derived and not reverseable value.\n // TODO: We should skip this update if it was already committed but currently\n // we have no way of detecting the difference between a committed and suspended\n // update here.\n\n\n markRenderEventTimeAndConfig(updateExpirationTime, update.suspenseConfig); // Process this update.\n\n newState = getStateFromUpdate(workInProgress, queue, update, newState, props, instance);\n var callback = update.callback;\n\n if (callback !== null) {\n workInProgress.effectTag |= Callback;\n var effects = queue.effects;\n\n if (effects === null) {\n queue.effects = [update];\n } else {\n effects.push(update);\n }\n }\n }\n\n update = update.next;\n\n if (update === null || update === first) {\n pendingQueue = queue.shared.pending;\n\n if (pendingQueue === null) {\n break;\n } else {\n // An update was scheduled from inside a reducer. Add the new\n // pending updates to the end of the list and keep processing.\n update = baseQueue.next = pendingQueue.next;\n pendingQueue.next = first;\n queue.baseQueue = baseQueue = pendingQueue;\n queue.shared.pending = null;\n }\n }\n } while (true);\n }\n\n if (newBaseQueueLast === null) {\n newBaseState = newState;\n } else {\n newBaseQueueLast.next = newBaseQueueFirst;\n }\n\n queue.baseState = newBaseState;\n queue.baseQueue = newBaseQueueLast; // Set the remaining expiration time to be whatever is remaining in the queue.\n // This should be fine because the only two other things that contribute to\n // expiration time are props and context. We're already in the middle of the\n // begin phase by the time we start processing the queue, so we've already\n // dealt with the props. Context in components that specify\n // shouldComponentUpdate is tricky; but we'll have to account for\n // that regardless.\n\n markUnprocessedUpdateTime(newExpirationTime);\n workInProgress.expirationTime = newExpirationTime;\n workInProgress.memoizedState = newState;\n }\n\n {\n currentlyProcessingQueue = null;\n }\n}\n\nfunction callCallback(callback, context) {\n if (!(typeof callback === 'function')) {\n {\n throw Error( \"Invalid argument passed as callback. Expected a function. Instead received: \" + callback );\n }\n }\n\n callback.call(context);\n}\n\nfunction resetHasForceUpdateBeforeProcessing() {\n hasForceUpdate = false;\n}\nfunction checkHasForceUpdateAfterProcessing() {\n return hasForceUpdate;\n}\nfunction commitUpdateQueue(finishedWork, finishedQueue, instance) {\n // Commit the effects\n var effects = finishedQueue.effects;\n finishedQueue.effects = null;\n\n if (effects !== null) {\n for (var i = 0; i < effects.length; i++) {\n var effect = effects[i];\n var callback = effect.callback;\n\n if (callback !== null) {\n effect.callback = null;\n callCallback(callback, instance);\n }\n }\n }\n}\n\nvar ReactCurrentBatchConfig = ReactSharedInternals.ReactCurrentBatchConfig;\nfunction requestCurrentSuspenseConfig() {\n return ReactCurrentBatchConfig.suspense;\n}\n\nvar fakeInternalInstance = {};\nvar isArray = Array.isArray; // React.Component uses a shared frozen object by default.\n// We'll use it to determine whether we need to initialize legacy refs.\n\nvar emptyRefsObject = new React.Component().refs;\nvar didWarnAboutStateAssignmentForComponent;\nvar didWarnAboutUninitializedState;\nvar didWarnAboutGetSnapshotBeforeUpdateWithoutDidUpdate;\nvar didWarnAboutLegacyLifecyclesAndDerivedState;\nvar didWarnAboutUndefinedDerivedState;\nvar warnOnUndefinedDerivedState;\nvar warnOnInvalidCallback;\nvar didWarnAboutDirectlyAssigningPropsToState;\nvar didWarnAboutContextTypeAndContextTypes;\nvar didWarnAboutInvalidateContextType;\n\n{\n didWarnAboutStateAssignmentForComponent = new Set();\n didWarnAboutUninitializedState = new Set();\n didWarnAboutGetSnapshotBeforeUpdateWithoutDidUpdate = new Set();\n didWarnAboutLegacyLifecyclesAndDerivedState = new Set();\n didWarnAboutDirectlyAssigningPropsToState = new Set();\n didWarnAboutUndefinedDerivedState = new Set();\n didWarnAboutContextTypeAndContextTypes = new Set();\n didWarnAboutInvalidateContextType = new Set();\n var didWarnOnInvalidCallback = new Set();\n\n warnOnInvalidCallback = function (callback, callerName) {\n if (callback === null || typeof callback === 'function') {\n return;\n }\n\n var key = callerName + \"_\" + callback;\n\n if (!didWarnOnInvalidCallback.has(key)) {\n didWarnOnInvalidCallback.add(key);\n\n error('%s(...): Expected the last optional `callback` argument to be a ' + 'function. Instead received: %s.', callerName, callback);\n }\n };\n\n warnOnUndefinedDerivedState = function (type, partialState) {\n if (partialState === undefined) {\n var componentName = getComponentName(type) || 'Component';\n\n if (!didWarnAboutUndefinedDerivedState.has(componentName)) {\n didWarnAboutUndefinedDerivedState.add(componentName);\n\n error('%s.getDerivedStateFromProps(): A valid state object (or null) must be returned. ' + 'You have returned undefined.', componentName);\n }\n }\n }; // This is so gross but it's at least non-critical and can be removed if\n // it causes problems. This is meant to give a nicer error message for\n // ReactDOM15.unstable_renderSubtreeIntoContainer(reactDOM16Component,\n // ...)) which otherwise throws a \"_processChildContext is not a function\"\n // exception.\n\n\n Object.defineProperty(fakeInternalInstance, '_processChildContext', {\n enumerable: false,\n value: function () {\n {\n {\n throw Error( \"_processChildContext is not available in React 16+. This likely means you have multiple copies of React and are attempting to nest a React 15 tree inside a React 16 tree using unstable_renderSubtreeIntoContainer, which isn't supported. Try to make sure you have only one copy of React (and ideally, switch to ReactDOM.createPortal).\" );\n }\n }\n }\n });\n Object.freeze(fakeInternalInstance);\n}\n\nfunction applyDerivedStateFromProps(workInProgress, ctor, getDerivedStateFromProps, nextProps) {\n var prevState = workInProgress.memoizedState;\n\n {\n if ( workInProgress.mode & StrictMode) {\n // Invoke the function an extra time to help detect side-effects.\n getDerivedStateFromProps(nextProps, prevState);\n }\n }\n\n var partialState = getDerivedStateFromProps(nextProps, prevState);\n\n {\n warnOnUndefinedDerivedState(ctor, partialState);\n } // Merge the partial state and the previous state.\n\n\n var memoizedState = partialState === null || partialState === undefined ? prevState : _assign({}, prevState, partialState);\n workInProgress.memoizedState = memoizedState; // Once the update queue is empty, persist the derived state onto the\n // base state.\n\n if (workInProgress.expirationTime === NoWork) {\n // Queue is always non-null for classes\n var updateQueue = workInProgress.updateQueue;\n updateQueue.baseState = memoizedState;\n }\n}\nvar classComponentUpdater = {\n isMounted: isMounted,\n enqueueSetState: function (inst, payload, callback) {\n var fiber = get(inst);\n var currentTime = requestCurrentTimeForUpdate();\n var suspenseConfig = requestCurrentSuspenseConfig();\n var expirationTime = computeExpirationForFiber(currentTime, fiber, suspenseConfig);\n var update = createUpdate(expirationTime, suspenseConfig);\n update.payload = payload;\n\n if (callback !== undefined && callback !== null) {\n {\n warnOnInvalidCallback(callback, 'setState');\n }\n\n update.callback = callback;\n }\n\n enqueueUpdate(fiber, update);\n scheduleWork(fiber, expirationTime);\n },\n enqueueReplaceState: function (inst, payload, callback) {\n var fiber = get(inst);\n var currentTime = requestCurrentTimeForUpdate();\n var suspenseConfig = requestCurrentSuspenseConfig();\n var expirationTime = computeExpirationForFiber(currentTime, fiber, suspenseConfig);\n var update = createUpdate(expirationTime, suspenseConfig);\n update.tag = ReplaceState;\n update.payload = payload;\n\n if (callback !== undefined && callback !== null) {\n {\n warnOnInvalidCallback(callback, 'replaceState');\n }\n\n update.callback = callback;\n }\n\n enqueueUpdate(fiber, update);\n scheduleWork(fiber, expirationTime);\n },\n enqueueForceUpdate: function (inst, callback) {\n var fiber = get(inst);\n var currentTime = requestCurrentTimeForUpdate();\n var suspenseConfig = requestCurrentSuspenseConfig();\n var expirationTime = computeExpirationForFiber(currentTime, fiber, suspenseConfig);\n var update = createUpdate(expirationTime, suspenseConfig);\n update.tag = ForceUpdate;\n\n if (callback !== undefined && callback !== null) {\n {\n warnOnInvalidCallback(callback, 'forceUpdate');\n }\n\n update.callback = callback;\n }\n\n enqueueUpdate(fiber, update);\n scheduleWork(fiber, expirationTime);\n }\n};\n\nfunction checkShouldComponentUpdate(workInProgress, ctor, oldProps, newProps, oldState, newState, nextContext) {\n var instance = workInProgress.stateNode;\n\n if (typeof instance.shouldComponentUpdate === 'function') {\n {\n if ( workInProgress.mode & StrictMode) {\n // Invoke the function an extra time to help detect side-effects.\n instance.shouldComponentUpdate(newProps, newState, nextContext);\n }\n }\n\n startPhaseTimer(workInProgress, 'shouldComponentUpdate');\n var shouldUpdate = instance.shouldComponentUpdate(newProps, newState, nextContext);\n stopPhaseTimer();\n\n {\n if (shouldUpdate === undefined) {\n error('%s.shouldComponentUpdate(): Returned undefined instead of a ' + 'boolean value. Make sure to return true or false.', getComponentName(ctor) || 'Component');\n }\n }\n\n return shouldUpdate;\n }\n\n if (ctor.prototype && ctor.prototype.isPureReactComponent) {\n return !shallowEqual(oldProps, newProps) || !shallowEqual(oldState, newState);\n }\n\n return true;\n}\n\nfunction checkClassInstance(workInProgress, ctor, newProps) {\n var instance = workInProgress.stateNode;\n\n {\n var name = getComponentName(ctor) || 'Component';\n var renderPresent = instance.render;\n\n if (!renderPresent) {\n if (ctor.prototype && typeof ctor.prototype.render === 'function') {\n error('%s(...): No `render` method found on the returned component ' + 'instance: did you accidentally return an object from the constructor?', name);\n } else {\n error('%s(...): No `render` method found on the returned component ' + 'instance: you may have forgotten to define `render`.', name);\n }\n }\n\n if (instance.getInitialState && !instance.getInitialState.isReactClassApproved && !instance.state) {\n error('getInitialState was defined on %s, a plain JavaScript class. ' + 'This is only supported for classes created using React.createClass. ' + 'Did you mean to define a state property instead?', name);\n }\n\n if (instance.getDefaultProps && !instance.getDefaultProps.isReactClassApproved) {\n error('getDefaultProps was defined on %s, a plain JavaScript class. ' + 'This is only supported for classes created using React.createClass. ' + 'Use a static property to define defaultProps instead.', name);\n }\n\n if (instance.propTypes) {\n error('propTypes was defined as an instance property on %s. Use a static ' + 'property to define propTypes instead.', name);\n }\n\n if (instance.contextType) {\n error('contextType was defined as an instance property on %s. Use a static ' + 'property to define contextType instead.', name);\n }\n\n {\n if (instance.contextTypes) {\n error('contextTypes was defined as an instance property on %s. Use a static ' + 'property to define contextTypes instead.', name);\n }\n\n if (ctor.contextType && ctor.contextTypes && !didWarnAboutContextTypeAndContextTypes.has(ctor)) {\n didWarnAboutContextTypeAndContextTypes.add(ctor);\n\n error('%s declares both contextTypes and contextType static properties. ' + 'The legacy contextTypes property will be ignored.', name);\n }\n }\n\n if (typeof instance.componentShouldUpdate === 'function') {\n error('%s has a method called ' + 'componentShouldUpdate(). Did you mean shouldComponentUpdate()? ' + 'The name is phrased as a question because the function is ' + 'expected to return a value.', name);\n }\n\n if (ctor.prototype && ctor.prototype.isPureReactComponent && typeof instance.shouldComponentUpdate !== 'undefined') {\n error('%s has a method called shouldComponentUpdate(). ' + 'shouldComponentUpdate should not be used when extending React.PureComponent. ' + 'Please extend React.Component if shouldComponentUpdate is used.', getComponentName(ctor) || 'A pure component');\n }\n\n if (typeof instance.componentDidUnmount === 'function') {\n error('%s has a method called ' + 'componentDidUnmount(). But there is no such lifecycle method. ' + 'Did you mean componentWillUnmount()?', name);\n }\n\n if (typeof instance.componentDidReceiveProps === 'function') {\n error('%s has a method called ' + 'componentDidReceiveProps(). But there is no such lifecycle method. ' + 'If you meant to update the state in response to changing props, ' + 'use componentWillReceiveProps(). If you meant to fetch data or ' + 'run side-effects or mutations after React has updated the UI, use componentDidUpdate().', name);\n }\n\n if (typeof instance.componentWillRecieveProps === 'function') {\n error('%s has a method called ' + 'componentWillRecieveProps(). Did you mean componentWillReceiveProps()?', name);\n }\n\n if (typeof instance.UNSAFE_componentWillRecieveProps === 'function') {\n error('%s has a method called ' + 'UNSAFE_componentWillRecieveProps(). Did you mean UNSAFE_componentWillReceiveProps()?', name);\n }\n\n var hasMutatedProps = instance.props !== newProps;\n\n if (instance.props !== undefined && hasMutatedProps) {\n error('%s(...): When calling super() in `%s`, make sure to pass ' + \"up the same props that your component's constructor was passed.\", name, name);\n }\n\n if (instance.defaultProps) {\n error('Setting defaultProps as an instance property on %s is not supported and will be ignored.' + ' Instead, define defaultProps as a static property on %s.', name, name);\n }\n\n if (typeof instance.getSnapshotBeforeUpdate === 'function' && typeof instance.componentDidUpdate !== 'function' && !didWarnAboutGetSnapshotBeforeUpdateWithoutDidUpdate.has(ctor)) {\n didWarnAboutGetSnapshotBeforeUpdateWithoutDidUpdate.add(ctor);\n\n error('%s: getSnapshotBeforeUpdate() should be used with componentDidUpdate(). ' + 'This component defines getSnapshotBeforeUpdate() only.', getComponentName(ctor));\n }\n\n if (typeof instance.getDerivedStateFromProps === 'function') {\n error('%s: getDerivedStateFromProps() is defined as an instance method ' + 'and will be ignored. Instead, declare it as a static method.', name);\n }\n\n if (typeof instance.getDerivedStateFromError === 'function') {\n error('%s: getDerivedStateFromError() is defined as an instance method ' + 'and will be ignored. Instead, declare it as a static method.', name);\n }\n\n if (typeof ctor.getSnapshotBeforeUpdate === 'function') {\n error('%s: getSnapshotBeforeUpdate() is defined as a static method ' + 'and will be ignored. Instead, declare it as an instance method.', name);\n }\n\n var _state = instance.state;\n\n if (_state && (typeof _state !== 'object' || isArray(_state))) {\n error('%s.state: must be set to an object or null', name);\n }\n\n if (typeof instance.getChildContext === 'function' && typeof ctor.childContextTypes !== 'object') {\n error('%s.getChildContext(): childContextTypes must be defined in order to ' + 'use getChildContext().', name);\n }\n }\n}\n\nfunction adoptClassInstance(workInProgress, instance) {\n instance.updater = classComponentUpdater;\n workInProgress.stateNode = instance; // The instance needs access to the fiber so that it can schedule updates\n\n set(instance, workInProgress);\n\n {\n instance._reactInternalInstance = fakeInternalInstance;\n }\n}\n\nfunction constructClassInstance(workInProgress, ctor, props) {\n var isLegacyContextConsumer = false;\n var unmaskedContext = emptyContextObject;\n var context = emptyContextObject;\n var contextType = ctor.contextType;\n\n {\n if ('contextType' in ctor) {\n var isValid = // Allow null for conditional declaration\n contextType === null || contextType !== undefined && contextType.$$typeof === REACT_CONTEXT_TYPE && contextType._context === undefined; // Not a <Context.Consumer>\n\n if (!isValid && !didWarnAboutInvalidateContextType.has(ctor)) {\n didWarnAboutInvalidateContextType.add(ctor);\n var addendum = '';\n\n if (contextType === undefined) {\n addendum = ' However, it is set to undefined. ' + 'This can be caused by a typo or by mixing up named and default imports. ' + 'This can also happen due to a circular dependency, so ' + 'try moving the createContext() call to a separate file.';\n } else if (typeof contextType !== 'object') {\n addendum = ' However, it is set to a ' + typeof contextType + '.';\n } else if (contextType.$$typeof === REACT_PROVIDER_TYPE) {\n addendum = ' Did you accidentally pass the Context.Provider instead?';\n } else if (contextType._context !== undefined) {\n // <Context.Consumer>\n addendum = ' Did you accidentally pass the Context.Consumer instead?';\n } else {\n addendum = ' However, it is set to an object with keys {' + Object.keys(contextType).join(', ') + '}.';\n }\n\n error('%s defines an invalid contextType. ' + 'contextType should point to the Context object returned by React.createContext().%s', getComponentName(ctor) || 'Component', addendum);\n }\n }\n }\n\n if (typeof contextType === 'object' && contextType !== null) {\n context = readContext(contextType);\n } else {\n unmaskedContext = getUnmaskedContext(workInProgress, ctor, true);\n var contextTypes = ctor.contextTypes;\n isLegacyContextConsumer = contextTypes !== null && contextTypes !== undefined;\n context = isLegacyContextConsumer ? getMaskedContext(workInProgress, unmaskedContext) : emptyContextObject;\n } // Instantiate twice to help detect side-effects.\n\n\n {\n if ( workInProgress.mode & StrictMode) {\n new ctor(props, context); // eslint-disable-line no-new\n }\n }\n\n var instance = new ctor(props, context);\n var state = workInProgress.memoizedState = instance.state !== null && instance.state !== undefined ? instance.state : null;\n adoptClassInstance(workInProgress, instance);\n\n {\n if (typeof ctor.getDerivedStateFromProps === 'function' && state === null) {\n var componentName = getComponentName(ctor) || 'Component';\n\n if (!didWarnAboutUninitializedState.has(componentName)) {\n didWarnAboutUninitializedState.add(componentName);\n\n error('`%s` uses `getDerivedStateFromProps` but its initial state is ' + '%s. This is not recommended. Instead, define the initial state by ' + 'assigning an object to `this.state` in the constructor of `%s`. ' + 'This ensures that `getDerivedStateFromProps` arguments have a consistent shape.', componentName, instance.state === null ? 'null' : 'undefined', componentName);\n }\n } // If new component APIs are defined, \"unsafe\" lifecycles won't be called.\n // Warn about these lifecycles if they are present.\n // Don't warn about react-lifecycles-compat polyfilled methods though.\n\n\n if (typeof ctor.getDerivedStateFromProps === 'function' || typeof instance.getSnapshotBeforeUpdate === 'function') {\n var foundWillMountName = null;\n var foundWillReceivePropsName = null;\n var foundWillUpdateName = null;\n\n if (typeof instance.componentWillMount === 'function' && instance.componentWillMount.__suppressDeprecationWarning !== true) {\n foundWillMountName = 'componentWillMount';\n } else if (typeof instance.UNSAFE_componentWillMount === 'function') {\n foundWillMountName = 'UNSAFE_componentWillMount';\n }\n\n if (typeof instance.componentWillReceiveProps === 'function' && instance.componentWillReceiveProps.__suppressDeprecationWarning !== true) {\n foundWillReceivePropsName = 'componentWillReceiveProps';\n } else if (typeof instance.UNSAFE_componentWillReceiveProps === 'function') {\n foundWillReceivePropsName = 'UNSAFE_componentWillReceiveProps';\n }\n\n if (typeof instance.componentWillUpdate === 'function' && instance.componentWillUpdate.__suppressDeprecationWarning !== true) {\n foundWillUpdateName = 'componentWillUpdate';\n } else if (typeof instance.UNSAFE_componentWillUpdate === 'function') {\n foundWillUpdateName = 'UNSAFE_componentWillUpdate';\n }\n\n if (foundWillMountName !== null || foundWillReceivePropsName !== null || foundWillUpdateName !== null) {\n var _componentName = getComponentName(ctor) || 'Component';\n\n var newApiName = typeof ctor.getDerivedStateFromProps === 'function' ? 'getDerivedStateFromProps()' : 'getSnapshotBeforeUpdate()';\n\n if (!didWarnAboutLegacyLifecyclesAndDerivedState.has(_componentName)) {\n didWarnAboutLegacyLifecyclesAndDerivedState.add(_componentName);\n\n error('Unsafe legacy lifecycles will not be called for components using new component APIs.\\n\\n' + '%s uses %s but also contains the following legacy lifecycles:%s%s%s\\n\\n' + 'The above lifecycles should be removed. Learn more about this warning here:\\n' + 'https://fb.me/react-unsafe-component-lifecycles', _componentName, newApiName, foundWillMountName !== null ? \"\\n \" + foundWillMountName : '', foundWillReceivePropsName !== null ? \"\\n \" + foundWillReceivePropsName : '', foundWillUpdateName !== null ? \"\\n \" + foundWillUpdateName : '');\n }\n }\n }\n } // Cache unmasked context so we can avoid recreating masked context unless necessary.\n // ReactFiberContext usually updates this cache but can't for newly-created instances.\n\n\n if (isLegacyContextConsumer) {\n cacheContext(workInProgress, unmaskedContext, context);\n }\n\n return instance;\n}\n\nfunction callComponentWillMount(workInProgress, instance) {\n startPhaseTimer(workInProgress, 'componentWillMount');\n var oldState = instance.state;\n\n if (typeof instance.componentWillMount === 'function') {\n instance.componentWillMount();\n }\n\n if (typeof instance.UNSAFE_componentWillMount === 'function') {\n instance.UNSAFE_componentWillMount();\n }\n\n stopPhaseTimer();\n\n if (oldState !== instance.state) {\n {\n error('%s.componentWillMount(): Assigning directly to this.state is ' + \"deprecated (except inside a component's \" + 'constructor). Use setState instead.', getComponentName(workInProgress.type) || 'Component');\n }\n\n classComponentUpdater.enqueueReplaceState(instance, instance.state, null);\n }\n}\n\nfunction callComponentWillReceiveProps(workInProgress, instance, newProps, nextContext) {\n var oldState = instance.state;\n startPhaseTimer(workInProgress, 'componentWillReceiveProps');\n\n if (typeof instance.componentWillReceiveProps === 'function') {\n instance.componentWillReceiveProps(newProps, nextContext);\n }\n\n if (typeof instance.UNSAFE_componentWillReceiveProps === 'function') {\n instance.UNSAFE_componentWillReceiveProps(newProps, nextContext);\n }\n\n stopPhaseTimer();\n\n if (instance.state !== oldState) {\n {\n var componentName = getComponentName(workInProgress.type) || 'Component';\n\n if (!didWarnAboutStateAssignmentForComponent.has(componentName)) {\n didWarnAboutStateAssignmentForComponent.add(componentName);\n\n error('%s.componentWillReceiveProps(): Assigning directly to ' + \"this.state is deprecated (except inside a component's \" + 'constructor). Use setState instead.', componentName);\n }\n }\n\n classComponentUpdater.enqueueReplaceState(instance, instance.state, null);\n }\n} // Invokes the mount life-cycles on a previously never rendered instance.\n\n\nfunction mountClassInstance(workInProgress, ctor, newProps, renderExpirationTime) {\n {\n checkClassInstance(workInProgress, ctor, newProps);\n }\n\n var instance = workInProgress.stateNode;\n instance.props = newProps;\n instance.state = workInProgress.memoizedState;\n instance.refs = emptyRefsObject;\n initializeUpdateQueue(workInProgress);\n var contextType = ctor.contextType;\n\n if (typeof contextType === 'object' && contextType !== null) {\n instance.context = readContext(contextType);\n } else {\n var unmaskedContext = getUnmaskedContext(workInProgress, ctor, true);\n instance.context = getMaskedContext(workInProgress, unmaskedContext);\n }\n\n {\n if (instance.state === newProps) {\n var componentName = getComponentName(ctor) || 'Component';\n\n if (!didWarnAboutDirectlyAssigningPropsToState.has(componentName)) {\n didWarnAboutDirectlyAssigningPropsToState.add(componentName);\n\n error('%s: It is not recommended to assign props directly to state ' + \"because updates to props won't be reflected in state. \" + 'In most cases, it is better to use props directly.', componentName);\n }\n }\n\n if (workInProgress.mode & StrictMode) {\n ReactStrictModeWarnings.recordLegacyContextWarning(workInProgress, instance);\n }\n\n {\n ReactStrictModeWarnings.recordUnsafeLifecycleWarnings(workInProgress, instance);\n }\n }\n\n processUpdateQueue(workInProgress, newProps, instance, renderExpirationTime);\n instance.state = workInProgress.memoizedState;\n var getDerivedStateFromProps = ctor.getDerivedStateFromProps;\n\n if (typeof getDerivedStateFromProps === 'function') {\n applyDerivedStateFromProps(workInProgress, ctor, getDerivedStateFromProps, newProps);\n instance.state = workInProgress.memoizedState;\n } // In order to support react-lifecycles-compat polyfilled components,\n // Unsafe lifecycles should not be invoked for components using the new APIs.\n\n\n if (typeof ctor.getDerivedStateFromProps !== 'function' && typeof instance.getSnapshotBeforeUpdate !== 'function' && (typeof instance.UNSAFE_componentWillMount === 'function' || typeof instance.componentWillMount === 'function')) {\n callComponentWillMount(workInProgress, instance); // If we had additional state updates during this life-cycle, let's\n // process them now.\n\n processUpdateQueue(workInProgress, newProps, instance, renderExpirationTime);\n instance.state = workInProgress.memoizedState;\n }\n\n if (typeof instance.componentDidMount === 'function') {\n workInProgress.effectTag |= Update;\n }\n}\n\nfunction resumeMountClassInstance(workInProgress, ctor, newProps, renderExpirationTime) {\n var instance = workInProgress.stateNode;\n var oldProps = workInProgress.memoizedProps;\n instance.props = oldProps;\n var oldContext = instance.context;\n var contextType = ctor.contextType;\n var nextContext = emptyContextObject;\n\n if (typeof contextType === 'object' && contextType !== null) {\n nextContext = readContext(contextType);\n } else {\n var nextLegacyUnmaskedContext = getUnmaskedContext(workInProgress, ctor, true);\n nextContext = getMaskedContext(workInProgress, nextLegacyUnmaskedContext);\n }\n\n var getDerivedStateFromProps = ctor.getDerivedStateFromProps;\n var hasNewLifecycles = typeof getDerivedStateFromProps === 'function' || typeof instance.getSnapshotBeforeUpdate === 'function'; // Note: During these life-cycles, instance.props/instance.state are what\n // ever the previously attempted to render - not the \"current\". However,\n // during componentDidUpdate we pass the \"current\" props.\n // In order to support react-lifecycles-compat polyfilled components,\n // Unsafe lifecycles should not be invoked for components using the new APIs.\n\n if (!hasNewLifecycles && (typeof instance.UNSAFE_componentWillReceiveProps === 'function' || typeof instance.componentWillReceiveProps === 'function')) {\n if (oldProps !== newProps || oldContext !== nextContext) {\n callComponentWillReceiveProps(workInProgress, instance, newProps, nextContext);\n }\n }\n\n resetHasForceUpdateBeforeProcessing();\n var oldState = workInProgress.memoizedState;\n var newState = instance.state = oldState;\n processUpdateQueue(workInProgress, newProps, instance, renderExpirationTime);\n newState = workInProgress.memoizedState;\n\n if (oldProps === newProps && oldState === newState && !hasContextChanged() && !checkHasForceUpdateAfterProcessing()) {\n // If an update was already in progress, we should schedule an Update\n // effect even though we're bailing out, so that cWU/cDU are called.\n if (typeof instance.componentDidMount === 'function') {\n workInProgress.effectTag |= Update;\n }\n\n return false;\n }\n\n if (typeof getDerivedStateFromProps === 'function') {\n applyDerivedStateFromProps(workInProgress, ctor, getDerivedStateFromProps, newProps);\n newState = workInProgress.memoizedState;\n }\n\n var shouldUpdate = checkHasForceUpdateAfterProcessing() || checkShouldComponentUpdate(workInProgress, ctor, oldProps, newProps, oldState, newState, nextContext);\n\n if (shouldUpdate) {\n // In order to support react-lifecycles-compat polyfilled components,\n // Unsafe lifecycles should not be invoked for components using the new APIs.\n if (!hasNewLifecycles && (typeof instance.UNSAFE_componentWillMount === 'function' || typeof instance.componentWillMount === 'function')) {\n startPhaseTimer(workInProgress, 'componentWillMount');\n\n if (typeof instance.componentWillMount === 'function') {\n instance.componentWillMount();\n }\n\n if (typeof instance.UNSAFE_componentWillMount === 'function') {\n instance.UNSAFE_componentWillMount();\n }\n\n stopPhaseTimer();\n }\n\n if (typeof instance.componentDidMount === 'function') {\n workInProgress.effectTag |= Update;\n }\n } else {\n // If an update was already in progress, we should schedule an Update\n // effect even though we're bailing out, so that cWU/cDU are called.\n if (typeof instance.componentDidMount === 'function') {\n workInProgress.effectTag |= Update;\n } // If shouldComponentUpdate returned false, we should still update the\n // memoized state to indicate that this work can be reused.\n\n\n workInProgress.memoizedProps = newProps;\n workInProgress.memoizedState = newState;\n } // Update the existing instance's state, props, and context pointers even\n // if shouldComponentUpdate returns false.\n\n\n instance.props = newProps;\n instance.state = newState;\n instance.context = nextContext;\n return shouldUpdate;\n} // Invokes the update life-cycles and returns false if it shouldn't rerender.\n\n\nfunction updateClassInstance(current, workInProgress, ctor, newProps, renderExpirationTime) {\n var instance = workInProgress.stateNode;\n cloneUpdateQueue(current, workInProgress);\n var oldProps = workInProgress.memoizedProps;\n instance.props = workInProgress.type === workInProgress.elementType ? oldProps : resolveDefaultProps(workInProgress.type, oldProps);\n var oldContext = instance.context;\n var contextType = ctor.contextType;\n var nextContext = emptyContextObject;\n\n if (typeof contextType === 'object' && contextType !== null) {\n nextContext = readContext(contextType);\n } else {\n var nextUnmaskedContext = getUnmaskedContext(workInProgress, ctor, true);\n nextContext = getMaskedContext(workInProgress, nextUnmaskedContext);\n }\n\n var getDerivedStateFromProps = ctor.getDerivedStateFromProps;\n var hasNewLifecycles = typeof getDerivedStateFromProps === 'function' || typeof instance.getSnapshotBeforeUpdate === 'function'; // Note: During these life-cycles, instance.props/instance.state are what\n // ever the previously attempted to render - not the \"current\". However,\n // during componentDidUpdate we pass the \"current\" props.\n // In order to support react-lifecycles-compat polyfilled components,\n // Unsafe lifecycles should not be invoked for components using the new APIs.\n\n if (!hasNewLifecycles && (typeof instance.UNSAFE_componentWillReceiveProps === 'function' || typeof instance.componentWillReceiveProps === 'function')) {\n if (oldProps !== newProps || oldContext !== nextContext) {\n callComponentWillReceiveProps(workInProgress, instance, newProps, nextContext);\n }\n }\n\n resetHasForceUpdateBeforeProcessing();\n var oldState = workInProgress.memoizedState;\n var newState = instance.state = oldState;\n processUpdateQueue(workInProgress, newProps, instance, renderExpirationTime);\n newState = workInProgress.memoizedState;\n\n if (oldProps === newProps && oldState === newState && !hasContextChanged() && !checkHasForceUpdateAfterProcessing()) {\n // If an update was already in progress, we should schedule an Update\n // effect even though we're bailing out, so that cWU/cDU are called.\n if (typeof instance.componentDidUpdate === 'function') {\n if (oldProps !== current.memoizedProps || oldState !== current.memoizedState) {\n workInProgress.effectTag |= Update;\n }\n }\n\n if (typeof instance.getSnapshotBeforeUpdate === 'function') {\n if (oldProps !== current.memoizedProps || oldState !== current.memoizedState) {\n workInProgress.effectTag |= Snapshot;\n }\n }\n\n return false;\n }\n\n if (typeof getDerivedStateFromProps === 'function') {\n applyDerivedStateFromProps(workInProgress, ctor, getDerivedStateFromProps, newProps);\n newState = workInProgress.memoizedState;\n }\n\n var shouldUpdate = checkHasForceUpdateAfterProcessing() || checkShouldComponentUpdate(workInProgress, ctor, oldProps, newProps, oldState, newState, nextContext);\n\n if (shouldUpdate) {\n // In order to support react-lifecycles-compat polyfilled components,\n // Unsafe lifecycles should not be invoked for components using the new APIs.\n if (!hasNewLifecycles && (typeof instance.UNSAFE_componentWillUpdate === 'function' || typeof instance.componentWillUpdate === 'function')) {\n startPhaseTimer(workInProgress, 'componentWillUpdate');\n\n if (typeof instance.componentWillUpdate === 'function') {\n instance.componentWillUpdate(newProps, newState, nextContext);\n }\n\n if (typeof instance.UNSAFE_componentWillUpdate === 'function') {\n instance.UNSAFE_componentWillUpdate(newProps, newState, nextContext);\n }\n\n stopPhaseTimer();\n }\n\n if (typeof instance.componentDidUpdate === 'function') {\n workInProgress.effectTag |= Update;\n }\n\n if (typeof instance.getSnapshotBeforeUpdate === 'function') {\n workInProgress.effectTag |= Snapshot;\n }\n } else {\n // If an update was already in progress, we should schedule an Update\n // effect even though we're bailing out, so that cWU/cDU are called.\n if (typeof instance.componentDidUpdate === 'function') {\n if (oldProps !== current.memoizedProps || oldState !== current.memoizedState) {\n workInProgress.effectTag |= Update;\n }\n }\n\n if (typeof instance.getSnapshotBeforeUpdate === 'function') {\n if (oldProps !== current.memoizedProps || oldState !== current.memoizedState) {\n workInProgress.effectTag |= Snapshot;\n }\n } // If shouldComponentUpdate returned false, we should still update the\n // memoized props/state to indicate that this work can be reused.\n\n\n workInProgress.memoizedProps = newProps;\n workInProgress.memoizedState = newState;\n } // Update the existing instance's state, props, and context pointers even\n // if shouldComponentUpdate returns false.\n\n\n instance.props = newProps;\n instance.state = newState;\n instance.context = nextContext;\n return shouldUpdate;\n}\n\nvar didWarnAboutMaps;\nvar didWarnAboutGenerators;\nvar didWarnAboutStringRefs;\nvar ownerHasKeyUseWarning;\nvar ownerHasFunctionTypeWarning;\n\nvar warnForMissingKey = function (child) {};\n\n{\n didWarnAboutMaps = false;\n didWarnAboutGenerators = false;\n didWarnAboutStringRefs = {};\n /**\n * Warn if there's no key explicitly set on dynamic arrays of children or\n * object keys are not valid. This allows us to keep track of children between\n * updates.\n */\n\n ownerHasKeyUseWarning = {};\n ownerHasFunctionTypeWarning = {};\n\n warnForMissingKey = function (child) {\n if (child === null || typeof child !== 'object') {\n return;\n }\n\n if (!child._store || child._store.validated || child.key != null) {\n return;\n }\n\n if (!(typeof child._store === 'object')) {\n {\n throw Error( \"React Component in warnForMissingKey should have a _store. This error is likely caused by a bug in React. Please file an issue.\" );\n }\n }\n\n child._store.validated = true;\n var currentComponentErrorInfo = 'Each child in a list should have a unique ' + '\"key\" prop. See https://fb.me/react-warning-keys for ' + 'more information.' + getCurrentFiberStackInDev();\n\n if (ownerHasKeyUseWarning[currentComponentErrorInfo]) {\n return;\n }\n\n ownerHasKeyUseWarning[currentComponentErrorInfo] = true;\n\n error('Each child in a list should have a unique ' + '\"key\" prop. See https://fb.me/react-warning-keys for ' + 'more information.');\n };\n}\n\nvar isArray$1 = Array.isArray;\n\nfunction coerceRef(returnFiber, current, element) {\n var mixedRef = element.ref;\n\n if (mixedRef !== null && typeof mixedRef !== 'function' && typeof mixedRef !== 'object') {\n {\n // TODO: Clean this up once we turn on the string ref warning for\n // everyone, because the strict mode case will no longer be relevant\n if ((returnFiber.mode & StrictMode || warnAboutStringRefs) && // We warn in ReactElement.js if owner and self are equal for string refs\n // because these cannot be automatically converted to an arrow function\n // using a codemod. Therefore, we don't have to warn about string refs again.\n !(element._owner && element._self && element._owner.stateNode !== element._self)) {\n var componentName = getComponentName(returnFiber.type) || 'Component';\n\n if (!didWarnAboutStringRefs[componentName]) {\n {\n error('A string ref, \"%s\", has been found within a strict mode tree. ' + 'String refs are a source of potential bugs and should be avoided. ' + 'We recommend using useRef() or createRef() instead. ' + 'Learn more about using refs safely here: ' + 'https://fb.me/react-strict-mode-string-ref%s', mixedRef, getStackByFiberInDevAndProd(returnFiber));\n }\n\n didWarnAboutStringRefs[componentName] = true;\n }\n }\n }\n\n if (element._owner) {\n var owner = element._owner;\n var inst;\n\n if (owner) {\n var ownerFiber = owner;\n\n if (!(ownerFiber.tag === ClassComponent)) {\n {\n throw Error( \"Function components cannot have string refs. We recommend using useRef() instead. Learn more about using refs safely here: https://fb.me/react-strict-mode-string-ref\" );\n }\n }\n\n inst = ownerFiber.stateNode;\n }\n\n if (!inst) {\n {\n throw Error( \"Missing owner for string ref \" + mixedRef + \". This error is likely caused by a bug in React. Please file an issue.\" );\n }\n }\n\n var stringRef = '' + mixedRef; // Check if previous string ref matches new string ref\n\n if (current !== null && current.ref !== null && typeof current.ref === 'function' && current.ref._stringRef === stringRef) {\n return current.ref;\n }\n\n var ref = function (value) {\n var refs = inst.refs;\n\n if (refs === emptyRefsObject) {\n // This is a lazy pooled frozen object, so we need to initialize.\n refs = inst.refs = {};\n }\n\n if (value === null) {\n delete refs[stringRef];\n } else {\n refs[stringRef] = value;\n }\n };\n\n ref._stringRef = stringRef;\n return ref;\n } else {\n if (!(typeof mixedRef === 'string')) {\n {\n throw Error( \"Expected ref to be a function, a string, an object returned by React.createRef(), or null.\" );\n }\n }\n\n if (!element._owner) {\n {\n throw Error( \"Element ref was specified as a string (\" + mixedRef + \") but no owner was set. This could happen for one of the following reasons:\\n1. You may be adding a ref to a function component\\n2. You may be adding a ref to a component that was not created inside a component's render method\\n3. You have multiple copies of React loaded\\nSee https://fb.me/react-refs-must-have-owner for more information.\" );\n }\n }\n }\n }\n\n return mixedRef;\n}\n\nfunction throwOnInvalidObjectType(returnFiber, newChild) {\n if (returnFiber.type !== 'textarea') {\n var addendum = '';\n\n {\n addendum = ' If you meant to render a collection of children, use an array ' + 'instead.' + getCurrentFiberStackInDev();\n }\n\n {\n {\n throw Error( \"Objects are not valid as a React child (found: \" + (Object.prototype.toString.call(newChild) === '[object Object]' ? 'object with keys {' + Object.keys(newChild).join(', ') + '}' : newChild) + \").\" + addendum );\n }\n }\n }\n}\n\nfunction warnOnFunctionType() {\n {\n var currentComponentErrorInfo = 'Functions are not valid as a React child. This may happen if ' + 'you return a Component instead of <Component /> from render. ' + 'Or maybe you meant to call this function rather than return it.' + getCurrentFiberStackInDev();\n\n if (ownerHasFunctionTypeWarning[currentComponentErrorInfo]) {\n return;\n }\n\n ownerHasFunctionTypeWarning[currentComponentErrorInfo] = true;\n\n error('Functions are not valid as a React child. This may happen if ' + 'you return a Component instead of <Component /> from render. ' + 'Or maybe you meant to call this function rather than return it.');\n }\n} // This wrapper function exists because I expect to clone the code in each path\n// to be able to optimize each path individually by branching early. This needs\n// a compiler or we can do it manually. Helpers that don't need this branching\n// live outside of this function.\n\n\nfunction ChildReconciler(shouldTrackSideEffects) {\n function deleteChild(returnFiber, childToDelete) {\n if (!shouldTrackSideEffects) {\n // Noop.\n return;\n } // Deletions are added in reversed order so we add it to the front.\n // At this point, the return fiber's effect list is empty except for\n // deletions, so we can just append the deletion to the list. The remaining\n // effects aren't added until the complete phase. Once we implement\n // resuming, this may not be true.\n\n\n var last = returnFiber.lastEffect;\n\n if (last !== null) {\n last.nextEffect = childToDelete;\n returnFiber.lastEffect = childToDelete;\n } else {\n returnFiber.firstEffect = returnFiber.lastEffect = childToDelete;\n }\n\n childToDelete.nextEffect = null;\n childToDelete.effectTag = Deletion;\n }\n\n function deleteRemainingChildren(returnFiber, currentFirstChild) {\n if (!shouldTrackSideEffects) {\n // Noop.\n return null;\n } // TODO: For the shouldClone case, this could be micro-optimized a bit by\n // assuming that after the first child we've already added everything.\n\n\n var childToDelete = currentFirstChild;\n\n while (childToDelete !== null) {\n deleteChild(returnFiber, childToDelete);\n childToDelete = childToDelete.sibling;\n }\n\n return null;\n }\n\n function mapRemainingChildren(returnFiber, currentFirstChild) {\n // Add the remaining children to a temporary map so that we can find them by\n // keys quickly. Implicit (null) keys get added to this set with their index\n // instead.\n var existingChildren = new Map();\n var existingChild = currentFirstChild;\n\n while (existingChild !== null) {\n if (existingChild.key !== null) {\n existingChildren.set(existingChild.key, existingChild);\n } else {\n existingChildren.set(existingChild.index, existingChild);\n }\n\n existingChild = existingChild.sibling;\n }\n\n return existingChildren;\n }\n\n function useFiber(fiber, pendingProps) {\n // We currently set sibling to null and index to 0 here because it is easy\n // to forget to do before returning it. E.g. for the single child case.\n var clone = createWorkInProgress(fiber, pendingProps);\n clone.index = 0;\n clone.sibling = null;\n return clone;\n }\n\n function placeChild(newFiber, lastPlacedIndex, newIndex) {\n newFiber.index = newIndex;\n\n if (!shouldTrackSideEffects) {\n // Noop.\n return lastPlacedIndex;\n }\n\n var current = newFiber.alternate;\n\n if (current !== null) {\n var oldIndex = current.index;\n\n if (oldIndex < lastPlacedIndex) {\n // This is a move.\n newFiber.effectTag = Placement;\n return lastPlacedIndex;\n } else {\n // This item can stay in place.\n return oldIndex;\n }\n } else {\n // This is an insertion.\n newFiber.effectTag = Placement;\n return lastPlacedIndex;\n }\n }\n\n function placeSingleChild(newFiber) {\n // This is simpler for the single child case. We only need to do a\n // placement for inserting new children.\n if (shouldTrackSideEffects && newFiber.alternate === null) {\n newFiber.effectTag = Placement;\n }\n\n return newFiber;\n }\n\n function updateTextNode(returnFiber, current, textContent, expirationTime) {\n if (current === null || current.tag !== HostText) {\n // Insert\n var created = createFiberFromText(textContent, returnFiber.mode, expirationTime);\n created.return = returnFiber;\n return created;\n } else {\n // Update\n var existing = useFiber(current, textContent);\n existing.return = returnFiber;\n return existing;\n }\n }\n\n function updateElement(returnFiber, current, element, expirationTime) {\n if (current !== null) {\n if (current.elementType === element.type || ( // Keep this check inline so it only runs on the false path:\n isCompatibleFamilyForHotReloading(current, element) )) {\n // Move based on index\n var existing = useFiber(current, element.props);\n existing.ref = coerceRef(returnFiber, current, element);\n existing.return = returnFiber;\n\n {\n existing._debugSource = element._source;\n existing._debugOwner = element._owner;\n }\n\n return existing;\n }\n } // Insert\n\n\n var created = createFiberFromElement(element, returnFiber.mode, expirationTime);\n created.ref = coerceRef(returnFiber, current, element);\n created.return = returnFiber;\n return created;\n }\n\n function updatePortal(returnFiber, current, portal, expirationTime) {\n if (current === null || current.tag !== HostPortal || current.stateNode.containerInfo !== portal.containerInfo || current.stateNode.implementation !== portal.implementation) {\n // Insert\n var created = createFiberFromPortal(portal, returnFiber.mode, expirationTime);\n created.return = returnFiber;\n return created;\n } else {\n // Update\n var existing = useFiber(current, portal.children || []);\n existing.return = returnFiber;\n return existing;\n }\n }\n\n function updateFragment(returnFiber, current, fragment, expirationTime, key) {\n if (current === null || current.tag !== Fragment) {\n // Insert\n var created = createFiberFromFragment(fragment, returnFiber.mode, expirationTime, key);\n created.return = returnFiber;\n return created;\n } else {\n // Update\n var existing = useFiber(current, fragment);\n existing.return = returnFiber;\n return existing;\n }\n }\n\n function createChild(returnFiber, newChild, expirationTime) {\n if (typeof newChild === 'string' || typeof newChild === 'number') {\n // Text nodes don't have keys. If the previous node is implicitly keyed\n // we can continue to replace it without aborting even if it is not a text\n // node.\n var created = createFiberFromText('' + newChild, returnFiber.mode, expirationTime);\n created.return = returnFiber;\n return created;\n }\n\n if (typeof newChild === 'object' && newChild !== null) {\n switch (newChild.$$typeof) {\n case REACT_ELEMENT_TYPE:\n {\n var _created = createFiberFromElement(newChild, returnFiber.mode, expirationTime);\n\n _created.ref = coerceRef(returnFiber, null, newChild);\n _created.return = returnFiber;\n return _created;\n }\n\n case REACT_PORTAL_TYPE:\n {\n var _created2 = createFiberFromPortal(newChild, returnFiber.mode, expirationTime);\n\n _created2.return = returnFiber;\n return _created2;\n }\n }\n\n if (isArray$1(newChild) || getIteratorFn(newChild)) {\n var _created3 = createFiberFromFragment(newChild, returnFiber.mode, expirationTime, null);\n\n _created3.return = returnFiber;\n return _created3;\n }\n\n throwOnInvalidObjectType(returnFiber, newChild);\n }\n\n {\n if (typeof newChild === 'function') {\n warnOnFunctionType();\n }\n }\n\n return null;\n }\n\n function updateSlot(returnFiber, oldFiber, newChild, expirationTime) {\n // Update the fiber if the keys match, otherwise return null.\n var key = oldFiber !== null ? oldFiber.key : null;\n\n if (typeof newChild === 'string' || typeof newChild === 'number') {\n // Text nodes don't have keys. If the previous node is implicitly keyed\n // we can continue to replace it without aborting even if it is not a text\n // node.\n if (key !== null) {\n return null;\n }\n\n return updateTextNode(returnFiber, oldFiber, '' + newChild, expirationTime);\n }\n\n if (typeof newChild === 'object' && newChild !== null) {\n switch (newChild.$$typeof) {\n case REACT_ELEMENT_TYPE:\n {\n if (newChild.key === key) {\n if (newChild.type === REACT_FRAGMENT_TYPE) {\n return updateFragment(returnFiber, oldFiber, newChild.props.children, expirationTime, key);\n }\n\n return updateElement(returnFiber, oldFiber, newChild, expirationTime);\n } else {\n return null;\n }\n }\n\n case REACT_PORTAL_TYPE:\n {\n if (newChild.key === key) {\n return updatePortal(returnFiber, oldFiber, newChild, expirationTime);\n } else {\n return null;\n }\n }\n }\n\n if (isArray$1(newChild) || getIteratorFn(newChild)) {\n if (key !== null) {\n return null;\n }\n\n return updateFragment(returnFiber, oldFiber, newChild, expirationTime, null);\n }\n\n throwOnInvalidObjectType(returnFiber, newChild);\n }\n\n {\n if (typeof newChild === 'function') {\n warnOnFunctionType();\n }\n }\n\n return null;\n }\n\n function updateFromMap(existingChildren, returnFiber, newIdx, newChild, expirationTime) {\n if (typeof newChild === 'string' || typeof newChild === 'number') {\n // Text nodes don't have keys, so we neither have to check the old nor\n // new node for the key. If both are text nodes, they match.\n var matchedFiber = existingChildren.get(newIdx) || null;\n return updateTextNode(returnFiber, matchedFiber, '' + newChild, expirationTime);\n }\n\n if (typeof newChild === 'object' && newChild !== null) {\n switch (newChild.$$typeof) {\n case REACT_ELEMENT_TYPE:\n {\n var _matchedFiber = existingChildren.get(newChild.key === null ? newIdx : newChild.key) || null;\n\n if (newChild.type === REACT_FRAGMENT_TYPE) {\n return updateFragment(returnFiber, _matchedFiber, newChild.props.children, expirationTime, newChild.key);\n }\n\n return updateElement(returnFiber, _matchedFiber, newChild, expirationTime);\n }\n\n case REACT_PORTAL_TYPE:\n {\n var _matchedFiber2 = existingChildren.get(newChild.key === null ? newIdx : newChild.key) || null;\n\n return updatePortal(returnFiber, _matchedFiber2, newChild, expirationTime);\n }\n }\n\n if (isArray$1(newChild) || getIteratorFn(newChild)) {\n var _matchedFiber3 = existingChildren.get(newIdx) || null;\n\n return updateFragment(returnFiber, _matchedFiber3, newChild, expirationTime, null);\n }\n\n throwOnInvalidObjectType(returnFiber, newChild);\n }\n\n {\n if (typeof newChild === 'function') {\n warnOnFunctionType();\n }\n }\n\n return null;\n }\n /**\n * Warns if there is a duplicate or missing key\n */\n\n\n function warnOnInvalidKey(child, knownKeys) {\n {\n if (typeof child !== 'object' || child === null) {\n return knownKeys;\n }\n\n switch (child.$$typeof) {\n case REACT_ELEMENT_TYPE:\n case REACT_PORTAL_TYPE:\n warnForMissingKey(child);\n var key = child.key;\n\n if (typeof key !== 'string') {\n break;\n }\n\n if (knownKeys === null) {\n knownKeys = new Set();\n knownKeys.add(key);\n break;\n }\n\n if (!knownKeys.has(key)) {\n knownKeys.add(key);\n break;\n }\n\n error('Encountered two children with the same key, `%s`. ' + 'Keys should be unique so that components maintain their identity ' + 'across updates. Non-unique keys may cause children to be ' + 'duplicated and/or omitted — the behavior is unsupported and ' + 'could change in a future version.', key);\n\n break;\n }\n }\n\n return knownKeys;\n }\n\n function reconcileChildrenArray(returnFiber, currentFirstChild, newChildren, expirationTime) {\n // This algorithm can't optimize by searching from both ends since we\n // don't have backpointers on fibers. I'm trying to see how far we can get\n // with that model. If it ends up not being worth the tradeoffs, we can\n // add it later.\n // Even with a two ended optimization, we'd want to optimize for the case\n // where there are few changes and brute force the comparison instead of\n // going for the Map. It'd like to explore hitting that path first in\n // forward-only mode and only go for the Map once we notice that we need\n // lots of look ahead. This doesn't handle reversal as well as two ended\n // search but that's unusual. Besides, for the two ended optimization to\n // work on Iterables, we'd need to copy the whole set.\n // In this first iteration, we'll just live with hitting the bad case\n // (adding everything to a Map) in for every insert/move.\n // If you change this code, also update reconcileChildrenIterator() which\n // uses the same algorithm.\n {\n // First, validate keys.\n var knownKeys = null;\n\n for (var i = 0; i < newChildren.length; i++) {\n var child = newChildren[i];\n knownKeys = warnOnInvalidKey(child, knownKeys);\n }\n }\n\n var resultingFirstChild = null;\n var previousNewFiber = null;\n var oldFiber = currentFirstChild;\n var lastPlacedIndex = 0;\n var newIdx = 0;\n var nextOldFiber = null;\n\n for (; oldFiber !== null && newIdx < newChildren.length; newIdx++) {\n if (oldFiber.index > newIdx) {\n nextOldFiber = oldFiber;\n oldFiber = null;\n } else {\n nextOldFiber = oldFiber.sibling;\n }\n\n var newFiber = updateSlot(returnFiber, oldFiber, newChildren[newIdx], expirationTime);\n\n if (newFiber === null) {\n // TODO: This breaks on empty slots like null children. That's\n // unfortunate because it triggers the slow path all the time. We need\n // a better way to communicate whether this was a miss or null,\n // boolean, undefined, etc.\n if (oldFiber === null) {\n oldFiber = nextOldFiber;\n }\n\n break;\n }\n\n if (shouldTrackSideEffects) {\n if (oldFiber && newFiber.alternate === null) {\n // We matched the slot, but we didn't reuse the existing fiber, so we\n // need to delete the existing child.\n deleteChild(returnFiber, oldFiber);\n }\n }\n\n lastPlacedIndex = placeChild(newFiber, lastPlacedIndex, newIdx);\n\n if (previousNewFiber === null) {\n // TODO: Move out of the loop. This only happens for the first run.\n resultingFirstChild = newFiber;\n } else {\n // TODO: Defer siblings if we're not at the right index for this slot.\n // I.e. if we had null values before, then we want to defer this\n // for each null value. However, we also don't want to call updateSlot\n // with the previous one.\n previousNewFiber.sibling = newFiber;\n }\n\n previousNewFiber = newFiber;\n oldFiber = nextOldFiber;\n }\n\n if (newIdx === newChildren.length) {\n // We've reached the end of the new children. We can delete the rest.\n deleteRemainingChildren(returnFiber, oldFiber);\n return resultingFirstChild;\n }\n\n if (oldFiber === null) {\n // If we don't have any more existing children we can choose a fast path\n // since the rest will all be insertions.\n for (; newIdx < newChildren.length; newIdx++) {\n var _newFiber = createChild(returnFiber, newChildren[newIdx], expirationTime);\n\n if (_newFiber === null) {\n continue;\n }\n\n lastPlacedIndex = placeChild(_newFiber, lastPlacedIndex, newIdx);\n\n if (previousNewFiber === null) {\n // TODO: Move out of the loop. This only happens for the first run.\n resultingFirstChild = _newFiber;\n } else {\n previousNewFiber.sibling = _newFiber;\n }\n\n previousNewFiber = _newFiber;\n }\n\n return resultingFirstChild;\n } // Add all children to a key map for quick lookups.\n\n\n var existingChildren = mapRemainingChildren(returnFiber, oldFiber); // Keep scanning and use the map to restore deleted items as moves.\n\n for (; newIdx < newChildren.length; newIdx++) {\n var _newFiber2 = updateFromMap(existingChildren, returnFiber, newIdx, newChildren[newIdx], expirationTime);\n\n if (_newFiber2 !== null) {\n if (shouldTrackSideEffects) {\n if (_newFiber2.alternate !== null) {\n // The new fiber is a work in progress, but if there exists a\n // current, that means that we reused the fiber. We need to delete\n // it from the child list so that we don't add it to the deletion\n // list.\n existingChildren.delete(_newFiber2.key === null ? newIdx : _newFiber2.key);\n }\n }\n\n lastPlacedIndex = placeChild(_newFiber2, lastPlacedIndex, newIdx);\n\n if (previousNewFiber === null) {\n resultingFirstChild = _newFiber2;\n } else {\n previousNewFiber.sibling = _newFiber2;\n }\n\n previousNewFiber = _newFiber2;\n }\n }\n\n if (shouldTrackSideEffects) {\n // Any existing children that weren't consumed above were deleted. We need\n // to add them to the deletion list.\n existingChildren.forEach(function (child) {\n return deleteChild(returnFiber, child);\n });\n }\n\n return resultingFirstChild;\n }\n\n function reconcileChildrenIterator(returnFiber, currentFirstChild, newChildrenIterable, expirationTime) {\n // This is the same implementation as reconcileChildrenArray(),\n // but using the iterator instead.\n var iteratorFn = getIteratorFn(newChildrenIterable);\n\n if (!(typeof iteratorFn === 'function')) {\n {\n throw Error( \"An object is not an iterable. This error is likely caused by a bug in React. Please file an issue.\" );\n }\n }\n\n {\n // We don't support rendering Generators because it's a mutation.\n // See https://github.com/facebook/react/issues/12995\n if (typeof Symbol === 'function' && // $FlowFixMe Flow doesn't know about toStringTag\n newChildrenIterable[Symbol.toStringTag] === 'Generator') {\n if (!didWarnAboutGenerators) {\n error('Using Generators as children is unsupported and will likely yield ' + 'unexpected results because enumerating a generator mutates it. ' + 'You may convert it to an array with `Array.from()` or the ' + '`[...spread]` operator before rendering. Keep in mind ' + 'you might need to polyfill these features for older browsers.');\n }\n\n didWarnAboutGenerators = true;\n } // Warn about using Maps as children\n\n\n if (newChildrenIterable.entries === iteratorFn) {\n if (!didWarnAboutMaps) {\n error('Using Maps as children is unsupported and will likely yield ' + 'unexpected results. Convert it to a sequence/iterable of keyed ' + 'ReactElements instead.');\n }\n\n didWarnAboutMaps = true;\n } // First, validate keys.\n // We'll get a different iterator later for the main pass.\n\n\n var _newChildren = iteratorFn.call(newChildrenIterable);\n\n if (_newChildren) {\n var knownKeys = null;\n\n var _step = _newChildren.next();\n\n for (; !_step.done; _step = _newChildren.next()) {\n var child = _step.value;\n knownKeys = warnOnInvalidKey(child, knownKeys);\n }\n }\n }\n\n var newChildren = iteratorFn.call(newChildrenIterable);\n\n if (!(newChildren != null)) {\n {\n throw Error( \"An iterable object provided no iterator.\" );\n }\n }\n\n var resultingFirstChild = null;\n var previousNewFiber = null;\n var oldFiber = currentFirstChild;\n var lastPlacedIndex = 0;\n var newIdx = 0;\n var nextOldFiber = null;\n var step = newChildren.next();\n\n for (; oldFiber !== null && !step.done; newIdx++, step = newChildren.next()) {\n if (oldFiber.index > newIdx) {\n nextOldFiber = oldFiber;\n oldFiber = null;\n } else {\n nextOldFiber = oldFiber.sibling;\n }\n\n var newFiber = updateSlot(returnFiber, oldFiber, step.value, expirationTime);\n\n if (newFiber === null) {\n // TODO: This breaks on empty slots like null children. That's\n // unfortunate because it triggers the slow path all the time. We need\n // a better way to communicate whether this was a miss or null,\n // boolean, undefined, etc.\n if (oldFiber === null) {\n oldFiber = nextOldFiber;\n }\n\n break;\n }\n\n if (shouldTrackSideEffects) {\n if (oldFiber && newFiber.alternate === null) {\n // We matched the slot, but we didn't reuse the existing fiber, so we\n // need to delete the existing child.\n deleteChild(returnFiber, oldFiber);\n }\n }\n\n lastPlacedIndex = placeChild(newFiber, lastPlacedIndex, newIdx);\n\n if (previousNewFiber === null) {\n // TODO: Move out of the loop. This only happens for the first run.\n resultingFirstChild = newFiber;\n } else {\n // TODO: Defer siblings if we're not at the right index for this slot.\n // I.e. if we had null values before, then we want to defer this\n // for each null value. However, we also don't want to call updateSlot\n // with the previous one.\n previousNewFiber.sibling = newFiber;\n }\n\n previousNewFiber = newFiber;\n oldFiber = nextOldFiber;\n }\n\n if (step.done) {\n // We've reached the end of the new children. We can delete the rest.\n deleteRemainingChildren(returnFiber, oldFiber);\n return resultingFirstChild;\n }\n\n if (oldFiber === null) {\n // If we don't have any more existing children we can choose a fast path\n // since the rest will all be insertions.\n for (; !step.done; newIdx++, step = newChildren.next()) {\n var _newFiber3 = createChild(returnFiber, step.value, expirationTime);\n\n if (_newFiber3 === null) {\n continue;\n }\n\n lastPlacedIndex = placeChild(_newFiber3, lastPlacedIndex, newIdx);\n\n if (previousNewFiber === null) {\n // TODO: Move out of the loop. This only happens for the first run.\n resultingFirstChild = _newFiber3;\n } else {\n previousNewFiber.sibling = _newFiber3;\n }\n\n previousNewFiber = _newFiber3;\n }\n\n return resultingFirstChild;\n } // Add all children to a key map for quick lookups.\n\n\n var existingChildren = mapRemainingChildren(returnFiber, oldFiber); // Keep scanning and use the map to restore deleted items as moves.\n\n for (; !step.done; newIdx++, step = newChildren.next()) {\n var _newFiber4 = updateFromMap(existingChildren, returnFiber, newIdx, step.value, expirationTime);\n\n if (_newFiber4 !== null) {\n if (shouldTrackSideEffects) {\n if (_newFiber4.alternate !== null) {\n // The new fiber is a work in progress, but if there exists a\n // current, that means that we reused the fiber. We need to delete\n // it from the child list so that we don't add it to the deletion\n // list.\n existingChildren.delete(_newFiber4.key === null ? newIdx : _newFiber4.key);\n }\n }\n\n lastPlacedIndex = placeChild(_newFiber4, lastPlacedIndex, newIdx);\n\n if (previousNewFiber === null) {\n resultingFirstChild = _newFiber4;\n } else {\n previousNewFiber.sibling = _newFiber4;\n }\n\n previousNewFiber = _newFiber4;\n }\n }\n\n if (shouldTrackSideEffects) {\n // Any existing children that weren't consumed above were deleted. We need\n // to add them to the deletion list.\n existingChildren.forEach(function (child) {\n return deleteChild(returnFiber, child);\n });\n }\n\n return resultingFirstChild;\n }\n\n function reconcileSingleTextNode(returnFiber, currentFirstChild, textContent, expirationTime) {\n // There's no need to check for keys on text nodes since we don't have a\n // way to define them.\n if (currentFirstChild !== null && currentFirstChild.tag === HostText) {\n // We already have an existing node so let's just update it and delete\n // the rest.\n deleteRemainingChildren(returnFiber, currentFirstChild.sibling);\n var existing = useFiber(currentFirstChild, textContent);\n existing.return = returnFiber;\n return existing;\n } // The existing first child is not a text node so we need to create one\n // and delete the existing ones.\n\n\n deleteRemainingChildren(returnFiber, currentFirstChild);\n var created = createFiberFromText(textContent, returnFiber.mode, expirationTime);\n created.return = returnFiber;\n return created;\n }\n\n function reconcileSingleElement(returnFiber, currentFirstChild, element, expirationTime) {\n var key = element.key;\n var child = currentFirstChild;\n\n while (child !== null) {\n // TODO: If key === null and child.key === null, then this only applies to\n // the first item in the list.\n if (child.key === key) {\n switch (child.tag) {\n case Fragment:\n {\n if (element.type === REACT_FRAGMENT_TYPE) {\n deleteRemainingChildren(returnFiber, child.sibling);\n var existing = useFiber(child, element.props.children);\n existing.return = returnFiber;\n\n {\n existing._debugSource = element._source;\n existing._debugOwner = element._owner;\n }\n\n return existing;\n }\n\n break;\n }\n\n case Block:\n\n // We intentionally fallthrough here if enableBlocksAPI is not on.\n // eslint-disable-next-lined no-fallthrough\n\n default:\n {\n if (child.elementType === element.type || ( // Keep this check inline so it only runs on the false path:\n isCompatibleFamilyForHotReloading(child, element) )) {\n deleteRemainingChildren(returnFiber, child.sibling);\n\n var _existing3 = useFiber(child, element.props);\n\n _existing3.ref = coerceRef(returnFiber, child, element);\n _existing3.return = returnFiber;\n\n {\n _existing3._debugSource = element._source;\n _existing3._debugOwner = element._owner;\n }\n\n return _existing3;\n }\n\n break;\n }\n } // Didn't match.\n\n\n deleteRemainingChildren(returnFiber, child);\n break;\n } else {\n deleteChild(returnFiber, child);\n }\n\n child = child.sibling;\n }\n\n if (element.type === REACT_FRAGMENT_TYPE) {\n var created = createFiberFromFragment(element.props.children, returnFiber.mode, expirationTime, element.key);\n created.return = returnFiber;\n return created;\n } else {\n var _created4 = createFiberFromElement(element, returnFiber.mode, expirationTime);\n\n _created4.ref = coerceRef(returnFiber, currentFirstChild, element);\n _created4.return = returnFiber;\n return _created4;\n }\n }\n\n function reconcileSinglePortal(returnFiber, currentFirstChild, portal, expirationTime) {\n var key = portal.key;\n var child = currentFirstChild;\n\n while (child !== null) {\n // TODO: If key === null and child.key === null, then this only applies to\n // the first item in the list.\n if (child.key === key) {\n if (child.tag === HostPortal && child.stateNode.containerInfo === portal.containerInfo && child.stateNode.implementation === portal.implementation) {\n deleteRemainingChildren(returnFiber, child.sibling);\n var existing = useFiber(child, portal.children || []);\n existing.return = returnFiber;\n return existing;\n } else {\n deleteRemainingChildren(returnFiber, child);\n break;\n }\n } else {\n deleteChild(returnFiber, child);\n }\n\n child = child.sibling;\n }\n\n var created = createFiberFromPortal(portal, returnFiber.mode, expirationTime);\n created.return = returnFiber;\n return created;\n } // This API will tag the children with the side-effect of the reconciliation\n // itself. They will be added to the side-effect list as we pass through the\n // children and the parent.\n\n\n function reconcileChildFibers(returnFiber, currentFirstChild, newChild, expirationTime) {\n // This function is not recursive.\n // If the top level item is an array, we treat it as a set of children,\n // not as a fragment. Nested arrays on the other hand will be treated as\n // fragment nodes. Recursion happens at the normal flow.\n // Handle top level unkeyed fragments as if they were arrays.\n // This leads to an ambiguity between <>{[...]}</> and <>...</>.\n // We treat the ambiguous cases above the same.\n var isUnkeyedTopLevelFragment = typeof newChild === 'object' && newChild !== null && newChild.type === REACT_FRAGMENT_TYPE && newChild.key === null;\n\n if (isUnkeyedTopLevelFragment) {\n newChild = newChild.props.children;\n } // Handle object types\n\n\n var isObject = typeof newChild === 'object' && newChild !== null;\n\n if (isObject) {\n switch (newChild.$$typeof) {\n case REACT_ELEMENT_TYPE:\n return placeSingleChild(reconcileSingleElement(returnFiber, currentFirstChild, newChild, expirationTime));\n\n case REACT_PORTAL_TYPE:\n return placeSingleChild(reconcileSinglePortal(returnFiber, currentFirstChild, newChild, expirationTime));\n }\n }\n\n if (typeof newChild === 'string' || typeof newChild === 'number') {\n return placeSingleChild(reconcileSingleTextNode(returnFiber, currentFirstChild, '' + newChild, expirationTime));\n }\n\n if (isArray$1(newChild)) {\n return reconcileChildrenArray(returnFiber, currentFirstChild, newChild, expirationTime);\n }\n\n if (getIteratorFn(newChild)) {\n return reconcileChildrenIterator(returnFiber, currentFirstChild, newChild, expirationTime);\n }\n\n if (isObject) {\n throwOnInvalidObjectType(returnFiber, newChild);\n }\n\n {\n if (typeof newChild === 'function') {\n warnOnFunctionType();\n }\n }\n\n if (typeof newChild === 'undefined' && !isUnkeyedTopLevelFragment) {\n // If the new child is undefined, and the return fiber is a composite\n // component, throw an error. If Fiber return types are disabled,\n // we already threw above.\n switch (returnFiber.tag) {\n case ClassComponent:\n {\n {\n var instance = returnFiber.stateNode;\n\n if (instance.render._isMockFunction) {\n // We allow auto-mocks to proceed as if they're returning null.\n break;\n }\n }\n }\n // Intentionally fall through to the next case, which handles both\n // functions and classes\n // eslint-disable-next-lined no-fallthrough\n\n case FunctionComponent:\n {\n var Component = returnFiber.type;\n\n {\n {\n throw Error( (Component.displayName || Component.name || 'Component') + \"(...): Nothing was returned from render. This usually means a return statement is missing. Or, to render nothing, return null.\" );\n }\n }\n }\n }\n } // Remaining cases are all treated as empty.\n\n\n return deleteRemainingChildren(returnFiber, currentFirstChild);\n }\n\n return reconcileChildFibers;\n}\n\nvar reconcileChildFibers = ChildReconciler(true);\nvar mountChildFibers = ChildReconciler(false);\nfunction cloneChildFibers(current, workInProgress) {\n if (!(current === null || workInProgress.child === current.child)) {\n {\n throw Error( \"Resuming work not yet implemented.\" );\n }\n }\n\n if (workInProgress.child === null) {\n return;\n }\n\n var currentChild = workInProgress.child;\n var newChild = createWorkInProgress(currentChild, currentChild.pendingProps);\n workInProgress.child = newChild;\n newChild.return = workInProgress;\n\n while (currentChild.sibling !== null) {\n currentChild = currentChild.sibling;\n newChild = newChild.sibling = createWorkInProgress(currentChild, currentChild.pendingProps);\n newChild.return = workInProgress;\n }\n\n newChild.sibling = null;\n} // Reset a workInProgress child set to prepare it for a second pass.\n\nfunction resetChildFibers(workInProgress, renderExpirationTime) {\n var child = workInProgress.child;\n\n while (child !== null) {\n resetWorkInProgress(child, renderExpirationTime);\n child = child.sibling;\n }\n}\n\nvar NO_CONTEXT = {};\nvar contextStackCursor$1 = createCursor(NO_CONTEXT);\nvar contextFiberStackCursor = createCursor(NO_CONTEXT);\nvar rootInstanceStackCursor = createCursor(NO_CONTEXT);\n\nfunction requiredContext(c) {\n if (!(c !== NO_CONTEXT)) {\n {\n throw Error( \"Expected host context to exist. This error is likely caused by a bug in React. Please file an issue.\" );\n }\n }\n\n return c;\n}\n\nfunction getRootHostContainer() {\n var rootInstance = requiredContext(rootInstanceStackCursor.current);\n return rootInstance;\n}\n\nfunction pushHostContainer(fiber, nextRootInstance) {\n // Push current root instance onto the stack;\n // This allows us to reset root when portals are popped.\n push(rootInstanceStackCursor, nextRootInstance, fiber); // Track the context and the Fiber that provided it.\n // This enables us to pop only Fibers that provide unique contexts.\n\n push(contextFiberStackCursor, fiber, fiber); // Finally, we need to push the host context to the stack.\n // However, we can't just call getRootHostContext() and push it because\n // we'd have a different number of entries on the stack depending on\n // whether getRootHostContext() throws somewhere in renderer code or not.\n // So we push an empty value first. This lets us safely unwind on errors.\n\n push(contextStackCursor$1, NO_CONTEXT, fiber);\n var nextRootContext = getRootHostContext(nextRootInstance); // Now that we know this function doesn't throw, replace it.\n\n pop(contextStackCursor$1, fiber);\n push(contextStackCursor$1, nextRootContext, fiber);\n}\n\nfunction popHostContainer(fiber) {\n pop(contextStackCursor$1, fiber);\n pop(contextFiberStackCursor, fiber);\n pop(rootInstanceStackCursor, fiber);\n}\n\nfunction getHostContext() {\n var context = requiredContext(contextStackCursor$1.current);\n return context;\n}\n\nfunction pushHostContext(fiber) {\n var rootInstance = requiredContext(rootInstanceStackCursor.current);\n var context = requiredContext(contextStackCursor$1.current);\n var nextContext = getChildHostContext(context, fiber.type); // Don't push this Fiber's context unless it's unique.\n\n if (context === nextContext) {\n return;\n } // Track the context and the Fiber that provided it.\n // This enables us to pop only Fibers that provide unique contexts.\n\n\n push(contextFiberStackCursor, fiber, fiber);\n push(contextStackCursor$1, nextContext, fiber);\n}\n\nfunction popHostContext(fiber) {\n // Do not pop unless this Fiber provided the current context.\n // pushHostContext() only pushes Fibers that provide unique contexts.\n if (contextFiberStackCursor.current !== fiber) {\n return;\n }\n\n pop(contextStackCursor$1, fiber);\n pop(contextFiberStackCursor, fiber);\n}\n\nvar DefaultSuspenseContext = 0; // The Suspense Context is split into two parts. The lower bits is\n// inherited deeply down the subtree. The upper bits only affect\n// this immediate suspense boundary and gets reset each new\n// boundary or suspense list.\n\nvar SubtreeSuspenseContextMask = 1; // Subtree Flags:\n// InvisibleParentSuspenseContext indicates that one of our parent Suspense\n// boundaries is not currently showing visible main content.\n// Either because it is already showing a fallback or is not mounted at all.\n// We can use this to determine if it is desirable to trigger a fallback at\n// the parent. If not, then we might need to trigger undesirable boundaries\n// and/or suspend the commit to avoid hiding the parent content.\n\nvar InvisibleParentSuspenseContext = 1; // Shallow Flags:\n// ForceSuspenseFallback can be used by SuspenseList to force newly added\n// items into their fallback state during one of the render passes.\n\nvar ForceSuspenseFallback = 2;\nvar suspenseStackCursor = createCursor(DefaultSuspenseContext);\nfunction hasSuspenseContext(parentContext, flag) {\n return (parentContext & flag) !== 0;\n}\nfunction setDefaultShallowSuspenseContext(parentContext) {\n return parentContext & SubtreeSuspenseContextMask;\n}\nfunction setShallowSuspenseContext(parentContext, shallowContext) {\n return parentContext & SubtreeSuspenseContextMask | shallowContext;\n}\nfunction addSubtreeSuspenseContext(parentContext, subtreeContext) {\n return parentContext | subtreeContext;\n}\nfunction pushSuspenseContext(fiber, newContext) {\n push(suspenseStackCursor, newContext, fiber);\n}\nfunction popSuspenseContext(fiber) {\n pop(suspenseStackCursor, fiber);\n}\n\nfunction shouldCaptureSuspense(workInProgress, hasInvisibleParent) {\n // If it was the primary children that just suspended, capture and render the\n // fallback. Otherwise, don't capture and bubble to the next boundary.\n var nextState = workInProgress.memoizedState;\n\n if (nextState !== null) {\n if (nextState.dehydrated !== null) {\n // A dehydrated boundary always captures.\n return true;\n }\n\n return false;\n }\n\n var props = workInProgress.memoizedProps; // In order to capture, the Suspense component must have a fallback prop.\n\n if (props.fallback === undefined) {\n return false;\n } // Regular boundaries always capture.\n\n\n if (props.unstable_avoidThisFallback !== true) {\n return true;\n } // If it's a boundary we should avoid, then we prefer to bubble up to the\n // parent boundary if it is currently invisible.\n\n\n if (hasInvisibleParent) {\n return false;\n } // If the parent is not able to handle it, we must handle it.\n\n\n return true;\n}\nfunction findFirstSuspended(row) {\n var node = row;\n\n while (node !== null) {\n if (node.tag === SuspenseComponent) {\n var state = node.memoizedState;\n\n if (state !== null) {\n var dehydrated = state.dehydrated;\n\n if (dehydrated === null || isSuspenseInstancePending(dehydrated) || isSuspenseInstanceFallback(dehydrated)) {\n return node;\n }\n }\n } else if (node.tag === SuspenseListComponent && // revealOrder undefined can't be trusted because it don't\n // keep track of whether it suspended or not.\n node.memoizedProps.revealOrder !== undefined) {\n var didSuspend = (node.effectTag & DidCapture) !== NoEffect;\n\n if (didSuspend) {\n return node;\n }\n } else if (node.child !== null) {\n node.child.return = node;\n node = node.child;\n continue;\n }\n\n if (node === row) {\n return null;\n }\n\n while (node.sibling === null) {\n if (node.return === null || node.return === row) {\n return null;\n }\n\n node = node.return;\n }\n\n node.sibling.return = node.return;\n node = node.sibling;\n }\n\n return null;\n}\n\nfunction createDeprecatedResponderListener(responder, props) {\n var eventResponderListener = {\n responder: responder,\n props: props\n };\n\n {\n Object.freeze(eventResponderListener);\n }\n\n return eventResponderListener;\n}\n\nvar HasEffect =\n/* */\n1; // Represents the phase in which the effect (not the clean-up) fires.\n\nvar Layout =\n/* */\n2;\nvar Passive$1 =\n/* */\n4;\n\nvar ReactCurrentDispatcher = ReactSharedInternals.ReactCurrentDispatcher,\n ReactCurrentBatchConfig$1 = ReactSharedInternals.ReactCurrentBatchConfig;\nvar didWarnAboutMismatchedHooksForComponent;\n\n{\n didWarnAboutMismatchedHooksForComponent = new Set();\n}\n\n// These are set right before calling the component.\nvar renderExpirationTime = NoWork; // The work-in-progress fiber. I've named it differently to distinguish it from\n// the work-in-progress hook.\n\nvar currentlyRenderingFiber$1 = null; // Hooks are stored as a linked list on the fiber's memoizedState field. The\n// current hook list is the list that belongs to the current fiber. The\n// work-in-progress hook list is a new list that will be added to the\n// work-in-progress fiber.\n\nvar currentHook = null;\nvar workInProgressHook = null; // Whether an update was scheduled at any point during the render phase. This\n// does not get reset if we do another render pass; only when we're completely\n// finished evaluating this component. This is an optimization so we know\n// whether we need to clear render phase updates after a throw.\n\nvar didScheduleRenderPhaseUpdate = false;\nvar RE_RENDER_LIMIT = 25; // In DEV, this is the name of the currently executing primitive hook\n\nvar currentHookNameInDev = null; // In DEV, this list ensures that hooks are called in the same order between renders.\n// The list stores the order of hooks used during the initial render (mount).\n// Subsequent renders (updates) reference this list.\n\nvar hookTypesDev = null;\nvar hookTypesUpdateIndexDev = -1; // In DEV, this tracks whether currently rendering component needs to ignore\n// the dependencies for Hooks that need them (e.g. useEffect or useMemo).\n// When true, such Hooks will always be \"remounted\". Only used during hot reload.\n\nvar ignorePreviousDependencies = false;\n\nfunction mountHookTypesDev() {\n {\n var hookName = currentHookNameInDev;\n\n if (hookTypesDev === null) {\n hookTypesDev = [hookName];\n } else {\n hookTypesDev.push(hookName);\n }\n }\n}\n\nfunction updateHookTypesDev() {\n {\n var hookName = currentHookNameInDev;\n\n if (hookTypesDev !== null) {\n hookTypesUpdateIndexDev++;\n\n if (hookTypesDev[hookTypesUpdateIndexDev] !== hookName) {\n warnOnHookMismatchInDev(hookName);\n }\n }\n }\n}\n\nfunction checkDepsAreArrayDev(deps) {\n {\n if (deps !== undefined && deps !== null && !Array.isArray(deps)) {\n // Verify deps, but only on mount to avoid extra checks.\n // It's unlikely their type would change as usually you define them inline.\n error('%s received a final argument that is not an array (instead, received `%s`). When ' + 'specified, the final argument must be an array.', currentHookNameInDev, typeof deps);\n }\n }\n}\n\nfunction warnOnHookMismatchInDev(currentHookName) {\n {\n var componentName = getComponentName(currentlyRenderingFiber$1.type);\n\n if (!didWarnAboutMismatchedHooksForComponent.has(componentName)) {\n didWarnAboutMismatchedHooksForComponent.add(componentName);\n\n if (hookTypesDev !== null) {\n var table = '';\n var secondColumnStart = 30;\n\n for (var i = 0; i <= hookTypesUpdateIndexDev; i++) {\n var oldHookName = hookTypesDev[i];\n var newHookName = i === hookTypesUpdateIndexDev ? currentHookName : oldHookName;\n var row = i + 1 + \". \" + oldHookName; // Extra space so second column lines up\n // lol @ IE not supporting String#repeat\n\n while (row.length < secondColumnStart) {\n row += ' ';\n }\n\n row += newHookName + '\\n';\n table += row;\n }\n\n error('React has detected a change in the order of Hooks called by %s. ' + 'This will lead to bugs and errors if not fixed. ' + 'For more information, read the Rules of Hooks: https://fb.me/rules-of-hooks\\n\\n' + ' Previous render Next render\\n' + ' ------------------------------------------------------\\n' + '%s' + ' ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\\n', componentName, table);\n }\n }\n }\n}\n\nfunction throwInvalidHookError() {\n {\n {\n throw Error( \"Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:\\n1. You might have mismatching versions of React and the renderer (such as React DOM)\\n2. You might be breaking the Rules of Hooks\\n3. You might have more than one copy of React in the same app\\nSee https://fb.me/react-invalid-hook-call for tips about how to debug and fix this problem.\" );\n }\n }\n}\n\nfunction areHookInputsEqual(nextDeps, prevDeps) {\n {\n if (ignorePreviousDependencies) {\n // Only true when this component is being hot reloaded.\n return false;\n }\n }\n\n if (prevDeps === null) {\n {\n error('%s received a final argument during this render, but not during ' + 'the previous render. Even though the final argument is optional, ' + 'its type cannot change between renders.', currentHookNameInDev);\n }\n\n return false;\n }\n\n {\n // Don't bother comparing lengths in prod because these arrays should be\n // passed inline.\n if (nextDeps.length !== prevDeps.length) {\n error('The final argument passed to %s changed size between renders. The ' + 'order and size of this array must remain constant.\\n\\n' + 'Previous: %s\\n' + 'Incoming: %s', currentHookNameInDev, \"[\" + prevDeps.join(', ') + \"]\", \"[\" + nextDeps.join(', ') + \"]\");\n }\n }\n\n for (var i = 0; i < prevDeps.length && i < nextDeps.length; i++) {\n if (objectIs(nextDeps[i], prevDeps[i])) {\n continue;\n }\n\n return false;\n }\n\n return true;\n}\n\nfunction renderWithHooks(current, workInProgress, Component, props, secondArg, nextRenderExpirationTime) {\n renderExpirationTime = nextRenderExpirationTime;\n currentlyRenderingFiber$1 = workInProgress;\n\n {\n hookTypesDev = current !== null ? current._debugHookTypes : null;\n hookTypesUpdateIndexDev = -1; // Used for hot reloading:\n\n ignorePreviousDependencies = current !== null && current.type !== workInProgress.type;\n }\n\n workInProgress.memoizedState = null;\n workInProgress.updateQueue = null;\n workInProgress.expirationTime = NoWork; // The following should have already been reset\n // currentHook = null;\n // workInProgressHook = null;\n // didScheduleRenderPhaseUpdate = false;\n // TODO Warn if no hooks are used at all during mount, then some are used during update.\n // Currently we will identify the update render as a mount because memoizedState === null.\n // This is tricky because it's valid for certain types of components (e.g. React.lazy)\n // Using memoizedState to differentiate between mount/update only works if at least one stateful hook is used.\n // Non-stateful hooks (e.g. context) don't get added to memoizedState,\n // so memoizedState would be null during updates and mounts.\n\n {\n if (current !== null && current.memoizedState !== null) {\n ReactCurrentDispatcher.current = HooksDispatcherOnUpdateInDEV;\n } else if (hookTypesDev !== null) {\n // This dispatcher handles an edge case where a component is updating,\n // but no stateful hooks have been used.\n // We want to match the production code behavior (which will use HooksDispatcherOnMount),\n // but with the extra DEV validation to ensure hooks ordering hasn't changed.\n // This dispatcher does that.\n ReactCurrentDispatcher.current = HooksDispatcherOnMountWithHookTypesInDEV;\n } else {\n ReactCurrentDispatcher.current = HooksDispatcherOnMountInDEV;\n }\n }\n\n var children = Component(props, secondArg); // Check if there was a render phase update\n\n if (workInProgress.expirationTime === renderExpirationTime) {\n // Keep rendering in a loop for as long as render phase updates continue to\n // be scheduled. Use a counter to prevent infinite loops.\n var numberOfReRenders = 0;\n\n do {\n workInProgress.expirationTime = NoWork;\n\n if (!(numberOfReRenders < RE_RENDER_LIMIT)) {\n {\n throw Error( \"Too many re-renders. React limits the number of renders to prevent an infinite loop.\" );\n }\n }\n\n numberOfReRenders += 1;\n\n {\n // Even when hot reloading, allow dependencies to stabilize\n // after first render to prevent infinite render phase updates.\n ignorePreviousDependencies = false;\n } // Start over from the beginning of the list\n\n\n currentHook = null;\n workInProgressHook = null;\n workInProgress.updateQueue = null;\n\n {\n // Also validate hook order for cascading updates.\n hookTypesUpdateIndexDev = -1;\n }\n\n ReactCurrentDispatcher.current = HooksDispatcherOnRerenderInDEV ;\n children = Component(props, secondArg);\n } while (workInProgress.expirationTime === renderExpirationTime);\n } // We can assume the previous dispatcher is always this one, since we set it\n // at the beginning of the render phase and there's no re-entrancy.\n\n\n ReactCurrentDispatcher.current = ContextOnlyDispatcher;\n\n {\n workInProgress._debugHookTypes = hookTypesDev;\n } // This check uses currentHook so that it works the same in DEV and prod bundles.\n // hookTypesDev could catch more cases (e.g. context) but only in DEV bundles.\n\n\n var didRenderTooFewHooks = currentHook !== null && currentHook.next !== null;\n renderExpirationTime = NoWork;\n currentlyRenderingFiber$1 = null;\n currentHook = null;\n workInProgressHook = null;\n\n {\n currentHookNameInDev = null;\n hookTypesDev = null;\n hookTypesUpdateIndexDev = -1;\n }\n\n didScheduleRenderPhaseUpdate = false;\n\n if (!!didRenderTooFewHooks) {\n {\n throw Error( \"Rendered fewer hooks than expected. This may be caused by an accidental early return statement.\" );\n }\n }\n\n return children;\n}\nfunction bailoutHooks(current, workInProgress, expirationTime) {\n workInProgress.updateQueue = current.updateQueue;\n workInProgress.effectTag &= ~(Passive | Update);\n\n if (current.expirationTime <= expirationTime) {\n current.expirationTime = NoWork;\n }\n}\nfunction resetHooksAfterThrow() {\n // We can assume the previous dispatcher is always this one, since we set it\n // at the beginning of the render phase and there's no re-entrancy.\n ReactCurrentDispatcher.current = ContextOnlyDispatcher;\n\n if (didScheduleRenderPhaseUpdate) {\n // There were render phase updates. These are only valid for this render\n // phase, which we are now aborting. Remove the updates from the queues so\n // they do not persist to the next render. Do not remove updates from hooks\n // that weren't processed.\n //\n // Only reset the updates from the queue if it has a clone. If it does\n // not have a clone, that means it wasn't processed, and the updates were\n // scheduled before we entered the render phase.\n var hook = currentlyRenderingFiber$1.memoizedState;\n\n while (hook !== null) {\n var queue = hook.queue;\n\n if (queue !== null) {\n queue.pending = null;\n }\n\n hook = hook.next;\n }\n }\n\n renderExpirationTime = NoWork;\n currentlyRenderingFiber$1 = null;\n currentHook = null;\n workInProgressHook = null;\n\n {\n hookTypesDev = null;\n hookTypesUpdateIndexDev = -1;\n currentHookNameInDev = null;\n }\n\n didScheduleRenderPhaseUpdate = false;\n}\n\nfunction mountWorkInProgressHook() {\n var hook = {\n memoizedState: null,\n baseState: null,\n baseQueue: null,\n queue: null,\n next: null\n };\n\n if (workInProgressHook === null) {\n // This is the first hook in the list\n currentlyRenderingFiber$1.memoizedState = workInProgressHook = hook;\n } else {\n // Append to the end of the list\n workInProgressHook = workInProgressHook.next = hook;\n }\n\n return workInProgressHook;\n}\n\nfunction updateWorkInProgressHook() {\n // This function is used both for updates and for re-renders triggered by a\n // render phase update. It assumes there is either a current hook we can\n // clone, or a work-in-progress hook from a previous render pass that we can\n // use as a base. When we reach the end of the base list, we must switch to\n // the dispatcher used for mounts.\n var nextCurrentHook;\n\n if (currentHook === null) {\n var current = currentlyRenderingFiber$1.alternate;\n\n if (current !== null) {\n nextCurrentHook = current.memoizedState;\n } else {\n nextCurrentHook = null;\n }\n } else {\n nextCurrentHook = currentHook.next;\n }\n\n var nextWorkInProgressHook;\n\n if (workInProgressHook === null) {\n nextWorkInProgressHook = currentlyRenderingFiber$1.memoizedState;\n } else {\n nextWorkInProgressHook = workInProgressHook.next;\n }\n\n if (nextWorkInProgressHook !== null) {\n // There's already a work-in-progress. Reuse it.\n workInProgressHook = nextWorkInProgressHook;\n nextWorkInProgressHook = workInProgressHook.next;\n currentHook = nextCurrentHook;\n } else {\n // Clone from the current hook.\n if (!(nextCurrentHook !== null)) {\n {\n throw Error( \"Rendered more hooks than during the previous render.\" );\n }\n }\n\n currentHook = nextCurrentHook;\n var newHook = {\n memoizedState: currentHook.memoizedState,\n baseState: currentHook.baseState,\n baseQueue: currentHook.baseQueue,\n queue: currentHook.queue,\n next: null\n };\n\n if (workInProgressHook === null) {\n // This is the first hook in the list.\n currentlyRenderingFiber$1.memoizedState = workInProgressHook = newHook;\n } else {\n // Append to the end of the list.\n workInProgressHook = workInProgressHook.next = newHook;\n }\n }\n\n return workInProgressHook;\n}\n\nfunction createFunctionComponentUpdateQueue() {\n return {\n lastEffect: null\n };\n}\n\nfunction basicStateReducer(state, action) {\n // $FlowFixMe: Flow doesn't like mixed types\n return typeof action === 'function' ? action(state) : action;\n}\n\nfunction mountReducer(reducer, initialArg, init) {\n var hook = mountWorkInProgressHook();\n var initialState;\n\n if (init !== undefined) {\n initialState = init(initialArg);\n } else {\n initialState = initialArg;\n }\n\n hook.memoizedState = hook.baseState = initialState;\n var queue = hook.queue = {\n pending: null,\n dispatch: null,\n lastRenderedReducer: reducer,\n lastRenderedState: initialState\n };\n var dispatch = queue.dispatch = dispatchAction.bind(null, currentlyRenderingFiber$1, queue);\n return [hook.memoizedState, dispatch];\n}\n\nfunction updateReducer(reducer, initialArg, init) {\n var hook = updateWorkInProgressHook();\n var queue = hook.queue;\n\n if (!(queue !== null)) {\n {\n throw Error( \"Should have a queue. This is likely a bug in React. Please file an issue.\" );\n }\n }\n\n queue.lastRenderedReducer = reducer;\n var current = currentHook; // The last rebase update that is NOT part of the base state.\n\n var baseQueue = current.baseQueue; // The last pending update that hasn't been processed yet.\n\n var pendingQueue = queue.pending;\n\n if (pendingQueue !== null) {\n // We have new updates that haven't been processed yet.\n // We'll add them to the base queue.\n if (baseQueue !== null) {\n // Merge the pending queue and the base queue.\n var baseFirst = baseQueue.next;\n var pendingFirst = pendingQueue.next;\n baseQueue.next = pendingFirst;\n pendingQueue.next = baseFirst;\n }\n\n current.baseQueue = baseQueue = pendingQueue;\n queue.pending = null;\n }\n\n if (baseQueue !== null) {\n // We have a queue to process.\n var first = baseQueue.next;\n var newState = current.baseState;\n var newBaseState = null;\n var newBaseQueueFirst = null;\n var newBaseQueueLast = null;\n var update = first;\n\n do {\n var updateExpirationTime = update.expirationTime;\n\n if (updateExpirationTime < renderExpirationTime) {\n // Priority is insufficient. Skip this update. If this is the first\n // skipped update, the previous update/state is the new base\n // update/state.\n var clone = {\n expirationTime: update.expirationTime,\n suspenseConfig: update.suspenseConfig,\n action: update.action,\n eagerReducer: update.eagerReducer,\n eagerState: update.eagerState,\n next: null\n };\n\n if (newBaseQueueLast === null) {\n newBaseQueueFirst = newBaseQueueLast = clone;\n newBaseState = newState;\n } else {\n newBaseQueueLast = newBaseQueueLast.next = clone;\n } // Update the remaining priority in the queue.\n\n\n if (updateExpirationTime > currentlyRenderingFiber$1.expirationTime) {\n currentlyRenderingFiber$1.expirationTime = updateExpirationTime;\n markUnprocessedUpdateTime(updateExpirationTime);\n }\n } else {\n // This update does have sufficient priority.\n if (newBaseQueueLast !== null) {\n var _clone = {\n expirationTime: Sync,\n // This update is going to be committed so we never want uncommit it.\n suspenseConfig: update.suspenseConfig,\n action: update.action,\n eagerReducer: update.eagerReducer,\n eagerState: update.eagerState,\n next: null\n };\n newBaseQueueLast = newBaseQueueLast.next = _clone;\n } // Mark the event time of this update as relevant to this render pass.\n // TODO: This should ideally use the true event time of this update rather than\n // its priority which is a derived and not reverseable value.\n // TODO: We should skip this update if it was already committed but currently\n // we have no way of detecting the difference between a committed and suspended\n // update here.\n\n\n markRenderEventTimeAndConfig(updateExpirationTime, update.suspenseConfig); // Process this update.\n\n if (update.eagerReducer === reducer) {\n // If this update was processed eagerly, and its reducer matches the\n // current reducer, we can use the eagerly computed state.\n newState = update.eagerState;\n } else {\n var action = update.action;\n newState = reducer(newState, action);\n }\n }\n\n update = update.next;\n } while (update !== null && update !== first);\n\n if (newBaseQueueLast === null) {\n newBaseState = newState;\n } else {\n newBaseQueueLast.next = newBaseQueueFirst;\n } // Mark that the fiber performed work, but only if the new state is\n // different from the current state.\n\n\n if (!objectIs(newState, hook.memoizedState)) {\n markWorkInProgressReceivedUpdate();\n }\n\n hook.memoizedState = newState;\n hook.baseState = newBaseState;\n hook.baseQueue = newBaseQueueLast;\n queue.lastRenderedState = newState;\n }\n\n var dispatch = queue.dispatch;\n return [hook.memoizedState, dispatch];\n}\n\nfunction rerenderReducer(reducer, initialArg, init) {\n var hook = updateWorkInProgressHook();\n var queue = hook.queue;\n\n if (!(queue !== null)) {\n {\n throw Error( \"Should have a queue. This is likely a bug in React. Please file an issue.\" );\n }\n }\n\n queue.lastRenderedReducer = reducer; // This is a re-render. Apply the new render phase updates to the previous\n // work-in-progress hook.\n\n var dispatch = queue.dispatch;\n var lastRenderPhaseUpdate = queue.pending;\n var newState = hook.memoizedState;\n\n if (lastRenderPhaseUpdate !== null) {\n // The queue doesn't persist past this render pass.\n queue.pending = null;\n var firstRenderPhaseUpdate = lastRenderPhaseUpdate.next;\n var update = firstRenderPhaseUpdate;\n\n do {\n // Process this render phase update. We don't have to check the\n // priority because it will always be the same as the current\n // render's.\n var action = update.action;\n newState = reducer(newState, action);\n update = update.next;\n } while (update !== firstRenderPhaseUpdate); // Mark that the fiber performed work, but only if the new state is\n // different from the current state.\n\n\n if (!objectIs(newState, hook.memoizedState)) {\n markWorkInProgressReceivedUpdate();\n }\n\n hook.memoizedState = newState; // Don't persist the state accumulated from the render phase updates to\n // the base state unless the queue is empty.\n // TODO: Not sure if this is the desired semantics, but it's what we\n // do for gDSFP. I can't remember why.\n\n if (hook.baseQueue === null) {\n hook.baseState = newState;\n }\n\n queue.lastRenderedState = newState;\n }\n\n return [newState, dispatch];\n}\n\nfunction mountState(initialState) {\n var hook = mountWorkInProgressHook();\n\n if (typeof initialState === 'function') {\n // $FlowFixMe: Flow doesn't like mixed types\n initialState = initialState();\n }\n\n hook.memoizedState = hook.baseState = initialState;\n var queue = hook.queue = {\n pending: null,\n dispatch: null,\n lastRenderedReducer: basicStateReducer,\n lastRenderedState: initialState\n };\n var dispatch = queue.dispatch = dispatchAction.bind(null, currentlyRenderingFiber$1, queue);\n return [hook.memoizedState, dispatch];\n}\n\nfunction updateState(initialState) {\n return updateReducer(basicStateReducer);\n}\n\nfunction rerenderState(initialState) {\n return rerenderReducer(basicStateReducer);\n}\n\nfunction pushEffect(tag, create, destroy, deps) {\n var effect = {\n tag: tag,\n create: create,\n destroy: destroy,\n deps: deps,\n // Circular\n next: null\n };\n var componentUpdateQueue = currentlyRenderingFiber$1.updateQueue;\n\n if (componentUpdateQueue === null) {\n componentUpdateQueue = createFunctionComponentUpdateQueue();\n currentlyRenderingFiber$1.updateQueue = componentUpdateQueue;\n componentUpdateQueue.lastEffect = effect.next = effect;\n } else {\n var lastEffect = componentUpdateQueue.lastEffect;\n\n if (lastEffect === null) {\n componentUpdateQueue.lastEffect = effect.next = effect;\n } else {\n var firstEffect = lastEffect.next;\n lastEffect.next = effect;\n effect.next = firstEffect;\n componentUpdateQueue.lastEffect = effect;\n }\n }\n\n return effect;\n}\n\nfunction mountRef(initialValue) {\n var hook = mountWorkInProgressHook();\n var ref = {\n current: initialValue\n };\n\n {\n Object.seal(ref);\n }\n\n hook.memoizedState = ref;\n return ref;\n}\n\nfunction updateRef(initialValue) {\n var hook = updateWorkInProgressHook();\n return hook.memoizedState;\n}\n\nfunction mountEffectImpl(fiberEffectTag, hookEffectTag, create, deps) {\n var hook = mountWorkInProgressHook();\n var nextDeps = deps === undefined ? null : deps;\n currentlyRenderingFiber$1.effectTag |= fiberEffectTag;\n hook.memoizedState = pushEffect(HasEffect | hookEffectTag, create, undefined, nextDeps);\n}\n\nfunction updateEffectImpl(fiberEffectTag, hookEffectTag, create, deps) {\n var hook = updateWorkInProgressHook();\n var nextDeps = deps === undefined ? null : deps;\n var destroy = undefined;\n\n if (currentHook !== null) {\n var prevEffect = currentHook.memoizedState;\n destroy = prevEffect.destroy;\n\n if (nextDeps !== null) {\n var prevDeps = prevEffect.deps;\n\n if (areHookInputsEqual(nextDeps, prevDeps)) {\n pushEffect(hookEffectTag, create, destroy, nextDeps);\n return;\n }\n }\n }\n\n currentlyRenderingFiber$1.effectTag |= fiberEffectTag;\n hook.memoizedState = pushEffect(HasEffect | hookEffectTag, create, destroy, nextDeps);\n}\n\nfunction mountEffect(create, deps) {\n {\n // $FlowExpectedError - jest isn't a global, and isn't recognized outside of tests\n if ('undefined' !== typeof jest) {\n warnIfNotCurrentlyActingEffectsInDEV(currentlyRenderingFiber$1);\n }\n }\n\n return mountEffectImpl(Update | Passive, Passive$1, create, deps);\n}\n\nfunction updateEffect(create, deps) {\n {\n // $FlowExpectedError - jest isn't a global, and isn't recognized outside of tests\n if ('undefined' !== typeof jest) {\n warnIfNotCurrentlyActingEffectsInDEV(currentlyRenderingFiber$1);\n }\n }\n\n return updateEffectImpl(Update | Passive, Passive$1, create, deps);\n}\n\nfunction mountLayoutEffect(create, deps) {\n return mountEffectImpl(Update, Layout, create, deps);\n}\n\nfunction updateLayoutEffect(create, deps) {\n return updateEffectImpl(Update, Layout, create, deps);\n}\n\nfunction imperativeHandleEffect(create, ref) {\n if (typeof ref === 'function') {\n var refCallback = ref;\n\n var _inst = create();\n\n refCallback(_inst);\n return function () {\n refCallback(null);\n };\n } else if (ref !== null && ref !== undefined) {\n var refObject = ref;\n\n {\n if (!refObject.hasOwnProperty('current')) {\n error('Expected useImperativeHandle() first argument to either be a ' + 'ref callback or React.createRef() object. Instead received: %s.', 'an object with keys {' + Object.keys(refObject).join(', ') + '}');\n }\n }\n\n var _inst2 = create();\n\n refObject.current = _inst2;\n return function () {\n refObject.current = null;\n };\n }\n}\n\nfunction mountImperativeHandle(ref, create, deps) {\n {\n if (typeof create !== 'function') {\n error('Expected useImperativeHandle() second argument to be a function ' + 'that creates a handle. Instead received: %s.', create !== null ? typeof create : 'null');\n }\n } // TODO: If deps are provided, should we skip comparing the ref itself?\n\n\n var effectDeps = deps !== null && deps !== undefined ? deps.concat([ref]) : null;\n return mountEffectImpl(Update, Layout, imperativeHandleEffect.bind(null, create, ref), effectDeps);\n}\n\nfunction updateImperativeHandle(ref, create, deps) {\n {\n if (typeof create !== 'function') {\n error('Expected useImperativeHandle() second argument to be a function ' + 'that creates a handle. Instead received: %s.', create !== null ? typeof create : 'null');\n }\n } // TODO: If deps are provided, should we skip comparing the ref itself?\n\n\n var effectDeps = deps !== null && deps !== undefined ? deps.concat([ref]) : null;\n return updateEffectImpl(Update, Layout, imperativeHandleEffect.bind(null, create, ref), effectDeps);\n}\n\nfunction mountDebugValue(value, formatterFn) {// This hook is normally a no-op.\n // The react-debug-hooks package injects its own implementation\n // so that e.g. DevTools can display custom hook values.\n}\n\nvar updateDebugValue = mountDebugValue;\n\nfunction mountCallback(callback, deps) {\n var hook = mountWorkInProgressHook();\n var nextDeps = deps === undefined ? null : deps;\n hook.memoizedState = [callback, nextDeps];\n return callback;\n}\n\nfunction updateCallback(callback, deps) {\n var hook = updateWorkInProgressHook();\n var nextDeps = deps === undefined ? null : deps;\n var prevState = hook.memoizedState;\n\n if (prevState !== null) {\n if (nextDeps !== null) {\n var prevDeps = prevState[1];\n\n if (areHookInputsEqual(nextDeps, prevDeps)) {\n return prevState[0];\n }\n }\n }\n\n hook.memoizedState = [callback, nextDeps];\n return callback;\n}\n\nfunction mountMemo(nextCreate, deps) {\n var hook = mountWorkInProgressHook();\n var nextDeps = deps === undefined ? null : deps;\n var nextValue = nextCreate();\n hook.memoizedState = [nextValue, nextDeps];\n return nextValue;\n}\n\nfunction updateMemo(nextCreate, deps) {\n var hook = updateWorkInProgressHook();\n var nextDeps = deps === undefined ? null : deps;\n var prevState = hook.memoizedState;\n\n if (prevState !== null) {\n // Assume these are defined. If they're not, areHookInputsEqual will warn.\n if (nextDeps !== null) {\n var prevDeps = prevState[1];\n\n if (areHookInputsEqual(nextDeps, prevDeps)) {\n return prevState[0];\n }\n }\n }\n\n var nextValue = nextCreate();\n hook.memoizedState = [nextValue, nextDeps];\n return nextValue;\n}\n\nfunction mountDeferredValue(value, config) {\n var _mountState = mountState(value),\n prevValue = _mountState[0],\n setValue = _mountState[1];\n\n mountEffect(function () {\n var previousConfig = ReactCurrentBatchConfig$1.suspense;\n ReactCurrentBatchConfig$1.suspense = config === undefined ? null : config;\n\n try {\n setValue(value);\n } finally {\n ReactCurrentBatchConfig$1.suspense = previousConfig;\n }\n }, [value, config]);\n return prevValue;\n}\n\nfunction updateDeferredValue(value, config) {\n var _updateState = updateState(),\n prevValue = _updateState[0],\n setValue = _updateState[1];\n\n updateEffect(function () {\n var previousConfig = ReactCurrentBatchConfig$1.suspense;\n ReactCurrentBatchConfig$1.suspense = config === undefined ? null : config;\n\n try {\n setValue(value);\n } finally {\n ReactCurrentBatchConfig$1.suspense = previousConfig;\n }\n }, [value, config]);\n return prevValue;\n}\n\nfunction rerenderDeferredValue(value, config) {\n var _rerenderState = rerenderState(),\n prevValue = _rerenderState[0],\n setValue = _rerenderState[1];\n\n updateEffect(function () {\n var previousConfig = ReactCurrentBatchConfig$1.suspense;\n ReactCurrentBatchConfig$1.suspense = config === undefined ? null : config;\n\n try {\n setValue(value);\n } finally {\n ReactCurrentBatchConfig$1.suspense = previousConfig;\n }\n }, [value, config]);\n return prevValue;\n}\n\nfunction startTransition(setPending, config, callback) {\n var priorityLevel = getCurrentPriorityLevel();\n runWithPriority$1(priorityLevel < UserBlockingPriority$1 ? UserBlockingPriority$1 : priorityLevel, function () {\n setPending(true);\n });\n runWithPriority$1(priorityLevel > NormalPriority ? NormalPriority : priorityLevel, function () {\n var previousConfig = ReactCurrentBatchConfig$1.suspense;\n ReactCurrentBatchConfig$1.suspense = config === undefined ? null : config;\n\n try {\n setPending(false);\n callback();\n } finally {\n ReactCurrentBatchConfig$1.suspense = previousConfig;\n }\n });\n}\n\nfunction mountTransition(config) {\n var _mountState2 = mountState(false),\n isPending = _mountState2[0],\n setPending = _mountState2[1];\n\n var start = mountCallback(startTransition.bind(null, setPending, config), [setPending, config]);\n return [start, isPending];\n}\n\nfunction updateTransition(config) {\n var _updateState2 = updateState(),\n isPending = _updateState2[0],\n setPending = _updateState2[1];\n\n var start = updateCallback(startTransition.bind(null, setPending, config), [setPending, config]);\n return [start, isPending];\n}\n\nfunction rerenderTransition(config) {\n var _rerenderState2 = rerenderState(),\n isPending = _rerenderState2[0],\n setPending = _rerenderState2[1];\n\n var start = updateCallback(startTransition.bind(null, setPending, config), [setPending, config]);\n return [start, isPending];\n}\n\nfunction dispatchAction(fiber, queue, action) {\n {\n if (typeof arguments[3] === 'function') {\n error(\"State updates from the useState() and useReducer() Hooks don't support the \" + 'second callback argument. To execute a side effect after ' + 'rendering, declare it in the component body with useEffect().');\n }\n }\n\n var currentTime = requestCurrentTimeForUpdate();\n var suspenseConfig = requestCurrentSuspenseConfig();\n var expirationTime = computeExpirationForFiber(currentTime, fiber, suspenseConfig);\n var update = {\n expirationTime: expirationTime,\n suspenseConfig: suspenseConfig,\n action: action,\n eagerReducer: null,\n eagerState: null,\n next: null\n };\n\n {\n update.priority = getCurrentPriorityLevel();\n } // Append the update to the end of the list.\n\n\n var pending = queue.pending;\n\n if (pending === null) {\n // This is the first update. Create a circular list.\n update.next = update;\n } else {\n update.next = pending.next;\n pending.next = update;\n }\n\n queue.pending = update;\n var alternate = fiber.alternate;\n\n if (fiber === currentlyRenderingFiber$1 || alternate !== null && alternate === currentlyRenderingFiber$1) {\n // This is a render phase update. Stash it in a lazily-created map of\n // queue -> linked list of updates. After this render pass, we'll restart\n // and apply the stashed updates on top of the work-in-progress hook.\n didScheduleRenderPhaseUpdate = true;\n update.expirationTime = renderExpirationTime;\n currentlyRenderingFiber$1.expirationTime = renderExpirationTime;\n } else {\n if (fiber.expirationTime === NoWork && (alternate === null || alternate.expirationTime === NoWork)) {\n // The queue is currently empty, which means we can eagerly compute the\n // next state before entering the render phase. If the new state is the\n // same as the current state, we may be able to bail out entirely.\n var lastRenderedReducer = queue.lastRenderedReducer;\n\n if (lastRenderedReducer !== null) {\n var prevDispatcher;\n\n {\n prevDispatcher = ReactCurrentDispatcher.current;\n ReactCurrentDispatcher.current = InvalidNestedHooksDispatcherOnUpdateInDEV;\n }\n\n try {\n var currentState = queue.lastRenderedState;\n var eagerState = lastRenderedReducer(currentState, action); // Stash the eagerly computed state, and the reducer used to compute\n // it, on the update object. If the reducer hasn't changed by the\n // time we enter the render phase, then the eager state can be used\n // without calling the reducer again.\n\n update.eagerReducer = lastRenderedReducer;\n update.eagerState = eagerState;\n\n if (objectIs(eagerState, currentState)) {\n // Fast path. We can bail out without scheduling React to re-render.\n // It's still possible that we'll need to rebase this update later,\n // if the component re-renders for a different reason and by that\n // time the reducer has changed.\n return;\n }\n } catch (error) {// Suppress the error. It will throw again in the render phase.\n } finally {\n {\n ReactCurrentDispatcher.current = prevDispatcher;\n }\n }\n }\n }\n\n {\n // $FlowExpectedError - jest isn't a global, and isn't recognized outside of tests\n if ('undefined' !== typeof jest) {\n warnIfNotScopedWithMatchingAct(fiber);\n warnIfNotCurrentlyActingUpdatesInDev(fiber);\n }\n }\n\n scheduleWork(fiber, expirationTime);\n }\n}\n\nvar ContextOnlyDispatcher = {\n readContext: readContext,\n useCallback: throwInvalidHookError,\n useContext: throwInvalidHookError,\n useEffect: throwInvalidHookError,\n useImperativeHandle: throwInvalidHookError,\n useLayoutEffect: throwInvalidHookError,\n useMemo: throwInvalidHookError,\n useReducer: throwInvalidHookError,\n useRef: throwInvalidHookError,\n useState: throwInvalidHookError,\n useDebugValue: throwInvalidHookError,\n useResponder: throwInvalidHookError,\n useDeferredValue: throwInvalidHookError,\n useTransition: throwInvalidHookError\n};\nvar HooksDispatcherOnMountInDEV = null;\nvar HooksDispatcherOnMountWithHookTypesInDEV = null;\nvar HooksDispatcherOnUpdateInDEV = null;\nvar HooksDispatcherOnRerenderInDEV = null;\nvar InvalidNestedHooksDispatcherOnMountInDEV = null;\nvar InvalidNestedHooksDispatcherOnUpdateInDEV = null;\nvar InvalidNestedHooksDispatcherOnRerenderInDEV = null;\n\n{\n var warnInvalidContextAccess = function () {\n error('Context can only be read while React is rendering. ' + 'In classes, you can read it in the render method or getDerivedStateFromProps. ' + 'In function components, you can read it directly in the function body, but not ' + 'inside Hooks like useReducer() or useMemo().');\n };\n\n var warnInvalidHookAccess = function () {\n error('Do not call Hooks inside useEffect(...), useMemo(...), or other built-in Hooks. ' + 'You can only call Hooks at the top level of your React function. ' + 'For more information, see ' + 'https://fb.me/rules-of-hooks');\n };\n\n HooksDispatcherOnMountInDEV = {\n readContext: function (context, observedBits) {\n return readContext(context, observedBits);\n },\n useCallback: function (callback, deps) {\n currentHookNameInDev = 'useCallback';\n mountHookTypesDev();\n checkDepsAreArrayDev(deps);\n return mountCallback(callback, deps);\n },\n useContext: function (context, observedBits) {\n currentHookNameInDev = 'useContext';\n mountHookTypesDev();\n return readContext(context, observedBits);\n },\n useEffect: function (create, deps) {\n currentHookNameInDev = 'useEffect';\n mountHookTypesDev();\n checkDepsAreArrayDev(deps);\n return mountEffect(create, deps);\n },\n useImperativeHandle: function (ref, create, deps) {\n currentHookNameInDev = 'useImperativeHandle';\n mountHookTypesDev();\n checkDepsAreArrayDev(deps);\n return mountImperativeHandle(ref, create, deps);\n },\n useLayoutEffect: function (create, deps) {\n currentHookNameInDev = 'useLayoutEffect';\n mountHookTypesDev();\n checkDepsAreArrayDev(deps);\n return mountLayoutEffect(create, deps);\n },\n useMemo: function (create, deps) {\n currentHookNameInDev = 'useMemo';\n mountHookTypesDev();\n checkDepsAreArrayDev(deps);\n var prevDispatcher = ReactCurrentDispatcher.current;\n ReactCurrentDispatcher.current = InvalidNestedHooksDispatcherOnMountInDEV;\n\n try {\n return mountMemo(create, deps);\n } finally {\n ReactCurrentDispatcher.current = prevDispatcher;\n }\n },\n useReducer: function (reducer, initialArg, init) {\n currentHookNameInDev = 'useReducer';\n mountHookTypesDev();\n var prevDispatcher = ReactCurrentDispatcher.current;\n ReactCurrentDispatcher.current = InvalidNestedHooksDispatcherOnMountInDEV;\n\n try {\n return mountReducer(reducer, initialArg, init);\n } finally {\n ReactCurrentDispatcher.current = prevDispatcher;\n }\n },\n useRef: function (initialValue) {\n currentHookNameInDev = 'useRef';\n mountHookTypesDev();\n return mountRef(initialValue);\n },\n useState: function (initialState) {\n currentHookNameInDev = 'useState';\n mountHookTypesDev();\n var prevDispatcher = ReactCurrentDispatcher.current;\n ReactCurrentDispatcher.current = InvalidNestedHooksDispatcherOnMountInDEV;\n\n try {\n return mountState(initialState);\n } finally {\n ReactCurrentDispatcher.current = prevDispatcher;\n }\n },\n useDebugValue: function (value, formatterFn) {\n currentHookNameInDev = 'useDebugValue';\n mountHookTypesDev();\n return mountDebugValue();\n },\n useResponder: function (responder, props) {\n currentHookNameInDev = 'useResponder';\n mountHookTypesDev();\n return createDeprecatedResponderListener(responder, props);\n },\n useDeferredValue: function (value, config) {\n currentHookNameInDev = 'useDeferredValue';\n mountHookTypesDev();\n return mountDeferredValue(value, config);\n },\n useTransition: function (config) {\n currentHookNameInDev = 'useTransition';\n mountHookTypesDev();\n return mountTransition(config);\n }\n };\n HooksDispatcherOnMountWithHookTypesInDEV = {\n readContext: function (context, observedBits) {\n return readContext(context, observedBits);\n },\n useCallback: function (callback, deps) {\n currentHookNameInDev = 'useCallback';\n updateHookTypesDev();\n return mountCallback(callback, deps);\n },\n useContext: function (context, observedBits) {\n currentHookNameInDev = 'useContext';\n updateHookTypesDev();\n return readContext(context, observedBits);\n },\n useEffect: function (create, deps) {\n currentHookNameInDev = 'useEffect';\n updateHookTypesDev();\n return mountEffect(create, deps);\n },\n useImperativeHandle: function (ref, create, deps) {\n currentHookNameInDev = 'useImperativeHandle';\n updateHookTypesDev();\n return mountImperativeHandle(ref, create, deps);\n },\n useLayoutEffect: function (create, deps) {\n currentHookNameInDev = 'useLayoutEffect';\n updateHookTypesDev();\n return mountLayoutEffect(create, deps);\n },\n useMemo: function (create, deps) {\n currentHookNameInDev = 'useMemo';\n updateHookTypesDev();\n var prevDispatcher = ReactCurrentDispatcher.current;\n ReactCurrentDispatcher.current = InvalidNestedHooksDispatcherOnMountInDEV;\n\n try {\n return mountMemo(create, deps);\n } finally {\n ReactCurrentDispatcher.current = prevDispatcher;\n }\n },\n useReducer: function (reducer, initialArg, init) {\n currentHookNameInDev = 'useReducer';\n updateHookTypesDev();\n var prevDispatcher = ReactCurrentDispatcher.current;\n ReactCurrentDispatcher.current = InvalidNestedHooksDispatcherOnMountInDEV;\n\n try {\n return mountReducer(reducer, initialArg, init);\n } finally {\n ReactCurrentDispatcher.current = prevDispatcher;\n }\n },\n useRef: function (initialValue) {\n currentHookNameInDev = 'useRef';\n updateHookTypesDev();\n return mountRef(initialValue);\n },\n useState: function (initialState) {\n currentHookNameInDev = 'useState';\n updateHookTypesDev();\n var prevDispatcher = ReactCurrentDispatcher.current;\n ReactCurrentDispatcher.current = InvalidNestedHooksDispatcherOnMountInDEV;\n\n try {\n return mountState(initialState);\n } finally {\n ReactCurrentDispatcher.current = prevDispatcher;\n }\n },\n useDebugValue: function (value, formatterFn) {\n currentHookNameInDev = 'useDebugValue';\n updateHookTypesDev();\n return mountDebugValue();\n },\n useResponder: function (responder, props) {\n currentHookNameInDev = 'useResponder';\n updateHookTypesDev();\n return createDeprecatedResponderListener(responder, props);\n },\n useDeferredValue: function (value, config) {\n currentHookNameInDev = 'useDeferredValue';\n updateHookTypesDev();\n return mountDeferredValue(value, config);\n },\n useTransition: function (config) {\n currentHookNameInDev = 'useTransition';\n updateHookTypesDev();\n return mountTransition(config);\n }\n };\n HooksDispatcherOnUpdateInDEV = {\n readContext: function (context, observedBits) {\n return readContext(context, observedBits);\n },\n useCallback: function (callback, deps) {\n currentHookNameInDev = 'useCallback';\n updateHookTypesDev();\n return updateCallback(callback, deps);\n },\n useContext: function (context, observedBits) {\n currentHookNameInDev = 'useContext';\n updateHookTypesDev();\n return readContext(context, observedBits);\n },\n useEffect: function (create, deps) {\n currentHookNameInDev = 'useEffect';\n updateHookTypesDev();\n return updateEffect(create, deps);\n },\n useImperativeHandle: function (ref, create, deps) {\n currentHookNameInDev = 'useImperativeHandle';\n updateHookTypesDev();\n return updateImperativeHandle(ref, create, deps);\n },\n useLayoutEffect: function (create, deps) {\n currentHookNameInDev = 'useLayoutEffect';\n updateHookTypesDev();\n return updateLayoutEffect(create, deps);\n },\n useMemo: function (create, deps) {\n currentHookNameInDev = 'useMemo';\n updateHookTypesDev();\n var prevDispatcher = ReactCurrentDispatcher.current;\n ReactCurrentDispatcher.current = InvalidNestedHooksDispatcherOnUpdateInDEV;\n\n try {\n return updateMemo(create, deps);\n } finally {\n ReactCurrentDispatcher.current = prevDispatcher;\n }\n },\n useReducer: function (reducer, initialArg, init) {\n currentHookNameInDev = 'useReducer';\n updateHookTypesDev();\n var prevDispatcher = ReactCurrentDispatcher.current;\n ReactCurrentDispatcher.current = InvalidNestedHooksDispatcherOnUpdateInDEV;\n\n try {\n return updateReducer(reducer, initialArg, init);\n } finally {\n ReactCurrentDispatcher.current = prevDispatcher;\n }\n },\n useRef: function (initialValue) {\n currentHookNameInDev = 'useRef';\n updateHookTypesDev();\n return updateRef();\n },\n useState: function (initialState) {\n currentHookNameInDev = 'useState';\n updateHookTypesDev();\n var prevDispatcher = ReactCurrentDispatcher.current;\n ReactCurrentDispatcher.current = InvalidNestedHooksDispatcherOnUpdateInDEV;\n\n try {\n return updateState(initialState);\n } finally {\n ReactCurrentDispatcher.current = prevDispatcher;\n }\n },\n useDebugValue: function (value, formatterFn) {\n currentHookNameInDev = 'useDebugValue';\n updateHookTypesDev();\n return updateDebugValue();\n },\n useResponder: function (responder, props) {\n currentHookNameInDev = 'useResponder';\n updateHookTypesDev();\n return createDeprecatedResponderListener(responder, props);\n },\n useDeferredValue: function (value, config) {\n currentHookNameInDev = 'useDeferredValue';\n updateHookTypesDev();\n return updateDeferredValue(value, config);\n },\n useTransition: function (config) {\n currentHookNameInDev = 'useTransition';\n updateHookTypesDev();\n return updateTransition(config);\n }\n };\n HooksDispatcherOnRerenderInDEV = {\n readContext: function (context, observedBits) {\n return readContext(context, observedBits);\n },\n useCallback: function (callback, deps) {\n currentHookNameInDev = 'useCallback';\n updateHookTypesDev();\n return updateCallback(callback, deps);\n },\n useContext: function (context, observedBits) {\n currentHookNameInDev = 'useContext';\n updateHookTypesDev();\n return readContext(context, observedBits);\n },\n useEffect: function (create, deps) {\n currentHookNameInDev = 'useEffect';\n updateHookTypesDev();\n return updateEffect(create, deps);\n },\n useImperativeHandle: function (ref, create, deps) {\n currentHookNameInDev = 'useImperativeHandle';\n updateHookTypesDev();\n return updateImperativeHandle(ref, create, deps);\n },\n useLayoutEffect: function (create, deps) {\n currentHookNameInDev = 'useLayoutEffect';\n updateHookTypesDev();\n return updateLayoutEffect(create, deps);\n },\n useMemo: function (create, deps) {\n currentHookNameInDev = 'useMemo';\n updateHookTypesDev();\n var prevDispatcher = ReactCurrentDispatcher.current;\n ReactCurrentDispatcher.current = InvalidNestedHooksDispatcherOnRerenderInDEV;\n\n try {\n return updateMemo(create, deps);\n } finally {\n ReactCurrentDispatcher.current = prevDispatcher;\n }\n },\n useReducer: function (reducer, initialArg, init) {\n currentHookNameInDev = 'useReducer';\n updateHookTypesDev();\n var prevDispatcher = ReactCurrentDispatcher.current;\n ReactCurrentDispatcher.current = InvalidNestedHooksDispatcherOnRerenderInDEV;\n\n try {\n return rerenderReducer(reducer, initialArg, init);\n } finally {\n ReactCurrentDispatcher.current = prevDispatcher;\n }\n },\n useRef: function (initialValue) {\n currentHookNameInDev = 'useRef';\n updateHookTypesDev();\n return updateRef();\n },\n useState: function (initialState) {\n currentHookNameInDev = 'useState';\n updateHookTypesDev();\n var prevDispatcher = ReactCurrentDispatcher.current;\n ReactCurrentDispatcher.current = InvalidNestedHooksDispatcherOnRerenderInDEV;\n\n try {\n return rerenderState(initialState);\n } finally {\n ReactCurrentDispatcher.current = prevDispatcher;\n }\n },\n useDebugValue: function (value, formatterFn) {\n currentHookNameInDev = 'useDebugValue';\n updateHookTypesDev();\n return updateDebugValue();\n },\n useResponder: function (responder, props) {\n currentHookNameInDev = 'useResponder';\n updateHookTypesDev();\n return createDeprecatedResponderListener(responder, props);\n },\n useDeferredValue: function (value, config) {\n currentHookNameInDev = 'useDeferredValue';\n updateHookTypesDev();\n return rerenderDeferredValue(value, config);\n },\n useTransition: function (config) {\n currentHookNameInDev = 'useTransition';\n updateHookTypesDev();\n return rerenderTransition(config);\n }\n };\n InvalidNestedHooksDispatcherOnMountInDEV = {\n readContext: function (context, observedBits) {\n warnInvalidContextAccess();\n return readContext(context, observedBits);\n },\n useCallback: function (callback, deps) {\n currentHookNameInDev = 'useCallback';\n warnInvalidHookAccess();\n mountHookTypesDev();\n return mountCallback(callback, deps);\n },\n useContext: function (context, observedBits) {\n currentHookNameInDev = 'useContext';\n warnInvalidHookAccess();\n mountHookTypesDev();\n return readContext(context, observedBits);\n },\n useEffect: function (create, deps) {\n currentHookNameInDev = 'useEffect';\n warnInvalidHookAccess();\n mountHookTypesDev();\n return mountEffect(create, deps);\n },\n useImperativeHandle: function (ref, create, deps) {\n currentHookNameInDev = 'useImperativeHandle';\n warnInvalidHookAccess();\n mountHookTypesDev();\n return mountImperativeHandle(ref, create, deps);\n },\n useLayoutEffect: function (create, deps) {\n currentHookNameInDev = 'useLayoutEffect';\n warnInvalidHookAccess();\n mountHookTypesDev();\n return mountLayoutEffect(create, deps);\n },\n useMemo: function (create, deps) {\n currentHookNameInDev = 'useMemo';\n warnInvalidHookAccess();\n mountHookTypesDev();\n var prevDispatcher = ReactCurrentDispatcher.current;\n ReactCurrentDispatcher.current = InvalidNestedHooksDispatcherOnMountInDEV;\n\n try {\n return mountMemo(create, deps);\n } finally {\n ReactCurrentDispatcher.current = prevDispatcher;\n }\n },\n useReducer: function (reducer, initialArg, init) {\n currentHookNameInDev = 'useReducer';\n warnInvalidHookAccess();\n mountHookTypesDev();\n var prevDispatcher = ReactCurrentDispatcher.current;\n ReactCurrentDispatcher.current = InvalidNestedHooksDispatcherOnMountInDEV;\n\n try {\n return mountReducer(reducer, initialArg, init);\n } finally {\n ReactCurrentDispatcher.current = prevDispatcher;\n }\n },\n useRef: function (initialValue) {\n currentHookNameInDev = 'useRef';\n warnInvalidHookAccess();\n mountHookTypesDev();\n return mountRef(initialValue);\n },\n useState: function (initialState) {\n currentHookNameInDev = 'useState';\n warnInvalidHookAccess();\n mountHookTypesDev();\n var prevDispatcher = ReactCurrentDispatcher.current;\n ReactCurrentDispatcher.current = InvalidNestedHooksDispatcherOnMountInDEV;\n\n try {\n return mountState(initialState);\n } finally {\n ReactCurrentDispatcher.current = prevDispatcher;\n }\n },\n useDebugValue: function (value, formatterFn) {\n currentHookNameInDev = 'useDebugValue';\n warnInvalidHookAccess();\n mountHookTypesDev();\n return mountDebugValue();\n },\n useResponder: function (responder, props) {\n currentHookNameInDev = 'useResponder';\n warnInvalidHookAccess();\n mountHookTypesDev();\n return createDeprecatedResponderListener(responder, props);\n },\n useDeferredValue: function (value, config) {\n currentHookNameInDev = 'useDeferredValue';\n warnInvalidHookAccess();\n mountHookTypesDev();\n return mountDeferredValue(value, config);\n },\n useTransition: function (config) {\n currentHookNameInDev = 'useTransition';\n warnInvalidHookAccess();\n mountHookTypesDev();\n return mountTransition(config);\n }\n };\n InvalidNestedHooksDispatcherOnUpdateInDEV = {\n readContext: function (context, observedBits) {\n warnInvalidContextAccess();\n return readContext(context, observedBits);\n },\n useCallback: function (callback, deps) {\n currentHookNameInDev = 'useCallback';\n warnInvalidHookAccess();\n updateHookTypesDev();\n return updateCallback(callback, deps);\n },\n useContext: function (context, observedBits) {\n currentHookNameInDev = 'useContext';\n warnInvalidHookAccess();\n updateHookTypesDev();\n return readContext(context, observedBits);\n },\n useEffect: function (create, deps) {\n currentHookNameInDev = 'useEffect';\n warnInvalidHookAccess();\n updateHookTypesDev();\n return updateEffect(create, deps);\n },\n useImperativeHandle: function (ref, create, deps) {\n currentHookNameInDev = 'useImperativeHandle';\n warnInvalidHookAccess();\n updateHookTypesDev();\n return updateImperativeHandle(ref, create, deps);\n },\n useLayoutEffect: function (create, deps) {\n currentHookNameInDev = 'useLayoutEffect';\n warnInvalidHookAccess();\n updateHookTypesDev();\n return updateLayoutEffect(create, deps);\n },\n useMemo: function (create, deps) {\n currentHookNameInDev = 'useMemo';\n warnInvalidHookAccess();\n updateHookTypesDev();\n var prevDispatcher = ReactCurrentDispatcher.current;\n ReactCurrentDispatcher.current = InvalidNestedHooksDispatcherOnUpdateInDEV;\n\n try {\n return updateMemo(create, deps);\n } finally {\n ReactCurrentDispatcher.current = prevDispatcher;\n }\n },\n useReducer: function (reducer, initialArg, init) {\n currentHookNameInDev = 'useReducer';\n warnInvalidHookAccess();\n updateHookTypesDev();\n var prevDispatcher = ReactCurrentDispatcher.current;\n ReactCurrentDispatcher.current = InvalidNestedHooksDispatcherOnUpdateInDEV;\n\n try {\n return updateReducer(reducer, initialArg, init);\n } finally {\n ReactCurrentDispatcher.current = prevDispatcher;\n }\n },\n useRef: function (initialValue) {\n currentHookNameInDev = 'useRef';\n warnInvalidHookAccess();\n updateHookTypesDev();\n return updateRef();\n },\n useState: function (initialState) {\n currentHookNameInDev = 'useState';\n warnInvalidHookAccess();\n updateHookTypesDev();\n var prevDispatcher = ReactCurrentDispatcher.current;\n ReactCurrentDispatcher.current = InvalidNestedHooksDispatcherOnUpdateInDEV;\n\n try {\n return updateState(initialState);\n } finally {\n ReactCurrentDispatcher.current = prevDispatcher;\n }\n },\n useDebugValue: function (value, formatterFn) {\n currentHookNameInDev = 'useDebugValue';\n warnInvalidHookAccess();\n updateHookTypesDev();\n return updateDebugValue();\n },\n useResponder: function (responder, props) {\n currentHookNameInDev = 'useResponder';\n warnInvalidHookAccess();\n updateHookTypesDev();\n return createDeprecatedResponderListener(responder, props);\n },\n useDeferredValue: function (value, config) {\n currentHookNameInDev = 'useDeferredValue';\n warnInvalidHookAccess();\n updateHookTypesDev();\n return updateDeferredValue(value, config);\n },\n useTransition: function (config) {\n currentHookNameInDev = 'useTransition';\n warnInvalidHookAccess();\n updateHookTypesDev();\n return updateTransition(config);\n }\n };\n InvalidNestedHooksDispatcherOnRerenderInDEV = {\n readContext: function (context, observedBits) {\n warnInvalidContextAccess();\n return readContext(context, observedBits);\n },\n useCallback: function (callback, deps) {\n currentHookNameInDev = 'useCallback';\n warnInvalidHookAccess();\n updateHookTypesDev();\n return updateCallback(callback, deps);\n },\n useContext: function (context, observedBits) {\n currentHookNameInDev = 'useContext';\n warnInvalidHookAccess();\n updateHookTypesDev();\n return readContext(context, observedBits);\n },\n useEffect: function (create, deps) {\n currentHookNameInDev = 'useEffect';\n warnInvalidHookAccess();\n updateHookTypesDev();\n return updateEffect(create, deps);\n },\n useImperativeHandle: function (ref, create, deps) {\n currentHookNameInDev = 'useImperativeHandle';\n warnInvalidHookAccess();\n updateHookTypesDev();\n return updateImperativeHandle(ref, create, deps);\n },\n useLayoutEffect: function (create, deps) {\n currentHookNameInDev = 'useLayoutEffect';\n warnInvalidHookAccess();\n updateHookTypesDev();\n return updateLayoutEffect(create, deps);\n },\n useMemo: function (create, deps) {\n currentHookNameInDev = 'useMemo';\n warnInvalidHookAccess();\n updateHookTypesDev();\n var prevDispatcher = ReactCurrentDispatcher.current;\n ReactCurrentDispatcher.current = InvalidNestedHooksDispatcherOnUpdateInDEV;\n\n try {\n return updateMemo(create, deps);\n } finally {\n ReactCurrentDispatcher.current = prevDispatcher;\n }\n },\n useReducer: function (reducer, initialArg, init) {\n currentHookNameInDev = 'useReducer';\n warnInvalidHookAccess();\n updateHookTypesDev();\n var prevDispatcher = ReactCurrentDispatcher.current;\n ReactCurrentDispatcher.current = InvalidNestedHooksDispatcherOnUpdateInDEV;\n\n try {\n return rerenderReducer(reducer, initialArg, init);\n } finally {\n ReactCurrentDispatcher.current = prevDispatcher;\n }\n },\n useRef: function (initialValue) {\n currentHookNameInDev = 'useRef';\n warnInvalidHookAccess();\n updateHookTypesDev();\n return updateRef();\n },\n useState: function (initialState) {\n currentHookNameInDev = 'useState';\n warnInvalidHookAccess();\n updateHookTypesDev();\n var prevDispatcher = ReactCurrentDispatcher.current;\n ReactCurrentDispatcher.current = InvalidNestedHooksDispatcherOnUpdateInDEV;\n\n try {\n return rerenderState(initialState);\n } finally {\n ReactCurrentDispatcher.current = prevDispatcher;\n }\n },\n useDebugValue: function (value, formatterFn) {\n currentHookNameInDev = 'useDebugValue';\n warnInvalidHookAccess();\n updateHookTypesDev();\n return updateDebugValue();\n },\n useResponder: function (responder, props) {\n currentHookNameInDev = 'useResponder';\n warnInvalidHookAccess();\n updateHookTypesDev();\n return createDeprecatedResponderListener(responder, props);\n },\n useDeferredValue: function (value, config) {\n currentHookNameInDev = 'useDeferredValue';\n warnInvalidHookAccess();\n updateHookTypesDev();\n return rerenderDeferredValue(value, config);\n },\n useTransition: function (config) {\n currentHookNameInDev = 'useTransition';\n warnInvalidHookAccess();\n updateHookTypesDev();\n return rerenderTransition(config);\n }\n };\n}\n\nvar now$1 = Scheduler.unstable_now;\nvar commitTime = 0;\nvar profilerStartTime = -1;\n\nfunction getCommitTime() {\n return commitTime;\n}\n\nfunction recordCommitTime() {\n\n commitTime = now$1();\n}\n\nfunction startProfilerTimer(fiber) {\n\n profilerStartTime = now$1();\n\n if (fiber.actualStartTime < 0) {\n fiber.actualStartTime = now$1();\n }\n}\n\nfunction stopProfilerTimerIfRunning(fiber) {\n\n profilerStartTime = -1;\n}\n\nfunction stopProfilerTimerIfRunningAndRecordDelta(fiber, overrideBaseTime) {\n\n if (profilerStartTime >= 0) {\n var elapsedTime = now$1() - profilerStartTime;\n fiber.actualDuration += elapsedTime;\n\n if (overrideBaseTime) {\n fiber.selfBaseDuration = elapsedTime;\n }\n\n profilerStartTime = -1;\n }\n}\n\n// This may have been an insertion or a hydration.\n\nvar hydrationParentFiber = null;\nvar nextHydratableInstance = null;\nvar isHydrating = false;\n\nfunction enterHydrationState(fiber) {\n\n var parentInstance = fiber.stateNode.containerInfo;\n nextHydratableInstance = getFirstHydratableChild(parentInstance);\n hydrationParentFiber = fiber;\n isHydrating = true;\n return true;\n}\n\nfunction deleteHydratableInstance(returnFiber, instance) {\n {\n switch (returnFiber.tag) {\n case HostRoot:\n didNotHydrateContainerInstance(returnFiber.stateNode.containerInfo, instance);\n break;\n\n case HostComponent:\n didNotHydrateInstance(returnFiber.type, returnFiber.memoizedProps, returnFiber.stateNode, instance);\n break;\n }\n }\n\n var childToDelete = createFiberFromHostInstanceForDeletion();\n childToDelete.stateNode = instance;\n childToDelete.return = returnFiber;\n childToDelete.effectTag = Deletion; // This might seem like it belongs on progressedFirstDeletion. However,\n // these children are not part of the reconciliation list of children.\n // Even if we abort and rereconcile the children, that will try to hydrate\n // again and the nodes are still in the host tree so these will be\n // recreated.\n\n if (returnFiber.lastEffect !== null) {\n returnFiber.lastEffect.nextEffect = childToDelete;\n returnFiber.lastEffect = childToDelete;\n } else {\n returnFiber.firstEffect = returnFiber.lastEffect = childToDelete;\n }\n}\n\nfunction insertNonHydratedInstance(returnFiber, fiber) {\n fiber.effectTag = fiber.effectTag & ~Hydrating | Placement;\n\n {\n switch (returnFiber.tag) {\n case HostRoot:\n {\n var parentContainer = returnFiber.stateNode.containerInfo;\n\n switch (fiber.tag) {\n case HostComponent:\n var type = fiber.type;\n var props = fiber.pendingProps;\n didNotFindHydratableContainerInstance(parentContainer, type);\n break;\n\n case HostText:\n var text = fiber.pendingProps;\n didNotFindHydratableContainerTextInstance(parentContainer, text);\n break;\n }\n\n break;\n }\n\n case HostComponent:\n {\n var parentType = returnFiber.type;\n var parentProps = returnFiber.memoizedProps;\n var parentInstance = returnFiber.stateNode;\n\n switch (fiber.tag) {\n case HostComponent:\n var _type = fiber.type;\n var _props = fiber.pendingProps;\n didNotFindHydratableInstance(parentType, parentProps, parentInstance, _type);\n break;\n\n case HostText:\n var _text = fiber.pendingProps;\n didNotFindHydratableTextInstance(parentType, parentProps, parentInstance, _text);\n break;\n\n case SuspenseComponent:\n didNotFindHydratableSuspenseInstance(parentType, parentProps);\n break;\n }\n\n break;\n }\n\n default:\n return;\n }\n }\n}\n\nfunction tryHydrate(fiber, nextInstance) {\n switch (fiber.tag) {\n case HostComponent:\n {\n var type = fiber.type;\n var props = fiber.pendingProps;\n var instance = canHydrateInstance(nextInstance, type);\n\n if (instance !== null) {\n fiber.stateNode = instance;\n return true;\n }\n\n return false;\n }\n\n case HostText:\n {\n var text = fiber.pendingProps;\n var textInstance = canHydrateTextInstance(nextInstance, text);\n\n if (textInstance !== null) {\n fiber.stateNode = textInstance;\n return true;\n }\n\n return false;\n }\n\n case SuspenseComponent:\n {\n\n return false;\n }\n\n default:\n return false;\n }\n}\n\nfunction tryToClaimNextHydratableInstance(fiber) {\n if (!isHydrating) {\n return;\n }\n\n var nextInstance = nextHydratableInstance;\n\n if (!nextInstance) {\n // Nothing to hydrate. Make it an insertion.\n insertNonHydratedInstance(hydrationParentFiber, fiber);\n isHydrating = false;\n hydrationParentFiber = fiber;\n return;\n }\n\n var firstAttemptedInstance = nextInstance;\n\n if (!tryHydrate(fiber, nextInstance)) {\n // If we can't hydrate this instance let's try the next one.\n // We use this as a heuristic. It's based on intuition and not data so it\n // might be flawed or unnecessary.\n nextInstance = getNextHydratableSibling(firstAttemptedInstance);\n\n if (!nextInstance || !tryHydrate(fiber, nextInstance)) {\n // Nothing to hydrate. Make it an insertion.\n insertNonHydratedInstance(hydrationParentFiber, fiber);\n isHydrating = false;\n hydrationParentFiber = fiber;\n return;\n } // We matched the next one, we'll now assume that the first one was\n // superfluous and we'll delete it. Since we can't eagerly delete it\n // we'll have to schedule a deletion. To do that, this node needs a dummy\n // fiber associated with it.\n\n\n deleteHydratableInstance(hydrationParentFiber, firstAttemptedInstance);\n }\n\n hydrationParentFiber = fiber;\n nextHydratableInstance = getFirstHydratableChild(nextInstance);\n}\n\nfunction prepareToHydrateHostInstance(fiber, rootContainerInstance, hostContext) {\n\n var instance = fiber.stateNode;\n var updatePayload = hydrateInstance(instance, fiber.type, fiber.memoizedProps, rootContainerInstance, hostContext, fiber); // TODO: Type this specific to this type of component.\n\n fiber.updateQueue = updatePayload; // If the update payload indicates that there is a change or if there\n // is a new ref we mark this as an update.\n\n if (updatePayload !== null) {\n return true;\n }\n\n return false;\n}\n\nfunction prepareToHydrateHostTextInstance(fiber) {\n\n var textInstance = fiber.stateNode;\n var textContent = fiber.memoizedProps;\n var shouldUpdate = hydrateTextInstance(textInstance, textContent, fiber);\n\n {\n if (shouldUpdate) {\n // We assume that prepareToHydrateHostTextInstance is called in a context where the\n // hydration parent is the parent host component of this host text.\n var returnFiber = hydrationParentFiber;\n\n if (returnFiber !== null) {\n switch (returnFiber.tag) {\n case HostRoot:\n {\n var parentContainer = returnFiber.stateNode.containerInfo;\n didNotMatchHydratedContainerTextInstance(parentContainer, textInstance, textContent);\n break;\n }\n\n case HostComponent:\n {\n var parentType = returnFiber.type;\n var parentProps = returnFiber.memoizedProps;\n var parentInstance = returnFiber.stateNode;\n didNotMatchHydratedTextInstance(parentType, parentProps, parentInstance, textInstance, textContent);\n break;\n }\n }\n }\n }\n }\n\n return shouldUpdate;\n}\n\nfunction skipPastDehydratedSuspenseInstance(fiber) {\n\n var suspenseState = fiber.memoizedState;\n var suspenseInstance = suspenseState !== null ? suspenseState.dehydrated : null;\n\n if (!suspenseInstance) {\n {\n throw Error( \"Expected to have a hydrated suspense instance. This error is likely caused by a bug in React. Please file an issue.\" );\n }\n }\n\n return getNextHydratableInstanceAfterSuspenseInstance(suspenseInstance);\n}\n\nfunction popToNextHostParent(fiber) {\n var parent = fiber.return;\n\n while (parent !== null && parent.tag !== HostComponent && parent.tag !== HostRoot && parent.tag !== SuspenseComponent) {\n parent = parent.return;\n }\n\n hydrationParentFiber = parent;\n}\n\nfunction popHydrationState(fiber) {\n\n if (fiber !== hydrationParentFiber) {\n // We're deeper than the current hydration context, inside an inserted\n // tree.\n return false;\n }\n\n if (!isHydrating) {\n // If we're not currently hydrating but we're in a hydration context, then\n // we were an insertion and now need to pop up reenter hydration of our\n // siblings.\n popToNextHostParent(fiber);\n isHydrating = true;\n return false;\n }\n\n var type = fiber.type; // If we have any remaining hydratable nodes, we need to delete them now.\n // We only do this deeper than head and body since they tend to have random\n // other nodes in them. We also ignore components with pure text content in\n // side of them.\n // TODO: Better heuristic.\n\n if (fiber.tag !== HostComponent || type !== 'head' && type !== 'body' && !shouldSetTextContent(type, fiber.memoizedProps)) {\n var nextInstance = nextHydratableInstance;\n\n while (nextInstance) {\n deleteHydratableInstance(fiber, nextInstance);\n nextInstance = getNextHydratableSibling(nextInstance);\n }\n }\n\n popToNextHostParent(fiber);\n\n if (fiber.tag === SuspenseComponent) {\n nextHydratableInstance = skipPastDehydratedSuspenseInstance(fiber);\n } else {\n nextHydratableInstance = hydrationParentFiber ? getNextHydratableSibling(fiber.stateNode) : null;\n }\n\n return true;\n}\n\nfunction resetHydrationState() {\n\n hydrationParentFiber = null;\n nextHydratableInstance = null;\n isHydrating = false;\n}\n\nvar ReactCurrentOwner$1 = ReactSharedInternals.ReactCurrentOwner;\nvar didReceiveUpdate = false;\nvar didWarnAboutBadClass;\nvar didWarnAboutModulePatternComponent;\nvar didWarnAboutContextTypeOnFunctionComponent;\nvar didWarnAboutGetDerivedStateOnFunctionComponent;\nvar didWarnAboutFunctionRefs;\nvar didWarnAboutReassigningProps;\nvar didWarnAboutRevealOrder;\nvar didWarnAboutTailOptions;\n\n{\n didWarnAboutBadClass = {};\n didWarnAboutModulePatternComponent = {};\n didWarnAboutContextTypeOnFunctionComponent = {};\n didWarnAboutGetDerivedStateOnFunctionComponent = {};\n didWarnAboutFunctionRefs = {};\n didWarnAboutReassigningProps = false;\n didWarnAboutRevealOrder = {};\n didWarnAboutTailOptions = {};\n}\n\nfunction reconcileChildren(current, workInProgress, nextChildren, renderExpirationTime) {\n if (current === null) {\n // If this is a fresh new component that hasn't been rendered yet, we\n // won't update its child set by applying minimal side-effects. Instead,\n // we will add them all to the child before it gets rendered. That means\n // we can optimize this reconciliation pass by not tracking side-effects.\n workInProgress.child = mountChildFibers(workInProgress, null, nextChildren, renderExpirationTime);\n } else {\n // If the current child is the same as the work in progress, it means that\n // we haven't yet started any work on these children. Therefore, we use\n // the clone algorithm to create a copy of all the current children.\n // If we had any progressed work already, that is invalid at this point so\n // let's throw it out.\n workInProgress.child = reconcileChildFibers(workInProgress, current.child, nextChildren, renderExpirationTime);\n }\n}\n\nfunction forceUnmountCurrentAndReconcile(current, workInProgress, nextChildren, renderExpirationTime) {\n // This function is fork of reconcileChildren. It's used in cases where we\n // want to reconcile without matching against the existing set. This has the\n // effect of all current children being unmounted; even if the type and key\n // are the same, the old child is unmounted and a new child is created.\n //\n // To do this, we're going to go through the reconcile algorithm twice. In\n // the first pass, we schedule a deletion for all the current children by\n // passing null.\n workInProgress.child = reconcileChildFibers(workInProgress, current.child, null, renderExpirationTime); // In the second pass, we mount the new children. The trick here is that we\n // pass null in place of where we usually pass the current child set. This has\n // the effect of remounting all children regardless of whether their\n // identities match.\n\n workInProgress.child = reconcileChildFibers(workInProgress, null, nextChildren, renderExpirationTime);\n}\n\nfunction updateForwardRef(current, workInProgress, Component, nextProps, renderExpirationTime) {\n // TODO: current can be non-null here even if the component\n // hasn't yet mounted. This happens after the first render suspends.\n // We'll need to figure out if this is fine or can cause issues.\n {\n if (workInProgress.type !== workInProgress.elementType) {\n // Lazy component props can't be validated in createElement\n // because they're only guaranteed to be resolved here.\n var innerPropTypes = Component.propTypes;\n\n if (innerPropTypes) {\n checkPropTypes(innerPropTypes, nextProps, // Resolved props\n 'prop', getComponentName(Component), getCurrentFiberStackInDev);\n }\n }\n }\n\n var render = Component.render;\n var ref = workInProgress.ref; // The rest is a fork of updateFunctionComponent\n\n var nextChildren;\n prepareToReadContext(workInProgress, renderExpirationTime);\n\n {\n ReactCurrentOwner$1.current = workInProgress;\n setIsRendering(true);\n nextChildren = renderWithHooks(current, workInProgress, render, nextProps, ref, renderExpirationTime);\n\n if ( workInProgress.mode & StrictMode) {\n // Only double-render components with Hooks\n if (workInProgress.memoizedState !== null) {\n nextChildren = renderWithHooks(current, workInProgress, render, nextProps, ref, renderExpirationTime);\n }\n }\n\n setIsRendering(false);\n }\n\n if (current !== null && !didReceiveUpdate) {\n bailoutHooks(current, workInProgress, renderExpirationTime);\n return bailoutOnAlreadyFinishedWork(current, workInProgress, renderExpirationTime);\n } // React DevTools reads this flag.\n\n\n workInProgress.effectTag |= PerformedWork;\n reconcileChildren(current, workInProgress, nextChildren, renderExpirationTime);\n return workInProgress.child;\n}\n\nfunction updateMemoComponent(current, workInProgress, Component, nextProps, updateExpirationTime, renderExpirationTime) {\n if (current === null) {\n var type = Component.type;\n\n if (isSimpleFunctionComponent(type) && Component.compare === null && // SimpleMemoComponent codepath doesn't resolve outer props either.\n Component.defaultProps === undefined) {\n var resolvedType = type;\n\n {\n resolvedType = resolveFunctionForHotReloading(type);\n } // If this is a plain function component without default props,\n // and with only the default shallow comparison, we upgrade it\n // to a SimpleMemoComponent to allow fast path updates.\n\n\n workInProgress.tag = SimpleMemoComponent;\n workInProgress.type = resolvedType;\n\n {\n validateFunctionComponentInDev(workInProgress, type);\n }\n\n return updateSimpleMemoComponent(current, workInProgress, resolvedType, nextProps, updateExpirationTime, renderExpirationTime);\n }\n\n {\n var innerPropTypes = type.propTypes;\n\n if (innerPropTypes) {\n // Inner memo component props aren't currently validated in createElement.\n // We could move it there, but we'd still need this for lazy code path.\n checkPropTypes(innerPropTypes, nextProps, // Resolved props\n 'prop', getComponentName(type), getCurrentFiberStackInDev);\n }\n }\n\n var child = createFiberFromTypeAndProps(Component.type, null, nextProps, null, workInProgress.mode, renderExpirationTime);\n child.ref = workInProgress.ref;\n child.return = workInProgress;\n workInProgress.child = child;\n return child;\n }\n\n {\n var _type = Component.type;\n var _innerPropTypes = _type.propTypes;\n\n if (_innerPropTypes) {\n // Inner memo component props aren't currently validated in createElement.\n // We could move it there, but we'd still need this for lazy code path.\n checkPropTypes(_innerPropTypes, nextProps, // Resolved props\n 'prop', getComponentName(_type), getCurrentFiberStackInDev);\n }\n }\n\n var currentChild = current.child; // This is always exactly one child\n\n if (updateExpirationTime < renderExpirationTime) {\n // This will be the props with resolved defaultProps,\n // unlike current.memoizedProps which will be the unresolved ones.\n var prevProps = currentChild.memoizedProps; // Default to shallow comparison\n\n var compare = Component.compare;\n compare = compare !== null ? compare : shallowEqual;\n\n if (compare(prevProps, nextProps) && current.ref === workInProgress.ref) {\n return bailoutOnAlreadyFinishedWork(current, workInProgress, renderExpirationTime);\n }\n } // React DevTools reads this flag.\n\n\n workInProgress.effectTag |= PerformedWork;\n var newChild = createWorkInProgress(currentChild, nextProps);\n newChild.ref = workInProgress.ref;\n newChild.return = workInProgress;\n workInProgress.child = newChild;\n return newChild;\n}\n\nfunction updateSimpleMemoComponent(current, workInProgress, Component, nextProps, updateExpirationTime, renderExpirationTime) {\n // TODO: current can be non-null here even if the component\n // hasn't yet mounted. This happens when the inner render suspends.\n // We'll need to figure out if this is fine or can cause issues.\n {\n if (workInProgress.type !== workInProgress.elementType) {\n // Lazy component props can't be validated in createElement\n // because they're only guaranteed to be resolved here.\n var outerMemoType = workInProgress.elementType;\n\n if (outerMemoType.$$typeof === REACT_LAZY_TYPE) {\n // We warn when you define propTypes on lazy()\n // so let's just skip over it to find memo() outer wrapper.\n // Inner props for memo are validated later.\n outerMemoType = refineResolvedLazyComponent(outerMemoType);\n }\n\n var outerPropTypes = outerMemoType && outerMemoType.propTypes;\n\n if (outerPropTypes) {\n checkPropTypes(outerPropTypes, nextProps, // Resolved (SimpleMemoComponent has no defaultProps)\n 'prop', getComponentName(outerMemoType), getCurrentFiberStackInDev);\n } // Inner propTypes will be validated in the function component path.\n\n }\n }\n\n if (current !== null) {\n var prevProps = current.memoizedProps;\n\n if (shallowEqual(prevProps, nextProps) && current.ref === workInProgress.ref && ( // Prevent bailout if the implementation changed due to hot reload.\n workInProgress.type === current.type )) {\n didReceiveUpdate = false;\n\n if (updateExpirationTime < renderExpirationTime) {\n // The pending update priority was cleared at the beginning of\n // beginWork. We're about to bail out, but there might be additional\n // updates at a lower priority. Usually, the priority level of the\n // remaining updates is accumlated during the evaluation of the\n // component (i.e. when processing the update queue). But since since\n // we're bailing out early *without* evaluating the component, we need\n // to account for it here, too. Reset to the value of the current fiber.\n // NOTE: This only applies to SimpleMemoComponent, not MemoComponent,\n // because a MemoComponent fiber does not have hooks or an update queue;\n // rather, it wraps around an inner component, which may or may not\n // contains hooks.\n // TODO: Move the reset at in beginWork out of the common path so that\n // this is no longer necessary.\n workInProgress.expirationTime = current.expirationTime;\n return bailoutOnAlreadyFinishedWork(current, workInProgress, renderExpirationTime);\n }\n }\n }\n\n return updateFunctionComponent(current, workInProgress, Component, nextProps, renderExpirationTime);\n}\n\nfunction updateFragment(current, workInProgress, renderExpirationTime) {\n var nextChildren = workInProgress.pendingProps;\n reconcileChildren(current, workInProgress, nextChildren, renderExpirationTime);\n return workInProgress.child;\n}\n\nfunction updateMode(current, workInProgress, renderExpirationTime) {\n var nextChildren = workInProgress.pendingProps.children;\n reconcileChildren(current, workInProgress, nextChildren, renderExpirationTime);\n return workInProgress.child;\n}\n\nfunction updateProfiler(current, workInProgress, renderExpirationTime) {\n {\n workInProgress.effectTag |= Update;\n }\n\n var nextProps = workInProgress.pendingProps;\n var nextChildren = nextProps.children;\n reconcileChildren(current, workInProgress, nextChildren, renderExpirationTime);\n return workInProgress.child;\n}\n\nfunction markRef(current, workInProgress) {\n var ref = workInProgress.ref;\n\n if (current === null && ref !== null || current !== null && current.ref !== ref) {\n // Schedule a Ref effect\n workInProgress.effectTag |= Ref;\n }\n}\n\nfunction updateFunctionComponent(current, workInProgress, Component, nextProps, renderExpirationTime) {\n {\n if (workInProgress.type !== workInProgress.elementType) {\n // Lazy component props can't be validated in createElement\n // because they're only guaranteed to be resolved here.\n var innerPropTypes = Component.propTypes;\n\n if (innerPropTypes) {\n checkPropTypes(innerPropTypes, nextProps, // Resolved props\n 'prop', getComponentName(Component), getCurrentFiberStackInDev);\n }\n }\n }\n\n var context;\n\n {\n var unmaskedContext = getUnmaskedContext(workInProgress, Component, true);\n context = getMaskedContext(workInProgress, unmaskedContext);\n }\n\n var nextChildren;\n prepareToReadContext(workInProgress, renderExpirationTime);\n\n {\n ReactCurrentOwner$1.current = workInProgress;\n setIsRendering(true);\n nextChildren = renderWithHooks(current, workInProgress, Component, nextProps, context, renderExpirationTime);\n\n if ( workInProgress.mode & StrictMode) {\n // Only double-render components with Hooks\n if (workInProgress.memoizedState !== null) {\n nextChildren = renderWithHooks(current, workInProgress, Component, nextProps, context, renderExpirationTime);\n }\n }\n\n setIsRendering(false);\n }\n\n if (current !== null && !didReceiveUpdate) {\n bailoutHooks(current, workInProgress, renderExpirationTime);\n return bailoutOnAlreadyFinishedWork(current, workInProgress, renderExpirationTime);\n } // React DevTools reads this flag.\n\n\n workInProgress.effectTag |= PerformedWork;\n reconcileChildren(current, workInProgress, nextChildren, renderExpirationTime);\n return workInProgress.child;\n}\n\nfunction updateClassComponent(current, workInProgress, Component, nextProps, renderExpirationTime) {\n {\n if (workInProgress.type !== workInProgress.elementType) {\n // Lazy component props can't be validated in createElement\n // because they're only guaranteed to be resolved here.\n var innerPropTypes = Component.propTypes;\n\n if (innerPropTypes) {\n checkPropTypes(innerPropTypes, nextProps, // Resolved props\n 'prop', getComponentName(Component), getCurrentFiberStackInDev);\n }\n }\n } // Push context providers early to prevent context stack mismatches.\n // During mounting we don't know the child context yet as the instance doesn't exist.\n // We will invalidate the child context in finishClassComponent() right after rendering.\n\n\n var hasContext;\n\n if (isContextProvider(Component)) {\n hasContext = true;\n pushContextProvider(workInProgress);\n } else {\n hasContext = false;\n }\n\n prepareToReadContext(workInProgress, renderExpirationTime);\n var instance = workInProgress.stateNode;\n var shouldUpdate;\n\n if (instance === null) {\n if (current !== null) {\n // A class component without an instance only mounts if it suspended\n // inside a non-concurrent tree, in an inconsistent state. We want to\n // treat it like a new mount, even though an empty version of it already\n // committed. Disconnect the alternate pointers.\n current.alternate = null;\n workInProgress.alternate = null; // Since this is conceptually a new fiber, schedule a Placement effect\n\n workInProgress.effectTag |= Placement;\n } // In the initial pass we might need to construct the instance.\n\n\n constructClassInstance(workInProgress, Component, nextProps);\n mountClassInstance(workInProgress, Component, nextProps, renderExpirationTime);\n shouldUpdate = true;\n } else if (current === null) {\n // In a resume, we'll already have an instance we can reuse.\n shouldUpdate = resumeMountClassInstance(workInProgress, Component, nextProps, renderExpirationTime);\n } else {\n shouldUpdate = updateClassInstance(current, workInProgress, Component, nextProps, renderExpirationTime);\n }\n\n var nextUnitOfWork = finishClassComponent(current, workInProgress, Component, shouldUpdate, hasContext, renderExpirationTime);\n\n {\n var inst = workInProgress.stateNode;\n\n if (inst.props !== nextProps) {\n if (!didWarnAboutReassigningProps) {\n error('It looks like %s is reassigning its own `this.props` while rendering. ' + 'This is not supported and can lead to confusing bugs.', getComponentName(workInProgress.type) || 'a component');\n }\n\n didWarnAboutReassigningProps = true;\n }\n }\n\n return nextUnitOfWork;\n}\n\nfunction finishClassComponent(current, workInProgress, Component, shouldUpdate, hasContext, renderExpirationTime) {\n // Refs should update even if shouldComponentUpdate returns false\n markRef(current, workInProgress);\n var didCaptureError = (workInProgress.effectTag & DidCapture) !== NoEffect;\n\n if (!shouldUpdate && !didCaptureError) {\n // Context providers should defer to sCU for rendering\n if (hasContext) {\n invalidateContextProvider(workInProgress, Component, false);\n }\n\n return bailoutOnAlreadyFinishedWork(current, workInProgress, renderExpirationTime);\n }\n\n var instance = workInProgress.stateNode; // Rerender\n\n ReactCurrentOwner$1.current = workInProgress;\n var nextChildren;\n\n if (didCaptureError && typeof Component.getDerivedStateFromError !== 'function') {\n // If we captured an error, but getDerivedStateFromError is not defined,\n // unmount all the children. componentDidCatch will schedule an update to\n // re-render a fallback. This is temporary until we migrate everyone to\n // the new API.\n // TODO: Warn in a future release.\n nextChildren = null;\n\n {\n stopProfilerTimerIfRunning();\n }\n } else {\n {\n setIsRendering(true);\n nextChildren = instance.render();\n\n if ( workInProgress.mode & StrictMode) {\n instance.render();\n }\n\n setIsRendering(false);\n }\n } // React DevTools reads this flag.\n\n\n workInProgress.effectTag |= PerformedWork;\n\n if (current !== null && didCaptureError) {\n // If we're recovering from an error, reconcile without reusing any of\n // the existing children. Conceptually, the normal children and the children\n // that are shown on error are two different sets, so we shouldn't reuse\n // normal children even if their identities match.\n forceUnmountCurrentAndReconcile(current, workInProgress, nextChildren, renderExpirationTime);\n } else {\n reconcileChildren(current, workInProgress, nextChildren, renderExpirationTime);\n } // Memoize state using the values we just used to render.\n // TODO: Restructure so we never read values from the instance.\n\n\n workInProgress.memoizedState = instance.state; // The context might have changed so we need to recalculate it.\n\n if (hasContext) {\n invalidateContextProvider(workInProgress, Component, true);\n }\n\n return workInProgress.child;\n}\n\nfunction pushHostRootContext(workInProgress) {\n var root = workInProgress.stateNode;\n\n if (root.pendingContext) {\n pushTopLevelContextObject(workInProgress, root.pendingContext, root.pendingContext !== root.context);\n } else if (root.context) {\n // Should always be set\n pushTopLevelContextObject(workInProgress, root.context, false);\n }\n\n pushHostContainer(workInProgress, root.containerInfo);\n}\n\nfunction updateHostRoot(current, workInProgress, renderExpirationTime) {\n pushHostRootContext(workInProgress);\n var updateQueue = workInProgress.updateQueue;\n\n if (!(current !== null && updateQueue !== null)) {\n {\n throw Error( \"If the root does not have an updateQueue, we should have already bailed out. This error is likely caused by a bug in React. Please file an issue.\" );\n }\n }\n\n var nextProps = workInProgress.pendingProps;\n var prevState = workInProgress.memoizedState;\n var prevChildren = prevState !== null ? prevState.element : null;\n cloneUpdateQueue(current, workInProgress);\n processUpdateQueue(workInProgress, nextProps, null, renderExpirationTime);\n var nextState = workInProgress.memoizedState; // Caution: React DevTools currently depends on this property\n // being called \"element\".\n\n var nextChildren = nextState.element;\n\n if (nextChildren === prevChildren) {\n // If the state is the same as before, that's a bailout because we had\n // no work that expires at this time.\n resetHydrationState();\n return bailoutOnAlreadyFinishedWork(current, workInProgress, renderExpirationTime);\n }\n\n var root = workInProgress.stateNode;\n\n if (root.hydrate && enterHydrationState(workInProgress)) {\n // If we don't have any current children this might be the first pass.\n // We always try to hydrate. If this isn't a hydration pass there won't\n // be any children to hydrate which is effectively the same thing as\n // not hydrating.\n var child = mountChildFibers(workInProgress, null, nextChildren, renderExpirationTime);\n workInProgress.child = child;\n var node = child;\n\n while (node) {\n // Mark each child as hydrating. This is a fast path to know whether this\n // tree is part of a hydrating tree. This is used to determine if a child\n // node has fully mounted yet, and for scheduling event replaying.\n // Conceptually this is similar to Placement in that a new subtree is\n // inserted into the React tree here. It just happens to not need DOM\n // mutations because it already exists.\n node.effectTag = node.effectTag & ~Placement | Hydrating;\n node = node.sibling;\n }\n } else {\n // Otherwise reset hydration state in case we aborted and resumed another\n // root.\n reconcileChildren(current, workInProgress, nextChildren, renderExpirationTime);\n resetHydrationState();\n }\n\n return workInProgress.child;\n}\n\nfunction updateHostComponent(current, workInProgress, renderExpirationTime) {\n pushHostContext(workInProgress);\n\n if (current === null) {\n tryToClaimNextHydratableInstance(workInProgress);\n }\n\n var type = workInProgress.type;\n var nextProps = workInProgress.pendingProps;\n var prevProps = current !== null ? current.memoizedProps : null;\n var nextChildren = nextProps.children;\n var isDirectTextChild = shouldSetTextContent(type, nextProps);\n\n if (isDirectTextChild) {\n // We special case a direct text child of a host node. This is a common\n // case. We won't handle it as a reified child. We will instead handle\n // this in the host environment that also has access to this prop. That\n // avoids allocating another HostText fiber and traversing it.\n nextChildren = null;\n } else if (prevProps !== null && shouldSetTextContent(type, prevProps)) {\n // If we're switching from a direct text child to a normal child, or to\n // empty, we need to schedule the text content to be reset.\n workInProgress.effectTag |= ContentReset;\n }\n\n markRef(current, workInProgress); // Check the host config to see if the children are offscreen/hidden.\n\n if (workInProgress.mode & ConcurrentMode && renderExpirationTime !== Never && shouldDeprioritizeSubtree(type, nextProps)) {\n {\n markSpawnedWork(Never);\n } // Schedule this fiber to re-render at offscreen priority. Then bailout.\n\n\n workInProgress.expirationTime = workInProgress.childExpirationTime = Never;\n return null;\n }\n\n reconcileChildren(current, workInProgress, nextChildren, renderExpirationTime);\n return workInProgress.child;\n}\n\nfunction updateHostText(current, workInProgress) {\n if (current === null) {\n tryToClaimNextHydratableInstance(workInProgress);\n } // Nothing to do here. This is terminal. We'll do the completion step\n // immediately after.\n\n\n return null;\n}\n\nfunction mountLazyComponent(_current, workInProgress, elementType, updateExpirationTime, renderExpirationTime) {\n if (_current !== null) {\n // A lazy component only mounts if it suspended inside a non-\n // concurrent tree, in an inconsistent state. We want to treat it like\n // a new mount, even though an empty version of it already committed.\n // Disconnect the alternate pointers.\n _current.alternate = null;\n workInProgress.alternate = null; // Since this is conceptually a new fiber, schedule a Placement effect\n\n workInProgress.effectTag |= Placement;\n }\n\n var props = workInProgress.pendingProps; // We can't start a User Timing measurement with correct label yet.\n // Cancel and resume right after we know the tag.\n\n cancelWorkTimer(workInProgress);\n var Component = readLazyComponentType(elementType); // Store the unwrapped component in the type.\n\n workInProgress.type = Component;\n var resolvedTag = workInProgress.tag = resolveLazyComponentTag(Component);\n startWorkTimer(workInProgress);\n var resolvedProps = resolveDefaultProps(Component, props);\n var child;\n\n switch (resolvedTag) {\n case FunctionComponent:\n {\n {\n validateFunctionComponentInDev(workInProgress, Component);\n workInProgress.type = Component = resolveFunctionForHotReloading(Component);\n }\n\n child = updateFunctionComponent(null, workInProgress, Component, resolvedProps, renderExpirationTime);\n return child;\n }\n\n case ClassComponent:\n {\n {\n workInProgress.type = Component = resolveClassForHotReloading(Component);\n }\n\n child = updateClassComponent(null, workInProgress, Component, resolvedProps, renderExpirationTime);\n return child;\n }\n\n case ForwardRef:\n {\n {\n workInProgress.type = Component = resolveForwardRefForHotReloading(Component);\n }\n\n child = updateForwardRef(null, workInProgress, Component, resolvedProps, renderExpirationTime);\n return child;\n }\n\n case MemoComponent:\n {\n {\n if (workInProgress.type !== workInProgress.elementType) {\n var outerPropTypes = Component.propTypes;\n\n if (outerPropTypes) {\n checkPropTypes(outerPropTypes, resolvedProps, // Resolved for outer only\n 'prop', getComponentName(Component), getCurrentFiberStackInDev);\n }\n }\n }\n\n child = updateMemoComponent(null, workInProgress, Component, resolveDefaultProps(Component.type, resolvedProps), // The inner type can have defaults too\n updateExpirationTime, renderExpirationTime);\n return child;\n }\n }\n\n var hint = '';\n\n {\n if (Component !== null && typeof Component === 'object' && Component.$$typeof === REACT_LAZY_TYPE) {\n hint = ' Did you wrap a component in React.lazy() more than once?';\n }\n } // This message intentionally doesn't mention ForwardRef or MemoComponent\n // because the fact that it's a separate type of work is an\n // implementation detail.\n\n\n {\n {\n throw Error( \"Element type is invalid. Received a promise that resolves to: \" + Component + \". Lazy element type must resolve to a class or function.\" + hint );\n }\n }\n}\n\nfunction mountIncompleteClassComponent(_current, workInProgress, Component, nextProps, renderExpirationTime) {\n if (_current !== null) {\n // An incomplete component only mounts if it suspended inside a non-\n // concurrent tree, in an inconsistent state. We want to treat it like\n // a new mount, even though an empty version of it already committed.\n // Disconnect the alternate pointers.\n _current.alternate = null;\n workInProgress.alternate = null; // Since this is conceptually a new fiber, schedule a Placement effect\n\n workInProgress.effectTag |= Placement;\n } // Promote the fiber to a class and try rendering again.\n\n\n workInProgress.tag = ClassComponent; // The rest of this function is a fork of `updateClassComponent`\n // Push context providers early to prevent context stack mismatches.\n // During mounting we don't know the child context yet as the instance doesn't exist.\n // We will invalidate the child context in finishClassComponent() right after rendering.\n\n var hasContext;\n\n if (isContextProvider(Component)) {\n hasContext = true;\n pushContextProvider(workInProgress);\n } else {\n hasContext = false;\n }\n\n prepareToReadContext(workInProgress, renderExpirationTime);\n constructClassInstance(workInProgress, Component, nextProps);\n mountClassInstance(workInProgress, Component, nextProps, renderExpirationTime);\n return finishClassComponent(null, workInProgress, Component, true, hasContext, renderExpirationTime);\n}\n\nfunction mountIndeterminateComponent(_current, workInProgress, Component, renderExpirationTime) {\n if (_current !== null) {\n // An indeterminate component only mounts if it suspended inside a non-\n // concurrent tree, in an inconsistent state. We want to treat it like\n // a new mount, even though an empty version of it already committed.\n // Disconnect the alternate pointers.\n _current.alternate = null;\n workInProgress.alternate = null; // Since this is conceptually a new fiber, schedule a Placement effect\n\n workInProgress.effectTag |= Placement;\n }\n\n var props = workInProgress.pendingProps;\n var context;\n\n {\n var unmaskedContext = getUnmaskedContext(workInProgress, Component, false);\n context = getMaskedContext(workInProgress, unmaskedContext);\n }\n\n prepareToReadContext(workInProgress, renderExpirationTime);\n var value;\n\n {\n if (Component.prototype && typeof Component.prototype.render === 'function') {\n var componentName = getComponentName(Component) || 'Unknown';\n\n if (!didWarnAboutBadClass[componentName]) {\n error(\"The <%s /> component appears to have a render method, but doesn't extend React.Component. \" + 'This is likely to cause errors. Change %s to extend React.Component instead.', componentName, componentName);\n\n didWarnAboutBadClass[componentName] = true;\n }\n }\n\n if (workInProgress.mode & StrictMode) {\n ReactStrictModeWarnings.recordLegacyContextWarning(workInProgress, null);\n }\n\n setIsRendering(true);\n ReactCurrentOwner$1.current = workInProgress;\n value = renderWithHooks(null, workInProgress, Component, props, context, renderExpirationTime);\n setIsRendering(false);\n } // React DevTools reads this flag.\n\n\n workInProgress.effectTag |= PerformedWork;\n\n if (typeof value === 'object' && value !== null && typeof value.render === 'function' && value.$$typeof === undefined) {\n {\n var _componentName = getComponentName(Component) || 'Unknown';\n\n if (!didWarnAboutModulePatternComponent[_componentName]) {\n error('The <%s /> component appears to be a function component that returns a class instance. ' + 'Change %s to a class that extends React.Component instead. ' + \"If you can't use a class try assigning the prototype on the function as a workaround. \" + \"`%s.prototype = React.Component.prototype`. Don't use an arrow function since it \" + 'cannot be called with `new` by React.', _componentName, _componentName, _componentName);\n\n didWarnAboutModulePatternComponent[_componentName] = true;\n }\n } // Proceed under the assumption that this is a class instance\n\n\n workInProgress.tag = ClassComponent; // Throw out any hooks that were used.\n\n workInProgress.memoizedState = null;\n workInProgress.updateQueue = null; // Push context providers early to prevent context stack mismatches.\n // During mounting we don't know the child context yet as the instance doesn't exist.\n // We will invalidate the child context in finishClassComponent() right after rendering.\n\n var hasContext = false;\n\n if (isContextProvider(Component)) {\n hasContext = true;\n pushContextProvider(workInProgress);\n } else {\n hasContext = false;\n }\n\n workInProgress.memoizedState = value.state !== null && value.state !== undefined ? value.state : null;\n initializeUpdateQueue(workInProgress);\n var getDerivedStateFromProps = Component.getDerivedStateFromProps;\n\n if (typeof getDerivedStateFromProps === 'function') {\n applyDerivedStateFromProps(workInProgress, Component, getDerivedStateFromProps, props);\n }\n\n adoptClassInstance(workInProgress, value);\n mountClassInstance(workInProgress, Component, props, renderExpirationTime);\n return finishClassComponent(null, workInProgress, Component, true, hasContext, renderExpirationTime);\n } else {\n // Proceed under the assumption that this is a function component\n workInProgress.tag = FunctionComponent;\n\n {\n\n if ( workInProgress.mode & StrictMode) {\n // Only double-render components with Hooks\n if (workInProgress.memoizedState !== null) {\n value = renderWithHooks(null, workInProgress, Component, props, context, renderExpirationTime);\n }\n }\n }\n\n reconcileChildren(null, workInProgress, value, renderExpirationTime);\n\n {\n validateFunctionComponentInDev(workInProgress, Component);\n }\n\n return workInProgress.child;\n }\n}\n\nfunction validateFunctionComponentInDev(workInProgress, Component) {\n {\n if (Component) {\n if (Component.childContextTypes) {\n error('%s(...): childContextTypes cannot be defined on a function component.', Component.displayName || Component.name || 'Component');\n }\n }\n\n if (workInProgress.ref !== null) {\n var info = '';\n var ownerName = getCurrentFiberOwnerNameInDevOrNull();\n\n if (ownerName) {\n info += '\\n\\nCheck the render method of `' + ownerName + '`.';\n }\n\n var warningKey = ownerName || workInProgress._debugID || '';\n var debugSource = workInProgress._debugSource;\n\n if (debugSource) {\n warningKey = debugSource.fileName + ':' + debugSource.lineNumber;\n }\n\n if (!didWarnAboutFunctionRefs[warningKey]) {\n didWarnAboutFunctionRefs[warningKey] = true;\n\n error('Function components cannot be given refs. ' + 'Attempts to access this ref will fail. ' + 'Did you mean to use React.forwardRef()?%s', info);\n }\n }\n\n if (typeof Component.getDerivedStateFromProps === 'function') {\n var _componentName2 = getComponentName(Component) || 'Unknown';\n\n if (!didWarnAboutGetDerivedStateOnFunctionComponent[_componentName2]) {\n error('%s: Function components do not support getDerivedStateFromProps.', _componentName2);\n\n didWarnAboutGetDerivedStateOnFunctionComponent[_componentName2] = true;\n }\n }\n\n if (typeof Component.contextType === 'object' && Component.contextType !== null) {\n var _componentName3 = getComponentName(Component) || 'Unknown';\n\n if (!didWarnAboutContextTypeOnFunctionComponent[_componentName3]) {\n error('%s: Function components do not support contextType.', _componentName3);\n\n didWarnAboutContextTypeOnFunctionComponent[_componentName3] = true;\n }\n }\n }\n}\n\nvar SUSPENDED_MARKER = {\n dehydrated: null,\n retryTime: NoWork\n};\n\nfunction shouldRemainOnFallback(suspenseContext, current, workInProgress) {\n // If the context is telling us that we should show a fallback, and we're not\n // already showing content, then we should show the fallback instead.\n return hasSuspenseContext(suspenseContext, ForceSuspenseFallback) && (current === null || current.memoizedState !== null);\n}\n\nfunction updateSuspenseComponent(current, workInProgress, renderExpirationTime) {\n var mode = workInProgress.mode;\n var nextProps = workInProgress.pendingProps; // This is used by DevTools to force a boundary to suspend.\n\n {\n if (shouldSuspend(workInProgress)) {\n workInProgress.effectTag |= DidCapture;\n }\n }\n\n var suspenseContext = suspenseStackCursor.current;\n var nextDidTimeout = false;\n var didSuspend = (workInProgress.effectTag & DidCapture) !== NoEffect;\n\n if (didSuspend || shouldRemainOnFallback(suspenseContext, current)) {\n // Something in this boundary's subtree already suspended. Switch to\n // rendering the fallback children.\n nextDidTimeout = true;\n workInProgress.effectTag &= ~DidCapture;\n } else {\n // Attempting the main content\n if (current === null || current.memoizedState !== null) {\n // This is a new mount or this boundary is already showing a fallback state.\n // Mark this subtree context as having at least one invisible parent that could\n // handle the fallback state.\n // Boundaries without fallbacks or should be avoided are not considered since\n // they cannot handle preferred fallback states.\n if (nextProps.fallback !== undefined && nextProps.unstable_avoidThisFallback !== true) {\n suspenseContext = addSubtreeSuspenseContext(suspenseContext, InvisibleParentSuspenseContext);\n }\n }\n }\n\n suspenseContext = setDefaultShallowSuspenseContext(suspenseContext);\n pushSuspenseContext(workInProgress, suspenseContext); // This next part is a bit confusing. If the children timeout, we switch to\n // showing the fallback children in place of the \"primary\" children.\n // However, we don't want to delete the primary children because then their\n // state will be lost (both the React state and the host state, e.g.\n // uncontrolled form inputs). Instead we keep them mounted and hide them.\n // Both the fallback children AND the primary children are rendered at the\n // same time. Once the primary children are un-suspended, we can delete\n // the fallback children — don't need to preserve their state.\n //\n // The two sets of children are siblings in the host environment, but\n // semantically, for purposes of reconciliation, they are two separate sets.\n // So we store them using two fragment fibers.\n //\n // However, we want to avoid allocating extra fibers for every placeholder.\n // They're only necessary when the children time out, because that's the\n // only time when both sets are mounted.\n //\n // So, the extra fragment fibers are only used if the children time out.\n // Otherwise, we render the primary children directly. This requires some\n // custom reconciliation logic to preserve the state of the primary\n // children. It's essentially a very basic form of re-parenting.\n\n if (current === null) {\n // If we're currently hydrating, try to hydrate this boundary.\n // But only if this has a fallback.\n if (nextProps.fallback !== undefined) {\n tryToClaimNextHydratableInstance(workInProgress); // This could've been a dehydrated suspense component.\n } // This is the initial mount. This branch is pretty simple because there's\n // no previous state that needs to be preserved.\n\n\n if (nextDidTimeout) {\n // Mount separate fragments for primary and fallback children.\n var nextFallbackChildren = nextProps.fallback;\n var primaryChildFragment = createFiberFromFragment(null, mode, NoWork, null);\n primaryChildFragment.return = workInProgress;\n\n if ((workInProgress.mode & BlockingMode) === NoMode) {\n // Outside of blocking mode, we commit the effects from the\n // partially completed, timed-out tree, too.\n var progressedState = workInProgress.memoizedState;\n var progressedPrimaryChild = progressedState !== null ? workInProgress.child.child : workInProgress.child;\n primaryChildFragment.child = progressedPrimaryChild;\n var progressedChild = progressedPrimaryChild;\n\n while (progressedChild !== null) {\n progressedChild.return = primaryChildFragment;\n progressedChild = progressedChild.sibling;\n }\n }\n\n var fallbackChildFragment = createFiberFromFragment(nextFallbackChildren, mode, renderExpirationTime, null);\n fallbackChildFragment.return = workInProgress;\n primaryChildFragment.sibling = fallbackChildFragment; // Skip the primary children, and continue working on the\n // fallback children.\n\n workInProgress.memoizedState = SUSPENDED_MARKER;\n workInProgress.child = primaryChildFragment;\n return fallbackChildFragment;\n } else {\n // Mount the primary children without an intermediate fragment fiber.\n var nextPrimaryChildren = nextProps.children;\n workInProgress.memoizedState = null;\n return workInProgress.child = mountChildFibers(workInProgress, null, nextPrimaryChildren, renderExpirationTime);\n }\n } else {\n // This is an update. This branch is more complicated because we need to\n // ensure the state of the primary children is preserved.\n var prevState = current.memoizedState;\n\n if (prevState !== null) {\n // wrapped in a fragment fiber.\n\n\n var currentPrimaryChildFragment = current.child;\n var currentFallbackChildFragment = currentPrimaryChildFragment.sibling;\n\n if (nextDidTimeout) {\n // Still timed out. Reuse the current primary children by cloning\n // its fragment. We're going to skip over these entirely.\n var _nextFallbackChildren2 = nextProps.fallback;\n\n var _primaryChildFragment2 = createWorkInProgress(currentPrimaryChildFragment, currentPrimaryChildFragment.pendingProps);\n\n _primaryChildFragment2.return = workInProgress;\n\n if ((workInProgress.mode & BlockingMode) === NoMode) {\n // Outside of blocking mode, we commit the effects from the\n // partially completed, timed-out tree, too.\n var _progressedState = workInProgress.memoizedState;\n\n var _progressedPrimaryChild = _progressedState !== null ? workInProgress.child.child : workInProgress.child;\n\n if (_progressedPrimaryChild !== currentPrimaryChildFragment.child) {\n _primaryChildFragment2.child = _progressedPrimaryChild;\n var _progressedChild2 = _progressedPrimaryChild;\n\n while (_progressedChild2 !== null) {\n _progressedChild2.return = _primaryChildFragment2;\n _progressedChild2 = _progressedChild2.sibling;\n }\n }\n } // Because primaryChildFragment is a new fiber that we're inserting as the\n // parent of a new tree, we need to set its treeBaseDuration.\n\n\n if ( workInProgress.mode & ProfileMode) {\n // treeBaseDuration is the sum of all the child tree base durations.\n var _treeBaseDuration = 0;\n var _hiddenChild = _primaryChildFragment2.child;\n\n while (_hiddenChild !== null) {\n _treeBaseDuration += _hiddenChild.treeBaseDuration;\n _hiddenChild = _hiddenChild.sibling;\n }\n\n _primaryChildFragment2.treeBaseDuration = _treeBaseDuration;\n } // Clone the fallback child fragment, too. These we'll continue\n // working on.\n\n\n var _fallbackChildFragment2 = createWorkInProgress(currentFallbackChildFragment, _nextFallbackChildren2);\n\n _fallbackChildFragment2.return = workInProgress;\n _primaryChildFragment2.sibling = _fallbackChildFragment2;\n _primaryChildFragment2.childExpirationTime = NoWork; // Skip the primary children, and continue working on the\n // fallback children.\n\n workInProgress.memoizedState = SUSPENDED_MARKER;\n workInProgress.child = _primaryChildFragment2;\n return _fallbackChildFragment2;\n } else {\n // No longer suspended. Switch back to showing the primary children,\n // and remove the intermediate fragment fiber.\n var _nextPrimaryChildren = nextProps.children;\n var currentPrimaryChild = currentPrimaryChildFragment.child;\n var primaryChild = reconcileChildFibers(workInProgress, currentPrimaryChild, _nextPrimaryChildren, renderExpirationTime); // If this render doesn't suspend, we need to delete the fallback\n // children. Wait until the complete phase, after we've confirmed the\n // fallback is no longer needed.\n // TODO: Would it be better to store the fallback fragment on\n // the stateNode?\n // Continue rendering the children, like we normally do.\n\n workInProgress.memoizedState = null;\n return workInProgress.child = primaryChild;\n }\n } else {\n // The current tree has not already timed out. That means the primary\n // children are not wrapped in a fragment fiber.\n var _currentPrimaryChild = current.child;\n\n if (nextDidTimeout) {\n // Timed out. Wrap the children in a fragment fiber to keep them\n // separate from the fallback children.\n var _nextFallbackChildren3 = nextProps.fallback;\n\n var _primaryChildFragment3 = createFiberFromFragment( // It shouldn't matter what the pending props are because we aren't\n // going to render this fragment.\n null, mode, NoWork, null);\n\n _primaryChildFragment3.return = workInProgress;\n _primaryChildFragment3.child = _currentPrimaryChild;\n\n if (_currentPrimaryChild !== null) {\n _currentPrimaryChild.return = _primaryChildFragment3;\n } // Even though we're creating a new fiber, there are no new children,\n // because we're reusing an already mounted tree. So we don't need to\n // schedule a placement.\n // primaryChildFragment.effectTag |= Placement;\n\n\n if ((workInProgress.mode & BlockingMode) === NoMode) {\n // Outside of blocking mode, we commit the effects from the\n // partially completed, timed-out tree, too.\n var _progressedState2 = workInProgress.memoizedState;\n\n var _progressedPrimaryChild2 = _progressedState2 !== null ? workInProgress.child.child : workInProgress.child;\n\n _primaryChildFragment3.child = _progressedPrimaryChild2;\n var _progressedChild3 = _progressedPrimaryChild2;\n\n while (_progressedChild3 !== null) {\n _progressedChild3.return = _primaryChildFragment3;\n _progressedChild3 = _progressedChild3.sibling;\n }\n } // Because primaryChildFragment is a new fiber that we're inserting as the\n // parent of a new tree, we need to set its treeBaseDuration.\n\n\n if ( workInProgress.mode & ProfileMode) {\n // treeBaseDuration is the sum of all the child tree base durations.\n var _treeBaseDuration2 = 0;\n var _hiddenChild2 = _primaryChildFragment3.child;\n\n while (_hiddenChild2 !== null) {\n _treeBaseDuration2 += _hiddenChild2.treeBaseDuration;\n _hiddenChild2 = _hiddenChild2.sibling;\n }\n\n _primaryChildFragment3.treeBaseDuration = _treeBaseDuration2;\n } // Create a fragment from the fallback children, too.\n\n\n var _fallbackChildFragment3 = createFiberFromFragment(_nextFallbackChildren3, mode, renderExpirationTime, null);\n\n _fallbackChildFragment3.return = workInProgress;\n _primaryChildFragment3.sibling = _fallbackChildFragment3;\n _fallbackChildFragment3.effectTag |= Placement;\n _primaryChildFragment3.childExpirationTime = NoWork; // Skip the primary children, and continue working on the\n // fallback children.\n\n workInProgress.memoizedState = SUSPENDED_MARKER;\n workInProgress.child = _primaryChildFragment3;\n return _fallbackChildFragment3;\n } else {\n // Still haven't timed out. Continue rendering the children, like we\n // normally do.\n workInProgress.memoizedState = null;\n var _nextPrimaryChildren2 = nextProps.children;\n return workInProgress.child = reconcileChildFibers(workInProgress, _currentPrimaryChild, _nextPrimaryChildren2, renderExpirationTime);\n }\n }\n }\n}\n\nfunction scheduleWorkOnFiber(fiber, renderExpirationTime) {\n if (fiber.expirationTime < renderExpirationTime) {\n fiber.expirationTime = renderExpirationTime;\n }\n\n var alternate = fiber.alternate;\n\n if (alternate !== null && alternate.expirationTime < renderExpirationTime) {\n alternate.expirationTime = renderExpirationTime;\n }\n\n scheduleWorkOnParentPath(fiber.return, renderExpirationTime);\n}\n\nfunction propagateSuspenseContextChange(workInProgress, firstChild, renderExpirationTime) {\n // Mark any Suspense boundaries with fallbacks as having work to do.\n // If they were previously forced into fallbacks, they may now be able\n // to unblock.\n var node = firstChild;\n\n while (node !== null) {\n if (node.tag === SuspenseComponent) {\n var state = node.memoizedState;\n\n if (state !== null) {\n scheduleWorkOnFiber(node, renderExpirationTime);\n }\n } else if (node.tag === SuspenseListComponent) {\n // If the tail is hidden there might not be an Suspense boundaries\n // to schedule work on. In this case we have to schedule it on the\n // list itself.\n // We don't have to traverse to the children of the list since\n // the list will propagate the change when it rerenders.\n scheduleWorkOnFiber(node, renderExpirationTime);\n } else if (node.child !== null) {\n node.child.return = node;\n node = node.child;\n continue;\n }\n\n if (node === workInProgress) {\n return;\n }\n\n while (node.sibling === null) {\n if (node.return === null || node.return === workInProgress) {\n return;\n }\n\n node = node.return;\n }\n\n node.sibling.return = node.return;\n node = node.sibling;\n }\n}\n\nfunction findLastContentRow(firstChild) {\n // This is going to find the last row among these children that is already\n // showing content on the screen, as opposed to being in fallback state or\n // new. If a row has multiple Suspense boundaries, any of them being in the\n // fallback state, counts as the whole row being in a fallback state.\n // Note that the \"rows\" will be workInProgress, but any nested children\n // will still be current since we haven't rendered them yet. The mounted\n // order may not be the same as the new order. We use the new order.\n var row = firstChild;\n var lastContentRow = null;\n\n while (row !== null) {\n var currentRow = row.alternate; // New rows can't be content rows.\n\n if (currentRow !== null && findFirstSuspended(currentRow) === null) {\n lastContentRow = row;\n }\n\n row = row.sibling;\n }\n\n return lastContentRow;\n}\n\nfunction validateRevealOrder(revealOrder) {\n {\n if (revealOrder !== undefined && revealOrder !== 'forwards' && revealOrder !== 'backwards' && revealOrder !== 'together' && !didWarnAboutRevealOrder[revealOrder]) {\n didWarnAboutRevealOrder[revealOrder] = true;\n\n if (typeof revealOrder === 'string') {\n switch (revealOrder.toLowerCase()) {\n case 'together':\n case 'forwards':\n case 'backwards':\n {\n error('\"%s\" is not a valid value for revealOrder on <SuspenseList />. ' + 'Use lowercase \"%s\" instead.', revealOrder, revealOrder.toLowerCase());\n\n break;\n }\n\n case 'forward':\n case 'backward':\n {\n error('\"%s\" is not a valid value for revealOrder on <SuspenseList />. ' + 'React uses the -s suffix in the spelling. Use \"%ss\" instead.', revealOrder, revealOrder.toLowerCase());\n\n break;\n }\n\n default:\n error('\"%s\" is not a supported revealOrder on <SuspenseList />. ' + 'Did you mean \"together\", \"forwards\" or \"backwards\"?', revealOrder);\n\n break;\n }\n } else {\n error('%s is not a supported value for revealOrder on <SuspenseList />. ' + 'Did you mean \"together\", \"forwards\" or \"backwards\"?', revealOrder);\n }\n }\n }\n}\n\nfunction validateTailOptions(tailMode, revealOrder) {\n {\n if (tailMode !== undefined && !didWarnAboutTailOptions[tailMode]) {\n if (tailMode !== 'collapsed' && tailMode !== 'hidden') {\n didWarnAboutTailOptions[tailMode] = true;\n\n error('\"%s\" is not a supported value for tail on <SuspenseList />. ' + 'Did you mean \"collapsed\" or \"hidden\"?', tailMode);\n } else if (revealOrder !== 'forwards' && revealOrder !== 'backwards') {\n didWarnAboutTailOptions[tailMode] = true;\n\n error('<SuspenseList tail=\"%s\" /> is only valid if revealOrder is ' + '\"forwards\" or \"backwards\". ' + 'Did you mean to specify revealOrder=\"forwards\"?', tailMode);\n }\n }\n }\n}\n\nfunction validateSuspenseListNestedChild(childSlot, index) {\n {\n var isArray = Array.isArray(childSlot);\n var isIterable = !isArray && typeof getIteratorFn(childSlot) === 'function';\n\n if (isArray || isIterable) {\n var type = isArray ? 'array' : 'iterable';\n\n error('A nested %s was passed to row #%s in <SuspenseList />. Wrap it in ' + 'an additional SuspenseList to configure its revealOrder: ' + '<SuspenseList revealOrder=...> ... ' + '<SuspenseList revealOrder=...>{%s}</SuspenseList> ... ' + '</SuspenseList>', type, index, type);\n\n return false;\n }\n }\n\n return true;\n}\n\nfunction validateSuspenseListChildren(children, revealOrder) {\n {\n if ((revealOrder === 'forwards' || revealOrder === 'backwards') && children !== undefined && children !== null && children !== false) {\n if (Array.isArray(children)) {\n for (var i = 0; i < children.length; i++) {\n if (!validateSuspenseListNestedChild(children[i], i)) {\n return;\n }\n }\n } else {\n var iteratorFn = getIteratorFn(children);\n\n if (typeof iteratorFn === 'function') {\n var childrenIterator = iteratorFn.call(children);\n\n if (childrenIterator) {\n var step = childrenIterator.next();\n var _i = 0;\n\n for (; !step.done; step = childrenIterator.next()) {\n if (!validateSuspenseListNestedChild(step.value, _i)) {\n return;\n }\n\n _i++;\n }\n }\n } else {\n error('A single row was passed to a <SuspenseList revealOrder=\"%s\" />. ' + 'This is not useful since it needs multiple rows. ' + 'Did you mean to pass multiple children or an array?', revealOrder);\n }\n }\n }\n }\n}\n\nfunction initSuspenseListRenderState(workInProgress, isBackwards, tail, lastContentRow, tailMode, lastEffectBeforeRendering) {\n var renderState = workInProgress.memoizedState;\n\n if (renderState === null) {\n workInProgress.memoizedState = {\n isBackwards: isBackwards,\n rendering: null,\n renderingStartTime: 0,\n last: lastContentRow,\n tail: tail,\n tailExpiration: 0,\n tailMode: tailMode,\n lastEffect: lastEffectBeforeRendering\n };\n } else {\n // We can reuse the existing object from previous renders.\n renderState.isBackwards = isBackwards;\n renderState.rendering = null;\n renderState.renderingStartTime = 0;\n renderState.last = lastContentRow;\n renderState.tail = tail;\n renderState.tailExpiration = 0;\n renderState.tailMode = tailMode;\n renderState.lastEffect = lastEffectBeforeRendering;\n }\n} // This can end up rendering this component multiple passes.\n// The first pass splits the children fibers into two sets. A head and tail.\n// We first render the head. If anything is in fallback state, we do another\n// pass through beginWork to rerender all children (including the tail) with\n// the force suspend context. If the first render didn't have anything in\n// in fallback state. Then we render each row in the tail one-by-one.\n// That happens in the completeWork phase without going back to beginWork.\n\n\nfunction updateSuspenseListComponent(current, workInProgress, renderExpirationTime) {\n var nextProps = workInProgress.pendingProps;\n var revealOrder = nextProps.revealOrder;\n var tailMode = nextProps.tail;\n var newChildren = nextProps.children;\n validateRevealOrder(revealOrder);\n validateTailOptions(tailMode, revealOrder);\n validateSuspenseListChildren(newChildren, revealOrder);\n reconcileChildren(current, workInProgress, newChildren, renderExpirationTime);\n var suspenseContext = suspenseStackCursor.current;\n var shouldForceFallback = hasSuspenseContext(suspenseContext, ForceSuspenseFallback);\n\n if (shouldForceFallback) {\n suspenseContext = setShallowSuspenseContext(suspenseContext, ForceSuspenseFallback);\n workInProgress.effectTag |= DidCapture;\n } else {\n var didSuspendBefore = current !== null && (current.effectTag & DidCapture) !== NoEffect;\n\n if (didSuspendBefore) {\n // If we previously forced a fallback, we need to schedule work\n // on any nested boundaries to let them know to try to render\n // again. This is the same as context updating.\n propagateSuspenseContextChange(workInProgress, workInProgress.child, renderExpirationTime);\n }\n\n suspenseContext = setDefaultShallowSuspenseContext(suspenseContext);\n }\n\n pushSuspenseContext(workInProgress, suspenseContext);\n\n if ((workInProgress.mode & BlockingMode) === NoMode) {\n // Outside of blocking mode, SuspenseList doesn't work so we just\n // use make it a noop by treating it as the default revealOrder.\n workInProgress.memoizedState = null;\n } else {\n switch (revealOrder) {\n case 'forwards':\n {\n var lastContentRow = findLastContentRow(workInProgress.child);\n var tail;\n\n if (lastContentRow === null) {\n // The whole list is part of the tail.\n // TODO: We could fast path by just rendering the tail now.\n tail = workInProgress.child;\n workInProgress.child = null;\n } else {\n // Disconnect the tail rows after the content row.\n // We're going to render them separately later.\n tail = lastContentRow.sibling;\n lastContentRow.sibling = null;\n }\n\n initSuspenseListRenderState(workInProgress, false, // isBackwards\n tail, lastContentRow, tailMode, workInProgress.lastEffect);\n break;\n }\n\n case 'backwards':\n {\n // We're going to find the first row that has existing content.\n // At the same time we're going to reverse the list of everything\n // we pass in the meantime. That's going to be our tail in reverse\n // order.\n var _tail = null;\n var row = workInProgress.child;\n workInProgress.child = null;\n\n while (row !== null) {\n var currentRow = row.alternate; // New rows can't be content rows.\n\n if (currentRow !== null && findFirstSuspended(currentRow) === null) {\n // This is the beginning of the main content.\n workInProgress.child = row;\n break;\n }\n\n var nextRow = row.sibling;\n row.sibling = _tail;\n _tail = row;\n row = nextRow;\n } // TODO: If workInProgress.child is null, we can continue on the tail immediately.\n\n\n initSuspenseListRenderState(workInProgress, true, // isBackwards\n _tail, null, // last\n tailMode, workInProgress.lastEffect);\n break;\n }\n\n case 'together':\n {\n initSuspenseListRenderState(workInProgress, false, // isBackwards\n null, // tail\n null, // last\n undefined, workInProgress.lastEffect);\n break;\n }\n\n default:\n {\n // The default reveal order is the same as not having\n // a boundary.\n workInProgress.memoizedState = null;\n }\n }\n }\n\n return workInProgress.child;\n}\n\nfunction updatePortalComponent(current, workInProgress, renderExpirationTime) {\n pushHostContainer(workInProgress, workInProgress.stateNode.containerInfo);\n var nextChildren = workInProgress.pendingProps;\n\n if (current === null) {\n // Portals are special because we don't append the children during mount\n // but at commit. Therefore we need to track insertions which the normal\n // flow doesn't do during mount. This doesn't happen at the root because\n // the root always starts with a \"current\" with a null child.\n // TODO: Consider unifying this with how the root works.\n workInProgress.child = reconcileChildFibers(workInProgress, null, nextChildren, renderExpirationTime);\n } else {\n reconcileChildren(current, workInProgress, nextChildren, renderExpirationTime);\n }\n\n return workInProgress.child;\n}\n\nfunction updateContextProvider(current, workInProgress, renderExpirationTime) {\n var providerType = workInProgress.type;\n var context = providerType._context;\n var newProps = workInProgress.pendingProps;\n var oldProps = workInProgress.memoizedProps;\n var newValue = newProps.value;\n\n {\n var providerPropTypes = workInProgress.type.propTypes;\n\n if (providerPropTypes) {\n checkPropTypes(providerPropTypes, newProps, 'prop', 'Context.Provider', getCurrentFiberStackInDev);\n }\n }\n\n pushProvider(workInProgress, newValue);\n\n if (oldProps !== null) {\n var oldValue = oldProps.value;\n var changedBits = calculateChangedBits(context, newValue, oldValue);\n\n if (changedBits === 0) {\n // No change. Bailout early if children are the same.\n if (oldProps.children === newProps.children && !hasContextChanged()) {\n return bailoutOnAlreadyFinishedWork(current, workInProgress, renderExpirationTime);\n }\n } else {\n // The context value changed. Search for matching consumers and schedule\n // them to update.\n propagateContextChange(workInProgress, context, changedBits, renderExpirationTime);\n }\n }\n\n var newChildren = newProps.children;\n reconcileChildren(current, workInProgress, newChildren, renderExpirationTime);\n return workInProgress.child;\n}\n\nvar hasWarnedAboutUsingContextAsConsumer = false;\n\nfunction updateContextConsumer(current, workInProgress, renderExpirationTime) {\n var context = workInProgress.type; // The logic below for Context differs depending on PROD or DEV mode. In\n // DEV mode, we create a separate object for Context.Consumer that acts\n // like a proxy to Context. This proxy object adds unnecessary code in PROD\n // so we use the old behaviour (Context.Consumer references Context) to\n // reduce size and overhead. The separate object references context via\n // a property called \"_context\", which also gives us the ability to check\n // in DEV mode if this property exists or not and warn if it does not.\n\n {\n if (context._context === undefined) {\n // This may be because it's a Context (rather than a Consumer).\n // Or it may be because it's older React where they're the same thing.\n // We only want to warn if we're sure it's a new React.\n if (context !== context.Consumer) {\n if (!hasWarnedAboutUsingContextAsConsumer) {\n hasWarnedAboutUsingContextAsConsumer = true;\n\n error('Rendering <Context> directly is not supported and will be removed in ' + 'a future major release. Did you mean to render <Context.Consumer> instead?');\n }\n }\n } else {\n context = context._context;\n }\n }\n\n var newProps = workInProgress.pendingProps;\n var render = newProps.children;\n\n {\n if (typeof render !== 'function') {\n error('A context consumer was rendered with multiple children, or a child ' + \"that isn't a function. A context consumer expects a single child \" + 'that is a function. If you did pass a function, make sure there ' + 'is no trailing or leading whitespace around it.');\n }\n }\n\n prepareToReadContext(workInProgress, renderExpirationTime);\n var newValue = readContext(context, newProps.unstable_observedBits);\n var newChildren;\n\n {\n ReactCurrentOwner$1.current = workInProgress;\n setIsRendering(true);\n newChildren = render(newValue);\n setIsRendering(false);\n } // React DevTools reads this flag.\n\n\n workInProgress.effectTag |= PerformedWork;\n reconcileChildren(current, workInProgress, newChildren, renderExpirationTime);\n return workInProgress.child;\n}\n\nfunction markWorkInProgressReceivedUpdate() {\n didReceiveUpdate = true;\n}\n\nfunction bailoutOnAlreadyFinishedWork(current, workInProgress, renderExpirationTime) {\n cancelWorkTimer(workInProgress);\n\n if (current !== null) {\n // Reuse previous dependencies\n workInProgress.dependencies = current.dependencies;\n }\n\n {\n // Don't update \"base\" render times for bailouts.\n stopProfilerTimerIfRunning();\n }\n\n var updateExpirationTime = workInProgress.expirationTime;\n\n if (updateExpirationTime !== NoWork) {\n markUnprocessedUpdateTime(updateExpirationTime);\n } // Check if the children have any pending work.\n\n\n var childExpirationTime = workInProgress.childExpirationTime;\n\n if (childExpirationTime < renderExpirationTime) {\n // The children don't have any work either. We can skip them.\n // TODO: Once we add back resuming, we should check if the children are\n // a work-in-progress set. If so, we need to transfer their effects.\n return null;\n } else {\n // This fiber doesn't have work, but its subtree does. Clone the child\n // fibers and continue.\n cloneChildFibers(current, workInProgress);\n return workInProgress.child;\n }\n}\n\nfunction remountFiber(current, oldWorkInProgress, newWorkInProgress) {\n {\n var returnFiber = oldWorkInProgress.return;\n\n if (returnFiber === null) {\n throw new Error('Cannot swap the root fiber.');\n } // Disconnect from the old current.\n // It will get deleted.\n\n\n current.alternate = null;\n oldWorkInProgress.alternate = null; // Connect to the new tree.\n\n newWorkInProgress.index = oldWorkInProgress.index;\n newWorkInProgress.sibling = oldWorkInProgress.sibling;\n newWorkInProgress.return = oldWorkInProgress.return;\n newWorkInProgress.ref = oldWorkInProgress.ref; // Replace the child/sibling pointers above it.\n\n if (oldWorkInProgress === returnFiber.child) {\n returnFiber.child = newWorkInProgress;\n } else {\n var prevSibling = returnFiber.child;\n\n if (prevSibling === null) {\n throw new Error('Expected parent to have a child.');\n }\n\n while (prevSibling.sibling !== oldWorkInProgress) {\n prevSibling = prevSibling.sibling;\n\n if (prevSibling === null) {\n throw new Error('Expected to find the previous sibling.');\n }\n }\n\n prevSibling.sibling = newWorkInProgress;\n } // Delete the old fiber and place the new one.\n // Since the old fiber is disconnected, we have to schedule it manually.\n\n\n var last = returnFiber.lastEffect;\n\n if (last !== null) {\n last.nextEffect = current;\n returnFiber.lastEffect = current;\n } else {\n returnFiber.firstEffect = returnFiber.lastEffect = current;\n }\n\n current.nextEffect = null;\n current.effectTag = Deletion;\n newWorkInProgress.effectTag |= Placement; // Restart work from the new fiber.\n\n return newWorkInProgress;\n }\n}\n\nfunction beginWork(current, workInProgress, renderExpirationTime) {\n var updateExpirationTime = workInProgress.expirationTime;\n\n {\n if (workInProgress._debugNeedsRemount && current !== null) {\n // This will restart the begin phase with a new fiber.\n return remountFiber(current, workInProgress, createFiberFromTypeAndProps(workInProgress.type, workInProgress.key, workInProgress.pendingProps, workInProgress._debugOwner || null, workInProgress.mode, workInProgress.expirationTime));\n }\n }\n\n if (current !== null) {\n var oldProps = current.memoizedProps;\n var newProps = workInProgress.pendingProps;\n\n if (oldProps !== newProps || hasContextChanged() || ( // Force a re-render if the implementation changed due to hot reload:\n workInProgress.type !== current.type )) {\n // If props or context changed, mark the fiber as having performed work.\n // This may be unset if the props are determined to be equal later (memo).\n didReceiveUpdate = true;\n } else if (updateExpirationTime < renderExpirationTime) {\n didReceiveUpdate = false; // This fiber does not have any pending work. Bailout without entering\n // the begin phase. There's still some bookkeeping we that needs to be done\n // in this optimized path, mostly pushing stuff onto the stack.\n\n switch (workInProgress.tag) {\n case HostRoot:\n pushHostRootContext(workInProgress);\n resetHydrationState();\n break;\n\n case HostComponent:\n pushHostContext(workInProgress);\n\n if (workInProgress.mode & ConcurrentMode && renderExpirationTime !== Never && shouldDeprioritizeSubtree(workInProgress.type, newProps)) {\n {\n markSpawnedWork(Never);\n } // Schedule this fiber to re-render at offscreen priority. Then bailout.\n\n\n workInProgress.expirationTime = workInProgress.childExpirationTime = Never;\n return null;\n }\n\n break;\n\n case ClassComponent:\n {\n var Component = workInProgress.type;\n\n if (isContextProvider(Component)) {\n pushContextProvider(workInProgress);\n }\n\n break;\n }\n\n case HostPortal:\n pushHostContainer(workInProgress, workInProgress.stateNode.containerInfo);\n break;\n\n case ContextProvider:\n {\n var newValue = workInProgress.memoizedProps.value;\n pushProvider(workInProgress, newValue);\n break;\n }\n\n case Profiler:\n {\n // Profiler should only call onRender when one of its descendants actually rendered.\n var hasChildWork = workInProgress.childExpirationTime >= renderExpirationTime;\n\n if (hasChildWork) {\n workInProgress.effectTag |= Update;\n }\n }\n\n break;\n\n case SuspenseComponent:\n {\n var state = workInProgress.memoizedState;\n\n if (state !== null) {\n // whether to retry the primary children, or to skip over it and\n // go straight to the fallback. Check the priority of the primary\n // child fragment.\n\n\n var primaryChildFragment = workInProgress.child;\n var primaryChildExpirationTime = primaryChildFragment.childExpirationTime;\n\n if (primaryChildExpirationTime !== NoWork && primaryChildExpirationTime >= renderExpirationTime) {\n // The primary children have pending work. Use the normal path\n // to attempt to render the primary children again.\n return updateSuspenseComponent(current, workInProgress, renderExpirationTime);\n } else {\n pushSuspenseContext(workInProgress, setDefaultShallowSuspenseContext(suspenseStackCursor.current)); // The primary children do not have pending work with sufficient\n // priority. Bailout.\n\n var child = bailoutOnAlreadyFinishedWork(current, workInProgress, renderExpirationTime);\n\n if (child !== null) {\n // The fallback children have pending work. Skip over the\n // primary children and work on the fallback.\n return child.sibling;\n } else {\n return null;\n }\n }\n } else {\n pushSuspenseContext(workInProgress, setDefaultShallowSuspenseContext(suspenseStackCursor.current));\n }\n\n break;\n }\n\n case SuspenseListComponent:\n {\n var didSuspendBefore = (current.effectTag & DidCapture) !== NoEffect;\n\n var _hasChildWork = workInProgress.childExpirationTime >= renderExpirationTime;\n\n if (didSuspendBefore) {\n if (_hasChildWork) {\n // If something was in fallback state last time, and we have all the\n // same children then we're still in progressive loading state.\n // Something might get unblocked by state updates or retries in the\n // tree which will affect the tail. So we need to use the normal\n // path to compute the correct tail.\n return updateSuspenseListComponent(current, workInProgress, renderExpirationTime);\n } // If none of the children had any work, that means that none of\n // them got retried so they'll still be blocked in the same way\n // as before. We can fast bail out.\n\n\n workInProgress.effectTag |= DidCapture;\n } // If nothing suspended before and we're rendering the same children,\n // then the tail doesn't matter. Anything new that suspends will work\n // in the \"together\" mode, so we can continue from the state we had.\n\n\n var renderState = workInProgress.memoizedState;\n\n if (renderState !== null) {\n // Reset to the \"together\" mode in case we've started a different\n // update in the past but didn't complete it.\n renderState.rendering = null;\n renderState.tail = null;\n }\n\n pushSuspenseContext(workInProgress, suspenseStackCursor.current);\n\n if (_hasChildWork) {\n break;\n } else {\n // If none of the children had any work, that means that none of\n // them got retried so they'll still be blocked in the same way\n // as before. We can fast bail out.\n return null;\n }\n }\n }\n\n return bailoutOnAlreadyFinishedWork(current, workInProgress, renderExpirationTime);\n } else {\n // An update was scheduled on this fiber, but there are no new props\n // nor legacy context. Set this to false. If an update queue or context\n // consumer produces a changed value, it will set this to true. Otherwise,\n // the component will assume the children have not changed and bail out.\n didReceiveUpdate = false;\n }\n } else {\n didReceiveUpdate = false;\n } // Before entering the begin phase, clear pending update priority.\n // TODO: This assumes that we're about to evaluate the component and process\n // the update queue. However, there's an exception: SimpleMemoComponent\n // sometimes bails out later in the begin phase. This indicates that we should\n // move this assignment out of the common path and into each branch.\n\n\n workInProgress.expirationTime = NoWork;\n\n switch (workInProgress.tag) {\n case IndeterminateComponent:\n {\n return mountIndeterminateComponent(current, workInProgress, workInProgress.type, renderExpirationTime);\n }\n\n case LazyComponent:\n {\n var elementType = workInProgress.elementType;\n return mountLazyComponent(current, workInProgress, elementType, updateExpirationTime, renderExpirationTime);\n }\n\n case FunctionComponent:\n {\n var _Component = workInProgress.type;\n var unresolvedProps = workInProgress.pendingProps;\n var resolvedProps = workInProgress.elementType === _Component ? unresolvedProps : resolveDefaultProps(_Component, unresolvedProps);\n return updateFunctionComponent(current, workInProgress, _Component, resolvedProps, renderExpirationTime);\n }\n\n case ClassComponent:\n {\n var _Component2 = workInProgress.type;\n var _unresolvedProps = workInProgress.pendingProps;\n\n var _resolvedProps = workInProgress.elementType === _Component2 ? _unresolvedProps : resolveDefaultProps(_Component2, _unresolvedProps);\n\n return updateClassComponent(current, workInProgress, _Component2, _resolvedProps, renderExpirationTime);\n }\n\n case HostRoot:\n return updateHostRoot(current, workInProgress, renderExpirationTime);\n\n case HostComponent:\n return updateHostComponent(current, workInProgress, renderExpirationTime);\n\n case HostText:\n return updateHostText(current, workInProgress);\n\n case SuspenseComponent:\n return updateSuspenseComponent(current, workInProgress, renderExpirationTime);\n\n case HostPortal:\n return updatePortalComponent(current, workInProgress, renderExpirationTime);\n\n case ForwardRef:\n {\n var type = workInProgress.type;\n var _unresolvedProps2 = workInProgress.pendingProps;\n\n var _resolvedProps2 = workInProgress.elementType === type ? _unresolvedProps2 : resolveDefaultProps(type, _unresolvedProps2);\n\n return updateForwardRef(current, workInProgress, type, _resolvedProps2, renderExpirationTime);\n }\n\n case Fragment:\n return updateFragment(current, workInProgress, renderExpirationTime);\n\n case Mode:\n return updateMode(current, workInProgress, renderExpirationTime);\n\n case Profiler:\n return updateProfiler(current, workInProgress, renderExpirationTime);\n\n case ContextProvider:\n return updateContextProvider(current, workInProgress, renderExpirationTime);\n\n case ContextConsumer:\n return updateContextConsumer(current, workInProgress, renderExpirationTime);\n\n case MemoComponent:\n {\n var _type2 = workInProgress.type;\n var _unresolvedProps3 = workInProgress.pendingProps; // Resolve outer props first, then resolve inner props.\n\n var _resolvedProps3 = resolveDefaultProps(_type2, _unresolvedProps3);\n\n {\n if (workInProgress.type !== workInProgress.elementType) {\n var outerPropTypes = _type2.propTypes;\n\n if (outerPropTypes) {\n checkPropTypes(outerPropTypes, _resolvedProps3, // Resolved for outer only\n 'prop', getComponentName(_type2), getCurrentFiberStackInDev);\n }\n }\n }\n\n _resolvedProps3 = resolveDefaultProps(_type2.type, _resolvedProps3);\n return updateMemoComponent(current, workInProgress, _type2, _resolvedProps3, updateExpirationTime, renderExpirationTime);\n }\n\n case SimpleMemoComponent:\n {\n return updateSimpleMemoComponent(current, workInProgress, workInProgress.type, workInProgress.pendingProps, updateExpirationTime, renderExpirationTime);\n }\n\n case IncompleteClassComponent:\n {\n var _Component3 = workInProgress.type;\n var _unresolvedProps4 = workInProgress.pendingProps;\n\n var _resolvedProps4 = workInProgress.elementType === _Component3 ? _unresolvedProps4 : resolveDefaultProps(_Component3, _unresolvedProps4);\n\n return mountIncompleteClassComponent(current, workInProgress, _Component3, _resolvedProps4, renderExpirationTime);\n }\n\n case SuspenseListComponent:\n {\n return updateSuspenseListComponent(current, workInProgress, renderExpirationTime);\n }\n }\n\n {\n {\n throw Error( \"Unknown unit of work tag (\" + workInProgress.tag + \"). This error is likely caused by a bug in React. Please file an issue.\" );\n }\n }\n}\n\nfunction markUpdate(workInProgress) {\n // Tag the fiber with an update effect. This turns a Placement into\n // a PlacementAndUpdate.\n workInProgress.effectTag |= Update;\n}\n\nfunction markRef$1(workInProgress) {\n workInProgress.effectTag |= Ref;\n}\n\nvar appendAllChildren;\nvar updateHostContainer;\nvar updateHostComponent$1;\nvar updateHostText$1;\n\n{\n // Mutation mode\n appendAllChildren = function (parent, workInProgress, needsVisibilityToggle, isHidden) {\n // We only have the top Fiber that was created but we need recurse down its\n // children to find all the terminal nodes.\n var node = workInProgress.child;\n\n while (node !== null) {\n if (node.tag === HostComponent || node.tag === HostText) {\n appendInitialChild(parent, node.stateNode);\n } else if (node.tag === HostPortal) ; else if (node.child !== null) {\n node.child.return = node;\n node = node.child;\n continue;\n }\n\n if (node === workInProgress) {\n return;\n }\n\n while (node.sibling === null) {\n if (node.return === null || node.return === workInProgress) {\n return;\n }\n\n node = node.return;\n }\n\n node.sibling.return = node.return;\n node = node.sibling;\n }\n };\n\n updateHostContainer = function (workInProgress) {// Noop\n };\n\n updateHostComponent$1 = function (current, workInProgress, type, newProps, rootContainerInstance) {\n // If we have an alternate, that means this is an update and we need to\n // schedule a side-effect to do the updates.\n var oldProps = current.memoizedProps;\n\n if (oldProps === newProps) {\n // In mutation mode, this is sufficient for a bailout because\n // we won't touch this node even if children changed.\n return;\n } // If we get updated because one of our children updated, we don't\n // have newProps so we'll have to reuse them.\n // TODO: Split the update API as separate for the props vs. children.\n // Even better would be if children weren't special cased at all tho.\n\n\n var instance = workInProgress.stateNode;\n var currentHostContext = getHostContext(); // TODO: Experiencing an error where oldProps is null. Suggests a host\n // component is hitting the resume path. Figure out why. Possibly\n // related to `hidden`.\n\n var updatePayload = prepareUpdate(instance, type, oldProps, newProps, rootContainerInstance, currentHostContext); // TODO: Type this specific to this type of component.\n\n workInProgress.updateQueue = updatePayload; // If the update payload indicates that there is a change or if there\n // is a new ref we mark this as an update. All the work is done in commitWork.\n\n if (updatePayload) {\n markUpdate(workInProgress);\n }\n };\n\n updateHostText$1 = function (current, workInProgress, oldText, newText) {\n // If the text differs, mark it as an update. All the work in done in commitWork.\n if (oldText !== newText) {\n markUpdate(workInProgress);\n }\n };\n}\n\nfunction cutOffTailIfNeeded(renderState, hasRenderedATailFallback) {\n switch (renderState.tailMode) {\n case 'hidden':\n {\n // Any insertions at the end of the tail list after this point\n // should be invisible. If there are already mounted boundaries\n // anything before them are not considered for collapsing.\n // Therefore we need to go through the whole tail to find if\n // there are any.\n var tailNode = renderState.tail;\n var lastTailNode = null;\n\n while (tailNode !== null) {\n if (tailNode.alternate !== null) {\n lastTailNode = tailNode;\n }\n\n tailNode = tailNode.sibling;\n } // Next we're simply going to delete all insertions after the\n // last rendered item.\n\n\n if (lastTailNode === null) {\n // All remaining items in the tail are insertions.\n renderState.tail = null;\n } else {\n // Detach the insertion after the last node that was already\n // inserted.\n lastTailNode.sibling = null;\n }\n\n break;\n }\n\n case 'collapsed':\n {\n // Any insertions at the end of the tail list after this point\n // should be invisible. If there are already mounted boundaries\n // anything before them are not considered for collapsing.\n // Therefore we need to go through the whole tail to find if\n // there are any.\n var _tailNode = renderState.tail;\n var _lastTailNode = null;\n\n while (_tailNode !== null) {\n if (_tailNode.alternate !== null) {\n _lastTailNode = _tailNode;\n }\n\n _tailNode = _tailNode.sibling;\n } // Next we're simply going to delete all insertions after the\n // last rendered item.\n\n\n if (_lastTailNode === null) {\n // All remaining items in the tail are insertions.\n if (!hasRenderedATailFallback && renderState.tail !== null) {\n // We suspended during the head. We want to show at least one\n // row at the tail. So we'll keep on and cut off the rest.\n renderState.tail.sibling = null;\n } else {\n renderState.tail = null;\n }\n } else {\n // Detach the insertion after the last node that was already\n // inserted.\n _lastTailNode.sibling = null;\n }\n\n break;\n }\n }\n}\n\nfunction completeWork(current, workInProgress, renderExpirationTime) {\n var newProps = workInProgress.pendingProps;\n\n switch (workInProgress.tag) {\n case IndeterminateComponent:\n case LazyComponent:\n case SimpleMemoComponent:\n case FunctionComponent:\n case ForwardRef:\n case Fragment:\n case Mode:\n case Profiler:\n case ContextConsumer:\n case MemoComponent:\n return null;\n\n case ClassComponent:\n {\n var Component = workInProgress.type;\n\n if (isContextProvider(Component)) {\n popContext(workInProgress);\n }\n\n return null;\n }\n\n case HostRoot:\n {\n popHostContainer(workInProgress);\n popTopLevelContextObject(workInProgress);\n var fiberRoot = workInProgress.stateNode;\n\n if (fiberRoot.pendingContext) {\n fiberRoot.context = fiberRoot.pendingContext;\n fiberRoot.pendingContext = null;\n }\n\n if (current === null || current.child === null) {\n // If we hydrated, pop so that we can delete any remaining children\n // that weren't hydrated.\n var wasHydrated = popHydrationState(workInProgress);\n\n if (wasHydrated) {\n // If we hydrated, then we'll need to schedule an update for\n // the commit side-effects on the root.\n markUpdate(workInProgress);\n }\n }\n\n updateHostContainer(workInProgress);\n return null;\n }\n\n case HostComponent:\n {\n popHostContext(workInProgress);\n var rootContainerInstance = getRootHostContainer();\n var type = workInProgress.type;\n\n if (current !== null && workInProgress.stateNode != null) {\n updateHostComponent$1(current, workInProgress, type, newProps, rootContainerInstance);\n\n if (current.ref !== workInProgress.ref) {\n markRef$1(workInProgress);\n }\n } else {\n if (!newProps) {\n if (!(workInProgress.stateNode !== null)) {\n {\n throw Error( \"We must have new props for new mounts. This error is likely caused by a bug in React. Please file an issue.\" );\n }\n } // This can happen when we abort work.\n\n\n return null;\n }\n\n var currentHostContext = getHostContext(); // TODO: Move createInstance to beginWork and keep it on a context\n // \"stack\" as the parent. Then append children as we go in beginWork\n // or completeWork depending on whether we want to add them top->down or\n // bottom->up. Top->down is faster in IE11.\n\n var _wasHydrated = popHydrationState(workInProgress);\n\n if (_wasHydrated) {\n // TODO: Move this and createInstance step into the beginPhase\n // to consolidate.\n if (prepareToHydrateHostInstance(workInProgress, rootContainerInstance, currentHostContext)) {\n // If changes to the hydrated node need to be applied at the\n // commit-phase we mark this as such.\n markUpdate(workInProgress);\n }\n } else {\n var instance = createInstance(type, newProps, rootContainerInstance, currentHostContext, workInProgress);\n appendAllChildren(instance, workInProgress, false, false); // This needs to be set before we mount Flare event listeners\n\n workInProgress.stateNode = instance;\n // (eg DOM renderer supports auto-focus for certain elements).\n // Make sure such renderers get scheduled for later work.\n\n\n if (finalizeInitialChildren(instance, type, newProps, rootContainerInstance)) {\n markUpdate(workInProgress);\n }\n }\n\n if (workInProgress.ref !== null) {\n // If there is a ref on a host node we need to schedule a callback\n markRef$1(workInProgress);\n }\n }\n\n return null;\n }\n\n case HostText:\n {\n var newText = newProps;\n\n if (current && workInProgress.stateNode != null) {\n var oldText = current.memoizedProps; // If we have an alternate, that means this is an update and we need\n // to schedule a side-effect to do the updates.\n\n updateHostText$1(current, workInProgress, oldText, newText);\n } else {\n if (typeof newText !== 'string') {\n if (!(workInProgress.stateNode !== null)) {\n {\n throw Error( \"We must have new props for new mounts. This error is likely caused by a bug in React. Please file an issue.\" );\n }\n } // This can happen when we abort work.\n\n }\n\n var _rootContainerInstance = getRootHostContainer();\n\n var _currentHostContext = getHostContext();\n\n var _wasHydrated2 = popHydrationState(workInProgress);\n\n if (_wasHydrated2) {\n if (prepareToHydrateHostTextInstance(workInProgress)) {\n markUpdate(workInProgress);\n }\n } else {\n workInProgress.stateNode = createTextInstance(newText, _rootContainerInstance, _currentHostContext, workInProgress);\n }\n }\n\n return null;\n }\n\n case SuspenseComponent:\n {\n popSuspenseContext(workInProgress);\n var nextState = workInProgress.memoizedState;\n\n if ((workInProgress.effectTag & DidCapture) !== NoEffect) {\n // Something suspended. Re-render with the fallback children.\n workInProgress.expirationTime = renderExpirationTime; // Do not reset the effect list.\n\n return workInProgress;\n }\n\n var nextDidTimeout = nextState !== null;\n var prevDidTimeout = false;\n\n if (current === null) {\n if (workInProgress.memoizedProps.fallback !== undefined) {\n popHydrationState(workInProgress);\n }\n } else {\n var prevState = current.memoizedState;\n prevDidTimeout = prevState !== null;\n\n if (!nextDidTimeout && prevState !== null) {\n // We just switched from the fallback to the normal children.\n // Delete the fallback.\n // TODO: Would it be better to store the fallback fragment on\n // the stateNode during the begin phase?\n var currentFallbackChild = current.child.sibling;\n\n if (currentFallbackChild !== null) {\n // Deletions go at the beginning of the return fiber's effect list\n var first = workInProgress.firstEffect;\n\n if (first !== null) {\n workInProgress.firstEffect = currentFallbackChild;\n currentFallbackChild.nextEffect = first;\n } else {\n workInProgress.firstEffect = workInProgress.lastEffect = currentFallbackChild;\n currentFallbackChild.nextEffect = null;\n }\n\n currentFallbackChild.effectTag = Deletion;\n }\n }\n }\n\n if (nextDidTimeout && !prevDidTimeout) {\n // If this subtreee is running in blocking mode we can suspend,\n // otherwise we won't suspend.\n // TODO: This will still suspend a synchronous tree if anything\n // in the concurrent tree already suspended during this render.\n // This is a known bug.\n if ((workInProgress.mode & BlockingMode) !== NoMode) {\n // TODO: Move this back to throwException because this is too late\n // if this is a large tree which is common for initial loads. We\n // don't know if we should restart a render or not until we get\n // this marker, and this is too late.\n // If this render already had a ping or lower pri updates,\n // and this is the first time we know we're going to suspend we\n // should be able to immediately restart from within throwException.\n var hasInvisibleChildContext = current === null && workInProgress.memoizedProps.unstable_avoidThisFallback !== true;\n\n if (hasInvisibleChildContext || hasSuspenseContext(suspenseStackCursor.current, InvisibleParentSuspenseContext)) {\n // If this was in an invisible tree or a new render, then showing\n // this boundary is ok.\n renderDidSuspend();\n } else {\n // Otherwise, we're going to have to hide content so we should\n // suspend for longer if possible.\n renderDidSuspendDelayIfPossible();\n }\n }\n }\n\n {\n // TODO: Only schedule updates if these values are non equal, i.e. it changed.\n if (nextDidTimeout || prevDidTimeout) {\n // If this boundary just timed out, schedule an effect to attach a\n // retry listener to the promise. This flag is also used to hide the\n // primary children. In mutation mode, we also need the flag to\n // *unhide* children that were previously hidden, so check if this\n // is currently timed out, too.\n workInProgress.effectTag |= Update;\n }\n }\n\n return null;\n }\n\n case HostPortal:\n popHostContainer(workInProgress);\n updateHostContainer(workInProgress);\n return null;\n\n case ContextProvider:\n // Pop provider fiber\n popProvider(workInProgress);\n return null;\n\n case IncompleteClassComponent:\n {\n // Same as class component case. I put it down here so that the tags are\n // sequential to ensure this switch is compiled to a jump table.\n var _Component = workInProgress.type;\n\n if (isContextProvider(_Component)) {\n popContext(workInProgress);\n }\n\n return null;\n }\n\n case SuspenseListComponent:\n {\n popSuspenseContext(workInProgress);\n var renderState = workInProgress.memoizedState;\n\n if (renderState === null) {\n // We're running in the default, \"independent\" mode.\n // We don't do anything in this mode.\n return null;\n }\n\n var didSuspendAlready = (workInProgress.effectTag & DidCapture) !== NoEffect;\n var renderedTail = renderState.rendering;\n\n if (renderedTail === null) {\n // We just rendered the head.\n if (!didSuspendAlready) {\n // This is the first pass. We need to figure out if anything is still\n // suspended in the rendered set.\n // If new content unsuspended, but there's still some content that\n // didn't. Then we need to do a second pass that forces everything\n // to keep showing their fallbacks.\n // We might be suspended if something in this render pass suspended, or\n // something in the previous committed pass suspended. Otherwise,\n // there's no chance so we can skip the expensive call to\n // findFirstSuspended.\n var cannotBeSuspended = renderHasNotSuspendedYet() && (current === null || (current.effectTag & DidCapture) === NoEffect);\n\n if (!cannotBeSuspended) {\n var row = workInProgress.child;\n\n while (row !== null) {\n var suspended = findFirstSuspended(row);\n\n if (suspended !== null) {\n didSuspendAlready = true;\n workInProgress.effectTag |= DidCapture;\n cutOffTailIfNeeded(renderState, false); // If this is a newly suspended tree, it might not get committed as\n // part of the second pass. In that case nothing will subscribe to\n // its thennables. Instead, we'll transfer its thennables to the\n // SuspenseList so that it can retry if they resolve.\n // There might be multiple of these in the list but since we're\n // going to wait for all of them anyway, it doesn't really matter\n // which ones gets to ping. In theory we could get clever and keep\n // track of how many dependencies remain but it gets tricky because\n // in the meantime, we can add/remove/change items and dependencies.\n // We might bail out of the loop before finding any but that\n // doesn't matter since that means that the other boundaries that\n // we did find already has their listeners attached.\n\n var newThennables = suspended.updateQueue;\n\n if (newThennables !== null) {\n workInProgress.updateQueue = newThennables;\n workInProgress.effectTag |= Update;\n } // Rerender the whole list, but this time, we'll force fallbacks\n // to stay in place.\n // Reset the effect list before doing the second pass since that's now invalid.\n\n\n if (renderState.lastEffect === null) {\n workInProgress.firstEffect = null;\n }\n\n workInProgress.lastEffect = renderState.lastEffect; // Reset the child fibers to their original state.\n\n resetChildFibers(workInProgress, renderExpirationTime); // Set up the Suspense Context to force suspense and immediately\n // rerender the children.\n\n pushSuspenseContext(workInProgress, setShallowSuspenseContext(suspenseStackCursor.current, ForceSuspenseFallback));\n return workInProgress.child;\n }\n\n row = row.sibling;\n }\n }\n } else {\n cutOffTailIfNeeded(renderState, false);\n } // Next we're going to render the tail.\n\n } else {\n // Append the rendered row to the child list.\n if (!didSuspendAlready) {\n var _suspended = findFirstSuspended(renderedTail);\n\n if (_suspended !== null) {\n workInProgress.effectTag |= DidCapture;\n didSuspendAlready = true; // Ensure we transfer the update queue to the parent so that it doesn't\n // get lost if this row ends up dropped during a second pass.\n\n var _newThennables = _suspended.updateQueue;\n\n if (_newThennables !== null) {\n workInProgress.updateQueue = _newThennables;\n workInProgress.effectTag |= Update;\n }\n\n cutOffTailIfNeeded(renderState, true); // This might have been modified.\n\n if (renderState.tail === null && renderState.tailMode === 'hidden' && !renderedTail.alternate) {\n // We need to delete the row we just rendered.\n // Reset the effect list to what it was before we rendered this\n // child. The nested children have already appended themselves.\n var lastEffect = workInProgress.lastEffect = renderState.lastEffect; // Remove any effects that were appended after this point.\n\n if (lastEffect !== null) {\n lastEffect.nextEffect = null;\n } // We're done.\n\n\n return null;\n }\n } else if ( // The time it took to render last row is greater than time until\n // the expiration.\n now() * 2 - renderState.renderingStartTime > renderState.tailExpiration && renderExpirationTime > Never) {\n // We have now passed our CPU deadline and we'll just give up further\n // attempts to render the main content and only render fallbacks.\n // The assumption is that this is usually faster.\n workInProgress.effectTag |= DidCapture;\n didSuspendAlready = true;\n cutOffTailIfNeeded(renderState, false); // Since nothing actually suspended, there will nothing to ping this\n // to get it started back up to attempt the next item. If we can show\n // them, then they really have the same priority as this render.\n // So we'll pick it back up the very next render pass once we've had\n // an opportunity to yield for paint.\n\n var nextPriority = renderExpirationTime - 1;\n workInProgress.expirationTime = workInProgress.childExpirationTime = nextPriority;\n\n {\n markSpawnedWork(nextPriority);\n }\n }\n }\n\n if (renderState.isBackwards) {\n // The effect list of the backwards tail will have been added\n // to the end. This breaks the guarantee that life-cycles fire in\n // sibling order but that isn't a strong guarantee promised by React.\n // Especially since these might also just pop in during future commits.\n // Append to the beginning of the list.\n renderedTail.sibling = workInProgress.child;\n workInProgress.child = renderedTail;\n } else {\n var previousSibling = renderState.last;\n\n if (previousSibling !== null) {\n previousSibling.sibling = renderedTail;\n } else {\n workInProgress.child = renderedTail;\n }\n\n renderState.last = renderedTail;\n }\n }\n\n if (renderState.tail !== null) {\n // We still have tail rows to render.\n if (renderState.tailExpiration === 0) {\n // Heuristic for how long we're willing to spend rendering rows\n // until we just give up and show what we have so far.\n var TAIL_EXPIRATION_TIMEOUT_MS = 500;\n renderState.tailExpiration = now() + TAIL_EXPIRATION_TIMEOUT_MS; // TODO: This is meant to mimic the train model or JND but this\n // is a per component value. It should really be since the start\n // of the total render or last commit. Consider using something like\n // globalMostRecentFallbackTime. That doesn't account for being\n // suspended for part of the time or when it's a new render.\n // It should probably use a global start time value instead.\n } // Pop a row.\n\n\n var next = renderState.tail;\n renderState.rendering = next;\n renderState.tail = next.sibling;\n renderState.lastEffect = workInProgress.lastEffect;\n renderState.renderingStartTime = now();\n next.sibling = null; // Restore the context.\n // TODO: We can probably just avoid popping it instead and only\n // setting it the first time we go from not suspended to suspended.\n\n var suspenseContext = suspenseStackCursor.current;\n\n if (didSuspendAlready) {\n suspenseContext = setShallowSuspenseContext(suspenseContext, ForceSuspenseFallback);\n } else {\n suspenseContext = setDefaultShallowSuspenseContext(suspenseContext);\n }\n\n pushSuspenseContext(workInProgress, suspenseContext); // Do a pass over the next row.\n\n return next;\n }\n\n return null;\n }\n }\n\n {\n {\n throw Error( \"Unknown unit of work tag (\" + workInProgress.tag + \"). This error is likely caused by a bug in React. Please file an issue.\" );\n }\n }\n}\n\nfunction unwindWork(workInProgress, renderExpirationTime) {\n switch (workInProgress.tag) {\n case ClassComponent:\n {\n var Component = workInProgress.type;\n\n if (isContextProvider(Component)) {\n popContext(workInProgress);\n }\n\n var effectTag = workInProgress.effectTag;\n\n if (effectTag & ShouldCapture) {\n workInProgress.effectTag = effectTag & ~ShouldCapture | DidCapture;\n return workInProgress;\n }\n\n return null;\n }\n\n case HostRoot:\n {\n popHostContainer(workInProgress);\n popTopLevelContextObject(workInProgress);\n var _effectTag = workInProgress.effectTag;\n\n if (!((_effectTag & DidCapture) === NoEffect)) {\n {\n throw Error( \"The root failed to unmount after an error. This is likely a bug in React. Please file an issue.\" );\n }\n }\n\n workInProgress.effectTag = _effectTag & ~ShouldCapture | DidCapture;\n return workInProgress;\n }\n\n case HostComponent:\n {\n // TODO: popHydrationState\n popHostContext(workInProgress);\n return null;\n }\n\n case SuspenseComponent:\n {\n popSuspenseContext(workInProgress);\n\n var _effectTag2 = workInProgress.effectTag;\n\n if (_effectTag2 & ShouldCapture) {\n workInProgress.effectTag = _effectTag2 & ~ShouldCapture | DidCapture; // Captured a suspense effect. Re-render the boundary.\n\n return workInProgress;\n }\n\n return null;\n }\n\n case SuspenseListComponent:\n {\n popSuspenseContext(workInProgress); // SuspenseList doesn't actually catch anything. It should've been\n // caught by a nested boundary. If not, it should bubble through.\n\n return null;\n }\n\n case HostPortal:\n popHostContainer(workInProgress);\n return null;\n\n case ContextProvider:\n popProvider(workInProgress);\n return null;\n\n default:\n return null;\n }\n}\n\nfunction unwindInterruptedWork(interruptedWork) {\n switch (interruptedWork.tag) {\n case ClassComponent:\n {\n var childContextTypes = interruptedWork.type.childContextTypes;\n\n if (childContextTypes !== null && childContextTypes !== undefined) {\n popContext(interruptedWork);\n }\n\n break;\n }\n\n case HostRoot:\n {\n popHostContainer(interruptedWork);\n popTopLevelContextObject(interruptedWork);\n break;\n }\n\n case HostComponent:\n {\n popHostContext(interruptedWork);\n break;\n }\n\n case HostPortal:\n popHostContainer(interruptedWork);\n break;\n\n case SuspenseComponent:\n popSuspenseContext(interruptedWork);\n break;\n\n case SuspenseListComponent:\n popSuspenseContext(interruptedWork);\n break;\n\n case ContextProvider:\n popProvider(interruptedWork);\n break;\n }\n}\n\nfunction createCapturedValue(value, source) {\n // If the value is an error, call this function immediately after it is thrown\n // so the stack is accurate.\n return {\n value: value,\n source: source,\n stack: getStackByFiberInDevAndProd(source)\n };\n}\n\nfunction logCapturedError(capturedError) {\n\n var error = capturedError.error;\n\n {\n var componentName = capturedError.componentName,\n componentStack = capturedError.componentStack,\n errorBoundaryName = capturedError.errorBoundaryName,\n errorBoundaryFound = capturedError.errorBoundaryFound,\n willRetry = capturedError.willRetry; // Browsers support silencing uncaught errors by calling\n // `preventDefault()` in window `error` handler.\n // We record this information as an expando on the error.\n\n if (error != null && error._suppressLogging) {\n if (errorBoundaryFound && willRetry) {\n // The error is recoverable and was silenced.\n // Ignore it and don't print the stack addendum.\n // This is handy for testing error boundaries without noise.\n return;\n } // The error is fatal. Since the silencing might have\n // been accidental, we'll surface it anyway.\n // However, the browser would have silenced the original error\n // so we'll print it first, and then print the stack addendum.\n\n\n console['error'](error); // Don't transform to our wrapper\n // For a more detailed description of this block, see:\n // https://github.com/facebook/react/pull/13384\n }\n\n var componentNameMessage = componentName ? \"The above error occurred in the <\" + componentName + \"> component:\" : 'The above error occurred in one of your React components:';\n var errorBoundaryMessage; // errorBoundaryFound check is sufficient; errorBoundaryName check is to satisfy Flow.\n\n if (errorBoundaryFound && errorBoundaryName) {\n if (willRetry) {\n errorBoundaryMessage = \"React will try to recreate this component tree from scratch \" + (\"using the error boundary you provided, \" + errorBoundaryName + \".\");\n } else {\n errorBoundaryMessage = \"This error was initially handled by the error boundary \" + errorBoundaryName + \".\\n\" + \"Recreating the tree from scratch failed so React will unmount the tree.\";\n }\n } else {\n errorBoundaryMessage = 'Consider adding an error boundary to your tree to customize error handling behavior.\\n' + 'Visit https://fb.me/react-error-boundaries to learn more about error boundaries.';\n }\n\n var combinedMessage = \"\" + componentNameMessage + componentStack + \"\\n\\n\" + (\"\" + errorBoundaryMessage); // In development, we provide our own message with just the component stack.\n // We don't include the original error message and JS stack because the browser\n // has already printed it. Even if the application swallows the error, it is still\n // displayed by the browser thanks to the DEV-only fake event trick in ReactErrorUtils.\n\n console['error'](combinedMessage); // Don't transform to our wrapper\n }\n}\n\nvar didWarnAboutUndefinedSnapshotBeforeUpdate = null;\n\n{\n didWarnAboutUndefinedSnapshotBeforeUpdate = new Set();\n}\n\nvar PossiblyWeakSet = typeof WeakSet === 'function' ? WeakSet : Set;\nfunction logError(boundary, errorInfo) {\n var source = errorInfo.source;\n var stack = errorInfo.stack;\n\n if (stack === null && source !== null) {\n stack = getStackByFiberInDevAndProd(source);\n }\n\n var capturedError = {\n componentName: source !== null ? getComponentName(source.type) : null,\n componentStack: stack !== null ? stack : '',\n error: errorInfo.value,\n errorBoundary: null,\n errorBoundaryName: null,\n errorBoundaryFound: false,\n willRetry: false\n };\n\n if (boundary !== null && boundary.tag === ClassComponent) {\n capturedError.errorBoundary = boundary.stateNode;\n capturedError.errorBoundaryName = getComponentName(boundary.type);\n capturedError.errorBoundaryFound = true;\n capturedError.willRetry = true;\n }\n\n try {\n logCapturedError(capturedError);\n } catch (e) {\n // This method must not throw, or React internal state will get messed up.\n // If console.error is overridden, or logCapturedError() shows a dialog that throws,\n // we want to report this error outside of the normal stack as a last resort.\n // https://github.com/facebook/react/issues/13188\n setTimeout(function () {\n throw e;\n });\n }\n}\n\nvar callComponentWillUnmountWithTimer = function (current, instance) {\n startPhaseTimer(current, 'componentWillUnmount');\n instance.props = current.memoizedProps;\n instance.state = current.memoizedState;\n instance.componentWillUnmount();\n stopPhaseTimer();\n}; // Capture errors so they don't interrupt unmounting.\n\n\nfunction safelyCallComponentWillUnmount(current, instance) {\n {\n invokeGuardedCallback(null, callComponentWillUnmountWithTimer, null, current, instance);\n\n if (hasCaughtError()) {\n var unmountError = clearCaughtError();\n captureCommitPhaseError(current, unmountError);\n }\n }\n}\n\nfunction safelyDetachRef(current) {\n var ref = current.ref;\n\n if (ref !== null) {\n if (typeof ref === 'function') {\n {\n invokeGuardedCallback(null, ref, null, null);\n\n if (hasCaughtError()) {\n var refError = clearCaughtError();\n captureCommitPhaseError(current, refError);\n }\n }\n } else {\n ref.current = null;\n }\n }\n}\n\nfunction safelyCallDestroy(current, destroy) {\n {\n invokeGuardedCallback(null, destroy, null);\n\n if (hasCaughtError()) {\n var error = clearCaughtError();\n captureCommitPhaseError(current, error);\n }\n }\n}\n\nfunction commitBeforeMutationLifeCycles(current, finishedWork) {\n switch (finishedWork.tag) {\n case FunctionComponent:\n case ForwardRef:\n case SimpleMemoComponent:\n case Block:\n {\n return;\n }\n\n case ClassComponent:\n {\n if (finishedWork.effectTag & Snapshot) {\n if (current !== null) {\n var prevProps = current.memoizedProps;\n var prevState = current.memoizedState;\n startPhaseTimer(finishedWork, 'getSnapshotBeforeUpdate');\n var instance = finishedWork.stateNode; // We could update instance props and state here,\n // but instead we rely on them being set during last render.\n // TODO: revisit this when we implement resuming.\n\n {\n if (finishedWork.type === finishedWork.elementType && !didWarnAboutReassigningProps) {\n if (instance.props !== finishedWork.memoizedProps) {\n error('Expected %s props to match memoized props before ' + 'getSnapshotBeforeUpdate. ' + 'This might either be because of a bug in React, or because ' + 'a component reassigns its own `this.props`. ' + 'Please file an issue.', getComponentName(finishedWork.type) || 'instance');\n }\n\n if (instance.state !== finishedWork.memoizedState) {\n error('Expected %s state to match memoized state before ' + 'getSnapshotBeforeUpdate. ' + 'This might either be because of a bug in React, or because ' + 'a component reassigns its own `this.props`. ' + 'Please file an issue.', getComponentName(finishedWork.type) || 'instance');\n }\n }\n }\n\n var snapshot = instance.getSnapshotBeforeUpdate(finishedWork.elementType === finishedWork.type ? prevProps : resolveDefaultProps(finishedWork.type, prevProps), prevState);\n\n {\n var didWarnSet = didWarnAboutUndefinedSnapshotBeforeUpdate;\n\n if (snapshot === undefined && !didWarnSet.has(finishedWork.type)) {\n didWarnSet.add(finishedWork.type);\n\n error('%s.getSnapshotBeforeUpdate(): A snapshot value (or null) ' + 'must be returned. You have returned undefined.', getComponentName(finishedWork.type));\n }\n }\n\n instance.__reactInternalSnapshotBeforeUpdate = snapshot;\n stopPhaseTimer();\n }\n }\n\n return;\n }\n\n case HostRoot:\n case HostComponent:\n case HostText:\n case HostPortal:\n case IncompleteClassComponent:\n // Nothing to do for these component types\n return;\n }\n\n {\n {\n throw Error( \"This unit of work tag should not have side-effects. This error is likely caused by a bug in React. Please file an issue.\" );\n }\n }\n}\n\nfunction commitHookEffectListUnmount(tag, finishedWork) {\n var updateQueue = finishedWork.updateQueue;\n var lastEffect = updateQueue !== null ? updateQueue.lastEffect : null;\n\n if (lastEffect !== null) {\n var firstEffect = lastEffect.next;\n var effect = firstEffect;\n\n do {\n if ((effect.tag & tag) === tag) {\n // Unmount\n var destroy = effect.destroy;\n effect.destroy = undefined;\n\n if (destroy !== undefined) {\n destroy();\n }\n }\n\n effect = effect.next;\n } while (effect !== firstEffect);\n }\n}\n\nfunction commitHookEffectListMount(tag, finishedWork) {\n var updateQueue = finishedWork.updateQueue;\n var lastEffect = updateQueue !== null ? updateQueue.lastEffect : null;\n\n if (lastEffect !== null) {\n var firstEffect = lastEffect.next;\n var effect = firstEffect;\n\n do {\n if ((effect.tag & tag) === tag) {\n // Mount\n var create = effect.create;\n effect.destroy = create();\n\n {\n var destroy = effect.destroy;\n\n if (destroy !== undefined && typeof destroy !== 'function') {\n var addendum = void 0;\n\n if (destroy === null) {\n addendum = ' You returned null. If your effect does not require clean ' + 'up, return undefined (or nothing).';\n } else if (typeof destroy.then === 'function') {\n addendum = '\\n\\nIt looks like you wrote useEffect(async () => ...) or returned a Promise. ' + 'Instead, write the async function inside your effect ' + 'and call it immediately:\\n\\n' + 'useEffect(() => {\\n' + ' async function fetchData() {\\n' + ' // You can await here\\n' + ' const response = await MyAPI.getData(someId);\\n' + ' // ...\\n' + ' }\\n' + ' fetchData();\\n' + \"}, [someId]); // Or [] if effect doesn't need props or state\\n\\n\" + 'Learn more about data fetching with Hooks: https://fb.me/react-hooks-data-fetching';\n } else {\n addendum = ' You returned: ' + destroy;\n }\n\n error('An effect function must not return anything besides a function, ' + 'which is used for clean-up.%s%s', addendum, getStackByFiberInDevAndProd(finishedWork));\n }\n }\n }\n\n effect = effect.next;\n } while (effect !== firstEffect);\n }\n}\n\nfunction commitPassiveHookEffects(finishedWork) {\n if ((finishedWork.effectTag & Passive) !== NoEffect) {\n switch (finishedWork.tag) {\n case FunctionComponent:\n case ForwardRef:\n case SimpleMemoComponent:\n case Block:\n {\n // TODO (#17945) We should call all passive destroy functions (for all fibers)\n // before calling any create functions. The current approach only serializes\n // these for a single fiber.\n commitHookEffectListUnmount(Passive$1 | HasEffect, finishedWork);\n commitHookEffectListMount(Passive$1 | HasEffect, finishedWork);\n break;\n }\n }\n }\n}\n\nfunction commitLifeCycles(finishedRoot, current, finishedWork, committedExpirationTime) {\n switch (finishedWork.tag) {\n case FunctionComponent:\n case ForwardRef:\n case SimpleMemoComponent:\n case Block:\n {\n // At this point layout effects have already been destroyed (during mutation phase).\n // This is done to prevent sibling component effects from interfering with each other,\n // e.g. a destroy function in one component should never override a ref set\n // by a create function in another component during the same commit.\n commitHookEffectListMount(Layout | HasEffect, finishedWork);\n\n return;\n }\n\n case ClassComponent:\n {\n var instance = finishedWork.stateNode;\n\n if (finishedWork.effectTag & Update) {\n if (current === null) {\n startPhaseTimer(finishedWork, 'componentDidMount'); // We could update instance props and state here,\n // but instead we rely on them being set during last render.\n // TODO: revisit this when we implement resuming.\n\n {\n if (finishedWork.type === finishedWork.elementType && !didWarnAboutReassigningProps) {\n if (instance.props !== finishedWork.memoizedProps) {\n error('Expected %s props to match memoized props before ' + 'componentDidMount. ' + 'This might either be because of a bug in React, or because ' + 'a component reassigns its own `this.props`. ' + 'Please file an issue.', getComponentName(finishedWork.type) || 'instance');\n }\n\n if (instance.state !== finishedWork.memoizedState) {\n error('Expected %s state to match memoized state before ' + 'componentDidMount. ' + 'This might either be because of a bug in React, or because ' + 'a component reassigns its own `this.props`. ' + 'Please file an issue.', getComponentName(finishedWork.type) || 'instance');\n }\n }\n }\n\n instance.componentDidMount();\n stopPhaseTimer();\n } else {\n var prevProps = finishedWork.elementType === finishedWork.type ? current.memoizedProps : resolveDefaultProps(finishedWork.type, current.memoizedProps);\n var prevState = current.memoizedState;\n startPhaseTimer(finishedWork, 'componentDidUpdate'); // We could update instance props and state here,\n // but instead we rely on them being set during last render.\n // TODO: revisit this when we implement resuming.\n\n {\n if (finishedWork.type === finishedWork.elementType && !didWarnAboutReassigningProps) {\n if (instance.props !== finishedWork.memoizedProps) {\n error('Expected %s props to match memoized props before ' + 'componentDidUpdate. ' + 'This might either be because of a bug in React, or because ' + 'a component reassigns its own `this.props`. ' + 'Please file an issue.', getComponentName(finishedWork.type) || 'instance');\n }\n\n if (instance.state !== finishedWork.memoizedState) {\n error('Expected %s state to match memoized state before ' + 'componentDidUpdate. ' + 'This might either be because of a bug in React, or because ' + 'a component reassigns its own `this.props`. ' + 'Please file an issue.', getComponentName(finishedWork.type) || 'instance');\n }\n }\n }\n\n instance.componentDidUpdate(prevProps, prevState, instance.__reactInternalSnapshotBeforeUpdate);\n stopPhaseTimer();\n }\n }\n\n var updateQueue = finishedWork.updateQueue;\n\n if (updateQueue !== null) {\n {\n if (finishedWork.type === finishedWork.elementType && !didWarnAboutReassigningProps) {\n if (instance.props !== finishedWork.memoizedProps) {\n error('Expected %s props to match memoized props before ' + 'processing the update queue. ' + 'This might either be because of a bug in React, or because ' + 'a component reassigns its own `this.props`. ' + 'Please file an issue.', getComponentName(finishedWork.type) || 'instance');\n }\n\n if (instance.state !== finishedWork.memoizedState) {\n error('Expected %s state to match memoized state before ' + 'processing the update queue. ' + 'This might either be because of a bug in React, or because ' + 'a component reassigns its own `this.props`. ' + 'Please file an issue.', getComponentName(finishedWork.type) || 'instance');\n }\n }\n } // We could update instance props and state here,\n // but instead we rely on them being set during last render.\n // TODO: revisit this when we implement resuming.\n\n\n commitUpdateQueue(finishedWork, updateQueue, instance);\n }\n\n return;\n }\n\n case HostRoot:\n {\n var _updateQueue = finishedWork.updateQueue;\n\n if (_updateQueue !== null) {\n var _instance = null;\n\n if (finishedWork.child !== null) {\n switch (finishedWork.child.tag) {\n case HostComponent:\n _instance = getPublicInstance(finishedWork.child.stateNode);\n break;\n\n case ClassComponent:\n _instance = finishedWork.child.stateNode;\n break;\n }\n }\n\n commitUpdateQueue(finishedWork, _updateQueue, _instance);\n }\n\n return;\n }\n\n case HostComponent:\n {\n var _instance2 = finishedWork.stateNode; // Renderers may schedule work to be done after host components are mounted\n // (eg DOM renderer may schedule auto-focus for inputs and form controls).\n // These effects should only be committed when components are first mounted,\n // aka when there is no current/alternate.\n\n if (current === null && finishedWork.effectTag & Update) {\n var type = finishedWork.type;\n var props = finishedWork.memoizedProps;\n commitMount(_instance2, type, props);\n }\n\n return;\n }\n\n case HostText:\n {\n // We have no life-cycles associated with text.\n return;\n }\n\n case HostPortal:\n {\n // We have no life-cycles associated with portals.\n return;\n }\n\n case Profiler:\n {\n {\n var onRender = finishedWork.memoizedProps.onRender;\n\n if (typeof onRender === 'function') {\n {\n onRender(finishedWork.memoizedProps.id, current === null ? 'mount' : 'update', finishedWork.actualDuration, finishedWork.treeBaseDuration, finishedWork.actualStartTime, getCommitTime(), finishedRoot.memoizedInteractions);\n }\n }\n }\n\n return;\n }\n\n case SuspenseComponent:\n {\n commitSuspenseHydrationCallbacks(finishedRoot, finishedWork);\n return;\n }\n\n case SuspenseListComponent:\n case IncompleteClassComponent:\n case FundamentalComponent:\n case ScopeComponent:\n return;\n }\n\n {\n {\n throw Error( \"This unit of work tag should not have side-effects. This error is likely caused by a bug in React. Please file an issue.\" );\n }\n }\n}\n\nfunction hideOrUnhideAllChildren(finishedWork, isHidden) {\n {\n // We only have the top Fiber that was inserted but we need to recurse down its\n // children to find all the terminal nodes.\n var node = finishedWork;\n\n while (true) {\n if (node.tag === HostComponent) {\n var instance = node.stateNode;\n\n if (isHidden) {\n hideInstance(instance);\n } else {\n unhideInstance(node.stateNode, node.memoizedProps);\n }\n } else if (node.tag === HostText) {\n var _instance3 = node.stateNode;\n\n if (isHidden) {\n hideTextInstance(_instance3);\n } else {\n unhideTextInstance(_instance3, node.memoizedProps);\n }\n } else if (node.tag === SuspenseComponent && node.memoizedState !== null && node.memoizedState.dehydrated === null) {\n // Found a nested Suspense component that timed out. Skip over the\n // primary child fragment, which should remain hidden.\n var fallbackChildFragment = node.child.sibling;\n fallbackChildFragment.return = node;\n node = fallbackChildFragment;\n continue;\n } else if (node.child !== null) {\n node.child.return = node;\n node = node.child;\n continue;\n }\n\n if (node === finishedWork) {\n return;\n }\n\n while (node.sibling === null) {\n if (node.return === null || node.return === finishedWork) {\n return;\n }\n\n node = node.return;\n }\n\n node.sibling.return = node.return;\n node = node.sibling;\n }\n }\n}\n\nfunction commitAttachRef(finishedWork) {\n var ref = finishedWork.ref;\n\n if (ref !== null) {\n var instance = finishedWork.stateNode;\n var instanceToUse;\n\n switch (finishedWork.tag) {\n case HostComponent:\n instanceToUse = getPublicInstance(instance);\n break;\n\n default:\n instanceToUse = instance;\n } // Moved outside to ensure DCE works with this flag\n\n if (typeof ref === 'function') {\n ref(instanceToUse);\n } else {\n {\n if (!ref.hasOwnProperty('current')) {\n error('Unexpected ref object provided for %s. ' + 'Use either a ref-setter function or React.createRef().%s', getComponentName(finishedWork.type), getStackByFiberInDevAndProd(finishedWork));\n }\n }\n\n ref.current = instanceToUse;\n }\n }\n}\n\nfunction commitDetachRef(current) {\n var currentRef = current.ref;\n\n if (currentRef !== null) {\n if (typeof currentRef === 'function') {\n currentRef(null);\n } else {\n currentRef.current = null;\n }\n }\n} // User-originating errors (lifecycles and refs) should not interrupt\n// deletion, so don't let them throw. Host-originating errors should\n// interrupt deletion, so it's okay\n\n\nfunction commitUnmount(finishedRoot, current, renderPriorityLevel) {\n onCommitUnmount(current);\n\n switch (current.tag) {\n case FunctionComponent:\n case ForwardRef:\n case MemoComponent:\n case SimpleMemoComponent:\n case Block:\n {\n var updateQueue = current.updateQueue;\n\n if (updateQueue !== null) {\n var lastEffect = updateQueue.lastEffect;\n\n if (lastEffect !== null) {\n var firstEffect = lastEffect.next;\n\n {\n // When the owner fiber is deleted, the destroy function of a passive\n // effect hook is called during the synchronous commit phase. This is\n // a concession to implementation complexity. Calling it in the\n // passive effect phase (like they usually are, when dependencies\n // change during an update) would require either traversing the\n // children of the deleted fiber again, or including unmount effects\n // as part of the fiber effect list.\n //\n // Because this is during the sync commit phase, we need to change\n // the priority.\n //\n // TODO: Reconsider this implementation trade off.\n var priorityLevel = renderPriorityLevel > NormalPriority ? NormalPriority : renderPriorityLevel;\n runWithPriority$1(priorityLevel, function () {\n var effect = firstEffect;\n\n do {\n var _destroy = effect.destroy;\n\n if (_destroy !== undefined) {\n safelyCallDestroy(current, _destroy);\n }\n\n effect = effect.next;\n } while (effect !== firstEffect);\n });\n }\n }\n }\n\n return;\n }\n\n case ClassComponent:\n {\n safelyDetachRef(current);\n var instance = current.stateNode;\n\n if (typeof instance.componentWillUnmount === 'function') {\n safelyCallComponentWillUnmount(current, instance);\n }\n\n return;\n }\n\n case HostComponent:\n {\n\n safelyDetachRef(current);\n return;\n }\n\n case HostPortal:\n {\n // TODO: this is recursive.\n // We are also not using this parent because\n // the portal will get pushed immediately.\n {\n unmountHostComponents(finishedRoot, current, renderPriorityLevel);\n }\n\n return;\n }\n\n case FundamentalComponent:\n {\n\n return;\n }\n\n case DehydratedFragment:\n {\n\n return;\n }\n\n case ScopeComponent:\n {\n\n return;\n }\n }\n}\n\nfunction commitNestedUnmounts(finishedRoot, root, renderPriorityLevel) {\n // While we're inside a removed host node we don't want to call\n // removeChild on the inner nodes because they're removed by the top\n // call anyway. We also want to call componentWillUnmount on all\n // composites before this host node is removed from the tree. Therefore\n // we do an inner loop while we're still inside the host node.\n var node = root;\n\n while (true) {\n commitUnmount(finishedRoot, node, renderPriorityLevel); // Visit children because they may contain more composite or host nodes.\n // Skip portals because commitUnmount() currently visits them recursively.\n\n if (node.child !== null && ( // If we use mutation we drill down into portals using commitUnmount above.\n // If we don't use mutation we drill down into portals here instead.\n node.tag !== HostPortal)) {\n node.child.return = node;\n node = node.child;\n continue;\n }\n\n if (node === root) {\n return;\n }\n\n while (node.sibling === null) {\n if (node.return === null || node.return === root) {\n return;\n }\n\n node = node.return;\n }\n\n node.sibling.return = node.return;\n node = node.sibling;\n }\n}\n\nfunction detachFiber(current) {\n var alternate = current.alternate; // Cut off the return pointers to disconnect it from the tree. Ideally, we\n // should clear the child pointer of the parent alternate to let this\n // get GC:ed but we don't know which for sure which parent is the current\n // one so we'll settle for GC:ing the subtree of this child. This child\n // itself will be GC:ed when the parent updates the next time.\n\n current.return = null;\n current.child = null;\n current.memoizedState = null;\n current.updateQueue = null;\n current.dependencies = null;\n current.alternate = null;\n current.firstEffect = null;\n current.lastEffect = null;\n current.pendingProps = null;\n current.memoizedProps = null;\n current.stateNode = null;\n\n if (alternate !== null) {\n detachFiber(alternate);\n }\n}\n\nfunction getHostParentFiber(fiber) {\n var parent = fiber.return;\n\n while (parent !== null) {\n if (isHostParent(parent)) {\n return parent;\n }\n\n parent = parent.return;\n }\n\n {\n {\n throw Error( \"Expected to find a host parent. This error is likely caused by a bug in React. Please file an issue.\" );\n }\n }\n}\n\nfunction isHostParent(fiber) {\n return fiber.tag === HostComponent || fiber.tag === HostRoot || fiber.tag === HostPortal;\n}\n\nfunction getHostSibling(fiber) {\n // We're going to search forward into the tree until we find a sibling host\n // node. Unfortunately, if multiple insertions are done in a row we have to\n // search past them. This leads to exponential search for the next sibling.\n // TODO: Find a more efficient way to do this.\n var node = fiber;\n\n siblings: while (true) {\n // If we didn't find anything, let's try the next sibling.\n while (node.sibling === null) {\n if (node.return === null || isHostParent(node.return)) {\n // If we pop out of the root or hit the parent the fiber we are the\n // last sibling.\n return null;\n }\n\n node = node.return;\n }\n\n node.sibling.return = node.return;\n node = node.sibling;\n\n while (node.tag !== HostComponent && node.tag !== HostText && node.tag !== DehydratedFragment) {\n // If it is not host node and, we might have a host node inside it.\n // Try to search down until we find one.\n if (node.effectTag & Placement) {\n // If we don't have a child, try the siblings instead.\n continue siblings;\n } // If we don't have a child, try the siblings instead.\n // We also skip portals because they are not part of this host tree.\n\n\n if (node.child === null || node.tag === HostPortal) {\n continue siblings;\n } else {\n node.child.return = node;\n node = node.child;\n }\n } // Check if this host node is stable or about to be placed.\n\n\n if (!(node.effectTag & Placement)) {\n // Found it!\n return node.stateNode;\n }\n }\n}\n\nfunction commitPlacement(finishedWork) {\n\n\n var parentFiber = getHostParentFiber(finishedWork); // Note: these two variables *must* always be updated together.\n\n var parent;\n var isContainer;\n var parentStateNode = parentFiber.stateNode;\n\n switch (parentFiber.tag) {\n case HostComponent:\n parent = parentStateNode;\n isContainer = false;\n break;\n\n case HostRoot:\n parent = parentStateNode.containerInfo;\n isContainer = true;\n break;\n\n case HostPortal:\n parent = parentStateNode.containerInfo;\n isContainer = true;\n break;\n\n case FundamentalComponent:\n\n // eslint-disable-next-line-no-fallthrough\n\n default:\n {\n {\n throw Error( \"Invalid host parent fiber. This error is likely caused by a bug in React. Please file an issue.\" );\n }\n }\n\n }\n\n if (parentFiber.effectTag & ContentReset) {\n // Reset the text content of the parent before doing any insertions\n resetTextContent(parent); // Clear ContentReset from the effect tag\n\n parentFiber.effectTag &= ~ContentReset;\n }\n\n var before = getHostSibling(finishedWork); // We only have the top Fiber that was inserted but we need to recurse down its\n // children to find all the terminal nodes.\n\n if (isContainer) {\n insertOrAppendPlacementNodeIntoContainer(finishedWork, before, parent);\n } else {\n insertOrAppendPlacementNode(finishedWork, before, parent);\n }\n}\n\nfunction insertOrAppendPlacementNodeIntoContainer(node, before, parent) {\n var tag = node.tag;\n var isHost = tag === HostComponent || tag === HostText;\n\n if (isHost || enableFundamentalAPI ) {\n var stateNode = isHost ? node.stateNode : node.stateNode.instance;\n\n if (before) {\n insertInContainerBefore(parent, stateNode, before);\n } else {\n appendChildToContainer(parent, stateNode);\n }\n } else if (tag === HostPortal) ; else {\n var child = node.child;\n\n if (child !== null) {\n insertOrAppendPlacementNodeIntoContainer(child, before, parent);\n var sibling = child.sibling;\n\n while (sibling !== null) {\n insertOrAppendPlacementNodeIntoContainer(sibling, before, parent);\n sibling = sibling.sibling;\n }\n }\n }\n}\n\nfunction insertOrAppendPlacementNode(node, before, parent) {\n var tag = node.tag;\n var isHost = tag === HostComponent || tag === HostText;\n\n if (isHost || enableFundamentalAPI ) {\n var stateNode = isHost ? node.stateNode : node.stateNode.instance;\n\n if (before) {\n insertBefore(parent, stateNode, before);\n } else {\n appendChild(parent, stateNode);\n }\n } else if (tag === HostPortal) ; else {\n var child = node.child;\n\n if (child !== null) {\n insertOrAppendPlacementNode(child, before, parent);\n var sibling = child.sibling;\n\n while (sibling !== null) {\n insertOrAppendPlacementNode(sibling, before, parent);\n sibling = sibling.sibling;\n }\n }\n }\n}\n\nfunction unmountHostComponents(finishedRoot, current, renderPriorityLevel) {\n // We only have the top Fiber that was deleted but we need to recurse down its\n // children to find all the terminal nodes.\n var node = current; // Each iteration, currentParent is populated with node's host parent if not\n // currentParentIsValid.\n\n var currentParentIsValid = false; // Note: these two variables *must* always be updated together.\n\n var currentParent;\n var currentParentIsContainer;\n\n while (true) {\n if (!currentParentIsValid) {\n var parent = node.return;\n\n findParent: while (true) {\n if (!(parent !== null)) {\n {\n throw Error( \"Expected to find a host parent. This error is likely caused by a bug in React. Please file an issue.\" );\n }\n }\n\n var parentStateNode = parent.stateNode;\n\n switch (parent.tag) {\n case HostComponent:\n currentParent = parentStateNode;\n currentParentIsContainer = false;\n break findParent;\n\n case HostRoot:\n currentParent = parentStateNode.containerInfo;\n currentParentIsContainer = true;\n break findParent;\n\n case HostPortal:\n currentParent = parentStateNode.containerInfo;\n currentParentIsContainer = true;\n break findParent;\n\n }\n\n parent = parent.return;\n }\n\n currentParentIsValid = true;\n }\n\n if (node.tag === HostComponent || node.tag === HostText) {\n commitNestedUnmounts(finishedRoot, node, renderPriorityLevel); // After all the children have unmounted, it is now safe to remove the\n // node from the tree.\n\n if (currentParentIsContainer) {\n removeChildFromContainer(currentParent, node.stateNode);\n } else {\n removeChild(currentParent, node.stateNode);\n } // Don't visit children because we already visited them.\n\n } else if (node.tag === HostPortal) {\n if (node.child !== null) {\n // When we go into a portal, it becomes the parent to remove from.\n // We will reassign it back when we pop the portal on the way up.\n currentParent = node.stateNode.containerInfo;\n currentParentIsContainer = true; // Visit children because portals might contain host components.\n\n node.child.return = node;\n node = node.child;\n continue;\n }\n } else {\n commitUnmount(finishedRoot, node, renderPriorityLevel); // Visit children because we may find more host components below.\n\n if (node.child !== null) {\n node.child.return = node;\n node = node.child;\n continue;\n }\n }\n\n if (node === current) {\n return;\n }\n\n while (node.sibling === null) {\n if (node.return === null || node.return === current) {\n return;\n }\n\n node = node.return;\n\n if (node.tag === HostPortal) {\n // When we go out of the portal, we need to restore the parent.\n // Since we don't keep a stack of them, we will search for it.\n currentParentIsValid = false;\n }\n }\n\n node.sibling.return = node.return;\n node = node.sibling;\n }\n}\n\nfunction commitDeletion(finishedRoot, current, renderPriorityLevel) {\n {\n // Recursively delete all host nodes from the parent.\n // Detach refs and call componentWillUnmount() on the whole subtree.\n unmountHostComponents(finishedRoot, current, renderPriorityLevel);\n }\n\n detachFiber(current);\n}\n\nfunction commitWork(current, finishedWork) {\n\n switch (finishedWork.tag) {\n case FunctionComponent:\n case ForwardRef:\n case MemoComponent:\n case SimpleMemoComponent:\n case Block:\n {\n // Layout effects are destroyed during the mutation phase so that all\n // destroy functions for all fibers are called before any create functions.\n // This prevents sibling component effects from interfering with each other,\n // e.g. a destroy function in one component should never override a ref set\n // by a create function in another component during the same commit.\n commitHookEffectListUnmount(Layout | HasEffect, finishedWork);\n return;\n }\n\n case ClassComponent:\n {\n return;\n }\n\n case HostComponent:\n {\n var instance = finishedWork.stateNode;\n\n if (instance != null) {\n // Commit the work prepared earlier.\n var newProps = finishedWork.memoizedProps; // For hydration we reuse the update path but we treat the oldProps\n // as the newProps. The updatePayload will contain the real change in\n // this case.\n\n var oldProps = current !== null ? current.memoizedProps : newProps;\n var type = finishedWork.type; // TODO: Type the updateQueue to be specific to host components.\n\n var updatePayload = finishedWork.updateQueue;\n finishedWork.updateQueue = null;\n\n if (updatePayload !== null) {\n commitUpdate(instance, updatePayload, type, oldProps, newProps);\n }\n }\n\n return;\n }\n\n case HostText:\n {\n if (!(finishedWork.stateNode !== null)) {\n {\n throw Error( \"This should have a text node initialized. This error is likely caused by a bug in React. Please file an issue.\" );\n }\n }\n\n var textInstance = finishedWork.stateNode;\n var newText = finishedWork.memoizedProps; // For hydration we reuse the update path but we treat the oldProps\n // as the newProps. The updatePayload will contain the real change in\n // this case.\n\n var oldText = current !== null ? current.memoizedProps : newText;\n commitTextUpdate(textInstance, oldText, newText);\n return;\n }\n\n case HostRoot:\n {\n {\n var _root = finishedWork.stateNode;\n\n if (_root.hydrate) {\n // We've just hydrated. No need to hydrate again.\n _root.hydrate = false;\n commitHydratedContainer(_root.containerInfo);\n }\n }\n\n return;\n }\n\n case Profiler:\n {\n return;\n }\n\n case SuspenseComponent:\n {\n commitSuspenseComponent(finishedWork);\n attachSuspenseRetryListeners(finishedWork);\n return;\n }\n\n case SuspenseListComponent:\n {\n attachSuspenseRetryListeners(finishedWork);\n return;\n }\n\n case IncompleteClassComponent:\n {\n return;\n }\n }\n\n {\n {\n throw Error( \"This unit of work tag should not have side-effects. This error is likely caused by a bug in React. Please file an issue.\" );\n }\n }\n}\n\nfunction commitSuspenseComponent(finishedWork) {\n var newState = finishedWork.memoizedState;\n var newDidTimeout;\n var primaryChildParent = finishedWork;\n\n if (newState === null) {\n newDidTimeout = false;\n } else {\n newDidTimeout = true;\n primaryChildParent = finishedWork.child;\n markCommitTimeOfFallback();\n }\n\n if ( primaryChildParent !== null) {\n hideOrUnhideAllChildren(primaryChildParent, newDidTimeout);\n }\n}\n\nfunction commitSuspenseHydrationCallbacks(finishedRoot, finishedWork) {\n\n var newState = finishedWork.memoizedState;\n\n if (newState === null) {\n var current = finishedWork.alternate;\n\n if (current !== null) {\n var prevState = current.memoizedState;\n\n if (prevState !== null) {\n var suspenseInstance = prevState.dehydrated;\n\n if (suspenseInstance !== null) {\n commitHydratedSuspenseInstance(suspenseInstance);\n }\n }\n }\n }\n}\n\nfunction attachSuspenseRetryListeners(finishedWork) {\n // If this boundary just timed out, then it will have a set of thenables.\n // For each thenable, attach a listener so that when it resolves, React\n // attempts to re-render the boundary in the primary (pre-timeout) state.\n var thenables = finishedWork.updateQueue;\n\n if (thenables !== null) {\n finishedWork.updateQueue = null;\n var retryCache = finishedWork.stateNode;\n\n if (retryCache === null) {\n retryCache = finishedWork.stateNode = new PossiblyWeakSet();\n }\n\n thenables.forEach(function (thenable) {\n // Memoize using the boundary fiber to prevent redundant listeners.\n var retry = resolveRetryThenable.bind(null, finishedWork, thenable);\n\n if (!retryCache.has(thenable)) {\n {\n if (thenable.__reactDoNotTraceInteractions !== true) {\n retry = tracing.unstable_wrap(retry);\n }\n }\n\n retryCache.add(thenable);\n thenable.then(retry, retry);\n }\n });\n }\n}\n\nfunction commitResetTextContent(current) {\n\n resetTextContent(current.stateNode);\n}\n\nvar PossiblyWeakMap$1 = typeof WeakMap === 'function' ? WeakMap : Map;\n\nfunction createRootErrorUpdate(fiber, errorInfo, expirationTime) {\n var update = createUpdate(expirationTime, null); // Unmount the root by rendering null.\n\n update.tag = CaptureUpdate; // Caution: React DevTools currently depends on this property\n // being called \"element\".\n\n update.payload = {\n element: null\n };\n var error = errorInfo.value;\n\n update.callback = function () {\n onUncaughtError(error);\n logError(fiber, errorInfo);\n };\n\n return update;\n}\n\nfunction createClassErrorUpdate(fiber, errorInfo, expirationTime) {\n var update = createUpdate(expirationTime, null);\n update.tag = CaptureUpdate;\n var getDerivedStateFromError = fiber.type.getDerivedStateFromError;\n\n if (typeof getDerivedStateFromError === 'function') {\n var error$1 = errorInfo.value;\n\n update.payload = function () {\n logError(fiber, errorInfo);\n return getDerivedStateFromError(error$1);\n };\n }\n\n var inst = fiber.stateNode;\n\n if (inst !== null && typeof inst.componentDidCatch === 'function') {\n update.callback = function callback() {\n {\n markFailedErrorBoundaryForHotReloading(fiber);\n }\n\n if (typeof getDerivedStateFromError !== 'function') {\n // To preserve the preexisting retry behavior of error boundaries,\n // we keep track of which ones already failed during this batch.\n // This gets reset before we yield back to the browser.\n // TODO: Warn in strict mode if getDerivedStateFromError is\n // not defined.\n markLegacyErrorBoundaryAsFailed(this); // Only log here if componentDidCatch is the only error boundary method defined\n\n logError(fiber, errorInfo);\n }\n\n var error$1 = errorInfo.value;\n var stack = errorInfo.stack;\n this.componentDidCatch(error$1, {\n componentStack: stack !== null ? stack : ''\n });\n\n {\n if (typeof getDerivedStateFromError !== 'function') {\n // If componentDidCatch is the only error boundary method defined,\n // then it needs to call setState to recover from errors.\n // If no state update is scheduled then the boundary will swallow the error.\n if (fiber.expirationTime !== Sync) {\n error('%s: Error boundaries should implement getDerivedStateFromError(). ' + 'In that method, return a state update to display an error message or fallback UI.', getComponentName(fiber.type) || 'Unknown');\n }\n }\n }\n };\n } else {\n update.callback = function () {\n markFailedErrorBoundaryForHotReloading(fiber);\n };\n }\n\n return update;\n}\n\nfunction attachPingListener(root, renderExpirationTime, thenable) {\n // Attach a listener to the promise to \"ping\" the root and retry. But\n // only if one does not already exist for the current render expiration\n // time (which acts like a \"thread ID\" here).\n var pingCache = root.pingCache;\n var threadIDs;\n\n if (pingCache === null) {\n pingCache = root.pingCache = new PossiblyWeakMap$1();\n threadIDs = new Set();\n pingCache.set(thenable, threadIDs);\n } else {\n threadIDs = pingCache.get(thenable);\n\n if (threadIDs === undefined) {\n threadIDs = new Set();\n pingCache.set(thenable, threadIDs);\n }\n }\n\n if (!threadIDs.has(renderExpirationTime)) {\n // Memoize using the thread ID to prevent redundant listeners.\n threadIDs.add(renderExpirationTime);\n var ping = pingSuspendedRoot.bind(null, root, thenable, renderExpirationTime);\n thenable.then(ping, ping);\n }\n}\n\nfunction throwException(root, returnFiber, sourceFiber, value, renderExpirationTime) {\n // The source fiber did not complete.\n sourceFiber.effectTag |= Incomplete; // Its effect list is no longer valid.\n\n sourceFiber.firstEffect = sourceFiber.lastEffect = null;\n\n if (value !== null && typeof value === 'object' && typeof value.then === 'function') {\n // This is a thenable.\n var thenable = value;\n\n if ((sourceFiber.mode & BlockingMode) === NoMode) {\n // Reset the memoizedState to what it was before we attempted\n // to render it.\n var currentSource = sourceFiber.alternate;\n\n if (currentSource) {\n sourceFiber.updateQueue = currentSource.updateQueue;\n sourceFiber.memoizedState = currentSource.memoizedState;\n sourceFiber.expirationTime = currentSource.expirationTime;\n } else {\n sourceFiber.updateQueue = null;\n sourceFiber.memoizedState = null;\n }\n }\n\n var hasInvisibleParentBoundary = hasSuspenseContext(suspenseStackCursor.current, InvisibleParentSuspenseContext); // Schedule the nearest Suspense to re-render the timed out view.\n\n var _workInProgress = returnFiber;\n\n do {\n if (_workInProgress.tag === SuspenseComponent && shouldCaptureSuspense(_workInProgress, hasInvisibleParentBoundary)) {\n // Found the nearest boundary.\n // Stash the promise on the boundary fiber. If the boundary times out, we'll\n // attach another listener to flip the boundary back to its normal state.\n var thenables = _workInProgress.updateQueue;\n\n if (thenables === null) {\n var updateQueue = new Set();\n updateQueue.add(thenable);\n _workInProgress.updateQueue = updateQueue;\n } else {\n thenables.add(thenable);\n } // If the boundary is outside of blocking mode, we should *not*\n // suspend the commit. Pretend as if the suspended component rendered\n // null and keep rendering. In the commit phase, we'll schedule a\n // subsequent synchronous update to re-render the Suspense.\n //\n // Note: It doesn't matter whether the component that suspended was\n // inside a blocking mode tree. If the Suspense is outside of it, we\n // should *not* suspend the commit.\n\n\n if ((_workInProgress.mode & BlockingMode) === NoMode) {\n _workInProgress.effectTag |= DidCapture; // We're going to commit this fiber even though it didn't complete.\n // But we shouldn't call any lifecycle methods or callbacks. Remove\n // all lifecycle effect tags.\n\n sourceFiber.effectTag &= ~(LifecycleEffectMask | Incomplete);\n\n if (sourceFiber.tag === ClassComponent) {\n var currentSourceFiber = sourceFiber.alternate;\n\n if (currentSourceFiber === null) {\n // This is a new mount. Change the tag so it's not mistaken for a\n // completed class component. For example, we should not call\n // componentWillUnmount if it is deleted.\n sourceFiber.tag = IncompleteClassComponent;\n } else {\n // When we try rendering again, we should not reuse the current fiber,\n // since it's known to be in an inconsistent state. Use a force update to\n // prevent a bail out.\n var update = createUpdate(Sync, null);\n update.tag = ForceUpdate;\n enqueueUpdate(sourceFiber, update);\n }\n } // The source fiber did not complete. Mark it with Sync priority to\n // indicate that it still has pending work.\n\n\n sourceFiber.expirationTime = Sync; // Exit without suspending.\n\n return;\n } // Confirmed that the boundary is in a concurrent mode tree. Continue\n // with the normal suspend path.\n //\n // After this we'll use a set of heuristics to determine whether this\n // render pass will run to completion or restart or \"suspend\" the commit.\n // The actual logic for this is spread out in different places.\n //\n // This first principle is that if we're going to suspend when we complete\n // a root, then we should also restart if we get an update or ping that\n // might unsuspend it, and vice versa. The only reason to suspend is\n // because you think you might want to restart before committing. However,\n // it doesn't make sense to restart only while in the period we're suspended.\n //\n // Restarting too aggressively is also not good because it starves out any\n // intermediate loading state. So we use heuristics to determine when.\n // Suspense Heuristics\n //\n // If nothing threw a Promise or all the same fallbacks are already showing,\n // then don't suspend/restart.\n //\n // If this is an initial render of a new tree of Suspense boundaries and\n // those trigger a fallback, then don't suspend/restart. We want to ensure\n // that we can show the initial loading state as quickly as possible.\n //\n // If we hit a \"Delayed\" case, such as when we'd switch from content back into\n // a fallback, then we should always suspend/restart. SuspenseConfig applies to\n // this case. If none is defined, JND is used instead.\n //\n // If we're already showing a fallback and it gets \"retried\", allowing us to show\n // another level, but there's still an inner boundary that would show a fallback,\n // then we suspend/restart for 500ms since the last time we showed a fallback\n // anywhere in the tree. This effectively throttles progressive loading into a\n // consistent train of commits. This also gives us an opportunity to restart to\n // get to the completed state slightly earlier.\n //\n // If there's ambiguity due to batching it's resolved in preference of:\n // 1) \"delayed\", 2) \"initial render\", 3) \"retry\".\n //\n // We want to ensure that a \"busy\" state doesn't get force committed. We want to\n // ensure that new initial loading states can commit as soon as possible.\n\n\n attachPingListener(root, renderExpirationTime, thenable);\n _workInProgress.effectTag |= ShouldCapture;\n _workInProgress.expirationTime = renderExpirationTime;\n return;\n } // This boundary already captured during this render. Continue to the next\n // boundary.\n\n\n _workInProgress = _workInProgress.return;\n } while (_workInProgress !== null); // No boundary was found. Fallthrough to error mode.\n // TODO: Use invariant so the message is stripped in prod?\n\n\n value = new Error((getComponentName(sourceFiber.type) || 'A React component') + ' suspended while rendering, but no fallback UI was specified.\\n' + '\\n' + 'Add a <Suspense fallback=...> component higher in the tree to ' + 'provide a loading indicator or placeholder to display.' + getStackByFiberInDevAndProd(sourceFiber));\n } // We didn't find a boundary that could handle this type of exception. Start\n // over and traverse parent path again, this time treating the exception\n // as an error.\n\n\n renderDidError();\n value = createCapturedValue(value, sourceFiber);\n var workInProgress = returnFiber;\n\n do {\n switch (workInProgress.tag) {\n case HostRoot:\n {\n var _errorInfo = value;\n workInProgress.effectTag |= ShouldCapture;\n workInProgress.expirationTime = renderExpirationTime;\n\n var _update = createRootErrorUpdate(workInProgress, _errorInfo, renderExpirationTime);\n\n enqueueCapturedUpdate(workInProgress, _update);\n return;\n }\n\n case ClassComponent:\n // Capture and retry\n var errorInfo = value;\n var ctor = workInProgress.type;\n var instance = workInProgress.stateNode;\n\n if ((workInProgress.effectTag & DidCapture) === NoEffect && (typeof ctor.getDerivedStateFromError === 'function' || instance !== null && typeof instance.componentDidCatch === 'function' && !isAlreadyFailedLegacyErrorBoundary(instance))) {\n workInProgress.effectTag |= ShouldCapture;\n workInProgress.expirationTime = renderExpirationTime; // Schedule the error boundary to re-render using updated state\n\n var _update2 = createClassErrorUpdate(workInProgress, errorInfo, renderExpirationTime);\n\n enqueueCapturedUpdate(workInProgress, _update2);\n return;\n }\n\n break;\n }\n\n workInProgress = workInProgress.return;\n } while (workInProgress !== null);\n}\n\nvar ceil = Math.ceil;\nvar ReactCurrentDispatcher$1 = ReactSharedInternals.ReactCurrentDispatcher,\n ReactCurrentOwner$2 = ReactSharedInternals.ReactCurrentOwner,\n IsSomeRendererActing = ReactSharedInternals.IsSomeRendererActing;\nvar NoContext =\n/* */\n0;\nvar BatchedContext =\n/* */\n1;\nvar EventContext =\n/* */\n2;\nvar DiscreteEventContext =\n/* */\n4;\nvar LegacyUnbatchedContext =\n/* */\n8;\nvar RenderContext =\n/* */\n16;\nvar CommitContext =\n/* */\n32;\nvar RootIncomplete = 0;\nvar RootFatalErrored = 1;\nvar RootErrored = 2;\nvar RootSuspended = 3;\nvar RootSuspendedWithDelay = 4;\nvar RootCompleted = 5;\n// Describes where we are in the React execution stack\nvar executionContext = NoContext; // The root we're working on\n\nvar workInProgressRoot = null; // The fiber we're working on\n\nvar workInProgress = null; // The expiration time we're rendering\n\nvar renderExpirationTime$1 = NoWork; // Whether to root completed, errored, suspended, etc.\n\nvar workInProgressRootExitStatus = RootIncomplete; // A fatal error, if one is thrown\n\nvar workInProgressRootFatalError = null; // Most recent event time among processed updates during this render.\n// This is conceptually a time stamp but expressed in terms of an ExpirationTime\n// because we deal mostly with expiration times in the hot path, so this avoids\n// the conversion happening in the hot path.\n\nvar workInProgressRootLatestProcessedExpirationTime = Sync;\nvar workInProgressRootLatestSuspenseTimeout = Sync;\nvar workInProgressRootCanSuspendUsingConfig = null; // The work left over by components that were visited during this render. Only\n// includes unprocessed updates, not work in bailed out children.\n\nvar workInProgressRootNextUnprocessedUpdateTime = NoWork; // If we're pinged while rendering we don't always restart immediately.\n// This flag determines if it might be worthwhile to restart if an opportunity\n// happens latere.\n\nvar workInProgressRootHasPendingPing = false; // The most recent time we committed a fallback. This lets us ensure a train\n// model where we don't commit new loading states in too quick succession.\n\nvar globalMostRecentFallbackTime = 0;\nvar FALLBACK_THROTTLE_MS = 500;\nvar nextEffect = null;\nvar hasUncaughtError = false;\nvar firstUncaughtError = null;\nvar legacyErrorBoundariesThatAlreadyFailed = null;\nvar rootDoesHavePassiveEffects = false;\nvar rootWithPendingPassiveEffects = null;\nvar pendingPassiveEffectsRenderPriority = NoPriority;\nvar pendingPassiveEffectsExpirationTime = NoWork;\nvar rootsWithPendingDiscreteUpdates = null; // Use these to prevent an infinite loop of nested updates\n\nvar NESTED_UPDATE_LIMIT = 50;\nvar nestedUpdateCount = 0;\nvar rootWithNestedUpdates = null;\nvar NESTED_PASSIVE_UPDATE_LIMIT = 50;\nvar nestedPassiveUpdateCount = 0;\nvar interruptedBy = null; // Marks the need to reschedule pending interactions at these expiration times\n// during the commit phase. This enables them to be traced across components\n// that spawn new work during render. E.g. hidden boundaries, suspended SSR\n// hydration or SuspenseList.\n\nvar spawnedWorkDuringRender = null; // Expiration times are computed by adding to the current time (the start\n// time). However, if two updates are scheduled within the same event, we\n// should treat their start times as simultaneous, even if the actual clock\n// time has advanced between the first and second call.\n// In other words, because expiration times determine how updates are batched,\n// we want all updates of like priority that occur within the same event to\n// receive the same expiration time. Otherwise we get tearing.\n\nvar currentEventTime = NoWork;\nfunction requestCurrentTimeForUpdate() {\n if ((executionContext & (RenderContext | CommitContext)) !== NoContext) {\n // We're inside React, so it's fine to read the actual time.\n return msToExpirationTime(now());\n } // We're not inside React, so we may be in the middle of a browser event.\n\n\n if (currentEventTime !== NoWork) {\n // Use the same start time for all updates until we enter React again.\n return currentEventTime;\n } // This is the first update since React yielded. Compute a new start time.\n\n\n currentEventTime = msToExpirationTime(now());\n return currentEventTime;\n}\nfunction getCurrentTime() {\n return msToExpirationTime(now());\n}\nfunction computeExpirationForFiber(currentTime, fiber, suspenseConfig) {\n var mode = fiber.mode;\n\n if ((mode & BlockingMode) === NoMode) {\n return Sync;\n }\n\n var priorityLevel = getCurrentPriorityLevel();\n\n if ((mode & ConcurrentMode) === NoMode) {\n return priorityLevel === ImmediatePriority ? Sync : Batched;\n }\n\n if ((executionContext & RenderContext) !== NoContext) {\n // Use whatever time we're already rendering\n // TODO: Should there be a way to opt out, like with `runWithPriority`?\n return renderExpirationTime$1;\n }\n\n var expirationTime;\n\n if (suspenseConfig !== null) {\n // Compute an expiration time based on the Suspense timeout.\n expirationTime = computeSuspenseExpiration(currentTime, suspenseConfig.timeoutMs | 0 || LOW_PRIORITY_EXPIRATION);\n } else {\n // Compute an expiration time based on the Scheduler priority.\n switch (priorityLevel) {\n case ImmediatePriority:\n expirationTime = Sync;\n break;\n\n case UserBlockingPriority$1:\n // TODO: Rename this to computeUserBlockingExpiration\n expirationTime = computeInteractiveExpiration(currentTime);\n break;\n\n case NormalPriority:\n case LowPriority:\n // TODO: Handle LowPriority\n // TODO: Rename this to... something better.\n expirationTime = computeAsyncExpiration(currentTime);\n break;\n\n case IdlePriority:\n expirationTime = Idle;\n break;\n\n default:\n {\n {\n throw Error( \"Expected a valid priority level\" );\n }\n }\n\n }\n } // If we're in the middle of rendering a tree, do not update at the same\n // expiration time that is already rendering.\n // TODO: We shouldn't have to do this if the update is on a different root.\n // Refactor computeExpirationForFiber + scheduleUpdate so we have access to\n // the root when we check for this condition.\n\n\n if (workInProgressRoot !== null && expirationTime === renderExpirationTime$1) {\n // This is a trick to move this update into a separate batch\n expirationTime -= 1;\n }\n\n return expirationTime;\n}\nfunction scheduleUpdateOnFiber(fiber, expirationTime) {\n checkForNestedUpdates();\n warnAboutRenderPhaseUpdatesInDEV(fiber);\n var root = markUpdateTimeFromFiberToRoot(fiber, expirationTime);\n\n if (root === null) {\n warnAboutUpdateOnUnmountedFiberInDEV(fiber);\n return;\n }\n\n checkForInterruption(fiber, expirationTime);\n recordScheduleUpdate(); // TODO: computeExpirationForFiber also reads the priority. Pass the\n // priority as an argument to that function and this one.\n\n var priorityLevel = getCurrentPriorityLevel();\n\n if (expirationTime === Sync) {\n if ( // Check if we're inside unbatchedUpdates\n (executionContext & LegacyUnbatchedContext) !== NoContext && // Check if we're not already rendering\n (executionContext & (RenderContext | CommitContext)) === NoContext) {\n // Register pending interactions on the root to avoid losing traced interaction data.\n schedulePendingInteractions(root, expirationTime); // This is a legacy edge case. The initial mount of a ReactDOM.render-ed\n // root inside of batchedUpdates should be synchronous, but layout updates\n // should be deferred until the end of the batch.\n\n performSyncWorkOnRoot(root);\n } else {\n ensureRootIsScheduled(root);\n schedulePendingInteractions(root, expirationTime);\n\n if (executionContext === NoContext) {\n // Flush the synchronous work now, unless we're already working or inside\n // a batch. This is intentionally inside scheduleUpdateOnFiber instead of\n // scheduleCallbackForFiber to preserve the ability to schedule a callback\n // without immediately flushing it. We only do this for user-initiated\n // updates, to preserve historical behavior of legacy mode.\n flushSyncCallbackQueue();\n }\n }\n } else {\n ensureRootIsScheduled(root);\n schedulePendingInteractions(root, expirationTime);\n }\n\n if ((executionContext & DiscreteEventContext) !== NoContext && ( // Only updates at user-blocking priority or greater are considered\n // discrete, even inside a discrete event.\n priorityLevel === UserBlockingPriority$1 || priorityLevel === ImmediatePriority)) {\n // This is the result of a discrete event. Track the lowest priority\n // discrete update per root so we can flush them early, if needed.\n if (rootsWithPendingDiscreteUpdates === null) {\n rootsWithPendingDiscreteUpdates = new Map([[root, expirationTime]]);\n } else {\n var lastDiscreteTime = rootsWithPendingDiscreteUpdates.get(root);\n\n if (lastDiscreteTime === undefined || lastDiscreteTime > expirationTime) {\n rootsWithPendingDiscreteUpdates.set(root, expirationTime);\n }\n }\n }\n}\nvar scheduleWork = scheduleUpdateOnFiber; // This is split into a separate function so we can mark a fiber with pending\n// work without treating it as a typical update that originates from an event;\n// e.g. retrying a Suspense boundary isn't an update, but it does schedule work\n// on a fiber.\n\nfunction markUpdateTimeFromFiberToRoot(fiber, expirationTime) {\n // Update the source fiber's expiration time\n if (fiber.expirationTime < expirationTime) {\n fiber.expirationTime = expirationTime;\n }\n\n var alternate = fiber.alternate;\n\n if (alternate !== null && alternate.expirationTime < expirationTime) {\n alternate.expirationTime = expirationTime;\n } // Walk the parent path to the root and update the child expiration time.\n\n\n var node = fiber.return;\n var root = null;\n\n if (node === null && fiber.tag === HostRoot) {\n root = fiber.stateNode;\n } else {\n while (node !== null) {\n alternate = node.alternate;\n\n if (node.childExpirationTime < expirationTime) {\n node.childExpirationTime = expirationTime;\n\n if (alternate !== null && alternate.childExpirationTime < expirationTime) {\n alternate.childExpirationTime = expirationTime;\n }\n } else if (alternate !== null && alternate.childExpirationTime < expirationTime) {\n alternate.childExpirationTime = expirationTime;\n }\n\n if (node.return === null && node.tag === HostRoot) {\n root = node.stateNode;\n break;\n }\n\n node = node.return;\n }\n }\n\n if (root !== null) {\n if (workInProgressRoot === root) {\n // Received an update to a tree that's in the middle of rendering. Mark\n // that's unprocessed work on this root.\n markUnprocessedUpdateTime(expirationTime);\n\n if (workInProgressRootExitStatus === RootSuspendedWithDelay) {\n // The root already suspended with a delay, which means this render\n // definitely won't finish. Since we have a new update, let's mark it as\n // suspended now, right before marking the incoming update. This has the\n // effect of interrupting the current render and switching to the update.\n // TODO: This happens to work when receiving an update during the render\n // phase, because of the trick inside computeExpirationForFiber to\n // subtract 1 from `renderExpirationTime` to move it into a\n // separate bucket. But we should probably model it with an exception,\n // using the same mechanism we use to force hydration of a subtree.\n // TODO: This does not account for low pri updates that were already\n // scheduled before the root started rendering. Need to track the next\n // pending expiration time (perhaps by backtracking the return path) and\n // then trigger a restart in the `renderDidSuspendDelayIfPossible` path.\n markRootSuspendedAtTime(root, renderExpirationTime$1);\n }\n } // Mark that the root has a pending update.\n\n\n markRootUpdatedAtTime(root, expirationTime);\n }\n\n return root;\n}\n\nfunction getNextRootExpirationTimeToWorkOn(root) {\n // Determines the next expiration time that the root should render, taking\n // into account levels that may be suspended, or levels that may have\n // received a ping.\n var lastExpiredTime = root.lastExpiredTime;\n\n if (lastExpiredTime !== NoWork) {\n return lastExpiredTime;\n } // \"Pending\" refers to any update that hasn't committed yet, including if it\n // suspended. The \"suspended\" range is therefore a subset.\n\n\n var firstPendingTime = root.firstPendingTime;\n\n if (!isRootSuspendedAtTime(root, firstPendingTime)) {\n // The highest priority pending time is not suspended. Let's work on that.\n return firstPendingTime;\n } // If the first pending time is suspended, check if there's a lower priority\n // pending level that we know about. Or check if we received a ping. Work\n // on whichever is higher priority.\n\n\n var lastPingedTime = root.lastPingedTime;\n var nextKnownPendingLevel = root.nextKnownPendingLevel;\n var nextLevel = lastPingedTime > nextKnownPendingLevel ? lastPingedTime : nextKnownPendingLevel;\n\n if ( nextLevel <= Idle && firstPendingTime !== nextLevel) {\n // Don't work on Idle/Never priority unless everything else is committed.\n return NoWork;\n }\n\n return nextLevel;\n} // Use this function to schedule a task for a root. There's only one task per\n// root; if a task was already scheduled, we'll check to make sure the\n// expiration time of the existing task is the same as the expiration time of\n// the next level that the root has work on. This function is called on every\n// update, and right before exiting a task.\n\n\nfunction ensureRootIsScheduled(root) {\n var lastExpiredTime = root.lastExpiredTime;\n\n if (lastExpiredTime !== NoWork) {\n // Special case: Expired work should flush synchronously.\n root.callbackExpirationTime = Sync;\n root.callbackPriority = ImmediatePriority;\n root.callbackNode = scheduleSyncCallback(performSyncWorkOnRoot.bind(null, root));\n return;\n }\n\n var expirationTime = getNextRootExpirationTimeToWorkOn(root);\n var existingCallbackNode = root.callbackNode;\n\n if (expirationTime === NoWork) {\n // There's nothing to work on.\n if (existingCallbackNode !== null) {\n root.callbackNode = null;\n root.callbackExpirationTime = NoWork;\n root.callbackPriority = NoPriority;\n }\n\n return;\n } // TODO: If this is an update, we already read the current time. Pass the\n // time as an argument.\n\n\n var currentTime = requestCurrentTimeForUpdate();\n var priorityLevel = inferPriorityFromExpirationTime(currentTime, expirationTime); // If there's an existing render task, confirm it has the correct priority and\n // expiration time. Otherwise, we'll cancel it and schedule a new one.\n\n if (existingCallbackNode !== null) {\n var existingCallbackPriority = root.callbackPriority;\n var existingCallbackExpirationTime = root.callbackExpirationTime;\n\n if ( // Callback must have the exact same expiration time.\n existingCallbackExpirationTime === expirationTime && // Callback must have greater or equal priority.\n existingCallbackPriority >= priorityLevel) {\n // Existing callback is sufficient.\n return;\n } // Need to schedule a new task.\n // TODO: Instead of scheduling a new task, we should be able to change the\n // priority of the existing one.\n\n\n cancelCallback(existingCallbackNode);\n }\n\n root.callbackExpirationTime = expirationTime;\n root.callbackPriority = priorityLevel;\n var callbackNode;\n\n if (expirationTime === Sync) {\n // Sync React callbacks are scheduled on a special internal queue\n callbackNode = scheduleSyncCallback(performSyncWorkOnRoot.bind(null, root));\n } else {\n callbackNode = scheduleCallback(priorityLevel, performConcurrentWorkOnRoot.bind(null, root), // Compute a task timeout based on the expiration time. This also affects\n // ordering because tasks are processed in timeout order.\n {\n timeout: expirationTimeToMs(expirationTime) - now()\n });\n }\n\n root.callbackNode = callbackNode;\n} // This is the entry point for every concurrent task, i.e. anything that\n// goes through Scheduler.\n\n\nfunction performConcurrentWorkOnRoot(root, didTimeout) {\n // Since we know we're in a React event, we can clear the current\n // event time. The next update will compute a new event time.\n currentEventTime = NoWork;\n\n if (didTimeout) {\n // The render task took too long to complete. Mark the current time as\n // expired to synchronously render all expired work in a single batch.\n var currentTime = requestCurrentTimeForUpdate();\n markRootExpiredAtTime(root, currentTime); // This will schedule a synchronous callback.\n\n ensureRootIsScheduled(root);\n return null;\n } // Determine the next expiration time to work on, using the fields stored\n // on the root.\n\n\n var expirationTime = getNextRootExpirationTimeToWorkOn(root);\n\n if (expirationTime !== NoWork) {\n var originalCallbackNode = root.callbackNode;\n\n if (!((executionContext & (RenderContext | CommitContext)) === NoContext)) {\n {\n throw Error( \"Should not already be working.\" );\n }\n }\n\n flushPassiveEffects(); // If the root or expiration time have changed, throw out the existing stack\n // and prepare a fresh one. Otherwise we'll continue where we left off.\n\n if (root !== workInProgressRoot || expirationTime !== renderExpirationTime$1) {\n prepareFreshStack(root, expirationTime);\n startWorkOnPendingInteractions(root, expirationTime);\n } // If we have a work-in-progress fiber, it means there's still work to do\n // in this root.\n\n\n if (workInProgress !== null) {\n var prevExecutionContext = executionContext;\n executionContext |= RenderContext;\n var prevDispatcher = pushDispatcher();\n var prevInteractions = pushInteractions(root);\n startWorkLoopTimer(workInProgress);\n\n do {\n try {\n workLoopConcurrent();\n break;\n } catch (thrownValue) {\n handleError(root, thrownValue);\n }\n } while (true);\n\n resetContextDependencies();\n executionContext = prevExecutionContext;\n popDispatcher(prevDispatcher);\n\n {\n popInteractions(prevInteractions);\n }\n\n if (workInProgressRootExitStatus === RootFatalErrored) {\n var fatalError = workInProgressRootFatalError;\n stopInterruptedWorkLoopTimer();\n prepareFreshStack(root, expirationTime);\n markRootSuspendedAtTime(root, expirationTime);\n ensureRootIsScheduled(root);\n throw fatalError;\n }\n\n if (workInProgress !== null) {\n // There's still work left over. Exit without committing.\n stopInterruptedWorkLoopTimer();\n } else {\n // We now have a consistent tree. The next step is either to commit it,\n // or, if something suspended, wait to commit it after a timeout.\n stopFinishedWorkLoopTimer();\n var finishedWork = root.finishedWork = root.current.alternate;\n root.finishedExpirationTime = expirationTime;\n finishConcurrentRender(root, finishedWork, workInProgressRootExitStatus, expirationTime);\n }\n\n ensureRootIsScheduled(root);\n\n if (root.callbackNode === originalCallbackNode) {\n // The task node scheduled for this root is the same one that's\n // currently executed. Need to return a continuation.\n return performConcurrentWorkOnRoot.bind(null, root);\n }\n }\n }\n\n return null;\n}\n\nfunction finishConcurrentRender(root, finishedWork, exitStatus, expirationTime) {\n // Set this to null to indicate there's no in-progress render.\n workInProgressRoot = null;\n\n switch (exitStatus) {\n case RootIncomplete:\n case RootFatalErrored:\n {\n {\n {\n throw Error( \"Root did not complete. This is a bug in React.\" );\n }\n }\n }\n // Flow knows about invariant, so it complains if I add a break\n // statement, but eslint doesn't know about invariant, so it complains\n // if I do. eslint-disable-next-line no-fallthrough\n\n case RootErrored:\n {\n // If this was an async render, the error may have happened due to\n // a mutation in a concurrent event. Try rendering one more time,\n // synchronously, to see if the error goes away. If there are\n // lower priority updates, let's include those, too, in case they\n // fix the inconsistency. Render at Idle to include all updates.\n // If it was Idle or Never or some not-yet-invented time, render\n // at that time.\n markRootExpiredAtTime(root, expirationTime > Idle ? Idle : expirationTime); // We assume that this second render pass will be synchronous\n // and therefore not hit this path again.\n\n break;\n }\n\n case RootSuspended:\n {\n markRootSuspendedAtTime(root, expirationTime);\n var lastSuspendedTime = root.lastSuspendedTime;\n\n if (expirationTime === lastSuspendedTime) {\n root.nextKnownPendingLevel = getRemainingExpirationTime(finishedWork);\n } // We have an acceptable loading state. We need to figure out if we\n // should immediately commit it or wait a bit.\n // If we have processed new updates during this render, we may now\n // have a new loading state ready. We want to ensure that we commit\n // that as soon as possible.\n\n\n var hasNotProcessedNewUpdates = workInProgressRootLatestProcessedExpirationTime === Sync;\n\n if (hasNotProcessedNewUpdates && // do not delay if we're inside an act() scope\n !( IsThisRendererActing.current)) {\n // If we have not processed any new updates during this pass, then\n // this is either a retry of an existing fallback state or a\n // hidden tree. Hidden trees shouldn't be batched with other work\n // and after that's fixed it can only be a retry. We're going to\n // throttle committing retries so that we don't show too many\n // loading states too quickly.\n var msUntilTimeout = globalMostRecentFallbackTime + FALLBACK_THROTTLE_MS - now(); // Don't bother with a very short suspense time.\n\n if (msUntilTimeout > 10) {\n if (workInProgressRootHasPendingPing) {\n var lastPingedTime = root.lastPingedTime;\n\n if (lastPingedTime === NoWork || lastPingedTime >= expirationTime) {\n // This render was pinged but we didn't get to restart\n // earlier so try restarting now instead.\n root.lastPingedTime = expirationTime;\n prepareFreshStack(root, expirationTime);\n break;\n }\n }\n\n var nextTime = getNextRootExpirationTimeToWorkOn(root);\n\n if (nextTime !== NoWork && nextTime !== expirationTime) {\n // There's additional work on this root.\n break;\n }\n\n if (lastSuspendedTime !== NoWork && lastSuspendedTime !== expirationTime) {\n // We should prefer to render the fallback of at the last\n // suspended level. Ping the last suspended level to try\n // rendering it again.\n root.lastPingedTime = lastSuspendedTime;\n break;\n } // The render is suspended, it hasn't timed out, and there's no\n // lower priority work to do. Instead of committing the fallback\n // immediately, wait for more data to arrive.\n\n\n root.timeoutHandle = scheduleTimeout(commitRoot.bind(null, root), msUntilTimeout);\n break;\n }\n } // The work expired. Commit immediately.\n\n\n commitRoot(root);\n break;\n }\n\n case RootSuspendedWithDelay:\n {\n markRootSuspendedAtTime(root, expirationTime);\n var _lastSuspendedTime = root.lastSuspendedTime;\n\n if (expirationTime === _lastSuspendedTime) {\n root.nextKnownPendingLevel = getRemainingExpirationTime(finishedWork);\n }\n\n if ( // do not delay if we're inside an act() scope\n !( IsThisRendererActing.current)) {\n // We're suspended in a state that should be avoided. We'll try to\n // avoid committing it for as long as the timeouts let us.\n if (workInProgressRootHasPendingPing) {\n var _lastPingedTime = root.lastPingedTime;\n\n if (_lastPingedTime === NoWork || _lastPingedTime >= expirationTime) {\n // This render was pinged but we didn't get to restart earlier\n // so try restarting now instead.\n root.lastPingedTime = expirationTime;\n prepareFreshStack(root, expirationTime);\n break;\n }\n }\n\n var _nextTime = getNextRootExpirationTimeToWorkOn(root);\n\n if (_nextTime !== NoWork && _nextTime !== expirationTime) {\n // There's additional work on this root.\n break;\n }\n\n if (_lastSuspendedTime !== NoWork && _lastSuspendedTime !== expirationTime) {\n // We should prefer to render the fallback of at the last\n // suspended level. Ping the last suspended level to try\n // rendering it again.\n root.lastPingedTime = _lastSuspendedTime;\n break;\n }\n\n var _msUntilTimeout;\n\n if (workInProgressRootLatestSuspenseTimeout !== Sync) {\n // We have processed a suspense config whose expiration time we\n // can use as the timeout.\n _msUntilTimeout = expirationTimeToMs(workInProgressRootLatestSuspenseTimeout) - now();\n } else if (workInProgressRootLatestProcessedExpirationTime === Sync) {\n // This should never normally happen because only new updates\n // cause delayed states, so we should have processed something.\n // However, this could also happen in an offscreen tree.\n _msUntilTimeout = 0;\n } else {\n // If we don't have a suspense config, we're going to use a\n // heuristic to determine how long we can suspend.\n var eventTimeMs = inferTimeFromExpirationTime(workInProgressRootLatestProcessedExpirationTime);\n var currentTimeMs = now();\n var timeUntilExpirationMs = expirationTimeToMs(expirationTime) - currentTimeMs;\n var timeElapsed = currentTimeMs - eventTimeMs;\n\n if (timeElapsed < 0) {\n // We get this wrong some time since we estimate the time.\n timeElapsed = 0;\n }\n\n _msUntilTimeout = jnd(timeElapsed) - timeElapsed; // Clamp the timeout to the expiration time. TODO: Once the\n // event time is exact instead of inferred from expiration time\n // we don't need this.\n\n if (timeUntilExpirationMs < _msUntilTimeout) {\n _msUntilTimeout = timeUntilExpirationMs;\n }\n } // Don't bother with a very short suspense time.\n\n\n if (_msUntilTimeout > 10) {\n // The render is suspended, it hasn't timed out, and there's no\n // lower priority work to do. Instead of committing the fallback\n // immediately, wait for more data to arrive.\n root.timeoutHandle = scheduleTimeout(commitRoot.bind(null, root), _msUntilTimeout);\n break;\n }\n } // The work expired. Commit immediately.\n\n\n commitRoot(root);\n break;\n }\n\n case RootCompleted:\n {\n // The work completed. Ready to commit.\n if ( // do not delay if we're inside an act() scope\n !( IsThisRendererActing.current) && workInProgressRootLatestProcessedExpirationTime !== Sync && workInProgressRootCanSuspendUsingConfig !== null) {\n // If we have exceeded the minimum loading delay, which probably\n // means we have shown a spinner already, we might have to suspend\n // a bit longer to ensure that the spinner is shown for\n // enough time.\n var _msUntilTimeout2 = computeMsUntilSuspenseLoadingDelay(workInProgressRootLatestProcessedExpirationTime, expirationTime, workInProgressRootCanSuspendUsingConfig);\n\n if (_msUntilTimeout2 > 10) {\n markRootSuspendedAtTime(root, expirationTime);\n root.timeoutHandle = scheduleTimeout(commitRoot.bind(null, root), _msUntilTimeout2);\n break;\n }\n }\n\n commitRoot(root);\n break;\n }\n\n default:\n {\n {\n {\n throw Error( \"Unknown root exit status.\" );\n }\n }\n }\n }\n} // This is the entry point for synchronous tasks that don't go\n// through Scheduler\n\n\nfunction performSyncWorkOnRoot(root) {\n // Check if there's expired work on this root. Otherwise, render at Sync.\n var lastExpiredTime = root.lastExpiredTime;\n var expirationTime = lastExpiredTime !== NoWork ? lastExpiredTime : Sync;\n\n if (!((executionContext & (RenderContext | CommitContext)) === NoContext)) {\n {\n throw Error( \"Should not already be working.\" );\n }\n }\n\n flushPassiveEffects(); // If the root or expiration time have changed, throw out the existing stack\n // and prepare a fresh one. Otherwise we'll continue where we left off.\n\n if (root !== workInProgressRoot || expirationTime !== renderExpirationTime$1) {\n prepareFreshStack(root, expirationTime);\n startWorkOnPendingInteractions(root, expirationTime);\n } // If we have a work-in-progress fiber, it means there's still work to do\n // in this root.\n\n\n if (workInProgress !== null) {\n var prevExecutionContext = executionContext;\n executionContext |= RenderContext;\n var prevDispatcher = pushDispatcher();\n var prevInteractions = pushInteractions(root);\n startWorkLoopTimer(workInProgress);\n\n do {\n try {\n workLoopSync();\n break;\n } catch (thrownValue) {\n handleError(root, thrownValue);\n }\n } while (true);\n\n resetContextDependencies();\n executionContext = prevExecutionContext;\n popDispatcher(prevDispatcher);\n\n {\n popInteractions(prevInteractions);\n }\n\n if (workInProgressRootExitStatus === RootFatalErrored) {\n var fatalError = workInProgressRootFatalError;\n stopInterruptedWorkLoopTimer();\n prepareFreshStack(root, expirationTime);\n markRootSuspendedAtTime(root, expirationTime);\n ensureRootIsScheduled(root);\n throw fatalError;\n }\n\n if (workInProgress !== null) {\n // This is a sync render, so we should have finished the whole tree.\n {\n {\n throw Error( \"Cannot commit an incomplete root. This error is likely caused by a bug in React. Please file an issue.\" );\n }\n }\n } else {\n // We now have a consistent tree. Because this is a sync render, we\n // will commit it even if something suspended.\n stopFinishedWorkLoopTimer();\n root.finishedWork = root.current.alternate;\n root.finishedExpirationTime = expirationTime;\n finishSyncRender(root);\n } // Before exiting, make sure there's a callback scheduled for the next\n // pending level.\n\n\n ensureRootIsScheduled(root);\n }\n\n return null;\n}\n\nfunction finishSyncRender(root) {\n // Set this to null to indicate there's no in-progress render.\n workInProgressRoot = null;\n commitRoot(root);\n}\nfunction flushDiscreteUpdates() {\n // TODO: Should be able to flush inside batchedUpdates, but not inside `act`.\n // However, `act` uses `batchedUpdates`, so there's no way to distinguish\n // those two cases. Need to fix this before exposing flushDiscreteUpdates\n // as a public API.\n if ((executionContext & (BatchedContext | RenderContext | CommitContext)) !== NoContext) {\n {\n if ((executionContext & RenderContext) !== NoContext) {\n error('unstable_flushDiscreteUpdates: Cannot flush updates when React is ' + 'already rendering.');\n }\n } // We're already rendering, so we can't synchronously flush pending work.\n // This is probably a nested event dispatch triggered by a lifecycle/effect,\n // like `el.focus()`. Exit.\n\n\n return;\n }\n\n flushPendingDiscreteUpdates(); // If the discrete updates scheduled passive effects, flush them now so that\n // they fire before the next serial event.\n\n flushPassiveEffects();\n}\nfunction syncUpdates(fn, a, b, c) {\n return runWithPriority$1(ImmediatePriority, fn.bind(null, a, b, c));\n}\n\nfunction flushPendingDiscreteUpdates() {\n if (rootsWithPendingDiscreteUpdates !== null) {\n // For each root with pending discrete updates, schedule a callback to\n // immediately flush them.\n var roots = rootsWithPendingDiscreteUpdates;\n rootsWithPendingDiscreteUpdates = null;\n roots.forEach(function (expirationTime, root) {\n markRootExpiredAtTime(root, expirationTime);\n ensureRootIsScheduled(root);\n }); // Now flush the immediate queue.\n\n flushSyncCallbackQueue();\n }\n}\n\nfunction batchedUpdates$1(fn, a) {\n var prevExecutionContext = executionContext;\n executionContext |= BatchedContext;\n\n try {\n return fn(a);\n } finally {\n executionContext = prevExecutionContext;\n\n if (executionContext === NoContext) {\n // Flush the immediate callbacks that were scheduled during this batch\n flushSyncCallbackQueue();\n }\n }\n}\nfunction batchedEventUpdates$1(fn, a) {\n var prevExecutionContext = executionContext;\n executionContext |= EventContext;\n\n try {\n return fn(a);\n } finally {\n executionContext = prevExecutionContext;\n\n if (executionContext === NoContext) {\n // Flush the immediate callbacks that were scheduled during this batch\n flushSyncCallbackQueue();\n }\n }\n}\nfunction discreteUpdates$1(fn, a, b, c, d) {\n var prevExecutionContext = executionContext;\n executionContext |= DiscreteEventContext;\n\n try {\n // Should this\n return runWithPriority$1(UserBlockingPriority$1, fn.bind(null, a, b, c, d));\n } finally {\n executionContext = prevExecutionContext;\n\n if (executionContext === NoContext) {\n // Flush the immediate callbacks that were scheduled during this batch\n flushSyncCallbackQueue();\n }\n }\n}\nfunction unbatchedUpdates(fn, a) {\n var prevExecutionContext = executionContext;\n executionContext &= ~BatchedContext;\n executionContext |= LegacyUnbatchedContext;\n\n try {\n return fn(a);\n } finally {\n executionContext = prevExecutionContext;\n\n if (executionContext === NoContext) {\n // Flush the immediate callbacks that were scheduled during this batch\n flushSyncCallbackQueue();\n }\n }\n}\nfunction flushSync(fn, a) {\n if ((executionContext & (RenderContext | CommitContext)) !== NoContext) {\n {\n {\n throw Error( \"flushSync was called from inside a lifecycle method. It cannot be called when React is already rendering.\" );\n }\n }\n }\n\n var prevExecutionContext = executionContext;\n executionContext |= BatchedContext;\n\n try {\n return runWithPriority$1(ImmediatePriority, fn.bind(null, a));\n } finally {\n executionContext = prevExecutionContext; // Flush the immediate callbacks that were scheduled during this batch.\n // Note that this will happen even if batchedUpdates is higher up\n // the stack.\n\n flushSyncCallbackQueue();\n }\n}\n\nfunction prepareFreshStack(root, expirationTime) {\n root.finishedWork = null;\n root.finishedExpirationTime = NoWork;\n var timeoutHandle = root.timeoutHandle;\n\n if (timeoutHandle !== noTimeout) {\n // The root previous suspended and scheduled a timeout to commit a fallback\n // state. Now that we have additional work, cancel the timeout.\n root.timeoutHandle = noTimeout; // $FlowFixMe Complains noTimeout is not a TimeoutID, despite the check above\n\n cancelTimeout(timeoutHandle);\n }\n\n if (workInProgress !== null) {\n var interruptedWork = workInProgress.return;\n\n while (interruptedWork !== null) {\n unwindInterruptedWork(interruptedWork);\n interruptedWork = interruptedWork.return;\n }\n }\n\n workInProgressRoot = root;\n workInProgress = createWorkInProgress(root.current, null);\n renderExpirationTime$1 = expirationTime;\n workInProgressRootExitStatus = RootIncomplete;\n workInProgressRootFatalError = null;\n workInProgressRootLatestProcessedExpirationTime = Sync;\n workInProgressRootLatestSuspenseTimeout = Sync;\n workInProgressRootCanSuspendUsingConfig = null;\n workInProgressRootNextUnprocessedUpdateTime = NoWork;\n workInProgressRootHasPendingPing = false;\n\n {\n spawnedWorkDuringRender = null;\n }\n\n {\n ReactStrictModeWarnings.discardPendingWarnings();\n }\n}\n\nfunction handleError(root, thrownValue) {\n do {\n try {\n // Reset module-level state that was set during the render phase.\n resetContextDependencies();\n resetHooksAfterThrow();\n resetCurrentFiber();\n\n if (workInProgress === null || workInProgress.return === null) {\n // Expected to be working on a non-root fiber. This is a fatal error\n // because there's no ancestor that can handle it; the root is\n // supposed to capture all errors that weren't caught by an error\n // boundary.\n workInProgressRootExitStatus = RootFatalErrored;\n workInProgressRootFatalError = thrownValue; // Set `workInProgress` to null. This represents advancing to the next\n // sibling, or the parent if there are no siblings. But since the root\n // has no siblings nor a parent, we set it to null. Usually this is\n // handled by `completeUnitOfWork` or `unwindWork`, but since we're\n // interntionally not calling those, we need set it here.\n // TODO: Consider calling `unwindWork` to pop the contexts.\n\n workInProgress = null;\n return null;\n }\n\n if (enableProfilerTimer && workInProgress.mode & ProfileMode) {\n // Record the time spent rendering before an error was thrown. This\n // avoids inaccurate Profiler durations in the case of a\n // suspended render.\n stopProfilerTimerIfRunningAndRecordDelta(workInProgress, true);\n }\n\n throwException(root, workInProgress.return, workInProgress, thrownValue, renderExpirationTime$1);\n workInProgress = completeUnitOfWork(workInProgress);\n } catch (yetAnotherThrownValue) {\n // Something in the return path also threw.\n thrownValue = yetAnotherThrownValue;\n continue;\n } // Return to the normal work loop.\n\n\n return;\n } while (true);\n}\n\nfunction pushDispatcher(root) {\n var prevDispatcher = ReactCurrentDispatcher$1.current;\n ReactCurrentDispatcher$1.current = ContextOnlyDispatcher;\n\n if (prevDispatcher === null) {\n // The React isomorphic package does not include a default dispatcher.\n // Instead the first renderer will lazily attach one, in order to give\n // nicer error messages.\n return ContextOnlyDispatcher;\n } else {\n return prevDispatcher;\n }\n}\n\nfunction popDispatcher(prevDispatcher) {\n ReactCurrentDispatcher$1.current = prevDispatcher;\n}\n\nfunction pushInteractions(root) {\n {\n var prevInteractions = tracing.__interactionsRef.current;\n tracing.__interactionsRef.current = root.memoizedInteractions;\n return prevInteractions;\n }\n}\n\nfunction popInteractions(prevInteractions) {\n {\n tracing.__interactionsRef.current = prevInteractions;\n }\n}\n\nfunction markCommitTimeOfFallback() {\n globalMostRecentFallbackTime = now();\n}\nfunction markRenderEventTimeAndConfig(expirationTime, suspenseConfig) {\n if (expirationTime < workInProgressRootLatestProcessedExpirationTime && expirationTime > Idle) {\n workInProgressRootLatestProcessedExpirationTime = expirationTime;\n }\n\n if (suspenseConfig !== null) {\n if (expirationTime < workInProgressRootLatestSuspenseTimeout && expirationTime > Idle) {\n workInProgressRootLatestSuspenseTimeout = expirationTime; // Most of the time we only have one config and getting wrong is not bad.\n\n workInProgressRootCanSuspendUsingConfig = suspenseConfig;\n }\n }\n}\nfunction markUnprocessedUpdateTime(expirationTime) {\n if (expirationTime > workInProgressRootNextUnprocessedUpdateTime) {\n workInProgressRootNextUnprocessedUpdateTime = expirationTime;\n }\n}\nfunction renderDidSuspend() {\n if (workInProgressRootExitStatus === RootIncomplete) {\n workInProgressRootExitStatus = RootSuspended;\n }\n}\nfunction renderDidSuspendDelayIfPossible() {\n if (workInProgressRootExitStatus === RootIncomplete || workInProgressRootExitStatus === RootSuspended) {\n workInProgressRootExitStatus = RootSuspendedWithDelay;\n } // Check if there's a lower priority update somewhere else in the tree.\n\n\n if (workInProgressRootNextUnprocessedUpdateTime !== NoWork && workInProgressRoot !== null) {\n // Mark the current render as suspended, and then mark that there's a\n // pending update.\n // TODO: This should immediately interrupt the current render, instead\n // of waiting until the next time we yield.\n markRootSuspendedAtTime(workInProgressRoot, renderExpirationTime$1);\n markRootUpdatedAtTime(workInProgressRoot, workInProgressRootNextUnprocessedUpdateTime);\n }\n}\nfunction renderDidError() {\n if (workInProgressRootExitStatus !== RootCompleted) {\n workInProgressRootExitStatus = RootErrored;\n }\n} // Called during render to determine if anything has suspended.\n// Returns false if we're not sure.\n\nfunction renderHasNotSuspendedYet() {\n // If something errored or completed, we can't really be sure,\n // so those are false.\n return workInProgressRootExitStatus === RootIncomplete;\n}\n\nfunction inferTimeFromExpirationTime(expirationTime) {\n // We don't know exactly when the update was scheduled, but we can infer an\n // approximate start time from the expiration time.\n var earliestExpirationTimeMs = expirationTimeToMs(expirationTime);\n return earliestExpirationTimeMs - LOW_PRIORITY_EXPIRATION;\n}\n\nfunction inferTimeFromExpirationTimeWithSuspenseConfig(expirationTime, suspenseConfig) {\n // We don't know exactly when the update was scheduled, but we can infer an\n // approximate start time from the expiration time by subtracting the timeout\n // that was added to the event time.\n var earliestExpirationTimeMs = expirationTimeToMs(expirationTime);\n return earliestExpirationTimeMs - (suspenseConfig.timeoutMs | 0 || LOW_PRIORITY_EXPIRATION);\n} // The work loop is an extremely hot path. Tell Closure not to inline it.\n\n/** @noinline */\n\n\nfunction workLoopSync() {\n // Already timed out, so perform work without checking if we need to yield.\n while (workInProgress !== null) {\n workInProgress = performUnitOfWork(workInProgress);\n }\n}\n/** @noinline */\n\n\nfunction workLoopConcurrent() {\n // Perform work until Scheduler asks us to yield\n while (workInProgress !== null && !shouldYield()) {\n workInProgress = performUnitOfWork(workInProgress);\n }\n}\n\nfunction performUnitOfWork(unitOfWork) {\n // The current, flushed, state of this fiber is the alternate. Ideally\n // nothing should rely on this, but relying on it here means that we don't\n // need an additional field on the work in progress.\n var current = unitOfWork.alternate;\n startWorkTimer(unitOfWork);\n setCurrentFiber(unitOfWork);\n var next;\n\n if ( (unitOfWork.mode & ProfileMode) !== NoMode) {\n startProfilerTimer(unitOfWork);\n next = beginWork$1(current, unitOfWork, renderExpirationTime$1);\n stopProfilerTimerIfRunningAndRecordDelta(unitOfWork, true);\n } else {\n next = beginWork$1(current, unitOfWork, renderExpirationTime$1);\n }\n\n resetCurrentFiber();\n unitOfWork.memoizedProps = unitOfWork.pendingProps;\n\n if (next === null) {\n // If this doesn't spawn new work, complete the current work.\n next = completeUnitOfWork(unitOfWork);\n }\n\n ReactCurrentOwner$2.current = null;\n return next;\n}\n\nfunction completeUnitOfWork(unitOfWork) {\n // Attempt to complete the current unit of work, then move to the next\n // sibling. If there are no more siblings, return to the parent fiber.\n workInProgress = unitOfWork;\n\n do {\n // The current, flushed, state of this fiber is the alternate. Ideally\n // nothing should rely on this, but relying on it here means that we don't\n // need an additional field on the work in progress.\n var current = workInProgress.alternate;\n var returnFiber = workInProgress.return; // Check if the work completed or if something threw.\n\n if ((workInProgress.effectTag & Incomplete) === NoEffect) {\n setCurrentFiber(workInProgress);\n var next = void 0;\n\n if ( (workInProgress.mode & ProfileMode) === NoMode) {\n next = completeWork(current, workInProgress, renderExpirationTime$1);\n } else {\n startProfilerTimer(workInProgress);\n next = completeWork(current, workInProgress, renderExpirationTime$1); // Update render duration assuming we didn't error.\n\n stopProfilerTimerIfRunningAndRecordDelta(workInProgress, false);\n }\n\n stopWorkTimer(workInProgress);\n resetCurrentFiber();\n resetChildExpirationTime(workInProgress);\n\n if (next !== null) {\n // Completing this fiber spawned new work. Work on that next.\n return next;\n }\n\n if (returnFiber !== null && // Do not append effects to parents if a sibling failed to complete\n (returnFiber.effectTag & Incomplete) === NoEffect) {\n // Append all the effects of the subtree and this fiber onto the effect\n // list of the parent. The completion order of the children affects the\n // side-effect order.\n if (returnFiber.firstEffect === null) {\n returnFiber.firstEffect = workInProgress.firstEffect;\n }\n\n if (workInProgress.lastEffect !== null) {\n if (returnFiber.lastEffect !== null) {\n returnFiber.lastEffect.nextEffect = workInProgress.firstEffect;\n }\n\n returnFiber.lastEffect = workInProgress.lastEffect;\n } // If this fiber had side-effects, we append it AFTER the children's\n // side-effects. We can perform certain side-effects earlier if needed,\n // by doing multiple passes over the effect list. We don't want to\n // schedule our own side-effect on our own list because if end up\n // reusing children we'll schedule this effect onto itself since we're\n // at the end.\n\n\n var effectTag = workInProgress.effectTag; // Skip both NoWork and PerformedWork tags when creating the effect\n // list. PerformedWork effect is read by React DevTools but shouldn't be\n // committed.\n\n if (effectTag > PerformedWork) {\n if (returnFiber.lastEffect !== null) {\n returnFiber.lastEffect.nextEffect = workInProgress;\n } else {\n returnFiber.firstEffect = workInProgress;\n }\n\n returnFiber.lastEffect = workInProgress;\n }\n }\n } else {\n // This fiber did not complete because something threw. Pop values off\n // the stack without entering the complete phase. If this is a boundary,\n // capture values if possible.\n var _next = unwindWork(workInProgress); // Because this fiber did not complete, don't reset its expiration time.\n\n\n if ( (workInProgress.mode & ProfileMode) !== NoMode) {\n // Record the render duration for the fiber that errored.\n stopProfilerTimerIfRunningAndRecordDelta(workInProgress, false); // Include the time spent working on failed children before continuing.\n\n var actualDuration = workInProgress.actualDuration;\n var child = workInProgress.child;\n\n while (child !== null) {\n actualDuration += child.actualDuration;\n child = child.sibling;\n }\n\n workInProgress.actualDuration = actualDuration;\n }\n\n if (_next !== null) {\n // If completing this work spawned new work, do that next. We'll come\n // back here again.\n // Since we're restarting, remove anything that is not a host effect\n // from the effect tag.\n // TODO: The name stopFailedWorkTimer is misleading because Suspense\n // also captures and restarts.\n stopFailedWorkTimer(workInProgress);\n _next.effectTag &= HostEffectMask;\n return _next;\n }\n\n stopWorkTimer(workInProgress);\n\n if (returnFiber !== null) {\n // Mark the parent fiber as incomplete and clear its effect list.\n returnFiber.firstEffect = returnFiber.lastEffect = null;\n returnFiber.effectTag |= Incomplete;\n }\n }\n\n var siblingFiber = workInProgress.sibling;\n\n if (siblingFiber !== null) {\n // If there is more work to do in this returnFiber, do that next.\n return siblingFiber;\n } // Otherwise, return to the parent\n\n\n workInProgress = returnFiber;\n } while (workInProgress !== null); // We've reached the root.\n\n\n if (workInProgressRootExitStatus === RootIncomplete) {\n workInProgressRootExitStatus = RootCompleted;\n }\n\n return null;\n}\n\nfunction getRemainingExpirationTime(fiber) {\n var updateExpirationTime = fiber.expirationTime;\n var childExpirationTime = fiber.childExpirationTime;\n return updateExpirationTime > childExpirationTime ? updateExpirationTime : childExpirationTime;\n}\n\nfunction resetChildExpirationTime(completedWork) {\n if (renderExpirationTime$1 !== Never && completedWork.childExpirationTime === Never) {\n // The children of this component are hidden. Don't bubble their\n // expiration times.\n return;\n }\n\n var newChildExpirationTime = NoWork; // Bubble up the earliest expiration time.\n\n if ( (completedWork.mode & ProfileMode) !== NoMode) {\n // In profiling mode, resetChildExpirationTime is also used to reset\n // profiler durations.\n var actualDuration = completedWork.actualDuration;\n var treeBaseDuration = completedWork.selfBaseDuration; // When a fiber is cloned, its actualDuration is reset to 0. This value will\n // only be updated if work is done on the fiber (i.e. it doesn't bailout).\n // When work is done, it should bubble to the parent's actualDuration. If\n // the fiber has not been cloned though, (meaning no work was done), then\n // this value will reflect the amount of time spent working on a previous\n // render. In that case it should not bubble. We determine whether it was\n // cloned by comparing the child pointer.\n\n var shouldBubbleActualDurations = completedWork.alternate === null || completedWork.child !== completedWork.alternate.child;\n var child = completedWork.child;\n\n while (child !== null) {\n var childUpdateExpirationTime = child.expirationTime;\n var childChildExpirationTime = child.childExpirationTime;\n\n if (childUpdateExpirationTime > newChildExpirationTime) {\n newChildExpirationTime = childUpdateExpirationTime;\n }\n\n if (childChildExpirationTime > newChildExpirationTime) {\n newChildExpirationTime = childChildExpirationTime;\n }\n\n if (shouldBubbleActualDurations) {\n actualDuration += child.actualDuration;\n }\n\n treeBaseDuration += child.treeBaseDuration;\n child = child.sibling;\n }\n\n completedWork.actualDuration = actualDuration;\n completedWork.treeBaseDuration = treeBaseDuration;\n } else {\n var _child = completedWork.child;\n\n while (_child !== null) {\n var _childUpdateExpirationTime = _child.expirationTime;\n var _childChildExpirationTime = _child.childExpirationTime;\n\n if (_childUpdateExpirationTime > newChildExpirationTime) {\n newChildExpirationTime = _childUpdateExpirationTime;\n }\n\n if (_childChildExpirationTime > newChildExpirationTime) {\n newChildExpirationTime = _childChildExpirationTime;\n }\n\n _child = _child.sibling;\n }\n }\n\n completedWork.childExpirationTime = newChildExpirationTime;\n}\n\nfunction commitRoot(root) {\n var renderPriorityLevel = getCurrentPriorityLevel();\n runWithPriority$1(ImmediatePriority, commitRootImpl.bind(null, root, renderPriorityLevel));\n return null;\n}\n\nfunction commitRootImpl(root, renderPriorityLevel) {\n do {\n // `flushPassiveEffects` will call `flushSyncUpdateQueue` at the end, which\n // means `flushPassiveEffects` will sometimes result in additional\n // passive effects. So we need to keep flushing in a loop until there are\n // no more pending effects.\n // TODO: Might be better if `flushPassiveEffects` did not automatically\n // flush synchronous work at the end, to avoid factoring hazards like this.\n flushPassiveEffects();\n } while (rootWithPendingPassiveEffects !== null);\n\n flushRenderPhaseStrictModeWarningsInDEV();\n\n if (!((executionContext & (RenderContext | CommitContext)) === NoContext)) {\n {\n throw Error( \"Should not already be working.\" );\n }\n }\n\n var finishedWork = root.finishedWork;\n var expirationTime = root.finishedExpirationTime;\n\n if (finishedWork === null) {\n return null;\n }\n\n root.finishedWork = null;\n root.finishedExpirationTime = NoWork;\n\n if (!(finishedWork !== root.current)) {\n {\n throw Error( \"Cannot commit the same tree as before. This error is likely caused by a bug in React. Please file an issue.\" );\n }\n } // commitRoot never returns a continuation; it always finishes synchronously.\n // So we can clear these now to allow a new callback to be scheduled.\n\n\n root.callbackNode = null;\n root.callbackExpirationTime = NoWork;\n root.callbackPriority = NoPriority;\n root.nextKnownPendingLevel = NoWork;\n startCommitTimer(); // Update the first and last pending times on this root. The new first\n // pending time is whatever is left on the root fiber.\n\n var remainingExpirationTimeBeforeCommit = getRemainingExpirationTime(finishedWork);\n markRootFinishedAtTime(root, expirationTime, remainingExpirationTimeBeforeCommit);\n\n if (root === workInProgressRoot) {\n // We can reset these now that they are finished.\n workInProgressRoot = null;\n workInProgress = null;\n renderExpirationTime$1 = NoWork;\n } // This indicates that the last root we worked on is not the same one that\n // we're committing now. This most commonly happens when a suspended root\n // times out.\n // Get the list of effects.\n\n\n var firstEffect;\n\n if (finishedWork.effectTag > PerformedWork) {\n // A fiber's effect list consists only of its children, not itself. So if\n // the root has an effect, we need to add it to the end of the list. The\n // resulting list is the set that would belong to the root's parent, if it\n // had one; that is, all the effects in the tree including the root.\n if (finishedWork.lastEffect !== null) {\n finishedWork.lastEffect.nextEffect = finishedWork;\n firstEffect = finishedWork.firstEffect;\n } else {\n firstEffect = finishedWork;\n }\n } else {\n // There is no effect on the root.\n firstEffect = finishedWork.firstEffect;\n }\n\n if (firstEffect !== null) {\n var prevExecutionContext = executionContext;\n executionContext |= CommitContext;\n var prevInteractions = pushInteractions(root); // Reset this to null before calling lifecycles\n\n ReactCurrentOwner$2.current = null; // The commit phase is broken into several sub-phases. We do a separate pass\n // of the effect list for each phase: all mutation effects come before all\n // layout effects, and so on.\n // The first phase a \"before mutation\" phase. We use this phase to read the\n // state of the host tree right before we mutate it. This is where\n // getSnapshotBeforeUpdate is called.\n\n startCommitSnapshotEffectsTimer();\n prepareForCommit(root.containerInfo);\n nextEffect = firstEffect;\n\n do {\n {\n invokeGuardedCallback(null, commitBeforeMutationEffects, null);\n\n if (hasCaughtError()) {\n if (!(nextEffect !== null)) {\n {\n throw Error( \"Should be working on an effect.\" );\n }\n }\n\n var error = clearCaughtError();\n captureCommitPhaseError(nextEffect, error);\n nextEffect = nextEffect.nextEffect;\n }\n }\n } while (nextEffect !== null);\n\n stopCommitSnapshotEffectsTimer();\n\n {\n // Mark the current commit time to be shared by all Profilers in this\n // batch. This enables them to be grouped later.\n recordCommitTime();\n } // The next phase is the mutation phase, where we mutate the host tree.\n\n\n startCommitHostEffectsTimer();\n nextEffect = firstEffect;\n\n do {\n {\n invokeGuardedCallback(null, commitMutationEffects, null, root, renderPriorityLevel);\n\n if (hasCaughtError()) {\n if (!(nextEffect !== null)) {\n {\n throw Error( \"Should be working on an effect.\" );\n }\n }\n\n var _error = clearCaughtError();\n\n captureCommitPhaseError(nextEffect, _error);\n nextEffect = nextEffect.nextEffect;\n }\n }\n } while (nextEffect !== null);\n\n stopCommitHostEffectsTimer();\n resetAfterCommit(root.containerInfo); // The work-in-progress tree is now the current tree. This must come after\n // the mutation phase, so that the previous tree is still current during\n // componentWillUnmount, but before the layout phase, so that the finished\n // work is current during componentDidMount/Update.\n\n root.current = finishedWork; // The next phase is the layout phase, where we call effects that read\n // the host tree after it's been mutated. The idiomatic use case for this is\n // layout, but class component lifecycles also fire here for legacy reasons.\n\n startCommitLifeCyclesTimer();\n nextEffect = firstEffect;\n\n do {\n {\n invokeGuardedCallback(null, commitLayoutEffects, null, root, expirationTime);\n\n if (hasCaughtError()) {\n if (!(nextEffect !== null)) {\n {\n throw Error( \"Should be working on an effect.\" );\n }\n }\n\n var _error2 = clearCaughtError();\n\n captureCommitPhaseError(nextEffect, _error2);\n nextEffect = nextEffect.nextEffect;\n }\n }\n } while (nextEffect !== null);\n\n stopCommitLifeCyclesTimer();\n nextEffect = null; // Tell Scheduler to yield at the end of the frame, so the browser has an\n // opportunity to paint.\n\n requestPaint();\n\n {\n popInteractions(prevInteractions);\n }\n\n executionContext = prevExecutionContext;\n } else {\n // No effects.\n root.current = finishedWork; // Measure these anyway so the flamegraph explicitly shows that there were\n // no effects.\n // TODO: Maybe there's a better way to report this.\n\n startCommitSnapshotEffectsTimer();\n stopCommitSnapshotEffectsTimer();\n\n {\n recordCommitTime();\n }\n\n startCommitHostEffectsTimer();\n stopCommitHostEffectsTimer();\n startCommitLifeCyclesTimer();\n stopCommitLifeCyclesTimer();\n }\n\n stopCommitTimer();\n var rootDidHavePassiveEffects = rootDoesHavePassiveEffects;\n\n if (rootDoesHavePassiveEffects) {\n // This commit has passive effects. Stash a reference to them. But don't\n // schedule a callback until after flushing layout work.\n rootDoesHavePassiveEffects = false;\n rootWithPendingPassiveEffects = root;\n pendingPassiveEffectsExpirationTime = expirationTime;\n pendingPassiveEffectsRenderPriority = renderPriorityLevel;\n } else {\n // We are done with the effect chain at this point so let's clear the\n // nextEffect pointers to assist with GC. If we have passive effects, we'll\n // clear this in flushPassiveEffects.\n nextEffect = firstEffect;\n\n while (nextEffect !== null) {\n var nextNextEffect = nextEffect.nextEffect;\n nextEffect.nextEffect = null;\n nextEffect = nextNextEffect;\n }\n } // Check if there's remaining work on this root\n\n\n var remainingExpirationTime = root.firstPendingTime;\n\n if (remainingExpirationTime !== NoWork) {\n {\n if (spawnedWorkDuringRender !== null) {\n var expirationTimes = spawnedWorkDuringRender;\n spawnedWorkDuringRender = null;\n\n for (var i = 0; i < expirationTimes.length; i++) {\n scheduleInteractions(root, expirationTimes[i], root.memoizedInteractions);\n }\n }\n\n schedulePendingInteractions(root, remainingExpirationTime);\n }\n } else {\n // If there's no remaining work, we can clear the set of already failed\n // error boundaries.\n legacyErrorBoundariesThatAlreadyFailed = null;\n }\n\n {\n if (!rootDidHavePassiveEffects) {\n // If there are no passive effects, then we can complete the pending interactions.\n // Otherwise, we'll wait until after the passive effects are flushed.\n // Wait to do this until after remaining work has been scheduled,\n // so that we don't prematurely signal complete for interactions when there's e.g. hidden work.\n finishPendingInteractions(root, expirationTime);\n }\n }\n\n if (remainingExpirationTime === Sync) {\n // Count the number of times the root synchronously re-renders without\n // finishing. If there are too many, it indicates an infinite update loop.\n if (root === rootWithNestedUpdates) {\n nestedUpdateCount++;\n } else {\n nestedUpdateCount = 0;\n rootWithNestedUpdates = root;\n }\n } else {\n nestedUpdateCount = 0;\n }\n\n onCommitRoot(finishedWork.stateNode, expirationTime); // Always call this before exiting `commitRoot`, to ensure that any\n // additional work on this root is scheduled.\n\n ensureRootIsScheduled(root);\n\n if (hasUncaughtError) {\n hasUncaughtError = false;\n var _error3 = firstUncaughtError;\n firstUncaughtError = null;\n throw _error3;\n }\n\n if ((executionContext & LegacyUnbatchedContext) !== NoContext) {\n // This is a legacy edge case. We just committed the initial mount of\n // a ReactDOM.render-ed root inside of batchedUpdates. The commit fired\n // synchronously, but layout updates should be deferred until the end\n // of the batch.\n return null;\n } // If layout work was scheduled, flush it now.\n\n\n flushSyncCallbackQueue();\n return null;\n}\n\nfunction commitBeforeMutationEffects() {\n while (nextEffect !== null) {\n var effectTag = nextEffect.effectTag;\n\n if ((effectTag & Snapshot) !== NoEffect) {\n setCurrentFiber(nextEffect);\n recordEffect();\n var current = nextEffect.alternate;\n commitBeforeMutationLifeCycles(current, nextEffect);\n resetCurrentFiber();\n }\n\n if ((effectTag & Passive) !== NoEffect) {\n // If there are passive effects, schedule a callback to flush at\n // the earliest opportunity.\n if (!rootDoesHavePassiveEffects) {\n rootDoesHavePassiveEffects = true;\n scheduleCallback(NormalPriority, function () {\n flushPassiveEffects();\n return null;\n });\n }\n }\n\n nextEffect = nextEffect.nextEffect;\n }\n}\n\nfunction commitMutationEffects(root, renderPriorityLevel) {\n // TODO: Should probably move the bulk of this function to commitWork.\n while (nextEffect !== null) {\n setCurrentFiber(nextEffect);\n var effectTag = nextEffect.effectTag;\n\n if (effectTag & ContentReset) {\n commitResetTextContent(nextEffect);\n }\n\n if (effectTag & Ref) {\n var current = nextEffect.alternate;\n\n if (current !== null) {\n commitDetachRef(current);\n }\n } // The following switch statement is only concerned about placement,\n // updates, and deletions. To avoid needing to add a case for every possible\n // bitmap value, we remove the secondary effects from the effect tag and\n // switch on that value.\n\n\n var primaryEffectTag = effectTag & (Placement | Update | Deletion | Hydrating);\n\n switch (primaryEffectTag) {\n case Placement:\n {\n commitPlacement(nextEffect); // Clear the \"placement\" from effect tag so that we know that this is\n // inserted, before any life-cycles like componentDidMount gets called.\n // TODO: findDOMNode doesn't rely on this any more but isMounted does\n // and isMounted is deprecated anyway so we should be able to kill this.\n\n nextEffect.effectTag &= ~Placement;\n break;\n }\n\n case PlacementAndUpdate:\n {\n // Placement\n commitPlacement(nextEffect); // Clear the \"placement\" from effect tag so that we know that this is\n // inserted, before any life-cycles like componentDidMount gets called.\n\n nextEffect.effectTag &= ~Placement; // Update\n\n var _current = nextEffect.alternate;\n commitWork(_current, nextEffect);\n break;\n }\n\n case Hydrating:\n {\n nextEffect.effectTag &= ~Hydrating;\n break;\n }\n\n case HydratingAndUpdate:\n {\n nextEffect.effectTag &= ~Hydrating; // Update\n\n var _current2 = nextEffect.alternate;\n commitWork(_current2, nextEffect);\n break;\n }\n\n case Update:\n {\n var _current3 = nextEffect.alternate;\n commitWork(_current3, nextEffect);\n break;\n }\n\n case Deletion:\n {\n commitDeletion(root, nextEffect, renderPriorityLevel);\n break;\n }\n } // TODO: Only record a mutation effect if primaryEffectTag is non-zero.\n\n\n recordEffect();\n resetCurrentFiber();\n nextEffect = nextEffect.nextEffect;\n }\n}\n\nfunction commitLayoutEffects(root, committedExpirationTime) {\n // TODO: Should probably move the bulk of this function to commitWork.\n while (nextEffect !== null) {\n setCurrentFiber(nextEffect);\n var effectTag = nextEffect.effectTag;\n\n if (effectTag & (Update | Callback)) {\n recordEffect();\n var current = nextEffect.alternate;\n commitLifeCycles(root, current, nextEffect);\n }\n\n if (effectTag & Ref) {\n recordEffect();\n commitAttachRef(nextEffect);\n }\n\n resetCurrentFiber();\n nextEffect = nextEffect.nextEffect;\n }\n}\n\nfunction flushPassiveEffects() {\n if (pendingPassiveEffectsRenderPriority !== NoPriority) {\n var priorityLevel = pendingPassiveEffectsRenderPriority > NormalPriority ? NormalPriority : pendingPassiveEffectsRenderPriority;\n pendingPassiveEffectsRenderPriority = NoPriority;\n return runWithPriority$1(priorityLevel, flushPassiveEffectsImpl);\n }\n}\n\nfunction flushPassiveEffectsImpl() {\n if (rootWithPendingPassiveEffects === null) {\n return false;\n }\n\n var root = rootWithPendingPassiveEffects;\n var expirationTime = pendingPassiveEffectsExpirationTime;\n rootWithPendingPassiveEffects = null;\n pendingPassiveEffectsExpirationTime = NoWork;\n\n if (!((executionContext & (RenderContext | CommitContext)) === NoContext)) {\n {\n throw Error( \"Cannot flush passive effects while already rendering.\" );\n }\n }\n\n var prevExecutionContext = executionContext;\n executionContext |= CommitContext;\n var prevInteractions = pushInteractions(root);\n\n {\n // Note: This currently assumes there are no passive effects on the root fiber\n // because the root is not part of its own effect list.\n // This could change in the future.\n var _effect2 = root.current.firstEffect;\n\n while (_effect2 !== null) {\n {\n setCurrentFiber(_effect2);\n invokeGuardedCallback(null, commitPassiveHookEffects, null, _effect2);\n\n if (hasCaughtError()) {\n if (!(_effect2 !== null)) {\n {\n throw Error( \"Should be working on an effect.\" );\n }\n }\n\n var _error5 = clearCaughtError();\n\n captureCommitPhaseError(_effect2, _error5);\n }\n\n resetCurrentFiber();\n }\n\n var nextNextEffect = _effect2.nextEffect; // Remove nextEffect pointer to assist GC\n\n _effect2.nextEffect = null;\n _effect2 = nextNextEffect;\n }\n }\n\n {\n popInteractions(prevInteractions);\n finishPendingInteractions(root, expirationTime);\n }\n\n executionContext = prevExecutionContext;\n flushSyncCallbackQueue(); // If additional passive effects were scheduled, increment a counter. If this\n // exceeds the limit, we'll fire a warning.\n\n nestedPassiveUpdateCount = rootWithPendingPassiveEffects === null ? 0 : nestedPassiveUpdateCount + 1;\n return true;\n}\n\nfunction isAlreadyFailedLegacyErrorBoundary(instance) {\n return legacyErrorBoundariesThatAlreadyFailed !== null && legacyErrorBoundariesThatAlreadyFailed.has(instance);\n}\nfunction markLegacyErrorBoundaryAsFailed(instance) {\n if (legacyErrorBoundariesThatAlreadyFailed === null) {\n legacyErrorBoundariesThatAlreadyFailed = new Set([instance]);\n } else {\n legacyErrorBoundariesThatAlreadyFailed.add(instance);\n }\n}\n\nfunction prepareToThrowUncaughtError(error) {\n if (!hasUncaughtError) {\n hasUncaughtError = true;\n firstUncaughtError = error;\n }\n}\n\nvar onUncaughtError = prepareToThrowUncaughtError;\n\nfunction captureCommitPhaseErrorOnRoot(rootFiber, sourceFiber, error) {\n var errorInfo = createCapturedValue(error, sourceFiber);\n var update = createRootErrorUpdate(rootFiber, errorInfo, Sync);\n enqueueUpdate(rootFiber, update);\n var root = markUpdateTimeFromFiberToRoot(rootFiber, Sync);\n\n if (root !== null) {\n ensureRootIsScheduled(root);\n schedulePendingInteractions(root, Sync);\n }\n}\n\nfunction captureCommitPhaseError(sourceFiber, error) {\n if (sourceFiber.tag === HostRoot) {\n // Error was thrown at the root. There is no parent, so the root\n // itself should capture it.\n captureCommitPhaseErrorOnRoot(sourceFiber, sourceFiber, error);\n return;\n }\n\n var fiber = sourceFiber.return;\n\n while (fiber !== null) {\n if (fiber.tag === HostRoot) {\n captureCommitPhaseErrorOnRoot(fiber, sourceFiber, error);\n return;\n } else if (fiber.tag === ClassComponent) {\n var ctor = fiber.type;\n var instance = fiber.stateNode;\n\n if (typeof ctor.getDerivedStateFromError === 'function' || typeof instance.componentDidCatch === 'function' && !isAlreadyFailedLegacyErrorBoundary(instance)) {\n var errorInfo = createCapturedValue(error, sourceFiber);\n var update = createClassErrorUpdate(fiber, errorInfo, // TODO: This is always sync\n Sync);\n enqueueUpdate(fiber, update);\n var root = markUpdateTimeFromFiberToRoot(fiber, Sync);\n\n if (root !== null) {\n ensureRootIsScheduled(root);\n schedulePendingInteractions(root, Sync);\n }\n\n return;\n }\n }\n\n fiber = fiber.return;\n }\n}\nfunction pingSuspendedRoot(root, thenable, suspendedTime) {\n var pingCache = root.pingCache;\n\n if (pingCache !== null) {\n // The thenable resolved, so we no longer need to memoize, because it will\n // never be thrown again.\n pingCache.delete(thenable);\n }\n\n if (workInProgressRoot === root && renderExpirationTime$1 === suspendedTime) {\n // Received a ping at the same priority level at which we're currently\n // rendering. We might want to restart this render. This should mirror\n // the logic of whether or not a root suspends once it completes.\n // TODO: If we're rendering sync either due to Sync, Batched or expired,\n // we should probably never restart.\n // If we're suspended with delay, we'll always suspend so we can always\n // restart. If we're suspended without any updates, it might be a retry.\n // If it's early in the retry we can restart. We can't know for sure\n // whether we'll eventually process an update during this render pass,\n // but it's somewhat unlikely that we get to a ping before that, since\n // getting to the root most update is usually very fast.\n if (workInProgressRootExitStatus === RootSuspendedWithDelay || workInProgressRootExitStatus === RootSuspended && workInProgressRootLatestProcessedExpirationTime === Sync && now() - globalMostRecentFallbackTime < FALLBACK_THROTTLE_MS) {\n // Restart from the root. Don't need to schedule a ping because\n // we're already working on this tree.\n prepareFreshStack(root, renderExpirationTime$1);\n } else {\n // Even though we can't restart right now, we might get an\n // opportunity later. So we mark this render as having a ping.\n workInProgressRootHasPendingPing = true;\n }\n\n return;\n }\n\n if (!isRootSuspendedAtTime(root, suspendedTime)) {\n // The root is no longer suspended at this time.\n return;\n }\n\n var lastPingedTime = root.lastPingedTime;\n\n if (lastPingedTime !== NoWork && lastPingedTime < suspendedTime) {\n // There's already a lower priority ping scheduled.\n return;\n } // Mark the time at which this ping was scheduled.\n\n\n root.lastPingedTime = suspendedTime;\n\n ensureRootIsScheduled(root);\n schedulePendingInteractions(root, suspendedTime);\n}\n\nfunction retryTimedOutBoundary(boundaryFiber, retryTime) {\n // The boundary fiber (a Suspense component or SuspenseList component)\n // previously was rendered in its fallback state. One of the promises that\n // suspended it has resolved, which means at least part of the tree was\n // likely unblocked. Try rendering again, at a new expiration time.\n if (retryTime === NoWork) {\n var suspenseConfig = null; // Retries don't carry over the already committed update.\n\n var currentTime = requestCurrentTimeForUpdate();\n retryTime = computeExpirationForFiber(currentTime, boundaryFiber, suspenseConfig);\n } // TODO: Special case idle priority?\n\n\n var root = markUpdateTimeFromFiberToRoot(boundaryFiber, retryTime);\n\n if (root !== null) {\n ensureRootIsScheduled(root);\n schedulePendingInteractions(root, retryTime);\n }\n}\nfunction resolveRetryThenable(boundaryFiber, thenable) {\n var retryTime = NoWork; // Default\n\n var retryCache;\n\n {\n retryCache = boundaryFiber.stateNode;\n }\n\n if (retryCache !== null) {\n // The thenable resolved, so we no longer need to memoize, because it will\n // never be thrown again.\n retryCache.delete(thenable);\n }\n\n retryTimedOutBoundary(boundaryFiber, retryTime);\n} // Computes the next Just Noticeable Difference (JND) boundary.\n// The theory is that a person can't tell the difference between small differences in time.\n// Therefore, if we wait a bit longer than necessary that won't translate to a noticeable\n// difference in the experience. However, waiting for longer might mean that we can avoid\n// showing an intermediate loading state. The longer we have already waited, the harder it\n// is to tell small differences in time. Therefore, the longer we've already waited,\n// the longer we can wait additionally. At some point we have to give up though.\n// We pick a train model where the next boundary commits at a consistent schedule.\n// These particular numbers are vague estimates. We expect to adjust them based on research.\n\nfunction jnd(timeElapsed) {\n return timeElapsed < 120 ? 120 : timeElapsed < 480 ? 480 : timeElapsed < 1080 ? 1080 : timeElapsed < 1920 ? 1920 : timeElapsed < 3000 ? 3000 : timeElapsed < 4320 ? 4320 : ceil(timeElapsed / 1960) * 1960;\n}\n\nfunction computeMsUntilSuspenseLoadingDelay(mostRecentEventTime, committedExpirationTime, suspenseConfig) {\n var busyMinDurationMs = suspenseConfig.busyMinDurationMs | 0;\n\n if (busyMinDurationMs <= 0) {\n return 0;\n }\n\n var busyDelayMs = suspenseConfig.busyDelayMs | 0; // Compute the time until this render pass would expire.\n\n var currentTimeMs = now();\n var eventTimeMs = inferTimeFromExpirationTimeWithSuspenseConfig(mostRecentEventTime, suspenseConfig);\n var timeElapsed = currentTimeMs - eventTimeMs;\n\n if (timeElapsed <= busyDelayMs) {\n // If we haven't yet waited longer than the initial delay, we don't\n // have to wait any additional time.\n return 0;\n }\n\n var msUntilTimeout = busyDelayMs + busyMinDurationMs - timeElapsed; // This is the value that is passed to `setTimeout`.\n\n return msUntilTimeout;\n}\n\nfunction checkForNestedUpdates() {\n if (nestedUpdateCount > NESTED_UPDATE_LIMIT) {\n nestedUpdateCount = 0;\n rootWithNestedUpdates = null;\n\n {\n {\n throw Error( \"Maximum update depth exceeded. This can happen when a component repeatedly calls setState inside componentWillUpdate or componentDidUpdate. React limits the number of nested updates to prevent infinite loops.\" );\n }\n }\n }\n\n {\n if (nestedPassiveUpdateCount > NESTED_PASSIVE_UPDATE_LIMIT) {\n nestedPassiveUpdateCount = 0;\n\n error('Maximum update depth exceeded. This can happen when a component ' + \"calls setState inside useEffect, but useEffect either doesn't \" + 'have a dependency array, or one of the dependencies changes on ' + 'every render.');\n }\n }\n}\n\nfunction flushRenderPhaseStrictModeWarningsInDEV() {\n {\n ReactStrictModeWarnings.flushLegacyContextWarning();\n\n {\n ReactStrictModeWarnings.flushPendingUnsafeLifecycleWarnings();\n }\n }\n}\n\nfunction stopFinishedWorkLoopTimer() {\n var didCompleteRoot = true;\n stopWorkLoopTimer(interruptedBy, didCompleteRoot);\n interruptedBy = null;\n}\n\nfunction stopInterruptedWorkLoopTimer() {\n // TODO: Track which fiber caused the interruption.\n var didCompleteRoot = false;\n stopWorkLoopTimer(interruptedBy, didCompleteRoot);\n interruptedBy = null;\n}\n\nfunction checkForInterruption(fiberThatReceivedUpdate, updateExpirationTime) {\n if ( workInProgressRoot !== null && updateExpirationTime > renderExpirationTime$1) {\n interruptedBy = fiberThatReceivedUpdate;\n }\n}\n\nvar didWarnStateUpdateForUnmountedComponent = null;\n\nfunction warnAboutUpdateOnUnmountedFiberInDEV(fiber) {\n {\n var tag = fiber.tag;\n\n if (tag !== HostRoot && tag !== ClassComponent && tag !== FunctionComponent && tag !== ForwardRef && tag !== MemoComponent && tag !== SimpleMemoComponent && tag !== Block) {\n // Only warn for user-defined components, not internal ones like Suspense.\n return;\n }\n // the problematic code almost always lies inside that component.\n\n\n var componentName = getComponentName(fiber.type) || 'ReactComponent';\n\n if (didWarnStateUpdateForUnmountedComponent !== null) {\n if (didWarnStateUpdateForUnmountedComponent.has(componentName)) {\n return;\n }\n\n didWarnStateUpdateForUnmountedComponent.add(componentName);\n } else {\n didWarnStateUpdateForUnmountedComponent = new Set([componentName]);\n }\n\n error(\"Can't perform a React state update on an unmounted component. This \" + 'is a no-op, but it indicates a memory leak in your application. To ' + 'fix, cancel all subscriptions and asynchronous tasks in %s.%s', tag === ClassComponent ? 'the componentWillUnmount method' : 'a useEffect cleanup function', getStackByFiberInDevAndProd(fiber));\n }\n}\n\nvar beginWork$1;\n\n{\n var dummyFiber = null;\n\n beginWork$1 = function (current, unitOfWork, expirationTime) {\n // If a component throws an error, we replay it again in a synchronously\n // dispatched event, so that the debugger will treat it as an uncaught\n // error See ReactErrorUtils for more information.\n // Before entering the begin phase, copy the work-in-progress onto a dummy\n // fiber. If beginWork throws, we'll use this to reset the state.\n var originalWorkInProgressCopy = assignFiberPropertiesInDEV(dummyFiber, unitOfWork);\n\n try {\n return beginWork(current, unitOfWork, expirationTime);\n } catch (originalError) {\n if (originalError !== null && typeof originalError === 'object' && typeof originalError.then === 'function') {\n // Don't replay promises. Treat everything else like an error.\n throw originalError;\n } // Keep this code in sync with handleError; any changes here must have\n // corresponding changes there.\n\n\n resetContextDependencies();\n resetHooksAfterThrow(); // Don't reset current debug fiber, since we're about to work on the\n // same fiber again.\n // Unwind the failed stack frame\n\n unwindInterruptedWork(unitOfWork); // Restore the original properties of the fiber.\n\n assignFiberPropertiesInDEV(unitOfWork, originalWorkInProgressCopy);\n\n if ( unitOfWork.mode & ProfileMode) {\n // Reset the profiler timer.\n startProfilerTimer(unitOfWork);\n } // Run beginWork again.\n\n\n invokeGuardedCallback(null, beginWork, null, current, unitOfWork, expirationTime);\n\n if (hasCaughtError()) {\n var replayError = clearCaughtError(); // `invokeGuardedCallback` sometimes sets an expando `_suppressLogging`.\n // Rethrow this error instead of the original one.\n\n throw replayError;\n } else {\n // This branch is reachable if the render phase is impure.\n throw originalError;\n }\n }\n };\n}\n\nvar didWarnAboutUpdateInRender = false;\nvar didWarnAboutUpdateInRenderForAnotherComponent;\n\n{\n didWarnAboutUpdateInRenderForAnotherComponent = new Set();\n}\n\nfunction warnAboutRenderPhaseUpdatesInDEV(fiber) {\n {\n if (isRendering && (executionContext & RenderContext) !== NoContext) {\n switch (fiber.tag) {\n case FunctionComponent:\n case ForwardRef:\n case SimpleMemoComponent:\n {\n var renderingComponentName = workInProgress && getComponentName(workInProgress.type) || 'Unknown'; // Dedupe by the rendering component because it's the one that needs to be fixed.\n\n var dedupeKey = renderingComponentName;\n\n if (!didWarnAboutUpdateInRenderForAnotherComponent.has(dedupeKey)) {\n didWarnAboutUpdateInRenderForAnotherComponent.add(dedupeKey);\n var setStateComponentName = getComponentName(fiber.type) || 'Unknown';\n\n error('Cannot update a component (`%s`) while rendering a ' + 'different component (`%s`). To locate the bad setState() call inside `%s`, ' + 'follow the stack trace as described in https://fb.me/setstate-in-render', setStateComponentName, renderingComponentName, renderingComponentName);\n }\n\n break;\n }\n\n case ClassComponent:\n {\n if (!didWarnAboutUpdateInRender) {\n error('Cannot update during an existing state transition (such as ' + 'within `render`). Render methods should be a pure ' + 'function of props and state.');\n\n didWarnAboutUpdateInRender = true;\n }\n\n break;\n }\n }\n }\n }\n} // a 'shared' variable that changes when act() opens/closes in tests.\n\n\nvar IsThisRendererActing = {\n current: false\n};\nfunction warnIfNotScopedWithMatchingAct(fiber) {\n {\n if ( IsSomeRendererActing.current === true && IsThisRendererActing.current !== true) {\n error(\"It looks like you're using the wrong act() around your test interactions.\\n\" + 'Be sure to use the matching version of act() corresponding to your renderer:\\n\\n' + '// for react-dom:\\n' + \"import {act} from 'react-dom/test-utils';\\n\" + '// ...\\n' + 'act(() => ...);\\n\\n' + '// for react-test-renderer:\\n' + \"import TestRenderer from 'react-test-renderer';\\n\" + 'const {act} = TestRenderer;\\n' + '// ...\\n' + 'act(() => ...);' + '%s', getStackByFiberInDevAndProd(fiber));\n }\n }\n}\nfunction warnIfNotCurrentlyActingEffectsInDEV(fiber) {\n {\n if ( (fiber.mode & StrictMode) !== NoMode && IsSomeRendererActing.current === false && IsThisRendererActing.current === false) {\n error('An update to %s ran an effect, but was not wrapped in act(...).\\n\\n' + 'When testing, code that causes React state updates should be ' + 'wrapped into act(...):\\n\\n' + 'act(() => {\\n' + ' /* fire events that update state */\\n' + '});\\n' + '/* assert on the output */\\n\\n' + \"This ensures that you're testing the behavior the user would see \" + 'in the browser.' + ' Learn more at https://fb.me/react-wrap-tests-with-act' + '%s', getComponentName(fiber.type), getStackByFiberInDevAndProd(fiber));\n }\n }\n}\n\nfunction warnIfNotCurrentlyActingUpdatesInDEV(fiber) {\n {\n if ( executionContext === NoContext && IsSomeRendererActing.current === false && IsThisRendererActing.current === false) {\n error('An update to %s inside a test was not wrapped in act(...).\\n\\n' + 'When testing, code that causes React state updates should be ' + 'wrapped into act(...):\\n\\n' + 'act(() => {\\n' + ' /* fire events that update state */\\n' + '});\\n' + '/* assert on the output */\\n\\n' + \"This ensures that you're testing the behavior the user would see \" + 'in the browser.' + ' Learn more at https://fb.me/react-wrap-tests-with-act' + '%s', getComponentName(fiber.type), getStackByFiberInDevAndProd(fiber));\n }\n }\n}\n\nvar warnIfNotCurrentlyActingUpdatesInDev = warnIfNotCurrentlyActingUpdatesInDEV; // In tests, we want to enforce a mocked scheduler.\n\nvar didWarnAboutUnmockedScheduler = false; // TODO Before we release concurrent mode, revisit this and decide whether a mocked\n// scheduler is the actual recommendation. The alternative could be a testing build,\n// a new lib, or whatever; we dunno just yet. This message is for early adopters\n// to get their tests right.\n\nfunction warnIfUnmockedScheduler(fiber) {\n {\n if (didWarnAboutUnmockedScheduler === false && Scheduler.unstable_flushAllWithoutAsserting === undefined) {\n if (fiber.mode & BlockingMode || fiber.mode & ConcurrentMode) {\n didWarnAboutUnmockedScheduler = true;\n\n error('In Concurrent or Sync modes, the \"scheduler\" module needs to be mocked ' + 'to guarantee consistent behaviour across tests and browsers. ' + 'For example, with jest: \\n' + \"jest.mock('scheduler', () => require('scheduler/unstable_mock'));\\n\\n\" + 'For more info, visit https://fb.me/react-mock-scheduler');\n }\n }\n }\n}\n\nfunction computeThreadID(root, expirationTime) {\n // Interaction threads are unique per root and expiration time.\n return expirationTime * 1000 + root.interactionThreadID;\n}\n\nfunction markSpawnedWork(expirationTime) {\n\n if (spawnedWorkDuringRender === null) {\n spawnedWorkDuringRender = [expirationTime];\n } else {\n spawnedWorkDuringRender.push(expirationTime);\n }\n}\n\nfunction scheduleInteractions(root, expirationTime, interactions) {\n\n if (interactions.size > 0) {\n var pendingInteractionMap = root.pendingInteractionMap;\n var pendingInteractions = pendingInteractionMap.get(expirationTime);\n\n if (pendingInteractions != null) {\n interactions.forEach(function (interaction) {\n if (!pendingInteractions.has(interaction)) {\n // Update the pending async work count for previously unscheduled interaction.\n interaction.__count++;\n }\n\n pendingInteractions.add(interaction);\n });\n } else {\n pendingInteractionMap.set(expirationTime, new Set(interactions)); // Update the pending async work count for the current interactions.\n\n interactions.forEach(function (interaction) {\n interaction.__count++;\n });\n }\n\n var subscriber = tracing.__subscriberRef.current;\n\n if (subscriber !== null) {\n var threadID = computeThreadID(root, expirationTime);\n subscriber.onWorkScheduled(interactions, threadID);\n }\n }\n}\n\nfunction schedulePendingInteractions(root, expirationTime) {\n\n scheduleInteractions(root, expirationTime, tracing.__interactionsRef.current);\n}\n\nfunction startWorkOnPendingInteractions(root, expirationTime) {\n // we can accurately attribute time spent working on it, And so that cascading\n // work triggered during the render phase will be associated with it.\n\n\n var interactions = new Set();\n root.pendingInteractionMap.forEach(function (scheduledInteractions, scheduledExpirationTime) {\n if (scheduledExpirationTime >= expirationTime) {\n scheduledInteractions.forEach(function (interaction) {\n return interactions.add(interaction);\n });\n }\n }); // Store the current set of interactions on the FiberRoot for a few reasons:\n // We can re-use it in hot functions like performConcurrentWorkOnRoot()\n // without having to recalculate it. We will also use it in commitWork() to\n // pass to any Profiler onRender() hooks. This also provides DevTools with a\n // way to access it when the onCommitRoot() hook is called.\n\n root.memoizedInteractions = interactions;\n\n if (interactions.size > 0) {\n var subscriber = tracing.__subscriberRef.current;\n\n if (subscriber !== null) {\n var threadID = computeThreadID(root, expirationTime);\n\n try {\n subscriber.onWorkStarted(interactions, threadID);\n } catch (error) {\n // If the subscriber throws, rethrow it in a separate task\n scheduleCallback(ImmediatePriority, function () {\n throw error;\n });\n }\n }\n }\n}\n\nfunction finishPendingInteractions(root, committedExpirationTime) {\n\n var earliestRemainingTimeAfterCommit = root.firstPendingTime;\n var subscriber;\n\n try {\n subscriber = tracing.__subscriberRef.current;\n\n if (subscriber !== null && root.memoizedInteractions.size > 0) {\n var threadID = computeThreadID(root, committedExpirationTime);\n subscriber.onWorkStopped(root.memoizedInteractions, threadID);\n }\n } catch (error) {\n // If the subscriber throws, rethrow it in a separate task\n scheduleCallback(ImmediatePriority, function () {\n throw error;\n });\n } finally {\n // Clear completed interactions from the pending Map.\n // Unless the render was suspended or cascading work was scheduled,\n // In which case– leave pending interactions until the subsequent render.\n var pendingInteractionMap = root.pendingInteractionMap;\n pendingInteractionMap.forEach(function (scheduledInteractions, scheduledExpirationTime) {\n // Only decrement the pending interaction count if we're done.\n // If there's still work at the current priority,\n // That indicates that we are waiting for suspense data.\n if (scheduledExpirationTime > earliestRemainingTimeAfterCommit) {\n pendingInteractionMap.delete(scheduledExpirationTime);\n scheduledInteractions.forEach(function (interaction) {\n interaction.__count--;\n\n if (subscriber !== null && interaction.__count === 0) {\n try {\n subscriber.onInteractionScheduledWorkCompleted(interaction);\n } catch (error) {\n // If the subscriber throws, rethrow it in a separate task\n scheduleCallback(ImmediatePriority, function () {\n throw error;\n });\n }\n }\n });\n }\n });\n }\n}\n\nvar onScheduleFiberRoot = null;\nvar onCommitFiberRoot = null;\nvar onCommitFiberUnmount = null;\nvar hasLoggedError = false;\nvar isDevToolsPresent = typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ !== 'undefined';\nfunction injectInternals(internals) {\n if (typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ === 'undefined') {\n // No DevTools\n return false;\n }\n\n var hook = __REACT_DEVTOOLS_GLOBAL_HOOK__;\n\n if (hook.isDisabled) {\n // This isn't a real property on the hook, but it can be set to opt out\n // of DevTools integration and associated warnings and logs.\n // https://github.com/facebook/react/issues/3877\n return true;\n }\n\n if (!hook.supportsFiber) {\n {\n error('The installed version of React DevTools is too old and will not work ' + 'with the current version of React. Please update React DevTools. ' + 'https://fb.me/react-devtools');\n } // DevTools exists, even though it doesn't support Fiber.\n\n\n return true;\n }\n\n try {\n var rendererID = hook.inject(internals); // We have successfully injected, so now it is safe to set up hooks.\n\n if (true) {\n // Only used by Fast Refresh\n if (typeof hook.onScheduleFiberRoot === 'function') {\n onScheduleFiberRoot = function (root, children) {\n try {\n hook.onScheduleFiberRoot(rendererID, root, children);\n } catch (err) {\n if ( true && !hasLoggedError) {\n hasLoggedError = true;\n\n error('React instrumentation encountered an error: %s', err);\n }\n }\n };\n }\n }\n\n onCommitFiberRoot = function (root, expirationTime) {\n try {\n var didError = (root.current.effectTag & DidCapture) === DidCapture;\n\n if (enableProfilerTimer) {\n var currentTime = getCurrentTime();\n var priorityLevel = inferPriorityFromExpirationTime(currentTime, expirationTime);\n hook.onCommitFiberRoot(rendererID, root, priorityLevel, didError);\n } else {\n hook.onCommitFiberRoot(rendererID, root, undefined, didError);\n }\n } catch (err) {\n if (true) {\n if (!hasLoggedError) {\n hasLoggedError = true;\n\n error('React instrumentation encountered an error: %s', err);\n }\n }\n }\n };\n\n onCommitFiberUnmount = function (fiber) {\n try {\n hook.onCommitFiberUnmount(rendererID, fiber);\n } catch (err) {\n if (true) {\n if (!hasLoggedError) {\n hasLoggedError = true;\n\n error('React instrumentation encountered an error: %s', err);\n }\n }\n }\n };\n } catch (err) {\n // Catch all errors because it is unsafe to throw during initialization.\n {\n error('React instrumentation encountered an error: %s.', err);\n }\n } // DevTools exists\n\n\n return true;\n}\nfunction onScheduleRoot(root, children) {\n if (typeof onScheduleFiberRoot === 'function') {\n onScheduleFiberRoot(root, children);\n }\n}\nfunction onCommitRoot(root, expirationTime) {\n if (typeof onCommitFiberRoot === 'function') {\n onCommitFiberRoot(root, expirationTime);\n }\n}\nfunction onCommitUnmount(fiber) {\n if (typeof onCommitFiberUnmount === 'function') {\n onCommitFiberUnmount(fiber);\n }\n}\n\nvar hasBadMapPolyfill;\n\n{\n hasBadMapPolyfill = false;\n\n try {\n var nonExtensibleObject = Object.preventExtensions({});\n var testMap = new Map([[nonExtensibleObject, null]]);\n var testSet = new Set([nonExtensibleObject]); // This is necessary for Rollup to not consider these unused.\n // https://github.com/rollup/rollup/issues/1771\n // TODO: we can remove these if Rollup fixes the bug.\n\n testMap.set(0, 0);\n testSet.add(0);\n } catch (e) {\n // TODO: Consider warning about bad polyfills\n hasBadMapPolyfill = true;\n }\n}\n\nvar debugCounter = 1;\n\nfunction FiberNode(tag, pendingProps, key, mode) {\n // Instance\n this.tag = tag;\n this.key = key;\n this.elementType = null;\n this.type = null;\n this.stateNode = null; // Fiber\n\n this.return = null;\n this.child = null;\n this.sibling = null;\n this.index = 0;\n this.ref = null;\n this.pendingProps = pendingProps;\n this.memoizedProps = null;\n this.updateQueue = null;\n this.memoizedState = null;\n this.dependencies = null;\n this.mode = mode; // Effects\n\n this.effectTag = NoEffect;\n this.nextEffect = null;\n this.firstEffect = null;\n this.lastEffect = null;\n this.expirationTime = NoWork;\n this.childExpirationTime = NoWork;\n this.alternate = null;\n\n {\n // Note: The following is done to avoid a v8 performance cliff.\n //\n // Initializing the fields below to smis and later updating them with\n // double values will cause Fibers to end up having separate shapes.\n // This behavior/bug has something to do with Object.preventExtension().\n // Fortunately this only impacts DEV builds.\n // Unfortunately it makes React unusably slow for some applications.\n // To work around this, initialize the fields below with doubles.\n //\n // Learn more about this here:\n // https://github.com/facebook/react/issues/14365\n // https://bugs.chromium.org/p/v8/issues/detail?id=8538\n this.actualDuration = Number.NaN;\n this.actualStartTime = Number.NaN;\n this.selfBaseDuration = Number.NaN;\n this.treeBaseDuration = Number.NaN; // It's okay to replace the initial doubles with smis after initialization.\n // This won't trigger the performance cliff mentioned above,\n // and it simplifies other profiler code (including DevTools).\n\n this.actualDuration = 0;\n this.actualStartTime = -1;\n this.selfBaseDuration = 0;\n this.treeBaseDuration = 0;\n } // This is normally DEV-only except www when it adds listeners.\n // TODO: remove the User Timing integration in favor of Root Events.\n\n\n {\n this._debugID = debugCounter++;\n this._debugIsCurrentlyTiming = false;\n }\n\n {\n this._debugSource = null;\n this._debugOwner = null;\n this._debugNeedsRemount = false;\n this._debugHookTypes = null;\n\n if (!hasBadMapPolyfill && typeof Object.preventExtensions === 'function') {\n Object.preventExtensions(this);\n }\n }\n} // This is a constructor function, rather than a POJO constructor, still\n// please ensure we do the following:\n// 1) Nobody should add any instance methods on this. Instance methods can be\n// more difficult to predict when they get optimized and they are almost\n// never inlined properly in static compilers.\n// 2) Nobody should rely on `instanceof Fiber` for type testing. We should\n// always know when it is a fiber.\n// 3) We might want to experiment with using numeric keys since they are easier\n// to optimize in a non-JIT environment.\n// 4) We can easily go from a constructor to a createFiber object literal if that\n// is faster.\n// 5) It should be easy to port this to a C struct and keep a C implementation\n// compatible.\n\n\nvar createFiber = function (tag, pendingProps, key, mode) {\n // $FlowFixMe: the shapes are exact here but Flow doesn't like constructors\n return new FiberNode(tag, pendingProps, key, mode);\n};\n\nfunction shouldConstruct(Component) {\n var prototype = Component.prototype;\n return !!(prototype && prototype.isReactComponent);\n}\n\nfunction isSimpleFunctionComponent(type) {\n return typeof type === 'function' && !shouldConstruct(type) && type.defaultProps === undefined;\n}\nfunction resolveLazyComponentTag(Component) {\n if (typeof Component === 'function') {\n return shouldConstruct(Component) ? ClassComponent : FunctionComponent;\n } else if (Component !== undefined && Component !== null) {\n var $$typeof = Component.$$typeof;\n\n if ($$typeof === REACT_FORWARD_REF_TYPE) {\n return ForwardRef;\n }\n\n if ($$typeof === REACT_MEMO_TYPE) {\n return MemoComponent;\n }\n }\n\n return IndeterminateComponent;\n} // This is used to create an alternate fiber to do work on.\n\nfunction createWorkInProgress(current, pendingProps) {\n var workInProgress = current.alternate;\n\n if (workInProgress === null) {\n // We use a double buffering pooling technique because we know that we'll\n // only ever need at most two versions of a tree. We pool the \"other\" unused\n // node that we're free to reuse. This is lazily created to avoid allocating\n // extra objects for things that are never updated. It also allow us to\n // reclaim the extra memory if needed.\n workInProgress = createFiber(current.tag, pendingProps, current.key, current.mode);\n workInProgress.elementType = current.elementType;\n workInProgress.type = current.type;\n workInProgress.stateNode = current.stateNode;\n\n {\n // DEV-only fields\n {\n workInProgress._debugID = current._debugID;\n }\n\n workInProgress._debugSource = current._debugSource;\n workInProgress._debugOwner = current._debugOwner;\n workInProgress._debugHookTypes = current._debugHookTypes;\n }\n\n workInProgress.alternate = current;\n current.alternate = workInProgress;\n } else {\n workInProgress.pendingProps = pendingProps; // We already have an alternate.\n // Reset the effect tag.\n\n workInProgress.effectTag = NoEffect; // The effect list is no longer valid.\n\n workInProgress.nextEffect = null;\n workInProgress.firstEffect = null;\n workInProgress.lastEffect = null;\n\n {\n // We intentionally reset, rather than copy, actualDuration & actualStartTime.\n // This prevents time from endlessly accumulating in new commits.\n // This has the downside of resetting values for different priority renders,\n // But works for yielding (the common case) and should support resuming.\n workInProgress.actualDuration = 0;\n workInProgress.actualStartTime = -1;\n }\n }\n\n workInProgress.childExpirationTime = current.childExpirationTime;\n workInProgress.expirationTime = current.expirationTime;\n workInProgress.child = current.child;\n workInProgress.memoizedProps = current.memoizedProps;\n workInProgress.memoizedState = current.memoizedState;\n workInProgress.updateQueue = current.updateQueue; // Clone the dependencies object. This is mutated during the render phase, so\n // it cannot be shared with the current fiber.\n\n var currentDependencies = current.dependencies;\n workInProgress.dependencies = currentDependencies === null ? null : {\n expirationTime: currentDependencies.expirationTime,\n firstContext: currentDependencies.firstContext,\n responders: currentDependencies.responders\n }; // These will be overridden during the parent's reconciliation\n\n workInProgress.sibling = current.sibling;\n workInProgress.index = current.index;\n workInProgress.ref = current.ref;\n\n {\n workInProgress.selfBaseDuration = current.selfBaseDuration;\n workInProgress.treeBaseDuration = current.treeBaseDuration;\n }\n\n {\n workInProgress._debugNeedsRemount = current._debugNeedsRemount;\n\n switch (workInProgress.tag) {\n case IndeterminateComponent:\n case FunctionComponent:\n case SimpleMemoComponent:\n workInProgress.type = resolveFunctionForHotReloading(current.type);\n break;\n\n case ClassComponent:\n workInProgress.type = resolveClassForHotReloading(current.type);\n break;\n\n case ForwardRef:\n workInProgress.type = resolveForwardRefForHotReloading(current.type);\n break;\n }\n }\n\n return workInProgress;\n} // Used to reuse a Fiber for a second pass.\n\nfunction resetWorkInProgress(workInProgress, renderExpirationTime) {\n // This resets the Fiber to what createFiber or createWorkInProgress would\n // have set the values to before during the first pass. Ideally this wouldn't\n // be necessary but unfortunately many code paths reads from the workInProgress\n // when they should be reading from current and writing to workInProgress.\n // We assume pendingProps, index, key, ref, return are still untouched to\n // avoid doing another reconciliation.\n // Reset the effect tag but keep any Placement tags, since that's something\n // that child fiber is setting, not the reconciliation.\n workInProgress.effectTag &= Placement; // The effect list is no longer valid.\n\n workInProgress.nextEffect = null;\n workInProgress.firstEffect = null;\n workInProgress.lastEffect = null;\n var current = workInProgress.alternate;\n\n if (current === null) {\n // Reset to createFiber's initial values.\n workInProgress.childExpirationTime = NoWork;\n workInProgress.expirationTime = renderExpirationTime;\n workInProgress.child = null;\n workInProgress.memoizedProps = null;\n workInProgress.memoizedState = null;\n workInProgress.updateQueue = null;\n workInProgress.dependencies = null;\n\n {\n // Note: We don't reset the actualTime counts. It's useful to accumulate\n // actual time across multiple render passes.\n workInProgress.selfBaseDuration = 0;\n workInProgress.treeBaseDuration = 0;\n }\n } else {\n // Reset to the cloned values that createWorkInProgress would've.\n workInProgress.childExpirationTime = current.childExpirationTime;\n workInProgress.expirationTime = current.expirationTime;\n workInProgress.child = current.child;\n workInProgress.memoizedProps = current.memoizedProps;\n workInProgress.memoizedState = current.memoizedState;\n workInProgress.updateQueue = current.updateQueue; // Clone the dependencies object. This is mutated during the render phase, so\n // it cannot be shared with the current fiber.\n\n var currentDependencies = current.dependencies;\n workInProgress.dependencies = currentDependencies === null ? null : {\n expirationTime: currentDependencies.expirationTime,\n firstContext: currentDependencies.firstContext,\n responders: currentDependencies.responders\n };\n\n {\n // Note: We don't reset the actualTime counts. It's useful to accumulate\n // actual time across multiple render passes.\n workInProgress.selfBaseDuration = current.selfBaseDuration;\n workInProgress.treeBaseDuration = current.treeBaseDuration;\n }\n }\n\n return workInProgress;\n}\nfunction createHostRootFiber(tag) {\n var mode;\n\n if (tag === ConcurrentRoot) {\n mode = ConcurrentMode | BlockingMode | StrictMode;\n } else if (tag === BlockingRoot) {\n mode = BlockingMode | StrictMode;\n } else {\n mode = NoMode;\n }\n\n if ( isDevToolsPresent) {\n // Always collect profile timings when DevTools are present.\n // This enables DevTools to start capturing timing at any point–\n // Without some nodes in the tree having empty base times.\n mode |= ProfileMode;\n }\n\n return createFiber(HostRoot, null, null, mode);\n}\nfunction createFiberFromTypeAndProps(type, // React$ElementType\nkey, pendingProps, owner, mode, expirationTime) {\n var fiber;\n var fiberTag = IndeterminateComponent; // The resolved type is set if we know what the final type will be. I.e. it's not lazy.\n\n var resolvedType = type;\n\n if (typeof type === 'function') {\n if (shouldConstruct(type)) {\n fiberTag = ClassComponent;\n\n {\n resolvedType = resolveClassForHotReloading(resolvedType);\n }\n } else {\n {\n resolvedType = resolveFunctionForHotReloading(resolvedType);\n }\n }\n } else if (typeof type === 'string') {\n fiberTag = HostComponent;\n } else {\n getTag: switch (type) {\n case REACT_FRAGMENT_TYPE:\n return createFiberFromFragment(pendingProps.children, mode, expirationTime, key);\n\n case REACT_CONCURRENT_MODE_TYPE:\n fiberTag = Mode;\n mode |= ConcurrentMode | BlockingMode | StrictMode;\n break;\n\n case REACT_STRICT_MODE_TYPE:\n fiberTag = Mode;\n mode |= StrictMode;\n break;\n\n case REACT_PROFILER_TYPE:\n return createFiberFromProfiler(pendingProps, mode, expirationTime, key);\n\n case REACT_SUSPENSE_TYPE:\n return createFiberFromSuspense(pendingProps, mode, expirationTime, key);\n\n case REACT_SUSPENSE_LIST_TYPE:\n return createFiberFromSuspenseList(pendingProps, mode, expirationTime, key);\n\n default:\n {\n if (typeof type === 'object' && type !== null) {\n switch (type.$$typeof) {\n case REACT_PROVIDER_TYPE:\n fiberTag = ContextProvider;\n break getTag;\n\n case REACT_CONTEXT_TYPE:\n // This is a consumer\n fiberTag = ContextConsumer;\n break getTag;\n\n case REACT_FORWARD_REF_TYPE:\n fiberTag = ForwardRef;\n\n {\n resolvedType = resolveForwardRefForHotReloading(resolvedType);\n }\n\n break getTag;\n\n case REACT_MEMO_TYPE:\n fiberTag = MemoComponent;\n break getTag;\n\n case REACT_LAZY_TYPE:\n fiberTag = LazyComponent;\n resolvedType = null;\n break getTag;\n\n case REACT_BLOCK_TYPE:\n fiberTag = Block;\n break getTag;\n\n }\n }\n\n var info = '';\n\n {\n if (type === undefined || typeof type === 'object' && type !== null && Object.keys(type).length === 0) {\n info += ' You likely forgot to export your component from the file ' + \"it's defined in, or you might have mixed up default and \" + 'named imports.';\n }\n\n var ownerName = owner ? getComponentName(owner.type) : null;\n\n if (ownerName) {\n info += '\\n\\nCheck the render method of `' + ownerName + '`.';\n }\n }\n\n {\n {\n throw Error( \"Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: \" + (type == null ? type : typeof type) + \".\" + info );\n }\n }\n }\n }\n }\n\n fiber = createFiber(fiberTag, pendingProps, key, mode);\n fiber.elementType = type;\n fiber.type = resolvedType;\n fiber.expirationTime = expirationTime;\n return fiber;\n}\nfunction createFiberFromElement(element, mode, expirationTime) {\n var owner = null;\n\n {\n owner = element._owner;\n }\n\n var type = element.type;\n var key = element.key;\n var pendingProps = element.props;\n var fiber = createFiberFromTypeAndProps(type, key, pendingProps, owner, mode, expirationTime);\n\n {\n fiber._debugSource = element._source;\n fiber._debugOwner = element._owner;\n }\n\n return fiber;\n}\nfunction createFiberFromFragment(elements, mode, expirationTime, key) {\n var fiber = createFiber(Fragment, elements, key, mode);\n fiber.expirationTime = expirationTime;\n return fiber;\n}\n\nfunction createFiberFromProfiler(pendingProps, mode, expirationTime, key) {\n {\n if (typeof pendingProps.id !== 'string' || typeof pendingProps.onRender !== 'function') {\n error('Profiler must specify an \"id\" string and \"onRender\" function as props');\n }\n }\n\n var fiber = createFiber(Profiler, pendingProps, key, mode | ProfileMode); // TODO: The Profiler fiber shouldn't have a type. It has a tag.\n\n fiber.elementType = REACT_PROFILER_TYPE;\n fiber.type = REACT_PROFILER_TYPE;\n fiber.expirationTime = expirationTime;\n return fiber;\n}\n\nfunction createFiberFromSuspense(pendingProps, mode, expirationTime, key) {\n var fiber = createFiber(SuspenseComponent, pendingProps, key, mode); // TODO: The SuspenseComponent fiber shouldn't have a type. It has a tag.\n // This needs to be fixed in getComponentName so that it relies on the tag\n // instead.\n\n fiber.type = REACT_SUSPENSE_TYPE;\n fiber.elementType = REACT_SUSPENSE_TYPE;\n fiber.expirationTime = expirationTime;\n return fiber;\n}\nfunction createFiberFromSuspenseList(pendingProps, mode, expirationTime, key) {\n var fiber = createFiber(SuspenseListComponent, pendingProps, key, mode);\n\n {\n // TODO: The SuspenseListComponent fiber shouldn't have a type. It has a tag.\n // This needs to be fixed in getComponentName so that it relies on the tag\n // instead.\n fiber.type = REACT_SUSPENSE_LIST_TYPE;\n }\n\n fiber.elementType = REACT_SUSPENSE_LIST_TYPE;\n fiber.expirationTime = expirationTime;\n return fiber;\n}\nfunction createFiberFromText(content, mode, expirationTime) {\n var fiber = createFiber(HostText, content, null, mode);\n fiber.expirationTime = expirationTime;\n return fiber;\n}\nfunction createFiberFromHostInstanceForDeletion() {\n var fiber = createFiber(HostComponent, null, null, NoMode); // TODO: These should not need a type.\n\n fiber.elementType = 'DELETED';\n fiber.type = 'DELETED';\n return fiber;\n}\nfunction createFiberFromPortal(portal, mode, expirationTime) {\n var pendingProps = portal.children !== null ? portal.children : [];\n var fiber = createFiber(HostPortal, pendingProps, portal.key, mode);\n fiber.expirationTime = expirationTime;\n fiber.stateNode = {\n containerInfo: portal.containerInfo,\n pendingChildren: null,\n // Used by persistent updates\n implementation: portal.implementation\n };\n return fiber;\n} // Used for stashing WIP properties to replay failed work in DEV.\n\nfunction assignFiberPropertiesInDEV(target, source) {\n if (target === null) {\n // This Fiber's initial properties will always be overwritten.\n // We only use a Fiber to ensure the same hidden class so DEV isn't slow.\n target = createFiber(IndeterminateComponent, null, null, NoMode);\n } // This is intentionally written as a list of all properties.\n // We tried to use Object.assign() instead but this is called in\n // the hottest path, and Object.assign() was too slow:\n // https://github.com/facebook/react/issues/12502\n // This code is DEV-only so size is not a concern.\n\n\n target.tag = source.tag;\n target.key = source.key;\n target.elementType = source.elementType;\n target.type = source.type;\n target.stateNode = source.stateNode;\n target.return = source.return;\n target.child = source.child;\n target.sibling = source.sibling;\n target.index = source.index;\n target.ref = source.ref;\n target.pendingProps = source.pendingProps;\n target.memoizedProps = source.memoizedProps;\n target.updateQueue = source.updateQueue;\n target.memoizedState = source.memoizedState;\n target.dependencies = source.dependencies;\n target.mode = source.mode;\n target.effectTag = source.effectTag;\n target.nextEffect = source.nextEffect;\n target.firstEffect = source.firstEffect;\n target.lastEffect = source.lastEffect;\n target.expirationTime = source.expirationTime;\n target.childExpirationTime = source.childExpirationTime;\n target.alternate = source.alternate;\n\n {\n target.actualDuration = source.actualDuration;\n target.actualStartTime = source.actualStartTime;\n target.selfBaseDuration = source.selfBaseDuration;\n target.treeBaseDuration = source.treeBaseDuration;\n }\n\n {\n target._debugID = source._debugID;\n }\n\n target._debugSource = source._debugSource;\n target._debugOwner = source._debugOwner;\n target._debugIsCurrentlyTiming = source._debugIsCurrentlyTiming;\n target._debugNeedsRemount = source._debugNeedsRemount;\n target._debugHookTypes = source._debugHookTypes;\n return target;\n}\n\nfunction FiberRootNode(containerInfo, tag, hydrate) {\n this.tag = tag;\n this.current = null;\n this.containerInfo = containerInfo;\n this.pendingChildren = null;\n this.pingCache = null;\n this.finishedExpirationTime = NoWork;\n this.finishedWork = null;\n this.timeoutHandle = noTimeout;\n this.context = null;\n this.pendingContext = null;\n this.hydrate = hydrate;\n this.callbackNode = null;\n this.callbackPriority = NoPriority;\n this.firstPendingTime = NoWork;\n this.firstSuspendedTime = NoWork;\n this.lastSuspendedTime = NoWork;\n this.nextKnownPendingLevel = NoWork;\n this.lastPingedTime = NoWork;\n this.lastExpiredTime = NoWork;\n\n {\n this.interactionThreadID = tracing.unstable_getThreadID();\n this.memoizedInteractions = new Set();\n this.pendingInteractionMap = new Map();\n }\n}\n\nfunction createFiberRoot(containerInfo, tag, hydrate, hydrationCallbacks) {\n var root = new FiberRootNode(containerInfo, tag, hydrate);\n // stateNode is any.\n\n\n var uninitializedFiber = createHostRootFiber(tag);\n root.current = uninitializedFiber;\n uninitializedFiber.stateNode = root;\n initializeUpdateQueue(uninitializedFiber);\n return root;\n}\nfunction isRootSuspendedAtTime(root, expirationTime) {\n var firstSuspendedTime = root.firstSuspendedTime;\n var lastSuspendedTime = root.lastSuspendedTime;\n return firstSuspendedTime !== NoWork && firstSuspendedTime >= expirationTime && lastSuspendedTime <= expirationTime;\n}\nfunction markRootSuspendedAtTime(root, expirationTime) {\n var firstSuspendedTime = root.firstSuspendedTime;\n var lastSuspendedTime = root.lastSuspendedTime;\n\n if (firstSuspendedTime < expirationTime) {\n root.firstSuspendedTime = expirationTime;\n }\n\n if (lastSuspendedTime > expirationTime || firstSuspendedTime === NoWork) {\n root.lastSuspendedTime = expirationTime;\n }\n\n if (expirationTime <= root.lastPingedTime) {\n root.lastPingedTime = NoWork;\n }\n\n if (expirationTime <= root.lastExpiredTime) {\n root.lastExpiredTime = NoWork;\n }\n}\nfunction markRootUpdatedAtTime(root, expirationTime) {\n // Update the range of pending times\n var firstPendingTime = root.firstPendingTime;\n\n if (expirationTime > firstPendingTime) {\n root.firstPendingTime = expirationTime;\n } // Update the range of suspended times. Treat everything lower priority or\n // equal to this update as unsuspended.\n\n\n var firstSuspendedTime = root.firstSuspendedTime;\n\n if (firstSuspendedTime !== NoWork) {\n if (expirationTime >= firstSuspendedTime) {\n // The entire suspended range is now unsuspended.\n root.firstSuspendedTime = root.lastSuspendedTime = root.nextKnownPendingLevel = NoWork;\n } else if (expirationTime >= root.lastSuspendedTime) {\n root.lastSuspendedTime = expirationTime + 1;\n } // This is a pending level. Check if it's higher priority than the next\n // known pending level.\n\n\n if (expirationTime > root.nextKnownPendingLevel) {\n root.nextKnownPendingLevel = expirationTime;\n }\n }\n}\nfunction markRootFinishedAtTime(root, finishedExpirationTime, remainingExpirationTime) {\n // Update the range of pending times\n root.firstPendingTime = remainingExpirationTime; // Update the range of suspended times. Treat everything higher priority or\n // equal to this update as unsuspended.\n\n if (finishedExpirationTime <= root.lastSuspendedTime) {\n // The entire suspended range is now unsuspended.\n root.firstSuspendedTime = root.lastSuspendedTime = root.nextKnownPendingLevel = NoWork;\n } else if (finishedExpirationTime <= root.firstSuspendedTime) {\n // Part of the suspended range is now unsuspended. Narrow the range to\n // include everything between the unsuspended time (non-inclusive) and the\n // last suspended time.\n root.firstSuspendedTime = finishedExpirationTime - 1;\n }\n\n if (finishedExpirationTime <= root.lastPingedTime) {\n // Clear the pinged time\n root.lastPingedTime = NoWork;\n }\n\n if (finishedExpirationTime <= root.lastExpiredTime) {\n // Clear the expired time\n root.lastExpiredTime = NoWork;\n }\n}\nfunction markRootExpiredAtTime(root, expirationTime) {\n var lastExpiredTime = root.lastExpiredTime;\n\n if (lastExpiredTime === NoWork || lastExpiredTime > expirationTime) {\n root.lastExpiredTime = expirationTime;\n }\n}\n\nvar didWarnAboutNestedUpdates;\nvar didWarnAboutFindNodeInStrictMode;\n\n{\n didWarnAboutNestedUpdates = false;\n didWarnAboutFindNodeInStrictMode = {};\n}\n\nfunction getContextForSubtree(parentComponent) {\n if (!parentComponent) {\n return emptyContextObject;\n }\n\n var fiber = get(parentComponent);\n var parentContext = findCurrentUnmaskedContext(fiber);\n\n if (fiber.tag === ClassComponent) {\n var Component = fiber.type;\n\n if (isContextProvider(Component)) {\n return processChildContext(fiber, Component, parentContext);\n }\n }\n\n return parentContext;\n}\n\nfunction findHostInstanceWithWarning(component, methodName) {\n {\n var fiber = get(component);\n\n if (fiber === undefined) {\n if (typeof component.render === 'function') {\n {\n {\n throw Error( \"Unable to find node on an unmounted component.\" );\n }\n }\n } else {\n {\n {\n throw Error( \"Argument appears to not be a ReactComponent. Keys: \" + Object.keys(component) );\n }\n }\n }\n }\n\n var hostFiber = findCurrentHostFiber(fiber);\n\n if (hostFiber === null) {\n return null;\n }\n\n if (hostFiber.mode & StrictMode) {\n var componentName = getComponentName(fiber.type) || 'Component';\n\n if (!didWarnAboutFindNodeInStrictMode[componentName]) {\n didWarnAboutFindNodeInStrictMode[componentName] = true;\n\n if (fiber.mode & StrictMode) {\n error('%s is deprecated in StrictMode. ' + '%s was passed an instance of %s which is inside StrictMode. ' + 'Instead, add a ref directly to the element you want to reference. ' + 'Learn more about using refs safely here: ' + 'https://fb.me/react-strict-mode-find-node%s', methodName, methodName, componentName, getStackByFiberInDevAndProd(hostFiber));\n } else {\n error('%s is deprecated in StrictMode. ' + '%s was passed an instance of %s which renders StrictMode children. ' + 'Instead, add a ref directly to the element you want to reference. ' + 'Learn more about using refs safely here: ' + 'https://fb.me/react-strict-mode-find-node%s', methodName, methodName, componentName, getStackByFiberInDevAndProd(hostFiber));\n }\n }\n }\n\n return hostFiber.stateNode;\n }\n}\n\nfunction createContainer(containerInfo, tag, hydrate, hydrationCallbacks) {\n return createFiberRoot(containerInfo, tag, hydrate);\n}\nfunction updateContainer(element, container, parentComponent, callback) {\n {\n onScheduleRoot(container, element);\n }\n\n var current$1 = container.current;\n var currentTime = requestCurrentTimeForUpdate();\n\n {\n // $FlowExpectedError - jest isn't a global, and isn't recognized outside of tests\n if ('undefined' !== typeof jest) {\n warnIfUnmockedScheduler(current$1);\n warnIfNotScopedWithMatchingAct(current$1);\n }\n }\n\n var suspenseConfig = requestCurrentSuspenseConfig();\n var expirationTime = computeExpirationForFiber(currentTime, current$1, suspenseConfig);\n var context = getContextForSubtree(parentComponent);\n\n if (container.context === null) {\n container.context = context;\n } else {\n container.pendingContext = context;\n }\n\n {\n if (isRendering && current !== null && !didWarnAboutNestedUpdates) {\n didWarnAboutNestedUpdates = true;\n\n error('Render methods should be a pure function of props and state; ' + 'triggering nested component updates from render is not allowed. ' + 'If necessary, trigger nested updates in componentDidUpdate.\\n\\n' + 'Check the render method of %s.', getComponentName(current.type) || 'Unknown');\n }\n }\n\n var update = createUpdate(expirationTime, suspenseConfig); // Caution: React DevTools currently depends on this property\n // being called \"element\".\n\n update.payload = {\n element: element\n };\n callback = callback === undefined ? null : callback;\n\n if (callback !== null) {\n {\n if (typeof callback !== 'function') {\n error('render(...): Expected the last optional `callback` argument to be a ' + 'function. Instead received: %s.', callback);\n }\n }\n\n update.callback = callback;\n }\n\n enqueueUpdate(current$1, update);\n scheduleWork(current$1, expirationTime);\n return expirationTime;\n}\nfunction getPublicRootInstance(container) {\n var containerFiber = container.current;\n\n if (!containerFiber.child) {\n return null;\n }\n\n switch (containerFiber.child.tag) {\n case HostComponent:\n return getPublicInstance(containerFiber.child.stateNode);\n\n default:\n return containerFiber.child.stateNode;\n }\n}\n\nfunction markRetryTimeImpl(fiber, retryTime) {\n var suspenseState = fiber.memoizedState;\n\n if (suspenseState !== null && suspenseState.dehydrated !== null) {\n if (suspenseState.retryTime < retryTime) {\n suspenseState.retryTime = retryTime;\n }\n }\n} // Increases the priority of thennables when they resolve within this boundary.\n\n\nfunction markRetryTimeIfNotHydrated(fiber, retryTime) {\n markRetryTimeImpl(fiber, retryTime);\n var alternate = fiber.alternate;\n\n if (alternate) {\n markRetryTimeImpl(alternate, retryTime);\n }\n}\n\nfunction attemptUserBlockingHydration$1(fiber) {\n if (fiber.tag !== SuspenseComponent) {\n // We ignore HostRoots here because we can't increase\n // their priority and they should not suspend on I/O,\n // since you have to wrap anything that might suspend in\n // Suspense.\n return;\n }\n\n var expTime = computeInteractiveExpiration(requestCurrentTimeForUpdate());\n scheduleWork(fiber, expTime);\n markRetryTimeIfNotHydrated(fiber, expTime);\n}\nfunction attemptContinuousHydration$1(fiber) {\n if (fiber.tag !== SuspenseComponent) {\n // We ignore HostRoots here because we can't increase\n // their priority and they should not suspend on I/O,\n // since you have to wrap anything that might suspend in\n // Suspense.\n return;\n }\n\n scheduleWork(fiber, ContinuousHydration);\n markRetryTimeIfNotHydrated(fiber, ContinuousHydration);\n}\nfunction attemptHydrationAtCurrentPriority$1(fiber) {\n if (fiber.tag !== SuspenseComponent) {\n // We ignore HostRoots here because we can't increase\n // their priority other than synchronously flush it.\n return;\n }\n\n var currentTime = requestCurrentTimeForUpdate();\n var expTime = computeExpirationForFiber(currentTime, fiber, null);\n scheduleWork(fiber, expTime);\n markRetryTimeIfNotHydrated(fiber, expTime);\n}\nfunction findHostInstanceWithNoPortals(fiber) {\n var hostFiber = findCurrentHostFiberWithNoPortals(fiber);\n\n if (hostFiber === null) {\n return null;\n }\n\n if (hostFiber.tag === FundamentalComponent) {\n return hostFiber.stateNode.instance;\n }\n\n return hostFiber.stateNode;\n}\n\nvar shouldSuspendImpl = function (fiber) {\n return false;\n};\n\nfunction shouldSuspend(fiber) {\n return shouldSuspendImpl(fiber);\n}\nvar overrideHookState = null;\nvar overrideProps = null;\nvar scheduleUpdate = null;\nvar setSuspenseHandler = null;\n\n{\n var copyWithSetImpl = function (obj, path, idx, value) {\n if (idx >= path.length) {\n return value;\n }\n\n var key = path[idx];\n var updated = Array.isArray(obj) ? obj.slice() : _assign({}, obj); // $FlowFixMe number or string is fine here\n\n updated[key] = copyWithSetImpl(obj[key], path, idx + 1, value);\n return updated;\n };\n\n var copyWithSet = function (obj, path, value) {\n return copyWithSetImpl(obj, path, 0, value);\n }; // Support DevTools editable values for useState and useReducer.\n\n\n overrideHookState = function (fiber, id, path, value) {\n // For now, the \"id\" of stateful hooks is just the stateful hook index.\n // This may change in the future with e.g. nested hooks.\n var currentHook = fiber.memoizedState;\n\n while (currentHook !== null && id > 0) {\n currentHook = currentHook.next;\n id--;\n }\n\n if (currentHook !== null) {\n var newState = copyWithSet(currentHook.memoizedState, path, value);\n currentHook.memoizedState = newState;\n currentHook.baseState = newState; // We aren't actually adding an update to the queue,\n // because there is no update we can add for useReducer hooks that won't trigger an error.\n // (There's no appropriate action type for DevTools overrides.)\n // As a result though, React will see the scheduled update as a noop and bailout.\n // Shallow cloning props works as a workaround for now to bypass the bailout check.\n\n fiber.memoizedProps = _assign({}, fiber.memoizedProps);\n scheduleWork(fiber, Sync);\n }\n }; // Support DevTools props for function components, forwardRef, memo, host components, etc.\n\n\n overrideProps = function (fiber, path, value) {\n fiber.pendingProps = copyWithSet(fiber.memoizedProps, path, value);\n\n if (fiber.alternate) {\n fiber.alternate.pendingProps = fiber.pendingProps;\n }\n\n scheduleWork(fiber, Sync);\n };\n\n scheduleUpdate = function (fiber) {\n scheduleWork(fiber, Sync);\n };\n\n setSuspenseHandler = function (newShouldSuspendImpl) {\n shouldSuspendImpl = newShouldSuspendImpl;\n };\n}\n\nfunction injectIntoDevTools(devToolsConfig) {\n var findFiberByHostInstance = devToolsConfig.findFiberByHostInstance;\n var ReactCurrentDispatcher = ReactSharedInternals.ReactCurrentDispatcher;\n return injectInternals(_assign({}, devToolsConfig, {\n overrideHookState: overrideHookState,\n overrideProps: overrideProps,\n setSuspenseHandler: setSuspenseHandler,\n scheduleUpdate: scheduleUpdate,\n currentDispatcherRef: ReactCurrentDispatcher,\n findHostInstanceByFiber: function (fiber) {\n var hostFiber = findCurrentHostFiber(fiber);\n\n if (hostFiber === null) {\n return null;\n }\n\n return hostFiber.stateNode;\n },\n findFiberByHostInstance: function (instance) {\n if (!findFiberByHostInstance) {\n // Might not be implemented by the renderer.\n return null;\n }\n\n return findFiberByHostInstance(instance);\n },\n // React Refresh\n findHostInstancesForRefresh: findHostInstancesForRefresh ,\n scheduleRefresh: scheduleRefresh ,\n scheduleRoot: scheduleRoot ,\n setRefreshHandler: setRefreshHandler ,\n // Enables DevTools to append owner stacks to error messages in DEV mode.\n getCurrentFiber: function () {\n return current;\n } \n }));\n}\nvar IsSomeRendererActing$1 = ReactSharedInternals.IsSomeRendererActing;\n\nfunction ReactDOMRoot(container, options) {\n this._internalRoot = createRootImpl(container, ConcurrentRoot, options);\n}\n\nfunction ReactDOMBlockingRoot(container, tag, options) {\n this._internalRoot = createRootImpl(container, tag, options);\n}\n\nReactDOMRoot.prototype.render = ReactDOMBlockingRoot.prototype.render = function (children) {\n var root = this._internalRoot;\n\n {\n if (typeof arguments[1] === 'function') {\n error('render(...): does not support the second callback argument. ' + 'To execute a side effect after rendering, declare it in a component body with useEffect().');\n }\n\n var container = root.containerInfo;\n\n if (container.nodeType !== COMMENT_NODE) {\n var hostInstance = findHostInstanceWithNoPortals(root.current);\n\n if (hostInstance) {\n if (hostInstance.parentNode !== container) {\n error('render(...): It looks like the React-rendered content of the ' + 'root container was removed without using React. This is not ' + 'supported and will cause errors. Instead, call ' + \"root.unmount() to empty a root's container.\");\n }\n }\n }\n }\n\n updateContainer(children, root, null, null);\n};\n\nReactDOMRoot.prototype.unmount = ReactDOMBlockingRoot.prototype.unmount = function () {\n {\n if (typeof arguments[0] === 'function') {\n error('unmount(...): does not support a callback argument. ' + 'To execute a side effect after rendering, declare it in a component body with useEffect().');\n }\n }\n\n var root = this._internalRoot;\n var container = root.containerInfo;\n updateContainer(null, root, null, function () {\n unmarkContainerAsRoot(container);\n });\n};\n\nfunction createRootImpl(container, tag, options) {\n // Tag is either LegacyRoot or Concurrent Root\n var hydrate = options != null && options.hydrate === true;\n var hydrationCallbacks = options != null && options.hydrationOptions || null;\n var root = createContainer(container, tag, hydrate);\n markContainerAsRoot(root.current, container);\n\n if (hydrate && tag !== LegacyRoot) {\n var doc = container.nodeType === DOCUMENT_NODE ? container : container.ownerDocument;\n eagerlyTrapReplayableEvents(container, doc);\n }\n\n return root;\n}\nfunction createLegacyRoot(container, options) {\n return new ReactDOMBlockingRoot(container, LegacyRoot, options);\n}\nfunction isValidContainer(node) {\n return !!(node && (node.nodeType === ELEMENT_NODE || node.nodeType === DOCUMENT_NODE || node.nodeType === DOCUMENT_FRAGMENT_NODE || node.nodeType === COMMENT_NODE && node.nodeValue === ' react-mount-point-unstable '));\n}\n\nvar ReactCurrentOwner$3 = ReactSharedInternals.ReactCurrentOwner;\nvar topLevelUpdateWarnings;\nvar warnedAboutHydrateAPI = false;\n\n{\n topLevelUpdateWarnings = function (container) {\n if (container._reactRootContainer && container.nodeType !== COMMENT_NODE) {\n var hostInstance = findHostInstanceWithNoPortals(container._reactRootContainer._internalRoot.current);\n\n if (hostInstance) {\n if (hostInstance.parentNode !== container) {\n error('render(...): It looks like the React-rendered content of this ' + 'container was removed without using React. This is not ' + 'supported and will cause errors. Instead, call ' + 'ReactDOM.unmountComponentAtNode to empty a container.');\n }\n }\n }\n\n var isRootRenderedBySomeReact = !!container._reactRootContainer;\n var rootEl = getReactRootElementInContainer(container);\n var hasNonRootReactChild = !!(rootEl && getInstanceFromNode$1(rootEl));\n\n if (hasNonRootReactChild && !isRootRenderedBySomeReact) {\n error('render(...): Replacing React-rendered children with a new root ' + 'component. If you intended to update the children of this node, ' + 'you should instead have the existing children update their state ' + 'and render the new components instead of calling ReactDOM.render.');\n }\n\n if (container.nodeType === ELEMENT_NODE && container.tagName && container.tagName.toUpperCase() === 'BODY') {\n error('render(): Rendering components directly into document.body is ' + 'discouraged, since its children are often manipulated by third-party ' + 'scripts and browser extensions. This may lead to subtle ' + 'reconciliation issues. Try rendering into a container element created ' + 'for your app.');\n }\n };\n}\n\nfunction getReactRootElementInContainer(container) {\n if (!container) {\n return null;\n }\n\n if (container.nodeType === DOCUMENT_NODE) {\n return container.documentElement;\n } else {\n return container.firstChild;\n }\n}\n\nfunction shouldHydrateDueToLegacyHeuristic(container) {\n var rootElement = getReactRootElementInContainer(container);\n return !!(rootElement && rootElement.nodeType === ELEMENT_NODE && rootElement.hasAttribute(ROOT_ATTRIBUTE_NAME));\n}\n\nfunction legacyCreateRootFromDOMContainer(container, forceHydrate) {\n var shouldHydrate = forceHydrate || shouldHydrateDueToLegacyHeuristic(container); // First clear any existing content.\n\n if (!shouldHydrate) {\n var warned = false;\n var rootSibling;\n\n while (rootSibling = container.lastChild) {\n {\n if (!warned && rootSibling.nodeType === ELEMENT_NODE && rootSibling.hasAttribute(ROOT_ATTRIBUTE_NAME)) {\n warned = true;\n\n error('render(): Target node has markup rendered by React, but there ' + 'are unrelated nodes as well. This is most commonly caused by ' + 'white-space inserted around server-rendered markup.');\n }\n }\n\n container.removeChild(rootSibling);\n }\n }\n\n {\n if (shouldHydrate && !forceHydrate && !warnedAboutHydrateAPI) {\n warnedAboutHydrateAPI = true;\n\n warn('render(): Calling ReactDOM.render() to hydrate server-rendered markup ' + 'will stop working in React v17. Replace the ReactDOM.render() call ' + 'with ReactDOM.hydrate() if you want React to attach to the server HTML.');\n }\n }\n\n return createLegacyRoot(container, shouldHydrate ? {\n hydrate: true\n } : undefined);\n}\n\nfunction warnOnInvalidCallback$1(callback, callerName) {\n {\n if (callback !== null && typeof callback !== 'function') {\n error('%s(...): Expected the last optional `callback` argument to be a ' + 'function. Instead received: %s.', callerName, callback);\n }\n }\n}\n\nfunction legacyRenderSubtreeIntoContainer(parentComponent, children, container, forceHydrate, callback) {\n {\n topLevelUpdateWarnings(container);\n warnOnInvalidCallback$1(callback === undefined ? null : callback, 'render');\n } // TODO: Without `any` type, Flow says \"Property cannot be accessed on any\n // member of intersection type.\" Whyyyyyy.\n\n\n var root = container._reactRootContainer;\n var fiberRoot;\n\n if (!root) {\n // Initial mount\n root = container._reactRootContainer = legacyCreateRootFromDOMContainer(container, forceHydrate);\n fiberRoot = root._internalRoot;\n\n if (typeof callback === 'function') {\n var originalCallback = callback;\n\n callback = function () {\n var instance = getPublicRootInstance(fiberRoot);\n originalCallback.call(instance);\n };\n } // Initial mount should not be batched.\n\n\n unbatchedUpdates(function () {\n updateContainer(children, fiberRoot, parentComponent, callback);\n });\n } else {\n fiberRoot = root._internalRoot;\n\n if (typeof callback === 'function') {\n var _originalCallback = callback;\n\n callback = function () {\n var instance = getPublicRootInstance(fiberRoot);\n\n _originalCallback.call(instance);\n };\n } // Update\n\n\n updateContainer(children, fiberRoot, parentComponent, callback);\n }\n\n return getPublicRootInstance(fiberRoot);\n}\n\nfunction findDOMNode(componentOrElement) {\n {\n var owner = ReactCurrentOwner$3.current;\n\n if (owner !== null && owner.stateNode !== null) {\n var warnedAboutRefsInRender = owner.stateNode._warnedAboutRefsInRender;\n\n if (!warnedAboutRefsInRender) {\n error('%s is accessing findDOMNode inside its render(). ' + 'render() should be a pure function of props and state. It should ' + 'never access something that requires stale data from the previous ' + 'render, such as refs. Move this logic to componentDidMount and ' + 'componentDidUpdate instead.', getComponentName(owner.type) || 'A component');\n }\n\n owner.stateNode._warnedAboutRefsInRender = true;\n }\n }\n\n if (componentOrElement == null) {\n return null;\n }\n\n if (componentOrElement.nodeType === ELEMENT_NODE) {\n return componentOrElement;\n }\n\n {\n return findHostInstanceWithWarning(componentOrElement, 'findDOMNode');\n }\n}\nfunction hydrate(element, container, callback) {\n if (!isValidContainer(container)) {\n {\n throw Error( \"Target container is not a DOM element.\" );\n }\n }\n\n {\n var isModernRoot = isContainerMarkedAsRoot(container) && container._reactRootContainer === undefined;\n\n if (isModernRoot) {\n error('You are calling ReactDOM.hydrate() on a container that was previously ' + 'passed to ReactDOM.createRoot(). This is not supported. ' + 'Did you mean to call createRoot(container, {hydrate: true}).render(element)?');\n }\n } // TODO: throw or warn if we couldn't hydrate?\n\n\n return legacyRenderSubtreeIntoContainer(null, element, container, true, callback);\n}\nfunction render(element, container, callback) {\n if (!isValidContainer(container)) {\n {\n throw Error( \"Target container is not a DOM element.\" );\n }\n }\n\n {\n var isModernRoot = isContainerMarkedAsRoot(container) && container._reactRootContainer === undefined;\n\n if (isModernRoot) {\n error('You are calling ReactDOM.render() on a container that was previously ' + 'passed to ReactDOM.createRoot(). This is not supported. ' + 'Did you mean to call root.render(element)?');\n }\n }\n\n return legacyRenderSubtreeIntoContainer(null, element, container, false, callback);\n}\nfunction unstable_renderSubtreeIntoContainer(parentComponent, element, containerNode, callback) {\n if (!isValidContainer(containerNode)) {\n {\n throw Error( \"Target container is not a DOM element.\" );\n }\n }\n\n if (!(parentComponent != null && has(parentComponent))) {\n {\n throw Error( \"parentComponent must be a valid React Component\" );\n }\n }\n\n return legacyRenderSubtreeIntoContainer(parentComponent, element, containerNode, false, callback);\n}\nfunction unmountComponentAtNode(container) {\n if (!isValidContainer(container)) {\n {\n throw Error( \"unmountComponentAtNode(...): Target container is not a DOM element.\" );\n }\n }\n\n {\n var isModernRoot = isContainerMarkedAsRoot(container) && container._reactRootContainer === undefined;\n\n if (isModernRoot) {\n error('You are calling ReactDOM.unmountComponentAtNode() on a container that was previously ' + 'passed to ReactDOM.createRoot(). This is not supported. Did you mean to call root.unmount()?');\n }\n }\n\n if (container._reactRootContainer) {\n {\n var rootEl = getReactRootElementInContainer(container);\n var renderedByDifferentReact = rootEl && !getInstanceFromNode$1(rootEl);\n\n if (renderedByDifferentReact) {\n error(\"unmountComponentAtNode(): The node you're attempting to unmount \" + 'was rendered by another copy of React.');\n }\n } // Unmount should not be batched.\n\n\n unbatchedUpdates(function () {\n legacyRenderSubtreeIntoContainer(null, null, container, false, function () {\n // $FlowFixMe This should probably use `delete container._reactRootContainer`\n container._reactRootContainer = null;\n unmarkContainerAsRoot(container);\n });\n }); // If you call unmountComponentAtNode twice in quick succession, you'll\n // get `true` twice. That's probably fine?\n\n return true;\n } else {\n {\n var _rootEl = getReactRootElementInContainer(container);\n\n var hasNonRootReactChild = !!(_rootEl && getInstanceFromNode$1(_rootEl)); // Check if the container itself is a React root node.\n\n var isContainerReactRoot = container.nodeType === ELEMENT_NODE && isValidContainer(container.parentNode) && !!container.parentNode._reactRootContainer;\n\n if (hasNonRootReactChild) {\n error(\"unmountComponentAtNode(): The node you're attempting to unmount \" + 'was rendered by React and is not a top-level container. %s', isContainerReactRoot ? 'You may have accidentally passed in a React root node instead ' + 'of its container.' : 'Instead, have the parent component update its state and ' + 'rerender in order to remove this component.');\n }\n }\n\n return false;\n }\n}\n\nfunction createPortal(children, containerInfo, // TODO: figure out the API for cross-renderer implementation.\nimplementation) {\n var key = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : null;\n return {\n // This tag allow us to uniquely identify this as a React Portal\n $$typeof: REACT_PORTAL_TYPE,\n key: key == null ? null : '' + key,\n children: children,\n containerInfo: containerInfo,\n implementation: implementation\n };\n}\n\nvar ReactVersion = '16.13.1';\n\nsetAttemptUserBlockingHydration(attemptUserBlockingHydration$1);\nsetAttemptContinuousHydration(attemptContinuousHydration$1);\nsetAttemptHydrationAtCurrentPriority(attemptHydrationAtCurrentPriority$1);\nvar didWarnAboutUnstableCreatePortal = false;\n\n{\n if (typeof Map !== 'function' || // $FlowIssue Flow incorrectly thinks Map has no prototype\n Map.prototype == null || typeof Map.prototype.forEach !== 'function' || typeof Set !== 'function' || // $FlowIssue Flow incorrectly thinks Set has no prototype\n Set.prototype == null || typeof Set.prototype.clear !== 'function' || typeof Set.prototype.forEach !== 'function') {\n error('React depends on Map and Set built-in types. Make sure that you load a ' + 'polyfill in older browsers. https://fb.me/react-polyfills');\n }\n}\n\nsetRestoreImplementation(restoreControlledState$3);\nsetBatchingImplementation(batchedUpdates$1, discreteUpdates$1, flushDiscreteUpdates, batchedEventUpdates$1);\n\nfunction createPortal$1(children, container) {\n var key = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null;\n\n if (!isValidContainer(container)) {\n {\n throw Error( \"Target container is not a DOM element.\" );\n }\n } // TODO: pass ReactDOM portal implementation as third argument\n // $FlowFixMe The Flow type is opaque but there's no way to actually create it.\n\n\n return createPortal(children, container, null, key);\n}\n\nfunction renderSubtreeIntoContainer(parentComponent, element, containerNode, callback) {\n\n return unstable_renderSubtreeIntoContainer(parentComponent, element, containerNode, callback);\n}\n\nfunction unstable_createPortal(children, container) {\n var key = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null;\n\n {\n if (!didWarnAboutUnstableCreatePortal) {\n didWarnAboutUnstableCreatePortal = true;\n\n warn('The ReactDOM.unstable_createPortal() alias has been deprecated, ' + 'and will be removed in React 17+. Update your code to use ' + 'ReactDOM.createPortal() instead. It has the exact same API, ' + 'but without the \"unstable_\" prefix.');\n }\n }\n\n return createPortal$1(children, container, key);\n}\n\nvar Internals = {\n // Keep in sync with ReactDOMUnstableNativeDependencies.js\n // ReactTestUtils.js, and ReactTestUtilsAct.js. This is an array for better minification.\n Events: [getInstanceFromNode$1, getNodeFromInstance$1, getFiberCurrentPropsFromNode$1, injectEventPluginsByName, eventNameDispatchConfigs, accumulateTwoPhaseDispatches, accumulateDirectDispatches, enqueueStateRestore, restoreStateIfNeeded, dispatchEvent, runEventsInBatch, flushPassiveEffects, IsThisRendererActing]\n};\nvar foundDevTools = injectIntoDevTools({\n findFiberByHostInstance: getClosestInstanceFromNode,\n bundleType: 1 ,\n version: ReactVersion,\n rendererPackageName: 'react-dom'\n});\n\n{\n if (!foundDevTools && canUseDOM && window.top === window.self) {\n // If we're in Chrome or Firefox, provide a download link if not installed.\n if (navigator.userAgent.indexOf('Chrome') > -1 && navigator.userAgent.indexOf('Edge') === -1 || navigator.userAgent.indexOf('Firefox') > -1) {\n var protocol = window.location.protocol; // Don't warn in exotic cases like chrome-extension://.\n\n if (/^(https?|file):$/.test(protocol)) {\n // eslint-disable-next-line react-internal/no-production-logging\n console.info('%cDownload the React DevTools ' + 'for a better development experience: ' + 'https://fb.me/react-devtools' + (protocol === 'file:' ? '\\nYou might need to use a local HTTP server (instead of file://): ' + 'https://fb.me/react-devtools-faq' : ''), 'font-weight:bold');\n }\n }\n }\n}\n\nexports.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED = Internals;\nexports.createPortal = createPortal$1;\nexports.findDOMNode = findDOMNode;\nexports.flushSync = flushSync;\nexports.hydrate = hydrate;\nexports.render = render;\nexports.unmountComponentAtNode = unmountComponentAtNode;\nexports.unstable_batchedUpdates = batchedUpdates$1;\nexports.unstable_createPortal = unstable_createPortal;\nexports.unstable_renderSubtreeIntoContainer = renderSubtreeIntoContainer;\nexports.version = ReactVersion;\n })();\n}\n\n\n//# sourceURL=webpack:///./node_modules/react-dom/cjs/react-dom.development.js?");
/***/ }),
/***/ "./node_modules/react-dom/index.js":
/*!*****************************************!*\
!*** ./node_modules/react-dom/index.js ***!
\*****************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
eval("\n\nfunction checkDCE() {\n /* global __REACT_DEVTOOLS_GLOBAL_HOOK__ */\n if (\n typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ === 'undefined' ||\n typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE !== 'function'\n ) {\n return;\n }\n if (true) {\n // This branch is unreachable because this function is only called\n // in production, but the condition is true only in development.\n // Therefore if the branch is still here, dead code elimination wasn't\n // properly applied.\n // Don't change the message. React DevTools relies on it. Also make sure\n // this message doesn't occur elsewhere in this function, or it will cause\n // a false positive.\n throw new Error('^_^');\n }\n try {\n // Verify that the code above has been dead code eliminated (DCE'd).\n __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(checkDCE);\n } catch (err) {\n // DevTools shouldn't crash React, no matter what.\n // We should still report in case we break this code.\n console.error(err);\n }\n}\n\nif (false) {} else {\n module.exports = __webpack_require__(/*! ./cjs/react-dom.development.js */ \"./node_modules/react-dom/cjs/react-dom.development.js\");\n}\n\n\n//# sourceURL=webpack:///./node_modules/react-dom/index.js?");
/***/ }),
/***/ "./node_modules/react-is/cjs/react-is.development.js":
/*!***********************************************************!*\
!*** ./node_modules/react-is/cjs/react-is.development.js ***!
\***********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
eval("/** @license React v16.13.1\n * react-is.development.js\n *\n * Copyright (c) Facebook, Inc. and its affiliates.\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\n\n\n\nif (true) {\n (function() {\n'use strict';\n\n// The Symbol used to tag the ReactElement-like types. If there is no native Symbol\n// nor polyfill, then a plain number is used for performance.\nvar hasSymbol = typeof Symbol === 'function' && Symbol.for;\nvar REACT_ELEMENT_TYPE = hasSymbol ? Symbol.for('react.element') : 0xeac7;\nvar REACT_PORTAL_TYPE = hasSymbol ? Symbol.for('react.portal') : 0xeaca;\nvar REACT_FRAGMENT_TYPE = hasSymbol ? Symbol.for('react.fragment') : 0xeacb;\nvar REACT_STRICT_MODE_TYPE = hasSymbol ? Symbol.for('react.strict_mode') : 0xeacc;\nvar REACT_PROFILER_TYPE = hasSymbol ? Symbol.for('react.profiler') : 0xead2;\nvar REACT_PROVIDER_TYPE = hasSymbol ? Symbol.for('react.provider') : 0xeacd;\nvar REACT_CONTEXT_TYPE = hasSymbol ? Symbol.for('react.context') : 0xeace; // TODO: We don't use AsyncMode or ConcurrentMode anymore. They were temporary\n// (unstable) APIs that have been removed. Can we remove the symbols?\n\nvar REACT_ASYNC_MODE_TYPE = hasSymbol ? Symbol.for('react.async_mode') : 0xeacf;\nvar REACT_CONCURRENT_MODE_TYPE = hasSymbol ? Symbol.for('react.concurrent_mode') : 0xeacf;\nvar REACT_FORWARD_REF_TYPE = hasSymbol ? Symbol.for('react.forward_ref') : 0xead0;\nvar REACT_SUSPENSE_TYPE = hasSymbol ? Symbol.for('react.suspense') : 0xead1;\nvar REACT_SUSPENSE_LIST_TYPE = hasSymbol ? Symbol.for('react.suspense_list') : 0xead8;\nvar REACT_MEMO_TYPE = hasSymbol ? Symbol.for('react.memo') : 0xead3;\nvar REACT_LAZY_TYPE = hasSymbol ? Symbol.for('react.lazy') : 0xead4;\nvar REACT_BLOCK_TYPE = hasSymbol ? Symbol.for('react.block') : 0xead9;\nvar REACT_FUNDAMENTAL_TYPE = hasSymbol ? Symbol.for('react.fundamental') : 0xead5;\nvar REACT_RESPONDER_TYPE = hasSymbol ? Symbol.for('react.responder') : 0xead6;\nvar REACT_SCOPE_TYPE = hasSymbol ? Symbol.for('react.scope') : 0xead7;\n\nfunction isValidElementType(type) {\n return typeof type === 'string' || typeof type === 'function' || // Note: its typeof might be other than 'symbol' or 'number' if it's a polyfill.\n type === REACT_FRAGMENT_TYPE || type === REACT_CONCURRENT_MODE_TYPE || type === REACT_PROFILER_TYPE || type === REACT_STRICT_MODE_TYPE || type === REACT_SUSPENSE_TYPE || type === REACT_SUSPENSE_LIST_TYPE || typeof type === 'object' && type !== null && (type.$$typeof === REACT_LAZY_TYPE || type.$$typeof === REACT_MEMO_TYPE || type.$$typeof === REACT_PROVIDER_TYPE || type.$$typeof === REACT_CONTEXT_TYPE || type.$$typeof === REACT_FORWARD_REF_TYPE || type.$$typeof === REACT_FUNDAMENTAL_TYPE || type.$$typeof === REACT_RESPONDER_TYPE || type.$$typeof === REACT_SCOPE_TYPE || type.$$typeof === REACT_BLOCK_TYPE);\n}\n\nfunction typeOf(object) {\n if (typeof object === 'object' && object !== null) {\n var $$typeof = object.$$typeof;\n\n switch ($$typeof) {\n case REACT_ELEMENT_TYPE:\n var type = object.type;\n\n switch (type) {\n case REACT_ASYNC_MODE_TYPE:\n case REACT_CONCURRENT_MODE_TYPE:\n case REACT_FRAGMENT_TYPE:\n case REACT_PROFILER_TYPE:\n case REACT_STRICT_MODE_TYPE:\n case REACT_SUSPENSE_TYPE:\n return type;\n\n default:\n var $$typeofType = type && type.$$typeof;\n\n switch ($$typeofType) {\n case REACT_CONTEXT_TYPE:\n case REACT_FORWARD_REF_TYPE:\n case REACT_LAZY_TYPE:\n case REACT_MEMO_TYPE:\n case REACT_PROVIDER_TYPE:\n return $$typeofType;\n\n default:\n return $$typeof;\n }\n\n }\n\n case REACT_PORTAL_TYPE:\n return $$typeof;\n }\n }\n\n return undefined;\n} // AsyncMode is deprecated along with isAsyncMode\n\nvar AsyncMode = REACT_ASYNC_MODE_TYPE;\nvar ConcurrentMode = REACT_CONCURRENT_MODE_TYPE;\nvar ContextConsumer = REACT_CONTEXT_TYPE;\nvar ContextProvider = REACT_PROVIDER_TYPE;\nvar Element = REACT_ELEMENT_TYPE;\nvar ForwardRef = REACT_FORWARD_REF_TYPE;\nvar Fragment = REACT_FRAGMENT_TYPE;\nvar Lazy = REACT_LAZY_TYPE;\nvar Memo = REACT_MEMO_TYPE;\nvar Portal = REACT_PORTAL_TYPE;\nvar Profiler = REACT_PROFILER_TYPE;\nvar StrictMode = REACT_STRICT_MODE_TYPE;\nvar Suspense = REACT_SUSPENSE_TYPE;\nvar hasWarnedAboutDeprecatedIsAsyncMode = false; // AsyncMode should be deprecated\n\nfunction isAsyncMode(object) {\n {\n if (!hasWarnedAboutDeprecatedIsAsyncMode) {\n hasWarnedAboutDeprecatedIsAsyncMode = true; // Using console['warn'] to evade Babel and ESLint\n\n console['warn']('The ReactIs.isAsyncMode() alias has been deprecated, ' + 'and will be removed in React 17+. Update your code to use ' + 'ReactIs.isConcurrentMode() instead. It has the exact same API.');\n }\n }\n\n return isConcurrentMode(object) || typeOf(object) === REACT_ASYNC_MODE_TYPE;\n}\nfunction isConcurrentMode(object) {\n return typeOf(object) === REACT_CONCURRENT_MODE_TYPE;\n}\nfunction isContextConsumer(object) {\n return typeOf(object) === REACT_CONTEXT_TYPE;\n}\nfunction isContextProvider(object) {\n return typeOf(object) === REACT_PROVIDER_TYPE;\n}\nfunction isElement(object) {\n return typeof object === 'object' && object !== null && object.$$typeof === REACT_ELEMENT_TYPE;\n}\nfunction isForwardRef(object) {\n return typeOf(object) === REACT_FORWARD_REF_TYPE;\n}\nfunction isFragment(object) {\n return typeOf(object) === REACT_FRAGMENT_TYPE;\n}\nfunction isLazy(object) {\n return typeOf(object) === REACT_LAZY_TYPE;\n}\nfunction isMemo(object) {\n return typeOf(object) === REACT_MEMO_TYPE;\n}\nfunction isPortal(object) {\n return typeOf(object) === REACT_PORTAL_TYPE;\n}\nfunction isProfiler(object) {\n return typeOf(object) === REACT_PROFILER_TYPE;\n}\nfunction isStrictMode(object) {\n return typeOf(object) === REACT_STRICT_MODE_TYPE;\n}\nfunction isSuspense(object) {\n return typeOf(object) === REACT_SUSPENSE_TYPE;\n}\n\nexports.AsyncMode = AsyncMode;\nexports.ConcurrentMode = ConcurrentMode;\nexports.ContextConsumer = ContextConsumer;\nexports.ContextProvider = ContextProvider;\nexports.Element = Element;\nexports.ForwardRef = ForwardRef;\nexports.Fragment = Fragment;\nexports.Lazy = Lazy;\nexports.Memo = Memo;\nexports.Portal = Portal;\nexports.Profiler = Profiler;\nexports.StrictMode = StrictMode;\nexports.Suspense = Suspense;\nexports.isAsyncMode = isAsyncMode;\nexports.isConcurrentMode = isConcurrentMode;\nexports.isContextConsumer = isContextConsumer;\nexports.isContextProvider = isContextProvider;\nexports.isElement = isElement;\nexports.isForwardRef = isForwardRef;\nexports.isFragment = isFragment;\nexports.isLazy = isLazy;\nexports.isMemo = isMemo;\nexports.isPortal = isPortal;\nexports.isProfiler = isProfiler;\nexports.isStrictMode = isStrictMode;\nexports.isSuspense = isSuspense;\nexports.isValidElementType = isValidElementType;\nexports.typeOf = typeOf;\n })();\n}\n\n\n//# sourceURL=webpack:///./node_modules/react-is/cjs/react-is.development.js?");
/***/ }),
/***/ "./node_modules/react-is/index.js":
/*!****************************************!*\
!*** ./node_modules/react-is/index.js ***!
\****************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
eval("\n\nif (false) {} else {\n module.exports = __webpack_require__(/*! ./cjs/react-is.development.js */ \"./node_modules/react-is/cjs/react-is.development.js\");\n}\n\n\n//# sourceURL=webpack:///./node_modules/react-is/index.js?");
/***/ }),
/***/ "./node_modules/react-router-dom/esm/react-router-dom.js":
/*!***************************************************************!*\
!*** ./node_modules/react-router-dom/esm/react-router-dom.js ***!
\***************************************************************/
/*! exports provided: MemoryRouter, Prompt, Redirect, Route, Router, StaticRouter, Switch, __RouterContext, generatePath, matchPath, useHistory, useLocation, useParams, useRouteMatch, withRouter, BrowserRouter, HashRouter, Link, NavLink */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"BrowserRouter\", function() { return BrowserRouter; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"HashRouter\", function() { return HashRouter; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"Link\", function() { return Link; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"NavLink\", function() { return NavLink; });\n/* harmony import */ var react_router__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! react-router */ \"./node_modules/react-router/esm/react-router.js\");\n/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, \"MemoryRouter\", function() { return react_router__WEBPACK_IMPORTED_MODULE_0__[\"MemoryRouter\"]; });\n\n/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, \"Prompt\", function() { return react_router__WEBPACK_IMPORTED_MODULE_0__[\"Prompt\"]; });\n\n/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, \"Redirect\", function() { return react_router__WEBPACK_IMPORTED_MODULE_0__[\"Redirect\"]; });\n\n/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, \"Route\", function() { return react_router__WEBPACK_IMPORTED_MODULE_0__[\"Route\"]; });\n\n/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, \"Router\", function() { return react_router__WEBPACK_IMPORTED_MODULE_0__[\"Router\"]; });\n\n/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, \"StaticRouter\", function() { return react_router__WEBPACK_IMPORTED_MODULE_0__[\"StaticRouter\"]; });\n\n/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, \"Switch\", function() { return react_router__WEBPACK_IMPORTED_MODULE_0__[\"Switch\"]; });\n\n/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, \"__RouterContext\", function() { return react_router__WEBPACK_IMPORTED_MODULE_0__[\"__RouterContext\"]; });\n\n/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, \"generatePath\", function() { return react_router__WEBPACK_IMPORTED_MODULE_0__[\"generatePath\"]; });\n\n/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, \"matchPath\", function() { return react_router__WEBPACK_IMPORTED_MODULE_0__[\"matchPath\"]; });\n\n/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, \"useHistory\", function() { return react_router__WEBPACK_IMPORTED_MODULE_0__[\"useHistory\"]; });\n\n/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, \"useLocation\", function() { return react_router__WEBPACK_IMPORTED_MODULE_0__[\"useLocation\"]; });\n\n/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, \"useParams\", function() { return react_router__WEBPACK_IMPORTED_MODULE_0__[\"useParams\"]; });\n\n/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, \"useRouteMatch\", function() { return react_router__WEBPACK_IMPORTED_MODULE_0__[\"useRouteMatch\"]; });\n\n/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, \"withRouter\", function() { return react_router__WEBPACK_IMPORTED_MODULE_0__[\"withRouter\"]; });\n\n/* harmony import */ var _babel_runtime_helpers_esm_inheritsLoose__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @babel/runtime/helpers/esm/inheritsLoose */ \"./node_modules/@babel/runtime/helpers/esm/inheritsLoose.js\");\n/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! react */ \"./node_modules/react/index.js\");\n/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_2__);\n/* harmony import */ var history__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! history */ \"./node_modules/history/esm/history.js\");\n/* harmony import */ var prop_types__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! prop-types */ \"./node_modules/prop-types/index.js\");\n/* harmony import */ var prop_types__WEBPACK_IMPORTED_MODULE_4___default = /*#__PURE__*/__webpack_require__.n(prop_types__WEBPACK_IMPORTED_MODULE_4__);\n/* harmony import */ var tiny_warning__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! tiny-warning */ \"./node_modules/tiny-warning/dist/tiny-warning.esm.js\");\n/* harmony import */ var _babel_runtime_helpers_esm_extends__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! @babel/runtime/helpers/esm/extends */ \"./node_modules/@babel/runtime/helpers/esm/extends.js\");\n/* harmony import */ var _babel_runtime_helpers_esm_objectWithoutPropertiesLoose__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! @babel/runtime/helpers/esm/objectWithoutPropertiesLoose */ \"./node_modules/@babel/runtime/helpers/esm/objectWithoutPropertiesLoose.js\");\n/* harmony import */ var tiny_invariant__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! tiny-invariant */ \"./node_modules/tiny-invariant/dist/tiny-invariant.esm.js\");\n\n\n\n\n\n\n\n\n\n\n\n/**\n * The public API for a <Router> that uses HTML5 history.\n */\n\nvar BrowserRouter =\n/*#__PURE__*/\nfunction (_React$Component) {\n Object(_babel_runtime_helpers_esm_inheritsLoose__WEBPACK_IMPORTED_MODULE_1__[\"default\"])(BrowserRouter, _React$Component);\n\n function BrowserRouter() {\n var _this;\n\n for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {\n args[_key] = arguments[_key];\n }\n\n _this = _React$Component.call.apply(_React$Component, [this].concat(args)) || this;\n _this.history = Object(history__WEBPACK_IMPORTED_MODULE_3__[\"createBrowserHistory\"])(_this.props);\n return _this;\n }\n\n var _proto = BrowserRouter.prototype;\n\n _proto.render = function render() {\n return react__WEBPACK_IMPORTED_MODULE_2___default.a.createElement(react_router__WEBPACK_IMPORTED_MODULE_0__[\"Router\"], {\n history: this.history,\n children: this.props.children\n });\n };\n\n return BrowserRouter;\n}(react__WEBPACK_IMPORTED_MODULE_2___default.a.Component);\n\nif (true) {\n BrowserRouter.propTypes = {\n basename: prop_types__WEBPACK_IMPORTED_MODULE_4___default.a.string,\n children: prop_types__WEBPACK_IMPORTED_MODULE_4___default.a.node,\n forceRefresh: prop_types__WEBPACK_IMPORTED_MODULE_4___default.a.bool,\n getUserConfirmation: prop_types__WEBPACK_IMPORTED_MODULE_4___default.a.func,\n keyLength: prop_types__WEBPACK_IMPORTED_MODULE_4___default.a.number\n };\n\n BrowserRouter.prototype.componentDidMount = function () {\n true ? Object(tiny_warning__WEBPACK_IMPORTED_MODULE_5__[\"default\"])(!this.props.history, \"<BrowserRouter> ignores the history prop. To use a custom history, \" + \"use `import { Router }` instead of `import { BrowserRouter as Router }`.\") : undefined;\n };\n}\n\n/**\n * The public API for a <Router> that uses window.location.hash.\n */\n\nvar HashRouter =\n/*#__PURE__*/\nfunction (_React$Component) {\n Object(_babel_runtime_helpers_esm_inheritsLoose__WEBPACK_IMPORTED_MODULE_1__[\"default\"])(HashRouter, _React$Component);\n\n function HashRouter() {\n var _this;\n\n for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {\n args[_key] = arguments[_key];\n }\n\n _this = _React$Component.call.apply(_React$Component, [this].concat(args)) || this;\n _this.history = Object(history__WEBPACK_IMPORTED_MODULE_3__[\"createHashHistory\"])(_this.props);\n return _this;\n }\n\n var _proto = HashRouter.prototype;\n\n _proto.render = function render() {\n return react__WEBPACK_IMPORTED_MODULE_2___default.a.createElement(react_router__WEBPACK_IMPORTED_MODULE_0__[\"Router\"], {\n history: this.history,\n children: this.props.children\n });\n };\n\n return HashRouter;\n}(react__WEBPACK_IMPORTED_MODULE_2___default.a.Component);\n\nif (true) {\n HashRouter.propTypes = {\n basename: prop_types__WEBPACK_IMPORTED_MODULE_4___default.a.string,\n children: prop_types__WEBPACK_IMPORTED_MODULE_4___default.a.node,\n getUserConfirmation: prop_types__WEBPACK_IMPORTED_MODULE_4___default.a.func,\n hashType: prop_types__WEBPACK_IMPORTED_MODULE_4___default.a.oneOf([\"hashbang\", \"noslash\", \"slash\"])\n };\n\n HashRouter.prototype.componentDidMount = function () {\n true ? Object(tiny_warning__WEBPACK_IMPORTED_MODULE_5__[\"default\"])(!this.props.history, \"<HashRouter> ignores the history prop. To use a custom history, \" + \"use `import { Router }` instead of `import { HashRouter as Router }`.\") : undefined;\n };\n}\n\nvar resolveToLocation = function resolveToLocation(to, currentLocation) {\n return typeof to === \"function\" ? to(currentLocation) : to;\n};\nvar normalizeToLocation = function normalizeToLocation(to, currentLocation) {\n return typeof to === \"string\" ? Object(history__WEBPACK_IMPORTED_MODULE_3__[\"createLocation\"])(to, null, null, currentLocation) : to;\n};\n\nvar forwardRefShim = function forwardRefShim(C) {\n return C;\n};\n\nvar forwardRef = react__WEBPACK_IMPORTED_MODULE_2___default.a.forwardRef;\n\nif (typeof forwardRef === \"undefined\") {\n forwardRef = forwardRefShim;\n}\n\nfunction isModifiedEvent(event) {\n return !!(event.metaKey || event.altKey || event.ctrlKey || event.shiftKey);\n}\n\nvar LinkAnchor = forwardRef(function (_ref, forwardedRef) {\n var innerRef = _ref.innerRef,\n navigate = _ref.navigate,\n _onClick = _ref.onClick,\n rest = Object(_babel_runtime_helpers_esm_objectWithoutPropertiesLoose__WEBPACK_IMPORTED_MODULE_7__[\"default\"])(_ref, [\"innerRef\", \"navigate\", \"onClick\"]);\n\n var target = rest.target;\n\n var props = Object(_babel_runtime_helpers_esm_extends__WEBPACK_IMPORTED_MODULE_6__[\"default\"])({}, rest, {\n onClick: function onClick(event) {\n try {\n if (_onClick) _onClick(event);\n } catch (ex) {\n event.preventDefault();\n throw ex;\n }\n\n if (!event.defaultPrevented && // onClick prevented default\n event.button === 0 && ( // ignore everything but left clicks\n !target || target === \"_self\") && // let browser handle \"target=_blank\" etc.\n !isModifiedEvent(event) // ignore clicks with modifier keys\n ) {\n event.preventDefault();\n navigate();\n }\n }\n }); // React 15 compat\n\n\n if (forwardRefShim !== forwardRef) {\n props.ref = forwardedRef || innerRef;\n } else {\n props.ref = innerRef;\n }\n\n return react__WEBPACK_IMPORTED_MODULE_2___default.a.createElement(\"a\", props);\n});\n\nif (true) {\n LinkAnchor.displayName = \"LinkAnchor\";\n}\n/**\n * The public API for rendering a history-aware <a>.\n */\n\n\nvar Link = forwardRef(function (_ref2, forwardedRef) {\n var _ref2$component = _ref2.component,\n component = _ref2$component === void 0 ? LinkAnchor : _ref2$component,\n replace = _ref2.replace,\n to = _ref2.to,\n innerRef = _ref2.innerRef,\n rest = Object(_babel_runtime_helpers_esm_objectWithoutPropertiesLoose__WEBPACK_IMPORTED_MODULE_7__[\"default\"])(_ref2, [\"component\", \"replace\", \"to\", \"innerRef\"]);\n\n return react__WEBPACK_IMPORTED_MODULE_2___default.a.createElement(react_router__WEBPACK_IMPORTED_MODULE_0__[\"__RouterContext\"].Consumer, null, function (context) {\n !context ? true ? Object(tiny_invariant__WEBPACK_IMPORTED_MODULE_8__[\"default\"])(false, \"You should not use <Link> outside a <Router>\") : undefined : void 0;\n var history = context.history;\n var location = normalizeToLocation(resolveToLocation(to, context.location), context.location);\n var href = location ? history.createHref(location) : \"\";\n\n var props = Object(_babel_runtime_helpers_esm_extends__WEBPACK_IMPORTED_MODULE_6__[\"default\"])({}, rest, {\n href: href,\n navigate: function navigate() {\n var location = resolveToLocation(to, context.location);\n var method = replace ? history.replace : history.push;\n method(location);\n }\n }); // React 15 compat\n\n\n if (forwardRefShim !== forwardRef) {\n props.ref = forwardedRef || innerRef;\n } else {\n props.innerRef = innerRef;\n }\n\n return react__WEBPACK_IMPORTED_MODULE_2___default.a.createElement(component, props);\n });\n});\n\nif (true) {\n var toType = prop_types__WEBPACK_IMPORTED_MODULE_4___default.a.oneOfType([prop_types__WEBPACK_IMPORTED_MODULE_4___default.a.string, prop_types__WEBPACK_IMPORTED_MODULE_4___default.a.object, prop_types__WEBPACK_IMPORTED_MODULE_4___default.a.func]);\n var refType = prop_types__WEBPACK_IMPORTED_MODULE_4___default.a.oneOfType([prop_types__WEBPACK_IMPORTED_MODULE_4___default.a.string, prop_types__WEBPACK_IMPORTED_MODULE_4___default.a.func, prop_types__WEBPACK_IMPORTED_MODULE_4___default.a.shape({\n current: prop_types__WEBPACK_IMPORTED_MODULE_4___default.a.any\n })]);\n Link.displayName = \"Link\";\n Link.propTypes = {\n innerRef: refType,\n onClick: prop_types__WEBPACK_IMPORTED_MODULE_4___default.a.func,\n replace: prop_types__WEBPACK_IMPORTED_MODULE_4___default.a.bool,\n target: prop_types__WEBPACK_IMPORTED_MODULE_4___default.a.string,\n to: toType.isRequired\n };\n}\n\nvar forwardRefShim$1 = function forwardRefShim(C) {\n return C;\n};\n\nvar forwardRef$1 = react__WEBPACK_IMPORTED_MODULE_2___default.a.forwardRef;\n\nif (typeof forwardRef$1 === \"undefined\") {\n forwardRef$1 = forwardRefShim$1;\n}\n\nfunction joinClassnames() {\n for (var _len = arguments.length, classnames = new Array(_len), _key = 0; _key < _len; _key++) {\n classnames[_key] = arguments[_key];\n }\n\n return classnames.filter(function (i) {\n return i;\n }).join(\" \");\n}\n/**\n * A <Link> wrapper that knows if it's \"active\" or not.\n */\n\n\nvar NavLink = forwardRef$1(function (_ref, forwardedRef) {\n var _ref$ariaCurrent = _ref[\"aria-current\"],\n ariaCurrent = _ref$ariaCurrent === void 0 ? \"page\" : _ref$ariaCurrent,\n _ref$activeClassName = _ref.activeClassName,\n activeClassName = _ref$activeClassName === void 0 ? \"active\" : _ref$activeClassName,\n activeStyle = _ref.activeStyle,\n classNameProp = _ref.className,\n exact = _ref.exact,\n isActiveProp = _ref.isActive,\n locationProp = _ref.location,\n strict = _ref.strict,\n styleProp = _ref.style,\n to = _ref.to,\n innerRef = _ref.innerRef,\n rest = Object(_babel_runtime_helpers_esm_objectWithoutPropertiesLoose__WEBPACK_IMPORTED_MODULE_7__[\"default\"])(_ref, [\"aria-current\", \"activeClassName\", \"activeStyle\", \"className\", \"exact\", \"isActive\", \"location\", \"strict\", \"style\", \"to\", \"innerRef\"]);\n\n return react__WEBPACK_IMPORTED_MODULE_2___default.a.createElement(react_router__WEBPACK_IMPORTED_MODULE_0__[\"__RouterContext\"].Consumer, null, function (context) {\n !context ? true ? Object(tiny_invariant__WEBPACK_IMPORTED_MODULE_8__[\"default\"])(false, \"You should not use <NavLink> outside a <Router>\") : undefined : void 0;\n var currentLocation = locationProp || context.location;\n var toLocation = normalizeToLocation(resolveToLocation(to, currentLocation), currentLocation);\n var path = toLocation.pathname; // Regex taken from: https://github.com/pillarjs/path-to-regexp/blob/master/index.js#L202\n\n var escapedPath = path && path.replace(/([.+*?=^!:${}()[\\]|/\\\\])/g, \"\\\\$1\");\n var match = escapedPath ? Object(react_router__WEBPACK_IMPORTED_MODULE_0__[\"matchPath\"])(currentLocation.pathname, {\n path: escapedPath,\n exact: exact,\n strict: strict\n }) : null;\n var isActive = !!(isActiveProp ? isActiveProp(match, currentLocation) : match);\n var className = isActive ? joinClassnames(classNameProp, activeClassName) : classNameProp;\n var style = isActive ? Object(_babel_runtime_helpers_esm_extends__WEBPACK_IMPORTED_MODULE_6__[\"default\"])({}, styleProp, {}, activeStyle) : styleProp;\n\n var props = Object(_babel_runtime_helpers_esm_extends__WEBPACK_IMPORTED_MODULE_6__[\"default\"])({\n \"aria-current\": isActive && ariaCurrent || null,\n className: className,\n style: style,\n to: toLocation\n }, rest); // React 15 compat\n\n\n if (forwardRefShim$1 !== forwardRef$1) {\n props.ref = forwardedRef || innerRef;\n } else {\n props.innerRef = innerRef;\n }\n\n return react__WEBPACK_IMPORTED_MODULE_2___default.a.createElement(Link, props);\n });\n});\n\nif (true) {\n NavLink.displayName = \"NavLink\";\n var ariaCurrentType = prop_types__WEBPACK_IMPORTED_MODULE_4___default.a.oneOf([\"page\", \"step\", \"location\", \"date\", \"time\", \"true\"]);\n NavLink.propTypes = Object(_babel_runtime_helpers_esm_extends__WEBPACK_IMPORTED_MODULE_6__[\"default\"])({}, Link.propTypes, {\n \"aria-current\": ariaCurrentType,\n activeClassName: prop_types__WEBPACK_IMPORTED_MODULE_4___default.a.string,\n activeStyle: prop_types__WEBPACK_IMPORTED_MODULE_4___default.a.object,\n className: prop_types__WEBPACK_IMPORTED_MODULE_4___default.a.string,\n exact: prop_types__WEBPACK_IMPORTED_MODULE_4___default.a.bool,\n isActive: prop_types__WEBPACK_IMPORTED_MODULE_4___default.a.func,\n location: prop_types__WEBPACK_IMPORTED_MODULE_4___default.a.object,\n strict: prop_types__WEBPACK_IMPORTED_MODULE_4___default.a.bool,\n style: prop_types__WEBPACK_IMPORTED_MODULE_4___default.a.object\n });\n}\n\n\n//# sourceMappingURL=react-router-dom.js.map\n\n\n//# sourceURL=webpack:///./node_modules/react-router-dom/esm/react-router-dom.js?");
/***/ }),
/***/ "./node_modules/react-router/esm/react-router.js":
/*!*******************************************************!*\
!*** ./node_modules/react-router/esm/react-router.js ***!
\*******************************************************/
/*! exports provided: MemoryRouter, Prompt, Redirect, Route, Router, StaticRouter, Switch, __RouterContext, generatePath, matchPath, useHistory, useLocation, useParams, useRouteMatch, withRouter */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"MemoryRouter\", function() { return MemoryRouter; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"Prompt\", function() { return Prompt; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"Redirect\", function() { return Redirect; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"Route\", function() { return Route; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"Router\", function() { return Router; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"StaticRouter\", function() { return StaticRouter; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"Switch\", function() { return Switch; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"__RouterContext\", function() { return context; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"generatePath\", function() { return generatePath; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"matchPath\", function() { return matchPath; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"useHistory\", function() { return useHistory; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"useLocation\", function() { return useLocation; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"useParams\", function() { return useParams; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"useRouteMatch\", function() { return useRouteMatch; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"withRouter\", function() { return withRouter; });\n/* harmony import */ var _babel_runtime_helpers_esm_inheritsLoose__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @babel/runtime/helpers/esm/inheritsLoose */ \"./node_modules/@babel/runtime/helpers/esm/inheritsLoose.js\");\n/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! react */ \"./node_modules/react/index.js\");\n/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_1__);\n/* harmony import */ var prop_types__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! prop-types */ \"./node_modules/prop-types/index.js\");\n/* harmony import */ var prop_types__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(prop_types__WEBPACK_IMPORTED_MODULE_2__);\n/* harmony import */ var history__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! history */ \"./node_modules/history/esm/history.js\");\n/* harmony import */ var tiny_warning__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! tiny-warning */ \"./node_modules/tiny-warning/dist/tiny-warning.esm.js\");\n/* harmony import */ var mini_create_react_context__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! mini-create-react-context */ \"./node_modules/mini-create-react-context/dist/esm/index.js\");\n/* harmony import */ var tiny_invariant__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! tiny-invariant */ \"./node_modules/tiny-invariant/dist/tiny-invariant.esm.js\");\n/* harmony import */ var _babel_runtime_helpers_esm_extends__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! @babel/runtime/helpers/esm/extends */ \"./node_modules/@babel/runtime/helpers/esm/extends.js\");\n/* harmony import */ var path_to_regexp__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! path-to-regexp */ \"./node_modules/react-router/node_modules/path-to-regexp/index.js\");\n/* harmony import */ var path_to_regexp__WEBPACK_IMPORTED_MODULE_8___default = /*#__PURE__*/__webpack_require__.n(path_to_regexp__WEBPACK_IMPORTED_MODULE_8__);\n/* harmony import */ var react_is__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! react-is */ \"./node_modules/react-is/index.js\");\n/* harmony import */ var react_is__WEBPACK_IMPORTED_MODULE_9___default = /*#__PURE__*/__webpack_require__.n(react_is__WEBPACK_IMPORTED_MODULE_9__);\n/* harmony import */ var _babel_runtime_helpers_esm_objectWithoutPropertiesLoose__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! @babel/runtime/helpers/esm/objectWithoutPropertiesLoose */ \"./node_modules/@babel/runtime/helpers/esm/objectWithoutPropertiesLoose.js\");\n/* harmony import */ var hoist_non_react_statics__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! hoist-non-react-statics */ \"./node_modules/hoist-non-react-statics/dist/hoist-non-react-statics.cjs.js\");\n/* harmony import */ var hoist_non_react_statics__WEBPACK_IMPORTED_MODULE_11___default = /*#__PURE__*/__webpack_require__.n(hoist_non_react_statics__WEBPACK_IMPORTED_MODULE_11__);\n\n\n\n\n\n\n\n\n\n\n\n\n\n// TODO: Replace with React.createContext once we can assume React 16+\n\nvar createNamedContext = function createNamedContext(name) {\n var context = Object(mini_create_react_context__WEBPACK_IMPORTED_MODULE_5__[\"default\"])();\n context.displayName = name;\n return context;\n};\n\nvar context =\n/*#__PURE__*/\ncreateNamedContext(\"Router\");\n\n/**\n * The public API for putting history on context.\n */\n\nvar Router =\n/*#__PURE__*/\nfunction (_React$Component) {\n Object(_babel_runtime_helpers_esm_inheritsLoose__WEBPACK_IMPORTED_MODULE_0__[\"default\"])(Router, _React$Component);\n\n Router.computeRootMatch = function computeRootMatch(pathname) {\n return {\n path: \"/\",\n url: \"/\",\n params: {},\n isExact: pathname === \"/\"\n };\n };\n\n function Router(props) {\n var _this;\n\n _this = _React$Component.call(this, props) || this;\n _this.state = {\n location: props.history.location\n }; // This is a bit of a hack. We have to start listening for location\n // changes here in the constructor in case there are any <Redirect>s\n // on the initial render. If there are, they will replace/push when\n // they mount and since cDM fires in children before parents, we may\n // get a new location before the <Router> is mounted.\n\n _this._isMounted = false;\n _this._pendingLocation = null;\n\n if (!props.staticContext) {\n _this.unlisten = props.history.listen(function (location) {\n if (_this._isMounted) {\n _this.setState({\n location: location\n });\n } else {\n _this._pendingLocation = location;\n }\n });\n }\n\n return _this;\n }\n\n var _proto = Router.prototype;\n\n _proto.componentDidMount = function componentDidMount() {\n this._isMounted = true;\n\n if (this._pendingLocation) {\n this.setState({\n location: this._pendingLocation\n });\n }\n };\n\n _proto.componentWillUnmount = function componentWillUnmount() {\n if (this.unlisten) this.unlisten();\n };\n\n _proto.render = function render() {\n return react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(context.Provider, {\n children: this.props.children || null,\n value: {\n history: this.props.history,\n location: this.state.location,\n match: Router.computeRootMatch(this.state.location.pathname),\n staticContext: this.props.staticContext\n }\n });\n };\n\n return Router;\n}(react__WEBPACK_IMPORTED_MODULE_1___default.a.Component);\n\nif (true) {\n Router.propTypes = {\n children: prop_types__WEBPACK_IMPORTED_MODULE_2___default.a.node,\n history: prop_types__WEBPACK_IMPORTED_MODULE_2___default.a.object.isRequired,\n staticContext: prop_types__WEBPACK_IMPORTED_MODULE_2___default.a.object\n };\n\n Router.prototype.componentDidUpdate = function (prevProps) {\n true ? Object(tiny_warning__WEBPACK_IMPORTED_MODULE_4__[\"default\"])(prevProps.history === this.props.history, \"You cannot change <Router history>\") : undefined;\n };\n}\n\n/**\n * The public API for a <Router> that stores location in memory.\n */\n\nvar MemoryRouter =\n/*#__PURE__*/\nfunction (_React$Component) {\n Object(_babel_runtime_helpers_esm_inheritsLoose__WEBPACK_IMPORTED_MODULE_0__[\"default\"])(MemoryRouter, _React$Component);\n\n function MemoryRouter() {\n var _this;\n\n for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {\n args[_key] = arguments[_key];\n }\n\n _this = _React$Component.call.apply(_React$Component, [this].concat(args)) || this;\n _this.history = Object(history__WEBPACK_IMPORTED_MODULE_3__[\"createMemoryHistory\"])(_this.props);\n return _this;\n }\n\n var _proto = MemoryRouter.prototype;\n\n _proto.render = function render() {\n return react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(Router, {\n history: this.history,\n children: this.props.children\n });\n };\n\n return MemoryRouter;\n}(react__WEBPACK_IMPORTED_MODULE_1___default.a.Component);\n\nif (true) {\n MemoryRouter.propTypes = {\n initialEntries: prop_types__WEBPACK_IMPORTED_MODULE_2___default.a.array,\n initialIndex: prop_types__WEBPACK_IMPORTED_MODULE_2___default.a.number,\n getUserConfirmation: prop_types__WEBPACK_IMPORTED_MODULE_2___default.a.func,\n keyLength: prop_types__WEBPACK_IMPORTED_MODULE_2___default.a.number,\n children: prop_types__WEBPACK_IMPORTED_MODULE_2___default.a.node\n };\n\n MemoryRouter.prototype.componentDidMount = function () {\n true ? Object(tiny_warning__WEBPACK_IMPORTED_MODULE_4__[\"default\"])(!this.props.history, \"<MemoryRouter> ignores the history prop. To use a custom history, \" + \"use `import { Router }` instead of `import { MemoryRouter as Router }`.\") : undefined;\n };\n}\n\nvar Lifecycle =\n/*#__PURE__*/\nfunction (_React$Component) {\n Object(_babel_runtime_helpers_esm_inheritsLoose__WEBPACK_IMPORTED_MODULE_0__[\"default\"])(Lifecycle, _React$Component);\n\n function Lifecycle() {\n return _React$Component.apply(this, arguments) || this;\n }\n\n var _proto = Lifecycle.prototype;\n\n _proto.componentDidMount = function componentDidMount() {\n if (this.props.onMount) this.props.onMount.call(this, this);\n };\n\n _proto.componentDidUpdate = function componentDidUpdate(prevProps) {\n if (this.props.onUpdate) this.props.onUpdate.call(this, this, prevProps);\n };\n\n _proto.componentWillUnmount = function componentWillUnmount() {\n if (this.props.onUnmount) this.props.onUnmount.call(this, this);\n };\n\n _proto.render = function render() {\n return null;\n };\n\n return Lifecycle;\n}(react__WEBPACK_IMPORTED_MODULE_1___default.a.Component);\n\n/**\n * The public API for prompting the user before navigating away from a screen.\n */\n\nfunction Prompt(_ref) {\n var message = _ref.message,\n _ref$when = _ref.when,\n when = _ref$when === void 0 ? true : _ref$when;\n return react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(context.Consumer, null, function (context) {\n !context ? true ? Object(tiny_invariant__WEBPACK_IMPORTED_MODULE_6__[\"default\"])(false, \"You should not use <Prompt> outside a <Router>\") : undefined : void 0;\n if (!when || context.staticContext) return null;\n var method = context.history.block;\n return react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(Lifecycle, {\n onMount: function onMount(self) {\n self.release = method(message);\n },\n onUpdate: function onUpdate(self, prevProps) {\n if (prevProps.message !== message) {\n self.release();\n self.release = method(message);\n }\n },\n onUnmount: function onUnmount(self) {\n self.release();\n },\n message: message\n });\n });\n}\n\nif (true) {\n var messageType = prop_types__WEBPACK_IMPORTED_MODULE_2___default.a.oneOfType([prop_types__WEBPACK_IMPORTED_MODULE_2___default.a.func, prop_types__WEBPACK_IMPORTED_MODULE_2___default.a.string]);\n Prompt.propTypes = {\n when: prop_types__WEBPACK_IMPORTED_MODULE_2___default.a.bool,\n message: messageType.isRequired\n };\n}\n\nvar cache = {};\nvar cacheLimit = 10000;\nvar cacheCount = 0;\n\nfunction compilePath(path) {\n if (cache[path]) return cache[path];\n var generator = path_to_regexp__WEBPACK_IMPORTED_MODULE_8___default.a.compile(path);\n\n if (cacheCount < cacheLimit) {\n cache[path] = generator;\n cacheCount++;\n }\n\n return generator;\n}\n/**\n * Public API for generating a URL pathname from a path and parameters.\n */\n\n\nfunction generatePath(path, params) {\n if (path === void 0) {\n path = \"/\";\n }\n\n if (params === void 0) {\n params = {};\n }\n\n return path === \"/\" ? path : compilePath(path)(params, {\n pretty: true\n });\n}\n\n/**\n * The public API for navigating programmatically with a component.\n */\n\nfunction Redirect(_ref) {\n var computedMatch = _ref.computedMatch,\n to = _ref.to,\n _ref$push = _ref.push,\n push = _ref$push === void 0 ? false : _ref$push;\n return react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(context.Consumer, null, function (context) {\n !context ? true ? Object(tiny_invariant__WEBPACK_IMPORTED_MODULE_6__[\"default\"])(false, \"You should not use <Redirect> outside a <Router>\") : undefined : void 0;\n var history = context.history,\n staticContext = context.staticContext;\n var method = push ? history.push : history.replace;\n var location = Object(history__WEBPACK_IMPORTED_MODULE_3__[\"createLocation\"])(computedMatch ? typeof to === \"string\" ? generatePath(to, computedMatch.params) : Object(_babel_runtime_helpers_esm_extends__WEBPACK_IMPORTED_MODULE_7__[\"default\"])({}, to, {\n pathname: generatePath(to.pathname, computedMatch.params)\n }) : to); // When rendering in a static context,\n // set the new location immediately.\n\n if (staticContext) {\n method(location);\n return null;\n }\n\n return react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(Lifecycle, {\n onMount: function onMount() {\n method(location);\n },\n onUpdate: function onUpdate(self, prevProps) {\n var prevLocation = Object(history__WEBPACK_IMPORTED_MODULE_3__[\"createLocation\"])(prevProps.to);\n\n if (!Object(history__WEBPACK_IMPORTED_MODULE_3__[\"locationsAreEqual\"])(prevLocation, Object(_babel_runtime_helpers_esm_extends__WEBPACK_IMPORTED_MODULE_7__[\"default\"])({}, location, {\n key: prevLocation.key\n }))) {\n method(location);\n }\n },\n to: to\n });\n });\n}\n\nif (true) {\n Redirect.propTypes = {\n push: prop_types__WEBPACK_IMPORTED_MODULE_2___default.a.bool,\n from: prop_types__WEBPACK_IMPORTED_MODULE_2___default.a.string,\n to: prop_types__WEBPACK_IMPORTED_MODULE_2___default.a.oneOfType([prop_types__WEBPACK_IMPORTED_MODULE_2___default.a.string, prop_types__WEBPACK_IMPORTED_MODULE_2___default.a.object]).isRequired\n };\n}\n\nvar cache$1 = {};\nvar cacheLimit$1 = 10000;\nvar cacheCount$1 = 0;\n\nfunction compilePath$1(path, options) {\n var cacheKey = \"\" + options.end + options.strict + options.sensitive;\n var pathCache = cache$1[cacheKey] || (cache$1[cacheKey] = {});\n if (pathCache[path]) return pathCache[path];\n var keys = [];\n var regexp = path_to_regexp__WEBPACK_IMPORTED_MODULE_8___default()(path, keys, options);\n var result = {\n regexp: regexp,\n keys: keys\n };\n\n if (cacheCount$1 < cacheLimit$1) {\n pathCache[path] = result;\n cacheCount$1++;\n }\n\n return result;\n}\n/**\n * Public API for matching a URL pathname to a path.\n */\n\n\nfunction matchPath(pathname, options) {\n if (options === void 0) {\n options = {};\n }\n\n if (typeof options === \"string\" || Array.isArray(options)) {\n options = {\n path: options\n };\n }\n\n var _options = options,\n path = _options.path,\n _options$exact = _options.exact,\n exact = _options$exact === void 0 ? false : _options$exact,\n _options$strict = _options.strict,\n strict = _options$strict === void 0 ? false : _options$strict,\n _options$sensitive = _options.sensitive,\n sensitive = _options$sensitive === void 0 ? false : _options$sensitive;\n var paths = [].concat(path);\n return paths.reduce(function (matched, path) {\n if (!path && path !== \"\") return null;\n if (matched) return matched;\n\n var _compilePath = compilePath$1(path, {\n end: exact,\n strict: strict,\n sensitive: sensitive\n }),\n regexp = _compilePath.regexp,\n keys = _compilePath.keys;\n\n var match = regexp.exec(pathname);\n if (!match) return null;\n var url = match[0],\n values = match.slice(1);\n var isExact = pathname === url;\n if (exact && !isExact) return null;\n return {\n path: path,\n // the path used to match\n url: path === \"/\" && url === \"\" ? \"/\" : url,\n // the matched portion of the URL\n isExact: isExact,\n // whether or not we matched exactly\n params: keys.reduce(function (memo, key, index) {\n memo[key.name] = values[index];\n return memo;\n }, {})\n };\n }, null);\n}\n\nfunction isEmptyChildren(children) {\n return react__WEBPACK_IMPORTED_MODULE_1___default.a.Children.count(children) === 0;\n}\n\nfunction evalChildrenDev(children, props, path) {\n var value = children(props);\n true ? Object(tiny_warning__WEBPACK_IMPORTED_MODULE_4__[\"default\"])(value !== undefined, \"You returned `undefined` from the `children` function of \" + (\"<Route\" + (path ? \" path=\\\"\" + path + \"\\\"\" : \"\") + \">, but you \") + \"should have returned a React element or `null`\") : undefined;\n return value || null;\n}\n/**\n * The public API for matching a single path and rendering.\n */\n\n\nvar Route =\n/*#__PURE__*/\nfunction (_React$Component) {\n Object(_babel_runtime_helpers_esm_inheritsLoose__WEBPACK_IMPORTED_MODULE_0__[\"default\"])(Route, _React$Component);\n\n function Route() {\n return _React$Component.apply(this, arguments) || this;\n }\n\n var _proto = Route.prototype;\n\n _proto.render = function render() {\n var _this = this;\n\n return react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(context.Consumer, null, function (context$1) {\n !context$1 ? true ? Object(tiny_invariant__WEBPACK_IMPORTED_MODULE_6__[\"default\"])(false, \"You should not use <Route> outside a <Router>\") : undefined : void 0;\n var location = _this.props.location || context$1.location;\n var match = _this.props.computedMatch ? _this.props.computedMatch // <Switch> already computed the match for us\n : _this.props.path ? matchPath(location.pathname, _this.props) : context$1.match;\n\n var props = Object(_babel_runtime_helpers_esm_extends__WEBPACK_IMPORTED_MODULE_7__[\"default\"])({}, context$1, {\n location: location,\n match: match\n });\n\n var _this$props = _this.props,\n children = _this$props.children,\n component = _this$props.component,\n render = _this$props.render; // Preact uses an empty array as children by\n // default, so use null if that's the case.\n\n if (Array.isArray(children) && children.length === 0) {\n children = null;\n }\n\n return react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(context.Provider, {\n value: props\n }, props.match ? children ? typeof children === \"function\" ? true ? evalChildrenDev(children, props, _this.props.path) : undefined : children : component ? react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(component, props) : render ? render(props) : null : typeof children === \"function\" ? true ? evalChildrenDev(children, props, _this.props.path) : undefined : null);\n });\n };\n\n return Route;\n}(react__WEBPACK_IMPORTED_MODULE_1___default.a.Component);\n\nif (true) {\n Route.propTypes = {\n children: prop_types__WEBPACK_IMPORTED_MODULE_2___default.a.oneOfType([prop_types__WEBPACK_IMPORTED_MODULE_2___default.a.func, prop_types__WEBPACK_IMPORTED_MODULE_2___default.a.node]),\n component: function component(props, propName) {\n if (props[propName] && !Object(react_is__WEBPACK_IMPORTED_MODULE_9__[\"isValidElementType\"])(props[propName])) {\n return new Error(\"Invalid prop 'component' supplied to 'Route': the prop is not a valid React component\");\n }\n },\n exact: prop_types__WEBPACK_IMPORTED_MODULE_2___default.a.bool,\n location: prop_types__WEBPACK_IMPORTED_MODULE_2___default.a.object,\n path: prop_types__WEBPACK_IMPORTED_MODULE_2___default.a.oneOfType([prop_types__WEBPACK_IMPORTED_MODULE_2___default.a.string, prop_types__WEBPACK_IMPORTED_MODULE_2___default.a.arrayOf(prop_types__WEBPACK_IMPORTED_MODULE_2___default.a.string)]),\n render: prop_types__WEBPACK_IMPORTED_MODULE_2___default.a.func,\n sensitive: prop_types__WEBPACK_IMPORTED_MODULE_2___default.a.bool,\n strict: prop_types__WEBPACK_IMPORTED_MODULE_2___default.a.bool\n };\n\n Route.prototype.componentDidMount = function () {\n true ? Object(tiny_warning__WEBPACK_IMPORTED_MODULE_4__[\"default\"])(!(this.props.children && !isEmptyChildren(this.props.children) && this.props.component), \"You should not use <Route component> and <Route children> in the same route; <Route component> will be ignored\") : undefined;\n true ? Object(tiny_warning__WEBPACK_IMPORTED_MODULE_4__[\"default\"])(!(this.props.children && !isEmptyChildren(this.props.children) && this.props.render), \"You should not use <Route render> and <Route children> in the same route; <Route render> will be ignored\") : undefined;\n true ? Object(tiny_warning__WEBPACK_IMPORTED_MODULE_4__[\"default\"])(!(this.props.component && this.props.render), \"You should not use <Route component> and <Route render> in the same route; <Route render> will be ignored\") : undefined;\n };\n\n Route.prototype.componentDidUpdate = function (prevProps) {\n true ? Object(tiny_warning__WEBPACK_IMPORTED_MODULE_4__[\"default\"])(!(this.props.location && !prevProps.location), '<Route> elements should not change from uncontrolled to controlled (or vice versa). You initially used no \"location\" prop and then provided one on a subsequent render.') : undefined;\n true ? Object(tiny_warning__WEBPACK_IMPORTED_MODULE_4__[\"default\"])(!(!this.props.location && prevProps.location), '<Route> elements should not change from controlled to uncontrolled (or vice versa). You provided a \"location\" prop initially but omitted it on a subsequent render.') : undefined;\n };\n}\n\nfunction addLeadingSlash(path) {\n return path.charAt(0) === \"/\" ? path : \"/\" + path;\n}\n\nfunction addBasename(basename, location) {\n if (!basename) return location;\n return Object(_babel_runtime_helpers_esm_extends__WEBPACK_IMPORTED_MODULE_7__[\"default\"])({}, location, {\n pathname: addLeadingSlash(basename) + location.pathname\n });\n}\n\nfunction stripBasename(basename, location) {\n if (!basename) return location;\n var base = addLeadingSlash(basename);\n if (location.pathname.indexOf(base) !== 0) return location;\n return Object(_babel_runtime_helpers_esm_extends__WEBPACK_IMPORTED_MODULE_7__[\"default\"])({}, location, {\n pathname: location.pathname.substr(base.length)\n });\n}\n\nfunction createURL(location) {\n return typeof location === \"string\" ? location : Object(history__WEBPACK_IMPORTED_MODULE_3__[\"createPath\"])(location);\n}\n\nfunction staticHandler(methodName) {\n return function () {\n true ? Object(tiny_invariant__WEBPACK_IMPORTED_MODULE_6__[\"default\"])(false, \"You cannot %s with <StaticRouter>\", methodName) : undefined ;\n };\n}\n\nfunction noop() {}\n/**\n * The public top-level API for a \"static\" <Router>, so-called because it\n * can't actually change the current location. Instead, it just records\n * location changes in a context object. Useful mainly in testing and\n * server-rendering scenarios.\n */\n\n\nvar StaticRouter =\n/*#__PURE__*/\nfunction (_React$Component) {\n Object(_babel_runtime_helpers_esm_inheritsLoose__WEBPACK_IMPORTED_MODULE_0__[\"default\"])(StaticRouter, _React$Component);\n\n function StaticRouter() {\n var _this;\n\n for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {\n args[_key] = arguments[_key];\n }\n\n _this = _React$Component.call.apply(_React$Component, [this].concat(args)) || this;\n\n _this.handlePush = function (location) {\n return _this.navigateTo(location, \"PUSH\");\n };\n\n _this.handleReplace = function (location) {\n return _this.navigateTo(location, \"REPLACE\");\n };\n\n _this.handleListen = function () {\n return noop;\n };\n\n _this.handleBlock = function () {\n return noop;\n };\n\n return _this;\n }\n\n var _proto = StaticRouter.prototype;\n\n _proto.navigateTo = function navigateTo(location, action) {\n var _this$props = this.props,\n _this$props$basename = _this$props.basename,\n basename = _this$props$basename === void 0 ? \"\" : _this$props$basename,\n _this$props$context = _this$props.context,\n context = _this$props$context === void 0 ? {} : _this$props$context;\n context.action = action;\n context.location = addBasename(basename, Object(history__WEBPACK_IMPORTED_MODULE_3__[\"createLocation\"])(location));\n context.url = createURL(context.location);\n };\n\n _proto.render = function render() {\n var _this$props2 = this.props,\n _this$props2$basename = _this$props2.basename,\n basename = _this$props2$basename === void 0 ? \"\" : _this$props2$basename,\n _this$props2$context = _this$props2.context,\n context = _this$props2$context === void 0 ? {} : _this$props2$context,\n _this$props2$location = _this$props2.location,\n location = _this$props2$location === void 0 ? \"/\" : _this$props2$location,\n rest = Object(_babel_runtime_helpers_esm_objectWithoutPropertiesLoose__WEBPACK_IMPORTED_MODULE_10__[\"default\"])(_this$props2, [\"basename\", \"context\", \"location\"]);\n\n var history = {\n createHref: function createHref(path) {\n return addLeadingSlash(basename + createURL(path));\n },\n action: \"POP\",\n location: stripBasename(basename, Object(history__WEBPACK_IMPORTED_MODULE_3__[\"createLocation\"])(location)),\n push: this.handlePush,\n replace: this.handleReplace,\n go: staticHandler(\"go\"),\n goBack: staticHandler(\"goBack\"),\n goForward: staticHandler(\"goForward\"),\n listen: this.handleListen,\n block: this.handleBlock\n };\n return react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(Router, Object(_babel_runtime_helpers_esm_extends__WEBPACK_IMPORTED_MODULE_7__[\"default\"])({}, rest, {\n history: history,\n staticContext: context\n }));\n };\n\n return StaticRouter;\n}(react__WEBPACK_IMPORTED_MODULE_1___default.a.Component);\n\nif (true) {\n StaticRouter.propTypes = {\n basename: prop_types__WEBPACK_IMPORTED_MODULE_2___default.a.string,\n context: prop_types__WEBPACK_IMPORTED_MODULE_2___default.a.object,\n location: prop_types__WEBPACK_IMPORTED_MODULE_2___default.a.oneOfType([prop_types__WEBPACK_IMPORTED_MODULE_2___default.a.string, prop_types__WEBPACK_IMPORTED_MODULE_2___default.a.object])\n };\n\n StaticRouter.prototype.componentDidMount = function () {\n true ? Object(tiny_warning__WEBPACK_IMPORTED_MODULE_4__[\"default\"])(!this.props.history, \"<StaticRouter> ignores the history prop. To use a custom history, \" + \"use `import { Router }` instead of `import { StaticRouter as Router }`.\") : undefined;\n };\n}\n\n/**\n * The public API for rendering the first <Route> that matches.\n */\n\nvar Switch =\n/*#__PURE__*/\nfunction (_React$Component) {\n Object(_babel_runtime_helpers_esm_inheritsLoose__WEBPACK_IMPORTED_MODULE_0__[\"default\"])(Switch, _React$Component);\n\n function Switch() {\n return _React$Component.apply(this, arguments) || this;\n }\n\n var _proto = Switch.prototype;\n\n _proto.render = function render() {\n var _this = this;\n\n return react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(context.Consumer, null, function (context) {\n !context ? true ? Object(tiny_invariant__WEBPACK_IMPORTED_MODULE_6__[\"default\"])(false, \"You should not use <Switch> outside a <Router>\") : undefined : void 0;\n var location = _this.props.location || context.location;\n var element, match; // We use React.Children.forEach instead of React.Children.toArray().find()\n // here because toArray adds keys to all child elements and we do not want\n // to trigger an unmount/remount for two <Route>s that render the same\n // component at different URLs.\n\n react__WEBPACK_IMPORTED_MODULE_1___default.a.Children.forEach(_this.props.children, function (child) {\n if (match == null && react__WEBPACK_IMPORTED_MODULE_1___default.a.isValidElement(child)) {\n element = child;\n var path = child.props.path || child.props.from;\n match = path ? matchPath(location.pathname, Object(_babel_runtime_helpers_esm_extends__WEBPACK_IMPORTED_MODULE_7__[\"default\"])({}, child.props, {\n path: path\n })) : context.match;\n }\n });\n return match ? react__WEBPACK_IMPORTED_MODULE_1___default.a.cloneElement(element, {\n location: location,\n computedMatch: match\n }) : null;\n });\n };\n\n return Switch;\n}(react__WEBPACK_IMPORTED_MODULE_1___default.a.Component);\n\nif (true) {\n Switch.propTypes = {\n children: prop_types__WEBPACK_IMPORTED_MODULE_2___default.a.node,\n location: prop_types__WEBPACK_IMPORTED_MODULE_2___default.a.object\n };\n\n Switch.prototype.componentDidUpdate = function (prevProps) {\n true ? Object(tiny_warning__WEBPACK_IMPORTED_MODULE_4__[\"default\"])(!(this.props.location && !prevProps.location), '<Switch> elements should not change from uncontrolled to controlled (or vice versa). You initially used no \"location\" prop and then provided one on a subsequent render.') : undefined;\n true ? Object(tiny_warning__WEBPACK_IMPORTED_MODULE_4__[\"default\"])(!(!this.props.location && prevProps.location), '<Switch> elements should not change from controlled to uncontrolled (or vice versa). You provided a \"location\" prop initially but omitted it on a subsequent render.') : undefined;\n };\n}\n\n/**\n * A public higher-order component to access the imperative API\n */\n\nfunction withRouter(Component) {\n var displayName = \"withRouter(\" + (Component.displayName || Component.name) + \")\";\n\n var C = function C(props) {\n var wrappedComponentRef = props.wrappedComponentRef,\n remainingProps = Object(_babel_runtime_helpers_esm_objectWithoutPropertiesLoose__WEBPACK_IMPORTED_MODULE_10__[\"default\"])(props, [\"wrappedComponentRef\"]);\n\n return react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(context.Consumer, null, function (context) {\n !context ? true ? Object(tiny_invariant__WEBPACK_IMPORTED_MODULE_6__[\"default\"])(false, \"You should not use <\" + displayName + \" /> outside a <Router>\") : undefined : void 0;\n return react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(Component, Object(_babel_runtime_helpers_esm_extends__WEBPACK_IMPORTED_MODULE_7__[\"default\"])({}, remainingProps, context, {\n ref: wrappedComponentRef\n }));\n });\n };\n\n C.displayName = displayName;\n C.WrappedComponent = Component;\n\n if (true) {\n C.propTypes = {\n wrappedComponentRef: prop_types__WEBPACK_IMPORTED_MODULE_2___default.a.oneOfType([prop_types__WEBPACK_IMPORTED_MODULE_2___default.a.string, prop_types__WEBPACK_IMPORTED_MODULE_2___default.a.func, prop_types__WEBPACK_IMPORTED_MODULE_2___default.a.object])\n };\n }\n\n return hoist_non_react_statics__WEBPACK_IMPORTED_MODULE_11___default()(C, Component);\n}\n\nvar useContext = react__WEBPACK_IMPORTED_MODULE_1___default.a.useContext;\nfunction useHistory() {\n if (true) {\n !(typeof useContext === \"function\") ? true ? Object(tiny_invariant__WEBPACK_IMPORTED_MODULE_6__[\"default\"])(false, \"You must use React >= 16.8 in order to use useHistory()\") : undefined : void 0;\n }\n\n return useContext(context).history;\n}\nfunction useLocation() {\n if (true) {\n !(typeof useContext === \"function\") ? true ? Object(tiny_invariant__WEBPACK_IMPORTED_MODULE_6__[\"default\"])(false, \"You must use React >= 16.8 in order to use useLocation()\") : undefined : void 0;\n }\n\n return useContext(context).location;\n}\nfunction useParams() {\n if (true) {\n !(typeof useContext === \"function\") ? true ? Object(tiny_invariant__WEBPACK_IMPORTED_MODULE_6__[\"default\"])(false, \"You must use React >= 16.8 in order to use useParams()\") : undefined : void 0;\n }\n\n var match = useContext(context).match;\n return match ? match.params : {};\n}\nfunction useRouteMatch(path) {\n if (true) {\n !(typeof useContext === \"function\") ? true ? Object(tiny_invariant__WEBPACK_IMPORTED_MODULE_6__[\"default\"])(false, \"You must use React >= 16.8 in order to use useRouteMatch()\") : undefined : void 0;\n }\n\n return path ? matchPath(useLocation().pathname, path) : useContext(context).match;\n}\n\nif (true) {\n if (typeof window !== \"undefined\") {\n var global = window;\n var key = \"__react_router_build__\";\n var buildNames = {\n cjs: \"CommonJS\",\n esm: \"ES modules\",\n umd: \"UMD\"\n };\n\n if (global[key] && global[key] !== \"esm\") {\n var initialBuildName = buildNames[global[key]];\n var secondaryBuildName = buildNames[\"esm\"]; // TODO: Add link to article that explains in detail how to avoid\n // loading 2 different builds.\n\n throw new Error(\"You are loading the \" + secondaryBuildName + \" build of React Router \" + (\"on a page that is already running the \" + initialBuildName + \" \") + \"build, so things won't work right.\");\n }\n\n global[key] = \"esm\";\n }\n}\n\n\n//# sourceMappingURL=react-router.js.map\n\n\n//# sourceURL=webpack:///./node_modules/react-router/esm/react-router.js?");
/***/ }),
/***/ "./node_modules/react-router/node_modules/isarray/index.js":
/*!*****************************************************************!*\
!*** ./node_modules/react-router/node_modules/isarray/index.js ***!
\*****************************************************************/
/*! no static exports found */
/***/ (function(module, exports) {
eval("module.exports = Array.isArray || function (arr) {\n return Object.prototype.toString.call(arr) == '[object Array]';\n};\n\n\n//# sourceURL=webpack:///./node_modules/react-router/node_modules/isarray/index.js?");
/***/ }),
/***/ "./node_modules/react-router/node_modules/path-to-regexp/index.js":
/*!************************************************************************!*\
!*** ./node_modules/react-router/node_modules/path-to-regexp/index.js ***!
\************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
eval("var isarray = __webpack_require__(/*! isarray */ \"./node_modules/react-router/node_modules/isarray/index.js\")\n\n/**\n * Expose `pathToRegexp`.\n */\nmodule.exports = pathToRegexp\nmodule.exports.parse = parse\nmodule.exports.compile = compile\nmodule.exports.tokensToFunction = tokensToFunction\nmodule.exports.tokensToRegExp = tokensToRegExp\n\n/**\n * The main path matching regexp utility.\n *\n * @type {RegExp}\n */\nvar PATH_REGEXP = new RegExp([\n // Match escaped characters that would otherwise appear in future matches.\n // This allows the user to escape special characters that won't transform.\n '(\\\\\\\\.)',\n // Match Express-style parameters and un-named parameters with a prefix\n // and optional suffixes. Matches appear as:\n //\n // \"/:test(\\\\d+)?\" => [\"/\", \"test\", \"\\d+\", undefined, \"?\", undefined]\n // \"/route(\\\\d+)\" => [undefined, undefined, undefined, \"\\d+\", undefined, undefined]\n // \"/*\" => [\"/\", undefined, undefined, undefined, undefined, \"*\"]\n '([\\\\/.])?(?:(?:\\\\:(\\\\w+)(?:\\\\(((?:\\\\\\\\.|[^\\\\\\\\()])+)\\\\))?|\\\\(((?:\\\\\\\\.|[^\\\\\\\\()])+)\\\\))([+*?])?|(\\\\*))'\n].join('|'), 'g')\n\n/**\n * Parse a string for the raw tokens.\n *\n * @param {string} str\n * @param {Object=} options\n * @return {!Array}\n */\nfunction parse (str, options) {\n var tokens = []\n var key = 0\n var index = 0\n var path = ''\n var defaultDelimiter = options && options.delimiter || '/'\n var res\n\n while ((res = PATH_REGEXP.exec(str)) != null) {\n var m = res[0]\n var escaped = res[1]\n var offset = res.index\n path += str.slice(index, offset)\n index = offset + m.length\n\n // Ignore already escaped sequences.\n if (escaped) {\n path += escaped[1]\n continue\n }\n\n var next = str[index]\n var prefix = res[2]\n var name = res[3]\n var capture = res[4]\n var group = res[5]\n var modifier = res[6]\n var asterisk = res[7]\n\n // Push the current path onto the tokens.\n if (path) {\n tokens.push(path)\n path = ''\n }\n\n var partial = prefix != null && next != null && next !== prefix\n var repeat = modifier === '+' || modifier === '*'\n var optional = modifier === '?' || modifier === '*'\n var delimiter = res[2] || defaultDelimiter\n var pattern = capture || group\n\n tokens.push({\n name: name || key++,\n prefix: prefix || '',\n delimiter: delimiter,\n optional: optional,\n repeat: repeat,\n partial: partial,\n asterisk: !!asterisk,\n pattern: pattern ? escapeGroup(pattern) : (asterisk ? '.*' : '[^' + escapeString(delimiter) + ']+?')\n })\n }\n\n // Match any characters still remaining.\n if (index < str.length) {\n path += str.substr(index)\n }\n\n // If the path exists, push it onto the end.\n if (path) {\n tokens.push(path)\n }\n\n return tokens\n}\n\n/**\n * Compile a string to a template function for the path.\n *\n * @param {string} str\n * @param {Object=} options\n * @return {!function(Object=, Object=)}\n */\nfunction compile (str, options) {\n return tokensToFunction(parse(str, options), options)\n}\n\n/**\n * Prettier encoding of URI path segments.\n *\n * @param {string}\n * @return {string}\n */\nfunction encodeURIComponentPretty (str) {\n return encodeURI(str).replace(/[\\/?#]/g, function (c) {\n return '%' + c.charCodeAt(0).toString(16).toUpperCase()\n })\n}\n\n/**\n * Encode the asterisk parameter. Similar to `pretty`, but allows slashes.\n *\n * @param {string}\n * @return {string}\n */\nfunction encodeAsterisk (str) {\n return encodeURI(str).replace(/[?#]/g, function (c) {\n return '%' + c.charCodeAt(0).toString(16).toUpperCase()\n })\n}\n\n/**\n * Expose a method for transforming tokens into the path function.\n */\nfunction tokensToFunction (tokens, options) {\n // Compile all the tokens into regexps.\n var matches = new Array(tokens.length)\n\n // Compile all the patterns before compilation.\n for (var i = 0; i < tokens.length; i++) {\n if (typeof tokens[i] === 'object') {\n matches[i] = new RegExp('^(?:' + tokens[i].pattern + ')$', flags(options))\n }\n }\n\n return function (obj, opts) {\n var path = ''\n var data = obj || {}\n var options = opts || {}\n var encode = options.pretty ? encodeURIComponentPretty : encodeURIComponent\n\n for (var i = 0; i < tokens.length; i++) {\n var token = tokens[i]\n\n if (typeof token === 'string') {\n path += token\n\n continue\n }\n\n var value = data[token.name]\n var segment\n\n if (value == null) {\n if (token.optional) {\n // Prepend partial segment prefixes.\n if (token.partial) {\n path += token.prefix\n }\n\n continue\n } else {\n throw new TypeError('Expected \"' + token.name + '\" to be defined')\n }\n }\n\n if (isarray(value)) {\n if (!token.repeat) {\n throw new TypeError('Expected \"' + token.name + '\" to not repeat, but received `' + JSON.stringify(value) + '`')\n }\n\n if (value.length === 0) {\n if (token.optional) {\n continue\n } else {\n throw new TypeError('Expected \"' + token.name + '\" to not be empty')\n }\n }\n\n for (var j = 0; j < value.length; j++) {\n segment = encode(value[j])\n\n if (!matches[i].test(segment)) {\n throw new TypeError('Expected all \"' + token.name + '\" to match \"' + token.pattern + '\", but received `' + JSON.stringify(segment) + '`')\n }\n\n path += (j === 0 ? token.prefix : token.delimiter) + segment\n }\n\n continue\n }\n\n segment = token.asterisk ? encodeAsterisk(value) : encode(value)\n\n if (!matches[i].test(segment)) {\n throw new TypeError('Expected \"' + token.name + '\" to match \"' + token.pattern + '\", but received \"' + segment + '\"')\n }\n\n path += token.prefix + segment\n }\n\n return path\n }\n}\n\n/**\n * Escape a regular expression string.\n *\n * @param {string} str\n * @return {string}\n */\nfunction escapeString (str) {\n return str.replace(/([.+*?=^!:${}()[\\]|\\/\\\\])/g, '\\\\$1')\n}\n\n/**\n * Escape the capturing group by escaping special characters and meaning.\n *\n * @param {string} group\n * @return {string}\n */\nfunction escapeGroup (group) {\n return group.replace(/([=!:$\\/()])/g, '\\\\$1')\n}\n\n/**\n * Attach the keys as a property of the regexp.\n *\n * @param {!RegExp} re\n * @param {Array} keys\n * @return {!RegExp}\n */\nfunction attachKeys (re, keys) {\n re.keys = keys\n return re\n}\n\n/**\n * Get the flags for a regexp from the options.\n *\n * @param {Object} options\n * @return {string}\n */\nfunction flags (options) {\n return options && options.sensitive ? '' : 'i'\n}\n\n/**\n * Pull out keys from a regexp.\n *\n * @param {!RegExp} path\n * @param {!Array} keys\n * @return {!RegExp}\n */\nfunction regexpToRegexp (path, keys) {\n // Use a negative lookahead to match only capturing groups.\n var groups = path.source.match(/\\((?!\\?)/g)\n\n if (groups) {\n for (var i = 0; i < groups.length; i++) {\n keys.push({\n name: i,\n prefix: null,\n delimiter: null,\n optional: false,\n repeat: false,\n partial: false,\n asterisk: false,\n pattern: null\n })\n }\n }\n\n return attachKeys(path, keys)\n}\n\n/**\n * Transform an array into a regexp.\n *\n * @param {!Array} path\n * @param {Array} keys\n * @param {!Object} options\n * @return {!RegExp}\n */\nfunction arrayToRegexp (path, keys, options) {\n var parts = []\n\n for (var i = 0; i < path.length; i++) {\n parts.push(pathToRegexp(path[i], keys, options).source)\n }\n\n var regexp = new RegExp('(?:' + parts.join('|') + ')', flags(options))\n\n return attachKeys(regexp, keys)\n}\n\n/**\n * Create a path regexp from string input.\n *\n * @param {string} path\n * @param {!Array} keys\n * @param {!Object} options\n * @return {!RegExp}\n */\nfunction stringToRegexp (path, keys, options) {\n return tokensToRegExp(parse(path, options), keys, options)\n}\n\n/**\n * Expose a function for taking tokens and returning a RegExp.\n *\n * @param {!Array} tokens\n * @param {(Array|Object)=} keys\n * @param {Object=} options\n * @return {!RegExp}\n */\nfunction tokensToRegExp (tokens, keys, options) {\n if (!isarray(keys)) {\n options = /** @type {!Object} */ (keys || options)\n keys = []\n }\n\n options = options || {}\n\n var strict = options.strict\n var end = options.end !== false\n var route = ''\n\n // Iterate over the tokens and create our regexp string.\n for (var i = 0; i < tokens.length; i++) {\n var token = tokens[i]\n\n if (typeof token === 'string') {\n route += escapeString(token)\n } else {\n var prefix = escapeString(token.prefix)\n var capture = '(?:' + token.pattern + ')'\n\n keys.push(token)\n\n if (token.repeat) {\n capture += '(?:' + prefix + capture + ')*'\n }\n\n if (token.optional) {\n if (!token.partial) {\n capture = '(?:' + prefix + '(' + capture + '))?'\n } else {\n capture = prefix + '(' + capture + ')?'\n }\n } else {\n capture = prefix + '(' + capture + ')'\n }\n\n route += capture\n }\n }\n\n var delimiter = escapeString(options.delimiter || '/')\n var endsWithDelimiter = route.slice(-delimiter.length) === delimiter\n\n // In non-strict mode we allow a slash at the end of match. If the path to\n // match already ends with a slash, we remove it for consistency. The slash\n // is valid at the end of a path match, not in the middle. This is important\n // in non-ending mode, where \"/test/\" shouldn't match \"/test//route\".\n if (!strict) {\n route = (endsWithDelimiter ? route.slice(0, -delimiter.length) : route) + '(?:' + delimiter + '(?=$))?'\n }\n\n if (end) {\n route += '$'\n } else {\n // In non-ending mode, we need the capturing groups to match as much as\n // possible by using a positive lookahead to the end or next path segment.\n route += strict && endsWithDelimiter ? '' : '(?=' + delimiter + '|$)'\n }\n\n return attachKeys(new RegExp('^' + route, flags(options)), keys)\n}\n\n/**\n * Normalize the given path string, returning a regular expression.\n *\n * An empty array can be passed in for the keys, which will hold the\n * placeholder key descriptions. For example, using `/user/:id`, `keys` will\n * contain `[{ name: 'id', delimiter: '/', optional: false, repeat: false }]`.\n *\n * @param {(string|RegExp|Array)} path\n * @param {(Array|Object)=} keys\n * @param {Object=} options\n * @return {!RegExp}\n */\nfunction pathToRegexp (path, keys, options) {\n if (!isarray(keys)) {\n options = /** @type {!Object} */ (keys || options)\n keys = []\n }\n\n options = options || {}\n\n if (path instanceof RegExp) {\n return regexpToRegexp(path, /** @type {!Array} */ (keys))\n }\n\n if (isarray(path)) {\n return arrayToRegexp(/** @type {!Array} */ (path), /** @type {!Array} */ (keys), options)\n }\n\n return stringToRegexp(/** @type {string} */ (path), /** @type {!Array} */ (keys), options)\n}\n\n\n//# sourceURL=webpack:///./node_modules/react-router/node_modules/path-to-regexp/index.js?");
/***/ }),
/***/ "./node_modules/react-validation/build/button.js":
/*!*******************************************************!*\
!*** ./node_modules/react-validation/build/button.js ***!
\*******************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
eval("!function(e,t){ true?module.exports=t(__webpack_require__(/*! react */ \"./node_modules/react/index.js\"),__webpack_require__(/*! prop-types */ \"./node_modules/prop-types/index.js\")):undefined}(this,function(e,t){return function(e){function t(n){if(r[n])return r[n].exports;var o=r[n]={i:n,l:!1,exports:{}};return e[n].call(o.exports,o,o.exports,t),o.l=!0,o.exports}var r={};return t.m=e,t.c=r,t.d=function(e,r,n){t.o(e,r)||Object.defineProperty(e,r,{configurable:!1,enumerable:!0,get:n})},t.n=function(e){var r=e&&e.__esModule?function(){return e.default}:function(){return e};return t.d(r,\"a\",r),r},t.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},t.p=\"/\",t(t.s=15)}({0:function(t,r){t.exports=e},1:function(e,r){e.exports=t},15:function(e,t,r){\"use strict\";function n(e,t){var r={};for(var n in e)t.indexOf(n)>=0||Object.prototype.hasOwnProperty.call(e,n)&&(r[n]=e[n]);return r}Object.defineProperty(t,\"__esModule\",{value:!0});var o=r(0),u=r.n(o),a=r(1),c=r.n(a),i=r(9),s=function(e){var t=e.hasErrors,r=n(e,[\"hasErrors\"]);return u.a.createElement(\"button\",Object.assign({},r,{disabled:t}))};s.contextTypes={hasErrors:c.a.bool},t.default=Object(i.a)(s)},9:function(e,t,r){\"use strict\";function n(e,t){if(!(e instanceof t))throw new TypeError(\"Cannot call a class as a function\")}function o(e,t){if(!e)throw new ReferenceError(\"this hasn't been initialised - super() hasn't been called\");return!t||\"object\"!==typeof t&&\"function\"!==typeof t?e:t}function u(e,t){if(\"function\"!==typeof t&&null!==t)throw new TypeError(\"Super expression must either be null or a function, not \"+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}function a(e){var t,r;return r=t=function(t){function r(){return n(this,r),o(this,(r.__proto__||Object.getPrototypeOf(r)).apply(this,arguments))}return u(r,t),f(r,[{key:\"shouldComponentUpdate\",value:function(e,t,r){return r._errors!==this.context._errors}},{key:\"render\",value:function(){var t=!!Object.keys(this.context._errors).length;return i.a.createElement(e,Object.assign({},this.props,{hasErrors:t}))}}]),r}(c.Component),t.contextTypes={_errors:p.a.arrayOf(p.a.oneOfType([p.a.object,p.a.string]))},t.displayName=\"Button(\"+e.name+\")\",r}t.a=a;var c=r(0),i=r.n(c),s=r(1),p=r.n(s),f=function(){function e(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,\"value\"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}}return function(t,r,n){return r&&e(t.prototype,r),n&&e(t,n),t}}()}})});\n//# sourceMappingURL=button.js.map\n\n//# sourceURL=webpack:///./node_modules/react-validation/build/button.js?");
/***/ }),
/***/ "./node_modules/react-validation/build/form.js":
/*!*****************************************************!*\
!*** ./node_modules/react-validation/build/form.js ***!
\*****************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
eval("!function(e,t){ true?module.exports=t(__webpack_require__(/*! react */ \"./node_modules/react/index.js\"),__webpack_require__(/*! prop-types */ \"./node_modules/prop-types/index.js\"),__webpack_require__(/*! lodash.omit */ \"./node_modules/lodash.omit/index.js\")):undefined}(this,function(e,t,r){return function(e){function t(n){if(r[n])return r[n].exports;var a=r[n]={i:n,l:!1,exports:{}};return e[n].call(a.exports,a,a.exports,t),a.l=!0,a.exports}var r={};return t.m=e,t.c=r,t.d=function(e,r,n){t.o(e,r)||Object.defineProperty(e,r,{configurable:!1,enumerable:!0,get:n})},t.n=function(e){var r=e&&e.__esModule?function(){return e.default}:function(){return e};return t.d(r,\"a\",r),r},t.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},t.p=\"/\",t(t.s=11)}([function(t,r){t.exports=e},function(e,r){e.exports=t},,,,,,function(e,t,r){\"use strict\";function n(e,t){var r={};for(var n in e)t.indexOf(n)>=0||Object.prototype.hasOwnProperty.call(e,n)&&(r[n]=e[n]);return r}function a(e,t,r){return t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function i(e){if(Array.isArray(e)){for(var t=0,r=Array(e.length);t<e.length;t++)r[t]=e[t];return r}return Array.from(e)}function o(e,t){if(!(e instanceof t))throw new TypeError(\"Cannot call a class as a function\")}function s(e,t){if(!e)throw new ReferenceError(\"this hasn't been initialised - super() hasn't been called\");return!t||\"object\"!==typeof t&&\"function\"!==typeof t?e:t}function u(e,t){if(\"function\"!==typeof t&&null!==t)throw new TypeError(\"Super expression must either be null or a function, not \"+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}function c(e){var t,r,c;return r=t=function(t){function r(e,t){o(this,r);var n=s(this,(r.__proto__||Object.getPrototypeOf(r)).call(this,e,t));return c.call(n),n.state={byName:{},byId:{}},n}return u(r,t),h(r,[{key:\"getChildContext\",value:function(){var e=this;return{_register:this._register,_unregister:this._unregister,_setProps:this._setProps,_handleChange:this._handleChange,_handleBlur:this._handleBlur,_getProps:this._getProps,_errors:Object.keys(this.state.byId).filter(function(t){return e.state.byId[t].error})}}},{key:\"render\",value:function(){return l.a.createElement(e,Object.assign({},this.props,{validate:this.validate,validateAll:this.validateAll,getValues:this.getValues,showError:this.showError,hideError:this.hideError}))}}]),r}(f.PureComponent),t.displayName=\"Form(\"+e.name+\")\",t.propTypes={},t.childContextTypes={_register:b.a.func.isRequired,_unregister:b.a.func.isRequired,_setProps:b.a.func.isRequired,_handleChange:b.a.func.isRequired,_handleBlur:b.a.func.isRequired,_getProps:b.a.func.isRequired,_errors:b.a.array},c=function(){var e=this;this._register=function(t,r){e.setState(function(e){return{byName:Object.assign({},e.byName,a({},t.props.name,[].concat(i(e.byName[t.props.name]||[]),[r]))),byId:Object.assign({},e.byId,a({},r,Object.assign({},t.props,{isCheckable:g(t),value:t.props.value||\"\"},g(t)?{checked:!!t.props.checked}:{})))}},e._setErrors)},this._unregister=function(t,r){var n=[].concat(i(e.state.byName[t.props.name]));n.splice(n.indexOf(r),1);var o=n.length?Object.assign({},e.state.byName,a({},t.props.name,n)):y()(e.state.byName,t.props.name);e.setState({byName:o,byId:y()(e.state.byId,r)})},this._getProps=function(t){if(e.state.byId[t]){var r=e.state.byId[t];r.validations,r.isCheckable;return n(r,[\"validations\",\"isCheckable\"])}},this._setProps=function(t,r){e.setState(function(e){return{byId:Object.assign({},e.byId,a({},r,Object.assign({},e.byId[r],t)))}},e._setErrors)},this._handleChange=function(t,r){var n=e.state.byId[r].isCheckable;e.setState({byId:Object.assign({},e.state.byId,n?Object.assign({},e.state.byName[e.state.byId[r].name].reduce(function(t,r){return t[r]=Object.assign({},e.state.byId[r],{checked:!1}),t},{})):{},a({},r,Object.assign({},e.state.byId[r],{isChanged:!0,value:t.target.value},n&&{checked:t.target.checked})))},e._setErrors)},this._handleBlur=function(t,r){e.setState({byId:Object.assign({},e.state.byId,a({},r,Object.assign({},e.state.byId[r],{isUsed:!0,value:t.target.value})))},e._setErrors)},this._setErrors=function(){e.setState(function(e){return{byId:Object.keys(e.byId).reduce(function(t,r){var n=e.byId[r].validations,a=e.byId[r],i=Object.keys(e.byName).reduce(function(t,r){return t[r]=e.byName[r].map(function(t){return e.byId[t]}),t},{}),o=a.value;t[r]=Object.assign({},e.byId[r]);var s=!0,u=!1,c=void 0;try{for(var f,l=n[Symbol.iterator]();!(s=(f=l.next()).done);s=!0){var d=f.value,b=d(o,a,i);if(b){t[r].error=b;break}delete t[r].error}}catch(e){u=!0,c=e}finally{try{!s&&l.return&&l.return()}finally{if(u)throw c}}return t},{})}})},this.getValues=function(){return Object.keys(e.state.byName).reduce(function(t,r){return e.state.byName[r].length>1?t[r]=e.state.byName[r].map(function(t){return e.state.byId[t].value}):t[r]=e.state.byId[e.state.byName[r][0]].value,t},{})},this.validate=function(t){e.setState(function(e){return{byId:Object.assign({},e.byId,e.byName[t].reduce(function(t,r){return t[r]=Object.assign({},e.byId[r],{isChanged:!0,isUsed:!0}),t},{}))}},e._setErrors)},this.validateAll=function(){e.setState(function(e){return{byId:Object.assign({},e.byId,Object.keys(e.byName).reduce(function(t,r){return e.byName[r].reduce(function(r,n){return t[n]=Object.assign({},e.byId[n],{isChanged:!0,isUsed:!0}),r},{}),t},{}))}},e._setErrors)},this.showError=function(t,r){t&&setTimeout(function(){e.setState({byId:Object.assign({},e.state.byId,a({},t.id,Object.assign({},e.state.byId[t.id],{isChanged:!0,isUsed:!0,error:r})))})},0)},this.hideError=function(t){e.setState(function(e){return{byId:Object.assign({},e.byId,a({},t.id,Object.assign({},y()(e.byId[t.id],\"error\"),{isChanged:!1,isUsed:!1})))}})}},r}t.a=c;var f=r(0),l=r.n(f),d=r(1),b=r.n(d),p=r(8),y=r.n(p),h=function(){function e(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,\"value\"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}}return function(t,r,n){return r&&e(t.prototype,r),n&&e(t,n),t}}(),g=function(e){return\"radio\"===e.props.type||\"checkbox\"===e.props.type}},function(e,t){e.exports=r},,,function(e,t,r){\"use strict\";function n(e,t){var r={};for(var n in e)t.indexOf(n)>=0||Object.prototype.hasOwnProperty.call(e,n)&&(r[n]=e[n]);return r}function a(e,t){if(!(e instanceof t))throw new TypeError(\"Cannot call a class as a function\")}function i(e,t){if(!e)throw new ReferenceError(\"this hasn't been initialised - super() hasn't been called\");return!t||\"object\"!==typeof t&&\"function\"!==typeof t?e:t}function o(e,t){if(\"function\"!==typeof t&&null!==t)throw new TypeError(\"Super expression must either be null or a function, not \"+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}Object.defineProperty(t,\"__esModule\",{value:!0});var s=r(0),u=r.n(s),c=r(1),f=r.n(c),l=r(7),d=function(){function e(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,\"value\"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}}return function(t,r,n){return r&&e(t.prototype,r),n&&e(t,n),t}}(),b=function(e){function t(){return a(this,t),i(this,(t.__proto__||Object.getPrototypeOf(t)).apply(this,arguments))}return o(t,e),d(t,[{key:\"render\",value:function(){var e=this.props,t=(e.getValues,e.validate,e.validateAll,e.showError,e.hideError,n(e,[\"getValues\",\"validate\",\"validateAll\",\"showError\",\"hideError\"]));return u.a.createElement(\"form\",t)}}]),t}(s.Component);b.propTypes={getValues:f.a.func.isRequired,validate:f.a.func.isRequired,validateAll:f.a.func.isRequired,showError:f.a.func.isRequired,hideError:f.a.func.isRequired},t.default=Object(l.a)(b)}])});\n//# sourceMappingURL=form.js.map\n\n//# sourceURL=webpack:///./node_modules/react-validation/build/form.js?");
/***/ }),
/***/ "./node_modules/react-validation/build/input.js":
/*!******************************************************!*\
!*** ./node_modules/react-validation/build/input.js ***!
\******************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
eval("!function(e,t){ true?module.exports=t(__webpack_require__(/*! react */ \"./node_modules/react/index.js\"),__webpack_require__(/*! prop-types */ \"./node_modules/prop-types/index.js\"),__webpack_require__(/*! uuid/v4 */ \"./node_modules/uuid/v4.js\")):undefined}(this,function(e,t,n){return function(e){function t(r){if(n[r])return n[r].exports;var o=n[r]={i:r,l:!1,exports:{}};return e[r].call(o.exports,o,o.exports,t),o.l=!0,o.exports}var n={};return t.m=e,t.c=n,t.d=function(e,n,r){t.o(e,n)||Object.defineProperty(e,n,{configurable:!1,enumerable:!0,get:r})},t.n=function(e){var n=e&&e.__esModule?function(){return e.default}:function(){return e};return t.d(n,\"a\",n),n},t.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},t.p=\"/\",t(t.s=12)}([function(t,n){t.exports=e},function(e,n){e.exports=t},function(e,t,n){\"use strict\";function r(e,t){if(!(e instanceof t))throw new TypeError(\"Cannot call a class as a function\")}function o(e,t){if(!e)throw new ReferenceError(\"this hasn't been initialised - super() hasn't been called\");return!t||\"object\"!==typeof t&&\"function\"!==typeof t?e:t}function i(e,t){if(\"function\"!==typeof t&&null!==t)throw new TypeError(\"Super expression must either be null or a function, not \"+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}function u(e){var t,n;return n=t=function(t){function n(){return r(this,n),o(this,(n.__proto__||Object.getPrototypeOf(n)).apply(this,arguments))}return i(n,t),f(n,[{key:\"render\",value:function(){var t=this.context._getProps(this.id);return t?c.a.createElement(e,Object.assign({},t,{onChange:this.handleChange,onBlur:this.handleBlur})):null}}]),n}(s.a),t.displayName=\"Control(\"+e.name+\")\",n}t.a=u;var a=n(0),c=n.n(a),s=n(3),f=function(){function e(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,\"value\"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}return function(t,n,r){return n&&e(t.prototype,n),r&&e(t,r),t}}()},function(e,t,n){\"use strict\";function r(e,t){var n={};for(var r in e)t.indexOf(r)>=0||Object.prototype.hasOwnProperty.call(e,r)&&(n[r]=e[r]);return n}function o(e,t){if(!(e instanceof t))throw new TypeError(\"Cannot call a class as a function\")}function i(e,t){if(!e)throw new ReferenceError(\"this hasn't been initialised - super() hasn't been called\");return!t||\"object\"!==typeof t&&\"function\"!==typeof t?e:t}function u(e,t){if(\"function\"!==typeof t&&null!==t)throw new TypeError(\"Super expression must either be null or a function, not \"+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}var a=n(0),c=(n.n(a),n(1)),s=n.n(c),f=n(4),p=n.n(f),l=n(5),d=n.n(l),h=n(6),y=n.n(h),v=function(){function e(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,\"value\"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}return function(t,n,r){return n&&e(t.prototype,n),r&&e(t,r),t}}(),b=function(e){function t(){var e,n,r,u;o(this,t);for(var a=arguments.length,c=Array(a),s=0;s<a;s++)c[s]=arguments[s];return n=r=i(this,(e=t.__proto__||Object.getPrototypeOf(t)).call.apply(e,[this].concat(c))),r.id=y()(),r.handleChange=function(e){e.persist(),r.context._handleChange(e,r.id),r.props.onChange&&r.props.onChange(e)},r.handleBlur=function(e){e.persist(),r.context._handleBlur(e,r.id),r.props.onBlur&&r.props.onBlur(e)},u=n,i(r,u)}return u(t,e),v(t,[{key:\"componentDidMount\",value:function(){this.context._register(this,this.id)}},{key:\"componentWillUnmount\",value:function(){this.context._unregister(this,this.id)}},{key:\"componentWillReceiveProps\",value:function(e){var t=e.validations,n=r(e,[\"validations\"]),o=this.props,i=o.validations,u=r(o,[\"validations\"]);d()(u,n)&&p()(i,t)||this.context._setProps(n,this.id)}},{key:\"shouldComponentUpdate\",value:function(e,t,n){return n!==this.context}},{key:\"render\",value:function(){return null}}]),t}(a.Component);b.contextTypes={_register:s.a.func.isRequired,_unregister:s.a.func.isRequired,_setProps:s.a.func.isRequired,_handleChange:s.a.func.isRequired,_handleBlur:s.a.func.isRequired,_getProps:s.a.func.isRequired},b.propTypes={validations:s.a.arrayOf(s.a.func),onChange:s.a.func,onBlur:s.a.func},b.defaultProps={validations:[]},t.a=b},function(e,t){e.exports=function(e,t){if(e===t)return!0;var n=e.length;if(t.length!==n)return!1;for(var r=0;r<n;r++)if(e[r]!==t[r])return!1;return!0}},function(e,t){e.exports=function(e,t){if(e===t)return!0;var n=Object.keys(e),r=Object.keys(t),o=n.length;if(r.length!==o)return!1;for(var i=0;i<o;i++){var u=n[i];if(e[u]!==t[u])return!1}return!0}},function(e,t){e.exports=n},,,,,,function(e,t,n){\"use strict\";function r(e,t){var n={};for(var r in e)t.indexOf(r)>=0||Object.prototype.hasOwnProperty.call(e,r)&&(n[r]=e[r]);return n}Object.defineProperty(t,\"__esModule\",{value:!0});var o=n(0),i=n.n(o),u=n(1),a=n.n(u),c=n(2),s=function(e){var t=e.error,n=e.isChanged,o=e.isUsed,u=r(e,[\"error\",\"isChanged\",\"isUsed\"]);return i.a.createElement(\"div\",null,i.a.createElement(\"input\",Object.assign({},u,n&&o&&t?{className:\"is-invalid-input \"+u.className}:{className:u.className})),n&&o&&t)};s.propTypes={error:a.a.oneOfType([a.a.node,a.a.string])},t.default=Object(c.a)(s)}])});\n//# sourceMappingURL=input.js.map\n\n//# sourceURL=webpack:///./node_modules/react-validation/build/input.js?");
/***/ }),
/***/ "./node_modules/react/cjs/react.development.js":
/*!*****************************************************!*\
!*** ./node_modules/react/cjs/react.development.js ***!
\*****************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
eval("/** @license React v16.13.1\n * react.development.js\n *\n * Copyright (c) Facebook, Inc. and its affiliates.\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\n\n\n\nif (true) {\n (function() {\n'use strict';\n\nvar _assign = __webpack_require__(/*! object-assign */ \"./node_modules/object-assign/index.js\");\nvar checkPropTypes = __webpack_require__(/*! prop-types/checkPropTypes */ \"./node_modules/prop-types/checkPropTypes.js\");\n\nvar ReactVersion = '16.13.1';\n\n// The Symbol used to tag the ReactElement-like types. If there is no native Symbol\n// nor polyfill, then a plain number is used for performance.\nvar hasSymbol = typeof Symbol === 'function' && Symbol.for;\nvar REACT_ELEMENT_TYPE = hasSymbol ? Symbol.for('react.element') : 0xeac7;\nvar REACT_PORTAL_TYPE = hasSymbol ? Symbol.for('react.portal') : 0xeaca;\nvar REACT_FRAGMENT_TYPE = hasSymbol ? Symbol.for('react.fragment') : 0xeacb;\nvar REACT_STRICT_MODE_TYPE = hasSymbol ? Symbol.for('react.strict_mode') : 0xeacc;\nvar REACT_PROFILER_TYPE = hasSymbol ? Symbol.for('react.profiler') : 0xead2;\nvar REACT_PROVIDER_TYPE = hasSymbol ? Symbol.for('react.provider') : 0xeacd;\nvar REACT_CONTEXT_TYPE = hasSymbol ? Symbol.for('react.context') : 0xeace; // TODO: We don't use AsyncMode or ConcurrentMode anymore. They were temporary\nvar REACT_CONCURRENT_MODE_TYPE = hasSymbol ? Symbol.for('react.concurrent_mode') : 0xeacf;\nvar REACT_FORWARD_REF_TYPE = hasSymbol ? Symbol.for('react.forward_ref') : 0xead0;\nvar REACT_SUSPENSE_TYPE = hasSymbol ? Symbol.for('react.suspense') : 0xead1;\nvar REACT_SUSPENSE_LIST_TYPE = hasSymbol ? Symbol.for('react.suspense_list') : 0xead8;\nvar REACT_MEMO_TYPE = hasSymbol ? Symbol.for('react.memo') : 0xead3;\nvar REACT_LAZY_TYPE = hasSymbol ? Symbol.for('react.lazy') : 0xead4;\nvar REACT_BLOCK_TYPE = hasSymbol ? Symbol.for('react.block') : 0xead9;\nvar REACT_FUNDAMENTAL_TYPE = hasSymbol ? Symbol.for('react.fundamental') : 0xead5;\nvar REACT_RESPONDER_TYPE = hasSymbol ? Symbol.for('react.responder') : 0xead6;\nvar REACT_SCOPE_TYPE = hasSymbol ? Symbol.for('react.scope') : 0xead7;\nvar MAYBE_ITERATOR_SYMBOL = typeof Symbol === 'function' && Symbol.iterator;\nvar FAUX_ITERATOR_SYMBOL = '@@iterator';\nfunction getIteratorFn(maybeIterable) {\n if (maybeIterable === null || typeof maybeIterable !== 'object') {\n return null;\n }\n\n var maybeIterator = MAYBE_ITERATOR_SYMBOL && maybeIterable[MAYBE_ITERATOR_SYMBOL] || maybeIterable[FAUX_ITERATOR_SYMBOL];\n\n if (typeof maybeIterator === 'function') {\n return maybeIterator;\n }\n\n return null;\n}\n\n/**\n * Keeps track of the current dispatcher.\n */\nvar ReactCurrentDispatcher = {\n /**\n * @internal\n * @type {ReactComponent}\n */\n current: null\n};\n\n/**\n * Keeps track of the current batch's configuration such as how long an update\n * should suspend for if it needs to.\n */\nvar ReactCurrentBatchConfig = {\n suspense: null\n};\n\n/**\n * Keeps track of the current owner.\n *\n * The current owner is the component who should own any components that are\n * currently being constructed.\n */\nvar ReactCurrentOwner = {\n /**\n * @internal\n * @type {ReactComponent}\n */\n current: null\n};\n\nvar BEFORE_SLASH_RE = /^(.*)[\\\\\\/]/;\nfunction describeComponentFrame (name, source, ownerName) {\n var sourceInfo = '';\n\n if (source) {\n var path = source.fileName;\n var fileName = path.replace(BEFORE_SLASH_RE, '');\n\n {\n // In DEV, include code for a common special case:\n // prefer \"folder/index.js\" instead of just \"index.js\".\n if (/^index\\./.test(fileName)) {\n var match = path.match(BEFORE_SLASH_RE);\n\n if (match) {\n var pathBeforeSlash = match[1];\n\n if (pathBeforeSlash) {\n var folderName = pathBeforeSlash.replace(BEFORE_SLASH_RE, '');\n fileName = folderName + '/' + fileName;\n }\n }\n }\n }\n\n sourceInfo = ' (at ' + fileName + ':' + source.lineNumber + ')';\n } else if (ownerName) {\n sourceInfo = ' (created by ' + ownerName + ')';\n }\n\n return '\\n in ' + (name || 'Unknown') + sourceInfo;\n}\n\nvar Resolved = 1;\nfunction refineResolvedLazyComponent(lazyComponent) {\n return lazyComponent._status === Resolved ? lazyComponent._result : null;\n}\n\nfunction getWrappedName(outerType, innerType, wrapperName) {\n var functionName = innerType.displayName || innerType.name || '';\n return outerType.displayName || (functionName !== '' ? wrapperName + \"(\" + functionName + \")\" : wrapperName);\n}\n\nfunction getComponentName(type) {\n if (type == null) {\n // Host root, text node or just invalid type.\n return null;\n }\n\n {\n if (typeof type.tag === 'number') {\n error('Received an unexpected object in getComponentName(). ' + 'This is likely a bug in React. Please file an issue.');\n }\n }\n\n if (typeof type === 'function') {\n return type.displayName || type.name || null;\n }\n\n if (typeof type === 'string') {\n return type;\n }\n\n switch (type) {\n case REACT_FRAGMENT_TYPE:\n return 'Fragment';\n\n case REACT_PORTAL_TYPE:\n return 'Portal';\n\n case REACT_PROFILER_TYPE:\n return \"Profiler\";\n\n case REACT_STRICT_MODE_TYPE:\n return 'StrictMode';\n\n case REACT_SUSPENSE_TYPE:\n return 'Suspense';\n\n case REACT_SUSPENSE_LIST_TYPE:\n return 'SuspenseList';\n }\n\n if (typeof type === 'object') {\n switch (type.$$typeof) {\n case REACT_CONTEXT_TYPE:\n return 'Context.Consumer';\n\n case REACT_PROVIDER_TYPE:\n return 'Context.Provider';\n\n case REACT_FORWARD_REF_TYPE:\n return getWrappedName(type, type.render, 'ForwardRef');\n\n case REACT_MEMO_TYPE:\n return getComponentName(type.type);\n\n case REACT_BLOCK_TYPE:\n return getComponentName(type.render);\n\n case REACT_LAZY_TYPE:\n {\n var thenable = type;\n var resolvedThenable = refineResolvedLazyComponent(thenable);\n\n if (resolvedThenable) {\n return getComponentName(resolvedThenable);\n }\n\n break;\n }\n }\n }\n\n return null;\n}\n\nvar ReactDebugCurrentFrame = {};\nvar currentlyValidatingElement = null;\nfunction setCurrentlyValidatingElement(element) {\n {\n currentlyValidatingElement = element;\n }\n}\n\n{\n // Stack implementation injected by the current renderer.\n ReactDebugCurrentFrame.getCurrentStack = null;\n\n ReactDebugCurrentFrame.getStackAddendum = function () {\n var stack = ''; // Add an extra top frame while an element is being validated\n\n if (currentlyValidatingElement) {\n var name = getComponentName(currentlyValidatingElement.type);\n var owner = currentlyValidatingElement._owner;\n stack += describeComponentFrame(name, currentlyValidatingElement._source, owner && getComponentName(owner.type));\n } // Delegate to the injected renderer-specific implementation\n\n\n var impl = ReactDebugCurrentFrame.getCurrentStack;\n\n if (impl) {\n stack += impl() || '';\n }\n\n return stack;\n };\n}\n\n/**\n * Used by act() to track whether you're inside an act() scope.\n */\nvar IsSomeRendererActing = {\n current: false\n};\n\nvar ReactSharedInternals = {\n ReactCurrentDispatcher: ReactCurrentDispatcher,\n ReactCurrentBatchConfig: ReactCurrentBatchConfig,\n ReactCurrentOwner: ReactCurrentOwner,\n IsSomeRendererActing: IsSomeRendererActing,\n // Used by renderers to avoid bundling object-assign twice in UMD bundles:\n assign: _assign\n};\n\n{\n _assign(ReactSharedInternals, {\n // These should not be included in production.\n ReactDebugCurrentFrame: ReactDebugCurrentFrame,\n // Shim for React DOM 16.0.0 which still destructured (but not used) this.\n // TODO: remove in React 17.0.\n ReactComponentTreeHook: {}\n });\n}\n\n// by calls to these methods by a Babel plugin.\n//\n// In PROD (or in packages without access to React internals),\n// they are left as they are instead.\n\nfunction warn(format) {\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 printWarning('warn', format, args);\n }\n}\nfunction error(format) {\n {\n for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {\n args[_key2 - 1] = arguments[_key2];\n }\n\n printWarning('error', format, args);\n }\n}\n\nfunction printWarning(level, format, args) {\n // When changing this logic, you might want to also\n // update consoleWithStackDev.www.js as well.\n {\n var hasExistingStack = args.length > 0 && typeof args[args.length - 1] === 'string' && args[args.length - 1].indexOf('\\n in') === 0;\n\n if (!hasExistingStack) {\n var ReactDebugCurrentFrame = ReactSharedInternals.ReactDebugCurrentFrame;\n var stack = ReactDebugCurrentFrame.getStackAddendum();\n\n if (stack !== '') {\n format += '%s';\n args = args.concat([stack]);\n }\n }\n\n var argsWithFormat = args.map(function (item) {\n return '' + item;\n }); // Careful: RN currently depends on this prefix\n\n argsWithFormat.unshift('Warning: ' + format); // We intentionally don't use spread (or .apply) directly because it\n // breaks IE9: https://github.com/facebook/react/issues/13610\n // eslint-disable-next-line react-internal/no-production-logging\n\n Function.prototype.apply.call(console[level], console, argsWithFormat);\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 var argIndex = 0;\n var message = 'Warning: ' + format.replace(/%s/g, function () {\n return args[argIndex++];\n });\n throw new Error(message);\n } catch (x) {}\n }\n}\n\nvar didWarnStateUpdateForUnmountedComponent = {};\n\nfunction warnNoop(publicInstance, callerName) {\n {\n var _constructor = publicInstance.constructor;\n var componentName = _constructor && (_constructor.displayName || _constructor.name) || 'ReactClass';\n var warningKey = componentName + \".\" + callerName;\n\n if (didWarnStateUpdateForUnmountedComponent[warningKey]) {\n return;\n }\n\n error(\"Can't call %s on a component that is not yet mounted. \" + 'This is a no-op, but it might indicate a bug in your application. ' + 'Instead, assign to `this.state` directly or define a `state = {};` ' + 'class property with the desired state in the %s component.', callerName, componentName);\n\n didWarnStateUpdateForUnmountedComponent[warningKey] = true;\n }\n}\n/**\n * This is the abstract API for an update queue.\n */\n\n\nvar ReactNoopUpdateQueue = {\n /**\n * Checks whether or not this composite component is mounted.\n * @param {ReactClass} publicInstance The instance we want to test.\n * @return {boolean} True if mounted, false otherwise.\n * @protected\n * @final\n */\n isMounted: function (publicInstance) {\n return false;\n },\n\n /**\n * Forces an update. This should only be invoked when it is known with\n * certainty that we are **not** in a DOM transaction.\n *\n * You may want to call this when you know that some deeper aspect of the\n * component's state has changed but `setState` was not called.\n *\n * This will not invoke `shouldComponentUpdate`, but it will invoke\n * `componentWillUpdate` and `componentDidUpdate`.\n *\n * @param {ReactClass} publicInstance The instance that should rerender.\n * @param {?function} callback Called after component is updated.\n * @param {?string} callerName name of the calling function in the public API.\n * @internal\n */\n enqueueForceUpdate: function (publicInstance, callback, callerName) {\n warnNoop(publicInstance, 'forceUpdate');\n },\n\n /**\n * Replaces all of the state. Always use this or `setState` to mutate state.\n * You should treat `this.state` as immutable.\n *\n * There is no guarantee that `this.state` will be immediately updated, so\n * accessing `this.state` after calling this method may return the old value.\n *\n * @param {ReactClass} publicInstance The instance that should rerender.\n * @param {object} completeState Next state.\n * @param {?function} callback Called after component is updated.\n * @param {?string} callerName name of the calling function in the public API.\n * @internal\n */\n enqueueReplaceState: function (publicInstance, completeState, callback, callerName) {\n warnNoop(publicInstance, 'replaceState');\n },\n\n /**\n * Sets a subset of the state. This only exists because _pendingState is\n * internal. This provides a merging strategy that is not available to deep\n * properties which is confusing. TODO: Expose pendingState or don't use it\n * during the merge.\n *\n * @param {ReactClass} publicInstance The instance that should rerender.\n * @param {object} partialState Next partial state to be merged with state.\n * @param {?function} callback Called after component is updated.\n * @param {?string} Name of the calling function in the public API.\n * @internal\n */\n enqueueSetState: function (publicInstance, partialState, callback, callerName) {\n warnNoop(publicInstance, 'setState');\n }\n};\n\nvar emptyObject = {};\n\n{\n Object.freeze(emptyObject);\n}\n/**\n * Base class helpers for the updating state of a component.\n */\n\n\nfunction Component(props, context, updater) {\n this.props = props;\n this.context = context; // If a component has string refs, we will assign a different object later.\n\n this.refs = emptyObject; // We initialize the default updater but the real one gets injected by the\n // renderer.\n\n this.updater = updater || ReactNoopUpdateQueue;\n}\n\nComponent.prototype.isReactComponent = {};\n/**\n * Sets a subset of the state. Always use this to mutate\n * state. You should treat `this.state` as immutable.\n *\n * There is no guarantee that `this.state` will be immediately updated, so\n * accessing `this.state` after calling this method may return the old value.\n *\n * There is no guarantee that calls to `setState` will run synchronously,\n * as they may eventually be batched together. You can provide an optional\n * callback that will be executed when the call to setState is actually\n * completed.\n *\n * When a function is provided to setState, it will be called at some point in\n * the future (not synchronously). It will be called with the up to date\n * component arguments (state, props, context). These values can be different\n * from this.* because your function may be called after receiveProps but before\n * shouldComponentUpdate, and this new state, props, and context will not yet be\n * assigned to this.\n *\n * @param {object|function} partialState Next partial state or function to\n * produce next partial state to be merged with current state.\n * @param {?function} callback Called after state is updated.\n * @final\n * @protected\n */\n\nComponent.prototype.setState = function (partialState, callback) {\n if (!(typeof partialState === 'object' || typeof partialState === 'function' || partialState == null)) {\n {\n throw Error( \"setState(...): takes an object of state variables to update or a function which returns an object of state variables.\" );\n }\n }\n\n this.updater.enqueueSetState(this, partialState, callback, 'setState');\n};\n/**\n * Forces an update. This should only be invoked when it is known with\n * certainty that we are **not** in a DOM transaction.\n *\n * You may want to call this when you know that some deeper aspect of the\n * component's state has changed but `setState` was not called.\n *\n * This will not invoke `shouldComponentUpdate`, but it will invoke\n * `componentWillUpdate` and `componentDidUpdate`.\n *\n * @param {?function} callback Called after update is complete.\n * @final\n * @protected\n */\n\n\nComponent.prototype.forceUpdate = function (callback) {\n this.updater.enqueueForceUpdate(this, callback, 'forceUpdate');\n};\n/**\n * Deprecated APIs. These APIs used to exist on classic React classes but since\n * we would like to deprecate them, we're not going to move them over to this\n * modern base class. Instead, we define a getter that warns if it's accessed.\n */\n\n\n{\n var deprecatedAPIs = {\n isMounted: ['isMounted', 'Instead, make sure to clean up subscriptions and pending requests in ' + 'componentWillUnmount to prevent memory leaks.'],\n replaceState: ['replaceState', 'Refactor your code to use setState instead (see ' + 'https://github.com/facebook/react/issues/3236).']\n };\n\n var defineDeprecationWarning = function (methodName, info) {\n Object.defineProperty(Component.prototype, methodName, {\n get: function () {\n warn('%s(...) is deprecated in plain JavaScript React classes. %s', info[0], info[1]);\n\n return undefined;\n }\n });\n };\n\n for (var fnName in deprecatedAPIs) {\n if (deprecatedAPIs.hasOwnProperty(fnName)) {\n defineDeprecationWarning(fnName, deprecatedAPIs[fnName]);\n }\n }\n}\n\nfunction ComponentDummy() {}\n\nComponentDummy.prototype = Component.prototype;\n/**\n * Convenience component with default shallow equality check for sCU.\n */\n\nfunction PureComponent(props, context, updater) {\n this.props = props;\n this.context = context; // If a component has string refs, we will assign a different object later.\n\n this.refs = emptyObject;\n this.updater = updater || ReactNoopUpdateQueue;\n}\n\nvar pureComponentPrototype = PureComponent.prototype = new ComponentDummy();\npureComponentPrototype.constructor = PureComponent; // Avoid an extra prototype jump for these methods.\n\n_assign(pureComponentPrototype, Component.prototype);\n\npureComponentPrototype.isPureReactComponent = true;\n\n// an immutable object with a single mutable value\nfunction createRef() {\n var refObject = {\n current: null\n };\n\n {\n Object.seal(refObject);\n }\n\n return refObject;\n}\n\nvar hasOwnProperty = Object.prototype.hasOwnProperty;\nvar RESERVED_PROPS = {\n key: true,\n ref: true,\n __self: true,\n __source: true\n};\nvar specialPropKeyWarningShown, specialPropRefWarningShown, didWarnAboutStringRefs;\n\n{\n didWarnAboutStringRefs = {};\n}\n\nfunction hasValidRef(config) {\n {\n if (hasOwnProperty.call(config, 'ref')) {\n var getter = Object.getOwnPropertyDescriptor(config, 'ref').get;\n\n if (getter && getter.isReactWarning) {\n return false;\n }\n }\n }\n\n return config.ref !== undefined;\n}\n\nfunction hasValidKey(config) {\n {\n if (hasOwnProperty.call(config, 'key')) {\n var getter = Object.getOwnPropertyDescriptor(config, 'key').get;\n\n if (getter && getter.isReactWarning) {\n return false;\n }\n }\n }\n\n return config.key !== undefined;\n}\n\nfunction defineKeyPropWarningGetter(props, displayName) {\n var warnAboutAccessingKey = function () {\n {\n if (!specialPropKeyWarningShown) {\n specialPropKeyWarningShown = true;\n\n error('%s: `key` is not a prop. Trying to access it will result ' + 'in `undefined` being returned. If you need to access the same ' + 'value within the child component, you should pass it as a different ' + 'prop. (https://fb.me/react-special-props)', displayName);\n }\n }\n };\n\n warnAboutAccessingKey.isReactWarning = true;\n Object.defineProperty(props, 'key', {\n get: warnAboutAccessingKey,\n configurable: true\n });\n}\n\nfunction defineRefPropWarningGetter(props, displayName) {\n var warnAboutAccessingRef = function () {\n {\n if (!specialPropRefWarningShown) {\n specialPropRefWarningShown = true;\n\n error('%s: `ref` is not a prop. Trying to access it will result ' + 'in `undefined` being returned. If you need to access the same ' + 'value within the child component, you should pass it as a different ' + 'prop. (https://fb.me/react-special-props)', displayName);\n }\n }\n };\n\n warnAboutAccessingRef.isReactWarning = true;\n Object.defineProperty(props, 'ref', {\n get: warnAboutAccessingRef,\n configurable: true\n });\n}\n\nfunction warnIfStringRefCannotBeAutoConverted(config) {\n {\n if (typeof config.ref === 'string' && ReactCurrentOwner.current && config.__self && ReactCurrentOwner.current.stateNode !== config.__self) {\n var componentName = getComponentName(ReactCurrentOwner.current.type);\n\n if (!didWarnAboutStringRefs[componentName]) {\n error('Component \"%s\" contains the string ref \"%s\". ' + 'Support for string refs will be removed in a future major release. ' + 'This case cannot be automatically converted to an arrow function. ' + 'We ask you to manually fix this case by using useRef() or createRef() instead. ' + 'Learn more about using refs safely here: ' + 'https://fb.me/react-strict-mode-string-ref', getComponentName(ReactCurrentOwner.current.type), config.ref);\n\n didWarnAboutStringRefs[componentName] = true;\n }\n }\n }\n}\n/**\n * Factory method to create a new React element. This no longer adheres to\n * the class pattern, so do not use new to call it. Also, instanceof check\n * will not work. Instead test $$typeof field against Symbol.for('react.element') to check\n * if something is a React Element.\n *\n * @param {*} type\n * @param {*} props\n * @param {*} key\n * @param {string|object} ref\n * @param {*} owner\n * @param {*} self A *temporary* helper to detect places where `this` is\n * different from the `owner` when React.createElement is called, so that we\n * can warn. We want to get rid of owner and replace string `ref`s with arrow\n * functions, and as long as `this` and owner are the same, there will be no\n * change in behavior.\n * @param {*} source An annotation object (added by a transpiler or otherwise)\n * indicating filename, line number, and/or other information.\n * @internal\n */\n\n\nvar ReactElement = function (type, key, ref, self, source, owner, props) {\n var element = {\n // This tag allows us to uniquely identify this as a React Element\n $$typeof: REACT_ELEMENT_TYPE,\n // Built-in properties that belong on the element\n type: type,\n key: key,\n ref: ref,\n props: props,\n // Record the component responsible for creating this element.\n _owner: owner\n };\n\n {\n // The validation flag is currently mutative. We put it on\n // an external backing store so that we can freeze the whole object.\n // This can be replaced with a WeakMap once they are implemented in\n // commonly used development environments.\n element._store = {}; // To make comparing ReactElements easier for testing purposes, we make\n // the validation flag non-enumerable (where possible, which should\n // include every environment we run tests in), so the test framework\n // ignores it.\n\n Object.defineProperty(element._store, 'validated', {\n configurable: false,\n enumerable: false,\n writable: true,\n value: false\n }); // self and source are DEV only properties.\n\n Object.defineProperty(element, '_self', {\n configurable: false,\n enumerable: false,\n writable: false,\n value: self\n }); // Two elements created in two different places should be considered\n // equal for testing purposes and therefore we hide it from enumeration.\n\n Object.defineProperty(element, '_source', {\n configurable: false,\n enumerable: false,\n writable: false,\n value: source\n });\n\n if (Object.freeze) {\n Object.freeze(element.props);\n Object.freeze(element);\n }\n }\n\n return element;\n};\n/**\n * Create and return a new ReactElement of the given type.\n * See https://reactjs.org/docs/react-api.html#createelement\n */\n\nfunction createElement(type, config, children) {\n var propName; // Reserved names are extracted\n\n var props = {};\n var key = null;\n var ref = null;\n var self = null;\n var source = null;\n\n if (config != null) {\n if (hasValidRef(config)) {\n ref = config.ref;\n\n {\n warnIfStringRefCannotBeAutoConverted(config);\n }\n }\n\n if (hasValidKey(config)) {\n key = '' + config.key;\n }\n\n self = config.__self === undefined ? null : config.__self;\n source = config.__source === undefined ? null : config.__source; // Remaining properties are added to a new props object\n\n for (propName in config) {\n if (hasOwnProperty.call(config, propName) && !RESERVED_PROPS.hasOwnProperty(propName)) {\n props[propName] = config[propName];\n }\n }\n } // Children can be more than one argument, and those are transferred onto\n // the newly allocated props object.\n\n\n var childrenLength = arguments.length - 2;\n\n if (childrenLength === 1) {\n props.children = children;\n } else if (childrenLength > 1) {\n var childArray = Array(childrenLength);\n\n for (var i = 0; i < childrenLength; i++) {\n childArray[i] = arguments[i + 2];\n }\n\n {\n if (Object.freeze) {\n Object.freeze(childArray);\n }\n }\n\n props.children = childArray;\n } // Resolve default props\n\n\n if (type && type.defaultProps) {\n var defaultProps = type.defaultProps;\n\n for (propName in defaultProps) {\n if (props[propName] === undefined) {\n props[propName] = defaultProps[propName];\n }\n }\n }\n\n {\n if (key || ref) {\n var displayName = typeof type === 'function' ? type.displayName || type.name || 'Unknown' : type;\n\n if (key) {\n defineKeyPropWarningGetter(props, displayName);\n }\n\n if (ref) {\n defineRefPropWarningGetter(props, displayName);\n }\n }\n }\n\n return ReactElement(type, key, ref, self, source, ReactCurrentOwner.current, props);\n}\nfunction cloneAndReplaceKey(oldElement, newKey) {\n var newElement = ReactElement(oldElement.type, newKey, oldElement.ref, oldElement._self, oldElement._source, oldElement._owner, oldElement.props);\n return newElement;\n}\n/**\n * Clone and return a new ReactElement using element as the starting point.\n * See https://reactjs.org/docs/react-api.html#cloneelement\n */\n\nfunction cloneElement(element, config, children) {\n if (!!(element === null || element === undefined)) {\n {\n throw Error( \"React.cloneElement(...): The argument must be a React element, but you passed \" + element + \".\" );\n }\n }\n\n var propName; // Original props are copied\n\n var props = _assign({}, element.props); // Reserved names are extracted\n\n\n var key = element.key;\n var ref = element.ref; // Self is preserved since the owner is preserved.\n\n var self = element._self; // Source is preserved since cloneElement is unlikely to be targeted by a\n // transpiler, and the original source is probably a better indicator of the\n // true owner.\n\n var source = element._source; // Owner will be preserved, unless ref is overridden\n\n var owner = element._owner;\n\n if (config != null) {\n if (hasValidRef(config)) {\n // Silently steal the ref from the parent.\n ref = config.ref;\n owner = ReactCurrentOwner.current;\n }\n\n if (hasValidKey(config)) {\n key = '' + config.key;\n } // Remaining properties override existing props\n\n\n var defaultProps;\n\n if (element.type && element.type.defaultProps) {\n defaultProps = element.type.defaultProps;\n }\n\n for (propName in config) {\n if (hasOwnProperty.call(config, propName) && !RESERVED_PROPS.hasOwnProperty(propName)) {\n if (config[propName] === undefined && defaultProps !== undefined) {\n // Resolve default props\n props[propName] = defaultProps[propName];\n } else {\n props[propName] = config[propName];\n }\n }\n }\n } // Children can be more than one argument, and those are transferred onto\n // the newly allocated props object.\n\n\n var childrenLength = arguments.length - 2;\n\n if (childrenLength === 1) {\n props.children = children;\n } else if (childrenLength > 1) {\n var childArray = Array(childrenLength);\n\n for (var i = 0; i < childrenLength; i++) {\n childArray[i] = arguments[i + 2];\n }\n\n props.children = childArray;\n }\n\n return ReactElement(element.type, key, ref, self, source, owner, props);\n}\n/**\n * Verifies the object is a ReactElement.\n * See https://reactjs.org/docs/react-api.html#isvalidelement\n * @param {?object} object\n * @return {boolean} True if `object` is a ReactElement.\n * @final\n */\n\nfunction isValidElement(object) {\n return typeof object === 'object' && object !== null && object.$$typeof === REACT_ELEMENT_TYPE;\n}\n\nvar SEPARATOR = '.';\nvar SUBSEPARATOR = ':';\n/**\n * Escape and wrap key so it is safe to use as a reactid\n *\n * @param {string} key to be escaped.\n * @return {string} the escaped key.\n */\n\nfunction escape(key) {\n var escapeRegex = /[=:]/g;\n var escaperLookup = {\n '=': '=0',\n ':': '=2'\n };\n var escapedString = ('' + key).replace(escapeRegex, function (match) {\n return escaperLookup[match];\n });\n return '$' + escapedString;\n}\n/**\n * TODO: Test that a single child and an array with one item have the same key\n * pattern.\n */\n\n\nvar didWarnAboutMaps = false;\nvar userProvidedKeyEscapeRegex = /\\/+/g;\n\nfunction escapeUserProvidedKey(text) {\n return ('' + text).replace(userProvidedKeyEscapeRegex, '$&/');\n}\n\nvar POOL_SIZE = 10;\nvar traverseContextPool = [];\n\nfunction getPooledTraverseContext(mapResult, keyPrefix, mapFunction, mapContext) {\n if (traverseContextPool.length) {\n var traverseContext = traverseContextPool.pop();\n traverseContext.result = mapResult;\n traverseContext.keyPrefix = keyPrefix;\n traverseContext.func = mapFunction;\n traverseContext.context = mapContext;\n traverseContext.count = 0;\n return traverseContext;\n } else {\n return {\n result: mapResult,\n keyPrefix: keyPrefix,\n func: mapFunction,\n context: mapContext,\n count: 0\n };\n }\n}\n\nfunction releaseTraverseContext(traverseContext) {\n traverseContext.result = null;\n traverseContext.keyPrefix = null;\n traverseContext.func = null;\n traverseContext.context = null;\n traverseContext.count = 0;\n\n if (traverseContextPool.length < POOL_SIZE) {\n traverseContextPool.push(traverseContext);\n }\n}\n/**\n * @param {?*} children Children tree container.\n * @param {!string} nameSoFar Name of the key path so far.\n * @param {!function} callback Callback to invoke with each child found.\n * @param {?*} traverseContext Used to pass information throughout the traversal\n * process.\n * @return {!number} The number of children in this subtree.\n */\n\n\nfunction traverseAllChildrenImpl(children, nameSoFar, callback, traverseContext) {\n var type = typeof children;\n\n if (type === 'undefined' || type === 'boolean') {\n // All of the above are perceived as null.\n children = null;\n }\n\n var invokeCallback = false;\n\n if (children === null) {\n invokeCallback = true;\n } else {\n switch (type) {\n case 'string':\n case 'number':\n invokeCallback = true;\n break;\n\n case 'object':\n switch (children.$$typeof) {\n case REACT_ELEMENT_TYPE:\n case REACT_PORTAL_TYPE:\n invokeCallback = true;\n }\n\n }\n }\n\n if (invokeCallback) {\n callback(traverseContext, children, // If it's the only child, treat the name as if it was wrapped in an array\n // so that it's consistent if the number of children grows.\n nameSoFar === '' ? SEPARATOR + getComponentKey(children, 0) : nameSoFar);\n return 1;\n }\n\n var child;\n var nextName;\n var subtreeCount = 0; // Count of children found in the current subtree.\n\n var nextNamePrefix = nameSoFar === '' ? SEPARATOR : nameSoFar + SUBSEPARATOR;\n\n if (Array.isArray(children)) {\n for (var i = 0; i < children.length; i++) {\n child = children[i];\n nextName = nextNamePrefix + getComponentKey(child, i);\n subtreeCount += traverseAllChildrenImpl(child, nextName, callback, traverseContext);\n }\n } else {\n var iteratorFn = getIteratorFn(children);\n\n if (typeof iteratorFn === 'function') {\n\n {\n // Warn about using Maps as children\n if (iteratorFn === children.entries) {\n if (!didWarnAboutMaps) {\n warn('Using Maps as children is deprecated and will be removed in ' + 'a future major release. Consider converting children to ' + 'an array of keyed ReactElements instead.');\n }\n\n didWarnAboutMaps = true;\n }\n }\n\n var iterator = iteratorFn.call(children);\n var step;\n var ii = 0;\n\n while (!(step = iterator.next()).done) {\n child = step.value;\n nextName = nextNamePrefix + getComponentKey(child, ii++);\n subtreeCount += traverseAllChildrenImpl(child, nextName, callback, traverseContext);\n }\n } else if (type === 'object') {\n var addendum = '';\n\n {\n addendum = ' If you meant to render a collection of children, use an array ' + 'instead.' + ReactDebugCurrentFrame.getStackAddendum();\n }\n\n var childrenString = '' + children;\n\n {\n {\n throw Error( \"Objects are not valid as a React child (found: \" + (childrenString === '[object Object]' ? 'object with keys {' + Object.keys(children).join(', ') + '}' : childrenString) + \").\" + addendum );\n }\n }\n }\n }\n\n return subtreeCount;\n}\n/**\n * Traverses children that are typically specified as `props.children`, but\n * might also be specified through attributes:\n *\n * - `traverseAllChildren(this.props.children, ...)`\n * - `traverseAllChildren(this.props.leftPanelChildren, ...)`\n *\n * The `traverseContext` is an optional argument that is passed through the\n * entire traversal. It can be used to store accumulations or anything else that\n * the callback might find relevant.\n *\n * @param {?*} children Children tree object.\n * @param {!function} callback To invoke upon traversing each child.\n * @param {?*} traverseContext Context for traversal.\n * @return {!number} The number of children in this subtree.\n */\n\n\nfunction traverseAllChildren(children, callback, traverseContext) {\n if (children == null) {\n return 0;\n }\n\n return traverseAllChildrenImpl(children, '', callback, traverseContext);\n}\n/**\n * Generate a key string that identifies a component within a set.\n *\n * @param {*} component A component that could contain a manual key.\n * @param {number} index Index that is used if a manual key is not provided.\n * @return {string}\n */\n\n\nfunction getComponentKey(component, index) {\n // Do some typechecking here since we call this blindly. We want to ensure\n // that we don't block potential future ES APIs.\n if (typeof component === 'object' && component !== null && component.key != null) {\n // Explicit key\n return escape(component.key);\n } // Implicit key determined by the index in the set\n\n\n return index.toString(36);\n}\n\nfunction forEachSingleChild(bookKeeping, child, name) {\n var func = bookKeeping.func,\n context = bookKeeping.context;\n func.call(context, child, bookKeeping.count++);\n}\n/**\n * Iterates through children that are typically specified as `props.children`.\n *\n * See https://reactjs.org/docs/react-api.html#reactchildrenforeach\n *\n * The provided forEachFunc(child, index) will be called for each\n * leaf child.\n *\n * @param {?*} children Children tree container.\n * @param {function(*, int)} forEachFunc\n * @param {*} forEachContext Context for forEachContext.\n */\n\n\nfunction forEachChildren(children, forEachFunc, forEachContext) {\n if (children == null) {\n return children;\n }\n\n var traverseContext = getPooledTraverseContext(null, null, forEachFunc, forEachContext);\n traverseAllChildren(children, forEachSingleChild, traverseContext);\n releaseTraverseContext(traverseContext);\n}\n\nfunction mapSingleChildIntoContext(bookKeeping, child, childKey) {\n var result = bookKeeping.result,\n keyPrefix = bookKeeping.keyPrefix,\n func = bookKeeping.func,\n context = bookKeeping.context;\n var mappedChild = func.call(context, child, bookKeeping.count++);\n\n if (Array.isArray(mappedChild)) {\n mapIntoWithKeyPrefixInternal(mappedChild, result, childKey, function (c) {\n return c;\n });\n } else if (mappedChild != null) {\n if (isValidElement(mappedChild)) {\n mappedChild = cloneAndReplaceKey(mappedChild, // Keep both the (mapped) and old keys if they differ, just as\n // traverseAllChildren used to do for objects as children\n keyPrefix + (mappedChild.key && (!child || child.key !== mappedChild.key) ? escapeUserProvidedKey(mappedChild.key) + '/' : '') + childKey);\n }\n\n result.push(mappedChild);\n }\n}\n\nfunction mapIntoWithKeyPrefixInternal(children, array, prefix, func, context) {\n var escapedPrefix = '';\n\n if (prefix != null) {\n escapedPrefix = escapeUserProvidedKey(prefix) + '/';\n }\n\n var traverseContext = getPooledTraverseContext(array, escapedPrefix, func, context);\n traverseAllChildren(children, mapSingleChildIntoContext, traverseContext);\n releaseTraverseContext(traverseContext);\n}\n/**\n * Maps children that are typically specified as `props.children`.\n *\n * See https://reactjs.org/docs/react-api.html#reactchildrenmap\n *\n * The provided mapFunction(child, key, index) will be called for each\n * leaf child.\n *\n * @param {?*} children Children tree container.\n * @param {function(*, int)} func The map function.\n * @param {*} context Context for mapFunction.\n * @return {object} Object containing the ordered map of results.\n */\n\n\nfunction mapChildren(children, func, context) {\n if (children == null) {\n return children;\n }\n\n var result = [];\n mapIntoWithKeyPrefixInternal(children, result, null, func, context);\n return result;\n}\n/**\n * Count the number of children that are typically specified as\n * `props.children`.\n *\n * See https://reactjs.org/docs/react-api.html#reactchildrencount\n *\n * @param {?*} children Children tree container.\n * @return {number} The number of children.\n */\n\n\nfunction countChildren(children) {\n return traverseAllChildren(children, function () {\n return null;\n }, null);\n}\n/**\n * Flatten a children object (typically specified as `props.children`) and\n * return an array with appropriately re-keyed children.\n *\n * See https://reactjs.org/docs/react-api.html#reactchildrentoarray\n */\n\n\nfunction toArray(children) {\n var result = [];\n mapIntoWithKeyPrefixInternal(children, result, null, function (child) {\n return child;\n });\n return result;\n}\n/**\n * Returns the first child in a collection of children and verifies that there\n * is only one child in the collection.\n *\n * See https://reactjs.org/docs/react-api.html#reactchildrenonly\n *\n * The current implementation of this function assumes that a single child gets\n * passed without a wrapper, but the purpose of this helper function is to\n * abstract away the particular structure of children.\n *\n * @param {?object} children Child collection structure.\n * @return {ReactElement} The first and only `ReactElement` contained in the\n * structure.\n */\n\n\nfunction onlyChild(children) {\n if (!isValidElement(children)) {\n {\n throw Error( \"React.Children.only expected to receive a single React element child.\" );\n }\n }\n\n return children;\n}\n\nfunction createContext(defaultValue, calculateChangedBits) {\n if (calculateChangedBits === undefined) {\n calculateChangedBits = null;\n } else {\n {\n if (calculateChangedBits !== null && typeof calculateChangedBits !== 'function') {\n error('createContext: Expected the optional second argument to be a ' + 'function. Instead received: %s', calculateChangedBits);\n }\n }\n }\n\n var context = {\n $$typeof: REACT_CONTEXT_TYPE,\n _calculateChangedBits: calculateChangedBits,\n // As a workaround to support multiple concurrent renderers, we categorize\n // some renderers as primary and others as secondary. We only expect\n // there to be two concurrent renderers at most: React Native (primary) and\n // Fabric (secondary); React DOM (primary) and React ART (secondary).\n // Secondary renderers store their context values on separate fields.\n _currentValue: defaultValue,\n _currentValue2: defaultValue,\n // Used to track how many concurrent renderers this context currently\n // supports within in a single renderer. Such as parallel server rendering.\n _threadCount: 0,\n // These are circular\n Provider: null,\n Consumer: null\n };\n context.Provider = {\n $$typeof: REACT_PROVIDER_TYPE,\n _context: context\n };\n var hasWarnedAboutUsingNestedContextConsumers = false;\n var hasWarnedAboutUsingConsumerProvider = false;\n\n {\n // A separate object, but proxies back to the original context object for\n // backwards compatibility. It has a different $$typeof, so we can properly\n // warn for the incorrect usage of Context as a Consumer.\n var Consumer = {\n $$typeof: REACT_CONTEXT_TYPE,\n _context: context,\n _calculateChangedBits: context._calculateChangedBits\n }; // $FlowFixMe: Flow complains about not setting a value, which is intentional here\n\n Object.defineProperties(Consumer, {\n Provider: {\n get: function () {\n if (!hasWarnedAboutUsingConsumerProvider) {\n hasWarnedAboutUsingConsumerProvider = true;\n\n error('Rendering <Context.Consumer.Provider> is not supported and will be removed in ' + 'a future major release. Did you mean to render <Context.Provider> instead?');\n }\n\n return context.Provider;\n },\n set: function (_Provider) {\n context.Provider = _Provider;\n }\n },\n _currentValue: {\n get: function () {\n return context._currentValue;\n },\n set: function (_currentValue) {\n context._currentValue = _currentValue;\n }\n },\n _currentValue2: {\n get: function () {\n return context._currentValue2;\n },\n set: function (_currentValue2) {\n context._currentValue2 = _currentValue2;\n }\n },\n _threadCount: {\n get: function () {\n return context._threadCount;\n },\n set: function (_threadCount) {\n context._threadCount = _threadCount;\n }\n },\n Consumer: {\n get: function () {\n if (!hasWarnedAboutUsingNestedContextConsumers) {\n hasWarnedAboutUsingNestedContextConsumers = true;\n\n error('Rendering <Context.Consumer.Consumer> is not supported and will be removed in ' + 'a future major release. Did you mean to render <Context.Consumer> instead?');\n }\n\n return context.Consumer;\n }\n }\n }); // $FlowFixMe: Flow complains about missing properties because it doesn't understand defineProperty\n\n context.Consumer = Consumer;\n }\n\n {\n context._currentRenderer = null;\n context._currentRenderer2 = null;\n }\n\n return context;\n}\n\nfunction lazy(ctor) {\n var lazyType = {\n $$typeof: REACT_LAZY_TYPE,\n _ctor: ctor,\n // React uses these fields to store the result.\n _status: -1,\n _result: null\n };\n\n {\n // In production, this would just set it on the object.\n var defaultProps;\n var propTypes;\n Object.defineProperties(lazyType, {\n defaultProps: {\n configurable: true,\n get: function () {\n return defaultProps;\n },\n set: function (newDefaultProps) {\n error('React.lazy(...): It is not supported to assign `defaultProps` to ' + 'a lazy component import. Either specify them where the component ' + 'is defined, or create a wrapping component around it.');\n\n defaultProps = newDefaultProps; // Match production behavior more closely:\n\n Object.defineProperty(lazyType, 'defaultProps', {\n enumerable: true\n });\n }\n },\n propTypes: {\n configurable: true,\n get: function () {\n return propTypes;\n },\n set: function (newPropTypes) {\n error('React.lazy(...): It is not supported to assign `propTypes` to ' + 'a lazy component import. Either specify them where the component ' + 'is defined, or create a wrapping component around it.');\n\n propTypes = newPropTypes; // Match production behavior more closely:\n\n Object.defineProperty(lazyType, 'propTypes', {\n enumerable: true\n });\n }\n }\n });\n }\n\n return lazyType;\n}\n\nfunction forwardRef(render) {\n {\n if (render != null && render.$$typeof === REACT_MEMO_TYPE) {\n error('forwardRef requires a render function but received a `memo` ' + 'component. Instead of forwardRef(memo(...)), use ' + 'memo(forwardRef(...)).');\n } else if (typeof render !== 'function') {\n error('forwardRef requires a render function but was given %s.', render === null ? 'null' : typeof render);\n } else {\n if (render.length !== 0 && render.length !== 2) {\n error('forwardRef render functions accept exactly two parameters: props and ref. %s', render.length === 1 ? 'Did you forget to use the ref parameter?' : 'Any additional parameter will be undefined.');\n }\n }\n\n if (render != null) {\n if (render.defaultProps != null || render.propTypes != null) {\n error('forwardRef render functions do not support propTypes or defaultProps. ' + 'Did you accidentally pass a React component?');\n }\n }\n }\n\n return {\n $$typeof: REACT_FORWARD_REF_TYPE,\n render: render\n };\n}\n\nfunction isValidElementType(type) {\n return typeof type === 'string' || typeof type === 'function' || // Note: its typeof might be other than 'symbol' or 'number' if it's a polyfill.\n type === REACT_FRAGMENT_TYPE || type === REACT_CONCURRENT_MODE_TYPE || type === REACT_PROFILER_TYPE || type === REACT_STRICT_MODE_TYPE || type === REACT_SUSPENSE_TYPE || type === REACT_SUSPENSE_LIST_TYPE || typeof type === 'object' && type !== null && (type.$$typeof === REACT_LAZY_TYPE || type.$$typeof === REACT_MEMO_TYPE || type.$$typeof === REACT_PROVIDER_TYPE || type.$$typeof === REACT_CONTEXT_TYPE || type.$$typeof === REACT_FORWARD_REF_TYPE || type.$$typeof === REACT_FUNDAMENTAL_TYPE || type.$$typeof === REACT_RESPONDER_TYPE || type.$$typeof === REACT_SCOPE_TYPE || type.$$typeof === REACT_BLOCK_TYPE);\n}\n\nfunction memo(type, compare) {\n {\n if (!isValidElementType(type)) {\n error('memo: The first argument must be a component. Instead ' + 'received: %s', type === null ? 'null' : typeof type);\n }\n }\n\n return {\n $$typeof: REACT_MEMO_TYPE,\n type: type,\n compare: compare === undefined ? null : compare\n };\n}\n\nfunction resolveDispatcher() {\n var dispatcher = ReactCurrentDispatcher.current;\n\n if (!(dispatcher !== null)) {\n {\n throw Error( \"Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:\\n1. You might have mismatching versions of React and the renderer (such as React DOM)\\n2. You might be breaking the Rules of Hooks\\n3. You might have more than one copy of React in the same app\\nSee https://fb.me/react-invalid-hook-call for tips about how to debug and fix this problem.\" );\n }\n }\n\n return dispatcher;\n}\n\nfunction useContext(Context, unstable_observedBits) {\n var dispatcher = resolveDispatcher();\n\n {\n if (unstable_observedBits !== undefined) {\n error('useContext() second argument is reserved for future ' + 'use in React. Passing it is not supported. ' + 'You passed: %s.%s', unstable_observedBits, typeof unstable_observedBits === 'number' && Array.isArray(arguments[2]) ? '\\n\\nDid you call array.map(useContext)? ' + 'Calling Hooks inside a loop is not supported. ' + 'Learn more at https://fb.me/rules-of-hooks' : '');\n } // TODO: add a more generic warning for invalid values.\n\n\n if (Context._context !== undefined) {\n var realContext = Context._context; // Don't deduplicate because this legitimately causes bugs\n // and nobody should be using this in existing code.\n\n if (realContext.Consumer === Context) {\n error('Calling useContext(Context.Consumer) is not supported, may cause bugs, and will be ' + 'removed in a future major release. Did you mean to call useContext(Context) instead?');\n } else if (realContext.Provider === Context) {\n error('Calling useContext(Context.Provider) is not supported. ' + 'Did you mean to call useContext(Context) instead?');\n }\n }\n }\n\n return dispatcher.useContext(Context, unstable_observedBits);\n}\nfunction useState(initialState) {\n var dispatcher = resolveDispatcher();\n return dispatcher.useState(initialState);\n}\nfunction useReducer(reducer, initialArg, init) {\n var dispatcher = resolveDispatcher();\n return dispatcher.useReducer(reducer, initialArg, init);\n}\nfunction useRef(initialValue) {\n var dispatcher = resolveDispatcher();\n return dispatcher.useRef(initialValue);\n}\nfunction useEffect(create, deps) {\n var dispatcher = resolveDispatcher();\n return dispatcher.useEffect(create, deps);\n}\nfunction useLayoutEffect(create, deps) {\n var dispatcher = resolveDispatcher();\n return dispatcher.useLayoutEffect(create, deps);\n}\nfunction useCallback(callback, deps) {\n var dispatcher = resolveDispatcher();\n return dispatcher.useCallback(callback, deps);\n}\nfunction useMemo(create, deps) {\n var dispatcher = resolveDispatcher();\n return dispatcher.useMemo(create, deps);\n}\nfunction useImperativeHandle(ref, create, deps) {\n var dispatcher = resolveDispatcher();\n return dispatcher.useImperativeHandle(ref, create, deps);\n}\nfunction useDebugValue(value, formatterFn) {\n {\n var dispatcher = resolveDispatcher();\n return dispatcher.useDebugValue(value, formatterFn);\n }\n}\n\nvar propTypesMisspellWarningShown;\n\n{\n propTypesMisspellWarningShown = false;\n}\n\nfunction getDeclarationErrorAddendum() {\n if (ReactCurrentOwner.current) {\n var name = getComponentName(ReactCurrentOwner.current.type);\n\n if (name) {\n return '\\n\\nCheck the render method of `' + name + '`.';\n }\n }\n\n return '';\n}\n\nfunction getSourceInfoErrorAddendum(source) {\n if (source !== undefined) {\n var fileName = source.fileName.replace(/^.*[\\\\\\/]/, '');\n var lineNumber = source.lineNumber;\n return '\\n\\nCheck your code at ' + fileName + ':' + lineNumber + '.';\n }\n\n return '';\n}\n\nfunction getSourceInfoErrorAddendumForProps(elementProps) {\n if (elementProps !== null && elementProps !== undefined) {\n return getSourceInfoErrorAddendum(elementProps.__source);\n }\n\n return '';\n}\n/**\n * Warn if there's no key explicitly set on dynamic arrays of children or\n * object keys are not valid. This allows us to keep track of children between\n * updates.\n */\n\n\nvar ownerHasKeyUseWarning = {};\n\nfunction getCurrentComponentErrorInfo(parentType) {\n var info = getDeclarationErrorAddendum();\n\n if (!info) {\n var parentName = typeof parentType === 'string' ? parentType : parentType.displayName || parentType.name;\n\n if (parentName) {\n info = \"\\n\\nCheck the top-level render call using <\" + parentName + \">.\";\n }\n }\n\n return info;\n}\n/**\n * Warn if the element doesn't have an explicit key assigned to it.\n * This element is in an array. The array could grow and shrink or be\n * reordered. All children that haven't already been validated are required to\n * have a \"key\" property assigned to it. Error statuses are cached so a warning\n * will only be shown once.\n *\n * @internal\n * @param {ReactElement} element Element that requires a key.\n * @param {*} parentType element's parent's type.\n */\n\n\nfunction validateExplicitKey(element, parentType) {\n if (!element._store || element._store.validated || element.key != null) {\n return;\n }\n\n element._store.validated = true;\n var currentComponentErrorInfo = getCurrentComponentErrorInfo(parentType);\n\n if (ownerHasKeyUseWarning[currentComponentErrorInfo]) {\n return;\n }\n\n ownerHasKeyUseWarning[currentComponentErrorInfo] = true; // Usually the current owner is the offender, but if it accepts children as a\n // property, it may be the creator of the child that's responsible for\n // assigning it a key.\n\n var childOwner = '';\n\n if (element && element._owner && element._owner !== ReactCurrentOwner.current) {\n // Give the component that originally created this child.\n childOwner = \" It was passed a child from \" + getComponentName(element._owner.type) + \".\";\n }\n\n setCurrentlyValidatingElement(element);\n\n {\n error('Each child in a list should have a unique \"key\" prop.' + '%s%s See https://fb.me/react-warning-keys for more information.', currentComponentErrorInfo, childOwner);\n }\n\n setCurrentlyValidatingElement(null);\n}\n/**\n * Ensure that every element either is passed in a static location, in an\n * array with an explicit keys property defined, or in an object literal\n * with valid key property.\n *\n * @internal\n * @param {ReactNode} node Statically passed child of any type.\n * @param {*} parentType node's parent's type.\n */\n\n\nfunction validateChildKeys(node, parentType) {\n if (typeof node !== 'object') {\n return;\n }\n\n if (Array.isArray(node)) {\n for (var i = 0; i < node.length; i++) {\n var child = node[i];\n\n if (isValidElement(child)) {\n validateExplicitKey(child, parentType);\n }\n }\n } else if (isValidElement(node)) {\n // This element was passed in a valid location.\n if (node._store) {\n node._store.validated = true;\n }\n } else if (node) {\n var iteratorFn = getIteratorFn(node);\n\n if (typeof iteratorFn === 'function') {\n // Entry iterators used to provide implicit keys,\n // but now we print a separate warning for them later.\n if (iteratorFn !== node.entries) {\n var iterator = iteratorFn.call(node);\n var step;\n\n while (!(step = iterator.next()).done) {\n if (isValidElement(step.value)) {\n validateExplicitKey(step.value, parentType);\n }\n }\n }\n }\n }\n}\n/**\n * Given an element, validate that its props follow the propTypes definition,\n * provided by the type.\n *\n * @param {ReactElement} element\n */\n\n\nfunction validatePropTypes(element) {\n {\n var type = element.type;\n\n if (type === null || type === undefined || typeof type === 'string') {\n return;\n }\n\n var name = getComponentName(type);\n var propTypes;\n\n if (typeof type === 'function') {\n propTypes = type.propTypes;\n } else if (typeof type === 'object' && (type.$$typeof === REACT_FORWARD_REF_TYPE || // Note: Memo only checks outer props here.\n // Inner props are checked in the reconciler.\n type.$$typeof === REACT_MEMO_TYPE)) {\n propTypes = type.propTypes;\n } else {\n return;\n }\n\n if (propTypes) {\n setCurrentlyValidatingElement(element);\n checkPropTypes(propTypes, element.props, 'prop', name, ReactDebugCurrentFrame.getStackAddendum);\n setCurrentlyValidatingElement(null);\n } else if (type.PropTypes !== undefined && !propTypesMisspellWarningShown) {\n propTypesMisspellWarningShown = true;\n\n error('Component %s declared `PropTypes` instead of `propTypes`. Did you misspell the property assignment?', name || 'Unknown');\n }\n\n if (typeof type.getDefaultProps === 'function' && !type.getDefaultProps.isReactClassApproved) {\n error('getDefaultProps is only used on classic React.createClass ' + 'definitions. Use a static property named `defaultProps` instead.');\n }\n }\n}\n/**\n * Given a fragment, validate that it can only be provided with fragment props\n * @param {ReactElement} fragment\n */\n\n\nfunction validateFragmentProps(fragment) {\n {\n setCurrentlyValidatingElement(fragment);\n var keys = Object.keys(fragment.props);\n\n for (var i = 0; i < keys.length; i++) {\n var key = keys[i];\n\n if (key !== 'children' && key !== 'key') {\n error('Invalid prop `%s` supplied to `React.Fragment`. ' + 'React.Fragment can only have `key` and `children` props.', key);\n\n break;\n }\n }\n\n if (fragment.ref !== null) {\n error('Invalid attribute `ref` supplied to `React.Fragment`.');\n }\n\n setCurrentlyValidatingElement(null);\n }\n}\nfunction createElementWithValidation(type, props, children) {\n var validType = isValidElementType(type); // We warn in this case but don't throw. We expect the element creation to\n // succeed and there will likely be errors in render.\n\n if (!validType) {\n var info = '';\n\n if (type === undefined || typeof type === 'object' && type !== null && Object.keys(type).length === 0) {\n info += ' You likely forgot to export your component from the file ' + \"it's defined in, or you might have mixed up default and named imports.\";\n }\n\n var sourceInfo = getSourceInfoErrorAddendumForProps(props);\n\n if (sourceInfo) {\n info += sourceInfo;\n } else {\n info += getDeclarationErrorAddendum();\n }\n\n var typeString;\n\n if (type === null) {\n typeString = 'null';\n } else if (Array.isArray(type)) {\n typeString = 'array';\n } else if (type !== undefined && type.$$typeof === REACT_ELEMENT_TYPE) {\n typeString = \"<\" + (getComponentName(type.type) || 'Unknown') + \" />\";\n info = ' Did you accidentally export a JSX literal instead of a component?';\n } else {\n typeString = typeof type;\n }\n\n {\n error('React.createElement: type is invalid -- expected a string (for ' + 'built-in components) or a class/function (for composite ' + 'components) but got: %s.%s', typeString, info);\n }\n }\n\n var element = createElement.apply(this, arguments); // The result can be nullish if a mock or a custom function is used.\n // TODO: Drop this when these are no longer allowed as the type argument.\n\n if (element == null) {\n return element;\n } // Skip key warning if the type isn't valid since our key validation logic\n // doesn't expect a non-string/function type and can throw confusing errors.\n // We don't want exception behavior to differ between dev and prod.\n // (Rendering will throw with a helpful message and as soon as the type is\n // fixed, the key warnings will appear.)\n\n\n if (validType) {\n for (var i = 2; i < arguments.length; i++) {\n validateChildKeys(arguments[i], type);\n }\n }\n\n if (type === REACT_FRAGMENT_TYPE) {\n validateFragmentProps(element);\n } else {\n validatePropTypes(element);\n }\n\n return element;\n}\nvar didWarnAboutDeprecatedCreateFactory = false;\nfunction createFactoryWithValidation(type) {\n var validatedFactory = createElementWithValidation.bind(null, type);\n validatedFactory.type = type;\n\n {\n if (!didWarnAboutDeprecatedCreateFactory) {\n didWarnAboutDeprecatedCreateFactory = true;\n\n warn('React.createFactory() is deprecated and will be removed in ' + 'a future major release. Consider using JSX ' + 'or use React.createElement() directly instead.');\n } // Legacy hook: remove it\n\n\n Object.defineProperty(validatedFactory, 'type', {\n enumerable: false,\n get: function () {\n warn('Factory.type is deprecated. Access the class directly ' + 'before passing it to createFactory.');\n\n Object.defineProperty(this, 'type', {\n value: type\n });\n return type;\n }\n });\n }\n\n return validatedFactory;\n}\nfunction cloneElementWithValidation(element, props, children) {\n var newElement = cloneElement.apply(this, arguments);\n\n for (var i = 2; i < arguments.length; i++) {\n validateChildKeys(arguments[i], newElement.type);\n }\n\n validatePropTypes(newElement);\n return newElement;\n}\n\n{\n\n try {\n var frozenObject = Object.freeze({});\n var testMap = new Map([[frozenObject, null]]);\n var testSet = new Set([frozenObject]); // This is necessary for Rollup to not consider these unused.\n // https://github.com/rollup/rollup/issues/1771\n // TODO: we can remove these if Rollup fixes the bug.\n\n testMap.set(0, 0);\n testSet.add(0);\n } catch (e) {\n }\n}\n\nvar createElement$1 = createElementWithValidation ;\nvar cloneElement$1 = cloneElementWithValidation ;\nvar createFactory = createFactoryWithValidation ;\nvar Children = {\n map: mapChildren,\n forEach: forEachChildren,\n count: countChildren,\n toArray: toArray,\n only: onlyChild\n};\n\nexports.Children = Children;\nexports.Component = Component;\nexports.Fragment = REACT_FRAGMENT_TYPE;\nexports.Profiler = REACT_PROFILER_TYPE;\nexports.PureComponent = PureComponent;\nexports.StrictMode = REACT_STRICT_MODE_TYPE;\nexports.Suspense = REACT_SUSPENSE_TYPE;\nexports.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED = ReactSharedInternals;\nexports.cloneElement = cloneElement$1;\nexports.createContext = createContext;\nexports.createElement = createElement$1;\nexports.createFactory = createFactory;\nexports.createRef = createRef;\nexports.forwardRef = forwardRef;\nexports.isValidElement = isValidElement;\nexports.lazy = lazy;\nexports.memo = memo;\nexports.useCallback = useCallback;\nexports.useContext = useContext;\nexports.useDebugValue = useDebugValue;\nexports.useEffect = useEffect;\nexports.useImperativeHandle = useImperativeHandle;\nexports.useLayoutEffect = useLayoutEffect;\nexports.useMemo = useMemo;\nexports.useReducer = useReducer;\nexports.useRef = useRef;\nexports.useState = useState;\nexports.version = ReactVersion;\n })();\n}\n\n\n//# sourceURL=webpack:///./node_modules/react/cjs/react.development.js?");
/***/ }),
/***/ "./node_modules/react/index.js":
/*!*************************************!*\
!*** ./node_modules/react/index.js ***!
\*************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
eval("\n\nif (false) {} else {\n module.exports = __webpack_require__(/*! ./cjs/react.development.js */ \"./node_modules/react/cjs/react.development.js\");\n}\n\n\n//# sourceURL=webpack:///./node_modules/react/index.js?");
/***/ }),
/***/ "./node_modules/resolve-pathname/esm/resolve-pathname.js":
/*!***************************************************************!*\
!*** ./node_modules/resolve-pathname/esm/resolve-pathname.js ***!
\***************************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
eval("__webpack_require__.r(__webpack_exports__);\nfunction isAbsolute(pathname) {\n return pathname.charAt(0) === '/';\n}\n\n// About 1.5x faster than the two-arg version of Array#splice()\nfunction spliceOne(list, index) {\n for (var i = index, k = i + 1, n = list.length; k < n; i += 1, k += 1) {\n list[i] = list[k];\n }\n\n list.pop();\n}\n\n// This implementation is based heavily on node's url.parse\nfunction resolvePathname(to, from) {\n if (from === undefined) from = '';\n\n var toParts = (to && to.split('/')) || [];\n var fromParts = (from && from.split('/')) || [];\n\n var isToAbs = to && isAbsolute(to);\n var isFromAbs = from && isAbsolute(from);\n var mustEndAbs = isToAbs || isFromAbs;\n\n if (to && isAbsolute(to)) {\n // to is absolute\n fromParts = toParts;\n } else if (toParts.length) {\n // to is relative, drop the filename\n fromParts.pop();\n fromParts = fromParts.concat(toParts);\n }\n\n if (!fromParts.length) return '/';\n\n var hasTrailingSlash;\n if (fromParts.length) {\n var last = fromParts[fromParts.length - 1];\n hasTrailingSlash = last === '.' || last === '..' || last === '';\n } else {\n hasTrailingSlash = false;\n }\n\n var up = 0;\n for (var i = fromParts.length; i >= 0; i--) {\n var part = fromParts[i];\n\n if (part === '.') {\n spliceOne(fromParts, i);\n } else if (part === '..') {\n spliceOne(fromParts, i);\n up++;\n } else if (up) {\n spliceOne(fromParts, i);\n up--;\n }\n }\n\n if (!mustEndAbs) for (; up--; up) fromParts.unshift('..');\n\n if (\n mustEndAbs &&\n fromParts[0] !== '' &&\n (!fromParts[0] || !isAbsolute(fromParts[0]))\n )\n fromParts.unshift('');\n\n var result = fromParts.join('/');\n\n if (hasTrailingSlash && result.substr(-1) !== '/') result += '/';\n\n return result;\n}\n\n/* harmony default export */ __webpack_exports__[\"default\"] = (resolvePathname);\n\n\n//# sourceURL=webpack:///./node_modules/resolve-pathname/esm/resolve-pathname.js?");
/***/ }),
/***/ "./node_modules/scheduler/cjs/scheduler-tracing.development.js":
/*!*********************************************************************!*\
!*** ./node_modules/scheduler/cjs/scheduler-tracing.development.js ***!
\*********************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
eval("/** @license React v0.19.1\n * scheduler-tracing.development.js\n *\n * Copyright (c) Facebook, Inc. and its affiliates.\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\n\n\n\nif (true) {\n (function() {\n'use strict';\n\nvar DEFAULT_THREAD_ID = 0; // Counters used to generate unique IDs.\n\nvar interactionIDCounter = 0;\nvar threadIDCounter = 0; // Set of currently traced interactions.\n// Interactions \"stack\"–\n// Meaning that newly traced interactions are appended to the previously active set.\n// When an interaction goes out of scope, the previous set (if any) is restored.\n\nexports.__interactionsRef = null; // Listener(s) to notify when interactions begin and end.\n\nexports.__subscriberRef = null;\n\n{\n exports.__interactionsRef = {\n current: new Set()\n };\n exports.__subscriberRef = {\n current: null\n };\n}\nfunction unstable_clear(callback) {\n\n var prevInteractions = exports.__interactionsRef.current;\n exports.__interactionsRef.current = new Set();\n\n try {\n return callback();\n } finally {\n exports.__interactionsRef.current = prevInteractions;\n }\n}\nfunction unstable_getCurrent() {\n {\n return exports.__interactionsRef.current;\n }\n}\nfunction unstable_getThreadID() {\n return ++threadIDCounter;\n}\nfunction unstable_trace(name, timestamp, callback) {\n var threadID = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : DEFAULT_THREAD_ID;\n\n var interaction = {\n __count: 1,\n id: interactionIDCounter++,\n name: name,\n timestamp: timestamp\n };\n var prevInteractions = exports.__interactionsRef.current; // Traced interactions should stack/accumulate.\n // To do that, clone the current interactions.\n // The previous set will be restored upon completion.\n\n var interactions = new Set(prevInteractions);\n interactions.add(interaction);\n exports.__interactionsRef.current = interactions;\n var subscriber = exports.__subscriberRef.current;\n var returnValue;\n\n try {\n if (subscriber !== null) {\n subscriber.onInteractionTraced(interaction);\n }\n } finally {\n try {\n if (subscriber !== null) {\n subscriber.onWorkStarted(interactions, threadID);\n }\n } finally {\n try {\n returnValue = callback();\n } finally {\n exports.__interactionsRef.current = prevInteractions;\n\n try {\n if (subscriber !== null) {\n subscriber.onWorkStopped(interactions, threadID);\n }\n } finally {\n interaction.__count--; // If no async work was scheduled for this interaction,\n // Notify subscribers that it's completed.\n\n if (subscriber !== null && interaction.__count === 0) {\n subscriber.onInteractionScheduledWorkCompleted(interaction);\n }\n }\n }\n }\n }\n\n return returnValue;\n}\nfunction unstable_wrap(callback) {\n var threadID = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : DEFAULT_THREAD_ID;\n\n var wrappedInteractions = exports.__interactionsRef.current;\n var subscriber = exports.__subscriberRef.current;\n\n if (subscriber !== null) {\n subscriber.onWorkScheduled(wrappedInteractions, threadID);\n } // Update the pending async work count for the current interactions.\n // Update after calling subscribers in case of error.\n\n\n wrappedInteractions.forEach(function (interaction) {\n interaction.__count++;\n });\n var hasRun = false;\n\n function wrapped() {\n var prevInteractions = exports.__interactionsRef.current;\n exports.__interactionsRef.current = wrappedInteractions;\n subscriber = exports.__subscriberRef.current;\n\n try {\n var returnValue;\n\n try {\n if (subscriber !== null) {\n subscriber.onWorkStarted(wrappedInteractions, threadID);\n }\n } finally {\n try {\n returnValue = callback.apply(undefined, arguments);\n } finally {\n exports.__interactionsRef.current = prevInteractions;\n\n if (subscriber !== null) {\n subscriber.onWorkStopped(wrappedInteractions, threadID);\n }\n }\n }\n\n return returnValue;\n } finally {\n if (!hasRun) {\n // We only expect a wrapped function to be executed once,\n // But in the event that it's executed more than once–\n // Only decrement the outstanding interaction counts once.\n hasRun = true; // Update pending async counts for all wrapped interactions.\n // If this was the last scheduled async work for any of them,\n // Mark them as completed.\n\n wrappedInteractions.forEach(function (interaction) {\n interaction.__count--;\n\n if (subscriber !== null && interaction.__count === 0) {\n subscriber.onInteractionScheduledWorkCompleted(interaction);\n }\n });\n }\n }\n }\n\n wrapped.cancel = function cancel() {\n subscriber = exports.__subscriberRef.current;\n\n try {\n if (subscriber !== null) {\n subscriber.onWorkCanceled(wrappedInteractions, threadID);\n }\n } finally {\n // Update pending async counts for all wrapped interactions.\n // If this was the last scheduled async work for any of them,\n // Mark them as completed.\n wrappedInteractions.forEach(function (interaction) {\n interaction.__count--;\n\n if (subscriber && interaction.__count === 0) {\n subscriber.onInteractionScheduledWorkCompleted(interaction);\n }\n });\n }\n };\n\n return wrapped;\n}\n\nvar subscribers = null;\n\n{\n subscribers = new Set();\n}\n\nfunction unstable_subscribe(subscriber) {\n {\n subscribers.add(subscriber);\n\n if (subscribers.size === 1) {\n exports.__subscriberRef.current = {\n onInteractionScheduledWorkCompleted: onInteractionScheduledWorkCompleted,\n onInteractionTraced: onInteractionTraced,\n onWorkCanceled: onWorkCanceled,\n onWorkScheduled: onWorkScheduled,\n onWorkStarted: onWorkStarted,\n onWorkStopped: onWorkStopped\n };\n }\n }\n}\nfunction unstable_unsubscribe(subscriber) {\n {\n subscribers.delete(subscriber);\n\n if (subscribers.size === 0) {\n exports.__subscriberRef.current = null;\n }\n }\n}\n\nfunction onInteractionTraced(interaction) {\n var didCatchError = false;\n var caughtError = null;\n subscribers.forEach(function (subscriber) {\n try {\n subscriber.onInteractionTraced(interaction);\n } catch (error) {\n if (!didCatchError) {\n didCatchError = true;\n caughtError = error;\n }\n }\n });\n\n if (didCatchError) {\n throw caughtError;\n }\n}\n\nfunction onInteractionScheduledWorkCompleted(interaction) {\n var didCatchError = false;\n var caughtError = null;\n subscribers.forEach(function (subscriber) {\n try {\n subscriber.onInteractionScheduledWorkCompleted(interaction);\n } catch (error) {\n if (!didCatchError) {\n didCatchError = true;\n caughtError = error;\n }\n }\n });\n\n if (didCatchError) {\n throw caughtError;\n }\n}\n\nfunction onWorkScheduled(interactions, threadID) {\n var didCatchError = false;\n var caughtError = null;\n subscribers.forEach(function (subscriber) {\n try {\n subscriber.onWorkScheduled(interactions, threadID);\n } catch (error) {\n if (!didCatchError) {\n didCatchError = true;\n caughtError = error;\n }\n }\n });\n\n if (didCatchError) {\n throw caughtError;\n }\n}\n\nfunction onWorkStarted(interactions, threadID) {\n var didCatchError = false;\n var caughtError = null;\n subscribers.forEach(function (subscriber) {\n try {\n subscriber.onWorkStarted(interactions, threadID);\n } catch (error) {\n if (!didCatchError) {\n didCatchError = true;\n caughtError = error;\n }\n }\n });\n\n if (didCatchError) {\n throw caughtError;\n }\n}\n\nfunction onWorkStopped(interactions, threadID) {\n var didCatchError = false;\n var caughtError = null;\n subscribers.forEach(function (subscriber) {\n try {\n subscriber.onWorkStopped(interactions, threadID);\n } catch (error) {\n if (!didCatchError) {\n didCatchError = true;\n caughtError = error;\n }\n }\n });\n\n if (didCatchError) {\n throw caughtError;\n }\n}\n\nfunction onWorkCanceled(interactions, threadID) {\n var didCatchError = false;\n var caughtError = null;\n subscribers.forEach(function (subscriber) {\n try {\n subscriber.onWorkCanceled(interactions, threadID);\n } catch (error) {\n if (!didCatchError) {\n didCatchError = true;\n caughtError = error;\n }\n }\n });\n\n if (didCatchError) {\n throw caughtError;\n }\n}\n\nexports.unstable_clear = unstable_clear;\nexports.unstable_getCurrent = unstable_getCurrent;\nexports.unstable_getThreadID = unstable_getThreadID;\nexports.unstable_subscribe = unstable_subscribe;\nexports.unstable_trace = unstable_trace;\nexports.unstable_unsubscribe = unstable_unsubscribe;\nexports.unstable_wrap = unstable_wrap;\n })();\n}\n\n\n//# sourceURL=webpack:///./node_modules/scheduler/cjs/scheduler-tracing.development.js?");
/***/ }),
/***/ "./node_modules/scheduler/cjs/scheduler.development.js":
/*!*************************************************************!*\
!*** ./node_modules/scheduler/cjs/scheduler.development.js ***!
\*************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
eval("/** @license React v0.19.1\n * scheduler.development.js\n *\n * Copyright (c) Facebook, Inc. and its affiliates.\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\n\n\n\nif (true) {\n (function() {\n'use strict';\n\nvar enableSchedulerDebugging = false;\nvar enableProfiling = true;\n\nvar requestHostCallback;\nvar requestHostTimeout;\nvar cancelHostTimeout;\nvar shouldYieldToHost;\nvar requestPaint;\n\nif ( // If Scheduler runs in a non-DOM environment, it falls back to a naive\n// implementation using setTimeout.\ntypeof window === 'undefined' || // Check if MessageChannel is supported, too.\ntypeof MessageChannel !== 'function') {\n // If this accidentally gets imported in a non-browser environment, e.g. JavaScriptCore,\n // fallback to a naive implementation.\n var _callback = null;\n var _timeoutID = null;\n\n var _flushCallback = function () {\n if (_callback !== null) {\n try {\n var currentTime = exports.unstable_now();\n var hasRemainingTime = true;\n\n _callback(hasRemainingTime, currentTime);\n\n _callback = null;\n } catch (e) {\n setTimeout(_flushCallback, 0);\n throw e;\n }\n }\n };\n\n var initialTime = Date.now();\n\n exports.unstable_now = function () {\n return Date.now() - initialTime;\n };\n\n requestHostCallback = function (cb) {\n if (_callback !== null) {\n // Protect against re-entrancy.\n setTimeout(requestHostCallback, 0, cb);\n } else {\n _callback = cb;\n setTimeout(_flushCallback, 0);\n }\n };\n\n requestHostTimeout = function (cb, ms) {\n _timeoutID = setTimeout(cb, ms);\n };\n\n cancelHostTimeout = function () {\n clearTimeout(_timeoutID);\n };\n\n shouldYieldToHost = function () {\n return false;\n };\n\n requestPaint = exports.unstable_forceFrameRate = function () {};\n} else {\n // Capture local references to native APIs, in case a polyfill overrides them.\n var performance = window.performance;\n var _Date = window.Date;\n var _setTimeout = window.setTimeout;\n var _clearTimeout = window.clearTimeout;\n\n if (typeof console !== 'undefined') {\n // TODO: Scheduler no longer requires these methods to be polyfilled. But\n // maybe we want to continue warning if they don't exist, to preserve the\n // option to rely on it in the future?\n var requestAnimationFrame = window.requestAnimationFrame;\n var cancelAnimationFrame = window.cancelAnimationFrame; // TODO: Remove fb.me link\n\n if (typeof requestAnimationFrame !== 'function') {\n // Using console['error'] to evade Babel and ESLint\n console['error'](\"This browser doesn't support requestAnimationFrame. \" + 'Make sure that you load a ' + 'polyfill in older browsers. https://fb.me/react-polyfills');\n }\n\n if (typeof cancelAnimationFrame !== 'function') {\n // Using console['error'] to evade Babel and ESLint\n console['error'](\"This browser doesn't support cancelAnimationFrame. \" + 'Make sure that you load a ' + 'polyfill in older browsers. https://fb.me/react-polyfills');\n }\n }\n\n if (typeof performance === 'object' && typeof performance.now === 'function') {\n exports.unstable_now = function () {\n return performance.now();\n };\n } else {\n var _initialTime = _Date.now();\n\n exports.unstable_now = function () {\n return _Date.now() - _initialTime;\n };\n }\n\n var isMessageLoopRunning = false;\n var scheduledHostCallback = null;\n var taskTimeoutID = -1; // Scheduler periodically yields in case there is other work on the main\n // thread, like user events. By default, it yields multiple times per frame.\n // It does not attempt to align with frame boundaries, since most tasks don't\n // need to be frame aligned; for those that do, use requestAnimationFrame.\n\n var yieldInterval = 5;\n var deadline = 0; // TODO: Make this configurable\n\n {\n // `isInputPending` is not available. Since we have no way of knowing if\n // there's pending input, always yield at the end of the frame.\n shouldYieldToHost = function () {\n return exports.unstable_now() >= deadline;\n }; // Since we yield every frame regardless, `requestPaint` has no effect.\n\n\n requestPaint = function () {};\n }\n\n exports.unstable_forceFrameRate = function (fps) {\n if (fps < 0 || fps > 125) {\n // Using console['error'] to evade Babel and ESLint\n console['error']('forceFrameRate takes a positive int between 0 and 125, ' + 'forcing framerates higher than 125 fps is not unsupported');\n return;\n }\n\n if (fps > 0) {\n yieldInterval = Math.floor(1000 / fps);\n } else {\n // reset the framerate\n yieldInterval = 5;\n }\n };\n\n var performWorkUntilDeadline = function () {\n if (scheduledHostCallback !== null) {\n var currentTime = exports.unstable_now(); // Yield after `yieldInterval` ms, regardless of where we are in the vsync\n // cycle. This means there's always time remaining at the beginning of\n // the message event.\n\n deadline = currentTime + yieldInterval;\n var hasTimeRemaining = true;\n\n try {\n var hasMoreWork = scheduledHostCallback(hasTimeRemaining, currentTime);\n\n if (!hasMoreWork) {\n isMessageLoopRunning = false;\n scheduledHostCallback = null;\n } else {\n // If there's more work, schedule the next message event at the end\n // of the preceding one.\n port.postMessage(null);\n }\n } catch (error) {\n // If a scheduler task throws, exit the current browser task so the\n // error can be observed.\n port.postMessage(null);\n throw error;\n }\n } else {\n isMessageLoopRunning = false;\n } // Yielding to the browser will give it a chance to paint, so we can\n };\n\n var channel = new MessageChannel();\n var port = channel.port2;\n channel.port1.onmessage = performWorkUntilDeadline;\n\n requestHostCallback = function (callback) {\n scheduledHostCallback = callback;\n\n if (!isMessageLoopRunning) {\n isMessageLoopRunning = true;\n port.postMessage(null);\n }\n };\n\n requestHostTimeout = function (callback, ms) {\n taskTimeoutID = _setTimeout(function () {\n callback(exports.unstable_now());\n }, ms);\n };\n\n cancelHostTimeout = function () {\n _clearTimeout(taskTimeoutID);\n\n taskTimeoutID = -1;\n };\n}\n\nfunction push(heap, node) {\n var index = heap.length;\n heap.push(node);\n siftUp(heap, node, index);\n}\nfunction peek(heap) {\n var first = heap[0];\n return first === undefined ? null : first;\n}\nfunction pop(heap) {\n var first = heap[0];\n\n if (first !== undefined) {\n var last = heap.pop();\n\n if (last !== first) {\n heap[0] = last;\n siftDown(heap, last, 0);\n }\n\n return first;\n } else {\n return null;\n }\n}\n\nfunction siftUp(heap, node, i) {\n var index = i;\n\n while (true) {\n var parentIndex = index - 1 >>> 1;\n var parent = heap[parentIndex];\n\n if (parent !== undefined && compare(parent, node) > 0) {\n // The parent is larger. Swap positions.\n heap[parentIndex] = node;\n heap[index] = parent;\n index = parentIndex;\n } else {\n // The parent is smaller. Exit.\n return;\n }\n }\n}\n\nfunction siftDown(heap, node, i) {\n var index = i;\n var length = heap.length;\n\n while (index < length) {\n var leftIndex = (index + 1) * 2 - 1;\n var left = heap[leftIndex];\n var rightIndex = leftIndex + 1;\n var right = heap[rightIndex]; // If the left or right node is smaller, swap with the smaller of those.\n\n if (left !== undefined && compare(left, node) < 0) {\n if (right !== undefined && compare(right, left) < 0) {\n heap[index] = right;\n heap[rightIndex] = node;\n index = rightIndex;\n } else {\n heap[index] = left;\n heap[leftIndex] = node;\n index = leftIndex;\n }\n } else if (right !== undefined && compare(right, node) < 0) {\n heap[index] = right;\n heap[rightIndex] = node;\n index = rightIndex;\n } else {\n // Neither child is smaller. Exit.\n return;\n }\n }\n}\n\nfunction compare(a, b) {\n // Compare sort index first, then task id.\n var diff = a.sortIndex - b.sortIndex;\n return diff !== 0 ? diff : a.id - b.id;\n}\n\n// TODO: Use symbols?\nvar NoPriority = 0;\nvar ImmediatePriority = 1;\nvar UserBlockingPriority = 2;\nvar NormalPriority = 3;\nvar LowPriority = 4;\nvar IdlePriority = 5;\n\nvar runIdCounter = 0;\nvar mainThreadIdCounter = 0;\nvar profilingStateSize = 4;\nvar sharedProfilingBuffer = // $FlowFixMe Flow doesn't know about SharedArrayBuffer\ntypeof SharedArrayBuffer === 'function' ? new SharedArrayBuffer(profilingStateSize * Int32Array.BYTES_PER_ELEMENT) : // $FlowFixMe Flow doesn't know about ArrayBuffer\ntypeof ArrayBuffer === 'function' ? new ArrayBuffer(profilingStateSize * Int32Array.BYTES_PER_ELEMENT) : null // Don't crash the init path on IE9\n;\nvar profilingState = sharedProfilingBuffer !== null ? new Int32Array(sharedProfilingBuffer) : []; // We can't read this but it helps save bytes for null checks\n\nvar PRIORITY = 0;\nvar CURRENT_TASK_ID = 1;\nvar CURRENT_RUN_ID = 2;\nvar QUEUE_SIZE = 3;\n\n{\n profilingState[PRIORITY] = NoPriority; // This is maintained with a counter, because the size of the priority queue\n // array might include canceled tasks.\n\n profilingState[QUEUE_SIZE] = 0;\n profilingState[CURRENT_TASK_ID] = 0;\n} // Bytes per element is 4\n\n\nvar INITIAL_EVENT_LOG_SIZE = 131072;\nvar MAX_EVENT_LOG_SIZE = 524288; // Equivalent to 2 megabytes\n\nvar eventLogSize = 0;\nvar eventLogBuffer = null;\nvar eventLog = null;\nvar eventLogIndex = 0;\nvar TaskStartEvent = 1;\nvar TaskCompleteEvent = 2;\nvar TaskErrorEvent = 3;\nvar TaskCancelEvent = 4;\nvar TaskRunEvent = 5;\nvar TaskYieldEvent = 6;\nvar SchedulerSuspendEvent = 7;\nvar SchedulerResumeEvent = 8;\n\nfunction logEvent(entries) {\n if (eventLog !== null) {\n var offset = eventLogIndex;\n eventLogIndex += entries.length;\n\n if (eventLogIndex + 1 > eventLogSize) {\n eventLogSize *= 2;\n\n if (eventLogSize > MAX_EVENT_LOG_SIZE) {\n // Using console['error'] to evade Babel and ESLint\n console['error'](\"Scheduler Profiling: Event log exceeded maximum size. Don't \" + 'forget to call `stopLoggingProfilingEvents()`.');\n stopLoggingProfilingEvents();\n return;\n }\n\n var newEventLog = new Int32Array(eventLogSize * 4);\n newEventLog.set(eventLog);\n eventLogBuffer = newEventLog.buffer;\n eventLog = newEventLog;\n }\n\n eventLog.set(entries, offset);\n }\n}\n\nfunction startLoggingProfilingEvents() {\n eventLogSize = INITIAL_EVENT_LOG_SIZE;\n eventLogBuffer = new ArrayBuffer(eventLogSize * 4);\n eventLog = new Int32Array(eventLogBuffer);\n eventLogIndex = 0;\n}\nfunction stopLoggingProfilingEvents() {\n var buffer = eventLogBuffer;\n eventLogSize = 0;\n eventLogBuffer = null;\n eventLog = null;\n eventLogIndex = 0;\n return buffer;\n}\nfunction markTaskStart(task, ms) {\n {\n profilingState[QUEUE_SIZE]++;\n\n if (eventLog !== null) {\n // performance.now returns a float, representing milliseconds. When the\n // event is logged, it's coerced to an int. Convert to microseconds to\n // maintain extra degrees of precision.\n logEvent([TaskStartEvent, ms * 1000, task.id, task.priorityLevel]);\n }\n }\n}\nfunction markTaskCompleted(task, ms) {\n {\n profilingState[PRIORITY] = NoPriority;\n profilingState[CURRENT_TASK_ID] = 0;\n profilingState[QUEUE_SIZE]--;\n\n if (eventLog !== null) {\n logEvent([TaskCompleteEvent, ms * 1000, task.id]);\n }\n }\n}\nfunction markTaskCanceled(task, ms) {\n {\n profilingState[QUEUE_SIZE]--;\n\n if (eventLog !== null) {\n logEvent([TaskCancelEvent, ms * 1000, task.id]);\n }\n }\n}\nfunction markTaskErrored(task, ms) {\n {\n profilingState[PRIORITY] = NoPriority;\n profilingState[CURRENT_TASK_ID] = 0;\n profilingState[QUEUE_SIZE]--;\n\n if (eventLog !== null) {\n logEvent([TaskErrorEvent, ms * 1000, task.id]);\n }\n }\n}\nfunction markTaskRun(task, ms) {\n {\n runIdCounter++;\n profilingState[PRIORITY] = task.priorityLevel;\n profilingState[CURRENT_TASK_ID] = task.id;\n profilingState[CURRENT_RUN_ID] = runIdCounter;\n\n if (eventLog !== null) {\n logEvent([TaskRunEvent, ms * 1000, task.id, runIdCounter]);\n }\n }\n}\nfunction markTaskYield(task, ms) {\n {\n profilingState[PRIORITY] = NoPriority;\n profilingState[CURRENT_TASK_ID] = 0;\n profilingState[CURRENT_RUN_ID] = 0;\n\n if (eventLog !== null) {\n logEvent([TaskYieldEvent, ms * 1000, task.id, runIdCounter]);\n }\n }\n}\nfunction markSchedulerSuspended(ms) {\n {\n mainThreadIdCounter++;\n\n if (eventLog !== null) {\n logEvent([SchedulerSuspendEvent, ms * 1000, mainThreadIdCounter]);\n }\n }\n}\nfunction markSchedulerUnsuspended(ms) {\n {\n if (eventLog !== null) {\n logEvent([SchedulerResumeEvent, ms * 1000, mainThreadIdCounter]);\n }\n }\n}\n\n/* eslint-disable no-var */\n// Math.pow(2, 30) - 1\n// 0b111111111111111111111111111111\n\nvar maxSigned31BitInt = 1073741823; // Times out immediately\n\nvar IMMEDIATE_PRIORITY_TIMEOUT = -1; // Eventually times out\n\nvar USER_BLOCKING_PRIORITY = 250;\nvar NORMAL_PRIORITY_TIMEOUT = 5000;\nvar LOW_PRIORITY_TIMEOUT = 10000; // Never times out\n\nvar IDLE_PRIORITY = maxSigned31BitInt; // Tasks are stored on a min heap\n\nvar taskQueue = [];\nvar timerQueue = []; // Incrementing id counter. Used to maintain insertion order.\n\nvar taskIdCounter = 1; // Pausing the scheduler is useful for debugging.\nvar currentTask = null;\nvar currentPriorityLevel = NormalPriority; // This is set while performing work, to prevent re-entrancy.\n\nvar isPerformingWork = false;\nvar isHostCallbackScheduled = false;\nvar isHostTimeoutScheduled = false;\n\nfunction advanceTimers(currentTime) {\n // Check for tasks that are no longer delayed and add them to the queue.\n var timer = peek(timerQueue);\n\n while (timer !== null) {\n if (timer.callback === null) {\n // Timer was cancelled.\n pop(timerQueue);\n } else if (timer.startTime <= currentTime) {\n // Timer fired. Transfer to the task queue.\n pop(timerQueue);\n timer.sortIndex = timer.expirationTime;\n push(taskQueue, timer);\n\n {\n markTaskStart(timer, currentTime);\n timer.isQueued = true;\n }\n } else {\n // Remaining timers are pending.\n return;\n }\n\n timer = peek(timerQueue);\n }\n}\n\nfunction handleTimeout(currentTime) {\n isHostTimeoutScheduled = false;\n advanceTimers(currentTime);\n\n if (!isHostCallbackScheduled) {\n if (peek(taskQueue) !== null) {\n isHostCallbackScheduled = true;\n requestHostCallback(flushWork);\n } else {\n var firstTimer = peek(timerQueue);\n\n if (firstTimer !== null) {\n requestHostTimeout(handleTimeout, firstTimer.startTime - currentTime);\n }\n }\n }\n}\n\nfunction flushWork(hasTimeRemaining, initialTime) {\n {\n markSchedulerUnsuspended(initialTime);\n } // We'll need a host callback the next time work is scheduled.\n\n\n isHostCallbackScheduled = false;\n\n if (isHostTimeoutScheduled) {\n // We scheduled a timeout but it's no longer needed. Cancel it.\n isHostTimeoutScheduled = false;\n cancelHostTimeout();\n }\n\n isPerformingWork = true;\n var previousPriorityLevel = currentPriorityLevel;\n\n try {\n if (enableProfiling) {\n try {\n return workLoop(hasTimeRemaining, initialTime);\n } catch (error) {\n if (currentTask !== null) {\n var currentTime = exports.unstable_now();\n markTaskErrored(currentTask, currentTime);\n currentTask.isQueued = false;\n }\n\n throw error;\n }\n } else {\n // No catch in prod codepath.\n return workLoop(hasTimeRemaining, initialTime);\n }\n } finally {\n currentTask = null;\n currentPriorityLevel = previousPriorityLevel;\n isPerformingWork = false;\n\n {\n var _currentTime = exports.unstable_now();\n\n markSchedulerSuspended(_currentTime);\n }\n }\n}\n\nfunction workLoop(hasTimeRemaining, initialTime) {\n var currentTime = initialTime;\n advanceTimers(currentTime);\n currentTask = peek(taskQueue);\n\n while (currentTask !== null && !(enableSchedulerDebugging )) {\n if (currentTask.expirationTime > currentTime && (!hasTimeRemaining || shouldYieldToHost())) {\n // This currentTask hasn't expired, and we've reached the deadline.\n break;\n }\n\n var callback = currentTask.callback;\n\n if (callback !== null) {\n currentTask.callback = null;\n currentPriorityLevel = currentTask.priorityLevel;\n var didUserCallbackTimeout = currentTask.expirationTime <= currentTime;\n markTaskRun(currentTask, currentTime);\n var continuationCallback = callback(didUserCallbackTimeout);\n currentTime = exports.unstable_now();\n\n if (typeof continuationCallback === 'function') {\n currentTask.callback = continuationCallback;\n markTaskYield(currentTask, currentTime);\n } else {\n {\n markTaskCompleted(currentTask, currentTime);\n currentTask.isQueued = false;\n }\n\n if (currentTask === peek(taskQueue)) {\n pop(taskQueue);\n }\n }\n\n advanceTimers(currentTime);\n } else {\n pop(taskQueue);\n }\n\n currentTask = peek(taskQueue);\n } // Return whether there's additional work\n\n\n if (currentTask !== null) {\n return true;\n } else {\n var firstTimer = peek(timerQueue);\n\n if (firstTimer !== null) {\n requestHostTimeout(handleTimeout, firstTimer.startTime - currentTime);\n }\n\n return false;\n }\n}\n\nfunction unstable_runWithPriority(priorityLevel, eventHandler) {\n switch (priorityLevel) {\n case ImmediatePriority:\n case UserBlockingPriority:\n case NormalPriority:\n case LowPriority:\n case IdlePriority:\n break;\n\n default:\n priorityLevel = NormalPriority;\n }\n\n var previousPriorityLevel = currentPriorityLevel;\n currentPriorityLevel = priorityLevel;\n\n try {\n return eventHandler();\n } finally {\n currentPriorityLevel = previousPriorityLevel;\n }\n}\n\nfunction unstable_next(eventHandler) {\n var priorityLevel;\n\n switch (currentPriorityLevel) {\n case ImmediatePriority:\n case UserBlockingPriority:\n case NormalPriority:\n // Shift down to normal priority\n priorityLevel = NormalPriority;\n break;\n\n default:\n // Anything lower than normal priority should remain at the current level.\n priorityLevel = currentPriorityLevel;\n break;\n }\n\n var previousPriorityLevel = currentPriorityLevel;\n currentPriorityLevel = priorityLevel;\n\n try {\n return eventHandler();\n } finally {\n currentPriorityLevel = previousPriorityLevel;\n }\n}\n\nfunction unstable_wrapCallback(callback) {\n var parentPriorityLevel = currentPriorityLevel;\n return function () {\n // This is a fork of runWithPriority, inlined for performance.\n var previousPriorityLevel = currentPriorityLevel;\n currentPriorityLevel = parentPriorityLevel;\n\n try {\n return callback.apply(this, arguments);\n } finally {\n currentPriorityLevel = previousPriorityLevel;\n }\n };\n}\n\nfunction timeoutForPriorityLevel(priorityLevel) {\n switch (priorityLevel) {\n case ImmediatePriority:\n return IMMEDIATE_PRIORITY_TIMEOUT;\n\n case UserBlockingPriority:\n return USER_BLOCKING_PRIORITY;\n\n case IdlePriority:\n return IDLE_PRIORITY;\n\n case LowPriority:\n return LOW_PRIORITY_TIMEOUT;\n\n case NormalPriority:\n default:\n return NORMAL_PRIORITY_TIMEOUT;\n }\n}\n\nfunction unstable_scheduleCallback(priorityLevel, callback, options) {\n var currentTime = exports.unstable_now();\n var startTime;\n var timeout;\n\n if (typeof options === 'object' && options !== null) {\n var delay = options.delay;\n\n if (typeof delay === 'number' && delay > 0) {\n startTime = currentTime + delay;\n } else {\n startTime = currentTime;\n }\n\n timeout = typeof options.timeout === 'number' ? options.timeout : timeoutForPriorityLevel(priorityLevel);\n } else {\n timeout = timeoutForPriorityLevel(priorityLevel);\n startTime = currentTime;\n }\n\n var expirationTime = startTime + timeout;\n var newTask = {\n id: taskIdCounter++,\n callback: callback,\n priorityLevel: priorityLevel,\n startTime: startTime,\n expirationTime: expirationTime,\n sortIndex: -1\n };\n\n {\n newTask.isQueued = false;\n }\n\n if (startTime > currentTime) {\n // This is a delayed task.\n newTask.sortIndex = startTime;\n push(timerQueue, newTask);\n\n if (peek(taskQueue) === null && newTask === peek(timerQueue)) {\n // All tasks are delayed, and this is the task with the earliest delay.\n if (isHostTimeoutScheduled) {\n // Cancel an existing timeout.\n cancelHostTimeout();\n } else {\n isHostTimeoutScheduled = true;\n } // Schedule a timeout.\n\n\n requestHostTimeout(handleTimeout, startTime - currentTime);\n }\n } else {\n newTask.sortIndex = expirationTime;\n push(taskQueue, newTask);\n\n {\n markTaskStart(newTask, currentTime);\n newTask.isQueued = true;\n } // Schedule a host callback, if needed. If we're already performing work,\n // wait until the next time we yield.\n\n\n if (!isHostCallbackScheduled && !isPerformingWork) {\n isHostCallbackScheduled = true;\n requestHostCallback(flushWork);\n }\n }\n\n return newTask;\n}\n\nfunction unstable_pauseExecution() {\n}\n\nfunction unstable_continueExecution() {\n\n if (!isHostCallbackScheduled && !isPerformingWork) {\n isHostCallbackScheduled = true;\n requestHostCallback(flushWork);\n }\n}\n\nfunction unstable_getFirstCallbackNode() {\n return peek(taskQueue);\n}\n\nfunction unstable_cancelCallback(task) {\n {\n if (task.isQueued) {\n var currentTime = exports.unstable_now();\n markTaskCanceled(task, currentTime);\n task.isQueued = false;\n }\n } // Null out the callback to indicate the task has been canceled. (Can't\n // remove from the queue because you can't remove arbitrary nodes from an\n // array based heap, only the first one.)\n\n\n task.callback = null;\n}\n\nfunction unstable_getCurrentPriorityLevel() {\n return currentPriorityLevel;\n}\n\nfunction unstable_shouldYield() {\n var currentTime = exports.unstable_now();\n advanceTimers(currentTime);\n var firstTask = peek(taskQueue);\n return firstTask !== currentTask && currentTask !== null && firstTask !== null && firstTask.callback !== null && firstTask.startTime <= currentTime && firstTask.expirationTime < currentTask.expirationTime || shouldYieldToHost();\n}\n\nvar unstable_requestPaint = requestPaint;\nvar unstable_Profiling = {\n startLoggingProfilingEvents: startLoggingProfilingEvents,\n stopLoggingProfilingEvents: stopLoggingProfilingEvents,\n sharedProfilingBuffer: sharedProfilingBuffer\n} ;\n\nexports.unstable_IdlePriority = IdlePriority;\nexports.unstable_ImmediatePriority = ImmediatePriority;\nexports.unstable_LowPriority = LowPriority;\nexports.unstable_NormalPriority = NormalPriority;\nexports.unstable_Profiling = unstable_Profiling;\nexports.unstable_UserBlockingPriority = UserBlockingPriority;\nexports.unstable_cancelCallback = unstable_cancelCallback;\nexports.unstable_continueExecution = unstable_continueExecution;\nexports.unstable_getCurrentPriorityLevel = unstable_getCurrentPriorityLevel;\nexports.unstable_getFirstCallbackNode = unstable_getFirstCallbackNode;\nexports.unstable_next = unstable_next;\nexports.unstable_pauseExecution = unstable_pauseExecution;\nexports.unstable_requestPaint = unstable_requestPaint;\nexports.unstable_runWithPriority = unstable_runWithPriority;\nexports.unstable_scheduleCallback = unstable_scheduleCallback;\nexports.unstable_shouldYield = unstable_shouldYield;\nexports.unstable_wrapCallback = unstable_wrapCallback;\n })();\n}\n\n\n//# sourceURL=webpack:///./node_modules/scheduler/cjs/scheduler.development.js?");
/***/ }),
/***/ "./node_modules/scheduler/index.js":
/*!*****************************************!*\
!*** ./node_modules/scheduler/index.js ***!
\*****************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
eval("\n\nif (false) {} else {\n module.exports = __webpack_require__(/*! ./cjs/scheduler.development.js */ \"./node_modules/scheduler/cjs/scheduler.development.js\");\n}\n\n\n//# sourceURL=webpack:///./node_modules/scheduler/index.js?");
/***/ }),
/***/ "./node_modules/scheduler/tracing.js":
/*!*******************************************!*\
!*** ./node_modules/scheduler/tracing.js ***!
\*******************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
eval("\n\nif (false) {} else {\n module.exports = __webpack_require__(/*! ./cjs/scheduler-tracing.development.js */ \"./node_modules/scheduler/cjs/scheduler-tracing.development.js\");\n}\n\n\n//# sourceURL=webpack:///./node_modules/scheduler/tracing.js?");
/***/ }),
/***/ "./node_modules/style-loader/dist/runtime/injectStylesIntoStyleTag.js":
/*!****************************************************************************!*\
!*** ./node_modules/style-loader/dist/runtime/injectStylesIntoStyleTag.js ***!
\****************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
eval("\n\nvar isOldIE = function isOldIE() {\n var memo;\n return function memorize() {\n if (typeof memo === 'undefined') {\n // Test for IE <= 9 as proposed by Browserhacks\n // @see http://browserhacks.com/#hack-e71d8692f65334173fee715c222cb805\n // Tests for existence of standard globals is to allow style-loader\n // to operate correctly into non-standard environments\n // @see https://github.com/webpack-contrib/style-loader/issues/177\n memo = Boolean(window && document && document.all && !window.atob);\n }\n\n return memo;\n };\n}();\n\nvar getTarget = function getTarget() {\n var memo = {};\n return function memorize(target) {\n if (typeof memo[target] === 'undefined') {\n var styleTarget = document.querySelector(target); // Special case to return head of iframe instead of iframe itself\n\n if (window.HTMLIFrameElement && styleTarget instanceof window.HTMLIFrameElement) {\n try {\n // This will throw an exception if access to iframe is blocked\n // due to cross-origin restrictions\n styleTarget = styleTarget.contentDocument.head;\n } catch (e) {\n // istanbul ignore next\n styleTarget = null;\n }\n }\n\n memo[target] = styleTarget;\n }\n\n return memo[target];\n };\n}();\n\nvar stylesInDom = [];\n\nfunction getIndexByIdentifier(identifier) {\n var result = -1;\n\n for (var i = 0; i < stylesInDom.length; i++) {\n if (stylesInDom[i].identifier === identifier) {\n result = i;\n break;\n }\n }\n\n return result;\n}\n\nfunction modulesToDom(list, options) {\n var idCountMap = {};\n var identifiers = [];\n\n for (var i = 0; i < list.length; i++) {\n var item = list[i];\n var id = options.base ? item[0] + options.base : item[0];\n var count = idCountMap[id] || 0;\n var identifier = \"\".concat(id, \" \").concat(count);\n idCountMap[id] = count + 1;\n var index = getIndexByIdentifier(identifier);\n var obj = {\n css: item[1],\n media: item[2],\n sourceMap: item[3]\n };\n\n if (index !== -1) {\n stylesInDom[index].references++;\n stylesInDom[index].updater(obj);\n } else {\n stylesInDom.push({\n identifier: identifier,\n updater: addStyle(obj, options),\n references: 1\n });\n }\n\n identifiers.push(identifier);\n }\n\n return identifiers;\n}\n\nfunction insertStyleElement(options) {\n var style = document.createElement('style');\n var attributes = options.attributes || {};\n\n if (typeof attributes.nonce === 'undefined') {\n var nonce = true ? __webpack_require__.nc : undefined;\n\n if (nonce) {\n attributes.nonce = nonce;\n }\n }\n\n Object.keys(attributes).forEach(function (key) {\n style.setAttribute(key, attributes[key]);\n });\n\n if (typeof options.insert === 'function') {\n options.insert(style);\n } else {\n var target = getTarget(options.insert || 'head');\n\n if (!target) {\n throw new Error(\"Couldn't find a style target. This probably means that the value for the 'insert' parameter is invalid.\");\n }\n\n target.appendChild(style);\n }\n\n return style;\n}\n\nfunction removeStyleElement(style) {\n // istanbul ignore if\n if (style.parentNode === null) {\n return false;\n }\n\n style.parentNode.removeChild(style);\n}\n/* istanbul ignore next */\n\n\nvar replaceText = function replaceText() {\n var textStore = [];\n return function replace(index, replacement) {\n textStore[index] = replacement;\n return textStore.filter(Boolean).join('\\n');\n };\n}();\n\nfunction applyToSingletonTag(style, index, remove, obj) {\n var css = remove ? '' : obj.media ? \"@media \".concat(obj.media, \" {\").concat(obj.css, \"}\") : obj.css; // For old IE\n\n /* istanbul ignore if */\n\n if (style.styleSheet) {\n style.styleSheet.cssText = replaceText(index, css);\n } else {\n var cssNode = document.createTextNode(css);\n var childNodes = style.childNodes;\n\n if (childNodes[index]) {\n style.removeChild(childNodes[index]);\n }\n\n if (childNodes.length) {\n style.insertBefore(cssNode, childNodes[index]);\n } else {\n style.appendChild(cssNode);\n }\n }\n}\n\nfunction applyToTag(style, options, obj) {\n var css = obj.css;\n var media = obj.media;\n var sourceMap = obj.sourceMap;\n\n if (media) {\n style.setAttribute('media', media);\n } else {\n style.removeAttribute('media');\n }\n\n if (sourceMap && btoa) {\n css += \"\\n/*# sourceMappingURL=data:application/json;base64,\".concat(btoa(unescape(encodeURIComponent(JSON.stringify(sourceMap)))), \" */\");\n } // For old IE\n\n /* istanbul ignore if */\n\n\n if (style.styleSheet) {\n style.styleSheet.cssText = css;\n } else {\n while (style.firstChild) {\n style.removeChild(style.firstChild);\n }\n\n style.appendChild(document.createTextNode(css));\n }\n}\n\nvar singleton = null;\nvar singletonCounter = 0;\n\nfunction addStyle(obj, options) {\n var style;\n var update;\n var remove;\n\n if (options.singleton) {\n var styleIndex = singletonCounter++;\n style = singleton || (singleton = insertStyleElement(options));\n update = applyToSingletonTag.bind(null, style, styleIndex, false);\n remove = applyToSingletonTag.bind(null, style, styleIndex, true);\n } else {\n style = insertStyleElement(options);\n update = applyToTag.bind(null, style, options);\n\n remove = function remove() {\n removeStyleElement(style);\n };\n }\n\n update(obj);\n return function updateStyle(newObj) {\n if (newObj) {\n if (newObj.css === obj.css && newObj.media === obj.media && newObj.sourceMap === obj.sourceMap) {\n return;\n }\n\n update(obj = newObj);\n } else {\n remove();\n }\n };\n}\n\nmodule.exports = function (list, options) {\n options = options || {}; // Force single-tag solution on IE6-9, which has a hard limit on the # of <style>\n // tags it will allow on a page\n\n if (!options.singleton && typeof options.singleton !== 'boolean') {\n options.singleton = isOldIE();\n }\n\n list = list || [];\n var lastIdentifiers = modulesToDom(list, options);\n return function update(newList) {\n newList = newList || [];\n\n if (Object.prototype.toString.call(newList) !== '[object Array]') {\n return;\n }\n\n for (var i = 0; i < lastIdentifiers.length; i++) {\n var identifier = lastIdentifiers[i];\n var index = getIndexByIdentifier(identifier);\n stylesInDom[index].references--;\n }\n\n var newLastIdentifiers = modulesToDom(newList, options);\n\n for (var _i = 0; _i < lastIdentifiers.length; _i++) {\n var _identifier = lastIdentifiers[_i];\n\n var _index = getIndexByIdentifier(_identifier);\n\n if (stylesInDom[_index].references === 0) {\n stylesInDom[_index].updater();\n\n stylesInDom.splice(_index, 1);\n }\n }\n\n lastIdentifiers = newLastIdentifiers;\n };\n};\n\n//# sourceURL=webpack:///./node_modules/style-loader/dist/runtime/injectStylesIntoStyleTag.js?");
/***/ }),
/***/ "./node_modules/tiny-invariant/dist/tiny-invariant.esm.js":
/*!****************************************************************!*\
!*** ./node_modules/tiny-invariant/dist/tiny-invariant.esm.js ***!
\****************************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
eval("__webpack_require__.r(__webpack_exports__);\nvar isProduction = \"development\" === 'production';\nvar prefix = 'Invariant failed';\nfunction invariant(condition, message) {\n if (condition) {\n return;\n }\n if (isProduction) {\n throw new Error(prefix);\n }\n throw new Error(prefix + \": \" + (message || ''));\n}\n\n/* harmony default export */ __webpack_exports__[\"default\"] = (invariant);\n\n\n//# sourceURL=webpack:///./node_modules/tiny-invariant/dist/tiny-invariant.esm.js?");
/***/ }),
/***/ "./node_modules/tiny-warning/dist/tiny-warning.esm.js":
/*!************************************************************!*\
!*** ./node_modules/tiny-warning/dist/tiny-warning.esm.js ***!
\************************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
eval("__webpack_require__.r(__webpack_exports__);\nvar isProduction = \"development\" === '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\n/* harmony default export */ __webpack_exports__[\"default\"] = (warning);\n\n\n//# sourceURL=webpack:///./node_modules/tiny-warning/dist/tiny-warning.esm.js?");
/***/ }),
/***/ "./node_modules/uuid/lib/bytesToUuid.js":
/*!**********************************************!*\
!*** ./node_modules/uuid/lib/bytesToUuid.js ***!
\**********************************************/
/*! no static exports found */
/***/ (function(module, exports) {
eval("/**\n * Convert array of 16 byte values to UUID string format of the form:\n * XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX\n */\nvar byteToHex = [];\nfor (var i = 0; i < 256; ++i) {\n byteToHex[i] = (i + 0x100).toString(16).substr(1);\n}\n\nfunction bytesToUuid(buf, offset) {\n var i = offset || 0;\n var bth = byteToHex;\n // join used to fix memory issue caused by concatenation: https://bugs.chromium.org/p/v8/issues/detail?id=3175#c4\n return ([\n bth[buf[i++]], bth[buf[i++]],\n bth[buf[i++]], bth[buf[i++]], '-',\n bth[buf[i++]], bth[buf[i++]], '-',\n bth[buf[i++]], bth[buf[i++]], '-',\n bth[buf[i++]], bth[buf[i++]], '-',\n bth[buf[i++]], bth[buf[i++]],\n bth[buf[i++]], bth[buf[i++]],\n bth[buf[i++]], bth[buf[i++]]\n ]).join('');\n}\n\nmodule.exports = bytesToUuid;\n\n\n//# sourceURL=webpack:///./node_modules/uuid/lib/bytesToUuid.js?");
/***/ }),
/***/ "./node_modules/uuid/lib/rng-browser.js":
/*!**********************************************!*\
!*** ./node_modules/uuid/lib/rng-browser.js ***!
\**********************************************/
/*! no static exports found */
/***/ (function(module, exports) {
eval("// Unique ID creation requires a high quality random # generator. In the\n// browser this is a little complicated due to unknown quality of Math.random()\n// and inconsistent support for the `crypto` API. We do the best we can via\n// feature-detection\n\n// getRandomValues needs to be invoked in a context where \"this\" is a Crypto\n// implementation. Also, find the complete implementation of crypto on IE11.\nvar getRandomValues = (typeof(crypto) != 'undefined' && crypto.getRandomValues && crypto.getRandomValues.bind(crypto)) ||\n (typeof(msCrypto) != 'undefined' && typeof window.msCrypto.getRandomValues == 'function' && msCrypto.getRandomValues.bind(msCrypto));\n\nif (getRandomValues) {\n // WHATWG crypto RNG - http://wiki.whatwg.org/wiki/Crypto\n var rnds8 = new Uint8Array(16); // eslint-disable-line no-undef\n\n module.exports = function whatwgRNG() {\n getRandomValues(rnds8);\n return rnds8;\n };\n} else {\n // Math.random()-based (RNG)\n //\n // If all else fails, use Math.random(). It's fast, but is of unspecified\n // quality.\n var rnds = new Array(16);\n\n module.exports = function mathRNG() {\n for (var i = 0, r; i < 16; i++) {\n if ((i & 0x03) === 0) r = Math.random() * 0x100000000;\n rnds[i] = r >>> ((i & 0x03) << 3) & 0xff;\n }\n\n return rnds;\n };\n}\n\n\n//# sourceURL=webpack:///./node_modules/uuid/lib/rng-browser.js?");
/***/ }),
/***/ "./node_modules/uuid/v4.js":
/*!*********************************!*\
!*** ./node_modules/uuid/v4.js ***!
\*********************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
eval("var rng = __webpack_require__(/*! ./lib/rng */ \"./node_modules/uuid/lib/rng-browser.js\");\nvar bytesToUuid = __webpack_require__(/*! ./lib/bytesToUuid */ \"./node_modules/uuid/lib/bytesToUuid.js\");\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\n\n//# sourceURL=webpack:///./node_modules/uuid/v4.js?");
/***/ }),
/***/ "./node_modules/validator/index.js":
/*!*****************************************!*\
!*** ./node_modules/validator/index.js ***!
\*****************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
eval("\n\nfunction _typeof(obj) { \"@babel/helpers - typeof\"; if (typeof Symbol === \"function\" && typeof Symbol.iterator === \"symbol\") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === \"function\" && obj.constructor === Symbol && obj !== Symbol.prototype ? \"symbol\" : typeof obj; }; } return _typeof(obj); }\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = void 0;\n\nvar _toDate = _interopRequireDefault(__webpack_require__(/*! ./lib/toDate */ \"./node_modules/validator/lib/toDate.js\"));\n\nvar _toFloat = _interopRequireDefault(__webpack_require__(/*! ./lib/toFloat */ \"./node_modules/validator/lib/toFloat.js\"));\n\nvar _toInt = _interopRequireDefault(__webpack_require__(/*! ./lib/toInt */ \"./node_modules/validator/lib/toInt.js\"));\n\nvar _toBoolean = _interopRequireDefault(__webpack_require__(/*! ./lib/toBoolean */ \"./node_modules/validator/lib/toBoolean.js\"));\n\nvar _equals = _interopRequireDefault(__webpack_require__(/*! ./lib/equals */ \"./node_modules/validator/lib/equals.js\"));\n\nvar _contains = _interopRequireDefault(__webpack_require__(/*! ./lib/contains */ \"./node_modules/validator/lib/contains.js\"));\n\nvar _matches = _interopRequireDefault(__webpack_require__(/*! ./lib/matches */ \"./node_modules/validator/lib/matches.js\"));\n\nvar _isEmail = _interopRequireDefault(__webpack_require__(/*! ./lib/isEmail */ \"./node_modules/validator/lib/isEmail.js\"));\n\nvar _isURL = _interopRequireDefault(__webpack_require__(/*! ./lib/isURL */ \"./node_modules/validator/lib/isURL.js\"));\n\nvar _isMACAddress = _interopRequireDefault(__webpack_require__(/*! ./lib/isMACAddress */ \"./node_modules/validator/lib/isMACAddress.js\"));\n\nvar _isIP = _interopRequireDefault(__webpack_require__(/*! ./lib/isIP */ \"./node_modules/validator/lib/isIP.js\"));\n\nvar _isIPRange = _interopRequireDefault(__webpack_require__(/*! ./lib/isIPRange */ \"./node_modules/validator/lib/isIPRange.js\"));\n\nvar _isFQDN = _interopRequireDefault(__webpack_require__(/*! ./lib/isFQDN */ \"./node_modules/validator/lib/isFQDN.js\"));\n\nvar _isBoolean = _interopRequireDefault(__webpack_require__(/*! ./lib/isBoolean */ \"./node_modules/validator/lib/isBoolean.js\"));\n\nvar _isLocale = _interopRequireDefault(__webpack_require__(/*! ./lib/isLocale */ \"./node_modules/validator/lib/isLocale.js\"));\n\nvar _isAlpha = _interopRequireWildcard(__webpack_require__(/*! ./lib/isAlpha */ \"./node_modules/validator/lib/isAlpha.js\"));\n\nvar _isAlphanumeric = _interopRequireWildcard(__webpack_require__(/*! ./lib/isAlphanumeric */ \"./node_modules/validator/lib/isAlphanumeric.js\"));\n\nvar _isNumeric = _interopRequireDefault(__webpack_require__(/*! ./lib/isNumeric */ \"./node_modules/validator/lib/isNumeric.js\"));\n\nvar _isPassportNumber = _interopRequireDefault(__webpack_require__(/*! ./lib/isPassportNumber */ \"./node_modules/validator/lib/isPassportNumber.js\"));\n\nvar _isPort = _interopRequireDefault(__webpack_require__(/*! ./lib/isPort */ \"./node_modules/validator/lib/isPort.js\"));\n\nvar _isLowercase = _interopRequireDefault(__webpack_require__(/*! ./lib/isLowercase */ \"./node_modules/validator/lib/isLowercase.js\"));\n\nvar _isUppercase = _interopRequireDefault(__webpack_require__(/*! ./lib/isUppercase */ \"./node_modules/validator/lib/isUppercase.js\"));\n\nvar _isAscii = _interopRequireDefault(__webpack_require__(/*! ./lib/isAscii */ \"./node_modules/validator/lib/isAscii.js\"));\n\nvar _isFullWidth = _interopRequireDefault(__webpack_require__(/*! ./lib/isFullWidth */ \"./node_modules/validator/lib/isFullWidth.js\"));\n\nvar _isHalfWidth = _interopRequireDefault(__webpack_require__(/*! ./lib/isHalfWidth */ \"./node_modules/validator/lib/isHalfWidth.js\"));\n\nvar _isVariableWidth = _interopRequireDefault(__webpack_require__(/*! ./lib/isVariableWidth */ \"./node_modules/validator/lib/isVariableWidth.js\"));\n\nvar _isMultibyte = _interopRequireDefault(__webpack_require__(/*! ./lib/isMultibyte */ \"./node_modules/validator/lib/isMultibyte.js\"));\n\nvar _isSemVer = _interopRequireDefault(__webpack_require__(/*! ./lib/isSemVer */ \"./node_modules/validator/lib/isSemVer.js\"));\n\nvar _isSurrogatePair = _interopRequireDefault(__webpack_require__(/*! ./lib/isSurrogatePair */ \"./node_modules/validator/lib/isSurrogatePair.js\"));\n\nvar _isInt = _interopRequireDefault(__webpack_require__(/*! ./lib/isInt */ \"./node_modules/validator/lib/isInt.js\"));\n\nvar _isFloat = _interopRequireWildcard(__webpack_require__(/*! ./lib/isFloat */ \"./node_modules/validator/lib/isFloat.js\"));\n\nvar _isDecimal = _interopRequireDefault(__webpack_require__(/*! ./lib/isDecimal */ \"./node_modules/validator/lib/isDecimal.js\"));\n\nvar _isHexadecimal = _interopRequireDefault(__webpack_require__(/*! ./lib/isHexadecimal */ \"./node_modules/validator/lib/isHexadecimal.js\"));\n\nvar _isOctal = _interopRequireDefault(__webpack_require__(/*! ./lib/isOctal */ \"./node_modules/validator/lib/isOctal.js\"));\n\nvar _isDivisibleBy = _interopRequireDefault(__webpack_require__(/*! ./lib/isDivisibleBy */ \"./node_modules/validator/lib/isDivisibleBy.js\"));\n\nvar _isHexColor = _interopRequireDefault(__webpack_require__(/*! ./lib/isHexColor */ \"./node_modules/validator/lib/isHexColor.js\"));\n\nvar _isRgbColor = _interopRequireDefault(__webpack_require__(/*! ./lib/isRgbColor */ \"./node_modules/validator/lib/isRgbColor.js\"));\n\nvar _isHSL = _interopRequireDefault(__webpack_require__(/*! ./lib/isHSL */ \"./node_modules/validator/lib/isHSL.js\"));\n\nvar _isISRC = _interopRequireDefault(__webpack_require__(/*! ./lib/isISRC */ \"./node_modules/validator/lib/isISRC.js\"));\n\nvar _isIBAN = _interopRequireDefault(__webpack_require__(/*! ./lib/isIBAN */ \"./node_modules/validator/lib/isIBAN.js\"));\n\nvar _isBIC = _interopRequireDefault(__webpack_require__(/*! ./lib/isBIC */ \"./node_modules/validator/lib/isBIC.js\"));\n\nvar _isMD = _interopRequireDefault(__webpack_require__(/*! ./lib/isMD5 */ \"./node_modules/validator/lib/isMD5.js\"));\n\nvar _isHash = _interopRequireDefault(__webpack_require__(/*! ./lib/isHash */ \"./node_modules/validator/lib/isHash.js\"));\n\nvar _isJWT = _interopRequireDefault(__webpack_require__(/*! ./lib/isJWT */ \"./node_modules/validator/lib/isJWT.js\"));\n\nvar _isJSON = _interopRequireDefault(__webpack_require__(/*! ./lib/isJSON */ \"./node_modules/validator/lib/isJSON.js\"));\n\nvar _isEmpty = _interopRequireDefault(__webpack_require__(/*! ./lib/isEmpty */ \"./node_modules/validator/lib/isEmpty.js\"));\n\nvar _isLength = _interopRequireDefault(__webpack_require__(/*! ./lib/isLength */ \"./node_modules/validator/lib/isLength.js\"));\n\nvar _isByteLength = _interopRequireDefault(__webpack_require__(/*! ./lib/isByteLength */ \"./node_modules/validator/lib/isByteLength.js\"));\n\nvar _isUUID = _interopRequireDefault(__webpack_require__(/*! ./lib/isUUID */ \"./node_modules/validator/lib/isUUID.js\"));\n\nvar _isMongoId = _interopRequireDefault(__webpack_require__(/*! ./lib/isMongoId */ \"./node_modules/validator/lib/isMongoId.js\"));\n\nvar _isAfter = _interopRequireDefault(__webpack_require__(/*! ./lib/isAfter */ \"./node_modules/validator/lib/isAfter.js\"));\n\nvar _isBefore = _interopRequireDefault(__webpack_require__(/*! ./lib/isBefore */ \"./node_modules/validator/lib/isBefore.js\"));\n\nvar _isIn = _interopRequireDefault(__webpack_require__(/*! ./lib/isIn */ \"./node_modules/validator/lib/isIn.js\"));\n\nvar _isCreditCard = _interopRequireDefault(__webpack_require__(/*! ./lib/isCreditCard */ \"./node_modules/validator/lib/isCreditCard.js\"));\n\nvar _isIdentityCard = _interopRequireDefault(__webpack_require__(/*! ./lib/isIdentityCard */ \"./node_modules/validator/lib/isIdentityCard.js\"));\n\nvar _isEAN = _interopRequireDefault(__webpack_require__(/*! ./lib/isEAN */ \"./node_modules/validator/lib/isEAN.js\"));\n\nvar _isISIN = _interopRequireDefault(__webpack_require__(/*! ./lib/isISIN */ \"./node_modules/validator/lib/isISIN.js\"));\n\nvar _isISBN = _interopRequireDefault(__webpack_require__(/*! ./lib/isISBN */ \"./node_modules/validator/lib/isISBN.js\"));\n\nvar _isISSN = _interopRequireDefault(__webpack_require__(/*! ./lib/isISSN */ \"./node_modules/validator/lib/isISSN.js\"));\n\nvar _isMobilePhone = _interopRequireWildcard(__webpack_require__(/*! ./lib/isMobilePhone */ \"./node_modules/validator/lib/isMobilePhone.js\"));\n\nvar _isEthereumAddress = _interopRequireDefault(__webpack_require__(/*! ./lib/isEthereumAddress */ \"./node_modules/validator/lib/isEthereumAddress.js\"));\n\nvar _isCurrency = _interopRequireDefault(__webpack_require__(/*! ./lib/isCurrency */ \"./node_modules/validator/lib/isCurrency.js\"));\n\nvar _isBtcAddress = _interopRequireDefault(__webpack_require__(/*! ./lib/isBtcAddress */ \"./node_modules/validator/lib/isBtcAddress.js\"));\n\nvar _isISO = _interopRequireDefault(__webpack_require__(/*! ./lib/isISO8601 */ \"./node_modules/validator/lib/isISO8601.js\"));\n\nvar _isRFC = _interopRequireDefault(__webpack_require__(/*! ./lib/isRFC3339 */ \"./node_modules/validator/lib/isRFC3339.js\"));\n\nvar _isISO31661Alpha = _interopRequireDefault(__webpack_require__(/*! ./lib/isISO31661Alpha2 */ \"./node_modules/validator/lib/isISO31661Alpha2.js\"));\n\nvar _isISO31661Alpha2 = _interopRequireDefault(__webpack_require__(/*! ./lib/isISO31661Alpha3 */ \"./node_modules/validator/lib/isISO31661Alpha3.js\"));\n\nvar _isBase = _interopRequireDefault(__webpack_require__(/*! ./lib/isBase32 */ \"./node_modules/validator/lib/isBase32.js\"));\n\nvar _isBase2 = _interopRequireDefault(__webpack_require__(/*! ./lib/isBase64 */ \"./node_modules/validator/lib/isBase64.js\"));\n\nvar _isDataURI = _interopRequireDefault(__webpack_require__(/*! ./lib/isDataURI */ \"./node_modules/validator/lib/isDataURI.js\"));\n\nvar _isMagnetURI = _interopRequireDefault(__webpack_require__(/*! ./lib/isMagnetURI */ \"./node_modules/validator/lib/isMagnetURI.js\"));\n\nvar _isMimeType = _interopRequireDefault(__webpack_require__(/*! ./lib/isMimeType */ \"./node_modules/validator/lib/isMimeType.js\"));\n\nvar _isLatLong = _interopRequireDefault(__webpack_require__(/*! ./lib/isLatLong */ \"./node_modules/validator/lib/isLatLong.js\"));\n\nvar _isPostalCode = _interopRequireWildcard(__webpack_require__(/*! ./lib/isPostalCode */ \"./node_modules/validator/lib/isPostalCode.js\"));\n\nvar _ltrim = _interopRequireDefault(__webpack_require__(/*! ./lib/ltrim */ \"./node_modules/validator/lib/ltrim.js\"));\n\nvar _rtrim = _interopRequireDefault(__webpack_require__(/*! ./lib/rtrim */ \"./node_modules/validator/lib/rtrim.js\"));\n\nvar _trim = _interopRequireDefault(__webpack_require__(/*! ./lib/trim */ \"./node_modules/validator/lib/trim.js\"));\n\nvar _escape = _interopRequireDefault(__webpack_require__(/*! ./lib/escape */ \"./node_modules/validator/lib/escape.js\"));\n\nvar _unescape = _interopRequireDefault(__webpack_require__(/*! ./lib/unescape */ \"./node_modules/validator/lib/unescape.js\"));\n\nvar _stripLow = _interopRequireDefault(__webpack_require__(/*! ./lib/stripLow */ \"./node_modules/validator/lib/stripLow.js\"));\n\nvar _whitelist = _interopRequireDefault(__webpack_require__(/*! ./lib/whitelist */ \"./node_modules/validator/lib/whitelist.js\"));\n\nvar _blacklist = _interopRequireDefault(__webpack_require__(/*! ./lib/blacklist */ \"./node_modules/validator/lib/blacklist.js\"));\n\nvar _isWhitelisted = _interopRequireDefault(__webpack_require__(/*! ./lib/isWhitelisted */ \"./node_modules/validator/lib/isWhitelisted.js\"));\n\nvar _normalizeEmail = _interopRequireDefault(__webpack_require__(/*! ./lib/normalizeEmail */ \"./node_modules/validator/lib/normalizeEmail.js\"));\n\nvar _isSlug = _interopRequireDefault(__webpack_require__(/*! ./lib/isSlug */ \"./node_modules/validator/lib/isSlug.js\"));\n\nfunction _getRequireWildcardCache() { if (typeof WeakMap !== \"function\") return null; var cache = new WeakMap(); _getRequireWildcardCache = function _getRequireWildcardCache() { return cache; }; return cache; }\n\nfunction _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || _typeof(obj) !== \"object\" && typeof obj !== \"function\") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\nvar version = '13.0.0';\nvar validator = {\n version: version,\n toDate: _toDate.default,\n toFloat: _toFloat.default,\n toInt: _toInt.default,\n toBoolean: _toBoolean.default,\n equals: _equals.default,\n contains: _contains.default,\n matches: _matches.default,\n isEmail: _isEmail.default,\n isURL: _isURL.default,\n isMACAddress: _isMACAddress.default,\n isIP: _isIP.default,\n isIPRange: _isIPRange.default,\n isFQDN: _isFQDN.default,\n isBoolean: _isBoolean.default,\n isIBAN: _isIBAN.default,\n isBIC: _isBIC.default,\n isAlpha: _isAlpha.default,\n isAlphaLocales: _isAlpha.locales,\n isAlphanumeric: _isAlphanumeric.default,\n isAlphanumericLocales: _isAlphanumeric.locales,\n isNumeric: _isNumeric.default,\n isPassportNumber: _isPassportNumber.default,\n isPort: _isPort.default,\n isLowercase: _isLowercase.default,\n isUppercase: _isUppercase.default,\n isAscii: _isAscii.default,\n isFullWidth: _isFullWidth.default,\n isHalfWidth: _isHalfWidth.default,\n isVariableWidth: _isVariableWidth.default,\n isMultibyte: _isMultibyte.default,\n isSemVer: _isSemVer.default,\n isSurrogatePair: _isSurrogatePair.default,\n isInt: _isInt.default,\n isFloat: _isFloat.default,\n isFloatLocales: _isFloat.locales,\n isDecimal: _isDecimal.default,\n isHexadecimal: _isHexadecimal.default,\n isOctal: _isOctal.default,\n isDivisibleBy: _isDivisibleBy.default,\n isHexColor: _isHexColor.default,\n isRgbColor: _isRgbColor.default,\n isHSL: _isHSL.default,\n isISRC: _isISRC.default,\n isMD5: _isMD.default,\n isHash: _isHash.default,\n isJWT: _isJWT.default,\n isJSON: _isJSON.default,\n isEmpty: _isEmpty.default,\n isLength: _isLength.default,\n isLocale: _isLocale.default,\n isByteLength: _isByteLength.default,\n isUUID: _isUUID.default,\n isMongoId: _isMongoId.default,\n isAfter: _isAfter.default,\n isBefore: _isBefore.default,\n isIn: _isIn.default,\n isCreditCard: _isCreditCard.default,\n isIdentityCard: _isIdentityCard.default,\n isEAN: _isEAN.default,\n isISIN: _isISIN.default,\n isISBN: _isISBN.default,\n isISSN: _isISSN.default,\n isMobilePhone: _isMobilePhone.default,\n isMobilePhoneLocales: _isMobilePhone.locales,\n isPostalCode: _isPostalCode.default,\n isPostalCodeLocales: _isPostalCode.locales,\n isEthereumAddress: _isEthereumAddress.default,\n isCurrency: _isCurrency.default,\n isBtcAddress: _isBtcAddress.default,\n isISO8601: _isISO.default,\n isRFC3339: _isRFC.default,\n isISO31661Alpha2: _isISO31661Alpha.default,\n isISO31661Alpha3: _isISO31661Alpha2.default,\n isBase32: _isBase.default,\n isBase64: _isBase2.default,\n isDataURI: _isDataURI.default,\n isMagnetURI: _isMagnetURI.default,\n isMimeType: _isMimeType.default,\n isLatLong: _isLatLong.default,\n ltrim: _ltrim.default,\n rtrim: _rtrim.default,\n trim: _trim.default,\n escape: _escape.default,\n unescape: _unescape.default,\n stripLow: _stripLow.default,\n whitelist: _whitelist.default,\n blacklist: _blacklist.default,\n isWhitelisted: _isWhitelisted.default,\n normalizeEmail: _normalizeEmail.default,\n toString: toString,\n isSlug: _isSlug.default\n};\nvar _default = validator;\nexports.default = _default;\nmodule.exports = exports.default;\nmodule.exports.default = exports.default;\n\n//# sourceURL=webpack:///./node_modules/validator/index.js?");
/***/ }),
/***/ "./node_modules/validator/lib/alpha.js":
/*!*********************************************!*\
!*** ./node_modules/validator/lib/alpha.js ***!
\*********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
eval("\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.commaDecimal = exports.dotDecimal = exports.arabicLocales = exports.englishLocales = exports.decimal = exports.alphanumeric = exports.alpha = void 0;\nvar alpha = {\n 'en-US': /^[A-Z]+$/i,\n 'bg-BG': /^[А-Я]+$/i,\n 'cs-CZ': /^[A-ZÁČĎÉĚÍŇÓŘŠŤÚŮÝŽ]+$/i,\n 'da-DK': /^[A-ZÆØÅ]+$/i,\n 'de-DE': /^[A-ZÄÖÜß]+$/i,\n 'el-GR': /^[Α-ώ]+$/i,\n 'es-ES': /^[A-ZÁÉÍÑÓÚÜ]+$/i,\n 'fr-FR': /^[A-ZÀÂÆÇÉÈÊËÏÎÔŒÙÛÜŸ]+$/i,\n 'it-IT': /^[A-ZÀÉÈÌÎÓÒÙ]+$/i,\n 'nb-NO': /^[A-ZÆØÅ]+$/i,\n 'nl-NL': /^[A-ZÁÉËÏÓÖÜÚ]+$/i,\n 'nn-NO': /^[A-ZÆØÅ]+$/i,\n 'hu-HU': /^[A-ZÁÉÍÓÖŐÚÜŰ]+$/i,\n 'pl-PL': /^[A-ZĄĆĘŚŁŃÓŻŹ]+$/i,\n 'pt-PT': /^[A-ZÃÁÀÂÄÇÉÊËÍÏÕÓÔÖÚÜ]+$/i,\n 'ru-RU': /^[А-ЯЁ]+$/i,\n 'sl-SI': /^[A-ZČĆĐŠŽ]+$/i,\n 'sk-SK': /^[A-ZÁČĎÉÍŇÓŠŤÚÝŽĹŔĽÄÔ]+$/i,\n 'sr-RS@latin': /^[A-ZČĆŽŠĐ]+$/i,\n 'sr-RS': /^[А-ЯЂЈЉЊЋЏ]+$/i,\n 'sv-SE': /^[A-ZÅÄÖ]+$/i,\n 'tr-TR': /^[A-ZÇĞİıÖŞÜ]+$/i,\n 'uk-UA': /^[А-ЩЬЮЯЄIЇҐі]+$/i,\n 'ku-IQ': /^[ئابپتجچحخدرڕزژسشعغفڤقکگلڵمنوۆھەیێيطؤثآإأكضصةظذ]+$/i,\n ar: /^[ءآأؤإئابةتثجحخدذرزسشصضطظعغفقكلمنهوىيًٌٍَُِّْٰ]+$/,\n he: /^[א-ת]+$/,\n 'fa-IR': /^['آابپتثجچهخدذرزژسشصضطظعغفقکگلمنوهی']+$/i\n};\nexports.alpha = alpha;\nvar alphanumeric = {\n 'en-US': /^[0-9A-Z]+$/i,\n 'bg-BG': /^[0-9А-Я]+$/i,\n 'cs-CZ': /^[0-9A-ZÁČĎÉĚÍŇÓŘŠŤÚŮÝŽ]+$/i,\n 'da-DK': /^[0-9A-ZÆØÅ]+$/i,\n 'de-DE': /^[0-9A-ZÄÖÜß]+$/i,\n 'el-GR': /^[0-9Α-ω]+$/i,\n 'es-ES': /^[0-9A-ZÁÉÍÑÓÚÜ]+$/i,\n 'fr-FR': /^[0-9A-ZÀÂÆÇÉÈÊËÏÎÔŒÙÛÜŸ]+$/i,\n 'it-IT': /^[0-9A-ZÀÉÈÌÎÓÒÙ]+$/i,\n 'hu-HU': /^[0-9A-ZÁÉÍÓÖŐÚÜŰ]+$/i,\n 'nb-NO': /^[0-9A-ZÆØÅ]+$/i,\n 'nl-NL': /^[0-9A-ZÁÉËÏÓÖÜÚ]+$/i,\n 'nn-NO': /^[0-9A-ZÆØÅ]+$/i,\n 'pl-PL': /^[0-9A-ZĄĆĘŚŁŃÓŻŹ]+$/i,\n 'pt-PT': /^[0-9A-ZÃÁÀÂÄÇÉÊËÍÏÕÓÔÖÚÜ]+$/i,\n 'ru-RU': /^[0-9А-ЯЁ]+$/i,\n 'sl-SI': /^[0-9A-ZČĆĐŠŽ]+$/i,\n 'sk-SK': /^[0-9A-ZÁČĎÉÍŇÓŠŤÚÝŽĹŔĽÄÔ]+$/i,\n 'sr-RS@latin': /^[0-9A-ZČĆŽŠĐ]+$/i,\n 'sr-RS': /^[0-9А-ЯЂЈЉЊЋЏ]+$/i,\n 'sv-SE': /^[0-9A-ZÅÄÖ]+$/i,\n 'tr-TR': /^[0-9A-ZÇĞİıÖŞÜ]+$/i,\n 'uk-UA': /^[0-9А-ЩЬЮЯЄIЇҐі]+$/i,\n 'ku-IQ': /^[٠١٢٣٤٥٦٧٨٩0-9ئابپتجچحخدرڕزژسشعغفڤقکگلڵمنوۆھەیێيطؤثآإأكضصةظذ]+$/i,\n ar: /^[٠١٢٣٤٥٦٧٨٩0-9ءآأؤإئابةتثجحخدذرزسشصضطظعغفقكلمنهوىيًٌٍَُِّْٰ]+$/,\n he: /^[0-9א-ת]+$/,\n 'fa-IR': /^['0-9آابپتثجچهخدذرزژسشصضطظعغفقکگلمنوهی۱۲۳۴۵۶۷۸۹۰']+$/i\n};\nexports.alphanumeric = alphanumeric;\nvar decimal = {\n 'en-US': '.',\n ar: '٫'\n};\nexports.decimal = decimal;\nvar englishLocales = ['AU', 'GB', 'HK', 'IN', 'NZ', 'ZA', 'ZM'];\nexports.englishLocales = englishLocales;\n\nfor (var locale, i = 0; i < englishLocales.length; i++) {\n locale = \"en-\".concat(englishLocales[i]);\n alpha[locale] = alpha['en-US'];\n alphanumeric[locale] = alphanumeric['en-US'];\n decimal[locale] = decimal['en-US'];\n} // Source: http://www.localeplanet.com/java/\n\n\nvar arabicLocales = ['AE', 'BH', 'DZ', 'EG', 'IQ', 'JO', 'KW', 'LB', 'LY', 'MA', 'QM', 'QA', 'SA', 'SD', 'SY', 'TN', 'YE'];\nexports.arabicLocales = arabicLocales;\n\nfor (var _locale, _i = 0; _i < arabicLocales.length; _i++) {\n _locale = \"ar-\".concat(arabicLocales[_i]);\n alpha[_locale] = alpha.ar;\n alphanumeric[_locale] = alphanumeric.ar;\n decimal[_locale] = decimal.ar;\n} // Source: https://en.wikipedia.org/wiki/Decimal_mark\n\n\nvar dotDecimal = ['ar-EG', 'ar-LB', 'ar-LY'];\nexports.dotDecimal = dotDecimal;\nvar commaDecimal = ['bg-BG', 'cs-CZ', 'da-DK', 'de-DE', 'el-GR', 'en-ZM', 'es-ES', 'fr-FR', 'it-IT', 'ku-IQ', 'hu-HU', 'nb-NO', 'nn-NO', 'nl-NL', 'pl-PL', 'pt-PT', 'ru-RU', 'sl-SI', 'sr-RS@latin', 'sr-RS', 'sv-SE', 'tr-TR', 'uk-UA'];\nexports.commaDecimal = commaDecimal;\n\nfor (var _i2 = 0; _i2 < dotDecimal.length; _i2++) {\n decimal[dotDecimal[_i2]] = decimal['en-US'];\n}\n\nfor (var _i3 = 0; _i3 < commaDecimal.length; _i3++) {\n decimal[commaDecimal[_i3]] = ',';\n}\n\nalpha['pt-BR'] = alpha['pt-PT'];\nalphanumeric['pt-BR'] = alphanumeric['pt-PT'];\ndecimal['pt-BR'] = decimal['pt-PT']; // see #862\n\nalpha['pl-Pl'] = alpha['pl-PL'];\nalphanumeric['pl-Pl'] = alphanumeric['pl-PL'];\ndecimal['pl-Pl'] = decimal['pl-PL'];\n\n//# sourceURL=webpack:///./node_modules/validator/lib/alpha.js?");
/***/ }),
/***/ "./node_modules/validator/lib/blacklist.js":
/*!*************************************************!*\
!*** ./node_modules/validator/lib/blacklist.js ***!
\*************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
eval("\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = blacklist;\n\nvar _assertString = _interopRequireDefault(__webpack_require__(/*! ./util/assertString */ \"./node_modules/validator/lib/util/assertString.js\"));\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\nfunction blacklist(str, chars) {\n (0, _assertString.default)(str);\n return str.replace(new RegExp(\"[\".concat(chars, \"]+\"), 'g'), '');\n}\n\nmodule.exports = exports.default;\nmodule.exports.default = exports.default;\n\n//# sourceURL=webpack:///./node_modules/validator/lib/blacklist.js?");
/***/ }),
/***/ "./node_modules/validator/lib/contains.js":
/*!************************************************!*\
!*** ./node_modules/validator/lib/contains.js ***!
\************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
eval("\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = contains;\n\nvar _assertString = _interopRequireDefault(__webpack_require__(/*! ./util/assertString */ \"./node_modules/validator/lib/util/assertString.js\"));\n\nvar _toString = _interopRequireDefault(__webpack_require__(/*! ./util/toString */ \"./node_modules/validator/lib/util/toString.js\"));\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\nfunction contains(str, elem) {\n (0, _assertString.default)(str);\n return str.indexOf((0, _toString.default)(elem)) >= 0;\n}\n\nmodule.exports = exports.default;\nmodule.exports.default = exports.default;\n\n//# sourceURL=webpack:///./node_modules/validator/lib/contains.js?");
/***/ }),
/***/ "./node_modules/validator/lib/equals.js":
/*!**********************************************!*\
!*** ./node_modules/validator/lib/equals.js ***!
\**********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
eval("\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = equals;\n\nvar _assertString = _interopRequireDefault(__webpack_require__(/*! ./util/assertString */ \"./node_modules/validator/lib/util/assertString.js\"));\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\nfunction equals(str, comparison) {\n (0, _assertString.default)(str);\n return str === comparison;\n}\n\nmodule.exports = exports.default;\nmodule.exports.default = exports.default;\n\n//# sourceURL=webpack:///./node_modules/validator/lib/equals.js?");
/***/ }),
/***/ "./node_modules/validator/lib/escape.js":
/*!**********************************************!*\
!*** ./node_modules/validator/lib/escape.js ***!
\**********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
eval("\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = escape;\n\nvar _assertString = _interopRequireDefault(__webpack_require__(/*! ./util/assertString */ \"./node_modules/validator/lib/util/assertString.js\"));\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\nfunction escape(str) {\n (0, _assertString.default)(str);\n return str.replace(/&/g, '&').replace(/\"/g, '"').replace(/'/g, ''').replace(/</g, '<').replace(/>/g, '>').replace(/\\//g, '/').replace(/\\\\/g, '\').replace(/`/g, '`');\n}\n\nmodule.exports = exports.default;\nmodule.exports.default = exports.default;\n\n//# sourceURL=webpack:///./node_modules/validator/lib/escape.js?");
/***/ }),
/***/ "./node_modules/validator/lib/isAfter.js":
/*!***********************************************!*\
!*** ./node_modules/validator/lib/isAfter.js ***!
\***********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
eval("\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = isAfter;\n\nvar _assertString = _interopRequireDefault(__webpack_require__(/*! ./util/assertString */ \"./node_modules/validator/lib/util/assertString.js\"));\n\nvar _toDate = _interopRequireDefault(__webpack_require__(/*! ./toDate */ \"./node_modules/validator/lib/toDate.js\"));\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\nfunction isAfter(str) {\n var date = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : String(new Date());\n (0, _assertString.default)(str);\n var comparison = (0, _toDate.default)(date);\n var original = (0, _toDate.default)(str);\n return !!(original && comparison && original > comparison);\n}\n\nmodule.exports = exports.default;\nmodule.exports.default = exports.default;\n\n//# sourceURL=webpack:///./node_modules/validator/lib/isAfter.js?");
/***/ }),
/***/ "./node_modules/validator/lib/isAlpha.js":
/*!***********************************************!*\
!*** ./node_modules/validator/lib/isAlpha.js ***!
\***********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
eval("\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = isAlpha;\nexports.locales = void 0;\n\nvar _assertString = _interopRequireDefault(__webpack_require__(/*! ./util/assertString */ \"./node_modules/validator/lib/util/assertString.js\"));\n\nvar _alpha = __webpack_require__(/*! ./alpha */ \"./node_modules/validator/lib/alpha.js\");\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\nfunction isAlpha(str) {\n var locale = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'en-US';\n (0, _assertString.default)(str);\n\n if (locale in _alpha.alpha) {\n return _alpha.alpha[locale].test(str);\n }\n\n throw new Error(\"Invalid locale '\".concat(locale, \"'\"));\n}\n\nvar locales = Object.keys(_alpha.alpha);\nexports.locales = locales;\n\n//# sourceURL=webpack:///./node_modules/validator/lib/isAlpha.js?");
/***/ }),
/***/ "./node_modules/validator/lib/isAlphanumeric.js":
/*!******************************************************!*\
!*** ./node_modules/validator/lib/isAlphanumeric.js ***!
\******************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
eval("\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = isAlphanumeric;\nexports.locales = void 0;\n\nvar _assertString = _interopRequireDefault(__webpack_require__(/*! ./util/assertString */ \"./node_modules/validator/lib/util/assertString.js\"));\n\nvar _alpha = __webpack_require__(/*! ./alpha */ \"./node_modules/validator/lib/alpha.js\");\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\nfunction isAlphanumeric(str) {\n var locale = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'en-US';\n (0, _assertString.default)(str);\n\n if (locale in _alpha.alphanumeric) {\n return _alpha.alphanumeric[locale].test(str);\n }\n\n throw new Error(\"Invalid locale '\".concat(locale, \"'\"));\n}\n\nvar locales = Object.keys(_alpha.alphanumeric);\nexports.locales = locales;\n\n//# sourceURL=webpack:///./node_modules/validator/lib/isAlphanumeric.js?");
/***/ }),
/***/ "./node_modules/validator/lib/isAscii.js":
/*!***********************************************!*\
!*** ./node_modules/validator/lib/isAscii.js ***!
\***********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
eval("\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = isAscii;\n\nvar _assertString = _interopRequireDefault(__webpack_require__(/*! ./util/assertString */ \"./node_modules/validator/lib/util/assertString.js\"));\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\n/* eslint-disable no-control-regex */\nvar ascii = /^[\\x00-\\x7F]+$/;\n/* eslint-enable no-control-regex */\n\nfunction isAscii(str) {\n (0, _assertString.default)(str);\n return ascii.test(str);\n}\n\nmodule.exports = exports.default;\nmodule.exports.default = exports.default;\n\n//# sourceURL=webpack:///./node_modules/validator/lib/isAscii.js?");
/***/ }),
/***/ "./node_modules/validator/lib/isBIC.js":
/*!*********************************************!*\
!*** ./node_modules/validator/lib/isBIC.js ***!
\*********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
eval("\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = isBIC;\n\nvar _assertString = _interopRequireDefault(__webpack_require__(/*! ./util/assertString */ \"./node_modules/validator/lib/util/assertString.js\"));\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\nvar isBICReg = /^[A-z]{4}[A-z]{2}\\w{2}(\\w{3})?$/;\n\nfunction isBIC(str) {\n (0, _assertString.default)(str);\n return isBICReg.test(str);\n}\n\nmodule.exports = exports.default;\nmodule.exports.default = exports.default;\n\n//# sourceURL=webpack:///./node_modules/validator/lib/isBIC.js?");
/***/ }),
/***/ "./node_modules/validator/lib/isBase32.js":
/*!************************************************!*\
!*** ./node_modules/validator/lib/isBase32.js ***!
\************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
eval("\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = isBase32;\n\nvar _assertString = _interopRequireDefault(__webpack_require__(/*! ./util/assertString */ \"./node_modules/validator/lib/util/assertString.js\"));\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\nvar base32 = /^[A-Z2-7]+=*$/;\n\nfunction isBase32(str) {\n (0, _assertString.default)(str);\n var len = str.length;\n\n if (len > 0 && len % 8 === 0 && base32.test(str)) {\n return true;\n }\n\n return false;\n}\n\nmodule.exports = exports.default;\nmodule.exports.default = exports.default;\n\n//# sourceURL=webpack:///./node_modules/validator/lib/isBase32.js?");
/***/ }),
/***/ "./node_modules/validator/lib/isBase64.js":
/*!************************************************!*\
!*** ./node_modules/validator/lib/isBase64.js ***!
\************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
eval("\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = isBase64;\n\nvar _assertString = _interopRequireDefault(__webpack_require__(/*! ./util/assertString */ \"./node_modules/validator/lib/util/assertString.js\"));\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\nvar notBase64 = /[^A-Z0-9+\\/=]/i;\n\nfunction isBase64(str) {\n (0, _assertString.default)(str);\n var len = str.length;\n\n if (!len || len % 4 !== 0 || notBase64.test(str)) {\n return false;\n }\n\n var firstPaddingChar = str.indexOf('=');\n return firstPaddingChar === -1 || firstPaddingChar === len - 1 || firstPaddingChar === len - 2 && str[len - 1] === '=';\n}\n\nmodule.exports = exports.default;\nmodule.exports.default = exports.default;\n\n//# sourceURL=webpack:///./node_modules/validator/lib/isBase64.js?");
/***/ }),
/***/ "./node_modules/validator/lib/isBefore.js":
/*!************************************************!*\
!*** ./node_modules/validator/lib/isBefore.js ***!
\************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
eval("\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = isBefore;\n\nvar _assertString = _interopRequireDefault(__webpack_require__(/*! ./util/assertString */ \"./node_modules/validator/lib/util/assertString.js\"));\n\nvar _toDate = _interopRequireDefault(__webpack_require__(/*! ./toDate */ \"./node_modules/validator/lib/toDate.js\"));\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\nfunction isBefore(str) {\n var date = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : String(new Date());\n (0, _assertString.default)(str);\n var comparison = (0, _toDate.default)(date);\n var original = (0, _toDate.default)(str);\n return !!(original && comparison && original < comparison);\n}\n\nmodule.exports = exports.default;\nmodule.exports.default = exports.default;\n\n//# sourceURL=webpack:///./node_modules/validator/lib/isBefore.js?");
/***/ }),
/***/ "./node_modules/validator/lib/isBoolean.js":
/*!*************************************************!*\
!*** ./node_modules/validator/lib/isBoolean.js ***!
\*************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
eval("\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = isBoolean;\n\nvar _assertString = _interopRequireDefault(__webpack_require__(/*! ./util/assertString */ \"./node_modules/validator/lib/util/assertString.js\"));\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\nfunction isBoolean(str) {\n (0, _assertString.default)(str);\n return ['true', 'false', '1', '0'].indexOf(str) >= 0;\n}\n\nmodule.exports = exports.default;\nmodule.exports.default = exports.default;\n\n//# sourceURL=webpack:///./node_modules/validator/lib/isBoolean.js?");
/***/ }),
/***/ "./node_modules/validator/lib/isBtcAddress.js":
/*!****************************************************!*\
!*** ./node_modules/validator/lib/isBtcAddress.js ***!
\****************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
eval("\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = isBtcAddress;\n\nvar _assertString = _interopRequireDefault(__webpack_require__(/*! ./util/assertString */ \"./node_modules/validator/lib/util/assertString.js\"));\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\n// supports Bech32 addresses\nvar btc = /^(bc1|[13])[a-zA-HJ-NP-Z0-9]{25,39}$/;\n\nfunction isBtcAddress(str) {\n (0, _assertString.default)(str);\n return btc.test(str);\n}\n\nmodule.exports = exports.default;\nmodule.exports.default = exports.default;\n\n//# sourceURL=webpack:///./node_modules/validator/lib/isBtcAddress.js?");
/***/ }),
/***/ "./node_modules/validator/lib/isByteLength.js":
/*!****************************************************!*\
!*** ./node_modules/validator/lib/isByteLength.js ***!
\****************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
eval("\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = isByteLength;\n\nvar _assertString = _interopRequireDefault(__webpack_require__(/*! ./util/assertString */ \"./node_modules/validator/lib/util/assertString.js\"));\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\nfunction _typeof(obj) { \"@babel/helpers - typeof\"; if (typeof Symbol === \"function\" && typeof Symbol.iterator === \"symbol\") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === \"function\" && obj.constructor === Symbol && obj !== Symbol.prototype ? \"symbol\" : typeof obj; }; } return _typeof(obj); }\n\n/* eslint-disable prefer-rest-params */\nfunction isByteLength(str, options) {\n (0, _assertString.default)(str);\n var min;\n var max;\n\n if (_typeof(options) === 'object') {\n min = options.min || 0;\n max = options.max;\n } else {\n // backwards compatibility: isByteLength(str, min [, max])\n min = arguments[1];\n max = arguments[2];\n }\n\n var len = encodeURI(str).split(/%..|./).length - 1;\n return len >= min && (typeof max === 'undefined' || len <= max);\n}\n\nmodule.exports = exports.default;\nmodule.exports.default = exports.default;\n\n//# sourceURL=webpack:///./node_modules/validator/lib/isByteLength.js?");
/***/ }),
/***/ "./node_modules/validator/lib/isCreditCard.js":
/*!****************************************************!*\
!*** ./node_modules/validator/lib/isCreditCard.js ***!
\****************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
eval("\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = isCreditCard;\n\nvar _assertString = _interopRequireDefault(__webpack_require__(/*! ./util/assertString */ \"./node_modules/validator/lib/util/assertString.js\"));\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\n/* eslint-disable max-len */\nvar creditCard = /^(?:4[0-9]{12}(?:[0-9]{3})?|5[1-5][0-9]{14}|(222[1-9]|22[3-9][0-9]|2[3-6][0-9]{2}|27[01][0-9]|2720)[0-9]{12}|6(?:011|5[0-9][0-9])[0-9]{12}|3[47][0-9]{13}|3(?:0[0-5]|[68][0-9])[0-9]{11}|(?:2131|1800|35\\d{3})\\d{11}|6[27][0-9]{14})$/;\n/* eslint-enable max-len */\n\nfunction isCreditCard(str) {\n (0, _assertString.default)(str);\n var sanitized = str.replace(/[- ]+/g, '');\n\n if (!creditCard.test(sanitized)) {\n return false;\n }\n\n var sum = 0;\n var digit;\n var tmpNum;\n var shouldDouble;\n\n for (var i = sanitized.length - 1; i >= 0; i--) {\n digit = sanitized.substring(i, i + 1);\n tmpNum = parseInt(digit, 10);\n\n if (shouldDouble) {\n tmpNum *= 2;\n\n if (tmpNum >= 10) {\n sum += tmpNum % 10 + 1;\n } else {\n sum += tmpNum;\n }\n } else {\n sum += tmpNum;\n }\n\n shouldDouble = !shouldDouble;\n }\n\n return !!(sum % 10 === 0 ? sanitized : false);\n}\n\nmodule.exports = exports.default;\nmodule.exports.default = exports.default;\n\n//# sourceURL=webpack:///./node_modules/validator/lib/isCreditCard.js?");
/***/ }),
/***/ "./node_modules/validator/lib/isCurrency.js":
/*!**************************************************!*\
!*** ./node_modules/validator/lib/isCurrency.js ***!
\**************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
eval("\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = isCurrency;\n\nvar _merge = _interopRequireDefault(__webpack_require__(/*! ./util/merge */ \"./node_modules/validator/lib/util/merge.js\"));\n\nvar _assertString = _interopRequireDefault(__webpack_require__(/*! ./util/assertString */ \"./node_modules/validator/lib/util/assertString.js\"));\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\nfunction currencyRegex(options) {\n var decimal_digits = \"\\\\d{\".concat(options.digits_after_decimal[0], \"}\");\n options.digits_after_decimal.forEach(function (digit, index) {\n if (index !== 0) decimal_digits = \"\".concat(decimal_digits, \"|\\\\d{\").concat(digit, \"}\");\n });\n var symbol = \"(\\\\\".concat(options.symbol.replace(/\\./g, '\\\\.'), \")\").concat(options.require_symbol ? '' : '?'),\n negative = '-?',\n whole_dollar_amount_without_sep = '[1-9]\\\\d*',\n whole_dollar_amount_with_sep = \"[1-9]\\\\d{0,2}(\\\\\".concat(options.thousands_separator, \"\\\\d{3})*\"),\n valid_whole_dollar_amounts = ['0', whole_dollar_amount_without_sep, whole_dollar_amount_with_sep],\n whole_dollar_amount = \"(\".concat(valid_whole_dollar_amounts.join('|'), \")?\"),\n decimal_amount = \"(\\\\\".concat(options.decimal_separator, \"(\").concat(decimal_digits, \"))\").concat(options.require_decimal ? '' : '?');\n var pattern = whole_dollar_amount + (options.allow_decimal || options.require_decimal ? decimal_amount : ''); // default is negative sign before symbol, but there are two other options (besides parens)\n\n if (options.allow_negatives && !options.parens_for_negatives) {\n if (options.negative_sign_after_digits) {\n pattern += negative;\n } else if (options.negative_sign_before_digits) {\n pattern = negative + pattern;\n }\n } // South African Rand, for example, uses R 123 (space) and R-123 (no space)\n\n\n if (options.allow_negative_sign_placeholder) {\n pattern = \"( (?!\\\\-))?\".concat(pattern);\n } else if (options.allow_space_after_symbol) {\n pattern = \" ?\".concat(pattern);\n } else if (options.allow_space_after_digits) {\n pattern += '( (?!$))?';\n }\n\n if (options.symbol_after_digits) {\n pattern += symbol;\n } else {\n pattern = symbol + pattern;\n }\n\n if (options.allow_negatives) {\n if (options.parens_for_negatives) {\n pattern = \"(\\\\(\".concat(pattern, \"\\\\)|\").concat(pattern, \")\");\n } else if (!(options.negative_sign_before_digits || options.negative_sign_after_digits)) {\n pattern = negative + pattern;\n }\n } // ensure there's a dollar and/or decimal amount, and that\n // it doesn't start with a space or a negative sign followed by a space\n\n\n return new RegExp(\"^(?!-? )(?=.*\\\\d)\".concat(pattern, \"$\"));\n}\n\nvar default_currency_options = {\n symbol: '$',\n require_symbol: false,\n allow_space_after_symbol: false,\n symbol_after_digits: false,\n allow_negatives: true,\n parens_for_negatives: false,\n negative_sign_before_digits: false,\n negative_sign_after_digits: false,\n allow_negative_sign_placeholder: false,\n thousands_separator: ',',\n decimal_separator: '.',\n allow_decimal: true,\n require_decimal: false,\n digits_after_decimal: [2],\n allow_space_after_digits: false\n};\n\nfunction isCurrency(str, options) {\n (0, _assertString.default)(str);\n options = (0, _merge.default)(options, default_currency_options);\n return currencyRegex(options).test(str);\n}\n\nmodule.exports = exports.default;\nmodule.exports.default = exports.default;\n\n//# sourceURL=webpack:///./node_modules/validator/lib/isCurrency.js?");
/***/ }),
/***/ "./node_modules/validator/lib/isDataURI.js":
/*!*************************************************!*\
!*** ./node_modules/validator/lib/isDataURI.js ***!
\*************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
eval("\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = isDataURI;\n\nvar _assertString = _interopRequireDefault(__webpack_require__(/*! ./util/assertString */ \"./node_modules/validator/lib/util/assertString.js\"));\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\nvar validMediaType = /^[a-z]+\\/[a-z0-9\\-\\+]+$/i;\nvar validAttribute = /^[a-z\\-]+=[a-z0-9\\-]+$/i;\nvar validData = /^[a-z0-9!\\$&'\\(\\)\\*\\+,;=\\-\\._~:@\\/\\?%\\s]*$/i;\n\nfunction isDataURI(str) {\n (0, _assertString.default)(str);\n var data = str.split(',');\n\n if (data.length < 2) {\n return false;\n }\n\n var attributes = data.shift().trim().split(';');\n var schemeAndMediaType = attributes.shift();\n\n if (schemeAndMediaType.substr(0, 5) !== 'data:') {\n return false;\n }\n\n var mediaType = schemeAndMediaType.substr(5);\n\n if (mediaType !== '' && !validMediaType.test(mediaType)) {\n return false;\n }\n\n for (var i = 0; i < attributes.length; i++) {\n if (i === attributes.length - 1 && attributes[i].toLowerCase() === 'base64') {// ok\n } else if (!validAttribute.test(attributes[i])) {\n return false;\n }\n }\n\n for (var _i = 0; _i < data.length; _i++) {\n if (!validData.test(data[_i])) {\n return false;\n }\n }\n\n return true;\n}\n\nmodule.exports = exports.default;\nmodule.exports.default = exports.default;\n\n//# sourceURL=webpack:///./node_modules/validator/lib/isDataURI.js?");
/***/ }),
/***/ "./node_modules/validator/lib/isDecimal.js":
/*!*************************************************!*\
!*** ./node_modules/validator/lib/isDecimal.js ***!
\*************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
eval("\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = isDecimal;\n\nvar _merge = _interopRequireDefault(__webpack_require__(/*! ./util/merge */ \"./node_modules/validator/lib/util/merge.js\"));\n\nvar _assertString = _interopRequireDefault(__webpack_require__(/*! ./util/assertString */ \"./node_modules/validator/lib/util/assertString.js\"));\n\nvar _includes = _interopRequireDefault(__webpack_require__(/*! ./util/includes */ \"./node_modules/validator/lib/util/includes.js\"));\n\nvar _alpha = __webpack_require__(/*! ./alpha */ \"./node_modules/validator/lib/alpha.js\");\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\nfunction decimalRegExp(options) {\n var regExp = new RegExp(\"^[-+]?([0-9]+)?(\\\\\".concat(_alpha.decimal[options.locale], \"[0-9]{\").concat(options.decimal_digits, \"})\").concat(options.force_decimal ? '' : '?', \"$\"));\n return regExp;\n}\n\nvar default_decimal_options = {\n force_decimal: false,\n decimal_digits: '1,',\n locale: 'en-US'\n};\nvar blacklist = ['', '-', '+'];\n\nfunction isDecimal(str, options) {\n (0, _assertString.default)(str);\n options = (0, _merge.default)(options, default_decimal_options);\n\n if (options.locale in _alpha.decimal) {\n return !(0, _includes.default)(blacklist, str.replace(/ /g, '')) && decimalRegExp(options).test(str);\n }\n\n throw new Error(\"Invalid locale '\".concat(options.locale, \"'\"));\n}\n\nmodule.exports = exports.default;\nmodule.exports.default = exports.default;\n\n//# sourceURL=webpack:///./node_modules/validator/lib/isDecimal.js?");
/***/ }),
/***/ "./node_modules/validator/lib/isDivisibleBy.js":
/*!*****************************************************!*\
!*** ./node_modules/validator/lib/isDivisibleBy.js ***!
\*****************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
eval("\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = isDivisibleBy;\n\nvar _assertString = _interopRequireDefault(__webpack_require__(/*! ./util/assertString */ \"./node_modules/validator/lib/util/assertString.js\"));\n\nvar _toFloat = _interopRequireDefault(__webpack_require__(/*! ./toFloat */ \"./node_modules/validator/lib/toFloat.js\"));\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\nfunction isDivisibleBy(str, num) {\n (0, _assertString.default)(str);\n return (0, _toFloat.default)(str) % parseInt(num, 10) === 0;\n}\n\nmodule.exports = exports.default;\nmodule.exports.default = exports.default;\n\n//# sourceURL=webpack:///./node_modules/validator/lib/isDivisibleBy.js?");
/***/ }),
/***/ "./node_modules/validator/lib/isEAN.js":
/*!*********************************************!*\
!*** ./node_modules/validator/lib/isEAN.js ***!
\*********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
eval("\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = isEAN;\n\nvar _assertString = _interopRequireDefault(__webpack_require__(/*! ./util/assertString */ \"./node_modules/validator/lib/util/assertString.js\"));\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\n/**\n * The most commonly used EAN standard is\n * the thirteen-digit EAN-13, while the\n * less commonly used 8-digit EAN-8 barcode was\n * introduced for use on small packages.\n * EAN consists of:\n * GS1 prefix, manufacturer code, product code and check digit\n * Reference: https://en.wikipedia.org/wiki/International_Article_Number\n */\n\n/**\n * Define EAN Lenghts; 8 for EAN-8; 13 for EAN-13\n * and Regular Expression for valid EANs (EAN-8, EAN-13),\n * with exact numberic matching of 8 or 13 digits [0-9]\n */\nvar LENGTH_EAN_8 = 8;\nvar validEanRegex = /^(\\d{8}|\\d{13})$/;\n/**\n * Get position weight given:\n * EAN length and digit index/position\n *\n * @param {number} length\n * @param {number} index\n * @return {number}\n */\n\nfunction getPositionWeightThroughLengthAndIndex(length, index) {\n if (length === LENGTH_EAN_8) {\n return index % 2 === 0 ? 3 : 1;\n }\n\n return index % 2 === 0 ? 1 : 3;\n}\n/**\n * Calculate EAN Check Digit\n * Reference: https://en.wikipedia.org/wiki/International_Article_Number#Calculation_of_checksum_digit\n *\n * @param {string} ean\n * @return {number}\n */\n\n\nfunction calculateCheckDigit(ean) {\n var checksum = ean.slice(0, -1).split('').map(function (char, index) {\n return Number(char) * getPositionWeightThroughLengthAndIndex(ean.length, index);\n }).reduce(function (acc, partialSum) {\n return acc + partialSum;\n }, 0);\n var remainder = 10 - checksum % 10;\n return remainder < 10 ? remainder : 0;\n}\n/**\n * Check if string is valid EAN:\n * Matches EAN-8/EAN-13 regex\n * Has valid check digit.\n *\n * @param {string} str\n * @return {boolean}\n */\n\n\nfunction isEAN(str) {\n (0, _assertString.default)(str);\n var actualCheckDigit = Number(str.slice(-1));\n return validEanRegex.test(str) && actualCheckDigit === calculateCheckDigit(str);\n}\n\nmodule.exports = exports.default;\nmodule.exports.default = exports.default;\n\n//# sourceURL=webpack:///./node_modules/validator/lib/isEAN.js?");
/***/ }),
/***/ "./node_modules/validator/lib/isEmail.js":
/*!***********************************************!*\
!*** ./node_modules/validator/lib/isEmail.js ***!
\***********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
eval("\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = isEmail;\n\nvar _assertString = _interopRequireDefault(__webpack_require__(/*! ./util/assertString */ \"./node_modules/validator/lib/util/assertString.js\"));\n\nvar _merge = _interopRequireDefault(__webpack_require__(/*! ./util/merge */ \"./node_modules/validator/lib/util/merge.js\"));\n\nvar _isByteLength = _interopRequireDefault(__webpack_require__(/*! ./isByteLength */ \"./node_modules/validator/lib/isByteLength.js\"));\n\nvar _isFQDN = _interopRequireDefault(__webpack_require__(/*! ./isFQDN */ \"./node_modules/validator/lib/isFQDN.js\"));\n\nvar _isIP = _interopRequireDefault(__webpack_require__(/*! ./isIP */ \"./node_modules/validator/lib/isIP.js\"));\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\nfunction _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _nonIterableRest(); }\n\nfunction _nonIterableRest() { throw new TypeError(\"Invalid attempt to destructure non-iterable instance\"); }\n\nfunction _iterableToArrayLimit(arr, i) { if (!(Symbol.iterator in Object(arr) || Object.prototype.toString.call(arr) === \"[object Arguments]\")) { return; } var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i[\"return\"] != null) _i[\"return\"](); } finally { if (_d) throw _e; } } return _arr; }\n\nfunction _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }\n\nvar default_email_options = {\n allow_display_name: false,\n require_display_name: false,\n allow_utf8_local_part: true,\n require_tld: true\n};\n/* eslint-disable max-len */\n\n/* eslint-disable no-control-regex */\n\nvar splitNameAddress = /^([^\\x00-\\x1F\\x7F-\\x9F\\cX]+)<(.+)>$/i;\nvar emailUserPart = /^[a-z\\d!#\\$%&'\\*\\+\\-\\/=\\?\\^_`{\\|}~]+$/i;\nvar gmailUserPart = /^[a-z\\d]+$/;\nvar quotedEmailUser = /^([\\s\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x7f\\x21\\x23-\\x5b\\x5d-\\x7e]|(\\\\[\\x01-\\x09\\x0b\\x0c\\x0d-\\x7f]))*$/i;\nvar emailUserUtf8Part = /^[a-z\\d!#\\$%&'\\*\\+\\-\\/=\\?\\^_`{\\|}~\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF]+$/i;\nvar quotedEmailUserUtf8 = /^([\\s\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x7f\\x21\\x23-\\x5b\\x5d-\\x7e\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF]|(\\\\[\\x01-\\x09\\x0b\\x0c\\x0d-\\x7f\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF]))*$/i;\nvar defaultMaxEmailLength = 254;\n/* eslint-enable max-len */\n\n/* eslint-enable no-control-regex */\n\n/**\n * Validate display name according to the RFC2822: https://tools.ietf.org/html/rfc2822#appendix-A.1.2\n * @param {String} display_name\n */\n\nfunction validateDisplayName(display_name) {\n var trim_quotes = display_name.match(/^\"(.+)\"$/i);\n var display_name_without_quotes = trim_quotes ? trim_quotes[1] : display_name; // display name with only spaces is not valid\n\n if (!display_name_without_quotes.trim()) {\n return false;\n } // check whether display name contains illegal character\n\n\n var contains_illegal = /[\\.\";<>]/.test(display_name_without_quotes);\n\n if (contains_illegal) {\n // if contains illegal characters,\n // must to be enclosed in double-quotes, otherwise it's not a valid display name\n if (!trim_quotes) {\n return false;\n } // the quotes in display name must start with character symbol \\\n\n\n var all_start_with_back_slash = display_name_without_quotes.split('\"').length === display_name_without_quotes.split('\\\\\"').length;\n\n if (!all_start_with_back_slash) {\n return false;\n }\n }\n\n return true;\n}\n\nfunction isEmail(str, options) {\n (0, _assertString.default)(str);\n options = (0, _merge.default)(options, default_email_options);\n\n if (options.require_display_name || options.allow_display_name) {\n var display_email = str.match(splitNameAddress);\n\n if (display_email) {\n var display_name;\n\n var _display_email = _slicedToArray(display_email, 3);\n\n display_name = _display_email[1];\n str = _display_email[2];\n\n // sometimes need to trim the last space to get the display name\n // because there may be a space between display name and email address\n // eg. myname <[email protected]>\n // the display name is `myname` instead of `myname `, so need to trim the last space\n if (display_name.endsWith(' ')) {\n display_name = display_name.substr(0, display_name.length - 1);\n }\n\n if (!validateDisplayName(display_name)) {\n return false;\n }\n } else if (options.require_display_name) {\n return false;\n }\n }\n\n if (!options.ignore_max_length && str.length > defaultMaxEmailLength) {\n return false;\n }\n\n var parts = str.split('@');\n var domain = parts.pop();\n var user = parts.join('@');\n var lower_domain = domain.toLowerCase();\n\n if (options.domain_specific_validation && (lower_domain === 'gmail.com' || lower_domain === 'googlemail.com')) {\n /*\n Previously we removed dots for gmail addresses before validating.\n This was removed because it allows `[email protected]`\n to be reported as valid, but it is not.\n Gmail only normalizes single dots, removing them from here is pointless,\n should be done in normalizeEmail\n */\n user = user.toLowerCase(); // Removing sub-address from username before gmail validation\n\n var username = user.split('+')[0]; // Dots are not included in gmail length restriction\n\n if (!(0, _isByteLength.default)(username.replace('.', ''), {\n min: 6,\n max: 30\n })) {\n return false;\n }\n\n var _user_parts = username.split('.');\n\n for (var i = 0; i < _user_parts.length; i++) {\n if (!gmailUserPart.test(_user_parts[i])) {\n return false;\n }\n }\n }\n\n if (!(0, _isByteLength.default)(user, {\n max: 64\n }) || !(0, _isByteLength.default)(domain, {\n max: 254\n })) {\n return false;\n }\n\n if (!(0, _isFQDN.default)(domain, {\n require_tld: options.require_tld\n })) {\n if (!options.allow_ip_domain) {\n return false;\n }\n\n if (!(0, _isIP.default)(domain)) {\n if (!domain.startsWith('[') || !domain.endsWith(']')) {\n return false;\n }\n\n var noBracketdomain = domain.substr(1, domain.length - 2);\n\n if (noBracketdomain.length === 0 || !(0, _isIP.default)(noBracketdomain)) {\n return false;\n }\n }\n }\n\n if (user[0] === '\"') {\n user = user.slice(1, user.length - 1);\n return options.allow_utf8_local_part ? quotedEmailUserUtf8.test(user) : quotedEmailUser.test(user);\n }\n\n var pattern = options.allow_utf8_local_part ? emailUserUtf8Part : emailUserPart;\n var user_parts = user.split('.');\n\n for (var _i2 = 0; _i2 < user_parts.length; _i2++) {\n if (!pattern.test(user_parts[_i2])) {\n return false;\n }\n }\n\n return true;\n}\n\nmodule.exports = exports.default;\nmodule.exports.default = exports.default;\n\n//# sourceURL=webpack:///./node_modules/validator/lib/isEmail.js?");
/***/ }),
/***/ "./node_modules/validator/lib/isEmpty.js":
/*!***********************************************!*\
!*** ./node_modules/validator/lib/isEmpty.js ***!
\***********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
eval("\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = isEmpty;\n\nvar _assertString = _interopRequireDefault(__webpack_require__(/*! ./util/assertString */ \"./node_modules/validator/lib/util/assertString.js\"));\n\nvar _merge = _interopRequireDefault(__webpack_require__(/*! ./util/merge */ \"./node_modules/validator/lib/util/merge.js\"));\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\nvar default_is_empty_options = {\n ignore_whitespace: false\n};\n\nfunction isEmpty(str, options) {\n (0, _assertString.default)(str);\n options = (0, _merge.default)(options, default_is_empty_options);\n return (options.ignore_whitespace ? str.trim().length : str.length) === 0;\n}\n\nmodule.exports = exports.default;\nmodule.exports.default = exports.default;\n\n//# sourceURL=webpack:///./node_modules/validator/lib/isEmpty.js?");
/***/ }),
/***/ "./node_modules/validator/lib/isEthereumAddress.js":
/*!*********************************************************!*\
!*** ./node_modules/validator/lib/isEthereumAddress.js ***!
\*********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
eval("\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = isEthereumAddress;\n\nvar _assertString = _interopRequireDefault(__webpack_require__(/*! ./util/assertString */ \"./node_modules/validator/lib/util/assertString.js\"));\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\nvar eth = /^(0x)[0-9a-f]{40}$/i;\n\nfunction isEthereumAddress(str) {\n (0, _assertString.default)(str);\n return eth.test(str);\n}\n\nmodule.exports = exports.default;\nmodule.exports.default = exports.default;\n\n//# sourceURL=webpack:///./node_modules/validator/lib/isEthereumAddress.js?");
/***/ }),
/***/ "./node_modules/validator/lib/isFQDN.js":
/*!**********************************************!*\
!*** ./node_modules/validator/lib/isFQDN.js ***!
\**********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
eval("\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = isFQDN;\n\nvar _assertString = _interopRequireDefault(__webpack_require__(/*! ./util/assertString */ \"./node_modules/validator/lib/util/assertString.js\"));\n\nvar _merge = _interopRequireDefault(__webpack_require__(/*! ./util/merge */ \"./node_modules/validator/lib/util/merge.js\"));\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\nvar default_fqdn_options = {\n require_tld: true,\n allow_underscores: false,\n allow_trailing_dot: false\n};\n\nfunction isFQDN(str, options) {\n (0, _assertString.default)(str);\n options = (0, _merge.default)(options, default_fqdn_options);\n /* Remove the optional trailing dot before checking validity */\n\n if (options.allow_trailing_dot && str[str.length - 1] === '.') {\n str = str.substring(0, str.length - 1);\n }\n\n var parts = str.split('.');\n\n for (var i = 0; i < parts.length; i++) {\n if (parts[i].length > 63) {\n return false;\n }\n }\n\n if (options.require_tld) {\n var tld = parts.pop();\n\n if (!parts.length || !/^([a-z\\u00a1-\\uffff]{2,}|xn[a-z0-9-]{2,})$/i.test(tld)) {\n return false;\n } // disallow spaces\n\n\n if (/[\\s\\u2002-\\u200B\\u202F\\u205F\\u3000\\uFEFF\\uDB40\\uDC20]/.test(tld)) {\n return false;\n }\n }\n\n for (var part, _i = 0; _i < parts.length; _i++) {\n part = parts[_i];\n\n if (options.allow_underscores) {\n part = part.replace(/_/g, '');\n }\n\n if (!/^[a-z\\u00a1-\\uffff0-9-]+$/i.test(part)) {\n return false;\n } // disallow full-width chars\n\n\n if (/[\\uff01-\\uff5e]/.test(part)) {\n return false;\n }\n\n if (part[0] === '-' || part[part.length - 1] === '-') {\n return false;\n }\n }\n\n return true;\n}\n\nmodule.exports = exports.default;\nmodule.exports.default = exports.default;\n\n//# sourceURL=webpack:///./node_modules/validator/lib/isFQDN.js?");
/***/ }),
/***/ "./node_modules/validator/lib/isFloat.js":
/*!***********************************************!*\
!*** ./node_modules/validator/lib/isFloat.js ***!
\***********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
eval("\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = isFloat;\nexports.locales = void 0;\n\nvar _assertString = _interopRequireDefault(__webpack_require__(/*! ./util/assertString */ \"./node_modules/validator/lib/util/assertString.js\"));\n\nvar _alpha = __webpack_require__(/*! ./alpha */ \"./node_modules/validator/lib/alpha.js\");\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\nfunction isFloat(str, options) {\n (0, _assertString.default)(str);\n options = options || {};\n var float = new RegExp(\"^(?:[-+])?(?:[0-9]+)?(?:\\\\\".concat(options.locale ? _alpha.decimal[options.locale] : '.', \"[0-9]*)?(?:[eE][\\\\+\\\\-]?(?:[0-9]+))?$\"));\n\n if (str === '' || str === '.' || str === '-' || str === '+') {\n return false;\n }\n\n var value = parseFloat(str.replace(',', '.'));\n return float.test(str) && (!options.hasOwnProperty('min') || value >= options.min) && (!options.hasOwnProperty('max') || value <= options.max) && (!options.hasOwnProperty('lt') || value < options.lt) && (!options.hasOwnProperty('gt') || value > options.gt);\n}\n\nvar locales = Object.keys(_alpha.decimal);\nexports.locales = locales;\n\n//# sourceURL=webpack:///./node_modules/validator/lib/isFloat.js?");
/***/ }),
/***/ "./node_modules/validator/lib/isFullWidth.js":
/*!***************************************************!*\
!*** ./node_modules/validator/lib/isFullWidth.js ***!
\***************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
eval("\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = isFullWidth;\nexports.fullWidth = void 0;\n\nvar _assertString = _interopRequireDefault(__webpack_require__(/*! ./util/assertString */ \"./node_modules/validator/lib/util/assertString.js\"));\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\nvar fullWidth = /[^\\u0020-\\u007E\\uFF61-\\uFF9F\\uFFA0-\\uFFDC\\uFFE8-\\uFFEE0-9a-zA-Z]/;\nexports.fullWidth = fullWidth;\n\nfunction isFullWidth(str) {\n (0, _assertString.default)(str);\n return fullWidth.test(str);\n}\n\n//# sourceURL=webpack:///./node_modules/validator/lib/isFullWidth.js?");
/***/ }),
/***/ "./node_modules/validator/lib/isHSL.js":
/*!*********************************************!*\
!*** ./node_modules/validator/lib/isHSL.js ***!
\*********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
eval("\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = isHSL;\n\nvar _assertString = _interopRequireDefault(__webpack_require__(/*! ./util/assertString */ \"./node_modules/validator/lib/util/assertString.js\"));\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\nvar hslcomma = /^(hsl)a?\\(\\s*((\\+|\\-)?([0-9]+(\\.[0-9]+)?(e(\\+|\\-)?[0-9]+)?|\\.[0-9]+(e(\\+|\\-)?[0-9]+)?))(deg|grad|rad|turn|\\s*)(\\s*,\\s*(\\+|\\-)?([0-9]+(\\.[0-9]+)?(e(\\+|\\-)?[0-9]+)?|\\.[0-9]+(e(\\+|\\-)?[0-9]+)?)%){2}\\s*(,\\s*((\\+|\\-)?([0-9]+(\\.[0-9]+)?(e(\\+|\\-)?[0-9]+)?|\\.[0-9]+(e(\\+|\\-)?[0-9]+)?)%?)\\s*)?\\)$/i;\nvar hslspace = /^(hsl)a?\\(\\s*((\\+|\\-)?([0-9]+(\\.[0-9]+)?(e(\\+|\\-)?[0-9]+)?|\\.[0-9]+(e(\\+|\\-)?[0-9]+)?))(deg|grad|rad|turn|\\s)(\\s*(\\+|\\-)?([0-9]+(\\.[0-9]+)?(e(\\+|\\-)?[0-9]+)?|\\.[0-9]+(e(\\+|\\-)?[0-9]+)?)%){2}\\s*(\\/\\s*((\\+|\\-)?([0-9]+(\\.[0-9]+)?(e(\\+|\\-)?[0-9]+)?|\\.[0-9]+(e(\\+|\\-)?[0-9]+)?)%?)\\s*)?\\)$/i;\n\nfunction isHSL(str) {\n (0, _assertString.default)(str);\n return hslcomma.test(str) || hslspace.test(str);\n}\n\nmodule.exports = exports.default;\nmodule.exports.default = exports.default;\n\n//# sourceURL=webpack:///./node_modules/validator/lib/isHSL.js?");
/***/ }),
/***/ "./node_modules/validator/lib/isHalfWidth.js":
/*!***************************************************!*\
!*** ./node_modules/validator/lib/isHalfWidth.js ***!
\***************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
eval("\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = isHalfWidth;\nexports.halfWidth = void 0;\n\nvar _assertString = _interopRequireDefault(__webpack_require__(/*! ./util/assertString */ \"./node_modules/validator/lib/util/assertString.js\"));\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\nvar halfWidth = /[\\u0020-\\u007E\\uFF61-\\uFF9F\\uFFA0-\\uFFDC\\uFFE8-\\uFFEE0-9a-zA-Z]/;\nexports.halfWidth = halfWidth;\n\nfunction isHalfWidth(str) {\n (0, _assertString.default)(str);\n return halfWidth.test(str);\n}\n\n//# sourceURL=webpack:///./node_modules/validator/lib/isHalfWidth.js?");
/***/ }),
/***/ "./node_modules/validator/lib/isHash.js":
/*!**********************************************!*\
!*** ./node_modules/validator/lib/isHash.js ***!
\**********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
eval("\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = isHash;\n\nvar _assertString = _interopRequireDefault(__webpack_require__(/*! ./util/assertString */ \"./node_modules/validator/lib/util/assertString.js\"));\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\nvar lengths = {\n md5: 32,\n md4: 32,\n sha1: 40,\n sha256: 64,\n sha384: 96,\n sha512: 128,\n ripemd128: 32,\n ripemd160: 40,\n tiger128: 32,\n tiger160: 40,\n tiger192: 48,\n crc32: 8,\n crc32b: 8\n};\n\nfunction isHash(str, algorithm) {\n (0, _assertString.default)(str);\n var hash = new RegExp(\"^[a-fA-F0-9]{\".concat(lengths[algorithm], \"}$\"));\n return hash.test(str);\n}\n\nmodule.exports = exports.default;\nmodule.exports.default = exports.default;\n\n//# sourceURL=webpack:///./node_modules/validator/lib/isHash.js?");
/***/ }),
/***/ "./node_modules/validator/lib/isHexColor.js":
/*!**************************************************!*\
!*** ./node_modules/validator/lib/isHexColor.js ***!
\**************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
eval("\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = isHexColor;\n\nvar _assertString = _interopRequireDefault(__webpack_require__(/*! ./util/assertString */ \"./node_modules/validator/lib/util/assertString.js\"));\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\nvar hexcolor = /^#?([0-9A-F]{3}|[0-9A-F]{4}|[0-9A-F]{6}|[0-9A-F]{8})$/i;\n\nfunction isHexColor(str) {\n (0, _assertString.default)(str);\n return hexcolor.test(str);\n}\n\nmodule.exports = exports.default;\nmodule.exports.default = exports.default;\n\n//# sourceURL=webpack:///./node_modules/validator/lib/isHexColor.js?");
/***/ }),
/***/ "./node_modules/validator/lib/isHexadecimal.js":
/*!*****************************************************!*\
!*** ./node_modules/validator/lib/isHexadecimal.js ***!
\*****************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
eval("\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = isHexadecimal;\n\nvar _assertString = _interopRequireDefault(__webpack_require__(/*! ./util/assertString */ \"./node_modules/validator/lib/util/assertString.js\"));\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\nvar hexadecimal = /^(0x|0h)?[0-9A-F]+$/i;\n\nfunction isHexadecimal(str) {\n (0, _assertString.default)(str);\n return hexadecimal.test(str);\n}\n\nmodule.exports = exports.default;\nmodule.exports.default = exports.default;\n\n//# sourceURL=webpack:///./node_modules/validator/lib/isHexadecimal.js?");
/***/ }),
/***/ "./node_modules/validator/lib/isIBAN.js":
/*!**********************************************!*\
!*** ./node_modules/validator/lib/isIBAN.js ***!
\**********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
eval("\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = isIBAN;\n\nvar _assertString = _interopRequireDefault(__webpack_require__(/*! ./util/assertString */ \"./node_modules/validator/lib/util/assertString.js\"));\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\n/**\n * List of country codes with\n * corresponding IBAN regular expression\n * Reference: https://en.wikipedia.org/wiki/International_Bank_Account_Number\n */\nvar ibanRegexThroughCountryCode = {\n AD: /^(AD[0-9]{2})\\d{8}[A-Z0-9]{12}$/,\n AE: /^(AE[0-9]{2})\\d{3}\\d{16}$/,\n AL: /^(AL[0-9]{2})\\d{8}[A-Z0-9]{16}$/,\n AT: /^(AT[0-9]{2})\\d{16}$/,\n AZ: /^(AZ[0-9]{2})[A-Z0-9]{4}\\d{20}$/,\n BA: /^(BA[0-9]{2})\\d{16}$/,\n BE: /^(BE[0-9]{2})\\d{12}$/,\n BG: /^(BG[0-9]{2})[A-Z]{4}\\d{6}[A-Z0-9]{8}$/,\n BH: /^(BH[0-9]{2})[A-Z]{4}[A-Z0-9]{14}$/,\n BR: /^(BR[0-9]{2})\\d{23}[A-Z]{1}[A-Z0-9]{1}$/,\n BY: /^(BY[0-9]{2})[A-Z0-9]{4}\\d{20}$/,\n CH: /^(CH[0-9]{2})\\d{5}[A-Z0-9]{12}$/,\n CR: /^(CR[0-9]{2})\\d{18}$/,\n CY: /^(CY[0-9]{2})\\d{8}[A-Z0-9]{16}$/,\n CZ: /^(CZ[0-9]{2})\\d{20}$/,\n DE: /^(DE[0-9]{2})\\d{18}$/,\n DK: /^(DK[0-9]{2})\\d{14}$/,\n DO: /^(DO[0-9]{2})[A-Z]{4}\\d{20}$/,\n EE: /^(EE[0-9]{2})\\d{16}$/,\n ES: /^(ES[0-9]{2})\\d{20}$/,\n FI: /^(FI[0-9]{2})\\d{14}$/,\n FO: /^(FO[0-9]{2})\\d{14}$/,\n FR: /^(FR[0-9]{2})\\d{10}[A-Z0-9]{11}\\d{2}$/,\n GB: /^(GB[0-9]{2})[A-Z]{4}\\d{14}$/,\n GE: /^(GE[0-9]{2})[A-Z0-9]{2}\\d{16}$/,\n GI: /^(GI[0-9]{2})[A-Z]{4}[A-Z0-9]{15}$/,\n GL: /^(GL[0-9]{2})\\d{14}$/,\n GR: /^(GR[0-9]{2})\\d{7}[A-Z0-9]{16}$/,\n GT: /^(GT[0-9]{2})[A-Z0-9]{4}[A-Z0-9]{20}$/,\n HR: /^(HR[0-9]{2})\\d{17}$/,\n HU: /^(HU[0-9]{2})\\d{24}$/,\n IE: /^(IE[0-9]{2})[A-Z0-9]{4}\\d{14}$/,\n IL: /^(IL[0-9]{2})\\d{19}$/,\n IQ: /^(IQ[0-9]{2})[A-Z]{4}\\d{15}$/,\n IS: /^(IS[0-9]{2})\\d{22}$/,\n IT: /^(IT[0-9]{2})[A-Z]{1}\\d{10}[A-Z0-9]{12}$/,\n JO: /^(JO[0-9]{2})[A-Z]{4}\\d{22}$/,\n KW: /^(KW[0-9]{2})[A-Z]{4}[A-Z0-9]{22}$/,\n KZ: /^(KZ[0-9]{2})\\d{3}[A-Z0-9]{13}$/,\n LB: /^(LB[0-9]{2})\\d{4}[A-Z0-9]{20}$/,\n LC: /^(LC[0-9]{2})[A-Z]{4}[A-Z0-9]{24}$/,\n LI: /^(LI[0-9]{2})\\d{5}[A-Z0-9]{12}$/,\n LT: /^(LT[0-9]{2})\\d{16}$/,\n LU: /^(LU[0-9]{2})\\d{3}[A-Z0-9]{13}$/,\n LV: /^(LV[0-9]{2})[A-Z]{4}[A-Z0-9]{13}$/,\n MC: /^(MC[0-9]{2})\\d{10}[A-Z0-9]{11}\\d{2}$/,\n MD: /^(MD[0-9]{2})[A-Z0-9]{20}$/,\n ME: /^(ME[0-9]{2})\\d{18}$/,\n MK: /^(MK[0-9]{2})\\d{3}[A-Z0-9]{10}\\d{2}$/,\n MR: /^(MR[0-9]{2})\\d{23}$/,\n MT: /^(MT[0-9]{2})[A-Z]{4}\\d{5}[A-Z0-9]{18}$/,\n MU: /^(MU[0-9]{2})[A-Z]{4}\\d{19}[A-Z]{3}$/,\n NL: /^(NL[0-9]{2})[A-Z]{4}\\d{10}$/,\n NO: /^(NO[0-9]{2})\\d{11}$/,\n PK: /^(PK[0-9]{2})[A-Z0-9]{4}\\d{16}$/,\n PL: /^(PL[0-9]{2})\\d{24}$/,\n PS: /^(PS[0-9]{2})[A-Z0-9]{4}\\d{21}$/,\n PT: /^(PT[0-9]{2})\\d{21}$/,\n QA: /^(QA[0-9]{2})[A-Z]{4}[A-Z0-9]{21}$/,\n RO: /^(RO[0-9]{2})[A-Z]{4}[A-Z0-9]{16}$/,\n RS: /^(RS[0-9]{2})\\d{18}$/,\n SA: /^(SA[0-9]{2})\\d{2}[A-Z0-9]{18}$/,\n SC: /^(SC[0-9]{2})[A-Z]{4}\\d{20}[A-Z]{3}$/,\n SE: /^(SE[0-9]{2})\\d{20}$/,\n SI: /^(SI[0-9]{2})\\d{15}$/,\n SK: /^(SK[0-9]{2})\\d{20}$/,\n SM: /^(SM[0-9]{2})[A-Z]{1}\\d{10}[A-Z0-9]{12}$/,\n TL: /^(TL[0-9]{2})\\d{19}$/,\n TN: /^(TN[0-9]{2})\\d{20}$/,\n TR: /^(TR[0-9]{2})\\d{5}[A-Z0-9]{17}$/,\n UA: /^(UA[0-9]{2})\\d{6}[A-Z0-9]{19}$/,\n VA: /^(VA[0-9]{2})\\d{18}$/,\n VG: /^(VG[0-9]{2})[A-Z0-9]{4}\\d{16}$/,\n XK: /^(XK[0-9]{2})\\d{16}$/\n};\n/**\n * Check whether string has correct universal IBAN format\n * The IBAN consists of up to 34 alphanumeric characters, as follows:\n * Country Code using ISO 3166-1 alpha-2, two letters\n * check digits, two digits and\n * Basic Bank Account Number (BBAN), up to 30 alphanumeric characters.\n * NOTE: Permitted IBAN characters are: digits [0-9] and the 26 latin alphabetic [A-Z]\n *\n * @param {string} str - string under validation\n * @return {boolean}\n */\n\nfunction hasValidIbanFormat(str) {\n // Strip white spaces and hyphens\n var strippedStr = str.replace(/[\\s\\-]+/gi, '').toUpperCase();\n var isoCountryCode = strippedStr.slice(0, 2).toUpperCase();\n return isoCountryCode in ibanRegexThroughCountryCode && ibanRegexThroughCountryCode[isoCountryCode].test(strippedStr);\n}\n/**\n * Check whether string has valid IBAN Checksum\n * by performing basic mod-97 operation and\n * the remainder should equal 1\n * -- Start by rearranging the IBAN by moving the four initial characters to the end of the string\n * -- Replace each letter in the string with two digits, A -> 10, B = 11, Z = 35\n * -- Interpret the string as a decimal integer and\n * -- compute the remainder on division by 97 (mod 97)\n * Reference: https://en.wikipedia.org/wiki/International_Bank_Account_Number\n *\n * @param {string} str\n * @return {boolean}\n */\n\n\nfunction hasValidIbanChecksum(str) {\n var strippedStr = str.replace(/[^A-Z0-9]+/gi, '').toUpperCase(); // Keep only digits and A-Z latin alphabetic\n\n var rearranged = strippedStr.slice(4) + strippedStr.slice(0, 4);\n var alphaCapsReplacedWithDigits = rearranged.replace(/[A-Z]/g, function (char) {\n return char.charCodeAt(0) - 55;\n });\n var remainder = alphaCapsReplacedWithDigits.match(/\\d{1,7}/g).reduce(function (acc, value) {\n return Number(acc + value) % 97;\n }, '');\n return remainder === 1;\n}\n\nfunction isIBAN(str) {\n (0, _assertString.default)(str);\n return hasValidIbanFormat(str) && hasValidIbanChecksum(str);\n}\n\nmodule.exports = exports.default;\nmodule.exports.default = exports.default;\n\n//# sourceURL=webpack:///./node_modules/validator/lib/isIBAN.js?");
/***/ }),
/***/ "./node_modules/validator/lib/isIP.js":
/*!********************************************!*\
!*** ./node_modules/validator/lib/isIP.js ***!
\********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
eval("\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = isIP;\n\nvar _assertString = _interopRequireDefault(__webpack_require__(/*! ./util/assertString */ \"./node_modules/validator/lib/util/assertString.js\"));\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\n/**\n11.3. Examples\n\n The following addresses\n\n fe80::1234 (on the 1st link of the node)\n ff02::5678 (on the 5th link of the node)\n ff08::9abc (on the 10th organization of the node)\n\n would be represented as follows:\n\n fe80::1234%1\n ff02::5678%5\n ff08::9abc%10\n\n (Here we assume a natural translation from a zone index to the\n <zone_id> part, where the Nth zone of any scope is translated into\n \"N\".)\n\n If we use interface names as <zone_id>, those addresses could also be\n represented as follows:\n\n fe80::1234%ne0\n ff02::5678%pvc1.3\n ff08::9abc%interface10\n\n where the interface \"ne0\" belongs to the 1st link, \"pvc1.3\" belongs\n to the 5th link, and \"interface10\" belongs to the 10th organization.\n * * */\nvar ipv4Maybe = /^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$/;\nvar ipv6Block = /^[0-9A-F]{1,4}$/i;\n\nfunction isIP(str) {\n var version = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : '';\n (0, _assertString.default)(str);\n version = String(version);\n\n if (!version) {\n return isIP(str, 4) || isIP(str, 6);\n } else if (version === '4') {\n if (!ipv4Maybe.test(str)) {\n return false;\n }\n\n var parts = str.split('.').sort(function (a, b) {\n return a - b;\n });\n return parts[3] <= 255;\n } else if (version === '6') {\n var addressAndZone = [str]; // ipv6 addresses could have scoped architecture\n // according to https://tools.ietf.org/html/rfc4007#section-11\n\n if (str.includes('%')) {\n addressAndZone = str.split('%');\n\n if (addressAndZone.length !== 2) {\n // it must be just two parts\n return false;\n }\n\n if (!addressAndZone[0].includes(':')) {\n // the first part must be the address\n return false;\n }\n\n if (addressAndZone[1] === '') {\n // the second part must not be empty\n return false;\n }\n }\n\n var blocks = addressAndZone[0].split(':');\n var foundOmissionBlock = false; // marker to indicate ::\n // At least some OS accept the last 32 bits of an IPv6 address\n // (i.e. 2 of the blocks) in IPv4 notation, and RFC 3493 says\n // that '::ffff:a.b.c.d' is valid for IPv4-mapped IPv6 addresses,\n // and '::a.b.c.d' is deprecated, but also valid.\n\n var foundIPv4TransitionBlock = isIP(blocks[blocks.length - 1], 4);\n var expectedNumberOfBlocks = foundIPv4TransitionBlock ? 7 : 8;\n\n if (blocks.length > expectedNumberOfBlocks) {\n return false;\n } // initial or final ::\n\n\n if (str === '::') {\n return true;\n } else if (str.substr(0, 2) === '::') {\n blocks.shift();\n blocks.shift();\n foundOmissionBlock = true;\n } else if (str.substr(str.length - 2) === '::') {\n blocks.pop();\n blocks.pop();\n foundOmissionBlock = true;\n }\n\n for (var i = 0; i < blocks.length; ++i) {\n // test for a :: which can not be at the string start/end\n // since those cases have been handled above\n if (blocks[i] === '' && i > 0 && i < blocks.length - 1) {\n if (foundOmissionBlock) {\n return false; // multiple :: in address\n }\n\n foundOmissionBlock = true;\n } else if (foundIPv4TransitionBlock && i === blocks.length - 1) {// it has been checked before that the last\n // block is a valid IPv4 address\n } else if (!ipv6Block.test(blocks[i])) {\n return false;\n }\n }\n\n if (foundOmissionBlock) {\n return blocks.length >= 1;\n }\n\n return blocks.length === expectedNumberOfBlocks;\n }\n\n return false;\n}\n\nmodule.exports = exports.default;\nmodule.exports.default = exports.default;\n\n//# sourceURL=webpack:///./node_modules/validator/lib/isIP.js?");
/***/ }),
/***/ "./node_modules/validator/lib/isIPRange.js":
/*!*************************************************!*\
!*** ./node_modules/validator/lib/isIPRange.js ***!
\*************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
eval("\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = isIPRange;\n\nvar _assertString = _interopRequireDefault(__webpack_require__(/*! ./util/assertString */ \"./node_modules/validator/lib/util/assertString.js\"));\n\nvar _isIP = _interopRequireDefault(__webpack_require__(/*! ./isIP */ \"./node_modules/validator/lib/isIP.js\"));\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\nvar subnetMaybe = /^\\d{1,2}$/;\n\nfunction isIPRange(str) {\n (0, _assertString.default)(str);\n var parts = str.split('/'); // parts[0] -> ip, parts[1] -> subnet\n\n if (parts.length !== 2) {\n return false;\n }\n\n if (!subnetMaybe.test(parts[1])) {\n return false;\n } // Disallow preceding 0 i.e. 01, 02, ...\n\n\n if (parts[1].length > 1 && parts[1].startsWith('0')) {\n return false;\n }\n\n return (0, _isIP.default)(parts[0], 4) && parts[1] <= 32 && parts[1] >= 0;\n}\n\nmodule.exports = exports.default;\nmodule.exports.default = exports.default;\n\n//# sourceURL=webpack:///./node_modules/validator/lib/isIPRange.js?");
/***/ }),
/***/ "./node_modules/validator/lib/isISBN.js":
/*!**********************************************!*\
!*** ./node_modules/validator/lib/isISBN.js ***!
\**********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
eval("\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = isISBN;\n\nvar _assertString = _interopRequireDefault(__webpack_require__(/*! ./util/assertString */ \"./node_modules/validator/lib/util/assertString.js\"));\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\nvar isbn10Maybe = /^(?:[0-9]{9}X|[0-9]{10})$/;\nvar isbn13Maybe = /^(?:[0-9]{13})$/;\nvar factor = [1, 3];\n\nfunction isISBN(str) {\n var version = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : '';\n (0, _assertString.default)(str);\n version = String(version);\n\n if (!version) {\n return isISBN(str, 10) || isISBN(str, 13);\n }\n\n var sanitized = str.replace(/[\\s-]+/g, '');\n var checksum = 0;\n var i;\n\n if (version === '10') {\n if (!isbn10Maybe.test(sanitized)) {\n return false;\n }\n\n for (i = 0; i < 9; i++) {\n checksum += (i + 1) * sanitized.charAt(i);\n }\n\n if (sanitized.charAt(9) === 'X') {\n checksum += 10 * 10;\n } else {\n checksum += 10 * sanitized.charAt(9);\n }\n\n if (checksum % 11 === 0) {\n return !!sanitized;\n }\n } else if (version === '13') {\n if (!isbn13Maybe.test(sanitized)) {\n return false;\n }\n\n for (i = 0; i < 12; i++) {\n checksum += factor[i % 2] * sanitized.charAt(i);\n }\n\n if (sanitized.charAt(12) - (10 - checksum % 10) % 10 === 0) {\n return !!sanitized;\n }\n }\n\n return false;\n}\n\nmodule.exports = exports.default;\nmodule.exports.default = exports.default;\n\n//# sourceURL=webpack:///./node_modules/validator/lib/isISBN.js?");
/***/ }),
/***/ "./node_modules/validator/lib/isISIN.js":
/*!**********************************************!*\
!*** ./node_modules/validator/lib/isISIN.js ***!
\**********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
eval("\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = isISIN;\n\nvar _assertString = _interopRequireDefault(__webpack_require__(/*! ./util/assertString */ \"./node_modules/validator/lib/util/assertString.js\"));\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\nvar isin = /^[A-Z]{2}[0-9A-Z]{9}[0-9]$/;\n\nfunction isISIN(str) {\n (0, _assertString.default)(str);\n\n if (!isin.test(str)) {\n return false;\n }\n\n var checksumStr = str.replace(/[A-Z]/g, function (character) {\n return parseInt(character, 36);\n });\n var sum = 0;\n var digit;\n var tmpNum;\n var shouldDouble = true;\n\n for (var i = checksumStr.length - 2; i >= 0; i--) {\n digit = checksumStr.substring(i, i + 1);\n tmpNum = parseInt(digit, 10);\n\n if (shouldDouble) {\n tmpNum *= 2;\n\n if (tmpNum >= 10) {\n sum += tmpNum + 1;\n } else {\n sum += tmpNum;\n }\n } else {\n sum += tmpNum;\n }\n\n shouldDouble = !shouldDouble;\n }\n\n return parseInt(str.substr(str.length - 1), 10) === (10000 - sum) % 10;\n}\n\nmodule.exports = exports.default;\nmodule.exports.default = exports.default;\n\n//# sourceURL=webpack:///./node_modules/validator/lib/isISIN.js?");
/***/ }),
/***/ "./node_modules/validator/lib/isISO31661Alpha2.js":
/*!********************************************************!*\
!*** ./node_modules/validator/lib/isISO31661Alpha2.js ***!
\********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
eval("\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = isISO31661Alpha2;\n\nvar _assertString = _interopRequireDefault(__webpack_require__(/*! ./util/assertString */ \"./node_modules/validator/lib/util/assertString.js\"));\n\nvar _includes = _interopRequireDefault(__webpack_require__(/*! ./util/includes */ \"./node_modules/validator/lib/util/includes.js\"));\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\n// from https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2\nvar validISO31661Alpha2CountriesCodes = ['AD', 'AE', 'AF', 'AG', 'AI', 'AL', 'AM', 'AO', 'AQ', 'AR', 'AS', 'AT', 'AU', 'AW', 'AX', 'AZ', 'BA', 'BB', 'BD', 'BE', 'BF', 'BG', 'BH', 'BI', 'BJ', 'BL', 'BM', 'BN', 'BO', 'BQ', 'BR', 'BS', 'BT', 'BV', 'BW', 'BY', 'BZ', 'CA', 'CC', 'CD', 'CF', 'CG', 'CH', 'CI', 'CK', 'CL', 'CM', 'CN', 'CO', 'CR', 'CU', 'CV', 'CW', 'CX', 'CY', 'CZ', 'DE', 'DJ', 'DK', 'DM', 'DO', 'DZ', 'EC', 'EE', 'EG', 'EH', 'ER', 'ES', 'ET', 'FI', 'FJ', 'FK', 'FM', 'FO', 'FR', 'GA', 'GB', 'GD', 'GE', 'GF', 'GG', 'GH', 'GI', 'GL', 'GM', 'GN', 'GP', 'GQ', 'GR', 'GS', 'GT', 'GU', 'GW', 'GY', 'HK', 'HM', 'HN', 'HR', 'HT', 'HU', 'ID', 'IE', 'IL', 'IM', 'IN', 'IO', 'IQ', 'IR', 'IS', 'IT', 'JE', 'JM', 'JO', 'JP', 'KE', 'KG', 'KH', 'KI', 'KM', 'KN', 'KP', 'KR', 'KW', 'KY', 'KZ', 'LA', 'LB', 'LC', 'LI', 'LK', 'LR', 'LS', 'LT', 'LU', 'LV', 'LY', 'MA', 'MC', 'MD', 'ME', 'MF', 'MG', 'MH', 'MK', 'ML', 'MM', 'MN', 'MO', 'MP', 'MQ', 'MR', 'MS', 'MT', 'MU', 'MV', 'MW', 'MX', 'MY', 'MZ', 'NA', 'NC', 'NE', 'NF', 'NG', 'NI', 'NL', 'NO', 'NP', 'NR', 'NU', 'NZ', 'OM', 'PA', 'PE', 'PF', 'PG', 'PH', 'PK', 'PL', 'PM', 'PN', 'PR', 'PS', 'PT', 'PW', 'PY', 'QA', 'RE', 'RO', 'RS', 'RU', 'RW', 'SA', 'SB', 'SC', 'SD', 'SE', 'SG', 'SH', 'SI', 'SJ', 'SK', 'SL', 'SM', 'SN', 'SO', 'SR', 'SS', 'ST', 'SV', 'SX', 'SY', 'SZ', 'TC', 'TD', 'TF', 'TG', 'TH', 'TJ', 'TK', 'TL', 'TM', 'TN', 'TO', 'TR', 'TT', 'TV', 'TW', 'TZ', 'UA', 'UG', 'UM', 'US', 'UY', 'UZ', 'VA', 'VC', 'VE', 'VG', 'VI', 'VN', 'VU', 'WF', 'WS', 'YE', 'YT', 'ZA', 'ZM', 'ZW'];\n\nfunction isISO31661Alpha2(str) {\n (0, _assertString.default)(str);\n return (0, _includes.default)(validISO31661Alpha2CountriesCodes, str.toUpperCase());\n}\n\nmodule.exports = exports.default;\nmodule.exports.default = exports.default;\n\n//# sourceURL=webpack:///./node_modules/validator/lib/isISO31661Alpha2.js?");
/***/ }),
/***/ "./node_modules/validator/lib/isISO31661Alpha3.js":
/*!********************************************************!*\
!*** ./node_modules/validator/lib/isISO31661Alpha3.js ***!
\********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
eval("\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = isISO31661Alpha3;\n\nvar _assertString = _interopRequireDefault(__webpack_require__(/*! ./util/assertString */ \"./node_modules/validator/lib/util/assertString.js\"));\n\nvar _includes = _interopRequireDefault(__webpack_require__(/*! ./util/includes */ \"./node_modules/validator/lib/util/includes.js\"));\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\n// from https://en.wikipedia.org/wiki/ISO_3166-1_alpha-3\nvar validISO31661Alpha3CountriesCodes = ['AFG', 'ALA', 'ALB', 'DZA', 'ASM', 'AND', 'AGO', 'AIA', 'ATA', 'ATG', 'ARG', 'ARM', 'ABW', 'AUS', 'AUT', 'AZE', 'BHS', 'BHR', 'BGD', 'BRB', 'BLR', 'BEL', 'BLZ', 'BEN', 'BMU', 'BTN', 'BOL', 'BES', 'BIH', 'BWA', 'BVT', 'BRA', 'IOT', 'BRN', 'BGR', 'BFA', 'BDI', 'KHM', 'CMR', 'CAN', 'CPV', 'CYM', 'CAF', 'TCD', 'CHL', 'CHN', 'CXR', 'CCK', 'COL', 'COM', 'COG', 'COD', 'COK', 'CRI', 'CIV', 'HRV', 'CUB', 'CUW', 'CYP', 'CZE', 'DNK', 'DJI', 'DMA', 'DOM', 'ECU', 'EGY', 'SLV', 'GNQ', 'ERI', 'EST', 'ETH', 'FLK', 'FRO', 'FJI', 'FIN', 'FRA', 'GUF', 'PYF', 'ATF', 'GAB', 'GMB', 'GEO', 'DEU', 'GHA', 'GIB', 'GRC', 'GRL', 'GRD', 'GLP', 'GUM', 'GTM', 'GGY', 'GIN', 'GNB', 'GUY', 'HTI', 'HMD', 'VAT', 'HND', 'HKG', 'HUN', 'ISL', 'IND', 'IDN', 'IRN', 'IRQ', 'IRL', 'IMN', 'ISR', 'ITA', 'JAM', 'JPN', 'JEY', 'JOR', 'KAZ', 'KEN', 'KIR', 'PRK', 'KOR', 'KWT', 'KGZ', 'LAO', 'LVA', 'LBN', 'LSO', 'LBR', 'LBY', 'LIE', 'LTU', 'LUX', 'MAC', 'MKD', 'MDG', 'MWI', 'MYS', 'MDV', 'MLI', 'MLT', 'MHL', 'MTQ', 'MRT', 'MUS', 'MYT', 'MEX', 'FSM', 'MDA', 'MCO', 'MNG', 'MNE', 'MSR', 'MAR', 'MOZ', 'MMR', 'NAM', 'NRU', 'NPL', 'NLD', 'NCL', 'NZL', 'NIC', 'NER', 'NGA', 'NIU', 'NFK', 'MNP', 'NOR', 'OMN', 'PAK', 'PLW', 'PSE', 'PAN', 'PNG', 'PRY', 'PER', 'PHL', 'PCN', 'POL', 'PRT', 'PRI', 'QAT', 'REU', 'ROU', 'RUS', 'RWA', 'BLM', 'SHN', 'KNA', 'LCA', 'MAF', 'SPM', 'VCT', 'WSM', 'SMR', 'STP', 'SAU', 'SEN', 'SRB', 'SYC', 'SLE', 'SGP', 'SXM', 'SVK', 'SVN', 'SLB', 'SOM', 'ZAF', 'SGS', 'SSD', 'ESP', 'LKA', 'SDN', 'SUR', 'SJM', 'SWZ', 'SWE', 'CHE', 'SYR', 'TWN', 'TJK', 'TZA', 'THA', 'TLS', 'TGO', 'TKL', 'TON', 'TTO', 'TUN', 'TUR', 'TKM', 'TCA', 'TUV', 'UGA', 'UKR', 'ARE', 'GBR', 'USA', 'UMI', 'URY', 'UZB', 'VUT', 'VEN', 'VNM', 'VGB', 'VIR', 'WLF', 'ESH', 'YEM', 'ZMB', 'ZWE'];\n\nfunction isISO31661Alpha3(str) {\n (0, _assertString.default)(str);\n return (0, _includes.default)(validISO31661Alpha3CountriesCodes, str.toUpperCase());\n}\n\nmodule.exports = exports.default;\nmodule.exports.default = exports.default;\n\n//# sourceURL=webpack:///./node_modules/validator/lib/isISO31661Alpha3.js?");
/***/ }),
/***/ "./node_modules/validator/lib/isISO8601.js":
/*!*************************************************!*\
!*** ./node_modules/validator/lib/isISO8601.js ***!
\*************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
eval("\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = isISO8601;\n\nvar _assertString = _interopRequireDefault(__webpack_require__(/*! ./util/assertString */ \"./node_modules/validator/lib/util/assertString.js\"));\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\n/* eslint-disable max-len */\n// from http://goo.gl/0ejHHW\nvar iso8601 = /^([\\+-]?\\d{4}(?!\\d{2}\\b))((-?)((0[1-9]|1[0-2])(\\3([12]\\d|0[1-9]|3[01]))?|W([0-4]\\d|5[0-3])(-?[1-7])?|(00[1-9]|0[1-9]\\d|[12]\\d{2}|3([0-5]\\d|6[1-6])))([T\\s]((([01]\\d|2[0-3])((:?)[0-5]\\d)?|24:?00)([\\.,]\\d+(?!:))?)?(\\17[0-5]\\d([\\.,]\\d+)?)?([zZ]|([\\+-])([01]\\d|2[0-3]):?([0-5]\\d)?)?)?)?$/;\n/* eslint-enable max-len */\n\nvar isValidDate = function isValidDate(str) {\n // str must have passed the ISO8601 check\n // this check is meant to catch invalid dates\n // like 2009-02-31\n // first check for ordinal dates\n var ordinalMatch = str.match(/^(\\d{4})-?(\\d{3})([ T]{1}\\.*|$)/);\n\n if (ordinalMatch) {\n var oYear = Number(ordinalMatch[1]);\n var oDay = Number(ordinalMatch[2]); // if is leap year\n\n if (oYear % 4 === 0 && oYear % 100 !== 0 || oYear % 400 === 0) return oDay <= 366;\n return oDay <= 365;\n }\n\n var match = str.match(/(\\d{4})-?(\\d{0,2})-?(\\d*)/).map(Number);\n var year = match[1];\n var month = match[2];\n var day = match[3];\n var monthString = month ? \"0\".concat(month).slice(-2) : month;\n var dayString = day ? \"0\".concat(day).slice(-2) : day; // create a date object and compare\n\n var d = new Date(\"\".concat(year, \"-\").concat(monthString || '01', \"-\").concat(dayString || '01'));\n\n if (month && day) {\n return d.getUTCFullYear() === year && d.getUTCMonth() + 1 === month && d.getUTCDate() === day;\n }\n\n return true;\n};\n\nfunction isISO8601(str, options) {\n (0, _assertString.default)(str);\n var check = iso8601.test(str);\n if (!options) return check;\n if (check && options.strict) return isValidDate(str);\n return check;\n}\n\nmodule.exports = exports.default;\nmodule.exports.default = exports.default;\n\n//# sourceURL=webpack:///./node_modules/validator/lib/isISO8601.js?");
/***/ }),
/***/ "./node_modules/validator/lib/isISRC.js":
/*!**********************************************!*\
!*** ./node_modules/validator/lib/isISRC.js ***!
\**********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
eval("\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = isISRC;\n\nvar _assertString = _interopRequireDefault(__webpack_require__(/*! ./util/assertString */ \"./node_modules/validator/lib/util/assertString.js\"));\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\n// see http://isrc.ifpi.org/en/isrc-standard/code-syntax\nvar isrc = /^[A-Z]{2}[0-9A-Z]{3}\\d{2}\\d{5}$/;\n\nfunction isISRC(str) {\n (0, _assertString.default)(str);\n return isrc.test(str);\n}\n\nmodule.exports = exports.default;\nmodule.exports.default = exports.default;\n\n//# sourceURL=webpack:///./node_modules/validator/lib/isISRC.js?");
/***/ }),
/***/ "./node_modules/validator/lib/isISSN.js":
/*!**********************************************!*\
!*** ./node_modules/validator/lib/isISSN.js ***!
\**********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
eval("\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = isISSN;\n\nvar _assertString = _interopRequireDefault(__webpack_require__(/*! ./util/assertString */ \"./node_modules/validator/lib/util/assertString.js\"));\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\nvar issn = '^\\\\d{4}-?\\\\d{3}[\\\\dX]$';\n\nfunction isISSN(str) {\n var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};\n (0, _assertString.default)(str);\n var testIssn = issn;\n testIssn = options.require_hyphen ? testIssn.replace('?', '') : testIssn;\n testIssn = options.case_sensitive ? new RegExp(testIssn) : new RegExp(testIssn, 'i');\n\n if (!testIssn.test(str)) {\n return false;\n }\n\n var digits = str.replace('-', '').toUpperCase();\n var checksum = 0;\n\n for (var i = 0; i < digits.length; i++) {\n var digit = digits[i];\n checksum += (digit === 'X' ? 10 : +digit) * (8 - i);\n }\n\n return checksum % 11 === 0;\n}\n\nmodule.exports = exports.default;\nmodule.exports.default = exports.default;\n\n//# sourceURL=webpack:///./node_modules/validator/lib/isISSN.js?");
/***/ }),
/***/ "./node_modules/validator/lib/isIdentityCard.js":
/*!******************************************************!*\
!*** ./node_modules/validator/lib/isIdentityCard.js ***!
\******************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
eval("\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = isIdentityCard;\n\nvar _assertString = _interopRequireDefault(__webpack_require__(/*! ./util/assertString */ \"./node_modules/validator/lib/util/assertString.js\"));\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\nvar validators = {\n ES: function ES(str) {\n (0, _assertString.default)(str);\n var DNI = /^[0-9X-Z][0-9]{7}[TRWAGMYFPDXBNJZSQVHLCKE]$/;\n var charsValue = {\n X: 0,\n Y: 1,\n Z: 2\n };\n var controlDigits = ['T', 'R', 'W', 'A', 'G', 'M', 'Y', 'F', 'P', 'D', 'X', 'B', 'N', 'J', 'Z', 'S', 'Q', 'V', 'H', 'L', 'C', 'K', 'E']; // sanitize user input\n\n var sanitized = str.trim().toUpperCase(); // validate the data structure\n\n if (!DNI.test(sanitized)) {\n return false;\n } // validate the control digit\n\n\n var number = sanitized.slice(0, -1).replace(/[X,Y,Z]/g, function (char) {\n return charsValue[char];\n });\n return sanitized.endsWith(controlDigits[number % 23]);\n },\n 'he-IL': function heIL(str) {\n var DNI = /^\\d{9}$/; // sanitize user input\n\n var sanitized = str.trim(); // validate the data structure\n\n if (!DNI.test(sanitized)) {\n return false;\n }\n\n var id = sanitized;\n var sum = 0,\n incNum;\n\n for (var i = 0; i < id.length; i++) {\n incNum = Number(id[i]) * (i % 2 + 1); // Multiply number by 1 or 2\n\n sum += incNum > 9 ? incNum - 9 : incNum; // Sum the digits up and add to total\n }\n\n return sum % 10 === 0;\n },\n 'zh-TW': function zhTW(str) {\n var ALPHABET_CODES = {\n A: 10,\n B: 11,\n C: 12,\n D: 13,\n E: 14,\n F: 15,\n G: 16,\n H: 17,\n I: 34,\n J: 18,\n K: 19,\n L: 20,\n M: 21,\n N: 22,\n O: 35,\n P: 23,\n Q: 24,\n R: 25,\n S: 26,\n T: 27,\n U: 28,\n V: 29,\n W: 32,\n X: 30,\n Y: 31,\n Z: 33\n };\n var sanitized = str.trim().toUpperCase();\n if (!/^[A-Z][0-9]{9}$/.test(sanitized)) return false;\n return Array.from(sanitized).reduce(function (sum, number, index) {\n if (index === 0) {\n var code = ALPHABET_CODES[number];\n return code % 10 * 9 + Math.floor(code / 10);\n }\n\n if (index === 9) {\n return (10 - sum % 10 - Number(number)) % 10 === 0;\n }\n\n return sum + Number(number) * (9 - index);\n }, 0);\n }\n};\n\nfunction isIdentityCard(str, locale) {\n (0, _assertString.default)(str);\n\n if (locale in validators) {\n return validators[locale](str);\n } else if (locale === 'any') {\n for (var key in validators) {\n // https://github.com/gotwarlost/istanbul/blob/master/ignoring-code-for-coverage.md#ignoring-code-for-coverage-purposes\n // istanbul ignore else\n if (validators.hasOwnProperty(key)) {\n var validator = validators[key];\n\n if (validator(str)) {\n return true;\n }\n }\n }\n\n return false;\n }\n\n throw new Error(\"Invalid locale '\".concat(locale, \"'\"));\n}\n\nmodule.exports = exports.default;\nmodule.exports.default = exports.default;\n\n//# sourceURL=webpack:///./node_modules/validator/lib/isIdentityCard.js?");
/***/ }),
/***/ "./node_modules/validator/lib/isIn.js":
/*!********************************************!*\
!*** ./node_modules/validator/lib/isIn.js ***!
\********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
eval("\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = isIn;\n\nvar _assertString = _interopRequireDefault(__webpack_require__(/*! ./util/assertString */ \"./node_modules/validator/lib/util/assertString.js\"));\n\nvar _toString = _interopRequireDefault(__webpack_require__(/*! ./util/toString */ \"./node_modules/validator/lib/util/toString.js\"));\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\nfunction _typeof(obj) { \"@babel/helpers - typeof\"; if (typeof Symbol === \"function\" && typeof Symbol.iterator === \"symbol\") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === \"function\" && obj.constructor === Symbol && obj !== Symbol.prototype ? \"symbol\" : typeof obj; }; } return _typeof(obj); }\n\nfunction isIn(str, options) {\n (0, _assertString.default)(str);\n var i;\n\n if (Object.prototype.toString.call(options) === '[object Array]') {\n var array = [];\n\n for (i in options) {\n // https://github.com/gotwarlost/istanbul/blob/master/ignoring-code-for-coverage.md#ignoring-code-for-coverage-purposes\n // istanbul ignore else\n if ({}.hasOwnProperty.call(options, i)) {\n array[i] = (0, _toString.default)(options[i]);\n }\n }\n\n return array.indexOf(str) >= 0;\n } else if (_typeof(options) === 'object') {\n return options.hasOwnProperty(str);\n } else if (options && typeof options.indexOf === 'function') {\n return options.indexOf(str) >= 0;\n }\n\n return false;\n}\n\nmodule.exports = exports.default;\nmodule.exports.default = exports.default;\n\n//# sourceURL=webpack:///./node_modules/validator/lib/isIn.js?");
/***/ }),
/***/ "./node_modules/validator/lib/isInt.js":
/*!*********************************************!*\
!*** ./node_modules/validator/lib/isInt.js ***!
\*********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
eval("\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = isInt;\n\nvar _assertString = _interopRequireDefault(__webpack_require__(/*! ./util/assertString */ \"./node_modules/validator/lib/util/assertString.js\"));\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\nvar int = /^(?:[-+]?(?:0|[1-9][0-9]*))$/;\nvar intLeadingZeroes = /^[-+]?[0-9]+$/;\n\nfunction isInt(str, options) {\n (0, _assertString.default)(str);\n options = options || {}; // Get the regex to use for testing, based on whether\n // leading zeroes are allowed or not.\n\n var regex = options.hasOwnProperty('allow_leading_zeroes') && !options.allow_leading_zeroes ? int : intLeadingZeroes; // Check min/max/lt/gt\n\n var minCheckPassed = !options.hasOwnProperty('min') || str >= options.min;\n var maxCheckPassed = !options.hasOwnProperty('max') || str <= options.max;\n var ltCheckPassed = !options.hasOwnProperty('lt') || str < options.lt;\n var gtCheckPassed = !options.hasOwnProperty('gt') || str > options.gt;\n return regex.test(str) && minCheckPassed && maxCheckPassed && ltCheckPassed && gtCheckPassed;\n}\n\nmodule.exports = exports.default;\nmodule.exports.default = exports.default;\n\n//# sourceURL=webpack:///./node_modules/validator/lib/isInt.js?");
/***/ }),
/***/ "./node_modules/validator/lib/isJSON.js":
/*!**********************************************!*\
!*** ./node_modules/validator/lib/isJSON.js ***!
\**********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
eval("\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = isJSON;\n\nvar _assertString = _interopRequireDefault(__webpack_require__(/*! ./util/assertString */ \"./node_modules/validator/lib/util/assertString.js\"));\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\nfunction _typeof(obj) { \"@babel/helpers - typeof\"; if (typeof Symbol === \"function\" && typeof Symbol.iterator === \"symbol\") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === \"function\" && obj.constructor === Symbol && obj !== Symbol.prototype ? \"symbol\" : typeof obj; }; } return _typeof(obj); }\n\nfunction isJSON(str) {\n (0, _assertString.default)(str);\n\n try {\n var obj = JSON.parse(str);\n return !!obj && _typeof(obj) === 'object';\n } catch (e) {\n /* ignore */\n }\n\n return false;\n}\n\nmodule.exports = exports.default;\nmodule.exports.default = exports.default;\n\n//# sourceURL=webpack:///./node_modules/validator/lib/isJSON.js?");
/***/ }),
/***/ "./node_modules/validator/lib/isJWT.js":
/*!*********************************************!*\
!*** ./node_modules/validator/lib/isJWT.js ***!
\*********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
eval("\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = isJWT;\n\nvar _assertString = _interopRequireDefault(__webpack_require__(/*! ./util/assertString */ \"./node_modules/validator/lib/util/assertString.js\"));\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\nvar jwt = /^([A-Za-z0-9\\-_~+\\/]+[=]{0,2})\\.([A-Za-z0-9\\-_~+\\/]+[=]{0,2})(?:\\.([A-Za-z0-9\\-_~+\\/]+[=]{0,2}))?$/;\n\nfunction isJWT(str) {\n (0, _assertString.default)(str);\n return jwt.test(str);\n}\n\nmodule.exports = exports.default;\nmodule.exports.default = exports.default;\n\n//# sourceURL=webpack:///./node_modules/validator/lib/isJWT.js?");
/***/ }),
/***/ "./node_modules/validator/lib/isLatLong.js":
/*!*************************************************!*\
!*** ./node_modules/validator/lib/isLatLong.js ***!
\*************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
eval("\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = _default;\n\nvar _assertString = _interopRequireDefault(__webpack_require__(/*! ./util/assertString */ \"./node_modules/validator/lib/util/assertString.js\"));\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\nvar lat = /^\\(?[+-]?(90(\\.0+)?|[1-8]?\\d(\\.\\d+)?)$/;\nvar long = /^\\s?[+-]?(180(\\.0+)?|1[0-7]\\d(\\.\\d+)?|\\d{1,2}(\\.\\d+)?)\\)?$/;\n\nfunction _default(str) {\n (0, _assertString.default)(str);\n if (!str.includes(',')) return false;\n var pair = str.split(',');\n if (pair[0].startsWith('(') && !pair[1].endsWith(')') || pair[1].endsWith(')') && !pair[0].startsWith('(')) return false;\n return lat.test(pair[0]) && long.test(pair[1]);\n}\n\nmodule.exports = exports.default;\nmodule.exports.default = exports.default;\n\n//# sourceURL=webpack:///./node_modules/validator/lib/isLatLong.js?");
/***/ }),
/***/ "./node_modules/validator/lib/isLength.js":
/*!************************************************!*\
!*** ./node_modules/validator/lib/isLength.js ***!
\************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
eval("\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = isLength;\n\nvar _assertString = _interopRequireDefault(__webpack_require__(/*! ./util/assertString */ \"./node_modules/validator/lib/util/assertString.js\"));\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\nfunction _typeof(obj) { \"@babel/helpers - typeof\"; if (typeof Symbol === \"function\" && typeof Symbol.iterator === \"symbol\") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === \"function\" && obj.constructor === Symbol && obj !== Symbol.prototype ? \"symbol\" : typeof obj; }; } return _typeof(obj); }\n\n/* eslint-disable prefer-rest-params */\nfunction isLength(str, options) {\n (0, _assertString.default)(str);\n var min;\n var max;\n\n if (_typeof(options) === 'object') {\n min = options.min || 0;\n max = options.max;\n } else {\n // backwards compatibility: isLength(str, min [, max])\n min = arguments[1] || 0;\n max = arguments[2];\n }\n\n var surrogatePairs = str.match(/[\\uD800-\\uDBFF][\\uDC00-\\uDFFF]/g) || [];\n var len = str.length - surrogatePairs.length;\n return len >= min && (typeof max === 'undefined' || len <= max);\n}\n\nmodule.exports = exports.default;\nmodule.exports.default = exports.default;\n\n//# sourceURL=webpack:///./node_modules/validator/lib/isLength.js?");
/***/ }),
/***/ "./node_modules/validator/lib/isLocale.js":
/*!************************************************!*\
!*** ./node_modules/validator/lib/isLocale.js ***!
\************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
eval("\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = isLocale;\n\nvar _assertString = _interopRequireDefault(__webpack_require__(/*! ./util/assertString */ \"./node_modules/validator/lib/util/assertString.js\"));\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\nvar localeReg = /^[A-z]{2,4}([_-]([A-z]{4}|[\\d]{3}))?([_-]([A-z]{2}|[\\d]{3}))?$/;\n\nfunction isLocale(str) {\n (0, _assertString.default)(str);\n\n if (str === 'en_US_POSIX' || str === 'ca_ES_VALENCIA') {\n return true;\n }\n\n return localeReg.test(str);\n}\n\nmodule.exports = exports.default;\nmodule.exports.default = exports.default;\n\n//# sourceURL=webpack:///./node_modules/validator/lib/isLocale.js?");
/***/ }),
/***/ "./node_modules/validator/lib/isLowercase.js":
/*!***************************************************!*\
!*** ./node_modules/validator/lib/isLowercase.js ***!
\***************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
eval("\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = isLowercase;\n\nvar _assertString = _interopRequireDefault(__webpack_require__(/*! ./util/assertString */ \"./node_modules/validator/lib/util/assertString.js\"));\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\nfunction isLowercase(str) {\n (0, _assertString.default)(str);\n return str === str.toLowerCase();\n}\n\nmodule.exports = exports.default;\nmodule.exports.default = exports.default;\n\n//# sourceURL=webpack:///./node_modules/validator/lib/isLowercase.js?");
/***/ }),
/***/ "./node_modules/validator/lib/isMACAddress.js":
/*!****************************************************!*\
!*** ./node_modules/validator/lib/isMACAddress.js ***!
\****************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
eval("\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = isMACAddress;\n\nvar _assertString = _interopRequireDefault(__webpack_require__(/*! ./util/assertString */ \"./node_modules/validator/lib/util/assertString.js\"));\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\nvar macAddress = /^([0-9a-fA-F][0-9a-fA-F]:){5}([0-9a-fA-F][0-9a-fA-F])$/;\nvar macAddressNoColons = /^([0-9a-fA-F]){12}$/;\nvar macAddressWithHyphen = /^([0-9a-fA-F][0-9a-fA-F]-){5}([0-9a-fA-F][0-9a-fA-F])$/;\nvar macAddressWithSpaces = /^([0-9a-fA-F][0-9a-fA-F]\\s){5}([0-9a-fA-F][0-9a-fA-F])$/;\nvar macAddressWithDots = /^([0-9a-fA-F]{4}).([0-9a-fA-F]{4}).([0-9a-fA-F]{4})$/;\n\nfunction isMACAddress(str, options) {\n (0, _assertString.default)(str);\n\n if (options && options.no_colons) {\n return macAddressNoColons.test(str);\n }\n\n return macAddress.test(str) || macAddressWithHyphen.test(str) || macAddressWithSpaces.test(str) || macAddressWithDots.test(str);\n}\n\nmodule.exports = exports.default;\nmodule.exports.default = exports.default;\n\n//# sourceURL=webpack:///./node_modules/validator/lib/isMACAddress.js?");
/***/ }),
/***/ "./node_modules/validator/lib/isMD5.js":
/*!*********************************************!*\
!*** ./node_modules/validator/lib/isMD5.js ***!
\*********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
eval("\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = isMD5;\n\nvar _assertString = _interopRequireDefault(__webpack_require__(/*! ./util/assertString */ \"./node_modules/validator/lib/util/assertString.js\"));\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\nvar md5 = /^[a-f0-9]{32}$/;\n\nfunction isMD5(str) {\n (0, _assertString.default)(str);\n return md5.test(str);\n}\n\nmodule.exports = exports.default;\nmodule.exports.default = exports.default;\n\n//# sourceURL=webpack:///./node_modules/validator/lib/isMD5.js?");
/***/ }),
/***/ "./node_modules/validator/lib/isMagnetURI.js":
/*!***************************************************!*\
!*** ./node_modules/validator/lib/isMagnetURI.js ***!
\***************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
eval("\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = isMagnetURI;\n\nvar _assertString = _interopRequireDefault(__webpack_require__(/*! ./util/assertString */ \"./node_modules/validator/lib/util/assertString.js\"));\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\nvar magnetURI = /^magnet:\\?xt=urn:[a-z0-9]+:[a-z0-9]{32,40}&dn=.+&tr=.+$/i;\n\nfunction isMagnetURI(url) {\n (0, _assertString.default)(url);\n return magnetURI.test(url.trim());\n}\n\nmodule.exports = exports.default;\nmodule.exports.default = exports.default;\n\n//# sourceURL=webpack:///./node_modules/validator/lib/isMagnetURI.js?");
/***/ }),
/***/ "./node_modules/validator/lib/isMimeType.js":
/*!**************************************************!*\
!*** ./node_modules/validator/lib/isMimeType.js ***!
\**************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
eval("\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = isMimeType;\n\nvar _assertString = _interopRequireDefault(__webpack_require__(/*! ./util/assertString */ \"./node_modules/validator/lib/util/assertString.js\"));\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\n/*\n Checks if the provided string matches to a correct Media type format (MIME type)\n\n This function only checks is the string format follows the\n etablished rules by the according RFC specifications.\n This function supports 'charset' in textual media types\n (https://tools.ietf.org/html/rfc6657).\n\n This function does not check against all the media types listed\n by the IANA (https://www.iana.org/assignments/media-types/media-types.xhtml)\n because of lightness purposes : it would require to include\n all these MIME types in this librairy, which would weigh it\n significantly. This kind of effort maybe is not worth for the use that\n this function has in this entire librairy.\n\n More informations in the RFC specifications :\n - https://tools.ietf.org/html/rfc2045\n - https://tools.ietf.org/html/rfc2046\n - https://tools.ietf.org/html/rfc7231#section-3.1.1.1\n - https://tools.ietf.org/html/rfc7231#section-3.1.1.5\n*/\n// Match simple MIME types\n// NB :\n// Subtype length must not exceed 100 characters.\n// This rule does not comply to the RFC specs (what is the max length ?).\nvar mimeTypeSimple = /^(application|audio|font|image|message|model|multipart|text|video)\\/[a-zA-Z0-9\\.\\-\\+]{1,100}$/i; // eslint-disable-line max-len\n// Handle \"charset\" in \"text/*\"\n\nvar mimeTypeText = /^text\\/[a-zA-Z0-9\\.\\-\\+]{1,100};\\s?charset=(\"[a-zA-Z0-9\\.\\-\\+\\s]{0,70}\"|[a-zA-Z0-9\\.\\-\\+]{0,70})(\\s?\\([a-zA-Z0-9\\.\\-\\+\\s]{1,20}\\))?$/i; // eslint-disable-line max-len\n// Handle \"boundary\" in \"multipart/*\"\n\nvar mimeTypeMultipart = /^multipart\\/[a-zA-Z0-9\\.\\-\\+]{1,100}(;\\s?(boundary|charset)=(\"[a-zA-Z0-9\\.\\-\\+\\s]{0,70}\"|[a-zA-Z0-9\\.\\-\\+]{0,70})(\\s?\\([a-zA-Z0-9\\.\\-\\+\\s]{1,20}\\))?){0,2}$/i; // eslint-disable-line max-len\n\nfunction isMimeType(str) {\n (0, _assertString.default)(str);\n return mimeTypeSimple.test(str) || mimeTypeText.test(str) || mimeTypeMultipart.test(str);\n}\n\nmodule.exports = exports.default;\nmodule.exports.default = exports.default;\n\n//# sourceURL=webpack:///./node_modules/validator/lib/isMimeType.js?");
/***/ }),
/***/ "./node_modules/validator/lib/isMobilePhone.js":
/*!*****************************************************!*\
!*** ./node_modules/validator/lib/isMobilePhone.js ***!
\*****************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
eval("\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = isMobilePhone;\nexports.locales = void 0;\n\nvar _assertString = _interopRequireDefault(__webpack_require__(/*! ./util/assertString */ \"./node_modules/validator/lib/util/assertString.js\"));\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\n/* eslint-disable max-len */\nvar phones = {\n 'am-AM': /^(\\+?374|0)((10|[9|7][0-9])\\d{6}$|[2-4]\\d{7}$)/,\n 'ar-AE': /^((\\+?971)|0)?5[024568]\\d{7}$/,\n 'ar-BH': /^(\\+?973)?(3|6)\\d{7}$/,\n 'ar-DZ': /^(\\+?213|0)(5|6|7)\\d{8}$/,\n 'ar-EG': /^((\\+?20)|0)?1[0125]\\d{8}$/,\n 'ar-IQ': /^(\\+?964|0)?7[0-9]\\d{8}$/,\n 'ar-JO': /^(\\+?962|0)?7[789]\\d{7}$/,\n 'ar-KW': /^(\\+?965)[569]\\d{7}$/,\n 'ar-SA': /^(!?(\\+?966)|0)?5\\d{8}$/,\n 'ar-SY': /^(!?(\\+?963)|0)?9\\d{8}$/,\n 'ar-TN': /^(\\+?216)?[2459]\\d{7}$/,\n 'be-BY': /^(\\+?375)?(24|25|29|33|44)\\d{7}$/,\n 'bg-BG': /^(\\+?359|0)?8[789]\\d{7}$/,\n 'bn-BD': /^(\\+?880|0)1[13456789][0-9]{8}$/,\n 'cs-CZ': /^(\\+?420)? ?[1-9][0-9]{2} ?[0-9]{3} ?[0-9]{3}$/,\n 'da-DK': /^(\\+?45)?\\s?\\d{2}\\s?\\d{2}\\s?\\d{2}\\s?\\d{2}$/,\n 'de-DE': /^(\\+49)?0?1(5[0-25-9]\\d|6([23]|0\\d?)|7([0-57-9]|6\\d))\\d{7}$/,\n 'de-AT': /^(\\+43|0)\\d{1,4}\\d{3,12}$/,\n 'el-GR': /^(\\+?30|0)?(69\\d{8})$/,\n 'en-AU': /^(\\+?61|0)4\\d{8}$/,\n 'en-GB': /^(\\+?44|0)7\\d{9}$/,\n 'en-GG': /^(\\+?44|0)1481\\d{6}$/,\n 'en-GH': /^(\\+233|0)(20|50|24|54|27|57|26|56|23|28)\\d{7}$/,\n 'en-HK': /^(\\+?852[-\\s]?)?[456789]\\d{3}[-\\s]?\\d{4}$/,\n 'en-MO': /^(\\+?853[-\\s]?)?[6]\\d{3}[-\\s]?\\d{4}$/,\n 'en-IE': /^(\\+?353|0)8[356789]\\d{7}$/,\n 'en-IN': /^(\\+?91|0)?[6789]\\d{9}$/,\n 'en-KE': /^(\\+?254|0)(7|1)\\d{8}$/,\n 'en-MT': /^(\\+?356|0)?(99|79|77|21|27|22|25)[0-9]{6}$/,\n 'en-MU': /^(\\+?230|0)?\\d{8}$/,\n 'en-NG': /^(\\+?234|0)?[789]\\d{9}$/,\n 'en-NZ': /^(\\+?64|0)[28]\\d{7,9}$/,\n 'en-PK': /^((\\+92)|(0092))-{0,1}\\d{3}-{0,1}\\d{7}$|^\\d{11}$|^\\d{4}-\\d{7}$/,\n 'en-RW': /^(\\+?250|0)?[7]\\d{8}$/,\n 'en-SG': /^(\\+65)?[89]\\d{7}$/,\n 'en-TZ': /^(\\+?255|0)?[67]\\d{8}$/,\n 'en-UG': /^(\\+?256|0)?[7]\\d{8}$/,\n 'en-US': /^((\\+1|1)?( |-)?)?(\\([2-9][0-9]{2}\\)|[2-9][0-9]{2})( |-)?([2-9][0-9]{2}( |-)?[0-9]{4})$/,\n 'en-ZA': /^(\\+?27|0)\\d{9}$/,\n 'en-ZM': /^(\\+?26)?09[567]\\d{7}$/,\n 'es-CL': /^(\\+?56|0)[2-9]\\d{1}\\d{7}$/,\n 'es-EC': /^(\\+?593|0)([2-7]|9[2-9])\\d{7}$/,\n 'es-ES': /^(\\+?34)?(6\\d{1}|7[1234])\\d{7}$/,\n 'es-MX': /^(\\+?52)?(1|01)?\\d{10,11}$/,\n 'es-PA': /^(\\+?507)\\d{7,8}$/,\n 'es-PY': /^(\\+?595|0)9[9876]\\d{7}$/,\n 'es-UY': /^(\\+598|0)9[1-9][\\d]{6}$/,\n 'et-EE': /^(\\+?372)?\\s?(5|8[1-4])\\s?([0-9]\\s?){6,7}$/,\n 'fa-IR': /^(\\+?98[\\-\\s]?|0)9[0-39]\\d[\\-\\s]?\\d{3}[\\-\\s]?\\d{4}$/,\n 'fi-FI': /^(\\+?358|0)\\s?(4(0|1|2|4|5|6)?|50)\\s?(\\d\\s?){4,8}\\d$/,\n 'fj-FJ': /^(\\+?679)?\\s?\\d{3}\\s?\\d{4}$/,\n 'fo-FO': /^(\\+?298)?\\s?\\d{2}\\s?\\d{2}\\s?\\d{2}$/,\n 'fr-FR': /^(\\+?33|0)[67]\\d{8}$/,\n 'fr-GF': /^(\\+?594|0|00594)[67]\\d{8}$/,\n 'fr-GP': /^(\\+?590|0|00590)[67]\\d{8}$/,\n 'fr-MQ': /^(\\+?596|0|00596)[67]\\d{8}$/,\n 'fr-RE': /^(\\+?262|0|00262)[67]\\d{8}$/,\n 'he-IL': /^(\\+972|0)([23489]|5[012345689]|77)[1-9]\\d{6}$/,\n 'hu-HU': /^(\\+?36)(20|30|70)\\d{7}$/,\n 'id-ID': /^(\\+?62|0)8(1[123456789]|2[1238]|3[1238]|5[12356789]|7[78]|9[56789]|8[123456789])([\\s?|\\d]{5,11})$/,\n 'it-IT': /^(\\+?39)?\\s?3\\d{2} ?\\d{6,7}$/,\n 'ja-JP': /^(\\+81[ \\-]?(\\(0\\))?|0)[6789]0[ \\-]?\\d{4}[ \\-]?\\d{4}$/,\n 'kk-KZ': /^(\\+?7|8)?7\\d{9}$/,\n 'kl-GL': /^(\\+?299)?\\s?\\d{2}\\s?\\d{2}\\s?\\d{2}$/,\n 'ko-KR': /^((\\+?82)[ \\-]?)?0?1([0|1|6|7|8|9]{1})[ \\-]?\\d{3,4}[ \\-]?\\d{4}$/,\n 'lt-LT': /^(\\+370|8)\\d{8}$/,\n 'ms-MY': /^(\\+?6?01){1}(([0145]{1}(\\-|\\s)?\\d{7,8})|([236789]{1}(\\s|\\-)?\\d{7}))$/,\n 'nb-NO': /^(\\+?47)?[49]\\d{7}$/,\n 'ne-NP': /^(\\+?977)?9[78]\\d{8}$/,\n 'nl-BE': /^(\\+?32|0)4?\\d{8}$/,\n 'nl-NL': /^(\\+?31|0)6?\\d{8}$/,\n 'nn-NO': /^(\\+?47)?[49]\\d{7}$/,\n 'pl-PL': /^(\\+?48)? ?[5-8]\\d ?\\d{3} ?\\d{2} ?\\d{2}$/,\n 'pt-BR': /(?=^(\\+?5{2}\\-?|0)[1-9]{2}\\-?\\d{4}\\-?\\d{4}$)(^(\\+?5{2}\\-?|0)[1-9]{2}\\-?[6-9]{1}\\d{3}\\-?\\d{4}$)|(^(\\+?5{2}\\-?|0)[1-9]{2}\\-?9[6-9]{1}\\d{3}\\-?\\d{4}$)/,\n 'pt-PT': /^(\\+?351)?9[1236]\\d{7}$/,\n 'ro-RO': /^(\\+?4?0)\\s?7\\d{2}(\\/|\\s|\\.|\\-)?\\d{3}(\\s|\\.|\\-)?\\d{3}$/,\n 'ru-RU': /^(\\+?7|8)?9\\d{9}$/,\n 'sl-SI': /^(\\+386\\s?|0)(\\d{1}\\s?\\d{3}\\s?\\d{2}\\s?\\d{2}|\\d{2}\\s?\\d{3}\\s?\\d{3})$/,\n 'sk-SK': /^(\\+?421)? ?[1-9][0-9]{2} ?[0-9]{3} ?[0-9]{3}$/,\n 'sr-RS': /^(\\+3816|06)[- \\d]{5,9}$/,\n 'sv-SE': /^(\\+?46|0)[\\s\\-]?7[\\s\\-]?[02369]([\\s\\-]?\\d){7}$/,\n 'th-TH': /^(\\+66|66|0)\\d{9}$/,\n 'tr-TR': /^(\\+?90|0)?5\\d{9}$/,\n 'uk-UA': /^(\\+?38|8)?0\\d{9}$/,\n 'vi-VN': /^(\\+?84|0)((3([2-9]))|(5([2689]))|(7([0|6-9]))|(8([1-6|89]))|(9([0-9])))([0-9]{7})$/,\n 'zh-CN': /^((\\+|00)86)?1([358][0-9]|4[579]|6[67]|7[01235678]|9[189])[0-9]{8}$/,\n 'zh-TW': /^(\\+?886\\-?|0)?9\\d{8}$/\n};\n/* eslint-enable max-len */\n// aliases\n\nphones['en-CA'] = phones['en-US'];\nphones['fr-BE'] = phones['nl-BE'];\nphones['zh-HK'] = phones['en-HK'];\nphones['zh-MO'] = phones['en-MO'];\n\nfunction isMobilePhone(str, locale, options) {\n (0, _assertString.default)(str);\n\n if (options && options.strictMode && !str.startsWith('+')) {\n return false;\n }\n\n if (Array.isArray(locale)) {\n return locale.some(function (key) {\n // https://github.com/gotwarlost/istanbul/blob/master/ignoring-code-for-coverage.md#ignoring-code-for-coverage-purposes\n // istanbul ignore else\n if (phones.hasOwnProperty(key)) {\n var phone = phones[key];\n\n if (phone.test(str)) {\n return true;\n }\n }\n\n return false;\n });\n } else if (locale in phones) {\n return phones[locale].test(str); // alias falsey locale as 'any'\n } else if (!locale || locale === 'any') {\n for (var key in phones) {\n // istanbul ignore else\n if (phones.hasOwnProperty(key)) {\n var phone = phones[key];\n\n if (phone.test(str)) {\n return true;\n }\n }\n }\n\n return false;\n }\n\n throw new Error(\"Invalid locale '\".concat(locale, \"'\"));\n}\n\nvar locales = Object.keys(phones);\nexports.locales = locales;\n\n//# sourceURL=webpack:///./node_modules/validator/lib/isMobilePhone.js?");
/***/ }),
/***/ "./node_modules/validator/lib/isMongoId.js":
/*!*************************************************!*\
!*** ./node_modules/validator/lib/isMongoId.js ***!
\*************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
eval("\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = isMongoId;\n\nvar _assertString = _interopRequireDefault(__webpack_require__(/*! ./util/assertString */ \"./node_modules/validator/lib/util/assertString.js\"));\n\nvar _isHexadecimal = _interopRequireDefault(__webpack_require__(/*! ./isHexadecimal */ \"./node_modules/validator/lib/isHexadecimal.js\"));\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\nfunction isMongoId(str) {\n (0, _assertString.default)(str);\n return (0, _isHexadecimal.default)(str) && str.length === 24;\n}\n\nmodule.exports = exports.default;\nmodule.exports.default = exports.default;\n\n//# sourceURL=webpack:///./node_modules/validator/lib/isMongoId.js?");
/***/ }),
/***/ "./node_modules/validator/lib/isMultibyte.js":
/*!***************************************************!*\
!*** ./node_modules/validator/lib/isMultibyte.js ***!
\***************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
eval("\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = isMultibyte;\n\nvar _assertString = _interopRequireDefault(__webpack_require__(/*! ./util/assertString */ \"./node_modules/validator/lib/util/assertString.js\"));\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\n/* eslint-disable no-control-regex */\nvar multibyte = /[^\\x00-\\x7F]/;\n/* eslint-enable no-control-regex */\n\nfunction isMultibyte(str) {\n (0, _assertString.default)(str);\n return multibyte.test(str);\n}\n\nmodule.exports = exports.default;\nmodule.exports.default = exports.default;\n\n//# sourceURL=webpack:///./node_modules/validator/lib/isMultibyte.js?");
/***/ }),
/***/ "./node_modules/validator/lib/isNumeric.js":
/*!*************************************************!*\
!*** ./node_modules/validator/lib/isNumeric.js ***!
\*************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
eval("\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = isNumeric;\n\nvar _assertString = _interopRequireDefault(__webpack_require__(/*! ./util/assertString */ \"./node_modules/validator/lib/util/assertString.js\"));\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\nvar numeric = /^[+-]?([0-9]*[.])?[0-9]+$/;\nvar numericNoSymbols = /^[0-9]+$/;\n\nfunction isNumeric(str, options) {\n (0, _assertString.default)(str);\n\n if (options && options.no_symbols) {\n return numericNoSymbols.test(str);\n }\n\n return numeric.test(str);\n}\n\nmodule.exports = exports.default;\nmodule.exports.default = exports.default;\n\n//# sourceURL=webpack:///./node_modules/validator/lib/isNumeric.js?");
/***/ }),
/***/ "./node_modules/validator/lib/isOctal.js":
/*!***********************************************!*\
!*** ./node_modules/validator/lib/isOctal.js ***!
\***********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
eval("\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = isOctal;\n\nvar _assertString = _interopRequireDefault(__webpack_require__(/*! ./util/assertString */ \"./node_modules/validator/lib/util/assertString.js\"));\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\nvar octal = /^(0o)?[0-7]+$/i;\n\nfunction isOctal(str) {\n (0, _assertString.default)(str);\n return octal.test(str);\n}\n\nmodule.exports = exports.default;\nmodule.exports.default = exports.default;\n\n//# sourceURL=webpack:///./node_modules/validator/lib/isOctal.js?");
/***/ }),
/***/ "./node_modules/validator/lib/isPassportNumber.js":
/*!********************************************************!*\
!*** ./node_modules/validator/lib/isPassportNumber.js ***!
\********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
eval("\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = isPassportNumber;\n\n/**\n * Reference:\n * https://en.wikipedia.org/ -- Wikipedia\n * https://docs.microsoft.com/en-us/microsoft-365/compliance/eu-passport-number -- EU Passport Number\n * https://countrycode.org/ -- Country Codes\n */\nvar passportRegexByCountryCode = {\n AM: /^[A-Z]{2}\\d{7}$/,\n // ARMENIA\n AR: /^[A-Z]{3}\\d{6}$/,\n // ARGENTINA\n AT: /^[A-Z]\\d{7}$/,\n // AUSTRIA\n AU: /^[A-Z]\\d{7}$/,\n // AUSTRALIA\n BE: /^[A-Z]{2}\\d{6}$/,\n // BELGIUM\n BG: /^\\d{9}$/,\n // BULGARIA\n CA: /^[A-Z]{2}\\d{6}$/,\n // CANADA\n CH: /^[A-Z]\\d{7}$/,\n // SWITZERLAND\n CN: /^[GE]\\d{8}$/,\n // CHINA [G=Ordinary, E=Electronic] followed by 8-digits\n CY: /^[A-Z](\\d{6}|\\d{8})$/,\n // CYPRUS\n CZ: /^\\d{8}$/,\n // CZECH REPUBLIC\n DE: /^[CFGHJKLMNPRTVWXYZ0-9]{9}$/,\n // GERMANY\n DK: /^\\d{9}$/,\n // DENMARK\n DZ: /^\\d{9}$/,\n // ALGERIA\n EE: /^([A-Z]\\d{7}|[A-Z]{2}\\d{7})$/,\n // ESTONIA (K followed by 7-digits), e-passports have 2 UPPERCASE followed by 7 digits\n ES: /^[A-Z0-9]{2}([A-Z0-9]?)\\d{6}$/,\n // SPAIN\n FI: /^[A-Z]{2}\\d{7}$/,\n // FINLAND\n FR: /^\\d{2}[A-Z]{2}\\d{5}$/,\n // FRANCE\n GB: /^\\d{9}$/,\n // UNITED KINGDOM\n GR: /^[A-Z]{2}\\d{7}$/,\n // GREECE\n HR: /^\\d{9}$/,\n // CROATIA\n HU: /^[A-Z]{2}(\\d{6}|\\d{7})$/,\n // HUNGARY\n IE: /^[A-Z0-9]{2}\\d{7}$/,\n // IRELAND\n IS: /^(A)\\d{7}$/,\n // ICELAND\n IT: /^[A-Z0-9]{2}\\d{7}$/,\n // ITALY\n JP: /^[A-Z]{2}\\d{7}$/,\n // JAPAN\n KR: /^[MS]\\d{8}$/,\n // SOUTH KOREA, REPUBLIC OF KOREA, [S=PS Passports, M=PM Passports]\n LT: /^[A-Z0-9]{8}$/,\n // LITHUANIA\n LU: /^[A-Z0-9]{8}$/,\n // LUXEMBURG\n LV: /^[A-Z0-9]{2}\\d{7}$/,\n // LATVIA\n MT: /^\\d{7}$/,\n // MALTA\n NL: /^[A-Z]{2}[A-Z0-9]{6}\\d$/,\n // NETHERLANDS\n PO: /^[A-Z]{2}\\d{7}$/,\n // POLAND\n PT: /^[A-Z]\\d{6}$/,\n // PORTUGAL\n RO: /^\\d{8,9}$/,\n // ROMANIA\n SE: /^\\d{8}$/,\n // SWEDEN\n SL: /^(P)[A-Z]\\d{7}$/,\n // SLOVANIA\n SK: /^[0-9A-Z]\\d{7}$/,\n // SLOVAKIA\n TR: /^[A-Z]\\d{8}$/,\n // TURKEY\n UA: /^[A-Z]{2}\\d{6}$/,\n // UKRAINE\n US: /^\\d{9}$/ // UNITED STATES\n\n};\n/**\n * Check if str is a valid passport number\n * relative to provided ISO Country Code.\n *\n * @param {string} str\n * @param {string} countryCode\n * @return {boolean}\n */\n\nfunction isPassportNumber(str, countryCode) {\n /** Remove All Whitespaces, Convert to UPPERCASE */\n var normalizedStr = str.replace(/\\s/g, '').toUpperCase();\n return countryCode.toUpperCase() in passportRegexByCountryCode && passportRegexByCountryCode[countryCode].test(normalizedStr);\n}\n\nmodule.exports = exports.default;\nmodule.exports.default = exports.default;\n\n//# sourceURL=webpack:///./node_modules/validator/lib/isPassportNumber.js?");
/***/ }),
/***/ "./node_modules/validator/lib/isPort.js":
/*!**********************************************!*\
!*** ./node_modules/validator/lib/isPort.js ***!
\**********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
eval("\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = isPort;\n\nvar _isInt = _interopRequireDefault(__webpack_require__(/*! ./isInt */ \"./node_modules/validator/lib/isInt.js\"));\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\nfunction isPort(str) {\n return (0, _isInt.default)(str, {\n min: 0,\n max: 65535\n });\n}\n\nmodule.exports = exports.default;\nmodule.exports.default = exports.default;\n\n//# sourceURL=webpack:///./node_modules/validator/lib/isPort.js?");
/***/ }),
/***/ "./node_modules/validator/lib/isPostalCode.js":
/*!****************************************************!*\
!*** ./node_modules/validator/lib/isPostalCode.js ***!
\****************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
eval("\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = _default;\nexports.locales = void 0;\n\nvar _assertString = _interopRequireDefault(__webpack_require__(/*! ./util/assertString */ \"./node_modules/validator/lib/util/assertString.js\"));\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\n// common patterns\nvar threeDigit = /^\\d{3}$/;\nvar fourDigit = /^\\d{4}$/;\nvar fiveDigit = /^\\d{5}$/;\nvar sixDigit = /^\\d{6}$/;\nvar patterns = {\n AD: /^AD\\d{3}$/,\n AT: fourDigit,\n AU: fourDigit,\n BE: fourDigit,\n BG: fourDigit,\n BR: /^\\d{5}-\\d{3}$/,\n CA: /^[ABCEGHJKLMNPRSTVXY]\\d[ABCEGHJ-NPRSTV-Z][\\s\\-]?\\d[ABCEGHJ-NPRSTV-Z]\\d$/i,\n CH: fourDigit,\n CZ: /^\\d{3}\\s?\\d{2}$/,\n DE: fiveDigit,\n DK: fourDigit,\n DZ: fiveDigit,\n EE: fiveDigit,\n ES: fiveDigit,\n FI: fiveDigit,\n FR: /^\\d{2}\\s?\\d{3}$/,\n GB: /^(gir\\s?0aa|[a-z]{1,2}\\d[\\da-z]?\\s?(\\d[a-z]{2})?)$/i,\n GR: /^\\d{3}\\s?\\d{2}$/,\n HR: /^([1-5]\\d{4}$)/,\n HU: fourDigit,\n ID: fiveDigit,\n IE: /^(?!.*(?:o))[A-z]\\d[\\dw]\\s\\w{4}$/i,\n IL: fiveDigit,\n IN: /^((?!10|29|35|54|55|65|66|86|87|88|89)[1-9][0-9]{5})$/,\n IS: threeDigit,\n IT: fiveDigit,\n JP: /^\\d{3}\\-\\d{4}$/,\n KE: fiveDigit,\n LI: /^(948[5-9]|949[0-7])$/,\n LT: /^LT\\-\\d{5}$/,\n LU: fourDigit,\n LV: /^LV\\-\\d{4}$/,\n MX: fiveDigit,\n MT: /^[A-Za-z]{3}\\s{0,1}\\d{4}$/,\n NL: /^\\d{4}\\s?[a-z]{2}$/i,\n NO: fourDigit,\n NZ: fourDigit,\n PL: /^\\d{2}\\-\\d{3}$/,\n PR: /^00[679]\\d{2}([ -]\\d{4})?$/,\n PT: /^\\d{4}\\-\\d{3}?$/,\n RO: sixDigit,\n RU: sixDigit,\n SA: fiveDigit,\n SE: /^[1-9]\\d{2}\\s?\\d{2}$/,\n SI: fourDigit,\n SK: /^\\d{3}\\s?\\d{2}$/,\n TN: fourDigit,\n TW: /^\\d{3}(\\d{2})?$/,\n UA: fiveDigit,\n US: /^\\d{5}(-\\d{4})?$/,\n ZA: fourDigit,\n ZM: fiveDigit\n};\nvar locales = Object.keys(patterns);\nexports.locales = locales;\n\nfunction _default(str, locale) {\n (0, _assertString.default)(str);\n\n if (locale in patterns) {\n return patterns[locale].test(str);\n } else if (locale === 'any') {\n for (var key in patterns) {\n // https://github.com/gotwarlost/istanbul/blob/master/ignoring-code-for-coverage.md#ignoring-code-for-coverage-purposes\n // istanbul ignore else\n if (patterns.hasOwnProperty(key)) {\n var pattern = patterns[key];\n\n if (pattern.test(str)) {\n return true;\n }\n }\n }\n\n return false;\n }\n\n throw new Error(\"Invalid locale '\".concat(locale, \"'\"));\n}\n\n//# sourceURL=webpack:///./node_modules/validator/lib/isPostalCode.js?");
/***/ }),
/***/ "./node_modules/validator/lib/isRFC3339.js":
/*!*************************************************!*\
!*** ./node_modules/validator/lib/isRFC3339.js ***!
\*************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
eval("\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = isRFC3339;\n\nvar _assertString = _interopRequireDefault(__webpack_require__(/*! ./util/assertString */ \"./node_modules/validator/lib/util/assertString.js\"));\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\n/* Based on https://tools.ietf.org/html/rfc3339#section-5.6 */\nvar dateFullYear = /[0-9]{4}/;\nvar dateMonth = /(0[1-9]|1[0-2])/;\nvar dateMDay = /([12]\\d|0[1-9]|3[01])/;\nvar timeHour = /([01][0-9]|2[0-3])/;\nvar timeMinute = /[0-5][0-9]/;\nvar timeSecond = /([0-5][0-9]|60)/;\nvar timeSecFrac = /(\\.[0-9]+)?/;\nvar timeNumOffset = new RegExp(\"[-+]\".concat(timeHour.source, \":\").concat(timeMinute.source));\nvar timeOffset = new RegExp(\"([zZ]|\".concat(timeNumOffset.source, \")\"));\nvar partialTime = new RegExp(\"\".concat(timeHour.source, \":\").concat(timeMinute.source, \":\").concat(timeSecond.source).concat(timeSecFrac.source));\nvar fullDate = new RegExp(\"\".concat(dateFullYear.source, \"-\").concat(dateMonth.source, \"-\").concat(dateMDay.source));\nvar fullTime = new RegExp(\"\".concat(partialTime.source).concat(timeOffset.source));\nvar rfc3339 = new RegExp(\"\".concat(fullDate.source, \"[ tT]\").concat(fullTime.source));\n\nfunction isRFC3339(str) {\n (0, _assertString.default)(str);\n return rfc3339.test(str);\n}\n\nmodule.exports = exports.default;\nmodule.exports.default = exports.default;\n\n//# sourceURL=webpack:///./node_modules/validator/lib/isRFC3339.js?");
/***/ }),
/***/ "./node_modules/validator/lib/isRgbColor.js":
/*!**************************************************!*\
!*** ./node_modules/validator/lib/isRgbColor.js ***!
\**************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
eval("\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = isRgbColor;\n\nvar _assertString = _interopRequireDefault(__webpack_require__(/*! ./util/assertString */ \"./node_modules/validator/lib/util/assertString.js\"));\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\nvar rgbColor = /^rgb\\((([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5]),){2}([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\\)$/;\nvar rgbaColor = /^rgba\\((([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5]),){3}(0?\\.\\d|1(\\.0)?|0(\\.0)?)\\)$/;\nvar rgbColorPercent = /^rgb\\((([0-9]%|[1-9][0-9]%|100%),){2}([0-9]%|[1-9][0-9]%|100%)\\)/;\nvar rgbaColorPercent = /^rgba\\((([0-9]%|[1-9][0-9]%|100%),){3}(0?\\.\\d|1(\\.0)?|0(\\.0)?)\\)/;\n\nfunction isRgbColor(str) {\n var includePercentValues = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;\n (0, _assertString.default)(str);\n\n if (!includePercentValues) {\n return rgbColor.test(str) || rgbaColor.test(str);\n }\n\n return rgbColor.test(str) || rgbaColor.test(str) || rgbColorPercent.test(str) || rgbaColorPercent.test(str);\n}\n\nmodule.exports = exports.default;\nmodule.exports.default = exports.default;\n\n//# sourceURL=webpack:///./node_modules/validator/lib/isRgbColor.js?");
/***/ }),
/***/ "./node_modules/validator/lib/isSemVer.js":
/*!************************************************!*\
!*** ./node_modules/validator/lib/isSemVer.js ***!
\************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
eval("\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = isSemVer;\n\nvar _assertString = _interopRequireDefault(__webpack_require__(/*! ./util/assertString */ \"./node_modules/validator/lib/util/assertString.js\"));\n\nvar _multilineRegex = _interopRequireDefault(__webpack_require__(/*! ./util/multilineRegex */ \"./node_modules/validator/lib/util/multilineRegex.js\"));\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\n/**\n * Regular Expression to match\n * semantic versioning (SemVer)\n * built from multi-line, multi-parts regexp\n * Reference: https://semver.org/\n */\nvar semanticVersioningRegex = (0, _multilineRegex.default)(['^(0|[1-9]\\\\d*)\\\\.(0|[1-9]\\\\d*)\\\\.(0|[1-9]\\\\d*)', '(?:-((?:0|[1-9]\\\\d*|\\\\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\\\\.(?:0|[1-9]\\\\d*|\\\\d*[a-zA-Z-][0-9a-zA-Z-]*))*))', '?(?:\\\\+([0-9a-zA-Z-]+(?:\\\\.[0-9a-zA-Z-]+)*))?$']);\n\nfunction isSemVer(str) {\n (0, _assertString.default)(str);\n return semanticVersioningRegex.test(str);\n}\n\nmodule.exports = exports.default;\nmodule.exports.default = exports.default;\n\n//# sourceURL=webpack:///./node_modules/validator/lib/isSemVer.js?");
/***/ }),
/***/ "./node_modules/validator/lib/isSlug.js":
/*!**********************************************!*\
!*** ./node_modules/validator/lib/isSlug.js ***!
\**********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
eval("\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = isSlug;\n\nvar _assertString = _interopRequireDefault(__webpack_require__(/*! ./util/assertString */ \"./node_modules/validator/lib/util/assertString.js\"));\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\nvar charsetRegex = /^[^-_](?!.*?[-_]{2,})([a-z0-9\\\\-]{1,}).*[^-_]$/;\n\nfunction isSlug(str) {\n (0, _assertString.default)(str);\n return charsetRegex.test(str);\n}\n\nmodule.exports = exports.default;\nmodule.exports.default = exports.default;\n\n//# sourceURL=webpack:///./node_modules/validator/lib/isSlug.js?");
/***/ }),
/***/ "./node_modules/validator/lib/isSurrogatePair.js":
/*!*******************************************************!*\
!*** ./node_modules/validator/lib/isSurrogatePair.js ***!
\*******************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
eval("\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = isSurrogatePair;\n\nvar _assertString = _interopRequireDefault(__webpack_require__(/*! ./util/assertString */ \"./node_modules/validator/lib/util/assertString.js\"));\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\nvar surrogatePair = /[\\uD800-\\uDBFF][\\uDC00-\\uDFFF]/;\n\nfunction isSurrogatePair(str) {\n (0, _assertString.default)(str);\n return surrogatePair.test(str);\n}\n\nmodule.exports = exports.default;\nmodule.exports.default = exports.default;\n\n//# sourceURL=webpack:///./node_modules/validator/lib/isSurrogatePair.js?");
/***/ }),
/***/ "./node_modules/validator/lib/isURL.js":
/*!*********************************************!*\
!*** ./node_modules/validator/lib/isURL.js ***!
\*********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
eval("\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = isURL;\n\nvar _assertString = _interopRequireDefault(__webpack_require__(/*! ./util/assertString */ \"./node_modules/validator/lib/util/assertString.js\"));\n\nvar _isFQDN = _interopRequireDefault(__webpack_require__(/*! ./isFQDN */ \"./node_modules/validator/lib/isFQDN.js\"));\n\nvar _isIP = _interopRequireDefault(__webpack_require__(/*! ./isIP */ \"./node_modules/validator/lib/isIP.js\"));\n\nvar _merge = _interopRequireDefault(__webpack_require__(/*! ./util/merge */ \"./node_modules/validator/lib/util/merge.js\"));\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\n/*\noptions for isURL method\n\nrequire_protocol - if set as true isURL will return false if protocol is not present in the URL\nrequire_valid_protocol - isURL will check if the URL's protocol is present in the protocols option\nprotocols - valid protocols can be modified with this option\nrequire_host - if set as false isURL will not check if host is present in the URL\nallow_protocol_relative_urls - if set as true protocol relative URLs will be allowed\n\n*/\nvar default_url_options = {\n protocols: ['http', 'https', 'ftp'],\n require_tld: true,\n require_protocol: false,\n require_host: true,\n require_valid_protocol: true,\n allow_underscores: false,\n allow_trailing_dot: false,\n allow_protocol_relative_urls: false\n};\nvar wrapped_ipv6 = /^\\[([^\\]]+)\\](?::([0-9]+))?$/;\n\nfunction isRegExp(obj) {\n return Object.prototype.toString.call(obj) === '[object RegExp]';\n}\n\nfunction checkHost(host, matches) {\n for (var i = 0; i < matches.length; i++) {\n var match = matches[i];\n\n if (host === match || isRegExp(match) && match.test(host)) {\n return true;\n }\n }\n\n return false;\n}\n\nfunction isURL(url, options) {\n (0, _assertString.default)(url);\n\n if (!url || url.length >= 2083 || /[\\s<>]/.test(url)) {\n return false;\n }\n\n if (url.indexOf('mailto:') === 0) {\n return false;\n }\n\n options = (0, _merge.default)(options, default_url_options);\n var protocol, auth, host, hostname, port, port_str, split, ipv6;\n split = url.split('#');\n url = split.shift();\n split = url.split('?');\n url = split.shift();\n split = url.split('://');\n\n if (split.length > 1) {\n protocol = split.shift().toLowerCase();\n\n if (options.require_valid_protocol && options.protocols.indexOf(protocol) === -1) {\n return false;\n }\n } else if (options.require_protocol) {\n return false;\n } else if (url.substr(0, 2) === '//') {\n if (!options.allow_protocol_relative_urls) {\n return false;\n }\n\n split[0] = url.substr(2);\n }\n\n url = split.join('://');\n\n if (url === '') {\n return false;\n }\n\n split = url.split('/');\n url = split.shift();\n\n if (url === '' && !options.require_host) {\n return true;\n }\n\n split = url.split('@');\n\n if (split.length > 1) {\n if (options.disallow_auth) {\n return false;\n }\n\n auth = split.shift();\n\n if (auth.indexOf(':') >= 0 && auth.split(':').length > 2) {\n return false;\n }\n }\n\n hostname = split.join('@');\n port_str = null;\n ipv6 = null;\n var ipv6_match = hostname.match(wrapped_ipv6);\n\n if (ipv6_match) {\n host = '';\n ipv6 = ipv6_match[1];\n port_str = ipv6_match[2] || null;\n } else {\n split = hostname.split(':');\n host = split.shift();\n\n if (split.length) {\n port_str = split.join(':');\n }\n }\n\n if (port_str !== null) {\n port = parseInt(port_str, 10);\n\n if (!/^[0-9]+$/.test(port_str) || port <= 0 || port > 65535) {\n return false;\n }\n }\n\n if (!(0, _isIP.default)(host) && !(0, _isFQDN.default)(host, options) && (!ipv6 || !(0, _isIP.default)(ipv6, 6))) {\n return false;\n }\n\n host = host || ipv6;\n\n if (options.host_whitelist && !checkHost(host, options.host_whitelist)) {\n return false;\n }\n\n if (options.host_blacklist && checkHost(host, options.host_blacklist)) {\n return false;\n }\n\n return true;\n}\n\nmodule.exports = exports.default;\nmodule.exports.default = exports.default;\n\n//# sourceURL=webpack:///./node_modules/validator/lib/isURL.js?");
/***/ }),
/***/ "./node_modules/validator/lib/isUUID.js":
/*!**********************************************!*\
!*** ./node_modules/validator/lib/isUUID.js ***!
\**********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
eval("\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = isUUID;\n\nvar _assertString = _interopRequireDefault(__webpack_require__(/*! ./util/assertString */ \"./node_modules/validator/lib/util/assertString.js\"));\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\nvar uuid = {\n 3: /^[0-9A-F]{8}-[0-9A-F]{4}-3[0-9A-F]{3}-[0-9A-F]{4}-[0-9A-F]{12}$/i,\n 4: /^[0-9A-F]{8}-[0-9A-F]{4}-4[0-9A-F]{3}-[89AB][0-9A-F]{3}-[0-9A-F]{12}$/i,\n 5: /^[0-9A-F]{8}-[0-9A-F]{4}-5[0-9A-F]{3}-[89AB][0-9A-F]{3}-[0-9A-F]{12}$/i,\n all: /^[0-9A-F]{8}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{12}$/i\n};\n\nfunction isUUID(str) {\n var version = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'all';\n (0, _assertString.default)(str);\n var pattern = uuid[version];\n return pattern && pattern.test(str);\n}\n\nmodule.exports = exports.default;\nmodule.exports.default = exports.default;\n\n//# sourceURL=webpack:///./node_modules/validator/lib/isUUID.js?");
/***/ }),
/***/ "./node_modules/validator/lib/isUppercase.js":
/*!***************************************************!*\
!*** ./node_modules/validator/lib/isUppercase.js ***!
\***************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
eval("\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = isUppercase;\n\nvar _assertString = _interopRequireDefault(__webpack_require__(/*! ./util/assertString */ \"./node_modules/validator/lib/util/assertString.js\"));\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\nfunction isUppercase(str) {\n (0, _assertString.default)(str);\n return str === str.toUpperCase();\n}\n\nmodule.exports = exports.default;\nmodule.exports.default = exports.default;\n\n//# sourceURL=webpack:///./node_modules/validator/lib/isUppercase.js?");
/***/ }),
/***/ "./node_modules/validator/lib/isVariableWidth.js":
/*!*******************************************************!*\
!*** ./node_modules/validator/lib/isVariableWidth.js ***!
\*******************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
eval("\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = isVariableWidth;\n\nvar _assertString = _interopRequireDefault(__webpack_require__(/*! ./util/assertString */ \"./node_modules/validator/lib/util/assertString.js\"));\n\nvar _isFullWidth = __webpack_require__(/*! ./isFullWidth */ \"./node_modules/validator/lib/isFullWidth.js\");\n\nvar _isHalfWidth = __webpack_require__(/*! ./isHalfWidth */ \"./node_modules/validator/lib/isHalfWidth.js\");\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\nfunction isVariableWidth(str) {\n (0, _assertString.default)(str);\n return _isFullWidth.fullWidth.test(str) && _isHalfWidth.halfWidth.test(str);\n}\n\nmodule.exports = exports.default;\nmodule.exports.default = exports.default;\n\n//# sourceURL=webpack:///./node_modules/validator/lib/isVariableWidth.js?");
/***/ }),
/***/ "./node_modules/validator/lib/isWhitelisted.js":
/*!*****************************************************!*\
!*** ./node_modules/validator/lib/isWhitelisted.js ***!
\*****************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
eval("\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = isWhitelisted;\n\nvar _assertString = _interopRequireDefault(__webpack_require__(/*! ./util/assertString */ \"./node_modules/validator/lib/util/assertString.js\"));\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\nfunction isWhitelisted(str, chars) {\n (0, _assertString.default)(str);\n\n for (var i = str.length - 1; i >= 0; i--) {\n if (chars.indexOf(str[i]) === -1) {\n return false;\n }\n }\n\n return true;\n}\n\nmodule.exports = exports.default;\nmodule.exports.default = exports.default;\n\n//# sourceURL=webpack:///./node_modules/validator/lib/isWhitelisted.js?");
/***/ }),
/***/ "./node_modules/validator/lib/ltrim.js":
/*!*********************************************!*\
!*** ./node_modules/validator/lib/ltrim.js ***!
\*********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
eval("\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = ltrim;\n\nvar _assertString = _interopRequireDefault(__webpack_require__(/*! ./util/assertString */ \"./node_modules/validator/lib/util/assertString.js\"));\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\nfunction ltrim(str, chars) {\n (0, _assertString.default)(str); // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions#Escaping\n\n var pattern = chars ? new RegExp(\"^[\".concat(chars.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&'), \"]+\"), 'g') : /^\\s+/g;\n return str.replace(pattern, '');\n}\n\nmodule.exports = exports.default;\nmodule.exports.default = exports.default;\n\n//# sourceURL=webpack:///./node_modules/validator/lib/ltrim.js?");
/***/ }),
/***/ "./node_modules/validator/lib/matches.js":
/*!***********************************************!*\
!*** ./node_modules/validator/lib/matches.js ***!
\***********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
eval("\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = matches;\n\nvar _assertString = _interopRequireDefault(__webpack_require__(/*! ./util/assertString */ \"./node_modules/validator/lib/util/assertString.js\"));\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\nfunction matches(str, pattern, modifiers) {\n (0, _assertString.default)(str);\n\n if (Object.prototype.toString.call(pattern) !== '[object RegExp]') {\n pattern = new RegExp(pattern, modifiers);\n }\n\n return pattern.test(str);\n}\n\nmodule.exports = exports.default;\nmodule.exports.default = exports.default;\n\n//# sourceURL=webpack:///./node_modules/validator/lib/matches.js?");
/***/ }),
/***/ "./node_modules/validator/lib/normalizeEmail.js":
/*!******************************************************!*\
!*** ./node_modules/validator/lib/normalizeEmail.js ***!
\******************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
eval("\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = normalizeEmail;\n\nvar _merge = _interopRequireDefault(__webpack_require__(/*! ./util/merge */ \"./node_modules/validator/lib/util/merge.js\"));\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\nvar default_normalize_email_options = {\n // The following options apply to all email addresses\n // Lowercases the local part of the email address.\n // Please note this may violate RFC 5321 as per http://stackoverflow.com/a/9808332/192024).\n // The domain is always lowercased, as per RFC 1035\n all_lowercase: true,\n // The following conversions are specific to GMail\n // Lowercases the local part of the GMail address (known to be case-insensitive)\n gmail_lowercase: true,\n // Removes dots from the local part of the email address, as that's ignored by GMail\n gmail_remove_dots: true,\n // Removes the subaddress (e.g. \"+foo\") from the email address\n gmail_remove_subaddress: true,\n // Conversts the googlemail.com domain to gmail.com\n gmail_convert_googlemaildotcom: true,\n // The following conversions are specific to Outlook.com / Windows Live / Hotmail\n // Lowercases the local part of the Outlook.com address (known to be case-insensitive)\n outlookdotcom_lowercase: true,\n // Removes the subaddress (e.g. \"+foo\") from the email address\n outlookdotcom_remove_subaddress: true,\n // The following conversions are specific to Yahoo\n // Lowercases the local part of the Yahoo address (known to be case-insensitive)\n yahoo_lowercase: true,\n // Removes the subaddress (e.g. \"-foo\") from the email address\n yahoo_remove_subaddress: true,\n // The following conversions are specific to Yandex\n // Lowercases the local part of the Yandex address (known to be case-insensitive)\n yandex_lowercase: true,\n // The following conversions are specific to iCloud\n // Lowercases the local part of the iCloud address (known to be case-insensitive)\n icloud_lowercase: true,\n // Removes the subaddress (e.g. \"+foo\") from the email address\n icloud_remove_subaddress: true\n}; // List of domains used by iCloud\n\nvar icloud_domains = ['icloud.com', 'me.com']; // List of domains used by Outlook.com and its predecessors\n// This list is likely incomplete.\n// Partial reference:\n// https://blogs.office.com/2013/04/17/outlook-com-gets-two-step-verification-sign-in-by-alias-and-new-international-domains/\n\nvar outlookdotcom_domains = ['hotmail.at', 'hotmail.be', 'hotmail.ca', 'hotmail.cl', 'hotmail.co.il', 'hotmail.co.nz', 'hotmail.co.th', 'hotmail.co.uk', 'hotmail.com', 'hotmail.com.ar', 'hotmail.com.au', 'hotmail.com.br', 'hotmail.com.gr', 'hotmail.com.mx', 'hotmail.com.pe', 'hotmail.com.tr', 'hotmail.com.vn', 'hotmail.cz', 'hotmail.de', 'hotmail.dk', 'hotmail.es', 'hotmail.fr', 'hotmail.hu', 'hotmail.id', 'hotmail.ie', 'hotmail.in', 'hotmail.it', 'hotmail.jp', 'hotmail.kr', 'hotmail.lv', 'hotmail.my', 'hotmail.ph', 'hotmail.pt', 'hotmail.sa', 'hotmail.sg', 'hotmail.sk', 'live.be', 'live.co.uk', 'live.com', 'live.com.ar', 'live.com.mx', 'live.de', 'live.es', 'live.eu', 'live.fr', 'live.it', 'live.nl', 'msn.com', 'outlook.at', 'outlook.be', 'outlook.cl', 'outlook.co.il', 'outlook.co.nz', 'outlook.co.th', 'outlook.com', 'outlook.com.ar', 'outlook.com.au', 'outlook.com.br', 'outlook.com.gr', 'outlook.com.pe', 'outlook.com.tr', 'outlook.com.vn', 'outlook.cz', 'outlook.de', 'outlook.dk', 'outlook.es', 'outlook.fr', 'outlook.hu', 'outlook.id', 'outlook.ie', 'outlook.in', 'outlook.it', 'outlook.jp', 'outlook.kr', 'outlook.lv', 'outlook.my', 'outlook.ph', 'outlook.pt', 'outlook.sa', 'outlook.sg', 'outlook.sk', 'passport.com']; // List of domains used by Yahoo Mail\n// This list is likely incomplete\n\nvar yahoo_domains = ['rocketmail.com', 'yahoo.ca', 'yahoo.co.uk', 'yahoo.com', 'yahoo.de', 'yahoo.fr', 'yahoo.in', 'yahoo.it', 'ymail.com']; // List of domains used by yandex.ru\n\nvar yandex_domains = ['yandex.ru', 'yandex.ua', 'yandex.kz', 'yandex.com', 'yandex.by', 'ya.ru']; // replace single dots, but not multiple consecutive dots\n\nfunction dotsReplacer(match) {\n if (match.length > 1) {\n return match;\n }\n\n return '';\n}\n\nfunction normalizeEmail(email, options) {\n options = (0, _merge.default)(options, default_normalize_email_options);\n var raw_parts = email.split('@');\n var domain = raw_parts.pop();\n var user = raw_parts.join('@');\n var parts = [user, domain]; // The domain is always lowercased, as it's case-insensitive per RFC 1035\n\n parts[1] = parts[1].toLowerCase();\n\n if (parts[1] === 'gmail.com' || parts[1] === 'googlemail.com') {\n // Address is GMail\n if (options.gmail_remove_subaddress) {\n parts[0] = parts[0].split('+')[0];\n }\n\n if (options.gmail_remove_dots) {\n // this does not replace consecutive dots like [email protected]\n parts[0] = parts[0].replace(/\\.+/g, dotsReplacer);\n }\n\n if (!parts[0].length) {\n return false;\n }\n\n if (options.all_lowercase || options.gmail_lowercase) {\n parts[0] = parts[0].toLowerCase();\n }\n\n parts[1] = options.gmail_convert_googlemaildotcom ? 'gmail.com' : parts[1];\n } else if (icloud_domains.indexOf(parts[1]) >= 0) {\n // Address is iCloud\n if (options.icloud_remove_subaddress) {\n parts[0] = parts[0].split('+')[0];\n }\n\n if (!parts[0].length) {\n return false;\n }\n\n if (options.all_lowercase || options.icloud_lowercase) {\n parts[0] = parts[0].toLowerCase();\n }\n } else if (outlookdotcom_domains.indexOf(parts[1]) >= 0) {\n // Address is Outlook.com\n if (options.outlookdotcom_remove_subaddress) {\n parts[0] = parts[0].split('+')[0];\n }\n\n if (!parts[0].length) {\n return false;\n }\n\n if (options.all_lowercase || options.outlookdotcom_lowercase) {\n parts[0] = parts[0].toLowerCase();\n }\n } else if (yahoo_domains.indexOf(parts[1]) >= 0) {\n // Address is Yahoo\n if (options.yahoo_remove_subaddress) {\n var components = parts[0].split('-');\n parts[0] = components.length > 1 ? components.slice(0, -1).join('-') : components[0];\n }\n\n if (!parts[0].length) {\n return false;\n }\n\n if (options.all_lowercase || options.yahoo_lowercase) {\n parts[0] = parts[0].toLowerCase();\n }\n } else if (yandex_domains.indexOf(parts[1]) >= 0) {\n if (options.all_lowercase || options.yandex_lowercase) {\n parts[0] = parts[0].toLowerCase();\n }\n\n parts[1] = 'yandex.ru'; // all yandex domains are equal, 1st preffered\n } else if (options.all_lowercase) {\n // Any other address\n parts[0] = parts[0].toLowerCase();\n }\n\n return parts.join('@');\n}\n\nmodule.exports = exports.default;\nmodule.exports.default = exports.default;\n\n//# sourceURL=webpack:///./node_modules/validator/lib/normalizeEmail.js?");
/***/ }),
/***/ "./node_modules/validator/lib/rtrim.js":
/*!*********************************************!*\
!*** ./node_modules/validator/lib/rtrim.js ***!
\*********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
eval("\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = rtrim;\n\nvar _assertString = _interopRequireDefault(__webpack_require__(/*! ./util/assertString */ \"./node_modules/validator/lib/util/assertString.js\"));\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\nfunction rtrim(str, chars) {\n (0, _assertString.default)(str); // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions#Escaping\n\n var pattern = chars ? new RegExp(\"[\".concat(chars.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&'), \"]+$\"), 'g') : /\\s+$/g;\n return str.replace(pattern, '');\n}\n\nmodule.exports = exports.default;\nmodule.exports.default = exports.default;\n\n//# sourceURL=webpack:///./node_modules/validator/lib/rtrim.js?");
/***/ }),
/***/ "./node_modules/validator/lib/stripLow.js":
/*!************************************************!*\
!*** ./node_modules/validator/lib/stripLow.js ***!
\************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
eval("\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = stripLow;\n\nvar _assertString = _interopRequireDefault(__webpack_require__(/*! ./util/assertString */ \"./node_modules/validator/lib/util/assertString.js\"));\n\nvar _blacklist = _interopRequireDefault(__webpack_require__(/*! ./blacklist */ \"./node_modules/validator/lib/blacklist.js\"));\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\nfunction stripLow(str, keep_new_lines) {\n (0, _assertString.default)(str);\n var chars = keep_new_lines ? '\\\\x00-\\\\x09\\\\x0B\\\\x0C\\\\x0E-\\\\x1F\\\\x7F' : '\\\\x00-\\\\x1F\\\\x7F';\n return (0, _blacklist.default)(str, chars);\n}\n\nmodule.exports = exports.default;\nmodule.exports.default = exports.default;\n\n//# sourceURL=webpack:///./node_modules/validator/lib/stripLow.js?");
/***/ }),
/***/ "./node_modules/validator/lib/toBoolean.js":
/*!*************************************************!*\
!*** ./node_modules/validator/lib/toBoolean.js ***!
\*************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
eval("\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = toBoolean;\n\nvar _assertString = _interopRequireDefault(__webpack_require__(/*! ./util/assertString */ \"./node_modules/validator/lib/util/assertString.js\"));\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\nfunction toBoolean(str, strict) {\n (0, _assertString.default)(str);\n\n if (strict) {\n return str === '1' || /^true$/i.test(str);\n }\n\n return str !== '0' && !/^false$/i.test(str) && str !== '';\n}\n\nmodule.exports = exports.default;\nmodule.exports.default = exports.default;\n\n//# sourceURL=webpack:///./node_modules/validator/lib/toBoolean.js?");
/***/ }),
/***/ "./node_modules/validator/lib/toDate.js":
/*!**********************************************!*\
!*** ./node_modules/validator/lib/toDate.js ***!
\**********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
eval("\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = toDate;\n\nvar _assertString = _interopRequireDefault(__webpack_require__(/*! ./util/assertString */ \"./node_modules/validator/lib/util/assertString.js\"));\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\nfunction toDate(date) {\n (0, _assertString.default)(date);\n date = Date.parse(date);\n return !isNaN(date) ? new Date(date) : null;\n}\n\nmodule.exports = exports.default;\nmodule.exports.default = exports.default;\n\n//# sourceURL=webpack:///./node_modules/validator/lib/toDate.js?");
/***/ }),
/***/ "./node_modules/validator/lib/toFloat.js":
/*!***********************************************!*\
!*** ./node_modules/validator/lib/toFloat.js ***!
\***********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
eval("\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = toFloat;\n\nvar _isFloat = _interopRequireDefault(__webpack_require__(/*! ./isFloat */ \"./node_modules/validator/lib/isFloat.js\"));\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\nfunction toFloat(str) {\n if (!(0, _isFloat.default)(str)) return NaN;\n return parseFloat(str);\n}\n\nmodule.exports = exports.default;\nmodule.exports.default = exports.default;\n\n//# sourceURL=webpack:///./node_modules/validator/lib/toFloat.js?");
/***/ }),
/***/ "./node_modules/validator/lib/toInt.js":
/*!*********************************************!*\
!*** ./node_modules/validator/lib/toInt.js ***!
\*********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
eval("\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = toInt;\n\nvar _assertString = _interopRequireDefault(__webpack_require__(/*! ./util/assertString */ \"./node_modules/validator/lib/util/assertString.js\"));\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\nfunction toInt(str, radix) {\n (0, _assertString.default)(str);\n return parseInt(str, radix || 10);\n}\n\nmodule.exports = exports.default;\nmodule.exports.default = exports.default;\n\n//# sourceURL=webpack:///./node_modules/validator/lib/toInt.js?");
/***/ }),
/***/ "./node_modules/validator/lib/trim.js":
/*!********************************************!*\
!*** ./node_modules/validator/lib/trim.js ***!
\********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
eval("\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = trim;\n\nvar _rtrim = _interopRequireDefault(__webpack_require__(/*! ./rtrim */ \"./node_modules/validator/lib/rtrim.js\"));\n\nvar _ltrim = _interopRequireDefault(__webpack_require__(/*! ./ltrim */ \"./node_modules/validator/lib/ltrim.js\"));\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\nfunction trim(str, chars) {\n return (0, _rtrim.default)((0, _ltrim.default)(str, chars), chars);\n}\n\nmodule.exports = exports.default;\nmodule.exports.default = exports.default;\n\n//# sourceURL=webpack:///./node_modules/validator/lib/trim.js?");
/***/ }),
/***/ "./node_modules/validator/lib/unescape.js":
/*!************************************************!*\
!*** ./node_modules/validator/lib/unescape.js ***!
\************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
eval("\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = unescape;\n\nvar _assertString = _interopRequireDefault(__webpack_require__(/*! ./util/assertString */ \"./node_modules/validator/lib/util/assertString.js\"));\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\nfunction unescape(str) {\n (0, _assertString.default)(str);\n return str.replace(/&/g, '&').replace(/"/g, '\"').replace(/'/g, \"'\").replace(/</g, '<').replace(/>/g, '>').replace(///g, '/').replace(/\/g, '\\\\').replace(/`/g, '`');\n}\n\nmodule.exports = exports.default;\nmodule.exports.default = exports.default;\n\n//# sourceURL=webpack:///./node_modules/validator/lib/unescape.js?");
/***/ }),
/***/ "./node_modules/validator/lib/util/assertString.js":
/*!*********************************************************!*\
!*** ./node_modules/validator/lib/util/assertString.js ***!
\*********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
eval("\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = assertString;\n\nfunction _typeof(obj) { \"@babel/helpers - typeof\"; if (typeof Symbol === \"function\" && typeof Symbol.iterator === \"symbol\") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === \"function\" && obj.constructor === Symbol && obj !== Symbol.prototype ? \"symbol\" : typeof obj; }; } return _typeof(obj); }\n\nfunction assertString(input) {\n var isString = typeof input === 'string' || input instanceof String;\n\n if (!isString) {\n var invalidType;\n\n if (input === null) {\n invalidType = 'null';\n } else {\n invalidType = _typeof(input);\n\n if (invalidType === 'object' && input.constructor && input.constructor.hasOwnProperty('name')) {\n invalidType = input.constructor.name;\n } else {\n invalidType = \"a \".concat(invalidType);\n }\n }\n\n throw new TypeError(\"Expected string but received \".concat(invalidType, \".\"));\n }\n}\n\nmodule.exports = exports.default;\nmodule.exports.default = exports.default;\n\n//# sourceURL=webpack:///./node_modules/validator/lib/util/assertString.js?");
/***/ }),
/***/ "./node_modules/validator/lib/util/includes.js":
/*!*****************************************************!*\
!*** ./node_modules/validator/lib/util/includes.js ***!
\*****************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
eval("\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = void 0;\n\nvar includes = function includes(arr, val) {\n return arr.some(function (arrVal) {\n return val === arrVal;\n });\n};\n\nvar _default = includes;\nexports.default = _default;\nmodule.exports = exports.default;\nmodule.exports.default = exports.default;\n\n//# sourceURL=webpack:///./node_modules/validator/lib/util/includes.js?");
/***/ }),
/***/ "./node_modules/validator/lib/util/merge.js":
/*!**************************************************!*\
!*** ./node_modules/validator/lib/util/merge.js ***!
\**************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
eval("\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = merge;\n\nfunction merge() {\n var obj = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};\n var defaults = arguments.length > 1 ? arguments[1] : undefined;\n\n for (var key in defaults) {\n if (typeof obj[key] === 'undefined') {\n obj[key] = defaults[key];\n }\n }\n\n return obj;\n}\n\nmodule.exports = exports.default;\nmodule.exports.default = exports.default;\n\n//# sourceURL=webpack:///./node_modules/validator/lib/util/merge.js?");
/***/ }),
/***/ "./node_modules/validator/lib/util/multilineRegex.js":
/*!***********************************************************!*\
!*** ./node_modules/validator/lib/util/multilineRegex.js ***!
\***********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
eval("\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = multilineRegexp;\n\n/**\n * Build RegExp object from an array\n * of multiple/multi-line regexp parts\n *\n * @param {string[]} parts\n * @param {string} flags\n * @return {object} - RegExp object\n */\nfunction multilineRegexp(parts) {\n var flags = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : '';\n var regexpAsStringLiteral = parts.join('');\n return new RegExp(regexpAsStringLiteral, flags);\n}\n\nmodule.exports = exports.default;\nmodule.exports.default = exports.default;\n\n//# sourceURL=webpack:///./node_modules/validator/lib/util/multilineRegex.js?");
/***/ }),
/***/ "./node_modules/validator/lib/util/toString.js":
/*!*****************************************************!*\
!*** ./node_modules/validator/lib/util/toString.js ***!
\*****************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
eval("\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = toString;\n\nfunction _typeof(obj) { \"@babel/helpers - typeof\"; if (typeof Symbol === \"function\" && typeof Symbol.iterator === \"symbol\") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === \"function\" && obj.constructor === Symbol && obj !== Symbol.prototype ? \"symbol\" : typeof obj; }; } return _typeof(obj); }\n\nfunction toString(input) {\n if (_typeof(input) === 'object' && input !== null) {\n if (typeof input.toString === 'function') {\n input = input.toString();\n } else {\n input = '[object Object]';\n }\n } else if (input === null || typeof input === 'undefined' || isNaN(input) && !input.length) {\n input = '';\n }\n\n return String(input);\n}\n\nmodule.exports = exports.default;\nmodule.exports.default = exports.default;\n\n//# sourceURL=webpack:///./node_modules/validator/lib/util/toString.js?");
/***/ }),
/***/ "./node_modules/validator/lib/whitelist.js":
/*!*************************************************!*\
!*** ./node_modules/validator/lib/whitelist.js ***!
\*************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
eval("\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = whitelist;\n\nvar _assertString = _interopRequireDefault(__webpack_require__(/*! ./util/assertString */ \"./node_modules/validator/lib/util/assertString.js\"));\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\nfunction whitelist(str, chars) {\n (0, _assertString.default)(str);\n return str.replace(new RegExp(\"[^\".concat(chars, \"]+\"), 'g'), '');\n}\n\nmodule.exports = exports.default;\nmodule.exports.default = exports.default;\n\n//# sourceURL=webpack:///./node_modules/validator/lib/whitelist.js?");
/***/ }),
/***/ "./node_modules/value-equal/esm/value-equal.js":
/*!*****************************************************!*\
!*** ./node_modules/value-equal/esm/value-equal.js ***!
\*****************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
eval("__webpack_require__.r(__webpack_exports__);\nfunction valueOf(obj) {\n return obj.valueOf ? obj.valueOf() : Object.prototype.valueOf.call(obj);\n}\n\nfunction valueEqual(a, b) {\n // Test for strict equality first.\n if (a === b) return true;\n\n // Otherwise, if either of them == null they are not equal.\n if (a == null || b == null) return false;\n\n if (Array.isArray(a)) {\n return (\n Array.isArray(b) &&\n a.length === b.length &&\n a.every(function(item, index) {\n return valueEqual(item, b[index]);\n })\n );\n }\n\n if (typeof a === 'object' || typeof b === 'object') {\n var aValue = valueOf(a);\n var bValue = valueOf(b);\n\n if (aValue !== a || bValue !== b) return valueEqual(aValue, bValue);\n\n return Object.keys(Object.assign({}, a, b)).every(function(key) {\n return valueEqual(a[key], b[key]);\n });\n }\n\n return false;\n}\n\n/* harmony default export */ __webpack_exports__[\"default\"] = (valueEqual);\n\n\n//# sourceURL=webpack:///./node_modules/value-equal/esm/value-equal.js?");
/***/ }),
/***/ "./node_modules/webpack/buildin/global.js":
/*!***********************************!*\
!*** (webpack)/buildin/global.js ***!
\***********************************/
/*! no static exports found */
/***/ (function(module, exports) {
eval("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\n\n//# sourceURL=webpack:///(webpack)/buildin/global.js?");
/***/ }),
/***/ "./src/App.css":
/*!*********************!*\
!*** ./src/App.css ***!
\*********************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
eval("var api = __webpack_require__(/*! ../node_modules/style-loader/dist/runtime/injectStylesIntoStyleTag.js */ \"./node_modules/style-loader/dist/runtime/injectStylesIntoStyleTag.js\");\n var content = __webpack_require__(/*! !../node_modules/css-loader/dist/cjs.js!./App.css */ \"./node_modules/css-loader/dist/cjs.js!./src/App.css\");\n\n content = content.__esModule ? content.default : content;\n\n if (typeof content === 'string') {\n content = [[module.i, content, '']];\n }\n\nvar options = {};\n\noptions.insert = \"head\";\noptions.singleton = false;\n\nvar update = api(content, options);\n\n\n\nmodule.exports = content.locals || {};\n\n//# sourceURL=webpack:///./src/App.css?");
/***/ }),
/***/ "./src/App.js":
/*!********************!*\
!*** ./src/App.js ***!
\********************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
eval("__webpack_require__.r(__webpack_exports__);\n/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! react */ \"./node_modules/react/index.js\");\n/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);\n/* harmony import */ var react_router_dom__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! react-router-dom */ \"./node_modules/react-router-dom/esm/react-router-dom.js\");\n/* harmony import */ var bootstrap_dist_css_bootstrap_min_css__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! bootstrap/dist/css/bootstrap.min.css */ \"./node_modules/bootstrap/dist/css/bootstrap.min.css\");\n/* harmony import */ var bootstrap_dist_css_bootstrap_min_css__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(bootstrap_dist_css_bootstrap_min_css__WEBPACK_IMPORTED_MODULE_2__);\n/* harmony import */ var _App_css__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./App.css */ \"./src/App.css\");\n/* harmony import */ var _App_css__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(_App_css__WEBPACK_IMPORTED_MODULE_3__);\n/* harmony import */ var _services_auth_service__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./services/auth-service */ \"./src/services/auth-service.js\");\n/* harmony import */ var _components_login_component__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./components/login.component */ \"./src/components/login.component.js\");\n/* harmony import */ var _components_register_component__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./components/register.component */ \"./src/components/register.component.js\");\n/* harmony import */ var _components_home_component__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./components/home.component */ \"./src/components/home.component.js\");\n/* harmony import */ var _components_profile_component__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./components/profile.component */ \"./src/components/profile.component.js\");\n/* harmony import */ var _components_board_user_component__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ./components/board-user.component */ \"./src/components/board-user.component.js\");\nfunction _typeof(obj) { \"@babel/helpers - typeof\"; if (typeof Symbol === \"function\" && typeof Symbol.iterator === \"symbol\") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === \"function\" && obj.constructor === Symbol && obj !== Symbol.prototype ? \"symbol\" : typeof obj; }; } return _typeof(obj); }\n\nfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(\"Cannot call a class as a function\"); } }\n\nfunction _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if (\"value\" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }\n\nfunction _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }\n\nfunction _inherits(subClass, superClass) { if (typeof superClass !== \"function\" && superClass !== null) { throw new TypeError(\"Super expression must either be null or a function\"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); }\n\nfunction _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }\n\nfunction _createSuper(Derived) { return function () { var Super = _getPrototypeOf(Derived), result; if (_isNativeReflectConstruct()) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }\n\nfunction _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === \"object\" || typeof call === \"function\")) { return call; } return _assertThisInitialized(self); }\n\nfunction _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError(\"this hasn't been initialised - super() hasn't been called\"); } return self; }\n\nfunction _isNativeReflectConstruct() { if (typeof Reflect === \"undefined\" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === \"function\") return true; try { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } }\n\nfunction _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }\n\n\n\n\n\n\n\n\n\n\n\n\nvar App = /*#__PURE__*/function (_Component) {\n _inherits(App, _Component);\n\n var _super = _createSuper(App);\n\n function App(props) {\n var _this;\n\n _classCallCheck(this, App);\n\n _this = _super.call(this, props);\n _this.logOut = _this.logOut.bind(_assertThisInitialized(_this));\n _this.state = {\n showModeratorBoard: false,\n showAdminBoard: false,\n currentUser: undefined\n };\n return _this;\n }\n\n _createClass(App, [{\n key: \"componentDidMount\",\n value: function componentDidMount() {\n var user = _services_auth_service__WEBPACK_IMPORTED_MODULE_4__[\"default\"].getCurrentUser();\n\n if (user) {\n this.setState({\n currentUser: _services_auth_service__WEBPACK_IMPORTED_MODULE_4__[\"default\"].getCurrentUser() // showModeratorBoard: user.roles.includes(\"ROLE_MODERATOR\"),\n // showAdminBoard: user.roles.includes(\"ROLE_ADMIN\")\n\n });\n }\n }\n }, {\n key: \"logOut\",\n value: function logOut() {\n _services_auth_service__WEBPACK_IMPORTED_MODULE_4__[\"default\"].logout();\n }\n }, {\n key: \"render\",\n value: function render() {\n var _this$state = this.state,\n currentUser = _this$state.currentUser,\n showModeratorBoard = _this$state.showModeratorBoard,\n showAdminBoard = _this$state.showAdminBoard;\n return /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(react_router_dom__WEBPACK_IMPORTED_MODULE_1__[\"BrowserRouter\"], null, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(\"div\", null, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(\"nav\", {\n className: \"navbar navbar-expand navbar-dark bg-dark\"\n }, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(react_router_dom__WEBPACK_IMPORTED_MODULE_1__[\"Link\"], {\n to: \"/\",\n className: \"navbar-brand\"\n }, \"VideoService\"), /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(\"div\", {\n className: \"navbar-nav mr-auto\"\n }, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(\"li\", {\n className: \"nav-item\"\n }, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(react_router_dom__WEBPACK_IMPORTED_MODULE_1__[\"Link\"], {\n to: \"/home\",\n className: \"nav-link\"\n }, \"Home\")), showModeratorBoard && /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(\"li\", {\n className: \"nav-item\"\n }, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(react_router_dom__WEBPACK_IMPORTED_MODULE_1__[\"Link\"], {\n to: \"/mod\",\n className: \"nav-link\"\n }, \"Moderator Board\")), showAdminBoard && /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(\"li\", {\n className: \"nav-item\"\n }, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(react_router_dom__WEBPACK_IMPORTED_MODULE_1__[\"Link\"], {\n to: \"/admin\",\n className: \"nav-link\"\n }, \"Admin Board\")), currentUser && /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(\"li\", {\n className: \"nav-item\"\n }, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(react_router_dom__WEBPACK_IMPORTED_MODULE_1__[\"Link\"], {\n to: \"/user\",\n className: \"nav-link\"\n }, \"User\"))), currentUser ? /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(\"div\", {\n className: \"navbar-nav ml-auto\"\n }, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(\"li\", {\n className: \"nav-item\"\n }, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(react_router_dom__WEBPACK_IMPORTED_MODULE_1__[\"Link\"], {\n to: \"/profile\",\n className: \"nav-link\"\n }, currentUser.username)), /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(\"li\", {\n className: \"nav-item\"\n }, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(\"a\", {\n href: \"/\",\n className: \"nav-link\",\n onClick: this.logOut\n }, \"LogOut\"))) : /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(\"div\", {\n className: \"navbar-nav ml-auto\"\n }, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(\"li\", {\n className: \"nav-item\"\n }, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(react_router_dom__WEBPACK_IMPORTED_MODULE_1__[\"Link\"], {\n to: \"/login\",\n className: \"nav-link\"\n }, \"Login\")), /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(\"li\", {\n className: \"nav-item\"\n }, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(react_router_dom__WEBPACK_IMPORTED_MODULE_1__[\"Link\"], {\n to: \"/register\",\n className: \"nav-link\"\n }, \"Sign Up\")))), /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(\"div\", {\n className: \"container mt-3\"\n }, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(react_router_dom__WEBPACK_IMPORTED_MODULE_1__[\"Switch\"], null, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(react_router_dom__WEBPACK_IMPORTED_MODULE_1__[\"Route\"], {\n exact: true,\n path: [\"/\", \"/home\"],\n component: _components_home_component__WEBPACK_IMPORTED_MODULE_7__[\"default\"]\n }), /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(react_router_dom__WEBPACK_IMPORTED_MODULE_1__[\"Route\"], {\n exact: true,\n path: \"/login\",\n component: _components_login_component__WEBPACK_IMPORTED_MODULE_5__[\"default\"]\n }), /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(react_router_dom__WEBPACK_IMPORTED_MODULE_1__[\"Route\"], {\n exact: true,\n path: \"/register\",\n component: _components_register_component__WEBPACK_IMPORTED_MODULE_6__[\"default\"]\n }), /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(react_router_dom__WEBPACK_IMPORTED_MODULE_1__[\"Route\"], {\n exact: true,\n path: \"/profile\",\n component: _components_profile_component__WEBPACK_IMPORTED_MODULE_8__[\"default\"]\n }), /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(react_router_dom__WEBPACK_IMPORTED_MODULE_1__[\"Route\"], {\n path: \"/user\",\n component: _components_board_user_component__WEBPACK_IMPORTED_MODULE_9__[\"default\"]\n })))));\n }\n }]);\n\n return App;\n}(react__WEBPACK_IMPORTED_MODULE_0__[\"Component\"]);\n\n/* harmony default export */ __webpack_exports__[\"default\"] = (App);\n\n//# sourceURL=webpack:///./src/App.js?");
/***/ }),
/***/ "./src/components/board-user.component.js":
/*!************************************************!*\
!*** ./src/components/board-user.component.js ***!
\************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"default\", function() { return BoardUser; });\n/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! react */ \"./node_modules/react/index.js\");\n/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);\n/* harmony import */ var _services_user_service__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../services/user-service */ \"./src/services/user-service.js\");\nfunction _typeof(obj) { \"@babel/helpers - typeof\"; if (typeof Symbol === \"function\" && typeof Symbol.iterator === \"symbol\") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === \"function\" && obj.constructor === Symbol && obj !== Symbol.prototype ? \"symbol\" : typeof obj; }; } return _typeof(obj); }\n\nfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(\"Cannot call a class as a function\"); } }\n\nfunction _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if (\"value\" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }\n\nfunction _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }\n\nfunction _inherits(subClass, superClass) { if (typeof superClass !== \"function\" && superClass !== null) { throw new TypeError(\"Super expression must either be null or a function\"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); }\n\nfunction _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }\n\nfunction _createSuper(Derived) { return function () { var Super = _getPrototypeOf(Derived), result; if (_isNativeReflectConstruct()) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }\n\nfunction _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === \"object\" || typeof call === \"function\")) { return call; } return _assertThisInitialized(self); }\n\nfunction _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError(\"this hasn't been initialised - super() hasn't been called\"); } return self; }\n\nfunction _isNativeReflectConstruct() { if (typeof Reflect === \"undefined\" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === \"function\") return true; try { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } }\n\nfunction _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }\n\n\n\n\nvar BoardUser = /*#__PURE__*/function (_Component) {\n _inherits(BoardUser, _Component);\n\n var _super = _createSuper(BoardUser);\n\n function BoardUser(props) {\n var _this;\n\n _classCallCheck(this, BoardUser);\n\n _this = _super.call(this, props);\n _this.state = {\n content: \"\"\n };\n return _this;\n }\n\n _createClass(BoardUser, [{\n key: \"componentDidMount\",\n value: function componentDidMount() {\n var _this2 = this;\n\n _services_user_service__WEBPACK_IMPORTED_MODULE_1__[\"default\"].getUserBoard().then(function (response) {\n _this2.setState({\n content: response.data\n });\n }, function (error) {\n _this2.setState({\n content: error.response && error.response.data && error.response.data.message || error.message || error.toString()\n });\n });\n }\n }, {\n key: \"render\",\n value: function render() {\n return /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(\"div\", {\n className: \"container\"\n }, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(\"header\", {\n className: \"jumbotron\"\n }, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(\"h3\", null, this.state.content)));\n }\n }]);\n\n return BoardUser;\n}(react__WEBPACK_IMPORTED_MODULE_0__[\"Component\"]);\n\n\n\n//# sourceURL=webpack:///./src/components/board-user.component.js?");
/***/ }),
/***/ "./src/components/home.component.js":
/*!******************************************!*\
!*** ./src/components/home.component.js ***!
\******************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"default\", function() { return Home; });\n/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! react */ \"./node_modules/react/index.js\");\n/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);\n/* harmony import */ var _config_config__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../config/config */ \"./src/config/config.js\");\n/* harmony import */ var _services_user_service__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../services/user-service */ \"./src/services/user-service.js\");\n/* harmony import */ var _services_auth_service__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../services/auth-service */ \"./src/services/auth-service.js\");\nfunction _typeof(obj) { \"@babel/helpers - typeof\"; if (typeof Symbol === \"function\" && typeof Symbol.iterator === \"symbol\") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === \"function\" && obj.constructor === Symbol && obj !== Symbol.prototype ? \"symbol\" : typeof obj; }; } return _typeof(obj); }\n\nfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(\"Cannot call a class as a function\"); } }\n\nfunction _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if (\"value\" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }\n\nfunction _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }\n\nfunction _inherits(subClass, superClass) { if (typeof superClass !== \"function\" && superClass !== null) { throw new TypeError(\"Super expression must either be null or a function\"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); }\n\nfunction _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }\n\nfunction _createSuper(Derived) { return function () { var Super = _getPrototypeOf(Derived), result; if (_isNativeReflectConstruct()) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }\n\nfunction _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === \"object\" || typeof call === \"function\")) { return call; } return _assertThisInitialized(self); }\n\nfunction _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError(\"this hasn't been initialised - super() hasn't been called\"); } return self; }\n\nfunction _isNativeReflectConstruct() { if (typeof Reflect === \"undefined\" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === \"function\") return true; try { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } }\n\nfunction _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }\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\n\n\n\n\n\nvar Home = /*#__PURE__*/function (_Component) {\n _inherits(Home, _Component);\n\n var _super = _createSuper(Home);\n\n function Home(props) {\n var _this;\n\n _classCallCheck(this, Home);\n\n _this = _super.call(this, props);\n\n _defineProperty(_assertThisInitialized(_this), \"videoSecond\", 0);\n\n _this.state = {\n content: \"\",\n currentUser: undefined\n };\n _this.videoTimeHandler = _this.videoTimeHandler.bind(_assertThisInitialized(_this));\n return _this;\n }\n\n _createClass(Home, [{\n key: \"componentDidMount\",\n value: function componentDidMount() {\n var _this2 = this;\n\n _services_user_service__WEBPACK_IMPORTED_MODULE_2__[\"default\"].getPublicContent().then(function (response) {\n _this2.setState({\n content: response.data\n });\n }, function (error) {\n _this2.setState({\n content: error.response && error.response.data || error.message || error.toString()\n });\n });\n var user = _services_auth_service__WEBPACK_IMPORTED_MODULE_3__[\"default\"].getCurrentUser();\n\n if (user) {\n this.setState({\n currentUser: _services_auth_service__WEBPACK_IMPORTED_MODULE_3__[\"default\"].getCurrentUser() // showModeratorBoard: user.roles.includes(\"ROLE_MODERATOR\"),\n // showAdminBoard: user.roles.includes(\"ROLE_ADMIN\")\n\n });\n }\n }\n }, {\n key: \"videoTimeHandler\",\n value: function videoTimeHandler(event) {\n //console.log(event.target.currentTime)\n var minutes = Math.floor(event.target.currentTime / 60);\n var seconds = Math.floor(event.target.currentTime - minutes * 60);\n\n if (this.videoSecond === 20) {\n this.videoSecond = 0; // call api to save this in database\n\n _services_user_service__WEBPACK_IMPORTED_MODULE_2__[\"default\"].updateStatus(\"01-01_Trailer\", this.state.currentUser.id, minutes + \":\" + seconds).then(function (response) {\n console.log(\"response:\" + response);\n }, function (error) {\n console.log(\"error:\" + error);\n });\n console.log(minutes + \":\" + seconds);\n }\n\n this.videoSecond = this.videoSecond + 1; // setTimeout(function(){\n // console.log('your audio is started just now');\n // }, 1000)\n }\n }, {\n key: \"render\",\n value: function render() {\n return /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(\"div\", {\n className: \"container\"\n }, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(\"header\", {\n className: \"jumbotron\"\n }, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(\"h3\", null, this.state.content), this.state.currentUser ? /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(\"video\", {\n width: \"320\",\n height: \"240\",\n autoPlay: \"autoplay\",\n onTimeUpdate: this.videoTimeHandler,\n controls: true\n }, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(\"source\", {\n src: _config_config__WEBPACK_IMPORTED_MODULE_1__[\"default\"].backendHost + \"/videos/01-01_Trailer?access_token=\" + this.state.currentUser.accessToken,\n type: \"video/mp4\"\n })) : /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(\"p\", null)));\n }\n }]);\n\n return Home;\n}(react__WEBPACK_IMPORTED_MODULE_0__[\"Component\"]);\n\n\n\n//# sourceURL=webpack:///./src/components/home.component.js?");
/***/ }),
/***/ "./src/components/login.component.js":
/*!*******************************************!*\
!*** ./src/components/login.component.js ***!
\*******************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"default\", function() { return Login; });\n/* harmony import */ var react_validation_build_form__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! react-validation/build/form */ \"./node_modules/react-validation/build/form.js\");\n/* harmony import */ var react_validation_build_form__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react_validation_build_form__WEBPACK_IMPORTED_MODULE_0__);\n/* harmony import */ var react_validation_build_input__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! react-validation/build/input */ \"./node_modules/react-validation/build/input.js\");\n/* harmony import */ var react_validation_build_input__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(react_validation_build_input__WEBPACK_IMPORTED_MODULE_1__);\n/* harmony import */ var react_validation_build_button__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! react-validation/build/button */ \"./node_modules/react-validation/build/button.js\");\n/* harmony import */ var react_validation_build_button__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(react_validation_build_button__WEBPACK_IMPORTED_MODULE_2__);\n/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! react */ \"./node_modules/react/index.js\");\n/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_3__);\n/* harmony import */ var _services_auth_service__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../services/auth-service */ \"./src/services/auth-service.js\");\n/* harmony import */ var react_router_dom__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! react-router-dom */ \"./node_modules/react-router-dom/esm/react-router-dom.js\");\n/* harmony import */ var validator__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! validator */ \"./node_modules/validator/index.js\");\n/* harmony import */ var validator__WEBPACK_IMPORTED_MODULE_6___default = /*#__PURE__*/__webpack_require__.n(validator__WEBPACK_IMPORTED_MODULE_6__);\nfunction _typeof(obj) { \"@babel/helpers - typeof\"; if (typeof Symbol === \"function\" && typeof Symbol.iterator === \"symbol\") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === \"function\" && obj.constructor === Symbol && obj !== Symbol.prototype ? \"symbol\" : typeof obj; }; } return _typeof(obj); }\n\nfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(\"Cannot call a class as a function\"); } }\n\nfunction _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if (\"value\" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }\n\nfunction _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }\n\nfunction _inherits(subClass, superClass) { if (typeof superClass !== \"function\" && superClass !== null) { throw new TypeError(\"Super expression must either be null or a function\"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); }\n\nfunction _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }\n\nfunction _createSuper(Derived) { return function () { var Super = _getPrototypeOf(Derived), result; if (_isNativeReflectConstruct()) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }\n\nfunction _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === \"object\" || typeof call === \"function\")) { return call; } return _assertThisInitialized(self); }\n\nfunction _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError(\"this hasn't been initialised - super() hasn't been called\"); } return self; }\n\nfunction _isNativeReflectConstruct() { if (typeof Reflect === \"undefined\" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === \"function\") return true; try { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } }\n\nfunction _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }\n\n\n\n\n\n\n\n\n\nvar required = function required(value) {\n if (!value) {\n return /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement(\"div\", {\n className: \"alert alert-danger\",\n role: \"alert\"\n }, \"This field is required!\");\n }\n};\n\nvar Login = /*#__PURE__*/function (_Component) {\n _inherits(Login, _Component);\n\n var _super = _createSuper(Login);\n\n function Login(props) {\n var _this;\n\n _classCallCheck(this, Login);\n\n _this = _super.call(this, props);\n _this.handleLogin = _this.handleLogin.bind(_assertThisInitialized(_this));\n _this.onChangeUsername = _this.onChangeUsername.bind(_assertThisInitialized(_this));\n _this.onChangePassword = _this.onChangePassword.bind(_assertThisInitialized(_this));\n _this.state = {\n username: \"\",\n password: \"\",\n loading: false,\n message: \"\"\n };\n return _this;\n }\n\n _createClass(Login, [{\n key: \"onChangeUsername\",\n value: function onChangeUsername(e) {\n this.setState({\n username: e.target.value\n });\n }\n }, {\n key: \"onChangePassword\",\n value: function onChangePassword(e) {\n this.setState({\n password: e.target.value\n });\n }\n }, {\n key: \"handleLogin\",\n value: function handleLogin(e) {\n var _this2 = this;\n\n e.preventDefault();\n this.setState({\n message: \"\",\n loading: true\n });\n this.form.validateAll();\n\n if (this.checkBtn.context._errors.length === 0) {\n _services_auth_service__WEBPACK_IMPORTED_MODULE_4__[\"default\"].login(this.state.username, this.state.password).then(function () {\n _this2.props.history.push(\"/\");\n\n window.location.reload();\n }, function (error) {\n var resMessage = error.response && error.response.data && error.response.data.message || error.message || error.toString();\n\n _this2.setState({\n loading: false,\n message: resMessage\n });\n });\n } else {\n this.setState({\n loading: false\n });\n }\n }\n }, {\n key: \"render\",\n value: function render() {\n var _this3 = this;\n\n return /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement(\"div\", {\n className: \"col-md-12\"\n }, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement(\"div\", {\n className: \"card card-container\"\n }, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement(\"img\", {\n src: \"//ssl.gstatic.com/accounts/ui/avatar_2x.png\",\n alt: \"profile-img\",\n className: \"profile-img-card\"\n }), /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement(react_validation_build_form__WEBPACK_IMPORTED_MODULE_0___default.a, {\n onSubmit: this.handleLogin,\n ref: function ref(c) {\n _this3.form = c;\n }\n }, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement(\"div\", {\n className: \"form-group\"\n }, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement(\"label\", {\n htmlFor: \"username\"\n }, \"Username\"), /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement(react_validation_build_input__WEBPACK_IMPORTED_MODULE_1___default.a, {\n type: \"text\",\n className: \"form-control\",\n name: \"username\",\n value: this.state.username,\n onChange: this.onChangeUsername,\n validations: [required]\n })), /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement(\"div\", {\n className: \"form-group\"\n }, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement(\"label\", {\n htmlFor: \"password\"\n }, \"Password\"), /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement(react_validation_build_input__WEBPACK_IMPORTED_MODULE_1___default.a, {\n type: \"password\",\n className: \"form-control\",\n name: \"password\",\n value: this.state.password,\n onChange: this.onChangePassword,\n validations: [required]\n })), /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement(\"div\", {\n className: \"form-group\"\n }, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement(\"button\", {\n className: \"btn btn-primary btn-block\",\n disabled: this.state.loading\n }, this.state.loading && /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement(\"span\", {\n className: \"spinner-border spinner-border-sm\"\n }), /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement(\"span\", null, \"Login\"))), this.state.message && /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement(\"div\", {\n className: \"form-group\"\n }, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement(\"div\", {\n className: \"alert alert-danger\",\n role: \"alert\"\n }, this.state.message)), /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement(react_validation_build_button__WEBPACK_IMPORTED_MODULE_2___default.a, {\n style: {\n display: \"none\"\n },\n ref: function ref(c) {\n _this3.checkBtn = c;\n }\n }))));\n }\n }]);\n\n return Login;\n}(react__WEBPACK_IMPORTED_MODULE_3__[\"Component\"]);\n\n\n\n//# sourceURL=webpack:///./src/components/login.component.js?");
/***/ }),
/***/ "./src/components/profile.component.js":
/*!*********************************************!*\
!*** ./src/components/profile.component.js ***!
\*********************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"default\", function() { return Profile; });\n/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! react */ \"./node_modules/react/index.js\");\n/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);\n/* harmony import */ var _services_auth_service__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../services/auth-service */ \"./src/services/auth-service.js\");\nfunction _typeof(obj) { \"@babel/helpers - typeof\"; if (typeof Symbol === \"function\" && typeof Symbol.iterator === \"symbol\") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === \"function\" && obj.constructor === Symbol && obj !== Symbol.prototype ? \"symbol\" : typeof obj; }; } return _typeof(obj); }\n\nfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(\"Cannot call a class as a function\"); } }\n\nfunction _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if (\"value\" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }\n\nfunction _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }\n\nfunction _inherits(subClass, superClass) { if (typeof superClass !== \"function\" && superClass !== null) { throw new TypeError(\"Super expression must either be null or a function\"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); }\n\nfunction _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }\n\nfunction _createSuper(Derived) { return function () { var Super = _getPrototypeOf(Derived), result; if (_isNativeReflectConstruct()) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }\n\nfunction _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === \"object\" || typeof call === \"function\")) { return call; } return _assertThisInitialized(self); }\n\nfunction _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError(\"this hasn't been initialised - super() hasn't been called\"); } return self; }\n\nfunction _isNativeReflectConstruct() { if (typeof Reflect === \"undefined\" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === \"function\") return true; try { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } }\n\nfunction _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }\n\n\n\n\nvar Profile = /*#__PURE__*/function (_Component) {\n _inherits(Profile, _Component);\n\n var _super = _createSuper(Profile);\n\n function Profile(props) {\n var _this;\n\n _classCallCheck(this, Profile);\n\n _this = _super.call(this, props);\n _this.state = {\n currentUser: _services_auth_service__WEBPACK_IMPORTED_MODULE_1__[\"default\"].getCurrentUser()\n };\n return _this;\n }\n\n _createClass(Profile, [{\n key: \"render\",\n value: function render() {\n var currentUser = this.state.currentUser;\n return /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(\"div\", {\n className: \"container\"\n }, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(\"header\", {\n className: \"jumbotron\"\n }, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(\"h3\", null, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(\"strong\", null, currentUser.username), \" Profile\")), /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(\"p\", null, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(\"strong\", null, \"Token:\"), \" \", currentUser.accessToken.substring(0, 20), \" ...\", \" \", currentUser.accessToken.substr(currentUser.accessToken.length - 20)), /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(\"p\", null, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(\"strong\", null, \"Id:\"), \" \", currentUser.id), /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(\"p\", null, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(\"strong\", null, \"Email:\"), \" \", currentUser.email), /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(\"strong\", null, \"Authorities:\"), /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(\"ul\", null, currentUser.roles && currentUser.roles.map(function (role, index) {\n return /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(\"li\", {\n key: index\n }, role);\n })));\n }\n }]);\n\n return Profile;\n}(react__WEBPACK_IMPORTED_MODULE_0__[\"Component\"]);\n\n\n\n//# sourceURL=webpack:///./src/components/profile.component.js?");
/***/ }),
/***/ "./src/components/register.component.js":
/*!**********************************************!*\
!*** ./src/components/register.component.js ***!
\**********************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"default\", function() { return Register; });\n/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! react */ \"./node_modules/react/index.js\");\n/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);\n/* harmony import */ var react_validation_build_form__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! react-validation/build/form */ \"./node_modules/react-validation/build/form.js\");\n/* harmony import */ var react_validation_build_form__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(react_validation_build_form__WEBPACK_IMPORTED_MODULE_1__);\n/* harmony import */ var react_validation_build_input__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! react-validation/build/input */ \"./node_modules/react-validation/build/input.js\");\n/* harmony import */ var react_validation_build_input__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(react_validation_build_input__WEBPACK_IMPORTED_MODULE_2__);\n/* harmony import */ var react_validation_build_button__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! react-validation/build/button */ \"./node_modules/react-validation/build/button.js\");\n/* harmony import */ var react_validation_build_button__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(react_validation_build_button__WEBPACK_IMPORTED_MODULE_3__);\n/* harmony import */ var validator__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! validator */ \"./node_modules/validator/index.js\");\n/* harmony import */ var validator__WEBPACK_IMPORTED_MODULE_4___default = /*#__PURE__*/__webpack_require__.n(validator__WEBPACK_IMPORTED_MODULE_4__);\n/* harmony import */ var _services_auth_service__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../services/auth-service */ \"./src/services/auth-service.js\");\nfunction _typeof(obj) { \"@babel/helpers - typeof\"; if (typeof Symbol === \"function\" && typeof Symbol.iterator === \"symbol\") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === \"function\" && obj.constructor === Symbol && obj !== Symbol.prototype ? \"symbol\" : typeof obj; }; } return _typeof(obj); }\n\nfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(\"Cannot call a class as a function\"); } }\n\nfunction _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if (\"value\" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }\n\nfunction _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }\n\nfunction _inherits(subClass, superClass) { if (typeof superClass !== \"function\" && superClass !== null) { throw new TypeError(\"Super expression must either be null or a function\"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); }\n\nfunction _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }\n\nfunction _createSuper(Derived) { return function () { var Super = _getPrototypeOf(Derived), result; if (_isNativeReflectConstruct()) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }\n\nfunction _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === \"object\" || typeof call === \"function\")) { return call; } return _assertThisInitialized(self); }\n\nfunction _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError(\"this hasn't been initialised - super() hasn't been called\"); } return self; }\n\nfunction _isNativeReflectConstruct() { if (typeof Reflect === \"undefined\" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === \"function\") return true; try { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } }\n\nfunction _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }\n\n\n\n\n\n\n\n\nvar required = function required(value) {\n if (!value) {\n return /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(\"div\", {\n className: \"alert alert-danger\",\n role: \"alert\"\n }, \"This field is required!\");\n }\n};\n\nvar email = function email(value) {\n if (!Object(validator__WEBPACK_IMPORTED_MODULE_4__[\"isEmail\"])(value)) {\n return /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(\"div\", {\n className: \"alert alert-danger\",\n role: \"alert\"\n }, \"This is not a valid email.\");\n }\n};\n\nvar vusername = function vusername(value) {\n if (value.length < 3 || value.length > 20) {\n return /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(\"div\", {\n className: \"alert alert-danger\",\n role: \"alert\"\n }, \"The username must be between 3 and 20 characters.\");\n }\n};\n\nvar vpassword = function vpassword(value) {\n if (value.length < 6 || value.length > 40) {\n return /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(\"div\", {\n className: \"alert alert-danger\",\n role: \"alert\"\n }, \"The password must be between 6 and 40 characters.\");\n }\n};\n\nvar Register = /*#__PURE__*/function (_Component) {\n _inherits(Register, _Component);\n\n var _super = _createSuper(Register);\n\n function Register(props) {\n var _this;\n\n _classCallCheck(this, Register);\n\n _this = _super.call(this, props);\n _this.handleRegister = _this.handleRegister.bind(_assertThisInitialized(_this));\n _this.onChangeUsername = _this.onChangeUsername.bind(_assertThisInitialized(_this));\n _this.onChangeEmail = _this.onChangeEmail.bind(_assertThisInitialized(_this));\n _this.onChangePassword = _this.onChangePassword.bind(_assertThisInitialized(_this));\n _this.state = {\n username: \"\",\n email: \"\",\n password: \"\",\n successful: false,\n message: \"\"\n };\n return _this;\n }\n\n _createClass(Register, [{\n key: \"onChangeUsername\",\n value: function onChangeUsername(e) {\n this.setState({\n username: e.target.value\n });\n }\n }, {\n key: \"onChangeEmail\",\n value: function onChangeEmail(e) {\n this.setState({\n email: e.target.value\n });\n }\n }, {\n key: \"onChangePassword\",\n value: function onChangePassword(e) {\n this.setState({\n password: e.target.value\n });\n }\n }, {\n key: \"handleRegister\",\n value: function handleRegister(e) {\n var _this2 = this;\n\n e.preventDefault();\n this.setState({\n message: \"\",\n successful: false\n });\n this.form.validateAll();\n\n if (this.checkBtn.context._errors.length === 0) {\n _services_auth_service__WEBPACK_IMPORTED_MODULE_5__[\"default\"].register(this.state.username, this.state.email, this.state.password).then(function (response) {\n _this2.setState({\n message: response.data.message,\n successful: true\n });\n }, function (error) {\n var resMessage = error.response && error.response.data && error.response.data.message || error.message || error.toString();\n\n _this2.setState({\n successful: false,\n message: resMessage\n });\n });\n }\n }\n }, {\n key: \"render\",\n value: function render() {\n var _this3 = this;\n\n return /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(\"div\", {\n className: \"col-md-12\"\n }, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(\"div\", {\n className: \"card card-container\"\n }, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(\"img\", {\n src: \"//ssl.gstatic.com/accounts/ui/avatar_2x.png\",\n alt: \"profile-img\",\n className: \"profile-img-card\"\n }), /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(react_validation_build_form__WEBPACK_IMPORTED_MODULE_1___default.a, {\n onSubmit: this.handleRegister,\n ref: function ref(c) {\n _this3.form = c;\n }\n }, !this.state.successful && /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(\"div\", null, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(\"div\", {\n className: \"form-group\"\n }, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(\"label\", {\n htmlFor: \"username\"\n }, \"Username\"), /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(react_validation_build_input__WEBPACK_IMPORTED_MODULE_2___default.a, {\n type: \"text\",\n className: \"form-control\",\n name: \"username\",\n value: this.state.username,\n onChange: this.onChangeUsername,\n validations: [required, vusername]\n })), /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(\"div\", {\n className: \"form-group\"\n }, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(\"label\", {\n htmlFor: \"email\"\n }, \"Email\"), /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(react_validation_build_input__WEBPACK_IMPORTED_MODULE_2___default.a, {\n type: \"text\",\n className: \"form-control\",\n name: \"email\",\n value: this.state.email,\n onChange: this.onChangeEmail,\n validations: [required, email]\n })), /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(\"div\", {\n className: \"form-group\"\n }, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(\"label\", {\n htmlFor: \"password\"\n }, \"Password\"), /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(react_validation_build_input__WEBPACK_IMPORTED_MODULE_2___default.a, {\n type: \"password\",\n className: \"form-control\",\n name: \"password\",\n value: this.state.password,\n onChange: this.onChangePassword,\n validations: [required, vpassword]\n })), /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(\"div\", {\n className: \"form-group\"\n }, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(\"button\", {\n className: \"btn btn-primary btn-block\"\n }, \"Sign Up\"))), this.state.message && /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(\"div\", {\n className: \"form-group\"\n }, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(\"div\", {\n className: this.state.successful ? \"alert alert-success\" : \"alert alert-danger\",\n role: \"alert\"\n }, this.state.message)), /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(react_validation_build_button__WEBPACK_IMPORTED_MODULE_3___default.a, {\n style: {\n display: \"none\"\n },\n ref: function ref(c) {\n _this3.checkBtn = c;\n }\n }))));\n }\n }]);\n\n return Register;\n}(react__WEBPACK_IMPORTED_MODULE_0__[\"Component\"]);\n\n\n\n//# sourceURL=webpack:///./src/components/register.component.js?");
/***/ }),
/***/ "./src/config/config.js":
/*!******************************!*\
!*** ./src/config/config.js ***!
\******************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
eval("__webpack_require__.r(__webpack_exports__);\nvar host = window.location.hostname === 'localhost' ? 'http://localhost:8081' : \"https://springboot-apis.herokuapp.com\";\nvar config = {\n backendHost: host\n};\n/* harmony default export */ __webpack_exports__[\"default\"] = (config);\n\n//# sourceURL=webpack:///./src/config/config.js?");
/***/ }),
/***/ "./src/index.js":
/*!**********************!*\
!*** ./src/index.js ***!
\**********************/
/*! no exports provided */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
eval("__webpack_require__.r(__webpack_exports__);\n/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! react */ \"./node_modules/react/index.js\");\n/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);\n/* harmony import */ var react_dom__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! react-dom */ \"./node_modules/react-dom/index.js\");\n/* harmony import */ var react_dom__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(react_dom__WEBPACK_IMPORTED_MODULE_1__);\n/* harmony import */ var react_router_dom__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! react-router-dom */ \"./node_modules/react-router-dom/esm/react-router-dom.js\");\n/* harmony import */ var _App__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./App */ \"./src/App.js\");\n\n\n // import MyInfo from \"./components/MyInfo\"\n//import App from './components/learning/LearningApp';\n\n\nreact_dom__WEBPACK_IMPORTED_MODULE_1___default.a.render( /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(react_router_dom__WEBPACK_IMPORTED_MODULE_2__[\"BrowserRouter\"], null, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(_App__WEBPACK_IMPORTED_MODULE_3__[\"default\"], null)), document.getElementById('root'));\n\n//# sourceURL=webpack:///./src/index.js?");
/***/ }),
/***/ "./src/services/auth-header.js":
/*!*************************************!*\
!*** ./src/services/auth-header.js ***!
\*************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"default\", function() { return authHeader; });\nfunction authHeader() {\n var user = JSON.parse(localStorage.getItem('user'));\n\n if (user && user.accessToken) {\n return {\n Authorization: 'Bearer ' + user.accessToken,\n \"Access-Control-Allow-Origin\": \"*\"\n };\n } else {\n return {};\n }\n}\n\n//# sourceURL=webpack:///./src/services/auth-header.js?");
/***/ }),
/***/ "./src/services/auth-service.js":
/*!**************************************!*\
!*** ./src/services/auth-service.js ***!
\**************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
eval("__webpack_require__.r(__webpack_exports__);\n/* harmony import */ var axios__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! axios */ \"./node_modules/axios/index.js\");\n/* harmony import */ var axios__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(axios__WEBPACK_IMPORTED_MODULE_0__);\n/* harmony import */ var _config_config__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../config/config */ \"./src/config/config.js\");\nfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(\"Cannot call a class as a function\"); } }\n\nfunction _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if (\"value\" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }\n\nfunction _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }\n\n\n\nvar API_URL = _config_config__WEBPACK_IMPORTED_MODULE_1__[\"default\"].backendHost + \"/api/auth/\";\n\nvar AuthService = /*#__PURE__*/function () {\n function AuthService() {\n _classCallCheck(this, AuthService);\n }\n\n _createClass(AuthService, [{\n key: \"login\",\n value: function login(username, password) {\n return axios__WEBPACK_IMPORTED_MODULE_0___default.a.post(API_URL + \"signin\", {\n username: username,\n password: password\n }).then(function (response) {\n if (response.data.accessToken) {\n localStorage.setItem(\"user\", JSON.stringify(response.data));\n }\n\n return response.data;\n });\n }\n }, {\n key: \"logout\",\n value: function logout() {\n localStorage.removeItem(\"user\");\n }\n }, {\n key: \"register\",\n value: function register(username, email, password) {\n return axios__WEBPACK_IMPORTED_MODULE_0___default.a.post(API_URL + \"signup\", {\n username: username,\n email: email,\n password: password\n });\n }\n }, {\n key: \"getCurrentUser\",\n value: function getCurrentUser() {\n return JSON.parse(localStorage.getItem('user'));\n }\n }]);\n\n return AuthService;\n}();\n\n/* harmony default export */ __webpack_exports__[\"default\"] = (new AuthService());\n\n//# sourceURL=webpack:///./src/services/auth-service.js?");
/***/ }),
/***/ "./src/services/user-service.js":
/*!**************************************!*\
!*** ./src/services/user-service.js ***!
\**************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
eval("__webpack_require__.r(__webpack_exports__);\n/* harmony import */ var axios__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! axios */ \"./node_modules/axios/index.js\");\n/* harmony import */ var axios__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(axios__WEBPACK_IMPORTED_MODULE_0__);\n/* harmony import */ var _auth_header__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./auth-header */ \"./src/services/auth-header.js\");\n/* harmony import */ var _config_config__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../config/config */ \"./src/config/config.js\");\nfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(\"Cannot call a class as a function\"); } }\n\nfunction _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if (\"value\" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }\n\nfunction _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }\n\n\n\n\nvar API_URL = _config_config__WEBPACK_IMPORTED_MODULE_2__[\"default\"].backendHost + '/users/';\n\nvar UserService = /*#__PURE__*/function () {\n function UserService() {\n _classCallCheck(this, UserService);\n }\n\n _createClass(UserService, [{\n key: \"getPublicContent\",\n value: function getPublicContent() {\n return axios__WEBPACK_IMPORTED_MODULE_0___default.a.get(API_URL + 'all');\n }\n }, {\n key: \"getUserBoard\",\n value: function getUserBoard() {\n return axios__WEBPACK_IMPORTED_MODULE_0___default.a.get(API_URL + 'user', {\n headers: Object(_auth_header__WEBPACK_IMPORTED_MODULE_1__[\"default\"])()\n });\n }\n }, {\n key: \"getUserDetails\",\n value: function getUserDetails(userId) {\n return axios__WEBPACK_IMPORTED_MODULE_0___default.a.get(API_URL + userId, {\n headers: Object(_auth_header__WEBPACK_IMPORTED_MODULE_1__[\"default\"])()\n });\n }\n }, {\n key: \"getModeratorBoard\",\n value: function getModeratorBoard() {\n return axios__WEBPACK_IMPORTED_MODULE_0___default.a.get(API_URL + 'mod', {\n headers: Object(_auth_header__WEBPACK_IMPORTED_MODULE_1__[\"default\"])()\n });\n }\n }, {\n key: \"getAdminBoard\",\n value: function getAdminBoard() {\n return axios__WEBPACK_IMPORTED_MODULE_0___default.a.get(API_URL + 'admin', {\n headers: Object(_auth_header__WEBPACK_IMPORTED_MODULE_1__[\"default\"])()\n });\n }\n }, {\n key: \"updateStatus\",\n value: function updateStatus(videoName, userId, duration) {\n return axios__WEBPACK_IMPORTED_MODULE_0___default.a.patch(API_URL + \"video_status\", {\n videoName: videoName,\n userId: userId,\n duration: duration\n }, {\n headers: Object(_auth_header__WEBPACK_IMPORTED_MODULE_1__[\"default\"])()\n });\n }\n }]);\n\n return UserService;\n}();\n\n/* harmony default export */ __webpack_exports__[\"default\"] = (new UserService());\n\n//# sourceURL=webpack:///./src/services/user-service.js?");
/***/ })
/******/ }); | bundle.js | /******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
/******/
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId]) {
/******/ return installedModules[moduleId].exports;
/******/ }
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ i: moduleId,
/******/ l: false,
/******/ exports: {}
/******/ };
/******/
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/
/******/ // Flag the module as loaded
/******/ module.l = true;
/******/
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/
/******/
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = modules;
/******/
/******/ // expose the module cache
/******/ __webpack_require__.c = installedModules;
/******/
/******/ // define getter function for harmony exports
/******/ __webpack_require__.d = function(exports, name, getter) {
/******/ if(!__webpack_require__.o(exports, name)) {
/******/ Object.defineProperty(exports, name, { enumerable: true, get: getter });
/******/ }
/******/ };
/******/
/******/ // define __esModule on exports
/******/ __webpack_require__.r = function(exports) {
/******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {
/******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
/******/ }
/******/ Object.defineProperty(exports, '__esModule', { value: true });
/******/ };
/******/
/******/ // create a fake namespace object
/******/ // mode & 1: value is a module id, require it
/******/ // mode & 2: merge all properties of value into the ns
/******/ // mode & 4: return value when already ns object
/******/ // mode & 8|1: behave like require
/******/ __webpack_require__.t = function(value, mode) {
/******/ if(mode & 1) value = __webpack_require__(value);
/******/ if(mode & 8) return value;
/******/ if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value;
/******/ var ns = Object.create(null);
/******/ __webpack_require__.r(ns);
/******/ Object.defineProperty(ns, 'default', { enumerable: true, value: value });
/******/ if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key));
/******/ return ns;
/******/ };
/******/
/******/ // getDefaultExport function for compatibility with non-harmony modules
/******/ __webpack_require__.n = function(module) {
/******/ var getter = module && module.__esModule ?
/******/ function getDefault() { return module['default']; } :
/******/ function getModuleExports() { return module; };
/******/ __webpack_require__.d(getter, 'a', getter);
/******/ return getter;
/******/ };
/******/
/******/ // Object.prototype.hasOwnProperty.call
/******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
/******/
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "";
/******/
/******/
/******/ // Load entry module and return exports
/******/ return __webpack_require__(__webpack_require__.s = "./src/index.js");
/******/ })
/************************************************************************/
/******/ ({
/***/ "./node_modules/@babel/runtime/helpers/esm/extends.js":
/*!************************************************************!*\
!*** ./node_modules/@babel/runtime/helpers/esm/extends.js ***!
\************************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"default\", function() { return _extends; });\nfunction _extends() {\n _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\n//# sourceURL=webpack:///./node_modules/@babel/runtime/helpers/esm/extends.js?");
/***/ }),
/***/ "./node_modules/@babel/runtime/helpers/esm/inheritsLoose.js":
/*!******************************************************************!*\
!*** ./node_modules/@babel/runtime/helpers/esm/inheritsLoose.js ***!
\******************************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"default\", function() { return _inheritsLoose; });\nfunction _inheritsLoose(subClass, superClass) {\n subClass.prototype = Object.create(superClass.prototype);\n subClass.prototype.constructor = subClass;\n subClass.__proto__ = superClass;\n}\n\n//# sourceURL=webpack:///./node_modules/@babel/runtime/helpers/esm/inheritsLoose.js?");
/***/ }),
/***/ "./node_modules/@babel/runtime/helpers/esm/objectWithoutPropertiesLoose.js":
/*!*********************************************************************************!*\
!*** ./node_modules/@babel/runtime/helpers/esm/objectWithoutPropertiesLoose.js ***!
\*********************************************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"default\", function() { return _objectWithoutPropertiesLoose; });\nfunction _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}\n\n//# sourceURL=webpack:///./node_modules/@babel/runtime/helpers/esm/objectWithoutPropertiesLoose.js?");
/***/ }),
/***/ "./node_modules/@babel/runtime/helpers/inheritsLoose.js":
/*!**************************************************************!*\
!*** ./node_modules/@babel/runtime/helpers/inheritsLoose.js ***!
\**************************************************************/
/*! no static exports found */
/***/ (function(module, exports) {
eval("function _inheritsLoose(subClass, superClass) {\n subClass.prototype = Object.create(superClass.prototype);\n subClass.prototype.constructor = subClass;\n subClass.__proto__ = superClass;\n}\n\nmodule.exports = _inheritsLoose;\n\n//# sourceURL=webpack:///./node_modules/@babel/runtime/helpers/inheritsLoose.js?");
/***/ }),
/***/ "./node_modules/axios/index.js":
/*!*************************************!*\
!*** ./node_modules/axios/index.js ***!
\*************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
eval("module.exports = __webpack_require__(/*! ./lib/axios */ \"./node_modules/axios/lib/axios.js\");\n\n//# sourceURL=webpack:///./node_modules/axios/index.js?");
/***/ }),
/***/ "./node_modules/axios/lib/adapters/xhr.js":
/*!************************************************!*\
!*** ./node_modules/axios/lib/adapters/xhr.js ***!
\************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
eval("\n\nvar utils = __webpack_require__(/*! ./../utils */ \"./node_modules/axios/lib/utils.js\");\nvar settle = __webpack_require__(/*! ./../core/settle */ \"./node_modules/axios/lib/core/settle.js\");\nvar buildURL = __webpack_require__(/*! ./../helpers/buildURL */ \"./node_modules/axios/lib/helpers/buildURL.js\");\nvar buildFullPath = __webpack_require__(/*! ../core/buildFullPath */ \"./node_modules/axios/lib/core/buildFullPath.js\");\nvar parseHeaders = __webpack_require__(/*! ./../helpers/parseHeaders */ \"./node_modules/axios/lib/helpers/parseHeaders.js\");\nvar isURLSameOrigin = __webpack_require__(/*! ./../helpers/isURLSameOrigin */ \"./node_modules/axios/lib/helpers/isURLSameOrigin.js\");\nvar createError = __webpack_require__(/*! ../core/createError */ \"./node_modules/axios/lib/core/createError.js\");\n\nmodule.exports = function xhrAdapter(config) {\n return new Promise(function dispatchXhrRequest(resolve, reject) {\n var requestData = config.data;\n var requestHeaders = config.headers;\n\n if (utils.isFormData(requestData)) {\n delete requestHeaders['Content-Type']; // Let the browser set it\n }\n\n var request = new XMLHttpRequest();\n\n // HTTP basic authentication\n if (config.auth) {\n var username = config.auth.username || '';\n var password = config.auth.password || '';\n requestHeaders.Authorization = 'Basic ' + btoa(username + ':' + password);\n }\n\n var fullPath = buildFullPath(config.baseURL, config.url);\n request.open(config.method.toUpperCase(), buildURL(fullPath, config.params, config.paramsSerializer), true);\n\n // Set the request timeout in MS\n request.timeout = config.timeout;\n\n // Listen for ready state\n request.onreadystatechange = function handleLoad() {\n if (!request || request.readyState !== 4) {\n return;\n }\n\n // The request errored out and we didn't get a response, this will be\n // handled by onerror instead\n // With one exception: request that using file: protocol, most browsers\n // will return status as 0 even though it's a successful request\n if (request.status === 0 && !(request.responseURL && request.responseURL.indexOf('file:') === 0)) {\n return;\n }\n\n // Prepare the response\n var responseHeaders = 'getAllResponseHeaders' in request ? parseHeaders(request.getAllResponseHeaders()) : null;\n var responseData = !config.responseType || config.responseType === 'text' ? request.responseText : request.response;\n var response = {\n data: responseData,\n status: request.status,\n statusText: request.statusText,\n headers: responseHeaders,\n config: config,\n request: request\n };\n\n settle(resolve, reject, response);\n\n // Clean up request\n request = null;\n };\n\n // Handle browser request cancellation (as opposed to a manual cancellation)\n request.onabort = function handleAbort() {\n if (!request) {\n return;\n }\n\n reject(createError('Request aborted', config, 'ECONNABORTED', request));\n\n // Clean up request\n request = null;\n };\n\n // Handle low level network errors\n request.onerror = function handleError() {\n // Real errors are hidden from us by the browser\n // onerror should only fire if it's a network error\n reject(createError('Network Error', config, null, request));\n\n // Clean up request\n request = null;\n };\n\n // Handle timeout\n request.ontimeout = function handleTimeout() {\n var timeoutErrorMessage = 'timeout of ' + config.timeout + 'ms exceeded';\n if (config.timeoutErrorMessage) {\n timeoutErrorMessage = config.timeoutErrorMessage;\n }\n reject(createError(timeoutErrorMessage, config, 'ECONNABORTED',\n request));\n\n // Clean up request\n request = null;\n };\n\n // Add xsrf header\n // This is only done if running in a standard browser environment.\n // Specifically not if we're in a web worker, or react-native.\n if (utils.isStandardBrowserEnv()) {\n var cookies = __webpack_require__(/*! ./../helpers/cookies */ \"./node_modules/axios/lib/helpers/cookies.js\");\n\n // Add xsrf header\n var xsrfValue = (config.withCredentials || isURLSameOrigin(fullPath)) && config.xsrfCookieName ?\n cookies.read(config.xsrfCookieName) :\n undefined;\n\n if (xsrfValue) {\n requestHeaders[config.xsrfHeaderName] = xsrfValue;\n }\n }\n\n // Add headers to the request\n if ('setRequestHeader' in request) {\n utils.forEach(requestHeaders, function setRequestHeader(val, key) {\n if (typeof requestData === 'undefined' && key.toLowerCase() === 'content-type') {\n // Remove Content-Type if data is undefined\n delete requestHeaders[key];\n } else {\n // Otherwise add header to the request\n request.setRequestHeader(key, val);\n }\n });\n }\n\n // Add withCredentials to request if needed\n if (!utils.isUndefined(config.withCredentials)) {\n request.withCredentials = !!config.withCredentials;\n }\n\n // Add responseType to request if needed\n if (config.responseType) {\n try {\n request.responseType = config.responseType;\n } catch (e) {\n // Expected DOMException thrown by browsers not compatible XMLHttpRequest Level 2.\n // But, this can be suppressed for 'json' type as it can be parsed by default 'transformResponse' function.\n if (config.responseType !== 'json') {\n throw e;\n }\n }\n }\n\n // Handle progress if needed\n if (typeof config.onDownloadProgress === 'function') {\n request.addEventListener('progress', config.onDownloadProgress);\n }\n\n // Not all browsers support upload events\n if (typeof config.onUploadProgress === 'function' && request.upload) {\n request.upload.addEventListener('progress', config.onUploadProgress);\n }\n\n if (config.cancelToken) {\n // Handle cancellation\n config.cancelToken.promise.then(function onCanceled(cancel) {\n if (!request) {\n return;\n }\n\n request.abort();\n reject(cancel);\n // Clean up request\n request = null;\n });\n }\n\n if (requestData === undefined) {\n requestData = null;\n }\n\n // Send the request\n request.send(requestData);\n });\n};\n\n\n//# sourceURL=webpack:///./node_modules/axios/lib/adapters/xhr.js?");
/***/ }),
/***/ "./node_modules/axios/lib/axios.js":
/*!*****************************************!*\
!*** ./node_modules/axios/lib/axios.js ***!
\*****************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
eval("\n\nvar utils = __webpack_require__(/*! ./utils */ \"./node_modules/axios/lib/utils.js\");\nvar bind = __webpack_require__(/*! ./helpers/bind */ \"./node_modules/axios/lib/helpers/bind.js\");\nvar Axios = __webpack_require__(/*! ./core/Axios */ \"./node_modules/axios/lib/core/Axios.js\");\nvar mergeConfig = __webpack_require__(/*! ./core/mergeConfig */ \"./node_modules/axios/lib/core/mergeConfig.js\");\nvar defaults = __webpack_require__(/*! ./defaults */ \"./node_modules/axios/lib/defaults.js\");\n\n/**\n * Create an instance of Axios\n *\n * @param {Object} defaultConfig The default config for the instance\n * @return {Axios} A new instance of Axios\n */\nfunction createInstance(defaultConfig) {\n var context = new Axios(defaultConfig);\n var instance = bind(Axios.prototype.request, context);\n\n // Copy axios.prototype to instance\n utils.extend(instance, Axios.prototype, context);\n\n // Copy context to instance\n utils.extend(instance, context);\n\n return instance;\n}\n\n// Create the default instance to be exported\nvar axios = createInstance(defaults);\n\n// Expose Axios class to allow class inheritance\naxios.Axios = Axios;\n\n// Factory for creating new instances\naxios.create = function create(instanceConfig) {\n return createInstance(mergeConfig(axios.defaults, instanceConfig));\n};\n\n// Expose Cancel & CancelToken\naxios.Cancel = __webpack_require__(/*! ./cancel/Cancel */ \"./node_modules/axios/lib/cancel/Cancel.js\");\naxios.CancelToken = __webpack_require__(/*! ./cancel/CancelToken */ \"./node_modules/axios/lib/cancel/CancelToken.js\");\naxios.isCancel = __webpack_require__(/*! ./cancel/isCancel */ \"./node_modules/axios/lib/cancel/isCancel.js\");\n\n// Expose all/spread\naxios.all = function all(promises) {\n return Promise.all(promises);\n};\naxios.spread = __webpack_require__(/*! ./helpers/spread */ \"./node_modules/axios/lib/helpers/spread.js\");\n\nmodule.exports = axios;\n\n// Allow use of default import syntax in TypeScript\nmodule.exports.default = axios;\n\n\n//# sourceURL=webpack:///./node_modules/axios/lib/axios.js?");
/***/ }),
/***/ "./node_modules/axios/lib/cancel/Cancel.js":
/*!*************************************************!*\
!*** ./node_modules/axios/lib/cancel/Cancel.js ***!
\*************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
eval("\n\n/**\n * A `Cancel` is an object that is thrown when an operation is canceled.\n *\n * @class\n * @param {string=} message The message.\n */\nfunction Cancel(message) {\n this.message = message;\n}\n\nCancel.prototype.toString = function toString() {\n return 'Cancel' + (this.message ? ': ' + this.message : '');\n};\n\nCancel.prototype.__CANCEL__ = true;\n\nmodule.exports = Cancel;\n\n\n//# sourceURL=webpack:///./node_modules/axios/lib/cancel/Cancel.js?");
/***/ }),
/***/ "./node_modules/axios/lib/cancel/CancelToken.js":
/*!******************************************************!*\
!*** ./node_modules/axios/lib/cancel/CancelToken.js ***!
\******************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
eval("\n\nvar Cancel = __webpack_require__(/*! ./Cancel */ \"./node_modules/axios/lib/cancel/Cancel.js\");\n\n/**\n * A `CancelToken` is an object that can be used to request cancellation of an operation.\n *\n * @class\n * @param {Function} executor The executor function.\n */\nfunction CancelToken(executor) {\n if (typeof executor !== 'function') {\n throw new TypeError('executor must be a function.');\n }\n\n var resolvePromise;\n this.promise = new Promise(function promiseExecutor(resolve) {\n resolvePromise = resolve;\n });\n\n var token = this;\n executor(function cancel(message) {\n if (token.reason) {\n // Cancellation has already been requested\n return;\n }\n\n token.reason = new Cancel(message);\n resolvePromise(token.reason);\n });\n}\n\n/**\n * Throws a `Cancel` if cancellation has been requested.\n */\nCancelToken.prototype.throwIfRequested = function throwIfRequested() {\n if (this.reason) {\n throw this.reason;\n }\n};\n\n/**\n * Returns an object that contains a new `CancelToken` and a function that, when called,\n * cancels the `CancelToken`.\n */\nCancelToken.source = function source() {\n var cancel;\n var token = new CancelToken(function executor(c) {\n cancel = c;\n });\n return {\n token: token,\n cancel: cancel\n };\n};\n\nmodule.exports = CancelToken;\n\n\n//# sourceURL=webpack:///./node_modules/axios/lib/cancel/CancelToken.js?");
/***/ }),
/***/ "./node_modules/axios/lib/cancel/isCancel.js":
/*!***************************************************!*\
!*** ./node_modules/axios/lib/cancel/isCancel.js ***!
\***************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
eval("\n\nmodule.exports = function isCancel(value) {\n return !!(value && value.__CANCEL__);\n};\n\n\n//# sourceURL=webpack:///./node_modules/axios/lib/cancel/isCancel.js?");
/***/ }),
/***/ "./node_modules/axios/lib/core/Axios.js":
/*!**********************************************!*\
!*** ./node_modules/axios/lib/core/Axios.js ***!
\**********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
eval("\n\nvar utils = __webpack_require__(/*! ./../utils */ \"./node_modules/axios/lib/utils.js\");\nvar buildURL = __webpack_require__(/*! ../helpers/buildURL */ \"./node_modules/axios/lib/helpers/buildURL.js\");\nvar InterceptorManager = __webpack_require__(/*! ./InterceptorManager */ \"./node_modules/axios/lib/core/InterceptorManager.js\");\nvar dispatchRequest = __webpack_require__(/*! ./dispatchRequest */ \"./node_modules/axios/lib/core/dispatchRequest.js\");\nvar mergeConfig = __webpack_require__(/*! ./mergeConfig */ \"./node_modules/axios/lib/core/mergeConfig.js\");\n\n/**\n * Create a new instance of Axios\n *\n * @param {Object} instanceConfig The default config for the instance\n */\nfunction Axios(instanceConfig) {\n this.defaults = instanceConfig;\n this.interceptors = {\n request: new InterceptorManager(),\n response: new InterceptorManager()\n };\n}\n\n/**\n * Dispatch a request\n *\n * @param {Object} config The config specific for this request (merged with this.defaults)\n */\nAxios.prototype.request = function request(config) {\n /*eslint no-param-reassign:0*/\n // Allow for axios('example/url'[, config]) a la fetch API\n if (typeof config === 'string') {\n config = arguments[1] || {};\n config.url = arguments[0];\n } else {\n config = config || {};\n }\n\n config = mergeConfig(this.defaults, config);\n\n // Set config.method\n if (config.method) {\n config.method = config.method.toLowerCase();\n } else if (this.defaults.method) {\n config.method = this.defaults.method.toLowerCase();\n } else {\n config.method = 'get';\n }\n\n // Hook up interceptors middleware\n var chain = [dispatchRequest, undefined];\n var promise = Promise.resolve(config);\n\n this.interceptors.request.forEach(function unshiftRequestInterceptors(interceptor) {\n chain.unshift(interceptor.fulfilled, interceptor.rejected);\n });\n\n this.interceptors.response.forEach(function pushResponseInterceptors(interceptor) {\n chain.push(interceptor.fulfilled, interceptor.rejected);\n });\n\n while (chain.length) {\n promise = promise.then(chain.shift(), chain.shift());\n }\n\n return promise;\n};\n\nAxios.prototype.getUri = function getUri(config) {\n config = mergeConfig(this.defaults, config);\n return buildURL(config.url, config.params, config.paramsSerializer).replace(/^\\?/, '');\n};\n\n// Provide aliases for supported request methods\nutils.forEach(['delete', 'get', 'head', 'options'], function forEachMethodNoData(method) {\n /*eslint func-names:0*/\n Axios.prototype[method] = function(url, config) {\n return this.request(utils.merge(config || {}, {\n method: method,\n url: url\n }));\n };\n});\n\nutils.forEach(['post', 'put', 'patch'], function forEachMethodWithData(method) {\n /*eslint func-names:0*/\n Axios.prototype[method] = function(url, data, config) {\n return this.request(utils.merge(config || {}, {\n method: method,\n url: url,\n data: data\n }));\n };\n});\n\nmodule.exports = Axios;\n\n\n//# sourceURL=webpack:///./node_modules/axios/lib/core/Axios.js?");
/***/ }),
/***/ "./node_modules/axios/lib/core/InterceptorManager.js":
/*!***********************************************************!*\
!*** ./node_modules/axios/lib/core/InterceptorManager.js ***!
\***********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
eval("\n\nvar utils = __webpack_require__(/*! ./../utils */ \"./node_modules/axios/lib/utils.js\");\n\nfunction InterceptorManager() {\n this.handlers = [];\n}\n\n/**\n * Add a new interceptor to the stack\n *\n * @param {Function} fulfilled The function to handle `then` for a `Promise`\n * @param {Function} rejected The function to handle `reject` for a `Promise`\n *\n * @return {Number} An ID used to remove interceptor later\n */\nInterceptorManager.prototype.use = function use(fulfilled, rejected) {\n this.handlers.push({\n fulfilled: fulfilled,\n rejected: rejected\n });\n return this.handlers.length - 1;\n};\n\n/**\n * Remove an interceptor from the stack\n *\n * @param {Number} id The ID that was returned by `use`\n */\nInterceptorManager.prototype.eject = function eject(id) {\n if (this.handlers[id]) {\n this.handlers[id] = null;\n }\n};\n\n/**\n * Iterate over all the registered interceptors\n *\n * This method is particularly useful for skipping over any\n * interceptors that may have become `null` calling `eject`.\n *\n * @param {Function} fn The function to call for each interceptor\n */\nInterceptorManager.prototype.forEach = function forEach(fn) {\n utils.forEach(this.handlers, function forEachHandler(h) {\n if (h !== null) {\n fn(h);\n }\n });\n};\n\nmodule.exports = InterceptorManager;\n\n\n//# sourceURL=webpack:///./node_modules/axios/lib/core/InterceptorManager.js?");
/***/ }),
/***/ "./node_modules/axios/lib/core/buildFullPath.js":
/*!******************************************************!*\
!*** ./node_modules/axios/lib/core/buildFullPath.js ***!
\******************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
eval("\n\nvar isAbsoluteURL = __webpack_require__(/*! ../helpers/isAbsoluteURL */ \"./node_modules/axios/lib/helpers/isAbsoluteURL.js\");\nvar combineURLs = __webpack_require__(/*! ../helpers/combineURLs */ \"./node_modules/axios/lib/helpers/combineURLs.js\");\n\n/**\n * Creates a new URL by combining the baseURL with the requestedURL,\n * only when the requestedURL is not already an absolute URL.\n * If the requestURL is absolute, this function returns the requestedURL untouched.\n *\n * @param {string} baseURL The base URL\n * @param {string} requestedURL Absolute or relative URL to combine\n * @returns {string} The combined full path\n */\nmodule.exports = function buildFullPath(baseURL, requestedURL) {\n if (baseURL && !isAbsoluteURL(requestedURL)) {\n return combineURLs(baseURL, requestedURL);\n }\n return requestedURL;\n};\n\n\n//# sourceURL=webpack:///./node_modules/axios/lib/core/buildFullPath.js?");
/***/ }),
/***/ "./node_modules/axios/lib/core/createError.js":
/*!****************************************************!*\
!*** ./node_modules/axios/lib/core/createError.js ***!
\****************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
eval("\n\nvar enhanceError = __webpack_require__(/*! ./enhanceError */ \"./node_modules/axios/lib/core/enhanceError.js\");\n\n/**\n * Create an Error with the specified message, config, error code, request and response.\n *\n * @param {string} message The error message.\n * @param {Object} config The config.\n * @param {string} [code] The error code (for example, 'ECONNABORTED').\n * @param {Object} [request] The request.\n * @param {Object} [response] The response.\n * @returns {Error} The created error.\n */\nmodule.exports = function createError(message, config, code, request, response) {\n var error = new Error(message);\n return enhanceError(error, config, code, request, response);\n};\n\n\n//# sourceURL=webpack:///./node_modules/axios/lib/core/createError.js?");
/***/ }),
/***/ "./node_modules/axios/lib/core/dispatchRequest.js":
/*!********************************************************!*\
!*** ./node_modules/axios/lib/core/dispatchRequest.js ***!
\********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
eval("\n\nvar utils = __webpack_require__(/*! ./../utils */ \"./node_modules/axios/lib/utils.js\");\nvar transformData = __webpack_require__(/*! ./transformData */ \"./node_modules/axios/lib/core/transformData.js\");\nvar isCancel = __webpack_require__(/*! ../cancel/isCancel */ \"./node_modules/axios/lib/cancel/isCancel.js\");\nvar defaults = __webpack_require__(/*! ../defaults */ \"./node_modules/axios/lib/defaults.js\");\n\n/**\n * Throws a `Cancel` if cancellation has been requested.\n */\nfunction throwIfCancellationRequested(config) {\n if (config.cancelToken) {\n config.cancelToken.throwIfRequested();\n }\n}\n\n/**\n * Dispatch a request to the server using the configured adapter.\n *\n * @param {object} config The config that is to be used for the request\n * @returns {Promise} The Promise to be fulfilled\n */\nmodule.exports = function dispatchRequest(config) {\n throwIfCancellationRequested(config);\n\n // Ensure headers exist\n config.headers = config.headers || {};\n\n // Transform request data\n config.data = transformData(\n config.data,\n config.headers,\n config.transformRequest\n );\n\n // Flatten headers\n config.headers = utils.merge(\n config.headers.common || {},\n config.headers[config.method] || {},\n config.headers\n );\n\n utils.forEach(\n ['delete', 'get', 'head', 'post', 'put', 'patch', 'common'],\n function cleanHeaderConfig(method) {\n delete config.headers[method];\n }\n );\n\n var adapter = config.adapter || defaults.adapter;\n\n return adapter(config).then(function onAdapterResolution(response) {\n throwIfCancellationRequested(config);\n\n // Transform response data\n response.data = transformData(\n response.data,\n response.headers,\n config.transformResponse\n );\n\n return response;\n }, function onAdapterRejection(reason) {\n if (!isCancel(reason)) {\n throwIfCancellationRequested(config);\n\n // Transform response data\n if (reason && reason.response) {\n reason.response.data = transformData(\n reason.response.data,\n reason.response.headers,\n config.transformResponse\n );\n }\n }\n\n return Promise.reject(reason);\n });\n};\n\n\n//# sourceURL=webpack:///./node_modules/axios/lib/core/dispatchRequest.js?");
/***/ }),
/***/ "./node_modules/axios/lib/core/enhanceError.js":
/*!*****************************************************!*\
!*** ./node_modules/axios/lib/core/enhanceError.js ***!
\*****************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
eval("\n\n/**\n * Update an Error with the specified config, error code, and response.\n *\n * @param {Error} error The error to update.\n * @param {Object} config The config.\n * @param {string} [code] The error code (for example, 'ECONNABORTED').\n * @param {Object} [request] The request.\n * @param {Object} [response] The response.\n * @returns {Error} The error.\n */\nmodule.exports = function enhanceError(error, config, code, request, response) {\n error.config = config;\n if (code) {\n error.code = code;\n }\n\n error.request = request;\n error.response = response;\n error.isAxiosError = true;\n\n error.toJSON = function() {\n return {\n // Standard\n message: this.message,\n name: this.name,\n // Microsoft\n description: this.description,\n number: this.number,\n // Mozilla\n fileName: this.fileName,\n lineNumber: this.lineNumber,\n columnNumber: this.columnNumber,\n stack: this.stack,\n // Axios\n config: this.config,\n code: this.code\n };\n };\n return error;\n};\n\n\n//# sourceURL=webpack:///./node_modules/axios/lib/core/enhanceError.js?");
/***/ }),
/***/ "./node_modules/axios/lib/core/mergeConfig.js":
/*!****************************************************!*\
!*** ./node_modules/axios/lib/core/mergeConfig.js ***!
\****************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
eval("\n\nvar utils = __webpack_require__(/*! ../utils */ \"./node_modules/axios/lib/utils.js\");\n\n/**\n * Config-specific merge-function which creates a new config-object\n * by merging two configuration objects together.\n *\n * @param {Object} config1\n * @param {Object} config2\n * @returns {Object} New object resulting from merging config2 to config1\n */\nmodule.exports = function mergeConfig(config1, config2) {\n // eslint-disable-next-line no-param-reassign\n config2 = config2 || {};\n var config = {};\n\n var valueFromConfig2Keys = ['url', 'method', 'params', 'data'];\n var mergeDeepPropertiesKeys = ['headers', 'auth', 'proxy'];\n var defaultToConfig2Keys = [\n 'baseURL', 'url', 'transformRequest', 'transformResponse', 'paramsSerializer',\n 'timeout', 'withCredentials', 'adapter', 'responseType', 'xsrfCookieName',\n 'xsrfHeaderName', 'onUploadProgress', 'onDownloadProgress',\n 'maxContentLength', 'validateStatus', 'maxRedirects', 'httpAgent',\n 'httpsAgent', 'cancelToken', 'socketPath'\n ];\n\n utils.forEach(valueFromConfig2Keys, function valueFromConfig2(prop) {\n if (typeof config2[prop] !== 'undefined') {\n config[prop] = config2[prop];\n }\n });\n\n utils.forEach(mergeDeepPropertiesKeys, function mergeDeepProperties(prop) {\n if (utils.isObject(config2[prop])) {\n config[prop] = utils.deepMerge(config1[prop], config2[prop]);\n } else if (typeof config2[prop] !== 'undefined') {\n config[prop] = config2[prop];\n } else if (utils.isObject(config1[prop])) {\n config[prop] = utils.deepMerge(config1[prop]);\n } else if (typeof config1[prop] !== 'undefined') {\n config[prop] = config1[prop];\n }\n });\n\n utils.forEach(defaultToConfig2Keys, function defaultToConfig2(prop) {\n if (typeof config2[prop] !== 'undefined') {\n config[prop] = config2[prop];\n } else if (typeof config1[prop] !== 'undefined') {\n config[prop] = config1[prop];\n }\n });\n\n var axiosKeys = valueFromConfig2Keys\n .concat(mergeDeepPropertiesKeys)\n .concat(defaultToConfig2Keys);\n\n var otherKeys = Object\n .keys(config2)\n .filter(function filterAxiosKeys(key) {\n return axiosKeys.indexOf(key) === -1;\n });\n\n utils.forEach(otherKeys, function otherKeysDefaultToConfig2(prop) {\n if (typeof config2[prop] !== 'undefined') {\n config[prop] = config2[prop];\n } else if (typeof config1[prop] !== 'undefined') {\n config[prop] = config1[prop];\n }\n });\n\n return config;\n};\n\n\n//# sourceURL=webpack:///./node_modules/axios/lib/core/mergeConfig.js?");
/***/ }),
/***/ "./node_modules/axios/lib/core/settle.js":
/*!***********************************************!*\
!*** ./node_modules/axios/lib/core/settle.js ***!
\***********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
eval("\n\nvar createError = __webpack_require__(/*! ./createError */ \"./node_modules/axios/lib/core/createError.js\");\n\n/**\n * Resolve or reject a Promise based on response status.\n *\n * @param {Function} resolve A function that resolves the promise.\n * @param {Function} reject A function that rejects the promise.\n * @param {object} response The response.\n */\nmodule.exports = function settle(resolve, reject, response) {\n var validateStatus = response.config.validateStatus;\n if (!validateStatus || validateStatus(response.status)) {\n resolve(response);\n } else {\n reject(createError(\n 'Request failed with status code ' + response.status,\n response.config,\n null,\n response.request,\n response\n ));\n }\n};\n\n\n//# sourceURL=webpack:///./node_modules/axios/lib/core/settle.js?");
/***/ }),
/***/ "./node_modules/axios/lib/core/transformData.js":
/*!******************************************************!*\
!*** ./node_modules/axios/lib/core/transformData.js ***!
\******************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
eval("\n\nvar utils = __webpack_require__(/*! ./../utils */ \"./node_modules/axios/lib/utils.js\");\n\n/**\n * Transform the data for a request or a response\n *\n * @param {Object|String} data The data to be transformed\n * @param {Array} headers The headers for the request or response\n * @param {Array|Function} fns A single function or Array of functions\n * @returns {*} The resulting transformed data\n */\nmodule.exports = function transformData(data, headers, fns) {\n /*eslint no-param-reassign:0*/\n utils.forEach(fns, function transform(fn) {\n data = fn(data, headers);\n });\n\n return data;\n};\n\n\n//# sourceURL=webpack:///./node_modules/axios/lib/core/transformData.js?");
/***/ }),
/***/ "./node_modules/axios/lib/defaults.js":
/*!********************************************!*\
!*** ./node_modules/axios/lib/defaults.js ***!
\********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
eval("/* WEBPACK VAR INJECTION */(function(process) {\n\nvar utils = __webpack_require__(/*! ./utils */ \"./node_modules/axios/lib/utils.js\");\nvar normalizeHeaderName = __webpack_require__(/*! ./helpers/normalizeHeaderName */ \"./node_modules/axios/lib/helpers/normalizeHeaderName.js\");\n\nvar DEFAULT_CONTENT_TYPE = {\n 'Content-Type': 'application/x-www-form-urlencoded'\n};\n\nfunction setContentTypeIfUnset(headers, value) {\n if (!utils.isUndefined(headers) && utils.isUndefined(headers['Content-Type'])) {\n headers['Content-Type'] = value;\n }\n}\n\nfunction getDefaultAdapter() {\n var adapter;\n if (typeof XMLHttpRequest !== 'undefined') {\n // For browsers use XHR adapter\n adapter = __webpack_require__(/*! ./adapters/xhr */ \"./node_modules/axios/lib/adapters/xhr.js\");\n } else if (typeof process !== 'undefined' && Object.prototype.toString.call(process) === '[object process]') {\n // For node use HTTP adapter\n adapter = __webpack_require__(/*! ./adapters/http */ \"./node_modules/axios/lib/adapters/xhr.js\");\n }\n return adapter;\n}\n\nvar defaults = {\n adapter: getDefaultAdapter(),\n\n transformRequest: [function transformRequest(data, headers) {\n normalizeHeaderName(headers, 'Accept');\n normalizeHeaderName(headers, 'Content-Type');\n if (utils.isFormData(data) ||\n utils.isArrayBuffer(data) ||\n utils.isBuffer(data) ||\n utils.isStream(data) ||\n utils.isFile(data) ||\n utils.isBlob(data)\n ) {\n return data;\n }\n if (utils.isArrayBufferView(data)) {\n return data.buffer;\n }\n if (utils.isURLSearchParams(data)) {\n setContentTypeIfUnset(headers, 'application/x-www-form-urlencoded;charset=utf-8');\n return data.toString();\n }\n if (utils.isObject(data)) {\n setContentTypeIfUnset(headers, 'application/json;charset=utf-8');\n return JSON.stringify(data);\n }\n return data;\n }],\n\n transformResponse: [function transformResponse(data) {\n /*eslint no-param-reassign:0*/\n if (typeof data === 'string') {\n try {\n data = JSON.parse(data);\n } catch (e) { /* Ignore */ }\n }\n return data;\n }],\n\n /**\n * A timeout in milliseconds to abort a request. If set to 0 (default) a\n * timeout is not created.\n */\n timeout: 0,\n\n xsrfCookieName: 'XSRF-TOKEN',\n xsrfHeaderName: 'X-XSRF-TOKEN',\n\n maxContentLength: -1,\n\n validateStatus: function validateStatus(status) {\n return status >= 200 && status < 300;\n }\n};\n\ndefaults.headers = {\n common: {\n 'Accept': 'application/json, text/plain, */*'\n }\n};\n\nutils.forEach(['delete', 'get', 'head'], function forEachMethodNoData(method) {\n defaults.headers[method] = {};\n});\n\nutils.forEach(['post', 'put', 'patch'], function forEachMethodWithData(method) {\n defaults.headers[method] = utils.merge(DEFAULT_CONTENT_TYPE);\n});\n\nmodule.exports = defaults;\n\n/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./../../process/browser.js */ \"./node_modules/process/browser.js\")))\n\n//# sourceURL=webpack:///./node_modules/axios/lib/defaults.js?");
/***/ }),
/***/ "./node_modules/axios/lib/helpers/bind.js":
/*!************************************************!*\
!*** ./node_modules/axios/lib/helpers/bind.js ***!
\************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
eval("\n\nmodule.exports = function bind(fn, thisArg) {\n return function wrap() {\n var args = new Array(arguments.length);\n for (var i = 0; i < args.length; i++) {\n args[i] = arguments[i];\n }\n return fn.apply(thisArg, args);\n };\n};\n\n\n//# sourceURL=webpack:///./node_modules/axios/lib/helpers/bind.js?");
/***/ }),
/***/ "./node_modules/axios/lib/helpers/buildURL.js":
/*!****************************************************!*\
!*** ./node_modules/axios/lib/helpers/buildURL.js ***!
\****************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
eval("\n\nvar utils = __webpack_require__(/*! ./../utils */ \"./node_modules/axios/lib/utils.js\");\n\nfunction encode(val) {\n return encodeURIComponent(val).\n replace(/%40/gi, '@').\n replace(/%3A/gi, ':').\n replace(/%24/g, '$').\n replace(/%2C/gi, ',').\n replace(/%20/g, '+').\n replace(/%5B/gi, '[').\n replace(/%5D/gi, ']');\n}\n\n/**\n * Build a URL by appending params to the end\n *\n * @param {string} url The base of the url (e.g., http://www.google.com)\n * @param {object} [params] The params to be appended\n * @returns {string} The formatted url\n */\nmodule.exports = function buildURL(url, params, paramsSerializer) {\n /*eslint no-param-reassign:0*/\n if (!params) {\n return url;\n }\n\n var serializedParams;\n if (paramsSerializer) {\n serializedParams = paramsSerializer(params);\n } else if (utils.isURLSearchParams(params)) {\n serializedParams = params.toString();\n } else {\n var parts = [];\n\n utils.forEach(params, function serialize(val, key) {\n if (val === null || typeof val === 'undefined') {\n return;\n }\n\n if (utils.isArray(val)) {\n key = key + '[]';\n } else {\n val = [val];\n }\n\n utils.forEach(val, function parseValue(v) {\n if (utils.isDate(v)) {\n v = v.toISOString();\n } else if (utils.isObject(v)) {\n v = JSON.stringify(v);\n }\n parts.push(encode(key) + '=' + encode(v));\n });\n });\n\n serializedParams = parts.join('&');\n }\n\n if (serializedParams) {\n var hashmarkIndex = url.indexOf('#');\n if (hashmarkIndex !== -1) {\n url = url.slice(0, hashmarkIndex);\n }\n\n url += (url.indexOf('?') === -1 ? '?' : '&') + serializedParams;\n }\n\n return url;\n};\n\n\n//# sourceURL=webpack:///./node_modules/axios/lib/helpers/buildURL.js?");
/***/ }),
/***/ "./node_modules/axios/lib/helpers/combineURLs.js":
/*!*******************************************************!*\
!*** ./node_modules/axios/lib/helpers/combineURLs.js ***!
\*******************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
eval("\n\n/**\n * Creates a new URL by combining the specified URLs\n *\n * @param {string} baseURL The base URL\n * @param {string} relativeURL The relative URL\n * @returns {string} The combined URL\n */\nmodule.exports = function combineURLs(baseURL, relativeURL) {\n return relativeURL\n ? baseURL.replace(/\\/+$/, '') + '/' + relativeURL.replace(/^\\/+/, '')\n : baseURL;\n};\n\n\n//# sourceURL=webpack:///./node_modules/axios/lib/helpers/combineURLs.js?");
/***/ }),
/***/ "./node_modules/axios/lib/helpers/cookies.js":
/*!***************************************************!*\
!*** ./node_modules/axios/lib/helpers/cookies.js ***!
\***************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
eval("\n\nvar utils = __webpack_require__(/*! ./../utils */ \"./node_modules/axios/lib/utils.js\");\n\nmodule.exports = (\n utils.isStandardBrowserEnv() ?\n\n // Standard browser envs support document.cookie\n (function standardBrowserEnv() {\n return {\n write: function write(name, value, expires, path, domain, secure) {\n var cookie = [];\n cookie.push(name + '=' + encodeURIComponent(value));\n\n if (utils.isNumber(expires)) {\n cookie.push('expires=' + new Date(expires).toGMTString());\n }\n\n if (utils.isString(path)) {\n cookie.push('path=' + path);\n }\n\n if (utils.isString(domain)) {\n cookie.push('domain=' + domain);\n }\n\n if (secure === true) {\n cookie.push('secure');\n }\n\n document.cookie = cookie.join('; ');\n },\n\n read: function read(name) {\n var match = document.cookie.match(new RegExp('(^|;\\\\s*)(' + name + ')=([^;]*)'));\n return (match ? decodeURIComponent(match[3]) : null);\n },\n\n remove: function remove(name) {\n this.write(name, '', Date.now() - 86400000);\n }\n };\n })() :\n\n // Non standard browser env (web workers, react-native) lack needed support.\n (function nonStandardBrowserEnv() {\n return {\n write: function write() {},\n read: function read() { return null; },\n remove: function remove() {}\n };\n })()\n);\n\n\n//# sourceURL=webpack:///./node_modules/axios/lib/helpers/cookies.js?");
/***/ }),
/***/ "./node_modules/axios/lib/helpers/isAbsoluteURL.js":
/*!*********************************************************!*\
!*** ./node_modules/axios/lib/helpers/isAbsoluteURL.js ***!
\*********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
eval("\n\n/**\n * Determines whether the specified URL is absolute\n *\n * @param {string} url The URL to test\n * @returns {boolean} True if the specified URL is absolute, otherwise false\n */\nmodule.exports = function isAbsoluteURL(url) {\n // A URL is considered absolute if it begins with \"<scheme>://\" or \"//\" (protocol-relative URL).\n // RFC 3986 defines scheme name as a sequence of characters beginning with a letter and followed\n // by any combination of letters, digits, plus, period, or hyphen.\n return /^([a-z][a-z\\d\\+\\-\\.]*:)?\\/\\//i.test(url);\n};\n\n\n//# sourceURL=webpack:///./node_modules/axios/lib/helpers/isAbsoluteURL.js?");
/***/ }),
/***/ "./node_modules/axios/lib/helpers/isURLSameOrigin.js":
/*!***********************************************************!*\
!*** ./node_modules/axios/lib/helpers/isURLSameOrigin.js ***!
\***********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
eval("\n\nvar utils = __webpack_require__(/*! ./../utils */ \"./node_modules/axios/lib/utils.js\");\n\nmodule.exports = (\n utils.isStandardBrowserEnv() ?\n\n // Standard browser envs have full support of the APIs needed to test\n // whether the request URL is of the same origin as current location.\n (function standardBrowserEnv() {\n var msie = /(msie|trident)/i.test(navigator.userAgent);\n var urlParsingNode = document.createElement('a');\n var originURL;\n\n /**\n * Parse a URL to discover it's components\n *\n * @param {String} url The URL to be parsed\n * @returns {Object}\n */\n function resolveURL(url) {\n var href = url;\n\n if (msie) {\n // IE needs attribute set twice to normalize properties\n urlParsingNode.setAttribute('href', href);\n href = urlParsingNode.href;\n }\n\n urlParsingNode.setAttribute('href', href);\n\n // urlParsingNode provides the UrlUtils interface - http://url.spec.whatwg.org/#urlutils\n return {\n href: urlParsingNode.href,\n protocol: urlParsingNode.protocol ? urlParsingNode.protocol.replace(/:$/, '') : '',\n host: urlParsingNode.host,\n search: urlParsingNode.search ? urlParsingNode.search.replace(/^\\?/, '') : '',\n hash: urlParsingNode.hash ? urlParsingNode.hash.replace(/^#/, '') : '',\n hostname: urlParsingNode.hostname,\n port: urlParsingNode.port,\n pathname: (urlParsingNode.pathname.charAt(0) === '/') ?\n urlParsingNode.pathname :\n '/' + urlParsingNode.pathname\n };\n }\n\n originURL = resolveURL(window.location.href);\n\n /**\n * Determine if a URL shares the same origin as the current location\n *\n * @param {String} requestURL The URL to test\n * @returns {boolean} True if URL shares the same origin, otherwise false\n */\n return function isURLSameOrigin(requestURL) {\n var parsed = (utils.isString(requestURL)) ? resolveURL(requestURL) : requestURL;\n return (parsed.protocol === originURL.protocol &&\n parsed.host === originURL.host);\n };\n })() :\n\n // Non standard browser envs (web workers, react-native) lack needed support.\n (function nonStandardBrowserEnv() {\n return function isURLSameOrigin() {\n return true;\n };\n })()\n);\n\n\n//# sourceURL=webpack:///./node_modules/axios/lib/helpers/isURLSameOrigin.js?");
/***/ }),
/***/ "./node_modules/axios/lib/helpers/normalizeHeaderName.js":
/*!***************************************************************!*\
!*** ./node_modules/axios/lib/helpers/normalizeHeaderName.js ***!
\***************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
eval("\n\nvar utils = __webpack_require__(/*! ../utils */ \"./node_modules/axios/lib/utils.js\");\n\nmodule.exports = function normalizeHeaderName(headers, normalizedName) {\n utils.forEach(headers, function processHeader(value, name) {\n if (name !== normalizedName && name.toUpperCase() === normalizedName.toUpperCase()) {\n headers[normalizedName] = value;\n delete headers[name];\n }\n });\n};\n\n\n//# sourceURL=webpack:///./node_modules/axios/lib/helpers/normalizeHeaderName.js?");
/***/ }),
/***/ "./node_modules/axios/lib/helpers/parseHeaders.js":
/*!********************************************************!*\
!*** ./node_modules/axios/lib/helpers/parseHeaders.js ***!
\********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
eval("\n\nvar utils = __webpack_require__(/*! ./../utils */ \"./node_modules/axios/lib/utils.js\");\n\n// Headers whose duplicates are ignored by node\n// c.f. https://nodejs.org/api/http.html#http_message_headers\nvar ignoreDuplicateOf = [\n 'age', 'authorization', 'content-length', 'content-type', 'etag',\n 'expires', 'from', 'host', 'if-modified-since', 'if-unmodified-since',\n 'last-modified', 'location', 'max-forwards', 'proxy-authorization',\n 'referer', 'retry-after', 'user-agent'\n];\n\n/**\n * Parse headers into an object\n *\n * ```\n * Date: Wed, 27 Aug 2014 08:58:49 GMT\n * Content-Type: application/json\n * Connection: keep-alive\n * Transfer-Encoding: chunked\n * ```\n *\n * @param {String} headers Headers needing to be parsed\n * @returns {Object} Headers parsed into an object\n */\nmodule.exports = function parseHeaders(headers) {\n var parsed = {};\n var key;\n var val;\n var i;\n\n if (!headers) { return parsed; }\n\n utils.forEach(headers.split('\\n'), function parser(line) {\n i = line.indexOf(':');\n key = utils.trim(line.substr(0, i)).toLowerCase();\n val = utils.trim(line.substr(i + 1));\n\n if (key) {\n if (parsed[key] && ignoreDuplicateOf.indexOf(key) >= 0) {\n return;\n }\n if (key === 'set-cookie') {\n parsed[key] = (parsed[key] ? parsed[key] : []).concat([val]);\n } else {\n parsed[key] = parsed[key] ? parsed[key] + ', ' + val : val;\n }\n }\n });\n\n return parsed;\n};\n\n\n//# sourceURL=webpack:///./node_modules/axios/lib/helpers/parseHeaders.js?");
/***/ }),
/***/ "./node_modules/axios/lib/helpers/spread.js":
/*!**************************************************!*\
!*** ./node_modules/axios/lib/helpers/spread.js ***!
\**************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
eval("\n\n/**\n * Syntactic sugar for invoking a function and expanding an array for arguments.\n *\n * Common use case would be to use `Function.prototype.apply`.\n *\n * ```js\n * function f(x, y, z) {}\n * var args = [1, 2, 3];\n * f.apply(null, args);\n * ```\n *\n * With `spread` this example can be re-written.\n *\n * ```js\n * spread(function(x, y, z) {})([1, 2, 3]);\n * ```\n *\n * @param {Function} callback\n * @returns {Function}\n */\nmodule.exports = function spread(callback) {\n return function wrap(arr) {\n return callback.apply(null, arr);\n };\n};\n\n\n//# sourceURL=webpack:///./node_modules/axios/lib/helpers/spread.js?");
/***/ }),
/***/ "./node_modules/axios/lib/utils.js":
/*!*****************************************!*\
!*** ./node_modules/axios/lib/utils.js ***!
\*****************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
eval("\n\nvar bind = __webpack_require__(/*! ./helpers/bind */ \"./node_modules/axios/lib/helpers/bind.js\");\n\n/*global toString:true*/\n\n// utils is a library of generic helper functions non-specific to axios\n\nvar toString = Object.prototype.toString;\n\n/**\n * Determine if a value is an Array\n *\n * @param {Object} val The value to test\n * @returns {boolean} True if value is an Array, otherwise false\n */\nfunction isArray(val) {\n return toString.call(val) === '[object Array]';\n}\n\n/**\n * Determine if a value is undefined\n *\n * @param {Object} val The value to test\n * @returns {boolean} True if the value is undefined, otherwise false\n */\nfunction isUndefined(val) {\n return typeof val === 'undefined';\n}\n\n/**\n * Determine if a value is a Buffer\n *\n * @param {Object} val The value to test\n * @returns {boolean} True if value is a Buffer, otherwise false\n */\nfunction isBuffer(val) {\n return val !== null && !isUndefined(val) && val.constructor !== null && !isUndefined(val.constructor)\n && typeof val.constructor.isBuffer === 'function' && val.constructor.isBuffer(val);\n}\n\n/**\n * Determine if a value is an ArrayBuffer\n *\n * @param {Object} val The value to test\n * @returns {boolean} True if value is an ArrayBuffer, otherwise false\n */\nfunction isArrayBuffer(val) {\n return toString.call(val) === '[object ArrayBuffer]';\n}\n\n/**\n * Determine if a value is a FormData\n *\n * @param {Object} val The value to test\n * @returns {boolean} True if value is an FormData, otherwise false\n */\nfunction isFormData(val) {\n return (typeof FormData !== 'undefined') && (val instanceof FormData);\n}\n\n/**\n * Determine if a value is a view on an ArrayBuffer\n *\n * @param {Object} val The value to test\n * @returns {boolean} True if value is a view on an ArrayBuffer, otherwise false\n */\nfunction isArrayBufferView(val) {\n var result;\n if ((typeof ArrayBuffer !== 'undefined') && (ArrayBuffer.isView)) {\n result = ArrayBuffer.isView(val);\n } else {\n result = (val) && (val.buffer) && (val.buffer instanceof ArrayBuffer);\n }\n return result;\n}\n\n/**\n * Determine if a value is a String\n *\n * @param {Object} val The value to test\n * @returns {boolean} True if value is a String, otherwise false\n */\nfunction isString(val) {\n return typeof val === 'string';\n}\n\n/**\n * Determine if a value is a Number\n *\n * @param {Object} val The value to test\n * @returns {boolean} True if value is a Number, otherwise false\n */\nfunction isNumber(val) {\n return typeof val === 'number';\n}\n\n/**\n * Determine if a value is an Object\n *\n * @param {Object} val The value to test\n * @returns {boolean} True if value is an Object, otherwise false\n */\nfunction isObject(val) {\n return val !== null && typeof val === 'object';\n}\n\n/**\n * Determine if a value is a Date\n *\n * @param {Object} val The value to test\n * @returns {boolean} True if value is a Date, otherwise false\n */\nfunction isDate(val) {\n return toString.call(val) === '[object Date]';\n}\n\n/**\n * Determine if a value is a File\n *\n * @param {Object} val The value to test\n * @returns {boolean} True if value is a File, otherwise false\n */\nfunction isFile(val) {\n return toString.call(val) === '[object File]';\n}\n\n/**\n * Determine if a value is a Blob\n *\n * @param {Object} val The value to test\n * @returns {boolean} True if value is a Blob, otherwise false\n */\nfunction isBlob(val) {\n return toString.call(val) === '[object Blob]';\n}\n\n/**\n * Determine if a value is a Function\n *\n * @param {Object} val The value to test\n * @returns {boolean} True if value is a Function, otherwise false\n */\nfunction isFunction(val) {\n return toString.call(val) === '[object Function]';\n}\n\n/**\n * Determine if a value is a Stream\n *\n * @param {Object} val The value to test\n * @returns {boolean} True if value is a Stream, otherwise false\n */\nfunction isStream(val) {\n return isObject(val) && isFunction(val.pipe);\n}\n\n/**\n * Determine if a value is a URLSearchParams object\n *\n * @param {Object} val The value to test\n * @returns {boolean} True if value is a URLSearchParams object, otherwise false\n */\nfunction isURLSearchParams(val) {\n return typeof URLSearchParams !== 'undefined' && val instanceof URLSearchParams;\n}\n\n/**\n * Trim excess whitespace off the beginning and end of a string\n *\n * @param {String} str The String to trim\n * @returns {String} The String freed of excess whitespace\n */\nfunction trim(str) {\n return str.replace(/^\\s*/, '').replace(/\\s*$/, '');\n}\n\n/**\n * Determine if we're running in a standard browser environment\n *\n * This allows axios to run in a web worker, and react-native.\n * Both environments support XMLHttpRequest, but not fully standard globals.\n *\n * web workers:\n * typeof window -> undefined\n * typeof document -> undefined\n *\n * react-native:\n * navigator.product -> 'ReactNative'\n * nativescript\n * navigator.product -> 'NativeScript' or 'NS'\n */\nfunction isStandardBrowserEnv() {\n if (typeof navigator !== 'undefined' && (navigator.product === 'ReactNative' ||\n navigator.product === 'NativeScript' ||\n navigator.product === 'NS')) {\n return false;\n }\n return (\n typeof window !== 'undefined' &&\n typeof document !== 'undefined'\n );\n}\n\n/**\n * Iterate over an Array or an Object invoking a function for each item.\n *\n * If `obj` is an Array callback will be called passing\n * the value, index, and complete array for each item.\n *\n * If 'obj' is an Object callback will be called passing\n * the value, key, and complete object for each property.\n *\n * @param {Object|Array} obj The object to iterate\n * @param {Function} fn The callback to invoke for each item\n */\nfunction forEach(obj, fn) {\n // Don't bother if no value provided\n if (obj === null || typeof obj === 'undefined') {\n return;\n }\n\n // Force an array if not already something iterable\n if (typeof obj !== 'object') {\n /*eslint no-param-reassign:0*/\n obj = [obj];\n }\n\n if (isArray(obj)) {\n // Iterate over array values\n for (var i = 0, l = obj.length; i < l; i++) {\n fn.call(null, obj[i], i, obj);\n }\n } else {\n // Iterate over object keys\n for (var key in obj) {\n if (Object.prototype.hasOwnProperty.call(obj, key)) {\n fn.call(null, obj[key], key, obj);\n }\n }\n }\n}\n\n/**\n * Accepts varargs expecting each argument to be an object, then\n * immutably merges the properties of each object and returns result.\n *\n * When multiple objects contain the same key the later object in\n * the arguments list will take precedence.\n *\n * Example:\n *\n * ```js\n * var result = merge({foo: 123}, {foo: 456});\n * console.log(result.foo); // outputs 456\n * ```\n *\n * @param {Object} obj1 Object to merge\n * @returns {Object} Result of all merge properties\n */\nfunction merge(/* obj1, obj2, obj3, ... */) {\n var result = {};\n function assignValue(val, key) {\n if (typeof result[key] === 'object' && typeof val === 'object') {\n result[key] = merge(result[key], val);\n } else {\n result[key] = val;\n }\n }\n\n for (var i = 0, l = arguments.length; i < l; i++) {\n forEach(arguments[i], assignValue);\n }\n return result;\n}\n\n/**\n * Function equal to merge with the difference being that no reference\n * to original objects is kept.\n *\n * @see merge\n * @param {Object} obj1 Object to merge\n * @returns {Object} Result of all merge properties\n */\nfunction deepMerge(/* obj1, obj2, obj3, ... */) {\n var result = {};\n function assignValue(val, key) {\n if (typeof result[key] === 'object' && typeof val === 'object') {\n result[key] = deepMerge(result[key], val);\n } else if (typeof val === 'object') {\n result[key] = deepMerge({}, val);\n } else {\n result[key] = val;\n }\n }\n\n for (var i = 0, l = arguments.length; i < l; i++) {\n forEach(arguments[i], assignValue);\n }\n return result;\n}\n\n/**\n * Extends object a by mutably adding to it the properties of object b.\n *\n * @param {Object} a The object to be extended\n * @param {Object} b The object to copy properties from\n * @param {Object} thisArg The object to bind function to\n * @return {Object} The resulting value of object a\n */\nfunction extend(a, b, thisArg) {\n forEach(b, function assignValue(val, key) {\n if (thisArg && typeof val === 'function') {\n a[key] = bind(val, thisArg);\n } else {\n a[key] = val;\n }\n });\n return a;\n}\n\nmodule.exports = {\n isArray: isArray,\n isArrayBuffer: isArrayBuffer,\n isBuffer: isBuffer,\n isFormData: isFormData,\n isArrayBufferView: isArrayBufferView,\n isString: isString,\n isNumber: isNumber,\n isObject: isObject,\n isUndefined: isUndefined,\n isDate: isDate,\n isFile: isFile,\n isBlob: isBlob,\n isFunction: isFunction,\n isStream: isStream,\n isURLSearchParams: isURLSearchParams,\n isStandardBrowserEnv: isStandardBrowserEnv,\n forEach: forEach,\n merge: merge,\n deepMerge: deepMerge,\n extend: extend,\n trim: trim\n};\n\n\n//# sourceURL=webpack:///./node_modules/axios/lib/utils.js?");
/***/ }),
/***/ "./node_modules/bootstrap/dist/css/bootstrap.min.css":
/*!***********************************************************!*\
!*** ./node_modules/bootstrap/dist/css/bootstrap.min.css ***!
\***********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
eval("var api = __webpack_require__(/*! ../../../style-loader/dist/runtime/injectStylesIntoStyleTag.js */ \"./node_modules/style-loader/dist/runtime/injectStylesIntoStyleTag.js\");\n var content = __webpack_require__(/*! !../../../css-loader/dist/cjs.js!./bootstrap.min.css */ \"./node_modules/css-loader/dist/cjs.js!./node_modules/bootstrap/dist/css/bootstrap.min.css\");\n\n content = content.__esModule ? content.default : content;\n\n if (typeof content === 'string') {\n content = [[module.i, content, '']];\n }\n\nvar options = {};\n\noptions.insert = \"head\";\noptions.singleton = false;\n\nvar update = api(content, options);\n\n\n\nmodule.exports = content.locals || {};\n\n//# sourceURL=webpack:///./node_modules/bootstrap/dist/css/bootstrap.min.css?");
/***/ }),
/***/ "./node_modules/css-loader/dist/cjs.js!./node_modules/bootstrap/dist/css/bootstrap.min.css":
/*!*************************************************************************************************!*\
!*** ./node_modules/css-loader/dist/cjs.js!./node_modules/bootstrap/dist/css/bootstrap.min.css ***!
\*************************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
eval("// Imports\nvar ___CSS_LOADER_API_IMPORT___ = __webpack_require__(/*! ../../../css-loader/dist/runtime/api.js */ \"./node_modules/css-loader/dist/runtime/api.js\");\nexports = ___CSS_LOADER_API_IMPORT___(false);\n// Module\nexports.push([module.i, \"/*!\\n * Bootstrap v4.4.1 (https://getbootstrap.com/)\\n * Copyright 2011-2019 The Bootstrap Authors\\n * Copyright 2011-2019 Twitter, Inc.\\n * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)\\n */:root{--blue:#007bff;--indigo:#6610f2;--purple:#6f42c1;--pink:#e83e8c;--red:#dc3545;--orange:#fd7e14;--yellow:#ffc107;--green:#28a745;--teal:#20c997;--cyan:#17a2b8;--white:#fff;--gray:#6c757d;--gray-dark:#343a40;--primary:#007bff;--secondary:#6c757d;--success:#28a745;--info:#17a2b8;--warning:#ffc107;--danger:#dc3545;--light:#f8f9fa;--dark:#343a40;--breakpoint-xs:0;--breakpoint-sm:576px;--breakpoint-md:768px;--breakpoint-lg:992px;--breakpoint-xl:1200px;--font-family-sans-serif:-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-family-monospace:SFMono-Regular,Menlo,Monaco,Consolas,\\\"Liberation Mono\\\",\\\"Courier New\\\",monospace}*,::after,::before{box-sizing:border-box}html{font-family:sans-serif;line-height:1.15;-webkit-text-size-adjust:100%;-webkit-tap-highlight-color:transparent}article,aside,figcaption,figure,footer,header,hgroup,main,nav,section{display:block}body{margin: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;color:#212529;text-align:left;background-color:#fff}[tabindex=\\\"-1\\\"]:focus:not(:focus-visible){outline:0!important}hr{box-sizing:content-box;height:0;overflow:visible}h1,h2,h3,h4,h5,h6{margin-top:0;margin-bottom:.5rem}p{margin-top:0;margin-bottom:1rem}abbr[data-original-title],abbr[title]{text-decoration:underline;-webkit-text-decoration:underline dotted;text-decoration:underline dotted;cursor:help;border-bottom:0;-webkit-text-decoration-skip-ink:none;text-decoration-skip-ink:none}address{margin-bottom:1rem;font-style:normal;line-height:inherit}dl,ol,ul{margin-top:0;margin-bottom:1rem}ol ol,ol ul,ul ol,ul ul{margin-bottom:0}dt{font-weight:700}dd{margin-bottom:.5rem;margin-left:0}blockquote{margin:0 0 1rem}b,strong{font-weight:bolder}small{font-size:80%}sub,sup{position:relative;font-size:75%;line-height:0;vertical-align:baseline}sub{bottom:-.25em}sup{top:-.5em}a{color:#007bff;text-decoration:none;background-color:transparent}a:hover{color:#0056b3;text-decoration:underline}a:not([href]){color:inherit;text-decoration:none}a:not([href]):hover{color:inherit;text-decoration:none}code,kbd,pre,samp{font-family:SFMono-Regular,Menlo,Monaco,Consolas,\\\"Liberation Mono\\\",\\\"Courier New\\\",monospace;font-size:1em}pre{margin-top:0;margin-bottom:1rem;overflow:auto}figure{margin:0 0 1rem}img{vertical-align:middle;border-style:none}svg{overflow:hidden;vertical-align:middle}table{border-collapse:collapse}caption{padding-top:.75rem;padding-bottom:.75rem;color:#6c757d;text-align:left;caption-side:bottom}th{text-align:inherit}label{display:inline-block;margin-bottom:.5rem}button{border-radius:0}button:focus{outline:1px dotted;outline:5px auto -webkit-focus-ring-color}button,input,optgroup,select,textarea{margin:0;font-family:inherit;font-size:inherit;line-height:inherit}button,input{overflow:visible}button,select{text-transform:none}select{word-wrap:normal}[type=button],[type=reset],[type=submit],button{-webkit-appearance:button}[type=button]:not(:disabled),[type=reset]:not(:disabled),[type=submit]:not(:disabled),button:not(:disabled){cursor:pointer}[type=button]::-moz-focus-inner,[type=reset]::-moz-focus-inner,[type=submit]::-moz-focus-inner,button::-moz-focus-inner{padding:0;border-style:none}input[type=checkbox],input[type=radio]{box-sizing:border-box;padding:0}input[type=date],input[type=datetime-local],input[type=month],input[type=time]{-webkit-appearance:listbox}textarea{overflow:auto;resize:vertical}fieldset{min-width:0;padding:0;margin:0;border:0}legend{display:block;width:100%;max-width:100%;padding:0;margin-bottom:.5rem;font-size:1.5rem;line-height:inherit;color:inherit;white-space:normal}progress{vertical-align:baseline}[type=number]::-webkit-inner-spin-button,[type=number]::-webkit-outer-spin-button{height:auto}[type=search]{outline-offset:-2px;-webkit-appearance:none}[type=search]::-webkit-search-decoration{-webkit-appearance:none}::-webkit-file-upload-button{font:inherit;-webkit-appearance:button}output{display:inline-block}summary{display:list-item;cursor:pointer}template{display:none}[hidden]{display:none!important}.h1,.h2,.h3,.h4,.h5,.h6,h1,h2,h3,h4,h5,h6{margin-bottom:.5rem;font-weight:500;line-height:1.2}.h1,h1{font-size:2.5rem}.h2,h2{font-size:2rem}.h3,h3{font-size:1.75rem}.h4,h4{font-size:1.5rem}.h5,h5{font-size:1.25rem}.h6,h6{font-size:1rem}.lead{font-size:1.25rem;font-weight:300}.display-1{font-size:6rem;font-weight:300;line-height:1.2}.display-2{font-size:5.5rem;font-weight:300;line-height:1.2}.display-3{font-size:4.5rem;font-weight:300;line-height:1.2}.display-4{font-size:3.5rem;font-weight:300;line-height:1.2}hr{margin-top:1rem;margin-bottom:1rem;border:0;border-top:1px solid rgba(0,0,0,.1)}.small,small{font-size:80%;font-weight:400}.mark,mark{padding:.2em;background-color:#fcf8e3}.list-unstyled{padding-left:0;list-style:none}.list-inline{padding-left:0;list-style:none}.list-inline-item{display:inline-block}.list-inline-item:not(:last-child){margin-right:.5rem}.initialism{font-size:90%;text-transform:uppercase}.blockquote{margin-bottom:1rem;font-size:1.25rem}.blockquote-footer{display:block;font-size:80%;color:#6c757d}.blockquote-footer::before{content:\\\"\\\\2014\\\\00A0\\\"}.img-fluid{max-width:100%;height:auto}.img-thumbnail{padding:.25rem;background-color:#fff;border:1px solid #dee2e6;border-radius:.25rem;max-width:100%;height:auto}.figure{display:inline-block}.figure-img{margin-bottom:.5rem;line-height:1}.figure-caption{font-size:90%;color:#6c757d}code{font-size:87.5%;color:#e83e8c;word-wrap:break-word}a>code{color:inherit}kbd{padding:.2rem .4rem;font-size:87.5%;color:#fff;background-color:#212529;border-radius:.2rem}kbd kbd{padding:0;font-size:100%;font-weight:700}pre{display:block;font-size:87.5%;color:#212529}pre code{font-size:inherit;color:inherit;word-break:normal}.pre-scrollable{max-height:340px;overflow-y:scroll}.container{width:100%;padding-right:15px;padding-left:15px;margin-right:auto;margin-left:auto}@media (min-width:576px){.container{max-width:540px}}@media (min-width:768px){.container{max-width:720px}}@media (min-width:992px){.container{max-width:960px}}@media (min-width:1200px){.container{max-width:1140px}}.container-fluid,.container-lg,.container-md,.container-sm,.container-xl{width:100%;padding-right:15px;padding-left:15px;margin-right:auto;margin-left:auto}@media (min-width:576px){.container,.container-sm{max-width:540px}}@media (min-width:768px){.container,.container-md,.container-sm{max-width:720px}}@media (min-width:992px){.container,.container-lg,.container-md,.container-sm{max-width:960px}}@media (min-width:1200px){.container,.container-lg,.container-md,.container-sm,.container-xl{max-width:1140px}}.row{display:-ms-flexbox;display:flex;-ms-flex-wrap:wrap;flex-wrap:wrap;margin-right:-15px;margin-left:-15px}.no-gutters{margin-right:0;margin-left:0}.no-gutters>.col,.no-gutters>[class*=col-]{padding-right:0;padding-left:0}.col,.col-1,.col-10,.col-11,.col-12,.col-2,.col-3,.col-4,.col-5,.col-6,.col-7,.col-8,.col-9,.col-auto,.col-lg,.col-lg-1,.col-lg-10,.col-lg-11,.col-lg-12,.col-lg-2,.col-lg-3,.col-lg-4,.col-lg-5,.col-lg-6,.col-lg-7,.col-lg-8,.col-lg-9,.col-lg-auto,.col-md,.col-md-1,.col-md-10,.col-md-11,.col-md-12,.col-md-2,.col-md-3,.col-md-4,.col-md-5,.col-md-6,.col-md-7,.col-md-8,.col-md-9,.col-md-auto,.col-sm,.col-sm-1,.col-sm-10,.col-sm-11,.col-sm-12,.col-sm-2,.col-sm-3,.col-sm-4,.col-sm-5,.col-sm-6,.col-sm-7,.col-sm-8,.col-sm-9,.col-sm-auto,.col-xl,.col-xl-1,.col-xl-10,.col-xl-11,.col-xl-12,.col-xl-2,.col-xl-3,.col-xl-4,.col-xl-5,.col-xl-6,.col-xl-7,.col-xl-8,.col-xl-9,.col-xl-auto{position:relative;width:100%;padding-right:15px;padding-left:15px}.col{-ms-flex-preferred-size:0;flex-basis:0;-ms-flex-positive:1;flex-grow:1;max-width:100%}.row-cols-1>*{-ms-flex:0 0 100%;flex:0 0 100%;max-width:100%}.row-cols-2>*{-ms-flex:0 0 50%;flex:0 0 50%;max-width:50%}.row-cols-3>*{-ms-flex:0 0 33.333333%;flex:0 0 33.333333%;max-width:33.333333%}.row-cols-4>*{-ms-flex:0 0 25%;flex:0 0 25%;max-width:25%}.row-cols-5>*{-ms-flex:0 0 20%;flex:0 0 20%;max-width:20%}.row-cols-6>*{-ms-flex:0 0 16.666667%;flex:0 0 16.666667%;max-width:16.666667%}.col-auto{-ms-flex:0 0 auto;flex:0 0 auto;width:auto;max-width:100%}.col-1{-ms-flex:0 0 8.333333%;flex:0 0 8.333333%;max-width:8.333333%}.col-2{-ms-flex:0 0 16.666667%;flex:0 0 16.666667%;max-width:16.666667%}.col-3{-ms-flex:0 0 25%;flex:0 0 25%;max-width:25%}.col-4{-ms-flex:0 0 33.333333%;flex:0 0 33.333333%;max-width:33.333333%}.col-5{-ms-flex:0 0 41.666667%;flex:0 0 41.666667%;max-width:41.666667%}.col-6{-ms-flex:0 0 50%;flex:0 0 50%;max-width:50%}.col-7{-ms-flex:0 0 58.333333%;flex:0 0 58.333333%;max-width:58.333333%}.col-8{-ms-flex:0 0 66.666667%;flex:0 0 66.666667%;max-width:66.666667%}.col-9{-ms-flex:0 0 75%;flex:0 0 75%;max-width:75%}.col-10{-ms-flex:0 0 83.333333%;flex:0 0 83.333333%;max-width:83.333333%}.col-11{-ms-flex:0 0 91.666667%;flex:0 0 91.666667%;max-width:91.666667%}.col-12{-ms-flex:0 0 100%;flex:0 0 100%;max-width:100%}.order-first{-ms-flex-order:-1;order:-1}.order-last{-ms-flex-order:13;order:13}.order-0{-ms-flex-order:0;order:0}.order-1{-ms-flex-order:1;order:1}.order-2{-ms-flex-order:2;order:2}.order-3{-ms-flex-order:3;order:3}.order-4{-ms-flex-order:4;order:4}.order-5{-ms-flex-order:5;order:5}.order-6{-ms-flex-order:6;order:6}.order-7{-ms-flex-order:7;order:7}.order-8{-ms-flex-order:8;order:8}.order-9{-ms-flex-order:9;order:9}.order-10{-ms-flex-order:10;order:10}.order-11{-ms-flex-order:11;order:11}.order-12{-ms-flex-order:12;order:12}.offset-1{margin-left:8.333333%}.offset-2{margin-left:16.666667%}.offset-3{margin-left:25%}.offset-4{margin-left:33.333333%}.offset-5{margin-left:41.666667%}.offset-6{margin-left:50%}.offset-7{margin-left:58.333333%}.offset-8{margin-left:66.666667%}.offset-9{margin-left:75%}.offset-10{margin-left:83.333333%}.offset-11{margin-left:91.666667%}@media (min-width:576px){.col-sm{-ms-flex-preferred-size:0;flex-basis:0;-ms-flex-positive:1;flex-grow:1;max-width:100%}.row-cols-sm-1>*{-ms-flex:0 0 100%;flex:0 0 100%;max-width:100%}.row-cols-sm-2>*{-ms-flex:0 0 50%;flex:0 0 50%;max-width:50%}.row-cols-sm-3>*{-ms-flex:0 0 33.333333%;flex:0 0 33.333333%;max-width:33.333333%}.row-cols-sm-4>*{-ms-flex:0 0 25%;flex:0 0 25%;max-width:25%}.row-cols-sm-5>*{-ms-flex:0 0 20%;flex:0 0 20%;max-width:20%}.row-cols-sm-6>*{-ms-flex:0 0 16.666667%;flex:0 0 16.666667%;max-width:16.666667%}.col-sm-auto{-ms-flex:0 0 auto;flex:0 0 auto;width:auto;max-width:100%}.col-sm-1{-ms-flex:0 0 8.333333%;flex:0 0 8.333333%;max-width:8.333333%}.col-sm-2{-ms-flex:0 0 16.666667%;flex:0 0 16.666667%;max-width:16.666667%}.col-sm-3{-ms-flex:0 0 25%;flex:0 0 25%;max-width:25%}.col-sm-4{-ms-flex:0 0 33.333333%;flex:0 0 33.333333%;max-width:33.333333%}.col-sm-5{-ms-flex:0 0 41.666667%;flex:0 0 41.666667%;max-width:41.666667%}.col-sm-6{-ms-flex:0 0 50%;flex:0 0 50%;max-width:50%}.col-sm-7{-ms-flex:0 0 58.333333%;flex:0 0 58.333333%;max-width:58.333333%}.col-sm-8{-ms-flex:0 0 66.666667%;flex:0 0 66.666667%;max-width:66.666667%}.col-sm-9{-ms-flex:0 0 75%;flex:0 0 75%;max-width:75%}.col-sm-10{-ms-flex:0 0 83.333333%;flex:0 0 83.333333%;max-width:83.333333%}.col-sm-11{-ms-flex:0 0 91.666667%;flex:0 0 91.666667%;max-width:91.666667%}.col-sm-12{-ms-flex:0 0 100%;flex:0 0 100%;max-width:100%}.order-sm-first{-ms-flex-order:-1;order:-1}.order-sm-last{-ms-flex-order:13;order:13}.order-sm-0{-ms-flex-order:0;order:0}.order-sm-1{-ms-flex-order:1;order:1}.order-sm-2{-ms-flex-order:2;order:2}.order-sm-3{-ms-flex-order:3;order:3}.order-sm-4{-ms-flex-order:4;order:4}.order-sm-5{-ms-flex-order:5;order:5}.order-sm-6{-ms-flex-order:6;order:6}.order-sm-7{-ms-flex-order:7;order:7}.order-sm-8{-ms-flex-order:8;order:8}.order-sm-9{-ms-flex-order:9;order:9}.order-sm-10{-ms-flex-order:10;order:10}.order-sm-11{-ms-flex-order:11;order:11}.order-sm-12{-ms-flex-order:12;order:12}.offset-sm-0{margin-left:0}.offset-sm-1{margin-left:8.333333%}.offset-sm-2{margin-left:16.666667%}.offset-sm-3{margin-left:25%}.offset-sm-4{margin-left:33.333333%}.offset-sm-5{margin-left:41.666667%}.offset-sm-6{margin-left:50%}.offset-sm-7{margin-left:58.333333%}.offset-sm-8{margin-left:66.666667%}.offset-sm-9{margin-left:75%}.offset-sm-10{margin-left:83.333333%}.offset-sm-11{margin-left:91.666667%}}@media (min-width:768px){.col-md{-ms-flex-preferred-size:0;flex-basis:0;-ms-flex-positive:1;flex-grow:1;max-width:100%}.row-cols-md-1>*{-ms-flex:0 0 100%;flex:0 0 100%;max-width:100%}.row-cols-md-2>*{-ms-flex:0 0 50%;flex:0 0 50%;max-width:50%}.row-cols-md-3>*{-ms-flex:0 0 33.333333%;flex:0 0 33.333333%;max-width:33.333333%}.row-cols-md-4>*{-ms-flex:0 0 25%;flex:0 0 25%;max-width:25%}.row-cols-md-5>*{-ms-flex:0 0 20%;flex:0 0 20%;max-width:20%}.row-cols-md-6>*{-ms-flex:0 0 16.666667%;flex:0 0 16.666667%;max-width:16.666667%}.col-md-auto{-ms-flex:0 0 auto;flex:0 0 auto;width:auto;max-width:100%}.col-md-1{-ms-flex:0 0 8.333333%;flex:0 0 8.333333%;max-width:8.333333%}.col-md-2{-ms-flex:0 0 16.666667%;flex:0 0 16.666667%;max-width:16.666667%}.col-md-3{-ms-flex:0 0 25%;flex:0 0 25%;max-width:25%}.col-md-4{-ms-flex:0 0 33.333333%;flex:0 0 33.333333%;max-width:33.333333%}.col-md-5{-ms-flex:0 0 41.666667%;flex:0 0 41.666667%;max-width:41.666667%}.col-md-6{-ms-flex:0 0 50%;flex:0 0 50%;max-width:50%}.col-md-7{-ms-flex:0 0 58.333333%;flex:0 0 58.333333%;max-width:58.333333%}.col-md-8{-ms-flex:0 0 66.666667%;flex:0 0 66.666667%;max-width:66.666667%}.col-md-9{-ms-flex:0 0 75%;flex:0 0 75%;max-width:75%}.col-md-10{-ms-flex:0 0 83.333333%;flex:0 0 83.333333%;max-width:83.333333%}.col-md-11{-ms-flex:0 0 91.666667%;flex:0 0 91.666667%;max-width:91.666667%}.col-md-12{-ms-flex:0 0 100%;flex:0 0 100%;max-width:100%}.order-md-first{-ms-flex-order:-1;order:-1}.order-md-last{-ms-flex-order:13;order:13}.order-md-0{-ms-flex-order:0;order:0}.order-md-1{-ms-flex-order:1;order:1}.order-md-2{-ms-flex-order:2;order:2}.order-md-3{-ms-flex-order:3;order:3}.order-md-4{-ms-flex-order:4;order:4}.order-md-5{-ms-flex-order:5;order:5}.order-md-6{-ms-flex-order:6;order:6}.order-md-7{-ms-flex-order:7;order:7}.order-md-8{-ms-flex-order:8;order:8}.order-md-9{-ms-flex-order:9;order:9}.order-md-10{-ms-flex-order:10;order:10}.order-md-11{-ms-flex-order:11;order:11}.order-md-12{-ms-flex-order:12;order:12}.offset-md-0{margin-left:0}.offset-md-1{margin-left:8.333333%}.offset-md-2{margin-left:16.666667%}.offset-md-3{margin-left:25%}.offset-md-4{margin-left:33.333333%}.offset-md-5{margin-left:41.666667%}.offset-md-6{margin-left:50%}.offset-md-7{margin-left:58.333333%}.offset-md-8{margin-left:66.666667%}.offset-md-9{margin-left:75%}.offset-md-10{margin-left:83.333333%}.offset-md-11{margin-left:91.666667%}}@media (min-width:992px){.col-lg{-ms-flex-preferred-size:0;flex-basis:0;-ms-flex-positive:1;flex-grow:1;max-width:100%}.row-cols-lg-1>*{-ms-flex:0 0 100%;flex:0 0 100%;max-width:100%}.row-cols-lg-2>*{-ms-flex:0 0 50%;flex:0 0 50%;max-width:50%}.row-cols-lg-3>*{-ms-flex:0 0 33.333333%;flex:0 0 33.333333%;max-width:33.333333%}.row-cols-lg-4>*{-ms-flex:0 0 25%;flex:0 0 25%;max-width:25%}.row-cols-lg-5>*{-ms-flex:0 0 20%;flex:0 0 20%;max-width:20%}.row-cols-lg-6>*{-ms-flex:0 0 16.666667%;flex:0 0 16.666667%;max-width:16.666667%}.col-lg-auto{-ms-flex:0 0 auto;flex:0 0 auto;width:auto;max-width:100%}.col-lg-1{-ms-flex:0 0 8.333333%;flex:0 0 8.333333%;max-width:8.333333%}.col-lg-2{-ms-flex:0 0 16.666667%;flex:0 0 16.666667%;max-width:16.666667%}.col-lg-3{-ms-flex:0 0 25%;flex:0 0 25%;max-width:25%}.col-lg-4{-ms-flex:0 0 33.333333%;flex:0 0 33.333333%;max-width:33.333333%}.col-lg-5{-ms-flex:0 0 41.666667%;flex:0 0 41.666667%;max-width:41.666667%}.col-lg-6{-ms-flex:0 0 50%;flex:0 0 50%;max-width:50%}.col-lg-7{-ms-flex:0 0 58.333333%;flex:0 0 58.333333%;max-width:58.333333%}.col-lg-8{-ms-flex:0 0 66.666667%;flex:0 0 66.666667%;max-width:66.666667%}.col-lg-9{-ms-flex:0 0 75%;flex:0 0 75%;max-width:75%}.col-lg-10{-ms-flex:0 0 83.333333%;flex:0 0 83.333333%;max-width:83.333333%}.col-lg-11{-ms-flex:0 0 91.666667%;flex:0 0 91.666667%;max-width:91.666667%}.col-lg-12{-ms-flex:0 0 100%;flex:0 0 100%;max-width:100%}.order-lg-first{-ms-flex-order:-1;order:-1}.order-lg-last{-ms-flex-order:13;order:13}.order-lg-0{-ms-flex-order:0;order:0}.order-lg-1{-ms-flex-order:1;order:1}.order-lg-2{-ms-flex-order:2;order:2}.order-lg-3{-ms-flex-order:3;order:3}.order-lg-4{-ms-flex-order:4;order:4}.order-lg-5{-ms-flex-order:5;order:5}.order-lg-6{-ms-flex-order:6;order:6}.order-lg-7{-ms-flex-order:7;order:7}.order-lg-8{-ms-flex-order:8;order:8}.order-lg-9{-ms-flex-order:9;order:9}.order-lg-10{-ms-flex-order:10;order:10}.order-lg-11{-ms-flex-order:11;order:11}.order-lg-12{-ms-flex-order:12;order:12}.offset-lg-0{margin-left:0}.offset-lg-1{margin-left:8.333333%}.offset-lg-2{margin-left:16.666667%}.offset-lg-3{margin-left:25%}.offset-lg-4{margin-left:33.333333%}.offset-lg-5{margin-left:41.666667%}.offset-lg-6{margin-left:50%}.offset-lg-7{margin-left:58.333333%}.offset-lg-8{margin-left:66.666667%}.offset-lg-9{margin-left:75%}.offset-lg-10{margin-left:83.333333%}.offset-lg-11{margin-left:91.666667%}}@media (min-width:1200px){.col-xl{-ms-flex-preferred-size:0;flex-basis:0;-ms-flex-positive:1;flex-grow:1;max-width:100%}.row-cols-xl-1>*{-ms-flex:0 0 100%;flex:0 0 100%;max-width:100%}.row-cols-xl-2>*{-ms-flex:0 0 50%;flex:0 0 50%;max-width:50%}.row-cols-xl-3>*{-ms-flex:0 0 33.333333%;flex:0 0 33.333333%;max-width:33.333333%}.row-cols-xl-4>*{-ms-flex:0 0 25%;flex:0 0 25%;max-width:25%}.row-cols-xl-5>*{-ms-flex:0 0 20%;flex:0 0 20%;max-width:20%}.row-cols-xl-6>*{-ms-flex:0 0 16.666667%;flex:0 0 16.666667%;max-width:16.666667%}.col-xl-auto{-ms-flex:0 0 auto;flex:0 0 auto;width:auto;max-width:100%}.col-xl-1{-ms-flex:0 0 8.333333%;flex:0 0 8.333333%;max-width:8.333333%}.col-xl-2{-ms-flex:0 0 16.666667%;flex:0 0 16.666667%;max-width:16.666667%}.col-xl-3{-ms-flex:0 0 25%;flex:0 0 25%;max-width:25%}.col-xl-4{-ms-flex:0 0 33.333333%;flex:0 0 33.333333%;max-width:33.333333%}.col-xl-5{-ms-flex:0 0 41.666667%;flex:0 0 41.666667%;max-width:41.666667%}.col-xl-6{-ms-flex:0 0 50%;flex:0 0 50%;max-width:50%}.col-xl-7{-ms-flex:0 0 58.333333%;flex:0 0 58.333333%;max-width:58.333333%}.col-xl-8{-ms-flex:0 0 66.666667%;flex:0 0 66.666667%;max-width:66.666667%}.col-xl-9{-ms-flex:0 0 75%;flex:0 0 75%;max-width:75%}.col-xl-10{-ms-flex:0 0 83.333333%;flex:0 0 83.333333%;max-width:83.333333%}.col-xl-11{-ms-flex:0 0 91.666667%;flex:0 0 91.666667%;max-width:91.666667%}.col-xl-12{-ms-flex:0 0 100%;flex:0 0 100%;max-width:100%}.order-xl-first{-ms-flex-order:-1;order:-1}.order-xl-last{-ms-flex-order:13;order:13}.order-xl-0{-ms-flex-order:0;order:0}.order-xl-1{-ms-flex-order:1;order:1}.order-xl-2{-ms-flex-order:2;order:2}.order-xl-3{-ms-flex-order:3;order:3}.order-xl-4{-ms-flex-order:4;order:4}.order-xl-5{-ms-flex-order:5;order:5}.order-xl-6{-ms-flex-order:6;order:6}.order-xl-7{-ms-flex-order:7;order:7}.order-xl-8{-ms-flex-order:8;order:8}.order-xl-9{-ms-flex-order:9;order:9}.order-xl-10{-ms-flex-order:10;order:10}.order-xl-11{-ms-flex-order:11;order:11}.order-xl-12{-ms-flex-order:12;order:12}.offset-xl-0{margin-left:0}.offset-xl-1{margin-left:8.333333%}.offset-xl-2{margin-left:16.666667%}.offset-xl-3{margin-left:25%}.offset-xl-4{margin-left:33.333333%}.offset-xl-5{margin-left:41.666667%}.offset-xl-6{margin-left:50%}.offset-xl-7{margin-left:58.333333%}.offset-xl-8{margin-left:66.666667%}.offset-xl-9{margin-left:75%}.offset-xl-10{margin-left:83.333333%}.offset-xl-11{margin-left:91.666667%}}.table{width:100%;margin-bottom:1rem;color:#212529}.table td,.table th{padding:.75rem;vertical-align:top;border-top:1px solid #dee2e6}.table thead th{vertical-align:bottom;border-bottom:2px solid #dee2e6}.table tbody+tbody{border-top:2px solid #dee2e6}.table-sm td,.table-sm th{padding:.3rem}.table-bordered{border:1px solid #dee2e6}.table-bordered td,.table-bordered th{border:1px solid #dee2e6}.table-bordered thead td,.table-bordered thead th{border-bottom-width:2px}.table-borderless tbody+tbody,.table-borderless td,.table-borderless th,.table-borderless thead th{border:0}.table-striped tbody tr:nth-of-type(odd){background-color:rgba(0,0,0,.05)}.table-hover tbody tr:hover{color:#212529;background-color:rgba(0,0,0,.075)}.table-primary,.table-primary>td,.table-primary>th{background-color:#b8daff}.table-primary tbody+tbody,.table-primary td,.table-primary th,.table-primary thead th{border-color:#7abaff}.table-hover .table-primary:hover{background-color:#9fcdff}.table-hover .table-primary:hover>td,.table-hover .table-primary:hover>th{background-color:#9fcdff}.table-secondary,.table-secondary>td,.table-secondary>th{background-color:#d6d8db}.table-secondary tbody+tbody,.table-secondary td,.table-secondary th,.table-secondary thead th{border-color:#b3b7bb}.table-hover .table-secondary:hover{background-color:#c8cbcf}.table-hover .table-secondary:hover>td,.table-hover .table-secondary:hover>th{background-color:#c8cbcf}.table-success,.table-success>td,.table-success>th{background-color:#c3e6cb}.table-success tbody+tbody,.table-success td,.table-success th,.table-success thead th{border-color:#8fd19e}.table-hover .table-success:hover{background-color:#b1dfbb}.table-hover .table-success:hover>td,.table-hover .table-success:hover>th{background-color:#b1dfbb}.table-info,.table-info>td,.table-info>th{background-color:#bee5eb}.table-info tbody+tbody,.table-info td,.table-info th,.table-info thead th{border-color:#86cfda}.table-hover .table-info:hover{background-color:#abdde5}.table-hover .table-info:hover>td,.table-hover .table-info:hover>th{background-color:#abdde5}.table-warning,.table-warning>td,.table-warning>th{background-color:#ffeeba}.table-warning tbody+tbody,.table-warning td,.table-warning th,.table-warning thead th{border-color:#ffdf7e}.table-hover .table-warning:hover{background-color:#ffe8a1}.table-hover .table-warning:hover>td,.table-hover .table-warning:hover>th{background-color:#ffe8a1}.table-danger,.table-danger>td,.table-danger>th{background-color:#f5c6cb}.table-danger tbody+tbody,.table-danger td,.table-danger th,.table-danger thead th{border-color:#ed969e}.table-hover .table-danger:hover{background-color:#f1b0b7}.table-hover .table-danger:hover>td,.table-hover .table-danger:hover>th{background-color:#f1b0b7}.table-light,.table-light>td,.table-light>th{background-color:#fdfdfe}.table-light tbody+tbody,.table-light td,.table-light th,.table-light thead th{border-color:#fbfcfc}.table-hover .table-light:hover{background-color:#ececf6}.table-hover .table-light:hover>td,.table-hover .table-light:hover>th{background-color:#ececf6}.table-dark,.table-dark>td,.table-dark>th{background-color:#c6c8ca}.table-dark tbody+tbody,.table-dark td,.table-dark th,.table-dark thead th{border-color:#95999c}.table-hover .table-dark:hover{background-color:#b9bbbe}.table-hover .table-dark:hover>td,.table-hover .table-dark:hover>th{background-color:#b9bbbe}.table-active,.table-active>td,.table-active>th{background-color:rgba(0,0,0,.075)}.table-hover .table-active:hover{background-color:rgba(0,0,0,.075)}.table-hover .table-active:hover>td,.table-hover .table-active:hover>th{background-color:rgba(0,0,0,.075)}.table .thead-dark th{color:#fff;background-color:#343a40;border-color:#454d55}.table .thead-light th{color:#495057;background-color:#e9ecef;border-color:#dee2e6}.table-dark{color:#fff;background-color:#343a40}.table-dark td,.table-dark th,.table-dark thead th{border-color:#454d55}.table-dark.table-bordered{border:0}.table-dark.table-striped tbody tr:nth-of-type(odd){background-color:rgba(255,255,255,.05)}.table-dark.table-hover tbody tr:hover{color:#fff;background-color:rgba(255,255,255,.075)}@media (max-width:575.98px){.table-responsive-sm{display:block;width:100%;overflow-x:auto;-webkit-overflow-scrolling:touch}.table-responsive-sm>.table-bordered{border:0}}@media (max-width:767.98px){.table-responsive-md{display:block;width:100%;overflow-x:auto;-webkit-overflow-scrolling:touch}.table-responsive-md>.table-bordered{border:0}}@media (max-width:991.98px){.table-responsive-lg{display:block;width:100%;overflow-x:auto;-webkit-overflow-scrolling:touch}.table-responsive-lg>.table-bordered{border:0}}@media (max-width:1199.98px){.table-responsive-xl{display:block;width:100%;overflow-x:auto;-webkit-overflow-scrolling:touch}.table-responsive-xl>.table-bordered{border:0}}.table-responsive{display:block;width:100%;overflow-x:auto;-webkit-overflow-scrolling:touch}.table-responsive>.table-bordered{border:0}.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){.form-control{transition:none}}.form-control::-ms-expand{background-color:transparent;border:0}.form-control:-moz-focusring{color:transparent;text-shadow:0 0 0 #495057}.form-control:focus{color:#495057;background-color:#fff;border-color:#80bdff;outline:0;box-shadow:0 0 0 .2rem rgba(0,123,255,.25)}.form-control::-webkit-input-placeholder{color:#6c757d;opacity:1}.form-control::-moz-placeholder{color:#6c757d;opacity:1}.form-control:-ms-input-placeholder{color:#6c757d;opacity:1}.form-control::-ms-input-placeholder{color:#6c757d;opacity:1}.form-control::placeholder{color:#6c757d;opacity:1}.form-control:disabled,.form-control[readonly]{background-color:#e9ecef;opacity:1}select.form-control:focus::-ms-value{color:#495057;background-color:#fff}.form-control-file,.form-control-range{display:block;width:100%}.col-form-label{padding-top:calc(.375rem + 1px);padding-bottom:calc(.375rem + 1px);margin-bottom:0;font-size:inherit;line-height:1.5}.col-form-label-lg{padding-top:calc(.5rem + 1px);padding-bottom:calc(.5rem + 1px);font-size:1.25rem;line-height:1.5}.col-form-label-sm{padding-top:calc(.25rem + 1px);padding-bottom:calc(.25rem + 1px);font-size:.875rem;line-height:1.5}.form-control-plaintext{display:block;width:100%;padding:.375rem 0;margin-bottom:0;font-size:1rem;line-height:1.5;color:#212529;background-color:transparent;border:solid transparent;border-width:1px 0}.form-control-plaintext.form-control-lg,.form-control-plaintext.form-control-sm{padding-right:0;padding-left:0}.form-control-sm{height:calc(1.5em + .5rem + 2px);padding:.25rem .5rem;font-size:.875rem;line-height:1.5;border-radius:.2rem}.form-control-lg{height:calc(1.5em + 1rem + 2px);padding:.5rem 1rem;font-size:1.25rem;line-height:1.5;border-radius:.3rem}select.form-control[multiple],select.form-control[size]{height:auto}textarea.form-control{height:auto}.form-group{margin-bottom:1rem}.form-text{display:block;margin-top:.25rem}.form-row{display:-ms-flexbox;display:flex;-ms-flex-wrap:wrap;flex-wrap:wrap;margin-right:-5px;margin-left:-5px}.form-row>.col,.form-row>[class*=col-]{padding-right:5px;padding-left:5px}.form-check{position:relative;display:block;padding-left:1.25rem}.form-check-input{position:absolute;margin-top:.3rem;margin-left:-1.25rem}.form-check-input:disabled~.form-check-label,.form-check-input[disabled]~.form-check-label{color:#6c757d}.form-check-label{margin-bottom:0}.form-check-inline{display:-ms-inline-flexbox;display:inline-flex;-ms-flex-align:center;align-items:center;padding-left:0;margin-right:.75rem}.form-check-inline .form-check-input{position:static;margin-top:0;margin-right:.3125rem;margin-left:0}.valid-feedback{display:none;width:100%;margin-top:.25rem;font-size:80%;color:#28a745}.valid-tooltip{position:absolute;top:100%;z-index:5;display:none;max-width:100%;padding:.25rem .5rem;margin-top:.1rem;font-size:.875rem;line-height:1.5;color:#fff;background-color:rgba(40,167,69,.9);border-radius:.25rem}.is-valid~.valid-feedback,.is-valid~.valid-tooltip,.was-validated :valid~.valid-feedback,.was-validated :valid~.valid-tooltip{display:block}.form-control.is-valid,.was-validated .form-control:valid{border-color:#28a745;padding-right:calc(1.5em + .75rem);background-image:url(\\\"data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' width='8' height='8' viewBox='0 0 8 8'%3e%3cpath fill='%2328a745' d='M2.3 6.73L.6 4.53c-.4-1.04.46-1.4 1.1-.8l1.1 1.4 3.4-3.8c.6-.63 1.6-.27 1.2.7l-4 4.6c-.43.5-.8.4-1.1.1z'/%3e%3c/svg%3e\\\");background-repeat:no-repeat;background-position:right calc(.375em + .1875rem) center;background-size:calc(.75em + .375rem) calc(.75em + .375rem)}.form-control.is-valid:focus,.was-validated .form-control:valid:focus{border-color:#28a745;box-shadow:0 0 0 .2rem rgba(40,167,69,.25)}.was-validated textarea.form-control:valid,textarea.form-control.is-valid{padding-right:calc(1.5em + .75rem);background-position:top calc(.375em + .1875rem) right calc(.375em + .1875rem)}.custom-select.is-valid,.was-validated .custom-select:valid{border-color:#28a745;padding-right:calc(.75em + 2.3125rem);background:url(\\\"data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' width='4' height='5' viewBox='0 0 4 5'%3e%3cpath fill='%23343a40' d='M2 0L0 2h4zm0 5L0 3h4z'/%3e%3c/svg%3e\\\") no-repeat right .75rem center/8px 10px,url(\\\"data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' width='8' height='8' viewBox='0 0 8 8'%3e%3cpath fill='%2328a745' d='M2.3 6.73L.6 4.53c-.4-1.04.46-1.4 1.1-.8l1.1 1.4 3.4-3.8c.6-.63 1.6-.27 1.2.7l-4 4.6c-.43.5-.8.4-1.1.1z'/%3e%3c/svg%3e\\\") #fff no-repeat center right 1.75rem/calc(.75em + .375rem) calc(.75em + .375rem)}.custom-select.is-valid:focus,.was-validated .custom-select:valid:focus{border-color:#28a745;box-shadow:0 0 0 .2rem rgba(40,167,69,.25)}.form-check-input.is-valid~.form-check-label,.was-validated .form-check-input:valid~.form-check-label{color:#28a745}.form-check-input.is-valid~.valid-feedback,.form-check-input.is-valid~.valid-tooltip,.was-validated .form-check-input:valid~.valid-feedback,.was-validated .form-check-input:valid~.valid-tooltip{display:block}.custom-control-input.is-valid~.custom-control-label,.was-validated .custom-control-input:valid~.custom-control-label{color:#28a745}.custom-control-input.is-valid~.custom-control-label::before,.was-validated .custom-control-input:valid~.custom-control-label::before{border-color:#28a745}.custom-control-input.is-valid:checked~.custom-control-label::before,.was-validated .custom-control-input:valid:checked~.custom-control-label::before{border-color:#34ce57;background-color:#34ce57}.custom-control-input.is-valid:focus~.custom-control-label::before,.was-validated .custom-control-input:valid:focus~.custom-control-label::before{box-shadow:0 0 0 .2rem rgba(40,167,69,.25)}.custom-control-input.is-valid:focus:not(:checked)~.custom-control-label::before,.was-validated .custom-control-input:valid:focus:not(:checked)~.custom-control-label::before{border-color:#28a745}.custom-file-input.is-valid~.custom-file-label,.was-validated .custom-file-input:valid~.custom-file-label{border-color:#28a745}.custom-file-input.is-valid:focus~.custom-file-label,.was-validated .custom-file-input:valid:focus~.custom-file-label{border-color:#28a745;box-shadow:0 0 0 .2rem rgba(40,167,69,.25)}.invalid-feedback{display:none;width:100%;margin-top:.25rem;font-size:80%;color:#dc3545}.invalid-tooltip{position:absolute;top:100%;z-index:5;display:none;max-width:100%;padding:.25rem .5rem;margin-top:.1rem;font-size:.875rem;line-height:1.5;color:#fff;background-color:rgba(220,53,69,.9);border-radius:.25rem}.is-invalid~.invalid-feedback,.is-invalid~.invalid-tooltip,.was-validated :invalid~.invalid-feedback,.was-validated :invalid~.invalid-tooltip{display:block}.form-control.is-invalid,.was-validated .form-control:invalid{border-color:#dc3545;padding-right:calc(1.5em + .75rem);background-image:url(\\\"data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' width='12' height='12' fill='none' stroke='%23dc3545' viewBox='0 0 12 12'%3e%3ccircle cx='6' cy='6' r='4.5'/%3e%3cpath stroke-linejoin='round' d='M5.8 3.6h.4L6 6.5z'/%3e%3ccircle cx='6' cy='8.2' r='.6' fill='%23dc3545' stroke='none'/%3e%3c/svg%3e\\\");background-repeat:no-repeat;background-position:right calc(.375em + .1875rem) center;background-size:calc(.75em + .375rem) calc(.75em + .375rem)}.form-control.is-invalid:focus,.was-validated .form-control:invalid:focus{border-color:#dc3545;box-shadow:0 0 0 .2rem rgba(220,53,69,.25)}.was-validated textarea.form-control:invalid,textarea.form-control.is-invalid{padding-right:calc(1.5em + .75rem);background-position:top calc(.375em + .1875rem) right calc(.375em + .1875rem)}.custom-select.is-invalid,.was-validated .custom-select:invalid{border-color:#dc3545;padding-right:calc(.75em + 2.3125rem);background:url(\\\"data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' width='4' height='5' viewBox='0 0 4 5'%3e%3cpath fill='%23343a40' d='M2 0L0 2h4zm0 5L0 3h4z'/%3e%3c/svg%3e\\\") no-repeat right .75rem center/8px 10px,url(\\\"data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' width='12' height='12' fill='none' stroke='%23dc3545' viewBox='0 0 12 12'%3e%3ccircle cx='6' cy='6' r='4.5'/%3e%3cpath stroke-linejoin='round' d='M5.8 3.6h.4L6 6.5z'/%3e%3ccircle cx='6' cy='8.2' r='.6' fill='%23dc3545' stroke='none'/%3e%3c/svg%3e\\\") #fff no-repeat center right 1.75rem/calc(.75em + .375rem) calc(.75em + .375rem)}.custom-select.is-invalid:focus,.was-validated .custom-select:invalid:focus{border-color:#dc3545;box-shadow:0 0 0 .2rem rgba(220,53,69,.25)}.form-check-input.is-invalid~.form-check-label,.was-validated .form-check-input:invalid~.form-check-label{color:#dc3545}.form-check-input.is-invalid~.invalid-feedback,.form-check-input.is-invalid~.invalid-tooltip,.was-validated .form-check-input:invalid~.invalid-feedback,.was-validated .form-check-input:invalid~.invalid-tooltip{display:block}.custom-control-input.is-invalid~.custom-control-label,.was-validated .custom-control-input:invalid~.custom-control-label{color:#dc3545}.custom-control-input.is-invalid~.custom-control-label::before,.was-validated .custom-control-input:invalid~.custom-control-label::before{border-color:#dc3545}.custom-control-input.is-invalid:checked~.custom-control-label::before,.was-validated .custom-control-input:invalid:checked~.custom-control-label::before{border-color:#e4606d;background-color:#e4606d}.custom-control-input.is-invalid:focus~.custom-control-label::before,.was-validated .custom-control-input:invalid:focus~.custom-control-label::before{box-shadow:0 0 0 .2rem rgba(220,53,69,.25)}.custom-control-input.is-invalid:focus:not(:checked)~.custom-control-label::before,.was-validated .custom-control-input:invalid:focus:not(:checked)~.custom-control-label::before{border-color:#dc3545}.custom-file-input.is-invalid~.custom-file-label,.was-validated .custom-file-input:invalid~.custom-file-label{border-color:#dc3545}.custom-file-input.is-invalid:focus~.custom-file-label,.was-validated .custom-file-input:invalid:focus~.custom-file-label{border-color:#dc3545;box-shadow:0 0 0 .2rem rgba(220,53,69,.25)}.form-inline{display:-ms-flexbox;display:flex;-ms-flex-flow:row wrap;flex-flow:row wrap;-ms-flex-align:center;align-items:center}.form-inline .form-check{width:100%}@media (min-width:576px){.form-inline label{display:-ms-flexbox;display:flex;-ms-flex-align:center;align-items:center;-ms-flex-pack:center;justify-content:center;margin-bottom:0}.form-inline .form-group{display:-ms-flexbox;display:flex;-ms-flex:0 0 auto;flex:0 0 auto;-ms-flex-flow:row wrap;flex-flow:row wrap;-ms-flex-align:center;align-items:center;margin-bottom:0}.form-inline .form-control{display:inline-block;width:auto;vertical-align:middle}.form-inline .form-control-plaintext{display:inline-block}.form-inline .custom-select,.form-inline .input-group{width:auto}.form-inline .form-check{display:-ms-flexbox;display:flex;-ms-flex-align:center;align-items:center;-ms-flex-pack:center;justify-content:center;width:auto;padding-left:0}.form-inline .form-check-input{position:relative;-ms-flex-negative:0;flex-shrink:0;margin-top:0;margin-right:.25rem;margin-left:0}.form-inline .custom-control{-ms-flex-align:center;align-items:center;-ms-flex-pack:center;justify-content:center}.form-inline .custom-control-label{margin-bottom:0}}.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){.btn{transition:none}}.btn:hover{color:#212529;text-decoration:none}.btn.focus,.btn:focus{outline:0;box-shadow:0 0 0 .2rem rgba(0,123,255,.25)}.btn.disabled,.btn:disabled{opacity:.65}a.btn.disabled,fieldset:disabled a.btn{pointer-events:none}.btn-primary{color:#fff;background-color:#007bff;border-color:#007bff}.btn-primary:hover{color:#fff;background-color:#0069d9;border-color:#0062cc}.btn-primary.focus,.btn-primary:focus{color:#fff;background-color:#0069d9;border-color:#0062cc;box-shadow:0 0 0 .2rem rgba(38,143,255,.5)}.btn-primary.disabled,.btn-primary:disabled{color:#fff;background-color:#007bff;border-color:#007bff}.btn-primary:not(:disabled):not(.disabled).active,.btn-primary:not(:disabled):not(.disabled):active,.show>.btn-primary.dropdown-toggle{color:#fff;background-color:#0062cc;border-color:#005cbf}.btn-primary:not(:disabled):not(.disabled).active:focus,.btn-primary:not(:disabled):not(.disabled):active:focus,.show>.btn-primary.dropdown-toggle:focus{box-shadow:0 0 0 .2rem rgba(38,143,255,.5)}.btn-secondary{color:#fff;background-color:#6c757d;border-color:#6c757d}.btn-secondary:hover{color:#fff;background-color:#5a6268;border-color:#545b62}.btn-secondary.focus,.btn-secondary:focus{color:#fff;background-color:#5a6268;border-color:#545b62;box-shadow:0 0 0 .2rem rgba(130,138,145,.5)}.btn-secondary.disabled,.btn-secondary:disabled{color:#fff;background-color:#6c757d;border-color:#6c757d}.btn-secondary:not(:disabled):not(.disabled).active,.btn-secondary:not(:disabled):not(.disabled):active,.show>.btn-secondary.dropdown-toggle{color:#fff;background-color:#545b62;border-color:#4e555b}.btn-secondary:not(:disabled):not(.disabled).active:focus,.btn-secondary:not(:disabled):not(.disabled):active:focus,.show>.btn-secondary.dropdown-toggle:focus{box-shadow:0 0 0 .2rem rgba(130,138,145,.5)}.btn-success{color:#fff;background-color:#28a745;border-color:#28a745}.btn-success:hover{color:#fff;background-color:#218838;border-color:#1e7e34}.btn-success.focus,.btn-success:focus{color:#fff;background-color:#218838;border-color:#1e7e34;box-shadow:0 0 0 .2rem rgba(72,180,97,.5)}.btn-success.disabled,.btn-success:disabled{color:#fff;background-color:#28a745;border-color:#28a745}.btn-success:not(:disabled):not(.disabled).active,.btn-success:not(:disabled):not(.disabled):active,.show>.btn-success.dropdown-toggle{color:#fff;background-color:#1e7e34;border-color:#1c7430}.btn-success:not(:disabled):not(.disabled).active:focus,.btn-success:not(:disabled):not(.disabled):active:focus,.show>.btn-success.dropdown-toggle:focus{box-shadow:0 0 0 .2rem rgba(72,180,97,.5)}.btn-info{color:#fff;background-color:#17a2b8;border-color:#17a2b8}.btn-info:hover{color:#fff;background-color:#138496;border-color:#117a8b}.btn-info.focus,.btn-info:focus{color:#fff;background-color:#138496;border-color:#117a8b;box-shadow:0 0 0 .2rem rgba(58,176,195,.5)}.btn-info.disabled,.btn-info:disabled{color:#fff;background-color:#17a2b8;border-color:#17a2b8}.btn-info:not(:disabled):not(.disabled).active,.btn-info:not(:disabled):not(.disabled):active,.show>.btn-info.dropdown-toggle{color:#fff;background-color:#117a8b;border-color:#10707f}.btn-info:not(:disabled):not(.disabled).active:focus,.btn-info:not(:disabled):not(.disabled):active:focus,.show>.btn-info.dropdown-toggle:focus{box-shadow:0 0 0 .2rem rgba(58,176,195,.5)}.btn-warning{color:#212529;background-color:#ffc107;border-color:#ffc107}.btn-warning:hover{color:#212529;background-color:#e0a800;border-color:#d39e00}.btn-warning.focus,.btn-warning:focus{color:#212529;background-color:#e0a800;border-color:#d39e00;box-shadow:0 0 0 .2rem rgba(222,170,12,.5)}.btn-warning.disabled,.btn-warning:disabled{color:#212529;background-color:#ffc107;border-color:#ffc107}.btn-warning:not(:disabled):not(.disabled).active,.btn-warning:not(:disabled):not(.disabled):active,.show>.btn-warning.dropdown-toggle{color:#212529;background-color:#d39e00;border-color:#c69500}.btn-warning:not(:disabled):not(.disabled).active:focus,.btn-warning:not(:disabled):not(.disabled):active:focus,.show>.btn-warning.dropdown-toggle:focus{box-shadow:0 0 0 .2rem rgba(222,170,12,.5)}.btn-danger{color:#fff;background-color:#dc3545;border-color:#dc3545}.btn-danger:hover{color:#fff;background-color:#c82333;border-color:#bd2130}.btn-danger.focus,.btn-danger:focus{color:#fff;background-color:#c82333;border-color:#bd2130;box-shadow:0 0 0 .2rem rgba(225,83,97,.5)}.btn-danger.disabled,.btn-danger:disabled{color:#fff;background-color:#dc3545;border-color:#dc3545}.btn-danger:not(:disabled):not(.disabled).active,.btn-danger:not(:disabled):not(.disabled):active,.show>.btn-danger.dropdown-toggle{color:#fff;background-color:#bd2130;border-color:#b21f2d}.btn-danger:not(:disabled):not(.disabled).active:focus,.btn-danger:not(:disabled):not(.disabled):active:focus,.show>.btn-danger.dropdown-toggle:focus{box-shadow:0 0 0 .2rem rgba(225,83,97,.5)}.btn-light{color:#212529;background-color:#f8f9fa;border-color:#f8f9fa}.btn-light:hover{color:#212529;background-color:#e2e6ea;border-color:#dae0e5}.btn-light.focus,.btn-light:focus{color:#212529;background-color:#e2e6ea;border-color:#dae0e5;box-shadow:0 0 0 .2rem rgba(216,217,219,.5)}.btn-light.disabled,.btn-light:disabled{color:#212529;background-color:#f8f9fa;border-color:#f8f9fa}.btn-light:not(:disabled):not(.disabled).active,.btn-light:not(:disabled):not(.disabled):active,.show>.btn-light.dropdown-toggle{color:#212529;background-color:#dae0e5;border-color:#d3d9df}.btn-light:not(:disabled):not(.disabled).active:focus,.btn-light:not(:disabled):not(.disabled):active:focus,.show>.btn-light.dropdown-toggle:focus{box-shadow:0 0 0 .2rem rgba(216,217,219,.5)}.btn-dark{color:#fff;background-color:#343a40;border-color:#343a40}.btn-dark:hover{color:#fff;background-color:#23272b;border-color:#1d2124}.btn-dark.focus,.btn-dark:focus{color:#fff;background-color:#23272b;border-color:#1d2124;box-shadow:0 0 0 .2rem rgba(82,88,93,.5)}.btn-dark.disabled,.btn-dark:disabled{color:#fff;background-color:#343a40;border-color:#343a40}.btn-dark:not(:disabled):not(.disabled).active,.btn-dark:not(:disabled):not(.disabled):active,.show>.btn-dark.dropdown-toggle{color:#fff;background-color:#1d2124;border-color:#171a1d}.btn-dark:not(:disabled):not(.disabled).active:focus,.btn-dark:not(:disabled):not(.disabled):active:focus,.show>.btn-dark.dropdown-toggle:focus{box-shadow:0 0 0 .2rem rgba(82,88,93,.5)}.btn-outline-primary{color:#007bff;border-color:#007bff}.btn-outline-primary:hover{color:#fff;background-color:#007bff;border-color:#007bff}.btn-outline-primary.focus,.btn-outline-primary:focus{box-shadow:0 0 0 .2rem rgba(0,123,255,.5)}.btn-outline-primary.disabled,.btn-outline-primary:disabled{color:#007bff;background-color:transparent}.btn-outline-primary:not(:disabled):not(.disabled).active,.btn-outline-primary:not(:disabled):not(.disabled):active,.show>.btn-outline-primary.dropdown-toggle{color:#fff;background-color:#007bff;border-color:#007bff}.btn-outline-primary:not(:disabled):not(.disabled).active:focus,.btn-outline-primary:not(:disabled):not(.disabled):active:focus,.show>.btn-outline-primary.dropdown-toggle:focus{box-shadow:0 0 0 .2rem rgba(0,123,255,.5)}.btn-outline-secondary{color:#6c757d;border-color:#6c757d}.btn-outline-secondary:hover{color:#fff;background-color:#6c757d;border-color:#6c757d}.btn-outline-secondary.focus,.btn-outline-secondary:focus{box-shadow:0 0 0 .2rem rgba(108,117,125,.5)}.btn-outline-secondary.disabled,.btn-outline-secondary:disabled{color:#6c757d;background-color:transparent}.btn-outline-secondary:not(:disabled):not(.disabled).active,.btn-outline-secondary:not(:disabled):not(.disabled):active,.show>.btn-outline-secondary.dropdown-toggle{color:#fff;background-color:#6c757d;border-color:#6c757d}.btn-outline-secondary:not(:disabled):not(.disabled).active:focus,.btn-outline-secondary:not(:disabled):not(.disabled):active:focus,.show>.btn-outline-secondary.dropdown-toggle:focus{box-shadow:0 0 0 .2rem rgba(108,117,125,.5)}.btn-outline-success{color:#28a745;border-color:#28a745}.btn-outline-success:hover{color:#fff;background-color:#28a745;border-color:#28a745}.btn-outline-success.focus,.btn-outline-success:focus{box-shadow:0 0 0 .2rem rgba(40,167,69,.5)}.btn-outline-success.disabled,.btn-outline-success:disabled{color:#28a745;background-color:transparent}.btn-outline-success:not(:disabled):not(.disabled).active,.btn-outline-success:not(:disabled):not(.disabled):active,.show>.btn-outline-success.dropdown-toggle{color:#fff;background-color:#28a745;border-color:#28a745}.btn-outline-success:not(:disabled):not(.disabled).active:focus,.btn-outline-success:not(:disabled):not(.disabled):active:focus,.show>.btn-outline-success.dropdown-toggle:focus{box-shadow:0 0 0 .2rem rgba(40,167,69,.5)}.btn-outline-info{color:#17a2b8;border-color:#17a2b8}.btn-outline-info:hover{color:#fff;background-color:#17a2b8;border-color:#17a2b8}.btn-outline-info.focus,.btn-outline-info:focus{box-shadow:0 0 0 .2rem rgba(23,162,184,.5)}.btn-outline-info.disabled,.btn-outline-info:disabled{color:#17a2b8;background-color:transparent}.btn-outline-info:not(:disabled):not(.disabled).active,.btn-outline-info:not(:disabled):not(.disabled):active,.show>.btn-outline-info.dropdown-toggle{color:#fff;background-color:#17a2b8;border-color:#17a2b8}.btn-outline-info:not(:disabled):not(.disabled).active:focus,.btn-outline-info:not(:disabled):not(.disabled):active:focus,.show>.btn-outline-info.dropdown-toggle:focus{box-shadow:0 0 0 .2rem rgba(23,162,184,.5)}.btn-outline-warning{color:#ffc107;border-color:#ffc107}.btn-outline-warning:hover{color:#212529;background-color:#ffc107;border-color:#ffc107}.btn-outline-warning.focus,.btn-outline-warning:focus{box-shadow:0 0 0 .2rem rgba(255,193,7,.5)}.btn-outline-warning.disabled,.btn-outline-warning:disabled{color:#ffc107;background-color:transparent}.btn-outline-warning:not(:disabled):not(.disabled).active,.btn-outline-warning:not(:disabled):not(.disabled):active,.show>.btn-outline-warning.dropdown-toggle{color:#212529;background-color:#ffc107;border-color:#ffc107}.btn-outline-warning:not(:disabled):not(.disabled).active:focus,.btn-outline-warning:not(:disabled):not(.disabled):active:focus,.show>.btn-outline-warning.dropdown-toggle:focus{box-shadow:0 0 0 .2rem rgba(255,193,7,.5)}.btn-outline-danger{color:#dc3545;border-color:#dc3545}.btn-outline-danger:hover{color:#fff;background-color:#dc3545;border-color:#dc3545}.btn-outline-danger.focus,.btn-outline-danger:focus{box-shadow:0 0 0 .2rem rgba(220,53,69,.5)}.btn-outline-danger.disabled,.btn-outline-danger:disabled{color:#dc3545;background-color:transparent}.btn-outline-danger:not(:disabled):not(.disabled).active,.btn-outline-danger:not(:disabled):not(.disabled):active,.show>.btn-outline-danger.dropdown-toggle{color:#fff;background-color:#dc3545;border-color:#dc3545}.btn-outline-danger:not(:disabled):not(.disabled).active:focus,.btn-outline-danger:not(:disabled):not(.disabled):active:focus,.show>.btn-outline-danger.dropdown-toggle:focus{box-shadow:0 0 0 .2rem rgba(220,53,69,.5)}.btn-outline-light{color:#f8f9fa;border-color:#f8f9fa}.btn-outline-light:hover{color:#212529;background-color:#f8f9fa;border-color:#f8f9fa}.btn-outline-light.focus,.btn-outline-light:focus{box-shadow:0 0 0 .2rem rgba(248,249,250,.5)}.btn-outline-light.disabled,.btn-outline-light:disabled{color:#f8f9fa;background-color:transparent}.btn-outline-light:not(:disabled):not(.disabled).active,.btn-outline-light:not(:disabled):not(.disabled):active,.show>.btn-outline-light.dropdown-toggle{color:#212529;background-color:#f8f9fa;border-color:#f8f9fa}.btn-outline-light:not(:disabled):not(.disabled).active:focus,.btn-outline-light:not(:disabled):not(.disabled):active:focus,.show>.btn-outline-light.dropdown-toggle:focus{box-shadow:0 0 0 .2rem rgba(248,249,250,.5)}.btn-outline-dark{color:#343a40;border-color:#343a40}.btn-outline-dark:hover{color:#fff;background-color:#343a40;border-color:#343a40}.btn-outline-dark.focus,.btn-outline-dark:focus{box-shadow:0 0 0 .2rem rgba(52,58,64,.5)}.btn-outline-dark.disabled,.btn-outline-dark:disabled{color:#343a40;background-color:transparent}.btn-outline-dark:not(:disabled):not(.disabled).active,.btn-outline-dark:not(:disabled):not(.disabled):active,.show>.btn-outline-dark.dropdown-toggle{color:#fff;background-color:#343a40;border-color:#343a40}.btn-outline-dark:not(:disabled):not(.disabled).active:focus,.btn-outline-dark:not(:disabled):not(.disabled):active:focus,.show>.btn-outline-dark.dropdown-toggle:focus{box-shadow:0 0 0 .2rem rgba(52,58,64,.5)}.btn-link{font-weight:400;color:#007bff;text-decoration:none}.btn-link:hover{color:#0056b3;text-decoration:underline}.btn-link.focus,.btn-link:focus{text-decoration:underline;box-shadow:none}.btn-link.disabled,.btn-link:disabled{color:#6c757d;pointer-events:none}.btn-group-lg>.btn,.btn-lg{padding:.5rem 1rem;font-size:1.25rem;line-height:1.5;border-radius:.3rem}.btn-group-sm>.btn,.btn-sm{padding:.25rem .5rem;font-size:.875rem;line-height:1.5;border-radius:.2rem}.btn-block{display:block;width:100%}.btn-block+.btn-block{margin-top:.5rem}input[type=button].btn-block,input[type=reset].btn-block,input[type=submit].btn-block{width:100%}.fade{transition:opacity .15s linear}@media (prefers-reduced-motion:reduce){.fade{transition:none}}.fade:not(.show){opacity:0}.collapse:not(.show){display:none}.collapsing{position:relative;height:0;overflow:hidden;transition:height .35s ease}@media (prefers-reduced-motion:reduce){.collapsing{transition:none}}.dropdown,.dropleft,.dropright,.dropup{position:relative}.dropdown-toggle{white-space:nowrap}.dropdown-toggle::after{display:inline-block;margin-left:.255em;vertical-align:.255em;content:\\\"\\\";border-top:.3em solid;border-right:.3em solid transparent;border-bottom:0;border-left:.3em solid transparent}.dropdown-toggle:empty::after{margin-left:0}.dropdown-menu{position:absolute;top:100%;left:0;z-index:1000;display:none;float:left;min-width:10rem;padding:.5rem 0;margin:.125rem 0 0;font-size:1rem;color:#212529;text-align:left;list-style:none;background-color:#fff;background-clip:padding-box;border:1px solid rgba(0,0,0,.15);border-radius:.25rem}.dropdown-menu-left{right:auto;left:0}.dropdown-menu-right{right:0;left:auto}@media (min-width:576px){.dropdown-menu-sm-left{right:auto;left:0}.dropdown-menu-sm-right{right:0;left:auto}}@media (min-width:768px){.dropdown-menu-md-left{right:auto;left:0}.dropdown-menu-md-right{right:0;left:auto}}@media (min-width:992px){.dropdown-menu-lg-left{right:auto;left:0}.dropdown-menu-lg-right{right:0;left:auto}}@media (min-width:1200px){.dropdown-menu-xl-left{right:auto;left:0}.dropdown-menu-xl-right{right:0;left:auto}}.dropup .dropdown-menu{top:auto;bottom:100%;margin-top:0;margin-bottom:.125rem}.dropup .dropdown-toggle::after{display:inline-block;margin-left:.255em;vertical-align:.255em;content:\\\"\\\";border-top:0;border-right:.3em solid transparent;border-bottom:.3em solid;border-left:.3em solid transparent}.dropup .dropdown-toggle:empty::after{margin-left:0}.dropright .dropdown-menu{top:0;right:auto;left:100%;margin-top:0;margin-left:.125rem}.dropright .dropdown-toggle::after{display:inline-block;margin-left:.255em;vertical-align:.255em;content:\\\"\\\";border-top:.3em solid transparent;border-right:0;border-bottom:.3em solid transparent;border-left:.3em solid}.dropright .dropdown-toggle:empty::after{margin-left:0}.dropright .dropdown-toggle::after{vertical-align:0}.dropleft .dropdown-menu{top:0;right:100%;left:auto;margin-top:0;margin-right:.125rem}.dropleft .dropdown-toggle::after{display:inline-block;margin-left:.255em;vertical-align:.255em;content:\\\"\\\"}.dropleft .dropdown-toggle::after{display:none}.dropleft .dropdown-toggle::before{display:inline-block;margin-right:.255em;vertical-align:.255em;content:\\\"\\\";border-top:.3em solid transparent;border-right:.3em solid;border-bottom:.3em solid transparent}.dropleft .dropdown-toggle:empty::after{margin-left:0}.dropleft .dropdown-toggle::before{vertical-align:0}.dropdown-menu[x-placement^=bottom],.dropdown-menu[x-placement^=left],.dropdown-menu[x-placement^=right],.dropdown-menu[x-placement^=top]{right:auto;bottom:auto}.dropdown-divider{height:0;margin:.5rem 0;overflow:hidden;border-top:1px solid #e9ecef}.dropdown-item{display:block;width:100%;padding:.25rem 1.5rem;clear:both;font-weight:400;color:#212529;text-align:inherit;white-space:nowrap;background-color:transparent;border:0}.dropdown-item:focus,.dropdown-item:hover{color:#16181b;text-decoration:none;background-color:#f8f9fa}.dropdown-item.active,.dropdown-item:active{color:#fff;text-decoration:none;background-color:#007bff}.dropdown-item.disabled,.dropdown-item:disabled{color:#6c757d;pointer-events:none;background-color:transparent}.dropdown-menu.show{display:block}.dropdown-header{display:block;padding:.5rem 1.5rem;margin-bottom:0;font-size:.875rem;color:#6c757d;white-space:nowrap}.dropdown-item-text{display:block;padding:.25rem 1.5rem;color:#212529}.btn-group,.btn-group-vertical{position:relative;display:-ms-inline-flexbox;display:inline-flex;vertical-align:middle}.btn-group-vertical>.btn,.btn-group>.btn{position:relative;-ms-flex:1 1 auto;flex:1 1 auto}.btn-group-vertical>.btn:hover,.btn-group>.btn:hover{z-index:1}.btn-group-vertical>.btn.active,.btn-group-vertical>.btn:active,.btn-group-vertical>.btn:focus,.btn-group>.btn.active,.btn-group>.btn:active,.btn-group>.btn:focus{z-index:1}.btn-toolbar{display:-ms-flexbox;display:flex;-ms-flex-wrap:wrap;flex-wrap:wrap;-ms-flex-pack:start;justify-content:flex-start}.btn-toolbar .input-group{width:auto}.btn-group>.btn-group:not(:first-child),.btn-group>.btn:not(:first-child){margin-left:-1px}.btn-group>.btn-group:not(:last-child)>.btn,.btn-group>.btn:not(:last-child):not(.dropdown-toggle){border-top-right-radius:0;border-bottom-right-radius:0}.btn-group>.btn-group:not(:first-child)>.btn,.btn-group>.btn:not(:first-child){border-top-left-radius:0;border-bottom-left-radius:0}.dropdown-toggle-split{padding-right:.5625rem;padding-left:.5625rem}.dropdown-toggle-split::after,.dropright .dropdown-toggle-split::after,.dropup .dropdown-toggle-split::after{margin-left:0}.dropleft .dropdown-toggle-split::before{margin-right:0}.btn-group-sm>.btn+.dropdown-toggle-split,.btn-sm+.dropdown-toggle-split{padding-right:.375rem;padding-left:.375rem}.btn-group-lg>.btn+.dropdown-toggle-split,.btn-lg+.dropdown-toggle-split{padding-right:.75rem;padding-left:.75rem}.btn-group-vertical{-ms-flex-direction:column;flex-direction:column;-ms-flex-align:start;align-items:flex-start;-ms-flex-pack:center;justify-content:center}.btn-group-vertical>.btn,.btn-group-vertical>.btn-group{width:100%}.btn-group-vertical>.btn-group:not(:first-child),.btn-group-vertical>.btn:not(:first-child){margin-top:-1px}.btn-group-vertical>.btn-group:not(:last-child)>.btn,.btn-group-vertical>.btn:not(:last-child):not(.dropdown-toggle){border-bottom-right-radius:0;border-bottom-left-radius:0}.btn-group-vertical>.btn-group:not(:first-child)>.btn,.btn-group-vertical>.btn:not(:first-child){border-top-left-radius:0;border-top-right-radius:0}.btn-group-toggle>.btn,.btn-group-toggle>.btn-group>.btn{margin-bottom:0}.btn-group-toggle>.btn input[type=checkbox],.btn-group-toggle>.btn input[type=radio],.btn-group-toggle>.btn-group>.btn input[type=checkbox],.btn-group-toggle>.btn-group>.btn input[type=radio]{position:absolute;clip:rect(0,0,0,0);pointer-events:none}.input-group{position:relative;display:-ms-flexbox;display:flex;-ms-flex-wrap:wrap;flex-wrap:wrap;-ms-flex-align:stretch;align-items:stretch;width:100%}.input-group>.custom-file,.input-group>.custom-select,.input-group>.form-control,.input-group>.form-control-plaintext{position:relative;-ms-flex:1 1 0%;flex:1 1 0%;min-width:0;margin-bottom:0}.input-group>.custom-file+.custom-file,.input-group>.custom-file+.custom-select,.input-group>.custom-file+.form-control,.input-group>.custom-select+.custom-file,.input-group>.custom-select+.custom-select,.input-group>.custom-select+.form-control,.input-group>.form-control+.custom-file,.input-group>.form-control+.custom-select,.input-group>.form-control+.form-control,.input-group>.form-control-plaintext+.custom-file,.input-group>.form-control-plaintext+.custom-select,.input-group>.form-control-plaintext+.form-control{margin-left:-1px}.input-group>.custom-file .custom-file-input:focus~.custom-file-label,.input-group>.custom-select:focus,.input-group>.form-control:focus{z-index:3}.input-group>.custom-file .custom-file-input:focus{z-index:4}.input-group>.custom-select:not(:last-child),.input-group>.form-control:not(:last-child){border-top-right-radius:0;border-bottom-right-radius:0}.input-group>.custom-select:not(:first-child),.input-group>.form-control:not(:first-child){border-top-left-radius:0;border-bottom-left-radius:0}.input-group>.custom-file{display:-ms-flexbox;display:flex;-ms-flex-align:center;align-items:center}.input-group>.custom-file:not(:last-child) .custom-file-label,.input-group>.custom-file:not(:last-child) .custom-file-label::after{border-top-right-radius:0;border-bottom-right-radius:0}.input-group>.custom-file:not(:first-child) .custom-file-label{border-top-left-radius:0;border-bottom-left-radius:0}.input-group-append,.input-group-prepend{display:-ms-flexbox;display:flex}.input-group-append .btn,.input-group-prepend .btn{position:relative;z-index:2}.input-group-append .btn:focus,.input-group-prepend .btn:focus{z-index:3}.input-group-append .btn+.btn,.input-group-append .btn+.input-group-text,.input-group-append .input-group-text+.btn,.input-group-append .input-group-text+.input-group-text,.input-group-prepend .btn+.btn,.input-group-prepend .btn+.input-group-text,.input-group-prepend .input-group-text+.btn,.input-group-prepend .input-group-text+.input-group-text{margin-left:-1px}.input-group-prepend{margin-right:-1px}.input-group-append{margin-left:-1px}.input-group-text{display:-ms-flexbox;display:flex;-ms-flex-align:center;align-items:center;padding:.375rem .75rem;margin-bottom:0;font-size:1rem;font-weight:400;line-height:1.5;color:#495057;text-align:center;white-space:nowrap;background-color:#e9ecef;border:1px solid #ced4da;border-radius:.25rem}.input-group-text input[type=checkbox],.input-group-text input[type=radio]{margin-top:0}.input-group-lg>.custom-select,.input-group-lg>.form-control:not(textarea){height:calc(1.5em + 1rem + 2px)}.input-group-lg>.custom-select,.input-group-lg>.form-control,.input-group-lg>.input-group-append>.btn,.input-group-lg>.input-group-append>.input-group-text,.input-group-lg>.input-group-prepend>.btn,.input-group-lg>.input-group-prepend>.input-group-text{padding:.5rem 1rem;font-size:1.25rem;line-height:1.5;border-radius:.3rem}.input-group-sm>.custom-select,.input-group-sm>.form-control:not(textarea){height:calc(1.5em + .5rem + 2px)}.input-group-sm>.custom-select,.input-group-sm>.form-control,.input-group-sm>.input-group-append>.btn,.input-group-sm>.input-group-append>.input-group-text,.input-group-sm>.input-group-prepend>.btn,.input-group-sm>.input-group-prepend>.input-group-text{padding:.25rem .5rem;font-size:.875rem;line-height:1.5;border-radius:.2rem}.input-group-lg>.custom-select,.input-group-sm>.custom-select{padding-right:1.75rem}.input-group>.input-group-append:last-child>.btn:not(:last-child):not(.dropdown-toggle),.input-group>.input-group-append:last-child>.input-group-text:not(:last-child),.input-group>.input-group-append:not(:last-child)>.btn,.input-group>.input-group-append:not(:last-child)>.input-group-text,.input-group>.input-group-prepend>.btn,.input-group>.input-group-prepend>.input-group-text{border-top-right-radius:0;border-bottom-right-radius:0}.input-group>.input-group-append>.btn,.input-group>.input-group-append>.input-group-text,.input-group>.input-group-prepend:first-child>.btn:not(:first-child),.input-group>.input-group-prepend:first-child>.input-group-text:not(:first-child),.input-group>.input-group-prepend:not(:first-child)>.btn,.input-group>.input-group-prepend:not(:first-child)>.input-group-text{border-top-left-radius:0;border-bottom-left-radius:0}.custom-control{position:relative;display:block;min-height:1.5rem;padding-left:1.5rem}.custom-control-inline{display:-ms-inline-flexbox;display:inline-flex;margin-right:1rem}.custom-control-input{position:absolute;left:0;z-index:-1;width:1rem;height:1.25rem;opacity:0}.custom-control-input:checked~.custom-control-label::before{color:#fff;border-color:#007bff;background-color:#007bff}.custom-control-input:focus~.custom-control-label::before{box-shadow:0 0 0 .2rem rgba(0,123,255,.25)}.custom-control-input:focus:not(:checked)~.custom-control-label::before{border-color:#80bdff}.custom-control-input:not(:disabled):active~.custom-control-label::before{color:#fff;background-color:#b3d7ff;border-color:#b3d7ff}.custom-control-input:disabled~.custom-control-label,.custom-control-input[disabled]~.custom-control-label{color:#6c757d}.custom-control-input:disabled~.custom-control-label::before,.custom-control-input[disabled]~.custom-control-label::before{background-color:#e9ecef}.custom-control-label{position:relative;margin-bottom:0;vertical-align:top}.custom-control-label::before{position:absolute;top:.25rem;left:-1.5rem;display:block;width:1rem;height:1rem;pointer-events:none;content:\\\"\\\";background-color:#fff;border:#adb5bd solid 1px}.custom-control-label::after{position:absolute;top:.25rem;left:-1.5rem;display:block;width:1rem;height:1rem;content:\\\"\\\";background:no-repeat 50%/50% 50%}.custom-checkbox .custom-control-label::before{border-radius:.25rem}.custom-checkbox .custom-control-input:checked~.custom-control-label::after{background-image:url(\\\"data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' width='8' height='8' viewBox='0 0 8 8'%3e%3cpath fill='%23fff' d='M6.564.75l-3.59 3.612-1.538-1.55L0 4.26l2.974 2.99L8 2.193z'/%3e%3c/svg%3e\\\")}.custom-checkbox .custom-control-input:indeterminate~.custom-control-label::before{border-color:#007bff;background-color:#007bff}.custom-checkbox .custom-control-input:indeterminate~.custom-control-label::after{background-image:url(\\\"data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' width='4' height='4' viewBox='0 0 4 4'%3e%3cpath stroke='%23fff' d='M0 2h4'/%3e%3c/svg%3e\\\")}.custom-checkbox .custom-control-input:disabled:checked~.custom-control-label::before{background-color:rgba(0,123,255,.5)}.custom-checkbox .custom-control-input:disabled:indeterminate~.custom-control-label::before{background-color:rgba(0,123,255,.5)}.custom-radio .custom-control-label::before{border-radius:50%}.custom-radio .custom-control-input:checked~.custom-control-label::after{background-image:url(\\\"data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' width='12' height='12' viewBox='-4 -4 8 8'%3e%3ccircle r='3' fill='%23fff'/%3e%3c/svg%3e\\\")}.custom-radio .custom-control-input:disabled:checked~.custom-control-label::before{background-color:rgba(0,123,255,.5)}.custom-switch{padding-left:2.25rem}.custom-switch .custom-control-label::before{left:-2.25rem;width:1.75rem;pointer-events:all;border-radius:.5rem}.custom-switch .custom-control-label::after{top:calc(.25rem + 2px);left:calc(-2.25rem + 2px);width:calc(1rem - 4px);height:calc(1rem - 4px);background-color:#adb5bd;border-radius:.5rem;transition:background-color .15s ease-in-out,border-color .15s ease-in-out,box-shadow .15s ease-in-out,-webkit-transform .15s ease-in-out;transition:transform .15s ease-in-out,background-color .15s ease-in-out,border-color .15s ease-in-out,box-shadow .15s ease-in-out;transition:transform .15s ease-in-out,background-color .15s ease-in-out,border-color .15s ease-in-out,box-shadow .15s ease-in-out,-webkit-transform .15s ease-in-out}@media (prefers-reduced-motion:reduce){.custom-switch .custom-control-label::after{transition:none}}.custom-switch .custom-control-input:checked~.custom-control-label::after{background-color:#fff;-webkit-transform:translateX(.75rem);transform:translateX(.75rem)}.custom-switch .custom-control-input:disabled:checked~.custom-control-label::before{background-color:rgba(0,123,255,.5)}.custom-select{display:inline-block;width:100%;height:calc(1.5em + .75rem + 2px);padding:.375rem 1.75rem .375rem .75rem;font-size:1rem;font-weight:400;line-height:1.5;color:#495057;vertical-align:middle;background:#fff url(\\\"data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' width='4' height='5' viewBox='0 0 4 5'%3e%3cpath fill='%23343a40' d='M2 0L0 2h4zm0 5L0 3h4z'/%3e%3c/svg%3e\\\") no-repeat right .75rem center/8px 10px;border:1px solid #ced4da;border-radius:.25rem;-webkit-appearance:none;-moz-appearance:none;appearance:none}.custom-select:focus{border-color:#80bdff;outline:0;box-shadow:0 0 0 .2rem rgba(0,123,255,.25)}.custom-select:focus::-ms-value{color:#495057;background-color:#fff}.custom-select[multiple],.custom-select[size]:not([size=\\\"1\\\"]){height:auto;padding-right:.75rem;background-image:none}.custom-select:disabled{color:#6c757d;background-color:#e9ecef}.custom-select::-ms-expand{display:none}.custom-select:-moz-focusring{color:transparent;text-shadow:0 0 0 #495057}.custom-select-sm{height:calc(1.5em + .5rem + 2px);padding-top:.25rem;padding-bottom:.25rem;padding-left:.5rem;font-size:.875rem}.custom-select-lg{height:calc(1.5em + 1rem + 2px);padding-top:.5rem;padding-bottom:.5rem;padding-left:1rem;font-size:1.25rem}.custom-file{position:relative;display:inline-block;width:100%;height:calc(1.5em + .75rem + 2px);margin-bottom:0}.custom-file-input{position:relative;z-index:2;width:100%;height:calc(1.5em + .75rem + 2px);margin:0;opacity:0}.custom-file-input:focus~.custom-file-label{border-color:#80bdff;box-shadow:0 0 0 .2rem rgba(0,123,255,.25)}.custom-file-input:disabled~.custom-file-label,.custom-file-input[disabled]~.custom-file-label{background-color:#e9ecef}.custom-file-input:lang(en)~.custom-file-label::after{content:\\\"Browse\\\"}.custom-file-input~.custom-file-label[data-browse]::after{content:attr(data-browse)}.custom-file-label{position:absolute;top:0;right:0;left:0;z-index:1;height:calc(1.5em + .75rem + 2px);padding:.375rem .75rem;font-weight:400;line-height:1.5;color:#495057;background-color:#fff;border:1px solid #ced4da;border-radius:.25rem}.custom-file-label::after{position:absolute;top:0;right:0;bottom:0;z-index:3;display:block;height:calc(1.5em + .75rem);padding:.375rem .75rem;line-height:1.5;color:#495057;content:\\\"Browse\\\";background-color:#e9ecef;border-left:inherit;border-radius:0 .25rem .25rem 0}.custom-range{width:100%;height:1.4rem;padding:0;background-color:transparent;-webkit-appearance:none;-moz-appearance:none;appearance:none}.custom-range:focus{outline:0}.custom-range:focus::-webkit-slider-thumb{box-shadow:0 0 0 1px #fff,0 0 0 .2rem rgba(0,123,255,.25)}.custom-range:focus::-moz-range-thumb{box-shadow:0 0 0 1px #fff,0 0 0 .2rem rgba(0,123,255,.25)}.custom-range:focus::-ms-thumb{box-shadow:0 0 0 1px #fff,0 0 0 .2rem rgba(0,123,255,.25)}.custom-range::-moz-focus-outer{border:0}.custom-range::-webkit-slider-thumb{width:1rem;height:1rem;margin-top:-.25rem;background-color:#007bff;border:0;border-radius:1rem;-webkit-transition:background-color .15s ease-in-out,border-color .15s ease-in-out,box-shadow .15s ease-in-out;transition:background-color .15s ease-in-out,border-color .15s ease-in-out,box-shadow .15s ease-in-out;-webkit-appearance:none;appearance:none}@media (prefers-reduced-motion:reduce){.custom-range::-webkit-slider-thumb{-webkit-transition:none;transition:none}}.custom-range::-webkit-slider-thumb:active{background-color:#b3d7ff}.custom-range::-webkit-slider-runnable-track{width:100%;height:.5rem;color:transparent;cursor:pointer;background-color:#dee2e6;border-color:transparent;border-radius:1rem}.custom-range::-moz-range-thumb{width:1rem;height:1rem;background-color:#007bff;border:0;border-radius:1rem;-moz-transition:background-color .15s ease-in-out,border-color .15s ease-in-out,box-shadow .15s ease-in-out;transition:background-color .15s ease-in-out,border-color .15s ease-in-out,box-shadow .15s ease-in-out;-moz-appearance:none;appearance:none}@media (prefers-reduced-motion:reduce){.custom-range::-moz-range-thumb{-moz-transition:none;transition:none}}.custom-range::-moz-range-thumb:active{background-color:#b3d7ff}.custom-range::-moz-range-track{width:100%;height:.5rem;color:transparent;cursor:pointer;background-color:#dee2e6;border-color:transparent;border-radius:1rem}.custom-range::-ms-thumb{width:1rem;height:1rem;margin-top:0;margin-right:.2rem;margin-left:.2rem;background-color:#007bff;border:0;border-radius:1rem;-ms-transition:background-color .15s ease-in-out,border-color .15s ease-in-out,box-shadow .15s ease-in-out;transition:background-color .15s ease-in-out,border-color .15s ease-in-out,box-shadow .15s ease-in-out;appearance:none}@media (prefers-reduced-motion:reduce){.custom-range::-ms-thumb{-ms-transition:none;transition:none}}.custom-range::-ms-thumb:active{background-color:#b3d7ff}.custom-range::-ms-track{width:100%;height:.5rem;color:transparent;cursor:pointer;background-color:transparent;border-color:transparent;border-width:.5rem}.custom-range::-ms-fill-lower{background-color:#dee2e6;border-radius:1rem}.custom-range::-ms-fill-upper{margin-right:15px;background-color:#dee2e6;border-radius:1rem}.custom-range:disabled::-webkit-slider-thumb{background-color:#adb5bd}.custom-range:disabled::-webkit-slider-runnable-track{cursor:default}.custom-range:disabled::-moz-range-thumb{background-color:#adb5bd}.custom-range:disabled::-moz-range-track{cursor:default}.custom-range:disabled::-ms-thumb{background-color:#adb5bd}.custom-control-label::before,.custom-file-label,.custom-select{transition:background-color .15s ease-in-out,border-color .15s ease-in-out,box-shadow .15s ease-in-out}@media (prefers-reduced-motion:reduce){.custom-control-label::before,.custom-file-label,.custom-select{transition:none}}.nav{display:-ms-flexbox;display:flex;-ms-flex-wrap:wrap;flex-wrap:wrap;padding-left:0;margin-bottom:0;list-style:none}.nav-link{display:block;padding:.5rem 1rem}.nav-link:focus,.nav-link:hover{text-decoration:none}.nav-link.disabled{color:#6c757d;pointer-events:none;cursor:default}.nav-tabs{border-bottom:1px solid #dee2e6}.nav-tabs .nav-item{margin-bottom:-1px}.nav-tabs .nav-link{border:1px solid transparent;border-top-left-radius:.25rem;border-top-right-radius:.25rem}.nav-tabs .nav-link:focus,.nav-tabs .nav-link:hover{border-color:#e9ecef #e9ecef #dee2e6}.nav-tabs .nav-link.disabled{color:#6c757d;background-color:transparent;border-color:transparent}.nav-tabs .nav-item.show .nav-link,.nav-tabs .nav-link.active{color:#495057;background-color:#fff;border-color:#dee2e6 #dee2e6 #fff}.nav-tabs .dropdown-menu{margin-top:-1px;border-top-left-radius:0;border-top-right-radius:0}.nav-pills .nav-link{border-radius:.25rem}.nav-pills .nav-link.active,.nav-pills .show>.nav-link{color:#fff;background-color:#007bff}.nav-fill .nav-item{-ms-flex:1 1 auto;flex:1 1 auto;text-align:center}.nav-justified .nav-item{-ms-flex-preferred-size:0;flex-basis:0;-ms-flex-positive:1;flex-grow:1;text-align:center}.tab-content>.tab-pane{display:none}.tab-content>.active{display:block}.navbar{position:relative;display:-ms-flexbox;display:flex;-ms-flex-wrap:wrap;flex-wrap:wrap;-ms-flex-align:center;align-items:center;-ms-flex-pack:justify;justify-content:space-between;padding:.5rem 1rem}.navbar .container,.navbar .container-fluid,.navbar .container-lg,.navbar .container-md,.navbar .container-sm,.navbar .container-xl{display:-ms-flexbox;display:flex;-ms-flex-wrap:wrap;flex-wrap:wrap;-ms-flex-align:center;align-items:center;-ms-flex-pack:justify;justify-content:space-between}.navbar-brand{display:inline-block;padding-top:.3125rem;padding-bottom:.3125rem;margin-right:1rem;font-size:1.25rem;line-height:inherit;white-space:nowrap}.navbar-brand:focus,.navbar-brand:hover{text-decoration:none}.navbar-nav{display:-ms-flexbox;display:flex;-ms-flex-direction:column;flex-direction:column;padding-left:0;margin-bottom:0;list-style:none}.navbar-nav .nav-link{padding-right:0;padding-left:0}.navbar-nav .dropdown-menu{position:static;float:none}.navbar-text{display:inline-block;padding-top:.5rem;padding-bottom:.5rem}.navbar-collapse{-ms-flex-preferred-size:100%;flex-basis:100%;-ms-flex-positive:1;flex-grow:1;-ms-flex-align:center;align-items:center}.navbar-toggler{padding:.25rem .75rem;font-size:1.25rem;line-height:1;background-color:transparent;border:1px solid transparent;border-radius:.25rem}.navbar-toggler:focus,.navbar-toggler:hover{text-decoration:none}.navbar-toggler-icon{display:inline-block;width:1.5em;height:1.5em;vertical-align:middle;content:\\\"\\\";background:no-repeat center center;background-size:100% 100%}@media (max-width:575.98px){.navbar-expand-sm>.container,.navbar-expand-sm>.container-fluid,.navbar-expand-sm>.container-lg,.navbar-expand-sm>.container-md,.navbar-expand-sm>.container-sm,.navbar-expand-sm>.container-xl{padding-right:0;padding-left:0}}@media (min-width:576px){.navbar-expand-sm{-ms-flex-flow:row nowrap;flex-flow:row nowrap;-ms-flex-pack:start;justify-content:flex-start}.navbar-expand-sm .navbar-nav{-ms-flex-direction:row;flex-direction:row}.navbar-expand-sm .navbar-nav .dropdown-menu{position:absolute}.navbar-expand-sm .navbar-nav .nav-link{padding-right:.5rem;padding-left:.5rem}.navbar-expand-sm>.container,.navbar-expand-sm>.container-fluid,.navbar-expand-sm>.container-lg,.navbar-expand-sm>.container-md,.navbar-expand-sm>.container-sm,.navbar-expand-sm>.container-xl{-ms-flex-wrap:nowrap;flex-wrap:nowrap}.navbar-expand-sm .navbar-collapse{display:-ms-flexbox!important;display:flex!important;-ms-flex-preferred-size:auto;flex-basis:auto}.navbar-expand-sm .navbar-toggler{display:none}}@media (max-width:767.98px){.navbar-expand-md>.container,.navbar-expand-md>.container-fluid,.navbar-expand-md>.container-lg,.navbar-expand-md>.container-md,.navbar-expand-md>.container-sm,.navbar-expand-md>.container-xl{padding-right:0;padding-left:0}}@media (min-width:768px){.navbar-expand-md{-ms-flex-flow:row nowrap;flex-flow:row nowrap;-ms-flex-pack:start;justify-content:flex-start}.navbar-expand-md .navbar-nav{-ms-flex-direction:row;flex-direction:row}.navbar-expand-md .navbar-nav .dropdown-menu{position:absolute}.navbar-expand-md .navbar-nav .nav-link{padding-right:.5rem;padding-left:.5rem}.navbar-expand-md>.container,.navbar-expand-md>.container-fluid,.navbar-expand-md>.container-lg,.navbar-expand-md>.container-md,.navbar-expand-md>.container-sm,.navbar-expand-md>.container-xl{-ms-flex-wrap:nowrap;flex-wrap:nowrap}.navbar-expand-md .navbar-collapse{display:-ms-flexbox!important;display:flex!important;-ms-flex-preferred-size:auto;flex-basis:auto}.navbar-expand-md .navbar-toggler{display:none}}@media (max-width:991.98px){.navbar-expand-lg>.container,.navbar-expand-lg>.container-fluid,.navbar-expand-lg>.container-lg,.navbar-expand-lg>.container-md,.navbar-expand-lg>.container-sm,.navbar-expand-lg>.container-xl{padding-right:0;padding-left:0}}@media (min-width:992px){.navbar-expand-lg{-ms-flex-flow:row nowrap;flex-flow:row nowrap;-ms-flex-pack:start;justify-content:flex-start}.navbar-expand-lg .navbar-nav{-ms-flex-direction:row;flex-direction:row}.navbar-expand-lg .navbar-nav .dropdown-menu{position:absolute}.navbar-expand-lg .navbar-nav .nav-link{padding-right:.5rem;padding-left:.5rem}.navbar-expand-lg>.container,.navbar-expand-lg>.container-fluid,.navbar-expand-lg>.container-lg,.navbar-expand-lg>.container-md,.navbar-expand-lg>.container-sm,.navbar-expand-lg>.container-xl{-ms-flex-wrap:nowrap;flex-wrap:nowrap}.navbar-expand-lg .navbar-collapse{display:-ms-flexbox!important;display:flex!important;-ms-flex-preferred-size:auto;flex-basis:auto}.navbar-expand-lg .navbar-toggler{display:none}}@media (max-width:1199.98px){.navbar-expand-xl>.container,.navbar-expand-xl>.container-fluid,.navbar-expand-xl>.container-lg,.navbar-expand-xl>.container-md,.navbar-expand-xl>.container-sm,.navbar-expand-xl>.container-xl{padding-right:0;padding-left:0}}@media (min-width:1200px){.navbar-expand-xl{-ms-flex-flow:row nowrap;flex-flow:row nowrap;-ms-flex-pack:start;justify-content:flex-start}.navbar-expand-xl .navbar-nav{-ms-flex-direction:row;flex-direction:row}.navbar-expand-xl .navbar-nav .dropdown-menu{position:absolute}.navbar-expand-xl .navbar-nav .nav-link{padding-right:.5rem;padding-left:.5rem}.navbar-expand-xl>.container,.navbar-expand-xl>.container-fluid,.navbar-expand-xl>.container-lg,.navbar-expand-xl>.container-md,.navbar-expand-xl>.container-sm,.navbar-expand-xl>.container-xl{-ms-flex-wrap:nowrap;flex-wrap:nowrap}.navbar-expand-xl .navbar-collapse{display:-ms-flexbox!important;display:flex!important;-ms-flex-preferred-size:auto;flex-basis:auto}.navbar-expand-xl .navbar-toggler{display:none}}.navbar-expand{-ms-flex-flow:row nowrap;flex-flow:row nowrap;-ms-flex-pack:start;justify-content:flex-start}.navbar-expand>.container,.navbar-expand>.container-fluid,.navbar-expand>.container-lg,.navbar-expand>.container-md,.navbar-expand>.container-sm,.navbar-expand>.container-xl{padding-right:0;padding-left:0}.navbar-expand .navbar-nav{-ms-flex-direction:row;flex-direction:row}.navbar-expand .navbar-nav .dropdown-menu{position:absolute}.navbar-expand .navbar-nav .nav-link{padding-right:.5rem;padding-left:.5rem}.navbar-expand>.container,.navbar-expand>.container-fluid,.navbar-expand>.container-lg,.navbar-expand>.container-md,.navbar-expand>.container-sm,.navbar-expand>.container-xl{-ms-flex-wrap:nowrap;flex-wrap:nowrap}.navbar-expand .navbar-collapse{display:-ms-flexbox!important;display:flex!important;-ms-flex-preferred-size:auto;flex-basis:auto}.navbar-expand .navbar-toggler{display:none}.navbar-light .navbar-brand{color:rgba(0,0,0,.9)}.navbar-light .navbar-brand:focus,.navbar-light .navbar-brand:hover{color:rgba(0,0,0,.9)}.navbar-light .navbar-nav .nav-link{color:rgba(0,0,0,.5)}.navbar-light .navbar-nav .nav-link:focus,.navbar-light .navbar-nav .nav-link:hover{color:rgba(0,0,0,.7)}.navbar-light .navbar-nav .nav-link.disabled{color:rgba(0,0,0,.3)}.navbar-light .navbar-nav .active>.nav-link,.navbar-light .navbar-nav .nav-link.active,.navbar-light .navbar-nav .nav-link.show,.navbar-light .navbar-nav .show>.nav-link{color:rgba(0,0,0,.9)}.navbar-light .navbar-toggler{color:rgba(0,0,0,.5);border-color:rgba(0,0,0,.1)}.navbar-light .navbar-toggler-icon{background-image:url(\\\"data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' width='30' height='30' viewBox='0 0 30 30'%3e%3cpath stroke='rgba(0, 0, 0, 0.5)' stroke-linecap='round' stroke-miterlimit='10' stroke-width='2' d='M4 7h22M4 15h22M4 23h22'/%3e%3c/svg%3e\\\")}.navbar-light .navbar-text{color:rgba(0,0,0,.5)}.navbar-light .navbar-text a{color:rgba(0,0,0,.9)}.navbar-light .navbar-text a:focus,.navbar-light .navbar-text a:hover{color:rgba(0,0,0,.9)}.navbar-dark .navbar-brand{color:#fff}.navbar-dark .navbar-brand:focus,.navbar-dark .navbar-brand:hover{color:#fff}.navbar-dark .navbar-nav .nav-link{color:rgba(255,255,255,.5)}.navbar-dark .navbar-nav .nav-link:focus,.navbar-dark .navbar-nav .nav-link:hover{color:rgba(255,255,255,.75)}.navbar-dark .navbar-nav .nav-link.disabled{color:rgba(255,255,255,.25)}.navbar-dark .navbar-nav .active>.nav-link,.navbar-dark .navbar-nav .nav-link.active,.navbar-dark .navbar-nav .nav-link.show,.navbar-dark .navbar-nav .show>.nav-link{color:#fff}.navbar-dark .navbar-toggler{color:rgba(255,255,255,.5);border-color:rgba(255,255,255,.1)}.navbar-dark .navbar-toggler-icon{background-image:url(\\\"data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' width='30' height='30' viewBox='0 0 30 30'%3e%3cpath stroke='rgba(255, 255, 255, 0.5)' stroke-linecap='round' stroke-miterlimit='10' stroke-width='2' d='M4 7h22M4 15h22M4 23h22'/%3e%3c/svg%3e\\\")}.navbar-dark .navbar-text{color:rgba(255,255,255,.5)}.navbar-dark .navbar-text a{color:#fff}.navbar-dark .navbar-text a:focus,.navbar-dark .navbar-text a:hover{color:#fff}.card{position:relative;display:-ms-flexbox;display:flex;-ms-flex-direction:column;flex-direction:column;min-width:0;word-wrap:break-word;background-color:#fff;background-clip:border-box;border:1px solid rgba(0,0,0,.125);border-radius:.25rem}.card>hr{margin-right:0;margin-left:0}.card>.list-group:first-child .list-group-item:first-child{border-top-left-radius:.25rem;border-top-right-radius:.25rem}.card>.list-group:last-child .list-group-item:last-child{border-bottom-right-radius:.25rem;border-bottom-left-radius:.25rem}.card-body{-ms-flex:1 1 auto;flex:1 1 auto;min-height:1px;padding:1.25rem}.card-title{margin-bottom:.75rem}.card-subtitle{margin-top:-.375rem;margin-bottom:0}.card-text:last-child{margin-bottom:0}.card-link:hover{text-decoration:none}.card-link+.card-link{margin-left:1.25rem}.card-header{padding:.75rem 1.25rem;margin-bottom:0;background-color:rgba(0,0,0,.03);border-bottom:1px solid rgba(0,0,0,.125)}.card-header:first-child{border-radius:calc(.25rem - 1px) calc(.25rem - 1px) 0 0}.card-header+.list-group .list-group-item:first-child{border-top:0}.card-footer{padding:.75rem 1.25rem;background-color:rgba(0,0,0,.03);border-top:1px solid rgba(0,0,0,.125)}.card-footer:last-child{border-radius:0 0 calc(.25rem - 1px) calc(.25rem - 1px)}.card-header-tabs{margin-right:-.625rem;margin-bottom:-.75rem;margin-left:-.625rem;border-bottom:0}.card-header-pills{margin-right:-.625rem;margin-left:-.625rem}.card-img-overlay{position:absolute;top:0;right:0;bottom:0;left:0;padding:1.25rem}.card-img,.card-img-bottom,.card-img-top{-ms-flex-negative:0;flex-shrink:0;width:100%}.card-img,.card-img-top{border-top-left-radius:calc(.25rem - 1px);border-top-right-radius:calc(.25rem - 1px)}.card-img,.card-img-bottom{border-bottom-right-radius:calc(.25rem - 1px);border-bottom-left-radius:calc(.25rem - 1px)}.card-deck .card{margin-bottom:15px}@media (min-width:576px){.card-deck{display:-ms-flexbox;display:flex;-ms-flex-flow:row wrap;flex-flow:row wrap;margin-right:-15px;margin-left:-15px}.card-deck .card{-ms-flex:1 0 0%;flex:1 0 0%;margin-right:15px;margin-bottom:0;margin-left:15px}}.card-group>.card{margin-bottom:15px}@media (min-width:576px){.card-group{display:-ms-flexbox;display:flex;-ms-flex-flow:row wrap;flex-flow:row wrap}.card-group>.card{-ms-flex:1 0 0%;flex:1 0 0%;margin-bottom:0}.card-group>.card+.card{margin-left:0;border-left:0}.card-group>.card:not(:last-child){border-top-right-radius:0;border-bottom-right-radius:0}.card-group>.card:not(:last-child) .card-header,.card-group>.card:not(:last-child) .card-img-top{border-top-right-radius:0}.card-group>.card:not(:last-child) .card-footer,.card-group>.card:not(:last-child) .card-img-bottom{border-bottom-right-radius:0}.card-group>.card:not(:first-child){border-top-left-radius:0;border-bottom-left-radius:0}.card-group>.card:not(:first-child) .card-header,.card-group>.card:not(:first-child) .card-img-top{border-top-left-radius:0}.card-group>.card:not(:first-child) .card-footer,.card-group>.card:not(:first-child) .card-img-bottom{border-bottom-left-radius:0}}.card-columns .card{margin-bottom:.75rem}@media (min-width:576px){.card-columns{-webkit-column-count:3;-moz-column-count:3;column-count:3;-webkit-column-gap:1.25rem;-moz-column-gap:1.25rem;column-gap:1.25rem;orphans:1;widows:1}.card-columns .card{display:inline-block;width:100%}}.accordion>.card{overflow:hidden}.accordion>.card:not(:last-of-type){border-bottom:0;border-bottom-right-radius:0;border-bottom-left-radius:0}.accordion>.card:not(:first-of-type){border-top-left-radius:0;border-top-right-radius:0}.accordion>.card>.card-header{border-radius:0;margin-bottom:-1px}.breadcrumb{display:-ms-flexbox;display:flex;-ms-flex-wrap:wrap;flex-wrap:wrap;padding:.75rem 1rem;margin-bottom:1rem;list-style:none;background-color:#e9ecef;border-radius:.25rem}.breadcrumb-item+.breadcrumb-item{padding-left:.5rem}.breadcrumb-item+.breadcrumb-item::before{display:inline-block;padding-right:.5rem;color:#6c757d;content:\\\"/\\\"}.breadcrumb-item+.breadcrumb-item:hover::before{text-decoration:underline}.breadcrumb-item+.breadcrumb-item:hover::before{text-decoration:none}.breadcrumb-item.active{color:#6c757d}.pagination{display:-ms-flexbox;display:flex;padding-left:0;list-style:none;border-radius:.25rem}.page-link{position:relative;display:block;padding:.5rem .75rem;margin-left:-1px;line-height:1.25;color:#007bff;background-color:#fff;border:1px solid #dee2e6}.page-link:hover{z-index:2;color:#0056b3;text-decoration:none;background-color:#e9ecef;border-color:#dee2e6}.page-link:focus{z-index:3;outline:0;box-shadow:0 0 0 .2rem rgba(0,123,255,.25)}.page-item:first-child .page-link{margin-left:0;border-top-left-radius:.25rem;border-bottom-left-radius:.25rem}.page-item:last-child .page-link{border-top-right-radius:.25rem;border-bottom-right-radius:.25rem}.page-item.active .page-link{z-index:3;color:#fff;background-color:#007bff;border-color:#007bff}.page-item.disabled .page-link{color:#6c757d;pointer-events:none;cursor:auto;background-color:#fff;border-color:#dee2e6}.pagination-lg .page-link{padding:.75rem 1.5rem;font-size:1.25rem;line-height:1.5}.pagination-lg .page-item:first-child .page-link{border-top-left-radius:.3rem;border-bottom-left-radius:.3rem}.pagination-lg .page-item:last-child .page-link{border-top-right-radius:.3rem;border-bottom-right-radius:.3rem}.pagination-sm .page-link{padding:.25rem .5rem;font-size:.875rem;line-height:1.5}.pagination-sm .page-item:first-child .page-link{border-top-left-radius:.2rem;border-bottom-left-radius:.2rem}.pagination-sm .page-item:last-child .page-link{border-top-right-radius:.2rem;border-bottom-right-radius:.2rem}.badge{display:inline-block;padding:.25em .4em;font-size:75%;font-weight:700;line-height:1;text-align:center;white-space:nowrap;vertical-align:baseline;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){.badge{transition:none}}a.badge:focus,a.badge:hover{text-decoration:none}.badge:empty{display:none}.btn .badge{position:relative;top:-1px}.badge-pill{padding-right:.6em;padding-left:.6em;border-radius:10rem}.badge-primary{color:#fff;background-color:#007bff}a.badge-primary:focus,a.badge-primary:hover{color:#fff;background-color:#0062cc}a.badge-primary.focus,a.badge-primary:focus{outline:0;box-shadow:0 0 0 .2rem rgba(0,123,255,.5)}.badge-secondary{color:#fff;background-color:#6c757d}a.badge-secondary:focus,a.badge-secondary:hover{color:#fff;background-color:#545b62}a.badge-secondary.focus,a.badge-secondary:focus{outline:0;box-shadow:0 0 0 .2rem rgba(108,117,125,.5)}.badge-success{color:#fff;background-color:#28a745}a.badge-success:focus,a.badge-success:hover{color:#fff;background-color:#1e7e34}a.badge-success.focus,a.badge-success:focus{outline:0;box-shadow:0 0 0 .2rem rgba(40,167,69,.5)}.badge-info{color:#fff;background-color:#17a2b8}a.badge-info:focus,a.badge-info:hover{color:#fff;background-color:#117a8b}a.badge-info.focus,a.badge-info:focus{outline:0;box-shadow:0 0 0 .2rem rgba(23,162,184,.5)}.badge-warning{color:#212529;background-color:#ffc107}a.badge-warning:focus,a.badge-warning:hover{color:#212529;background-color:#d39e00}a.badge-warning.focus,a.badge-warning:focus{outline:0;box-shadow:0 0 0 .2rem rgba(255,193,7,.5)}.badge-danger{color:#fff;background-color:#dc3545}a.badge-danger:focus,a.badge-danger:hover{color:#fff;background-color:#bd2130}a.badge-danger.focus,a.badge-danger:focus{outline:0;box-shadow:0 0 0 .2rem rgba(220,53,69,.5)}.badge-light{color:#212529;background-color:#f8f9fa}a.badge-light:focus,a.badge-light:hover{color:#212529;background-color:#dae0e5}a.badge-light.focus,a.badge-light:focus{outline:0;box-shadow:0 0 0 .2rem rgba(248,249,250,.5)}.badge-dark{color:#fff;background-color:#343a40}a.badge-dark:focus,a.badge-dark:hover{color:#fff;background-color:#1d2124}a.badge-dark.focus,a.badge-dark:focus{outline:0;box-shadow:0 0 0 .2rem rgba(52,58,64,.5)}.jumbotron{padding:2rem 1rem;margin-bottom:2rem;background-color:#e9ecef;border-radius:.3rem}@media (min-width:576px){.jumbotron{padding:4rem 2rem}}.jumbotron-fluid{padding-right:0;padding-left:0;border-radius:0}.alert{position:relative;padding:.75rem 1.25rem;margin-bottom:1rem;border:1px solid transparent;border-radius:.25rem}.alert-heading{color:inherit}.alert-link{font-weight:700}.alert-dismissible{padding-right:4rem}.alert-dismissible .close{position:absolute;top:0;right:0;padding:.75rem 1.25rem;color:inherit}.alert-primary{color:#004085;background-color:#cce5ff;border-color:#b8daff}.alert-primary hr{border-top-color:#9fcdff}.alert-primary .alert-link{color:#002752}.alert-secondary{color:#383d41;background-color:#e2e3e5;border-color:#d6d8db}.alert-secondary hr{border-top-color:#c8cbcf}.alert-secondary .alert-link{color:#202326}.alert-success{color:#155724;background-color:#d4edda;border-color:#c3e6cb}.alert-success hr{border-top-color:#b1dfbb}.alert-success .alert-link{color:#0b2e13}.alert-info{color:#0c5460;background-color:#d1ecf1;border-color:#bee5eb}.alert-info hr{border-top-color:#abdde5}.alert-info .alert-link{color:#062c33}.alert-warning{color:#856404;background-color:#fff3cd;border-color:#ffeeba}.alert-warning hr{border-top-color:#ffe8a1}.alert-warning .alert-link{color:#533f03}.alert-danger{color:#721c24;background-color:#f8d7da;border-color:#f5c6cb}.alert-danger hr{border-top-color:#f1b0b7}.alert-danger .alert-link{color:#491217}.alert-light{color:#818182;background-color:#fefefe;border-color:#fdfdfe}.alert-light hr{border-top-color:#ececf6}.alert-light .alert-link{color:#686868}.alert-dark{color:#1b1e21;background-color:#d6d8d9;border-color:#c6c8ca}.alert-dark hr{border-top-color:#b9bbbe}.alert-dark .alert-link{color:#040505}@-webkit-keyframes progress-bar-stripes{from{background-position:1rem 0}to{background-position:0 0}}@keyframes progress-bar-stripes{from{background-position:1rem 0}to{background-position:0 0}}.progress{display:-ms-flexbox;display:flex;height:1rem;overflow:hidden;font-size:.75rem;background-color:#e9ecef;border-radius:.25rem}.progress-bar{display:-ms-flexbox;display:flex;-ms-flex-direction:column;flex-direction:column;-ms-flex-pack:center;justify-content:center;overflow:hidden;color:#fff;text-align:center;white-space:nowrap;background-color:#007bff;transition:width .6s ease}@media (prefers-reduced-motion:reduce){.progress-bar{transition:none}}.progress-bar-striped{background-image:linear-gradient(45deg,rgba(255,255,255,.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,.15) 50%,rgba(255,255,255,.15) 75%,transparent 75%,transparent);background-size:1rem 1rem}.progress-bar-animated{-webkit-animation:progress-bar-stripes 1s linear infinite;animation:progress-bar-stripes 1s linear infinite}@media (prefers-reduced-motion:reduce){.progress-bar-animated{-webkit-animation:none;animation:none}}.media{display:-ms-flexbox;display:flex;-ms-flex-align:start;align-items:flex-start}.media-body{-ms-flex:1;flex:1}.list-group{display:-ms-flexbox;display:flex;-ms-flex-direction:column;flex-direction:column;padding-left:0;margin-bottom:0}.list-group-item-action{width:100%;color:#495057;text-align:inherit}.list-group-item-action:focus,.list-group-item-action:hover{z-index:1;color:#495057;text-decoration:none;background-color:#f8f9fa}.list-group-item-action:active{color:#212529;background-color:#e9ecef}.list-group-item{position:relative;display:block;padding:.75rem 1.25rem;background-color:#fff;border:1px solid rgba(0,0,0,.125)}.list-group-item:first-child{border-top-left-radius:.25rem;border-top-right-radius:.25rem}.list-group-item:last-child{border-bottom-right-radius:.25rem;border-bottom-left-radius:.25rem}.list-group-item.disabled,.list-group-item:disabled{color:#6c757d;pointer-events:none;background-color:#fff}.list-group-item.active{z-index:2;color:#fff;background-color:#007bff;border-color:#007bff}.list-group-item+.list-group-item{border-top-width:0}.list-group-item+.list-group-item.active{margin-top:-1px;border-top-width:1px}.list-group-horizontal{-ms-flex-direction:row;flex-direction:row}.list-group-horizontal .list-group-item:first-child{border-bottom-left-radius:.25rem;border-top-right-radius:0}.list-group-horizontal .list-group-item:last-child{border-top-right-radius:.25rem;border-bottom-left-radius:0}.list-group-horizontal .list-group-item.active{margin-top:0}.list-group-horizontal .list-group-item+.list-group-item{border-top-width:1px;border-left-width:0}.list-group-horizontal .list-group-item+.list-group-item.active{margin-left:-1px;border-left-width:1px}@media (min-width:576px){.list-group-horizontal-sm{-ms-flex-direction:row;flex-direction:row}.list-group-horizontal-sm .list-group-item:first-child{border-bottom-left-radius:.25rem;border-top-right-radius:0}.list-group-horizontal-sm .list-group-item:last-child{border-top-right-radius:.25rem;border-bottom-left-radius:0}.list-group-horizontal-sm .list-group-item.active{margin-top:0}.list-group-horizontal-sm .list-group-item+.list-group-item{border-top-width:1px;border-left-width:0}.list-group-horizontal-sm .list-group-item+.list-group-item.active{margin-left:-1px;border-left-width:1px}}@media (min-width:768px){.list-group-horizontal-md{-ms-flex-direction:row;flex-direction:row}.list-group-horizontal-md .list-group-item:first-child{border-bottom-left-radius:.25rem;border-top-right-radius:0}.list-group-horizontal-md .list-group-item:last-child{border-top-right-radius:.25rem;border-bottom-left-radius:0}.list-group-horizontal-md .list-group-item.active{margin-top:0}.list-group-horizontal-md .list-group-item+.list-group-item{border-top-width:1px;border-left-width:0}.list-group-horizontal-md .list-group-item+.list-group-item.active{margin-left:-1px;border-left-width:1px}}@media (min-width:992px){.list-group-horizontal-lg{-ms-flex-direction:row;flex-direction:row}.list-group-horizontal-lg .list-group-item:first-child{border-bottom-left-radius:.25rem;border-top-right-radius:0}.list-group-horizontal-lg .list-group-item:last-child{border-top-right-radius:.25rem;border-bottom-left-radius:0}.list-group-horizontal-lg .list-group-item.active{margin-top:0}.list-group-horizontal-lg .list-group-item+.list-group-item{border-top-width:1px;border-left-width:0}.list-group-horizontal-lg .list-group-item+.list-group-item.active{margin-left:-1px;border-left-width:1px}}@media (min-width:1200px){.list-group-horizontal-xl{-ms-flex-direction:row;flex-direction:row}.list-group-horizontal-xl .list-group-item:first-child{border-bottom-left-radius:.25rem;border-top-right-radius:0}.list-group-horizontal-xl .list-group-item:last-child{border-top-right-radius:.25rem;border-bottom-left-radius:0}.list-group-horizontal-xl .list-group-item.active{margin-top:0}.list-group-horizontal-xl .list-group-item+.list-group-item{border-top-width:1px;border-left-width:0}.list-group-horizontal-xl .list-group-item+.list-group-item.active{margin-left:-1px;border-left-width:1px}}.list-group-flush .list-group-item{border-right-width:0;border-left-width:0;border-radius:0}.list-group-flush .list-group-item:first-child{border-top-width:0}.list-group-flush:last-child .list-group-item:last-child{border-bottom-width:0}.list-group-item-primary{color:#004085;background-color:#b8daff}.list-group-item-primary.list-group-item-action:focus,.list-group-item-primary.list-group-item-action:hover{color:#004085;background-color:#9fcdff}.list-group-item-primary.list-group-item-action.active{color:#fff;background-color:#004085;border-color:#004085}.list-group-item-secondary{color:#383d41;background-color:#d6d8db}.list-group-item-secondary.list-group-item-action:focus,.list-group-item-secondary.list-group-item-action:hover{color:#383d41;background-color:#c8cbcf}.list-group-item-secondary.list-group-item-action.active{color:#fff;background-color:#383d41;border-color:#383d41}.list-group-item-success{color:#155724;background-color:#c3e6cb}.list-group-item-success.list-group-item-action:focus,.list-group-item-success.list-group-item-action:hover{color:#155724;background-color:#b1dfbb}.list-group-item-success.list-group-item-action.active{color:#fff;background-color:#155724;border-color:#155724}.list-group-item-info{color:#0c5460;background-color:#bee5eb}.list-group-item-info.list-group-item-action:focus,.list-group-item-info.list-group-item-action:hover{color:#0c5460;background-color:#abdde5}.list-group-item-info.list-group-item-action.active{color:#fff;background-color:#0c5460;border-color:#0c5460}.list-group-item-warning{color:#856404;background-color:#ffeeba}.list-group-item-warning.list-group-item-action:focus,.list-group-item-warning.list-group-item-action:hover{color:#856404;background-color:#ffe8a1}.list-group-item-warning.list-group-item-action.active{color:#fff;background-color:#856404;border-color:#856404}.list-group-item-danger{color:#721c24;background-color:#f5c6cb}.list-group-item-danger.list-group-item-action:focus,.list-group-item-danger.list-group-item-action:hover{color:#721c24;background-color:#f1b0b7}.list-group-item-danger.list-group-item-action.active{color:#fff;background-color:#721c24;border-color:#721c24}.list-group-item-light{color:#818182;background-color:#fdfdfe}.list-group-item-light.list-group-item-action:focus,.list-group-item-light.list-group-item-action:hover{color:#818182;background-color:#ececf6}.list-group-item-light.list-group-item-action.active{color:#fff;background-color:#818182;border-color:#818182}.list-group-item-dark{color:#1b1e21;background-color:#c6c8ca}.list-group-item-dark.list-group-item-action:focus,.list-group-item-dark.list-group-item-action:hover{color:#1b1e21;background-color:#b9bbbe}.list-group-item-dark.list-group-item-action.active{color:#fff;background-color:#1b1e21;border-color:#1b1e21}.close{float:right;font-size:1.5rem;font-weight:700;line-height:1;color:#000;text-shadow:0 1px 0 #fff;opacity:.5}.close:hover{color:#000;text-decoration:none}.close:not(:disabled):not(.disabled):focus,.close:not(:disabled):not(.disabled):hover{opacity:.75}button.close{padding:0;background-color:transparent;border:0;-webkit-appearance:none;-moz-appearance:none;appearance:none}a.close.disabled{pointer-events:none}.toast{max-width:350px;overflow:hidden;font-size:.875rem;background-color:rgba(255,255,255,.85);background-clip:padding-box;border:1px solid rgba(0,0,0,.1);box-shadow:0 .25rem .75rem rgba(0,0,0,.1);-webkit-backdrop-filter:blur(10px);backdrop-filter:blur(10px);opacity:0;border-radius:.25rem}.toast:not(:last-child){margin-bottom:.75rem}.toast.showing{opacity:1}.toast.show{display:block;opacity:1}.toast.hide{display:none}.toast-header{display:-ms-flexbox;display:flex;-ms-flex-align:center;align-items:center;padding:.25rem .75rem;color:#6c757d;background-color:rgba(255,255,255,.85);background-clip:padding-box;border-bottom:1px solid rgba(0,0,0,.05)}.toast-body{padding:.75rem}.modal-open{overflow:hidden}.modal-open .modal{overflow-x:hidden;overflow-y:auto}.modal{position:fixed;top:0;left:0;z-index:1050;display:none;width:100%;height:100%;overflow:hidden;outline:0}.modal-dialog{position:relative;width:auto;margin:.5rem;pointer-events:none}.modal.fade .modal-dialog{transition:-webkit-transform .3s ease-out;transition:transform .3s ease-out;transition:transform .3s ease-out,-webkit-transform .3s ease-out;-webkit-transform:translate(0,-50px);transform:translate(0,-50px)}@media (prefers-reduced-motion:reduce){.modal.fade .modal-dialog{transition:none}}.modal.show .modal-dialog{-webkit-transform:none;transform:none}.modal.modal-static .modal-dialog{-webkit-transform:scale(1.02);transform:scale(1.02)}.modal-dialog-scrollable{display:-ms-flexbox;display:flex;max-height:calc(100% - 1rem)}.modal-dialog-scrollable .modal-content{max-height:calc(100vh - 1rem);overflow:hidden}.modal-dialog-scrollable .modal-footer,.modal-dialog-scrollable .modal-header{-ms-flex-negative:0;flex-shrink:0}.modal-dialog-scrollable .modal-body{overflow-y:auto}.modal-dialog-centered{display:-ms-flexbox;display:flex;-ms-flex-align:center;align-items:center;min-height:calc(100% - 1rem)}.modal-dialog-centered::before{display:block;height:calc(100vh - 1rem);content:\\\"\\\"}.modal-dialog-centered.modal-dialog-scrollable{-ms-flex-direction:column;flex-direction:column;-ms-flex-pack:center;justify-content:center;height:100%}.modal-dialog-centered.modal-dialog-scrollable .modal-content{max-height:none}.modal-dialog-centered.modal-dialog-scrollable::before{content:none}.modal-content{position:relative;display:-ms-flexbox;display:flex;-ms-flex-direction:column;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}.modal-backdrop{position:fixed;top:0;left:0;z-index:1040;width:100vw;height:100vh;background-color:#000}.modal-backdrop.fade{opacity:0}.modal-backdrop.show{opacity:.5}.modal-header{display:-ms-flexbox;display:flex;-ms-flex-align:start;align-items:flex-start;-ms-flex-pack:justify;justify-content:space-between;padding:1rem 1rem;border-bottom:1px solid #dee2e6;border-top-left-radius:calc(.3rem - 1px);border-top-right-radius:calc(.3rem - 1px)}.modal-header .close{padding:1rem 1rem;margin:-1rem -1rem -1rem auto}.modal-title{margin-bottom:0;line-height:1.5}.modal-body{position:relative;-ms-flex:1 1 auto;flex:1 1 auto;padding:1rem}.modal-footer{display:-ms-flexbox;display:flex;-ms-flex-wrap:wrap;flex-wrap:wrap;-ms-flex-align:center;align-items:center;-ms-flex-pack:end;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)}.modal-footer>*{margin:.25rem}.modal-scrollbar-measure{position:absolute;top:-9999px;width:50px;height:50px;overflow:scroll}@media (min-width:576px){.modal-dialog{max-width:500px;margin:1.75rem auto}.modal-dialog-scrollable{max-height:calc(100% - 3.5rem)}.modal-dialog-scrollable .modal-content{max-height:calc(100vh - 3.5rem)}.modal-dialog-centered{min-height:calc(100% - 3.5rem)}.modal-dialog-centered::before{height:calc(100vh - 3.5rem)}.modal-sm{max-width:300px}}@media (min-width:992px){.modal-lg,.modal-xl{max-width:800px}}@media (min-width:1200px){.modal-xl{max-width:1140px}}.tooltip{position:absolute;z-index:1070;display:block;margin: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-style:normal;font-weight:400;line-height:1.5;text-align:left;text-align:start;text-decoration:none;text-shadow:none;text-transform:none;letter-spacing:normal;word-break:normal;word-spacing:normal;white-space:normal;line-break:auto;font-size:.875rem;word-wrap:break-word;opacity:0}.tooltip.show{opacity:.9}.tooltip .arrow{position:absolute;display:block;width:.8rem;height:.4rem}.tooltip .arrow::before{position:absolute;content:\\\"\\\";border-color:transparent;border-style:solid}.bs-tooltip-auto[x-placement^=top],.bs-tooltip-top{padding:.4rem 0}.bs-tooltip-auto[x-placement^=top] .arrow,.bs-tooltip-top .arrow{bottom:0}.bs-tooltip-auto[x-placement^=top] .arrow::before,.bs-tooltip-top .arrow::before{top:0;border-width:.4rem .4rem 0;border-top-color:#000}.bs-tooltip-auto[x-placement^=right],.bs-tooltip-right{padding:0 .4rem}.bs-tooltip-auto[x-placement^=right] .arrow,.bs-tooltip-right .arrow{left:0;width:.4rem;height:.8rem}.bs-tooltip-auto[x-placement^=right] .arrow::before,.bs-tooltip-right .arrow::before{right:0;border-width:.4rem .4rem .4rem 0;border-right-color:#000}.bs-tooltip-auto[x-placement^=bottom],.bs-tooltip-bottom{padding:.4rem 0}.bs-tooltip-auto[x-placement^=bottom] .arrow,.bs-tooltip-bottom .arrow{top:0}.bs-tooltip-auto[x-placement^=bottom] .arrow::before,.bs-tooltip-bottom .arrow::before{bottom:0;border-width:0 .4rem .4rem;border-bottom-color:#000}.bs-tooltip-auto[x-placement^=left],.bs-tooltip-left{padding:0 .4rem}.bs-tooltip-auto[x-placement^=left] .arrow,.bs-tooltip-left .arrow{right:0;width:.4rem;height:.8rem}.bs-tooltip-auto[x-placement^=left] .arrow::before,.bs-tooltip-left .arrow::before{left:0;border-width:.4rem 0 .4rem .4rem;border-left-color:#000}.tooltip-inner{max-width:200px;padding:.25rem .5rem;color:#fff;text-align:center;background-color:#000;border-radius:.25rem}.popover{position:absolute;top:0;left:0;z-index:1060;display:block;max-width:276px;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-style:normal;font-weight:400;line-height:1.5;text-align:left;text-align:start;text-decoration:none;text-shadow:none;text-transform:none;letter-spacing:normal;word-break:normal;word-spacing:normal;white-space:normal;line-break:auto;font-size:.875rem;word-wrap:break-word;background-color:#fff;background-clip:padding-box;border:1px solid rgba(0,0,0,.2);border-radius:.3rem}.popover .arrow{position:absolute;display:block;width:1rem;height:.5rem;margin:0 .3rem}.popover .arrow::after,.popover .arrow::before{position:absolute;display:block;content:\\\"\\\";border-color:transparent;border-style:solid}.bs-popover-auto[x-placement^=top],.bs-popover-top{margin-bottom:.5rem}.bs-popover-auto[x-placement^=top]>.arrow,.bs-popover-top>.arrow{bottom:calc(-.5rem - 1px)}.bs-popover-auto[x-placement^=top]>.arrow::before,.bs-popover-top>.arrow::before{bottom:0;border-width:.5rem .5rem 0;border-top-color:rgba(0,0,0,.25)}.bs-popover-auto[x-placement^=top]>.arrow::after,.bs-popover-top>.arrow::after{bottom:1px;border-width:.5rem .5rem 0;border-top-color:#fff}.bs-popover-auto[x-placement^=right],.bs-popover-right{margin-left:.5rem}.bs-popover-auto[x-placement^=right]>.arrow,.bs-popover-right>.arrow{left:calc(-.5rem - 1px);width:.5rem;height:1rem;margin:.3rem 0}.bs-popover-auto[x-placement^=right]>.arrow::before,.bs-popover-right>.arrow::before{left:0;border-width:.5rem .5rem .5rem 0;border-right-color:rgba(0,0,0,.25)}.bs-popover-auto[x-placement^=right]>.arrow::after,.bs-popover-right>.arrow::after{left:1px;border-width:.5rem .5rem .5rem 0;border-right-color:#fff}.bs-popover-auto[x-placement^=bottom],.bs-popover-bottom{margin-top:.5rem}.bs-popover-auto[x-placement^=bottom]>.arrow,.bs-popover-bottom>.arrow{top:calc(-.5rem - 1px)}.bs-popover-auto[x-placement^=bottom]>.arrow::before,.bs-popover-bottom>.arrow::before{top:0;border-width:0 .5rem .5rem .5rem;border-bottom-color:rgba(0,0,0,.25)}.bs-popover-auto[x-placement^=bottom]>.arrow::after,.bs-popover-bottom>.arrow::after{top:1px;border-width:0 .5rem .5rem .5rem;border-bottom-color:#fff}.bs-popover-auto[x-placement^=bottom] .popover-header::before,.bs-popover-bottom .popover-header::before{position:absolute;top:0;left:50%;display:block;width:1rem;margin-left:-.5rem;content:\\\"\\\";border-bottom:1px solid #f7f7f7}.bs-popover-auto[x-placement^=left],.bs-popover-left{margin-right:.5rem}.bs-popover-auto[x-placement^=left]>.arrow,.bs-popover-left>.arrow{right:calc(-.5rem - 1px);width:.5rem;height:1rem;margin:.3rem 0}.bs-popover-auto[x-placement^=left]>.arrow::before,.bs-popover-left>.arrow::before{right:0;border-width:.5rem 0 .5rem .5rem;border-left-color:rgba(0,0,0,.25)}.bs-popover-auto[x-placement^=left]>.arrow::after,.bs-popover-left>.arrow::after{right:1px;border-width:.5rem 0 .5rem .5rem;border-left-color:#fff}.popover-header{padding:.5rem .75rem;margin-bottom:0;font-size:1rem;background-color:#f7f7f7;border-bottom:1px solid #ebebeb;border-top-left-radius:calc(.3rem - 1px);border-top-right-radius:calc(.3rem - 1px)}.popover-header:empty{display:none}.popover-body{padding:.5rem .75rem;color:#212529}.carousel{position:relative}.carousel.pointer-event{-ms-touch-action:pan-y;touch-action:pan-y}.carousel-inner{position:relative;width:100%;overflow:hidden}.carousel-inner::after{display:block;clear:both;content:\\\"\\\"}.carousel-item{position:relative;display:none;float:left;width:100%;margin-right:-100%;-webkit-backface-visibility:hidden;backface-visibility:hidden;transition:-webkit-transform .6s ease-in-out;transition:transform .6s ease-in-out;transition:transform .6s ease-in-out,-webkit-transform .6s ease-in-out}@media (prefers-reduced-motion:reduce){.carousel-item{transition:none}}.carousel-item-next,.carousel-item-prev,.carousel-item.active{display:block}.active.carousel-item-right,.carousel-item-next:not(.carousel-item-left){-webkit-transform:translateX(100%);transform:translateX(100%)}.active.carousel-item-left,.carousel-item-prev:not(.carousel-item-right){-webkit-transform:translateX(-100%);transform:translateX(-100%)}.carousel-fade .carousel-item{opacity:0;transition-property:opacity;-webkit-transform:none;transform:none}.carousel-fade .carousel-item-next.carousel-item-left,.carousel-fade .carousel-item-prev.carousel-item-right,.carousel-fade .carousel-item.active{z-index:1;opacity:1}.carousel-fade .active.carousel-item-left,.carousel-fade .active.carousel-item-right{z-index:0;opacity:0;transition:opacity 0s .6s}@media (prefers-reduced-motion:reduce){.carousel-fade .active.carousel-item-left,.carousel-fade .active.carousel-item-right{transition:none}}.carousel-control-next,.carousel-control-prev{position:absolute;top:0;bottom:0;z-index:1;display:-ms-flexbox;display:flex;-ms-flex-align:center;align-items:center;-ms-flex-pack:center;justify-content:center;width:15%;color:#fff;text-align:center;opacity:.5;transition:opacity .15s ease}@media (prefers-reduced-motion:reduce){.carousel-control-next,.carousel-control-prev{transition:none}}.carousel-control-next:focus,.carousel-control-next:hover,.carousel-control-prev:focus,.carousel-control-prev:hover{color:#fff;text-decoration:none;outline:0;opacity:.9}.carousel-control-prev{left:0}.carousel-control-next{right:0}.carousel-control-next-icon,.carousel-control-prev-icon{display:inline-block;width:20px;height:20px;background:no-repeat 50%/100% 100%}.carousel-control-prev-icon{background-image:url(\\\"data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' fill='%23fff' width='8' height='8' viewBox='0 0 8 8'%3e%3cpath d='M5.25 0l-4 4 4 4 1.5-1.5L4.25 4l2.5-2.5L5.25 0z'/%3e%3c/svg%3e\\\")}.carousel-control-next-icon{background-image:url(\\\"data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' fill='%23fff' width='8' height='8' viewBox='0 0 8 8'%3e%3cpath d='M2.75 0l-1.5 1.5L3.75 4l-2.5 2.5L2.75 8l4-4-4-4z'/%3e%3c/svg%3e\\\")}.carousel-indicators{position:absolute;right:0;bottom:0;left:0;z-index:15;display:-ms-flexbox;display:flex;-ms-flex-pack:center;justify-content:center;padding-left:0;margin-right:15%;margin-left:15%;list-style:none}.carousel-indicators li{box-sizing:content-box;-ms-flex:0 1 auto;flex:0 1 auto;width:30px;height:3px;margin-right:3px;margin-left:3px;text-indent:-999px;cursor:pointer;background-color:#fff;background-clip:padding-box;border-top:10px solid transparent;border-bottom:10px solid transparent;opacity:.5;transition:opacity .6s ease}@media (prefers-reduced-motion:reduce){.carousel-indicators li{transition:none}}.carousel-indicators .active{opacity:1}.carousel-caption{position:absolute;right:15%;bottom:20px;left:15%;z-index:10;padding-top:20px;padding-bottom:20px;color:#fff;text-align:center}@-webkit-keyframes spinner-border{to{-webkit-transform:rotate(360deg);transform:rotate(360deg)}}@keyframes spinner-border{to{-webkit-transform:rotate(360deg);transform:rotate(360deg)}}.spinner-border{display:inline-block;width:2rem;height:2rem;vertical-align:text-bottom;border:.25em solid currentColor;border-right-color:transparent;border-radius:50%;-webkit-animation:spinner-border .75s linear infinite;animation:spinner-border .75s linear infinite}.spinner-border-sm{width:1rem;height:1rem;border-width:.2em}@-webkit-keyframes spinner-grow{0%{-webkit-transform:scale(0);transform:scale(0)}50%{opacity:1}}@keyframes spinner-grow{0%{-webkit-transform:scale(0);transform:scale(0)}50%{opacity:1}}.spinner-grow{display:inline-block;width:2rem;height:2rem;vertical-align:text-bottom;background-color:currentColor;border-radius:50%;opacity:0;-webkit-animation:spinner-grow .75s linear infinite;animation:spinner-grow .75s linear infinite}.spinner-grow-sm{width:1rem;height:1rem}.align-baseline{vertical-align:baseline!important}.align-top{vertical-align:top!important}.align-middle{vertical-align:middle!important}.align-bottom{vertical-align:bottom!important}.align-text-bottom{vertical-align:text-bottom!important}.align-text-top{vertical-align:text-top!important}.bg-primary{background-color:#007bff!important}a.bg-primary:focus,a.bg-primary:hover,button.bg-primary:focus,button.bg-primary:hover{background-color:#0062cc!important}.bg-secondary{background-color:#6c757d!important}a.bg-secondary:focus,a.bg-secondary:hover,button.bg-secondary:focus,button.bg-secondary:hover{background-color:#545b62!important}.bg-success{background-color:#28a745!important}a.bg-success:focus,a.bg-success:hover,button.bg-success:focus,button.bg-success:hover{background-color:#1e7e34!important}.bg-info{background-color:#17a2b8!important}a.bg-info:focus,a.bg-info:hover,button.bg-info:focus,button.bg-info:hover{background-color:#117a8b!important}.bg-warning{background-color:#ffc107!important}a.bg-warning:focus,a.bg-warning:hover,button.bg-warning:focus,button.bg-warning:hover{background-color:#d39e00!important}.bg-danger{background-color:#dc3545!important}a.bg-danger:focus,a.bg-danger:hover,button.bg-danger:focus,button.bg-danger:hover{background-color:#bd2130!important}.bg-light{background-color:#f8f9fa!important}a.bg-light:focus,a.bg-light:hover,button.bg-light:focus,button.bg-light:hover{background-color:#dae0e5!important}.bg-dark{background-color:#343a40!important}a.bg-dark:focus,a.bg-dark:hover,button.bg-dark:focus,button.bg-dark:hover{background-color:#1d2124!important}.bg-white{background-color:#fff!important}.bg-transparent{background-color:transparent!important}.border{border:1px solid #dee2e6!important}.border-top{border-top:1px solid #dee2e6!important}.border-right{border-right:1px solid #dee2e6!important}.border-bottom{border-bottom:1px solid #dee2e6!important}.border-left{border-left:1px solid #dee2e6!important}.border-0{border:0!important}.border-top-0{border-top:0!important}.border-right-0{border-right:0!important}.border-bottom-0{border-bottom:0!important}.border-left-0{border-left:0!important}.border-primary{border-color:#007bff!important}.border-secondary{border-color:#6c757d!important}.border-success{border-color:#28a745!important}.border-info{border-color:#17a2b8!important}.border-warning{border-color:#ffc107!important}.border-danger{border-color:#dc3545!important}.border-light{border-color:#f8f9fa!important}.border-dark{border-color:#343a40!important}.border-white{border-color:#fff!important}.rounded-sm{border-radius:.2rem!important}.rounded{border-radius:.25rem!important}.rounded-top{border-top-left-radius:.25rem!important;border-top-right-radius:.25rem!important}.rounded-right{border-top-right-radius:.25rem!important;border-bottom-right-radius:.25rem!important}.rounded-bottom{border-bottom-right-radius:.25rem!important;border-bottom-left-radius:.25rem!important}.rounded-left{border-top-left-radius:.25rem!important;border-bottom-left-radius:.25rem!important}.rounded-lg{border-radius:.3rem!important}.rounded-circle{border-radius:50%!important}.rounded-pill{border-radius:50rem!important}.rounded-0{border-radius:0!important}.clearfix::after{display:block;clear:both;content:\\\"\\\"}.d-none{display:none!important}.d-inline{display:inline!important}.d-inline-block{display:inline-block!important}.d-block{display:block!important}.d-table{display:table!important}.d-table-row{display:table-row!important}.d-table-cell{display:table-cell!important}.d-flex{display:-ms-flexbox!important;display:flex!important}.d-inline-flex{display:-ms-inline-flexbox!important;display:inline-flex!important}@media (min-width:576px){.d-sm-none{display:none!important}.d-sm-inline{display:inline!important}.d-sm-inline-block{display:inline-block!important}.d-sm-block{display:block!important}.d-sm-table{display:table!important}.d-sm-table-row{display:table-row!important}.d-sm-table-cell{display:table-cell!important}.d-sm-flex{display:-ms-flexbox!important;display:flex!important}.d-sm-inline-flex{display:-ms-inline-flexbox!important;display:inline-flex!important}}@media (min-width:768px){.d-md-none{display:none!important}.d-md-inline{display:inline!important}.d-md-inline-block{display:inline-block!important}.d-md-block{display:block!important}.d-md-table{display:table!important}.d-md-table-row{display:table-row!important}.d-md-table-cell{display:table-cell!important}.d-md-flex{display:-ms-flexbox!important;display:flex!important}.d-md-inline-flex{display:-ms-inline-flexbox!important;display:inline-flex!important}}@media (min-width:992px){.d-lg-none{display:none!important}.d-lg-inline{display:inline!important}.d-lg-inline-block{display:inline-block!important}.d-lg-block{display:block!important}.d-lg-table{display:table!important}.d-lg-table-row{display:table-row!important}.d-lg-table-cell{display:table-cell!important}.d-lg-flex{display:-ms-flexbox!important;display:flex!important}.d-lg-inline-flex{display:-ms-inline-flexbox!important;display:inline-flex!important}}@media (min-width:1200px){.d-xl-none{display:none!important}.d-xl-inline{display:inline!important}.d-xl-inline-block{display:inline-block!important}.d-xl-block{display:block!important}.d-xl-table{display:table!important}.d-xl-table-row{display:table-row!important}.d-xl-table-cell{display:table-cell!important}.d-xl-flex{display:-ms-flexbox!important;display:flex!important}.d-xl-inline-flex{display:-ms-inline-flexbox!important;display:inline-flex!important}}@media print{.d-print-none{display:none!important}.d-print-inline{display:inline!important}.d-print-inline-block{display:inline-block!important}.d-print-block{display:block!important}.d-print-table{display:table!important}.d-print-table-row{display:table-row!important}.d-print-table-cell{display:table-cell!important}.d-print-flex{display:-ms-flexbox!important;display:flex!important}.d-print-inline-flex{display:-ms-inline-flexbox!important;display:inline-flex!important}}.embed-responsive{position:relative;display:block;width:100%;padding:0;overflow:hidden}.embed-responsive::before{display:block;content:\\\"\\\"}.embed-responsive .embed-responsive-item,.embed-responsive embed,.embed-responsive iframe,.embed-responsive object,.embed-responsive video{position:absolute;top:0;bottom:0;left:0;width:100%;height:100%;border:0}.embed-responsive-21by9::before{padding-top:42.857143%}.embed-responsive-16by9::before{padding-top:56.25%}.embed-responsive-4by3::before{padding-top:75%}.embed-responsive-1by1::before{padding-top:100%}.flex-row{-ms-flex-direction:row!important;flex-direction:row!important}.flex-column{-ms-flex-direction:column!important;flex-direction:column!important}.flex-row-reverse{-ms-flex-direction:row-reverse!important;flex-direction:row-reverse!important}.flex-column-reverse{-ms-flex-direction:column-reverse!important;flex-direction:column-reverse!important}.flex-wrap{-ms-flex-wrap:wrap!important;flex-wrap:wrap!important}.flex-nowrap{-ms-flex-wrap:nowrap!important;flex-wrap:nowrap!important}.flex-wrap-reverse{-ms-flex-wrap:wrap-reverse!important;flex-wrap:wrap-reverse!important}.flex-fill{-ms-flex:1 1 auto!important;flex:1 1 auto!important}.flex-grow-0{-ms-flex-positive:0!important;flex-grow:0!important}.flex-grow-1{-ms-flex-positive:1!important;flex-grow:1!important}.flex-shrink-0{-ms-flex-negative:0!important;flex-shrink:0!important}.flex-shrink-1{-ms-flex-negative:1!important;flex-shrink:1!important}.justify-content-start{-ms-flex-pack:start!important;justify-content:flex-start!important}.justify-content-end{-ms-flex-pack:end!important;justify-content:flex-end!important}.justify-content-center{-ms-flex-pack:center!important;justify-content:center!important}.justify-content-between{-ms-flex-pack:justify!important;justify-content:space-between!important}.justify-content-around{-ms-flex-pack:distribute!important;justify-content:space-around!important}.align-items-start{-ms-flex-align:start!important;align-items:flex-start!important}.align-items-end{-ms-flex-align:end!important;align-items:flex-end!important}.align-items-center{-ms-flex-align:center!important;align-items:center!important}.align-items-baseline{-ms-flex-align:baseline!important;align-items:baseline!important}.align-items-stretch{-ms-flex-align:stretch!important;align-items:stretch!important}.align-content-start{-ms-flex-line-pack:start!important;align-content:flex-start!important}.align-content-end{-ms-flex-line-pack:end!important;align-content:flex-end!important}.align-content-center{-ms-flex-line-pack:center!important;align-content:center!important}.align-content-between{-ms-flex-line-pack:justify!important;align-content:space-between!important}.align-content-around{-ms-flex-line-pack:distribute!important;align-content:space-around!important}.align-content-stretch{-ms-flex-line-pack:stretch!important;align-content:stretch!important}.align-self-auto{-ms-flex-item-align:auto!important;align-self:auto!important}.align-self-start{-ms-flex-item-align:start!important;align-self:flex-start!important}.align-self-end{-ms-flex-item-align:end!important;align-self:flex-end!important}.align-self-center{-ms-flex-item-align:center!important;align-self:center!important}.align-self-baseline{-ms-flex-item-align:baseline!important;align-self:baseline!important}.align-self-stretch{-ms-flex-item-align:stretch!important;align-self:stretch!important}@media (min-width:576px){.flex-sm-row{-ms-flex-direction:row!important;flex-direction:row!important}.flex-sm-column{-ms-flex-direction:column!important;flex-direction:column!important}.flex-sm-row-reverse{-ms-flex-direction:row-reverse!important;flex-direction:row-reverse!important}.flex-sm-column-reverse{-ms-flex-direction:column-reverse!important;flex-direction:column-reverse!important}.flex-sm-wrap{-ms-flex-wrap:wrap!important;flex-wrap:wrap!important}.flex-sm-nowrap{-ms-flex-wrap:nowrap!important;flex-wrap:nowrap!important}.flex-sm-wrap-reverse{-ms-flex-wrap:wrap-reverse!important;flex-wrap:wrap-reverse!important}.flex-sm-fill{-ms-flex:1 1 auto!important;flex:1 1 auto!important}.flex-sm-grow-0{-ms-flex-positive:0!important;flex-grow:0!important}.flex-sm-grow-1{-ms-flex-positive:1!important;flex-grow:1!important}.flex-sm-shrink-0{-ms-flex-negative:0!important;flex-shrink:0!important}.flex-sm-shrink-1{-ms-flex-negative:1!important;flex-shrink:1!important}.justify-content-sm-start{-ms-flex-pack:start!important;justify-content:flex-start!important}.justify-content-sm-end{-ms-flex-pack:end!important;justify-content:flex-end!important}.justify-content-sm-center{-ms-flex-pack:center!important;justify-content:center!important}.justify-content-sm-between{-ms-flex-pack:justify!important;justify-content:space-between!important}.justify-content-sm-around{-ms-flex-pack:distribute!important;justify-content:space-around!important}.align-items-sm-start{-ms-flex-align:start!important;align-items:flex-start!important}.align-items-sm-end{-ms-flex-align:end!important;align-items:flex-end!important}.align-items-sm-center{-ms-flex-align:center!important;align-items:center!important}.align-items-sm-baseline{-ms-flex-align:baseline!important;align-items:baseline!important}.align-items-sm-stretch{-ms-flex-align:stretch!important;align-items:stretch!important}.align-content-sm-start{-ms-flex-line-pack:start!important;align-content:flex-start!important}.align-content-sm-end{-ms-flex-line-pack:end!important;align-content:flex-end!important}.align-content-sm-center{-ms-flex-line-pack:center!important;align-content:center!important}.align-content-sm-between{-ms-flex-line-pack:justify!important;align-content:space-between!important}.align-content-sm-around{-ms-flex-line-pack:distribute!important;align-content:space-around!important}.align-content-sm-stretch{-ms-flex-line-pack:stretch!important;align-content:stretch!important}.align-self-sm-auto{-ms-flex-item-align:auto!important;align-self:auto!important}.align-self-sm-start{-ms-flex-item-align:start!important;align-self:flex-start!important}.align-self-sm-end{-ms-flex-item-align:end!important;align-self:flex-end!important}.align-self-sm-center{-ms-flex-item-align:center!important;align-self:center!important}.align-self-sm-baseline{-ms-flex-item-align:baseline!important;align-self:baseline!important}.align-self-sm-stretch{-ms-flex-item-align:stretch!important;align-self:stretch!important}}@media (min-width:768px){.flex-md-row{-ms-flex-direction:row!important;flex-direction:row!important}.flex-md-column{-ms-flex-direction:column!important;flex-direction:column!important}.flex-md-row-reverse{-ms-flex-direction:row-reverse!important;flex-direction:row-reverse!important}.flex-md-column-reverse{-ms-flex-direction:column-reverse!important;flex-direction:column-reverse!important}.flex-md-wrap{-ms-flex-wrap:wrap!important;flex-wrap:wrap!important}.flex-md-nowrap{-ms-flex-wrap:nowrap!important;flex-wrap:nowrap!important}.flex-md-wrap-reverse{-ms-flex-wrap:wrap-reverse!important;flex-wrap:wrap-reverse!important}.flex-md-fill{-ms-flex:1 1 auto!important;flex:1 1 auto!important}.flex-md-grow-0{-ms-flex-positive:0!important;flex-grow:0!important}.flex-md-grow-1{-ms-flex-positive:1!important;flex-grow:1!important}.flex-md-shrink-0{-ms-flex-negative:0!important;flex-shrink:0!important}.flex-md-shrink-1{-ms-flex-negative:1!important;flex-shrink:1!important}.justify-content-md-start{-ms-flex-pack:start!important;justify-content:flex-start!important}.justify-content-md-end{-ms-flex-pack:end!important;justify-content:flex-end!important}.justify-content-md-center{-ms-flex-pack:center!important;justify-content:center!important}.justify-content-md-between{-ms-flex-pack:justify!important;justify-content:space-between!important}.justify-content-md-around{-ms-flex-pack:distribute!important;justify-content:space-around!important}.align-items-md-start{-ms-flex-align:start!important;align-items:flex-start!important}.align-items-md-end{-ms-flex-align:end!important;align-items:flex-end!important}.align-items-md-center{-ms-flex-align:center!important;align-items:center!important}.align-items-md-baseline{-ms-flex-align:baseline!important;align-items:baseline!important}.align-items-md-stretch{-ms-flex-align:stretch!important;align-items:stretch!important}.align-content-md-start{-ms-flex-line-pack:start!important;align-content:flex-start!important}.align-content-md-end{-ms-flex-line-pack:end!important;align-content:flex-end!important}.align-content-md-center{-ms-flex-line-pack:center!important;align-content:center!important}.align-content-md-between{-ms-flex-line-pack:justify!important;align-content:space-between!important}.align-content-md-around{-ms-flex-line-pack:distribute!important;align-content:space-around!important}.align-content-md-stretch{-ms-flex-line-pack:stretch!important;align-content:stretch!important}.align-self-md-auto{-ms-flex-item-align:auto!important;align-self:auto!important}.align-self-md-start{-ms-flex-item-align:start!important;align-self:flex-start!important}.align-self-md-end{-ms-flex-item-align:end!important;align-self:flex-end!important}.align-self-md-center{-ms-flex-item-align:center!important;align-self:center!important}.align-self-md-baseline{-ms-flex-item-align:baseline!important;align-self:baseline!important}.align-self-md-stretch{-ms-flex-item-align:stretch!important;align-self:stretch!important}}@media (min-width:992px){.flex-lg-row{-ms-flex-direction:row!important;flex-direction:row!important}.flex-lg-column{-ms-flex-direction:column!important;flex-direction:column!important}.flex-lg-row-reverse{-ms-flex-direction:row-reverse!important;flex-direction:row-reverse!important}.flex-lg-column-reverse{-ms-flex-direction:column-reverse!important;flex-direction:column-reverse!important}.flex-lg-wrap{-ms-flex-wrap:wrap!important;flex-wrap:wrap!important}.flex-lg-nowrap{-ms-flex-wrap:nowrap!important;flex-wrap:nowrap!important}.flex-lg-wrap-reverse{-ms-flex-wrap:wrap-reverse!important;flex-wrap:wrap-reverse!important}.flex-lg-fill{-ms-flex:1 1 auto!important;flex:1 1 auto!important}.flex-lg-grow-0{-ms-flex-positive:0!important;flex-grow:0!important}.flex-lg-grow-1{-ms-flex-positive:1!important;flex-grow:1!important}.flex-lg-shrink-0{-ms-flex-negative:0!important;flex-shrink:0!important}.flex-lg-shrink-1{-ms-flex-negative:1!important;flex-shrink:1!important}.justify-content-lg-start{-ms-flex-pack:start!important;justify-content:flex-start!important}.justify-content-lg-end{-ms-flex-pack:end!important;justify-content:flex-end!important}.justify-content-lg-center{-ms-flex-pack:center!important;justify-content:center!important}.justify-content-lg-between{-ms-flex-pack:justify!important;justify-content:space-between!important}.justify-content-lg-around{-ms-flex-pack:distribute!important;justify-content:space-around!important}.align-items-lg-start{-ms-flex-align:start!important;align-items:flex-start!important}.align-items-lg-end{-ms-flex-align:end!important;align-items:flex-end!important}.align-items-lg-center{-ms-flex-align:center!important;align-items:center!important}.align-items-lg-baseline{-ms-flex-align:baseline!important;align-items:baseline!important}.align-items-lg-stretch{-ms-flex-align:stretch!important;align-items:stretch!important}.align-content-lg-start{-ms-flex-line-pack:start!important;align-content:flex-start!important}.align-content-lg-end{-ms-flex-line-pack:end!important;align-content:flex-end!important}.align-content-lg-center{-ms-flex-line-pack:center!important;align-content:center!important}.align-content-lg-between{-ms-flex-line-pack:justify!important;align-content:space-between!important}.align-content-lg-around{-ms-flex-line-pack:distribute!important;align-content:space-around!important}.align-content-lg-stretch{-ms-flex-line-pack:stretch!important;align-content:stretch!important}.align-self-lg-auto{-ms-flex-item-align:auto!important;align-self:auto!important}.align-self-lg-start{-ms-flex-item-align:start!important;align-self:flex-start!important}.align-self-lg-end{-ms-flex-item-align:end!important;align-self:flex-end!important}.align-self-lg-center{-ms-flex-item-align:center!important;align-self:center!important}.align-self-lg-baseline{-ms-flex-item-align:baseline!important;align-self:baseline!important}.align-self-lg-stretch{-ms-flex-item-align:stretch!important;align-self:stretch!important}}@media (min-width:1200px){.flex-xl-row{-ms-flex-direction:row!important;flex-direction:row!important}.flex-xl-column{-ms-flex-direction:column!important;flex-direction:column!important}.flex-xl-row-reverse{-ms-flex-direction:row-reverse!important;flex-direction:row-reverse!important}.flex-xl-column-reverse{-ms-flex-direction:column-reverse!important;flex-direction:column-reverse!important}.flex-xl-wrap{-ms-flex-wrap:wrap!important;flex-wrap:wrap!important}.flex-xl-nowrap{-ms-flex-wrap:nowrap!important;flex-wrap:nowrap!important}.flex-xl-wrap-reverse{-ms-flex-wrap:wrap-reverse!important;flex-wrap:wrap-reverse!important}.flex-xl-fill{-ms-flex:1 1 auto!important;flex:1 1 auto!important}.flex-xl-grow-0{-ms-flex-positive:0!important;flex-grow:0!important}.flex-xl-grow-1{-ms-flex-positive:1!important;flex-grow:1!important}.flex-xl-shrink-0{-ms-flex-negative:0!important;flex-shrink:0!important}.flex-xl-shrink-1{-ms-flex-negative:1!important;flex-shrink:1!important}.justify-content-xl-start{-ms-flex-pack:start!important;justify-content:flex-start!important}.justify-content-xl-end{-ms-flex-pack:end!important;justify-content:flex-end!important}.justify-content-xl-center{-ms-flex-pack:center!important;justify-content:center!important}.justify-content-xl-between{-ms-flex-pack:justify!important;justify-content:space-between!important}.justify-content-xl-around{-ms-flex-pack:distribute!important;justify-content:space-around!important}.align-items-xl-start{-ms-flex-align:start!important;align-items:flex-start!important}.align-items-xl-end{-ms-flex-align:end!important;align-items:flex-end!important}.align-items-xl-center{-ms-flex-align:center!important;align-items:center!important}.align-items-xl-baseline{-ms-flex-align:baseline!important;align-items:baseline!important}.align-items-xl-stretch{-ms-flex-align:stretch!important;align-items:stretch!important}.align-content-xl-start{-ms-flex-line-pack:start!important;align-content:flex-start!important}.align-content-xl-end{-ms-flex-line-pack:end!important;align-content:flex-end!important}.align-content-xl-center{-ms-flex-line-pack:center!important;align-content:center!important}.align-content-xl-between{-ms-flex-line-pack:justify!important;align-content:space-between!important}.align-content-xl-around{-ms-flex-line-pack:distribute!important;align-content:space-around!important}.align-content-xl-stretch{-ms-flex-line-pack:stretch!important;align-content:stretch!important}.align-self-xl-auto{-ms-flex-item-align:auto!important;align-self:auto!important}.align-self-xl-start{-ms-flex-item-align:start!important;align-self:flex-start!important}.align-self-xl-end{-ms-flex-item-align:end!important;align-self:flex-end!important}.align-self-xl-center{-ms-flex-item-align:center!important;align-self:center!important}.align-self-xl-baseline{-ms-flex-item-align:baseline!important;align-self:baseline!important}.align-self-xl-stretch{-ms-flex-item-align:stretch!important;align-self:stretch!important}}.float-left{float:left!important}.float-right{float:right!important}.float-none{float:none!important}@media (min-width:576px){.float-sm-left{float:left!important}.float-sm-right{float:right!important}.float-sm-none{float:none!important}}@media (min-width:768px){.float-md-left{float:left!important}.float-md-right{float:right!important}.float-md-none{float:none!important}}@media (min-width:992px){.float-lg-left{float:left!important}.float-lg-right{float:right!important}.float-lg-none{float:none!important}}@media (min-width:1200px){.float-xl-left{float:left!important}.float-xl-right{float:right!important}.float-xl-none{float:none!important}}.overflow-auto{overflow:auto!important}.overflow-hidden{overflow:hidden!important}.position-static{position:static!important}.position-relative{position:relative!important}.position-absolute{position:absolute!important}.position-fixed{position:fixed!important}.position-sticky{position:-webkit-sticky!important;position:sticky!important}.fixed-top{position:fixed;top:0;right:0;left:0;z-index:1030}.fixed-bottom{position:fixed;right:0;bottom:0;left:0;z-index:1030}@supports ((position:-webkit-sticky) or (position:sticky)){.sticky-top{position:-webkit-sticky;position:sticky;top:0;z-index:1020}}.sr-only{position:absolute;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip:rect(0,0,0,0);white-space:nowrap;border:0}.sr-only-focusable:active,.sr-only-focusable:focus{position:static;width:auto;height:auto;overflow:visible;clip:auto;white-space:normal}.shadow-sm{box-shadow:0 .125rem .25rem rgba(0,0,0,.075)!important}.shadow{box-shadow:0 .5rem 1rem rgba(0,0,0,.15)!important}.shadow-lg{box-shadow:0 1rem 3rem rgba(0,0,0,.175)!important}.shadow-none{box-shadow:none!important}.w-25{width:25%!important}.w-50{width:50%!important}.w-75{width:75%!important}.w-100{width:100%!important}.w-auto{width:auto!important}.h-25{height:25%!important}.h-50{height:50%!important}.h-75{height:75%!important}.h-100{height:100%!important}.h-auto{height:auto!important}.mw-100{max-width:100%!important}.mh-100{max-height:100%!important}.min-vw-100{min-width:100vw!important}.min-vh-100{min-height:100vh!important}.vw-100{width:100vw!important}.vh-100{height:100vh!important}.stretched-link::after{position:absolute;top:0;right:0;bottom:0;left:0;z-index:1;pointer-events:auto;content:\\\"\\\";background-color:rgba(0,0,0,0)}.m-0{margin:0!important}.mt-0,.my-0{margin-top:0!important}.mr-0,.mx-0{margin-right:0!important}.mb-0,.my-0{margin-bottom:0!important}.ml-0,.mx-0{margin-left:0!important}.m-1{margin:.25rem!important}.mt-1,.my-1{margin-top:.25rem!important}.mr-1,.mx-1{margin-right:.25rem!important}.mb-1,.my-1{margin-bottom:.25rem!important}.ml-1,.mx-1{margin-left:.25rem!important}.m-2{margin:.5rem!important}.mt-2,.my-2{margin-top:.5rem!important}.mr-2,.mx-2{margin-right:.5rem!important}.mb-2,.my-2{margin-bottom:.5rem!important}.ml-2,.mx-2{margin-left:.5rem!important}.m-3{margin:1rem!important}.mt-3,.my-3{margin-top:1rem!important}.mr-3,.mx-3{margin-right:1rem!important}.mb-3,.my-3{margin-bottom:1rem!important}.ml-3,.mx-3{margin-left:1rem!important}.m-4{margin:1.5rem!important}.mt-4,.my-4{margin-top:1.5rem!important}.mr-4,.mx-4{margin-right:1.5rem!important}.mb-4,.my-4{margin-bottom:1.5rem!important}.ml-4,.mx-4{margin-left:1.5rem!important}.m-5{margin:3rem!important}.mt-5,.my-5{margin-top:3rem!important}.mr-5,.mx-5{margin-right:3rem!important}.mb-5,.my-5{margin-bottom:3rem!important}.ml-5,.mx-5{margin-left:3rem!important}.p-0{padding:0!important}.pt-0,.py-0{padding-top:0!important}.pr-0,.px-0{padding-right:0!important}.pb-0,.py-0{padding-bottom:0!important}.pl-0,.px-0{padding-left:0!important}.p-1{padding:.25rem!important}.pt-1,.py-1{padding-top:.25rem!important}.pr-1,.px-1{padding-right:.25rem!important}.pb-1,.py-1{padding-bottom:.25rem!important}.pl-1,.px-1{padding-left:.25rem!important}.p-2{padding:.5rem!important}.pt-2,.py-2{padding-top:.5rem!important}.pr-2,.px-2{padding-right:.5rem!important}.pb-2,.py-2{padding-bottom:.5rem!important}.pl-2,.px-2{padding-left:.5rem!important}.p-3{padding:1rem!important}.pt-3,.py-3{padding-top:1rem!important}.pr-3,.px-3{padding-right:1rem!important}.pb-3,.py-3{padding-bottom:1rem!important}.pl-3,.px-3{padding-left:1rem!important}.p-4{padding:1.5rem!important}.pt-4,.py-4{padding-top:1.5rem!important}.pr-4,.px-4{padding-right:1.5rem!important}.pb-4,.py-4{padding-bottom:1.5rem!important}.pl-4,.px-4{padding-left:1.5rem!important}.p-5{padding:3rem!important}.pt-5,.py-5{padding-top:3rem!important}.pr-5,.px-5{padding-right:3rem!important}.pb-5,.py-5{padding-bottom:3rem!important}.pl-5,.px-5{padding-left:3rem!important}.m-n1{margin:-.25rem!important}.mt-n1,.my-n1{margin-top:-.25rem!important}.mr-n1,.mx-n1{margin-right:-.25rem!important}.mb-n1,.my-n1{margin-bottom:-.25rem!important}.ml-n1,.mx-n1{margin-left:-.25rem!important}.m-n2{margin:-.5rem!important}.mt-n2,.my-n2{margin-top:-.5rem!important}.mr-n2,.mx-n2{margin-right:-.5rem!important}.mb-n2,.my-n2{margin-bottom:-.5rem!important}.ml-n2,.mx-n2{margin-left:-.5rem!important}.m-n3{margin:-1rem!important}.mt-n3,.my-n3{margin-top:-1rem!important}.mr-n3,.mx-n3{margin-right:-1rem!important}.mb-n3,.my-n3{margin-bottom:-1rem!important}.ml-n3,.mx-n3{margin-left:-1rem!important}.m-n4{margin:-1.5rem!important}.mt-n4,.my-n4{margin-top:-1.5rem!important}.mr-n4,.mx-n4{margin-right:-1.5rem!important}.mb-n4,.my-n4{margin-bottom:-1.5rem!important}.ml-n4,.mx-n4{margin-left:-1.5rem!important}.m-n5{margin:-3rem!important}.mt-n5,.my-n5{margin-top:-3rem!important}.mr-n5,.mx-n5{margin-right:-3rem!important}.mb-n5,.my-n5{margin-bottom:-3rem!important}.ml-n5,.mx-n5{margin-left:-3rem!important}.m-auto{margin:auto!important}.mt-auto,.my-auto{margin-top:auto!important}.mr-auto,.mx-auto{margin-right:auto!important}.mb-auto,.my-auto{margin-bottom:auto!important}.ml-auto,.mx-auto{margin-left:auto!important}@media (min-width:576px){.m-sm-0{margin:0!important}.mt-sm-0,.my-sm-0{margin-top:0!important}.mr-sm-0,.mx-sm-0{margin-right:0!important}.mb-sm-0,.my-sm-0{margin-bottom:0!important}.ml-sm-0,.mx-sm-0{margin-left:0!important}.m-sm-1{margin:.25rem!important}.mt-sm-1,.my-sm-1{margin-top:.25rem!important}.mr-sm-1,.mx-sm-1{margin-right:.25rem!important}.mb-sm-1,.my-sm-1{margin-bottom:.25rem!important}.ml-sm-1,.mx-sm-1{margin-left:.25rem!important}.m-sm-2{margin:.5rem!important}.mt-sm-2,.my-sm-2{margin-top:.5rem!important}.mr-sm-2,.mx-sm-2{margin-right:.5rem!important}.mb-sm-2,.my-sm-2{margin-bottom:.5rem!important}.ml-sm-2,.mx-sm-2{margin-left:.5rem!important}.m-sm-3{margin:1rem!important}.mt-sm-3,.my-sm-3{margin-top:1rem!important}.mr-sm-3,.mx-sm-3{margin-right:1rem!important}.mb-sm-3,.my-sm-3{margin-bottom:1rem!important}.ml-sm-3,.mx-sm-3{margin-left:1rem!important}.m-sm-4{margin:1.5rem!important}.mt-sm-4,.my-sm-4{margin-top:1.5rem!important}.mr-sm-4,.mx-sm-4{margin-right:1.5rem!important}.mb-sm-4,.my-sm-4{margin-bottom:1.5rem!important}.ml-sm-4,.mx-sm-4{margin-left:1.5rem!important}.m-sm-5{margin:3rem!important}.mt-sm-5,.my-sm-5{margin-top:3rem!important}.mr-sm-5,.mx-sm-5{margin-right:3rem!important}.mb-sm-5,.my-sm-5{margin-bottom:3rem!important}.ml-sm-5,.mx-sm-5{margin-left:3rem!important}.p-sm-0{padding:0!important}.pt-sm-0,.py-sm-0{padding-top:0!important}.pr-sm-0,.px-sm-0{padding-right:0!important}.pb-sm-0,.py-sm-0{padding-bottom:0!important}.pl-sm-0,.px-sm-0{padding-left:0!important}.p-sm-1{padding:.25rem!important}.pt-sm-1,.py-sm-1{padding-top:.25rem!important}.pr-sm-1,.px-sm-1{padding-right:.25rem!important}.pb-sm-1,.py-sm-1{padding-bottom:.25rem!important}.pl-sm-1,.px-sm-1{padding-left:.25rem!important}.p-sm-2{padding:.5rem!important}.pt-sm-2,.py-sm-2{padding-top:.5rem!important}.pr-sm-2,.px-sm-2{padding-right:.5rem!important}.pb-sm-2,.py-sm-2{padding-bottom:.5rem!important}.pl-sm-2,.px-sm-2{padding-left:.5rem!important}.p-sm-3{padding:1rem!important}.pt-sm-3,.py-sm-3{padding-top:1rem!important}.pr-sm-3,.px-sm-3{padding-right:1rem!important}.pb-sm-3,.py-sm-3{padding-bottom:1rem!important}.pl-sm-3,.px-sm-3{padding-left:1rem!important}.p-sm-4{padding:1.5rem!important}.pt-sm-4,.py-sm-4{padding-top:1.5rem!important}.pr-sm-4,.px-sm-4{padding-right:1.5rem!important}.pb-sm-4,.py-sm-4{padding-bottom:1.5rem!important}.pl-sm-4,.px-sm-4{padding-left:1.5rem!important}.p-sm-5{padding:3rem!important}.pt-sm-5,.py-sm-5{padding-top:3rem!important}.pr-sm-5,.px-sm-5{padding-right:3rem!important}.pb-sm-5,.py-sm-5{padding-bottom:3rem!important}.pl-sm-5,.px-sm-5{padding-left:3rem!important}.m-sm-n1{margin:-.25rem!important}.mt-sm-n1,.my-sm-n1{margin-top:-.25rem!important}.mr-sm-n1,.mx-sm-n1{margin-right:-.25rem!important}.mb-sm-n1,.my-sm-n1{margin-bottom:-.25rem!important}.ml-sm-n1,.mx-sm-n1{margin-left:-.25rem!important}.m-sm-n2{margin:-.5rem!important}.mt-sm-n2,.my-sm-n2{margin-top:-.5rem!important}.mr-sm-n2,.mx-sm-n2{margin-right:-.5rem!important}.mb-sm-n2,.my-sm-n2{margin-bottom:-.5rem!important}.ml-sm-n2,.mx-sm-n2{margin-left:-.5rem!important}.m-sm-n3{margin:-1rem!important}.mt-sm-n3,.my-sm-n3{margin-top:-1rem!important}.mr-sm-n3,.mx-sm-n3{margin-right:-1rem!important}.mb-sm-n3,.my-sm-n3{margin-bottom:-1rem!important}.ml-sm-n3,.mx-sm-n3{margin-left:-1rem!important}.m-sm-n4{margin:-1.5rem!important}.mt-sm-n4,.my-sm-n4{margin-top:-1.5rem!important}.mr-sm-n4,.mx-sm-n4{margin-right:-1.5rem!important}.mb-sm-n4,.my-sm-n4{margin-bottom:-1.5rem!important}.ml-sm-n4,.mx-sm-n4{margin-left:-1.5rem!important}.m-sm-n5{margin:-3rem!important}.mt-sm-n5,.my-sm-n5{margin-top:-3rem!important}.mr-sm-n5,.mx-sm-n5{margin-right:-3rem!important}.mb-sm-n5,.my-sm-n5{margin-bottom:-3rem!important}.ml-sm-n5,.mx-sm-n5{margin-left:-3rem!important}.m-sm-auto{margin:auto!important}.mt-sm-auto,.my-sm-auto{margin-top:auto!important}.mr-sm-auto,.mx-sm-auto{margin-right:auto!important}.mb-sm-auto,.my-sm-auto{margin-bottom:auto!important}.ml-sm-auto,.mx-sm-auto{margin-left:auto!important}}@media (min-width:768px){.m-md-0{margin:0!important}.mt-md-0,.my-md-0{margin-top:0!important}.mr-md-0,.mx-md-0{margin-right:0!important}.mb-md-0,.my-md-0{margin-bottom:0!important}.ml-md-0,.mx-md-0{margin-left:0!important}.m-md-1{margin:.25rem!important}.mt-md-1,.my-md-1{margin-top:.25rem!important}.mr-md-1,.mx-md-1{margin-right:.25rem!important}.mb-md-1,.my-md-1{margin-bottom:.25rem!important}.ml-md-1,.mx-md-1{margin-left:.25rem!important}.m-md-2{margin:.5rem!important}.mt-md-2,.my-md-2{margin-top:.5rem!important}.mr-md-2,.mx-md-2{margin-right:.5rem!important}.mb-md-2,.my-md-2{margin-bottom:.5rem!important}.ml-md-2,.mx-md-2{margin-left:.5rem!important}.m-md-3{margin:1rem!important}.mt-md-3,.my-md-3{margin-top:1rem!important}.mr-md-3,.mx-md-3{margin-right:1rem!important}.mb-md-3,.my-md-3{margin-bottom:1rem!important}.ml-md-3,.mx-md-3{margin-left:1rem!important}.m-md-4{margin:1.5rem!important}.mt-md-4,.my-md-4{margin-top:1.5rem!important}.mr-md-4,.mx-md-4{margin-right:1.5rem!important}.mb-md-4,.my-md-4{margin-bottom:1.5rem!important}.ml-md-4,.mx-md-4{margin-left:1.5rem!important}.m-md-5{margin:3rem!important}.mt-md-5,.my-md-5{margin-top:3rem!important}.mr-md-5,.mx-md-5{margin-right:3rem!important}.mb-md-5,.my-md-5{margin-bottom:3rem!important}.ml-md-5,.mx-md-5{margin-left:3rem!important}.p-md-0{padding:0!important}.pt-md-0,.py-md-0{padding-top:0!important}.pr-md-0,.px-md-0{padding-right:0!important}.pb-md-0,.py-md-0{padding-bottom:0!important}.pl-md-0,.px-md-0{padding-left:0!important}.p-md-1{padding:.25rem!important}.pt-md-1,.py-md-1{padding-top:.25rem!important}.pr-md-1,.px-md-1{padding-right:.25rem!important}.pb-md-1,.py-md-1{padding-bottom:.25rem!important}.pl-md-1,.px-md-1{padding-left:.25rem!important}.p-md-2{padding:.5rem!important}.pt-md-2,.py-md-2{padding-top:.5rem!important}.pr-md-2,.px-md-2{padding-right:.5rem!important}.pb-md-2,.py-md-2{padding-bottom:.5rem!important}.pl-md-2,.px-md-2{padding-left:.5rem!important}.p-md-3{padding:1rem!important}.pt-md-3,.py-md-3{padding-top:1rem!important}.pr-md-3,.px-md-3{padding-right:1rem!important}.pb-md-3,.py-md-3{padding-bottom:1rem!important}.pl-md-3,.px-md-3{padding-left:1rem!important}.p-md-4{padding:1.5rem!important}.pt-md-4,.py-md-4{padding-top:1.5rem!important}.pr-md-4,.px-md-4{padding-right:1.5rem!important}.pb-md-4,.py-md-4{padding-bottom:1.5rem!important}.pl-md-4,.px-md-4{padding-left:1.5rem!important}.p-md-5{padding:3rem!important}.pt-md-5,.py-md-5{padding-top:3rem!important}.pr-md-5,.px-md-5{padding-right:3rem!important}.pb-md-5,.py-md-5{padding-bottom:3rem!important}.pl-md-5,.px-md-5{padding-left:3rem!important}.m-md-n1{margin:-.25rem!important}.mt-md-n1,.my-md-n1{margin-top:-.25rem!important}.mr-md-n1,.mx-md-n1{margin-right:-.25rem!important}.mb-md-n1,.my-md-n1{margin-bottom:-.25rem!important}.ml-md-n1,.mx-md-n1{margin-left:-.25rem!important}.m-md-n2{margin:-.5rem!important}.mt-md-n2,.my-md-n2{margin-top:-.5rem!important}.mr-md-n2,.mx-md-n2{margin-right:-.5rem!important}.mb-md-n2,.my-md-n2{margin-bottom:-.5rem!important}.ml-md-n2,.mx-md-n2{margin-left:-.5rem!important}.m-md-n3{margin:-1rem!important}.mt-md-n3,.my-md-n3{margin-top:-1rem!important}.mr-md-n3,.mx-md-n3{margin-right:-1rem!important}.mb-md-n3,.my-md-n3{margin-bottom:-1rem!important}.ml-md-n3,.mx-md-n3{margin-left:-1rem!important}.m-md-n4{margin:-1.5rem!important}.mt-md-n4,.my-md-n4{margin-top:-1.5rem!important}.mr-md-n4,.mx-md-n4{margin-right:-1.5rem!important}.mb-md-n4,.my-md-n4{margin-bottom:-1.5rem!important}.ml-md-n4,.mx-md-n4{margin-left:-1.5rem!important}.m-md-n5{margin:-3rem!important}.mt-md-n5,.my-md-n5{margin-top:-3rem!important}.mr-md-n5,.mx-md-n5{margin-right:-3rem!important}.mb-md-n5,.my-md-n5{margin-bottom:-3rem!important}.ml-md-n5,.mx-md-n5{margin-left:-3rem!important}.m-md-auto{margin:auto!important}.mt-md-auto,.my-md-auto{margin-top:auto!important}.mr-md-auto,.mx-md-auto{margin-right:auto!important}.mb-md-auto,.my-md-auto{margin-bottom:auto!important}.ml-md-auto,.mx-md-auto{margin-left:auto!important}}@media (min-width:992px){.m-lg-0{margin:0!important}.mt-lg-0,.my-lg-0{margin-top:0!important}.mr-lg-0,.mx-lg-0{margin-right:0!important}.mb-lg-0,.my-lg-0{margin-bottom:0!important}.ml-lg-0,.mx-lg-0{margin-left:0!important}.m-lg-1{margin:.25rem!important}.mt-lg-1,.my-lg-1{margin-top:.25rem!important}.mr-lg-1,.mx-lg-1{margin-right:.25rem!important}.mb-lg-1,.my-lg-1{margin-bottom:.25rem!important}.ml-lg-1,.mx-lg-1{margin-left:.25rem!important}.m-lg-2{margin:.5rem!important}.mt-lg-2,.my-lg-2{margin-top:.5rem!important}.mr-lg-2,.mx-lg-2{margin-right:.5rem!important}.mb-lg-2,.my-lg-2{margin-bottom:.5rem!important}.ml-lg-2,.mx-lg-2{margin-left:.5rem!important}.m-lg-3{margin:1rem!important}.mt-lg-3,.my-lg-3{margin-top:1rem!important}.mr-lg-3,.mx-lg-3{margin-right:1rem!important}.mb-lg-3,.my-lg-3{margin-bottom:1rem!important}.ml-lg-3,.mx-lg-3{margin-left:1rem!important}.m-lg-4{margin:1.5rem!important}.mt-lg-4,.my-lg-4{margin-top:1.5rem!important}.mr-lg-4,.mx-lg-4{margin-right:1.5rem!important}.mb-lg-4,.my-lg-4{margin-bottom:1.5rem!important}.ml-lg-4,.mx-lg-4{margin-left:1.5rem!important}.m-lg-5{margin:3rem!important}.mt-lg-5,.my-lg-5{margin-top:3rem!important}.mr-lg-5,.mx-lg-5{margin-right:3rem!important}.mb-lg-5,.my-lg-5{margin-bottom:3rem!important}.ml-lg-5,.mx-lg-5{margin-left:3rem!important}.p-lg-0{padding:0!important}.pt-lg-0,.py-lg-0{padding-top:0!important}.pr-lg-0,.px-lg-0{padding-right:0!important}.pb-lg-0,.py-lg-0{padding-bottom:0!important}.pl-lg-0,.px-lg-0{padding-left:0!important}.p-lg-1{padding:.25rem!important}.pt-lg-1,.py-lg-1{padding-top:.25rem!important}.pr-lg-1,.px-lg-1{padding-right:.25rem!important}.pb-lg-1,.py-lg-1{padding-bottom:.25rem!important}.pl-lg-1,.px-lg-1{padding-left:.25rem!important}.p-lg-2{padding:.5rem!important}.pt-lg-2,.py-lg-2{padding-top:.5rem!important}.pr-lg-2,.px-lg-2{padding-right:.5rem!important}.pb-lg-2,.py-lg-2{padding-bottom:.5rem!important}.pl-lg-2,.px-lg-2{padding-left:.5rem!important}.p-lg-3{padding:1rem!important}.pt-lg-3,.py-lg-3{padding-top:1rem!important}.pr-lg-3,.px-lg-3{padding-right:1rem!important}.pb-lg-3,.py-lg-3{padding-bottom:1rem!important}.pl-lg-3,.px-lg-3{padding-left:1rem!important}.p-lg-4{padding:1.5rem!important}.pt-lg-4,.py-lg-4{padding-top:1.5rem!important}.pr-lg-4,.px-lg-4{padding-right:1.5rem!important}.pb-lg-4,.py-lg-4{padding-bottom:1.5rem!important}.pl-lg-4,.px-lg-4{padding-left:1.5rem!important}.p-lg-5{padding:3rem!important}.pt-lg-5,.py-lg-5{padding-top:3rem!important}.pr-lg-5,.px-lg-5{padding-right:3rem!important}.pb-lg-5,.py-lg-5{padding-bottom:3rem!important}.pl-lg-5,.px-lg-5{padding-left:3rem!important}.m-lg-n1{margin:-.25rem!important}.mt-lg-n1,.my-lg-n1{margin-top:-.25rem!important}.mr-lg-n1,.mx-lg-n1{margin-right:-.25rem!important}.mb-lg-n1,.my-lg-n1{margin-bottom:-.25rem!important}.ml-lg-n1,.mx-lg-n1{margin-left:-.25rem!important}.m-lg-n2{margin:-.5rem!important}.mt-lg-n2,.my-lg-n2{margin-top:-.5rem!important}.mr-lg-n2,.mx-lg-n2{margin-right:-.5rem!important}.mb-lg-n2,.my-lg-n2{margin-bottom:-.5rem!important}.ml-lg-n2,.mx-lg-n2{margin-left:-.5rem!important}.m-lg-n3{margin:-1rem!important}.mt-lg-n3,.my-lg-n3{margin-top:-1rem!important}.mr-lg-n3,.mx-lg-n3{margin-right:-1rem!important}.mb-lg-n3,.my-lg-n3{margin-bottom:-1rem!important}.ml-lg-n3,.mx-lg-n3{margin-left:-1rem!important}.m-lg-n4{margin:-1.5rem!important}.mt-lg-n4,.my-lg-n4{margin-top:-1.5rem!important}.mr-lg-n4,.mx-lg-n4{margin-right:-1.5rem!important}.mb-lg-n4,.my-lg-n4{margin-bottom:-1.5rem!important}.ml-lg-n4,.mx-lg-n4{margin-left:-1.5rem!important}.m-lg-n5{margin:-3rem!important}.mt-lg-n5,.my-lg-n5{margin-top:-3rem!important}.mr-lg-n5,.mx-lg-n5{margin-right:-3rem!important}.mb-lg-n5,.my-lg-n5{margin-bottom:-3rem!important}.ml-lg-n5,.mx-lg-n5{margin-left:-3rem!important}.m-lg-auto{margin:auto!important}.mt-lg-auto,.my-lg-auto{margin-top:auto!important}.mr-lg-auto,.mx-lg-auto{margin-right:auto!important}.mb-lg-auto,.my-lg-auto{margin-bottom:auto!important}.ml-lg-auto,.mx-lg-auto{margin-left:auto!important}}@media (min-width:1200px){.m-xl-0{margin:0!important}.mt-xl-0,.my-xl-0{margin-top:0!important}.mr-xl-0,.mx-xl-0{margin-right:0!important}.mb-xl-0,.my-xl-0{margin-bottom:0!important}.ml-xl-0,.mx-xl-0{margin-left:0!important}.m-xl-1{margin:.25rem!important}.mt-xl-1,.my-xl-1{margin-top:.25rem!important}.mr-xl-1,.mx-xl-1{margin-right:.25rem!important}.mb-xl-1,.my-xl-1{margin-bottom:.25rem!important}.ml-xl-1,.mx-xl-1{margin-left:.25rem!important}.m-xl-2{margin:.5rem!important}.mt-xl-2,.my-xl-2{margin-top:.5rem!important}.mr-xl-2,.mx-xl-2{margin-right:.5rem!important}.mb-xl-2,.my-xl-2{margin-bottom:.5rem!important}.ml-xl-2,.mx-xl-2{margin-left:.5rem!important}.m-xl-3{margin:1rem!important}.mt-xl-3,.my-xl-3{margin-top:1rem!important}.mr-xl-3,.mx-xl-3{margin-right:1rem!important}.mb-xl-3,.my-xl-3{margin-bottom:1rem!important}.ml-xl-3,.mx-xl-3{margin-left:1rem!important}.m-xl-4{margin:1.5rem!important}.mt-xl-4,.my-xl-4{margin-top:1.5rem!important}.mr-xl-4,.mx-xl-4{margin-right:1.5rem!important}.mb-xl-4,.my-xl-4{margin-bottom:1.5rem!important}.ml-xl-4,.mx-xl-4{margin-left:1.5rem!important}.m-xl-5{margin:3rem!important}.mt-xl-5,.my-xl-5{margin-top:3rem!important}.mr-xl-5,.mx-xl-5{margin-right:3rem!important}.mb-xl-5,.my-xl-5{margin-bottom:3rem!important}.ml-xl-5,.mx-xl-5{margin-left:3rem!important}.p-xl-0{padding:0!important}.pt-xl-0,.py-xl-0{padding-top:0!important}.pr-xl-0,.px-xl-0{padding-right:0!important}.pb-xl-0,.py-xl-0{padding-bottom:0!important}.pl-xl-0,.px-xl-0{padding-left:0!important}.p-xl-1{padding:.25rem!important}.pt-xl-1,.py-xl-1{padding-top:.25rem!important}.pr-xl-1,.px-xl-1{padding-right:.25rem!important}.pb-xl-1,.py-xl-1{padding-bottom:.25rem!important}.pl-xl-1,.px-xl-1{padding-left:.25rem!important}.p-xl-2{padding:.5rem!important}.pt-xl-2,.py-xl-2{padding-top:.5rem!important}.pr-xl-2,.px-xl-2{padding-right:.5rem!important}.pb-xl-2,.py-xl-2{padding-bottom:.5rem!important}.pl-xl-2,.px-xl-2{padding-left:.5rem!important}.p-xl-3{padding:1rem!important}.pt-xl-3,.py-xl-3{padding-top:1rem!important}.pr-xl-3,.px-xl-3{padding-right:1rem!important}.pb-xl-3,.py-xl-3{padding-bottom:1rem!important}.pl-xl-3,.px-xl-3{padding-left:1rem!important}.p-xl-4{padding:1.5rem!important}.pt-xl-4,.py-xl-4{padding-top:1.5rem!important}.pr-xl-4,.px-xl-4{padding-right:1.5rem!important}.pb-xl-4,.py-xl-4{padding-bottom:1.5rem!important}.pl-xl-4,.px-xl-4{padding-left:1.5rem!important}.p-xl-5{padding:3rem!important}.pt-xl-5,.py-xl-5{padding-top:3rem!important}.pr-xl-5,.px-xl-5{padding-right:3rem!important}.pb-xl-5,.py-xl-5{padding-bottom:3rem!important}.pl-xl-5,.px-xl-5{padding-left:3rem!important}.m-xl-n1{margin:-.25rem!important}.mt-xl-n1,.my-xl-n1{margin-top:-.25rem!important}.mr-xl-n1,.mx-xl-n1{margin-right:-.25rem!important}.mb-xl-n1,.my-xl-n1{margin-bottom:-.25rem!important}.ml-xl-n1,.mx-xl-n1{margin-left:-.25rem!important}.m-xl-n2{margin:-.5rem!important}.mt-xl-n2,.my-xl-n2{margin-top:-.5rem!important}.mr-xl-n2,.mx-xl-n2{margin-right:-.5rem!important}.mb-xl-n2,.my-xl-n2{margin-bottom:-.5rem!important}.ml-xl-n2,.mx-xl-n2{margin-left:-.5rem!important}.m-xl-n3{margin:-1rem!important}.mt-xl-n3,.my-xl-n3{margin-top:-1rem!important}.mr-xl-n3,.mx-xl-n3{margin-right:-1rem!important}.mb-xl-n3,.my-xl-n3{margin-bottom:-1rem!important}.ml-xl-n3,.mx-xl-n3{margin-left:-1rem!important}.m-xl-n4{margin:-1.5rem!important}.mt-xl-n4,.my-xl-n4{margin-top:-1.5rem!important}.mr-xl-n4,.mx-xl-n4{margin-right:-1.5rem!important}.mb-xl-n4,.my-xl-n4{margin-bottom:-1.5rem!important}.ml-xl-n4,.mx-xl-n4{margin-left:-1.5rem!important}.m-xl-n5{margin:-3rem!important}.mt-xl-n5,.my-xl-n5{margin-top:-3rem!important}.mr-xl-n5,.mx-xl-n5{margin-right:-3rem!important}.mb-xl-n5,.my-xl-n5{margin-bottom:-3rem!important}.ml-xl-n5,.mx-xl-n5{margin-left:-3rem!important}.m-xl-auto{margin:auto!important}.mt-xl-auto,.my-xl-auto{margin-top:auto!important}.mr-xl-auto,.mx-xl-auto{margin-right:auto!important}.mb-xl-auto,.my-xl-auto{margin-bottom:auto!important}.ml-xl-auto,.mx-xl-auto{margin-left:auto!important}}.text-monospace{font-family:SFMono-Regular,Menlo,Monaco,Consolas,\\\"Liberation Mono\\\",\\\"Courier New\\\",monospace!important}.text-justify{text-align:justify!important}.text-wrap{white-space:normal!important}.text-nowrap{white-space:nowrap!important}.text-truncate{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.text-left{text-align:left!important}.text-right{text-align:right!important}.text-center{text-align:center!important}@media (min-width:576px){.text-sm-left{text-align:left!important}.text-sm-right{text-align:right!important}.text-sm-center{text-align:center!important}}@media (min-width:768px){.text-md-left{text-align:left!important}.text-md-right{text-align:right!important}.text-md-center{text-align:center!important}}@media (min-width:992px){.text-lg-left{text-align:left!important}.text-lg-right{text-align:right!important}.text-lg-center{text-align:center!important}}@media (min-width:1200px){.text-xl-left{text-align:left!important}.text-xl-right{text-align:right!important}.text-xl-center{text-align:center!important}}.text-lowercase{text-transform:lowercase!important}.text-uppercase{text-transform:uppercase!important}.text-capitalize{text-transform:capitalize!important}.font-weight-light{font-weight:300!important}.font-weight-lighter{font-weight:lighter!important}.font-weight-normal{font-weight:400!important}.font-weight-bold{font-weight:700!important}.font-weight-bolder{font-weight:bolder!important}.font-italic{font-style:italic!important}.text-white{color:#fff!important}.text-primary{color:#007bff!important}a.text-primary:focus,a.text-primary:hover{color:#0056b3!important}.text-secondary{color:#6c757d!important}a.text-secondary:focus,a.text-secondary:hover{color:#494f54!important}.text-success{color:#28a745!important}a.text-success:focus,a.text-success:hover{color:#19692c!important}.text-info{color:#17a2b8!important}a.text-info:focus,a.text-info:hover{color:#0f6674!important}.text-warning{color:#ffc107!important}a.text-warning:focus,a.text-warning:hover{color:#ba8b00!important}.text-danger{color:#dc3545!important}a.text-danger:focus,a.text-danger:hover{color:#a71d2a!important}.text-light{color:#f8f9fa!important}a.text-light:focus,a.text-light:hover{color:#cbd3da!important}.text-dark{color:#343a40!important}a.text-dark:focus,a.text-dark:hover{color:#121416!important}.text-body{color:#212529!important}.text-muted{color:#6c757d!important}.text-black-50{color:rgba(0,0,0,.5)!important}.text-white-50{color:rgba(255,255,255,.5)!important}.text-hide{font:0/0 a;color:transparent;text-shadow:none;background-color:transparent;border:0}.text-decoration-none{text-decoration:none!important}.text-break{word-break:break-word!important;overflow-wrap:break-word!important}.text-reset{color:inherit!important}.visible{visibility:visible!important}.invisible{visibility:hidden!important}@media print{*,::after,::before{text-shadow:none!important;box-shadow:none!important}a:not(.btn){text-decoration:underline}abbr[title]::after{content:\\\" (\\\" attr(title) \\\")\\\"}pre{white-space:pre-wrap!important}blockquote,pre{border:1px solid #adb5bd;page-break-inside:avoid}thead{display:table-header-group}img,tr{page-break-inside:avoid}h2,h3,p{orphans:3;widows:3}h2,h3{page-break-after:avoid}@page{size:a3}body{min-width:992px!important}.container{min-width:992px!important}.navbar{display:none}.badge{border:1px solid #000}.table{border-collapse:collapse!important}.table td,.table th{background-color:#fff!important}.table-bordered td,.table-bordered th{border:1px solid #dee2e6!important}.table-dark{color:inherit}.table-dark tbody+tbody,.table-dark td,.table-dark th,.table-dark thead th{border-color:#dee2e6}.table .thead-dark th{color:inherit;border-color:#dee2e6}}\", \"\"]);\n// Exports\nmodule.exports = exports;\n\n\n//# sourceURL=webpack:///./node_modules/bootstrap/dist/css/bootstrap.min.css?./node_modules/css-loader/dist/cjs.js");
/***/ }),
/***/ "./node_modules/css-loader/dist/cjs.js!./src/App.css":
/*!***********************************************************!*\
!*** ./node_modules/css-loader/dist/cjs.js!./src/App.css ***!
\***********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
eval("// Imports\nvar ___CSS_LOADER_API_IMPORT___ = __webpack_require__(/*! ../node_modules/css-loader/dist/runtime/api.js */ \"./node_modules/css-loader/dist/runtime/api.js\");\nexports = ___CSS_LOADER_API_IMPORT___(false);\n// Module\nexports.push([module.i, \"label {\\n display: block;\\n margin-top: 10px;\\n }\\n \\n .card-container.card {\\n max-width: 350px !important;\\n padding: 40px 40px;\\n }\\n \\n .card {\\n background-color: #f7f7f7;\\n padding: 20px 25px 30px;\\n margin: 0 auto 25px;\\n margin-top: 50px;\\n -moz-border-radius: 2px;\\n -webkit-border-radius: 2px;\\n border-radius: 2px;\\n -moz-box-shadow: 0px 2px 2px rgba(0, 0, 0, 0.3);\\n -webkit-box-shadow: 0px 2px 2px rgba(0, 0, 0, 0.3);\\n box-shadow: 0px 2px 2px rgba(0, 0, 0, 0.3);\\n }\\n \\n .profile-img-card {\\n width: 96px;\\n height: 96px;\\n margin: 0 auto 10px;\\n display: block;\\n -moz-border-radius: 50%;\\n -webkit-border-radius: 50%;\\n border-radius: 50%;\\n }\", \"\"]);\n// Exports\nmodule.exports = exports;\n\n\n//# sourceURL=webpack:///./src/App.css?./node_modules/css-loader/dist/cjs.js");
/***/ }),
/***/ "./node_modules/css-loader/dist/runtime/api.js":
/*!*****************************************************!*\
!*** ./node_modules/css-loader/dist/runtime/api.js ***!
\*****************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
eval("\n\n/*\n MIT License http://www.opensource.org/licenses/mit-license.php\n Author Tobias Koppers @sokra\n*/\n// css base code, injected by the css-loader\n// eslint-disable-next-line func-names\nmodule.exports = function (useSourceMap) {\n var list = []; // return the list of modules as css string\n\n list.toString = function toString() {\n return this.map(function (item) {\n var content = cssWithMappingToString(item, useSourceMap);\n\n if (item[2]) {\n return \"@media \".concat(item[2], \" {\").concat(content, \"}\");\n }\n\n return content;\n }).join('');\n }; // import a list of modules into the list\n // eslint-disable-next-line func-names\n\n\n list.i = function (modules, mediaQuery, dedupe) {\n if (typeof modules === 'string') {\n // eslint-disable-next-line no-param-reassign\n modules = [[null, modules, '']];\n }\n\n var alreadyImportedModules = {};\n\n if (dedupe) {\n for (var i = 0; i < this.length; i++) {\n // eslint-disable-next-line prefer-destructuring\n var id = this[i][0];\n\n if (id != null) {\n alreadyImportedModules[id] = true;\n }\n }\n }\n\n for (var _i = 0; _i < modules.length; _i++) {\n var item = [].concat(modules[_i]);\n\n if (dedupe && alreadyImportedModules[item[0]]) {\n // eslint-disable-next-line no-continue\n continue;\n }\n\n if (mediaQuery) {\n if (!item[2]) {\n item[2] = mediaQuery;\n } else {\n item[2] = \"\".concat(mediaQuery, \" and \").concat(item[2]);\n }\n }\n\n list.push(item);\n }\n };\n\n return list;\n};\n\nfunction cssWithMappingToString(item, useSourceMap) {\n var content = item[1] || ''; // eslint-disable-next-line prefer-destructuring\n\n var cssMapping = item[3];\n\n if (!cssMapping) {\n return content;\n }\n\n if (useSourceMap && typeof btoa === 'function') {\n var sourceMapping = toComment(cssMapping);\n var sourceURLs = cssMapping.sources.map(function (source) {\n return \"/*# sourceURL=\".concat(cssMapping.sourceRoot || '').concat(source, \" */\");\n });\n return [content].concat(sourceURLs).concat([sourceMapping]).join('\\n');\n }\n\n return [content].join('\\n');\n} // Adapted from convert-source-map (MIT)\n\n\nfunction toComment(sourceMap) {\n // eslint-disable-next-line no-undef\n var base64 = btoa(unescape(encodeURIComponent(JSON.stringify(sourceMap))));\n var data = \"sourceMappingURL=data:application/json;charset=utf-8;base64,\".concat(base64);\n return \"/*# \".concat(data, \" */\");\n}\n\n//# sourceURL=webpack:///./node_modules/css-loader/dist/runtime/api.js?");
/***/ }),
/***/ "./node_modules/gud/index.js":
/*!***********************************!*\
!*** ./node_modules/gud/index.js ***!
\***********************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
eval("/* WEBPACK VAR INJECTION */(function(global) {// @flow\n\n\nvar key = '__global_unique_id__';\n\nmodule.exports = function() {\n return global[key] = (global[key] || 0) + 1;\n};\n\n/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./../webpack/buildin/global.js */ \"./node_modules/webpack/buildin/global.js\")))\n\n//# sourceURL=webpack:///./node_modules/gud/index.js?");
/***/ }),
/***/ "./node_modules/history/esm/history.js":
/*!*********************************************!*\
!*** ./node_modules/history/esm/history.js ***!
\*********************************************/
/*! exports provided: createBrowserHistory, createHashHistory, createMemoryHistory, createLocation, locationsAreEqual, parsePath, createPath */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"createBrowserHistory\", function() { return createBrowserHistory; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"createHashHistory\", function() { return createHashHistory; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"createMemoryHistory\", function() { return createMemoryHistory; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"createLocation\", function() { return createLocation; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"locationsAreEqual\", function() { return locationsAreEqual; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"parsePath\", function() { return parsePath; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"createPath\", function() { return createPath; });\n/* harmony import */ var _babel_runtime_helpers_esm_extends__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @babel/runtime/helpers/esm/extends */ \"./node_modules/@babel/runtime/helpers/esm/extends.js\");\n/* harmony import */ var resolve_pathname__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! resolve-pathname */ \"./node_modules/resolve-pathname/esm/resolve-pathname.js\");\n/* harmony import */ var value_equal__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! value-equal */ \"./node_modules/value-equal/esm/value-equal.js\");\n/* harmony import */ var tiny_warning__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! tiny-warning */ \"./node_modules/tiny-warning/dist/tiny-warning.esm.js\");\n/* harmony import */ var tiny_invariant__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! tiny-invariant */ \"./node_modules/tiny-invariant/dist/tiny-invariant.esm.js\");\n\n\n\n\n\n\nfunction addLeadingSlash(path) {\n return path.charAt(0) === '/' ? path : '/' + path;\n}\nfunction stripLeadingSlash(path) {\n return path.charAt(0) === '/' ? path.substr(1) : path;\n}\nfunction hasBasename(path, prefix) {\n return path.toLowerCase().indexOf(prefix.toLowerCase()) === 0 && '/?#'.indexOf(path.charAt(prefix.length)) !== -1;\n}\nfunction stripBasename(path, prefix) {\n return hasBasename(path, prefix) ? path.substr(prefix.length) : path;\n}\nfunction stripTrailingSlash(path) {\n return path.charAt(path.length - 1) === '/' ? path.slice(0, -1) : path;\n}\nfunction parsePath(path) {\n var pathname = path || '/';\n var search = '';\n var hash = '';\n var hashIndex = pathname.indexOf('#');\n\n if (hashIndex !== -1) {\n hash = pathname.substr(hashIndex);\n pathname = pathname.substr(0, hashIndex);\n }\n\n var searchIndex = pathname.indexOf('?');\n\n if (searchIndex !== -1) {\n search = pathname.substr(searchIndex);\n pathname = pathname.substr(0, searchIndex);\n }\n\n return {\n pathname: pathname,\n search: search === '?' ? '' : search,\n hash: hash === '#' ? '' : hash\n };\n}\nfunction createPath(location) {\n var pathname = location.pathname,\n search = location.search,\n hash = location.hash;\n var path = pathname || '/';\n if (search && search !== '?') path += search.charAt(0) === '?' ? search : \"?\" + search;\n if (hash && hash !== '#') path += hash.charAt(0) === '#' ? hash : \"#\" + hash;\n return path;\n}\n\nfunction createLocation(path, state, key, currentLocation) {\n var location;\n\n if (typeof path === 'string') {\n // Two-arg form: push(path, state)\n location = parsePath(path);\n location.state = state;\n } else {\n // One-arg form: push(location)\n location = Object(_babel_runtime_helpers_esm_extends__WEBPACK_IMPORTED_MODULE_0__[\"default\"])({}, path);\n if (location.pathname === undefined) location.pathname = '';\n\n if (location.search) {\n if (location.search.charAt(0) !== '?') location.search = '?' + location.search;\n } else {\n location.search = '';\n }\n\n if (location.hash) {\n if (location.hash.charAt(0) !== '#') location.hash = '#' + location.hash;\n } else {\n location.hash = '';\n }\n\n if (state !== undefined && location.state === undefined) location.state = state;\n }\n\n try {\n location.pathname = decodeURI(location.pathname);\n } catch (e) {\n if (e instanceof URIError) {\n throw new URIError('Pathname \"' + location.pathname + '\" could not be decoded. ' + 'This is likely caused by an invalid percent-encoding.');\n } else {\n throw e;\n }\n }\n\n if (key) location.key = key;\n\n if (currentLocation) {\n // Resolve incomplete/relative pathname relative to current location.\n if (!location.pathname) {\n location.pathname = currentLocation.pathname;\n } else if (location.pathname.charAt(0) !== '/') {\n location.pathname = Object(resolve_pathname__WEBPACK_IMPORTED_MODULE_1__[\"default\"])(location.pathname, currentLocation.pathname);\n }\n } else {\n // When there is no prior location and pathname is empty, set it to /\n if (!location.pathname) {\n location.pathname = '/';\n }\n }\n\n return location;\n}\nfunction locationsAreEqual(a, b) {\n return a.pathname === b.pathname && a.search === b.search && a.hash === b.hash && a.key === b.key && Object(value_equal__WEBPACK_IMPORTED_MODULE_2__[\"default\"])(a.state, b.state);\n}\n\nfunction createTransitionManager() {\n var prompt = null;\n\n function setPrompt(nextPrompt) {\n true ? Object(tiny_warning__WEBPACK_IMPORTED_MODULE_3__[\"default\"])(prompt == null, 'A history supports only one prompt at a time') : undefined;\n prompt = nextPrompt;\n return function () {\n if (prompt === nextPrompt) prompt = null;\n };\n }\n\n function confirmTransitionTo(location, action, getUserConfirmation, callback) {\n // TODO: If another transition starts while we're still confirming\n // the previous one, we may end up in a weird state. Figure out the\n // best way to handle this.\n if (prompt != null) {\n var result = typeof prompt === 'function' ? prompt(location, action) : prompt;\n\n if (typeof result === 'string') {\n if (typeof getUserConfirmation === 'function') {\n getUserConfirmation(result, callback);\n } else {\n true ? Object(tiny_warning__WEBPACK_IMPORTED_MODULE_3__[\"default\"])(false, 'A history needs a getUserConfirmation function in order to use a prompt message') : undefined;\n callback(true);\n }\n } else {\n // Return false from a transition hook to cancel the transition.\n callback(result !== false);\n }\n } else {\n callback(true);\n }\n }\n\n var listeners = [];\n\n function appendListener(fn) {\n var isActive = true;\n\n function listener() {\n if (isActive) fn.apply(void 0, arguments);\n }\n\n listeners.push(listener);\n return function () {\n isActive = false;\n listeners = listeners.filter(function (item) {\n return item !== listener;\n });\n };\n }\n\n function notifyListeners() {\n for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {\n args[_key] = arguments[_key];\n }\n\n listeners.forEach(function (listener) {\n return listener.apply(void 0, args);\n });\n }\n\n return {\n setPrompt: setPrompt,\n confirmTransitionTo: confirmTransitionTo,\n appendListener: appendListener,\n notifyListeners: notifyListeners\n };\n}\n\nvar canUseDOM = !!(typeof window !== 'undefined' && window.document && window.document.createElement);\nfunction getConfirmation(message, callback) {\n callback(window.confirm(message)); // eslint-disable-line no-alert\n}\n/**\n * Returns true if the HTML5 history API is supported. Taken from Modernizr.\n *\n * https://github.com/Modernizr/Modernizr/blob/master/LICENSE\n * https://github.com/Modernizr/Modernizr/blob/master/feature-detects/history.js\n * changed to avoid false negatives for Windows Phones: https://github.com/reactjs/react-router/issues/586\n */\n\nfunction supportsHistory() {\n var ua = window.navigator.userAgent;\n if ((ua.indexOf('Android 2.') !== -1 || ua.indexOf('Android 4.0') !== -1) && ua.indexOf('Mobile Safari') !== -1 && ua.indexOf('Chrome') === -1 && ua.indexOf('Windows Phone') === -1) return false;\n return window.history && 'pushState' in window.history;\n}\n/**\n * Returns true if browser fires popstate on hash change.\n * IE10 and IE11 do not.\n */\n\nfunction supportsPopStateOnHashChange() {\n return window.navigator.userAgent.indexOf('Trident') === -1;\n}\n/**\n * Returns false if using go(n) with hash history causes a full page reload.\n */\n\nfunction supportsGoWithoutReloadUsingHash() {\n return window.navigator.userAgent.indexOf('Firefox') === -1;\n}\n/**\n * Returns true if a given popstate event is an extraneous WebKit event.\n * Accounts for the fact that Chrome on iOS fires real popstate events\n * containing undefined state when pressing the back button.\n */\n\nfunction isExtraneousPopstateEvent(event) {\n return event.state === undefined && navigator.userAgent.indexOf('CriOS') === -1;\n}\n\nvar PopStateEvent = 'popstate';\nvar HashChangeEvent = 'hashchange';\n\nfunction getHistoryState() {\n try {\n return window.history.state || {};\n } catch (e) {\n // IE 11 sometimes throws when accessing window.history.state\n // See https://github.com/ReactTraining/history/pull/289\n return {};\n }\n}\n/**\n * Creates a history object that uses the HTML5 history API including\n * pushState, replaceState, and the popstate event.\n */\n\n\nfunction createBrowserHistory(props) {\n if (props === void 0) {\n props = {};\n }\n\n !canUseDOM ? true ? Object(tiny_invariant__WEBPACK_IMPORTED_MODULE_4__[\"default\"])(false, 'Browser history needs a DOM') : undefined : void 0;\n var globalHistory = window.history;\n var canUseHistory = supportsHistory();\n var needsHashChangeListener = !supportsPopStateOnHashChange();\n var _props = props,\n _props$forceRefresh = _props.forceRefresh,\n forceRefresh = _props$forceRefresh === void 0 ? false : _props$forceRefresh,\n _props$getUserConfirm = _props.getUserConfirmation,\n getUserConfirmation = _props$getUserConfirm === void 0 ? getConfirmation : _props$getUserConfirm,\n _props$keyLength = _props.keyLength,\n keyLength = _props$keyLength === void 0 ? 6 : _props$keyLength;\n var basename = props.basename ? stripTrailingSlash(addLeadingSlash(props.basename)) : '';\n\n function getDOMLocation(historyState) {\n var _ref = historyState || {},\n key = _ref.key,\n state = _ref.state;\n\n var _window$location = window.location,\n pathname = _window$location.pathname,\n search = _window$location.search,\n hash = _window$location.hash;\n var path = pathname + search + hash;\n true ? Object(tiny_warning__WEBPACK_IMPORTED_MODULE_3__[\"default\"])(!basename || hasBasename(path, basename), 'You are attempting to use a basename on a page whose URL path does not begin ' + 'with the basename. Expected path \"' + path + '\" to begin with \"' + basename + '\".') : undefined;\n if (basename) path = stripBasename(path, basename);\n return createLocation(path, state, key);\n }\n\n function createKey() {\n return Math.random().toString(36).substr(2, keyLength);\n }\n\n var transitionManager = createTransitionManager();\n\n function setState(nextState) {\n Object(_babel_runtime_helpers_esm_extends__WEBPACK_IMPORTED_MODULE_0__[\"default\"])(history, nextState);\n\n history.length = globalHistory.length;\n transitionManager.notifyListeners(history.location, history.action);\n }\n\n function handlePopState(event) {\n // Ignore extraneous popstate events in WebKit.\n if (isExtraneousPopstateEvent(event)) return;\n handlePop(getDOMLocation(event.state));\n }\n\n function handleHashChange() {\n handlePop(getDOMLocation(getHistoryState()));\n }\n\n var forceNextPop = false;\n\n function handlePop(location) {\n if (forceNextPop) {\n forceNextPop = false;\n setState();\n } else {\n var action = 'POP';\n transitionManager.confirmTransitionTo(location, action, getUserConfirmation, function (ok) {\n if (ok) {\n setState({\n action: action,\n location: location\n });\n } else {\n revertPop(location);\n }\n });\n }\n }\n\n function revertPop(fromLocation) {\n var toLocation = history.location; // TODO: We could probably make this more reliable by\n // keeping a list of keys we've seen in sessionStorage.\n // Instead, we just default to 0 for keys we don't know.\n\n var toIndex = allKeys.indexOf(toLocation.key);\n if (toIndex === -1) toIndex = 0;\n var fromIndex = allKeys.indexOf(fromLocation.key);\n if (fromIndex === -1) fromIndex = 0;\n var delta = toIndex - fromIndex;\n\n if (delta) {\n forceNextPop = true;\n go(delta);\n }\n }\n\n var initialLocation = getDOMLocation(getHistoryState());\n var allKeys = [initialLocation.key]; // Public interface\n\n function createHref(location) {\n return basename + createPath(location);\n }\n\n function push(path, state) {\n true ? Object(tiny_warning__WEBPACK_IMPORTED_MODULE_3__[\"default\"])(!(typeof path === 'object' && path.state !== undefined && state !== undefined), 'You should avoid providing a 2nd state argument to push when the 1st ' + 'argument is a location-like object that already has state; it is ignored') : undefined;\n var action = 'PUSH';\n var location = createLocation(path, state, createKey(), history.location);\n transitionManager.confirmTransitionTo(location, action, getUserConfirmation, function (ok) {\n if (!ok) return;\n var href = createHref(location);\n var key = location.key,\n state = location.state;\n\n if (canUseHistory) {\n globalHistory.pushState({\n key: key,\n state: state\n }, null, href);\n\n if (forceRefresh) {\n window.location.href = href;\n } else {\n var prevIndex = allKeys.indexOf(history.location.key);\n var nextKeys = allKeys.slice(0, prevIndex + 1);\n nextKeys.push(location.key);\n allKeys = nextKeys;\n setState({\n action: action,\n location: location\n });\n }\n } else {\n true ? Object(tiny_warning__WEBPACK_IMPORTED_MODULE_3__[\"default\"])(state === undefined, 'Browser history cannot push state in browsers that do not support HTML5 history') : undefined;\n window.location.href = href;\n }\n });\n }\n\n function replace(path, state) {\n true ? Object(tiny_warning__WEBPACK_IMPORTED_MODULE_3__[\"default\"])(!(typeof path === 'object' && path.state !== undefined && state !== undefined), 'You should avoid providing a 2nd state argument to replace when the 1st ' + 'argument is a location-like object that already has state; it is ignored') : undefined;\n var action = 'REPLACE';\n var location = createLocation(path, state, createKey(), history.location);\n transitionManager.confirmTransitionTo(location, action, getUserConfirmation, function (ok) {\n if (!ok) return;\n var href = createHref(location);\n var key = location.key,\n state = location.state;\n\n if (canUseHistory) {\n globalHistory.replaceState({\n key: key,\n state: state\n }, null, href);\n\n if (forceRefresh) {\n window.location.replace(href);\n } else {\n var prevIndex = allKeys.indexOf(history.location.key);\n if (prevIndex !== -1) allKeys[prevIndex] = location.key;\n setState({\n action: action,\n location: location\n });\n }\n } else {\n true ? Object(tiny_warning__WEBPACK_IMPORTED_MODULE_3__[\"default\"])(state === undefined, 'Browser history cannot replace state in browsers that do not support HTML5 history') : undefined;\n window.location.replace(href);\n }\n });\n }\n\n function go(n) {\n globalHistory.go(n);\n }\n\n function goBack() {\n go(-1);\n }\n\n function goForward() {\n go(1);\n }\n\n var listenerCount = 0;\n\n function checkDOMListeners(delta) {\n listenerCount += delta;\n\n if (listenerCount === 1 && delta === 1) {\n window.addEventListener(PopStateEvent, handlePopState);\n if (needsHashChangeListener) window.addEventListener(HashChangeEvent, handleHashChange);\n } else if (listenerCount === 0) {\n window.removeEventListener(PopStateEvent, handlePopState);\n if (needsHashChangeListener) window.removeEventListener(HashChangeEvent, handleHashChange);\n }\n }\n\n var isBlocked = false;\n\n function block(prompt) {\n if (prompt === void 0) {\n prompt = false;\n }\n\n var unblock = transitionManager.setPrompt(prompt);\n\n if (!isBlocked) {\n checkDOMListeners(1);\n isBlocked = true;\n }\n\n return function () {\n if (isBlocked) {\n isBlocked = false;\n checkDOMListeners(-1);\n }\n\n return unblock();\n };\n }\n\n function listen(listener) {\n var unlisten = transitionManager.appendListener(listener);\n checkDOMListeners(1);\n return function () {\n checkDOMListeners(-1);\n unlisten();\n };\n }\n\n var history = {\n length: globalHistory.length,\n action: 'POP',\n location: initialLocation,\n createHref: createHref,\n push: push,\n replace: replace,\n go: go,\n goBack: goBack,\n goForward: goForward,\n block: block,\n listen: listen\n };\n return history;\n}\n\nvar HashChangeEvent$1 = 'hashchange';\nvar HashPathCoders = {\n hashbang: {\n encodePath: function encodePath(path) {\n return path.charAt(0) === '!' ? path : '!/' + stripLeadingSlash(path);\n },\n decodePath: function decodePath(path) {\n return path.charAt(0) === '!' ? path.substr(1) : path;\n }\n },\n noslash: {\n encodePath: stripLeadingSlash,\n decodePath: addLeadingSlash\n },\n slash: {\n encodePath: addLeadingSlash,\n decodePath: addLeadingSlash\n }\n};\n\nfunction stripHash(url) {\n var hashIndex = url.indexOf('#');\n return hashIndex === -1 ? url : url.slice(0, hashIndex);\n}\n\nfunction getHashPath() {\n // We can't use window.location.hash here because it's not\n // consistent across browsers - Firefox will pre-decode it!\n var href = window.location.href;\n var hashIndex = href.indexOf('#');\n return hashIndex === -1 ? '' : href.substring(hashIndex + 1);\n}\n\nfunction pushHashPath(path) {\n window.location.hash = path;\n}\n\nfunction replaceHashPath(path) {\n window.location.replace(stripHash(window.location.href) + '#' + path);\n}\n\nfunction createHashHistory(props) {\n if (props === void 0) {\n props = {};\n }\n\n !canUseDOM ? true ? Object(tiny_invariant__WEBPACK_IMPORTED_MODULE_4__[\"default\"])(false, 'Hash history needs a DOM') : undefined : void 0;\n var globalHistory = window.history;\n var canGoWithoutReload = supportsGoWithoutReloadUsingHash();\n var _props = props,\n _props$getUserConfirm = _props.getUserConfirmation,\n getUserConfirmation = _props$getUserConfirm === void 0 ? getConfirmation : _props$getUserConfirm,\n _props$hashType = _props.hashType,\n hashType = _props$hashType === void 0 ? 'slash' : _props$hashType;\n var basename = props.basename ? stripTrailingSlash(addLeadingSlash(props.basename)) : '';\n var _HashPathCoders$hashT = HashPathCoders[hashType],\n encodePath = _HashPathCoders$hashT.encodePath,\n decodePath = _HashPathCoders$hashT.decodePath;\n\n function getDOMLocation() {\n var path = decodePath(getHashPath());\n true ? Object(tiny_warning__WEBPACK_IMPORTED_MODULE_3__[\"default\"])(!basename || hasBasename(path, basename), 'You are attempting to use a basename on a page whose URL path does not begin ' + 'with the basename. Expected path \"' + path + '\" to begin with \"' + basename + '\".') : undefined;\n if (basename) path = stripBasename(path, basename);\n return createLocation(path);\n }\n\n var transitionManager = createTransitionManager();\n\n function setState(nextState) {\n Object(_babel_runtime_helpers_esm_extends__WEBPACK_IMPORTED_MODULE_0__[\"default\"])(history, nextState);\n\n history.length = globalHistory.length;\n transitionManager.notifyListeners(history.location, history.action);\n }\n\n var forceNextPop = false;\n var ignorePath = null;\n\n function locationsAreEqual$$1(a, b) {\n return a.pathname === b.pathname && a.search === b.search && a.hash === b.hash;\n }\n\n function handleHashChange() {\n var path = getHashPath();\n var encodedPath = encodePath(path);\n\n if (path !== encodedPath) {\n // Ensure we always have a properly-encoded hash.\n replaceHashPath(encodedPath);\n } else {\n var location = getDOMLocation();\n var prevLocation = history.location;\n if (!forceNextPop && locationsAreEqual$$1(prevLocation, location)) return; // A hashchange doesn't always == location change.\n\n if (ignorePath === createPath(location)) return; // Ignore this change; we already setState in push/replace.\n\n ignorePath = null;\n handlePop(location);\n }\n }\n\n function handlePop(location) {\n if (forceNextPop) {\n forceNextPop = false;\n setState();\n } else {\n var action = 'POP';\n transitionManager.confirmTransitionTo(location, action, getUserConfirmation, function (ok) {\n if (ok) {\n setState({\n action: action,\n location: location\n });\n } else {\n revertPop(location);\n }\n });\n }\n }\n\n function revertPop(fromLocation) {\n var toLocation = history.location; // TODO: We could probably make this more reliable by\n // keeping a list of paths we've seen in sessionStorage.\n // Instead, we just default to 0 for paths we don't know.\n\n var toIndex = allPaths.lastIndexOf(createPath(toLocation));\n if (toIndex === -1) toIndex = 0;\n var fromIndex = allPaths.lastIndexOf(createPath(fromLocation));\n if (fromIndex === -1) fromIndex = 0;\n var delta = toIndex - fromIndex;\n\n if (delta) {\n forceNextPop = true;\n go(delta);\n }\n } // Ensure the hash is encoded properly before doing anything else.\n\n\n var path = getHashPath();\n var encodedPath = encodePath(path);\n if (path !== encodedPath) replaceHashPath(encodedPath);\n var initialLocation = getDOMLocation();\n var allPaths = [createPath(initialLocation)]; // Public interface\n\n function createHref(location) {\n var baseTag = document.querySelector('base');\n var href = '';\n\n if (baseTag && baseTag.getAttribute('href')) {\n href = stripHash(window.location.href);\n }\n\n return href + '#' + encodePath(basename + createPath(location));\n }\n\n function push(path, state) {\n true ? Object(tiny_warning__WEBPACK_IMPORTED_MODULE_3__[\"default\"])(state === undefined, 'Hash history cannot push state; it is ignored') : undefined;\n var action = 'PUSH';\n var location = createLocation(path, undefined, undefined, history.location);\n transitionManager.confirmTransitionTo(location, action, getUserConfirmation, function (ok) {\n if (!ok) return;\n var path = createPath(location);\n var encodedPath = encodePath(basename + path);\n var hashChanged = getHashPath() !== encodedPath;\n\n if (hashChanged) {\n // We cannot tell if a hashchange was caused by a PUSH, so we'd\n // rather setState here and ignore the hashchange. The caveat here\n // is that other hash histories in the page will consider it a POP.\n ignorePath = path;\n pushHashPath(encodedPath);\n var prevIndex = allPaths.lastIndexOf(createPath(history.location));\n var nextPaths = allPaths.slice(0, prevIndex + 1);\n nextPaths.push(path);\n allPaths = nextPaths;\n setState({\n action: action,\n location: location\n });\n } else {\n true ? Object(tiny_warning__WEBPACK_IMPORTED_MODULE_3__[\"default\"])(false, 'Hash history cannot PUSH the same path; a new entry will not be added to the history stack') : undefined;\n setState();\n }\n });\n }\n\n function replace(path, state) {\n true ? Object(tiny_warning__WEBPACK_IMPORTED_MODULE_3__[\"default\"])(state === undefined, 'Hash history cannot replace state; it is ignored') : undefined;\n var action = 'REPLACE';\n var location = createLocation(path, undefined, undefined, history.location);\n transitionManager.confirmTransitionTo(location, action, getUserConfirmation, function (ok) {\n if (!ok) return;\n var path = createPath(location);\n var encodedPath = encodePath(basename + path);\n var hashChanged = getHashPath() !== encodedPath;\n\n if (hashChanged) {\n // We cannot tell if a hashchange was caused by a REPLACE, so we'd\n // rather setState here and ignore the hashchange. The caveat here\n // is that other hash histories in the page will consider it a POP.\n ignorePath = path;\n replaceHashPath(encodedPath);\n }\n\n var prevIndex = allPaths.indexOf(createPath(history.location));\n if (prevIndex !== -1) allPaths[prevIndex] = path;\n setState({\n action: action,\n location: location\n });\n });\n }\n\n function go(n) {\n true ? Object(tiny_warning__WEBPACK_IMPORTED_MODULE_3__[\"default\"])(canGoWithoutReload, 'Hash history go(n) causes a full page reload in this browser') : undefined;\n globalHistory.go(n);\n }\n\n function goBack() {\n go(-1);\n }\n\n function goForward() {\n go(1);\n }\n\n var listenerCount = 0;\n\n function checkDOMListeners(delta) {\n listenerCount += delta;\n\n if (listenerCount === 1 && delta === 1) {\n window.addEventListener(HashChangeEvent$1, handleHashChange);\n } else if (listenerCount === 0) {\n window.removeEventListener(HashChangeEvent$1, handleHashChange);\n }\n }\n\n var isBlocked = false;\n\n function block(prompt) {\n if (prompt === void 0) {\n prompt = false;\n }\n\n var unblock = transitionManager.setPrompt(prompt);\n\n if (!isBlocked) {\n checkDOMListeners(1);\n isBlocked = true;\n }\n\n return function () {\n if (isBlocked) {\n isBlocked = false;\n checkDOMListeners(-1);\n }\n\n return unblock();\n };\n }\n\n function listen(listener) {\n var unlisten = transitionManager.appendListener(listener);\n checkDOMListeners(1);\n return function () {\n checkDOMListeners(-1);\n unlisten();\n };\n }\n\n var history = {\n length: globalHistory.length,\n action: 'POP',\n location: initialLocation,\n createHref: createHref,\n push: push,\n replace: replace,\n go: go,\n goBack: goBack,\n goForward: goForward,\n block: block,\n listen: listen\n };\n return history;\n}\n\nfunction clamp(n, lowerBound, upperBound) {\n return Math.min(Math.max(n, lowerBound), upperBound);\n}\n/**\n * Creates a history object that stores locations in memory.\n */\n\n\nfunction createMemoryHistory(props) {\n if (props === void 0) {\n props = {};\n }\n\n var _props = props,\n getUserConfirmation = _props.getUserConfirmation,\n _props$initialEntries = _props.initialEntries,\n initialEntries = _props$initialEntries === void 0 ? ['/'] : _props$initialEntries,\n _props$initialIndex = _props.initialIndex,\n initialIndex = _props$initialIndex === void 0 ? 0 : _props$initialIndex,\n _props$keyLength = _props.keyLength,\n keyLength = _props$keyLength === void 0 ? 6 : _props$keyLength;\n var transitionManager = createTransitionManager();\n\n function setState(nextState) {\n Object(_babel_runtime_helpers_esm_extends__WEBPACK_IMPORTED_MODULE_0__[\"default\"])(history, nextState);\n\n history.length = history.entries.length;\n transitionManager.notifyListeners(history.location, history.action);\n }\n\n function createKey() {\n return Math.random().toString(36).substr(2, keyLength);\n }\n\n var index = clamp(initialIndex, 0, initialEntries.length - 1);\n var entries = initialEntries.map(function (entry) {\n return typeof entry === 'string' ? createLocation(entry, undefined, createKey()) : createLocation(entry, undefined, entry.key || createKey());\n }); // Public interface\n\n var createHref = createPath;\n\n function push(path, state) {\n true ? Object(tiny_warning__WEBPACK_IMPORTED_MODULE_3__[\"default\"])(!(typeof path === 'object' && path.state !== undefined && state !== undefined), 'You should avoid providing a 2nd state argument to push when the 1st ' + 'argument is a location-like object that already has state; it is ignored') : undefined;\n var action = 'PUSH';\n var location = createLocation(path, state, createKey(), history.location);\n transitionManager.confirmTransitionTo(location, action, getUserConfirmation, function (ok) {\n if (!ok) return;\n var prevIndex = history.index;\n var nextIndex = prevIndex + 1;\n var nextEntries = history.entries.slice(0);\n\n if (nextEntries.length > nextIndex) {\n nextEntries.splice(nextIndex, nextEntries.length - nextIndex, location);\n } else {\n nextEntries.push(location);\n }\n\n setState({\n action: action,\n location: location,\n index: nextIndex,\n entries: nextEntries\n });\n });\n }\n\n function replace(path, state) {\n true ? Object(tiny_warning__WEBPACK_IMPORTED_MODULE_3__[\"default\"])(!(typeof path === 'object' && path.state !== undefined && state !== undefined), 'You should avoid providing a 2nd state argument to replace when the 1st ' + 'argument is a location-like object that already has state; it is ignored') : undefined;\n var action = 'REPLACE';\n var location = createLocation(path, state, createKey(), history.location);\n transitionManager.confirmTransitionTo(location, action, getUserConfirmation, function (ok) {\n if (!ok) return;\n history.entries[history.index] = location;\n setState({\n action: action,\n location: location\n });\n });\n }\n\n function go(n) {\n var nextIndex = clamp(history.index + n, 0, history.entries.length - 1);\n var action = 'POP';\n var location = history.entries[nextIndex];\n transitionManager.confirmTransitionTo(location, action, getUserConfirmation, function (ok) {\n if (ok) {\n setState({\n action: action,\n location: location,\n index: nextIndex\n });\n } else {\n // Mimic the behavior of DOM histories by\n // causing a render after a cancelled POP.\n setState();\n }\n });\n }\n\n function goBack() {\n go(-1);\n }\n\n function goForward() {\n go(1);\n }\n\n function canGo(n) {\n var nextIndex = history.index + n;\n return nextIndex >= 0 && nextIndex < history.entries.length;\n }\n\n function block(prompt) {\n if (prompt === void 0) {\n prompt = false;\n }\n\n return transitionManager.setPrompt(prompt);\n }\n\n function listen(listener) {\n return transitionManager.appendListener(listener);\n }\n\n var history = {\n length: entries.length,\n action: 'POP',\n location: entries[index],\n index: index,\n entries: entries,\n createHref: createHref,\n push: push,\n replace: replace,\n go: go,\n goBack: goBack,\n goForward: goForward,\n canGo: canGo,\n block: block,\n listen: listen\n };\n return history;\n}\n\n\n\n\n//# sourceURL=webpack:///./node_modules/history/esm/history.js?");
/***/ }),
/***/ "./node_modules/hoist-non-react-statics/dist/hoist-non-react-statics.cjs.js":
/*!**********************************************************************************!*\
!*** ./node_modules/hoist-non-react-statics/dist/hoist-non-react-statics.cjs.js ***!
\**********************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
eval("\n\nvar reactIs = __webpack_require__(/*! react-is */ \"./node_modules/react-is/index.js\");\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\n\n//# sourceURL=webpack:///./node_modules/hoist-non-react-statics/dist/hoist-non-react-statics.cjs.js?");
/***/ }),
/***/ "./node_modules/lodash.omit/index.js":
/*!*******************************************!*\
!*** ./node_modules/lodash.omit/index.js ***!
\*******************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
eval("/* WEBPACK VAR INJECTION */(function(global) {/**\n * lodash (Custom Build) <https://lodash.com/>\n * Build: `lodash modularize exports=\"npm\" -o ./`\n * Copyright jQuery Foundation and other contributors <https://jquery.org/>\n * Released under MIT license <https://lodash.com/license>\n * Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE>\n * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors\n */\n\n/** Used as the size to enable large array optimizations. */\nvar LARGE_ARRAY_SIZE = 200;\n\n/** Used to stand-in for `undefined` hash values. */\nvar HASH_UNDEFINED = '__lodash_hash_undefined__';\n\n/** Used as references for various `Number` constants. */\nvar INFINITY = 1 / 0,\n MAX_SAFE_INTEGER = 9007199254740991;\n\n/** `Object#toString` result references. */\nvar argsTag = '[object Arguments]',\n funcTag = '[object Function]',\n genTag = '[object GeneratorFunction]',\n symbolTag = '[object Symbol]';\n\n/**\n * Used to match `RegExp`\n * [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns).\n */\nvar reRegExpChar = /[\\\\^$.*+?()[\\]{}|]/g;\n\n/** Used to detect host constructors (Safari). */\nvar reIsHostCtor = /^\\[object .+?Constructor\\]$/;\n\n/** Used to detect unsigned integer values. */\nvar reIsUint = /^(?:0|[1-9]\\d*)$/;\n\n/** Detect free variable `global` from Node.js. */\nvar freeGlobal = typeof global == 'object' && global && global.Object === Object && global;\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\n/**\n * A faster alternative to `Function#apply`, this function invokes `func`\n * with the `this` binding of `thisArg` and the arguments of `args`.\n *\n * @private\n * @param {Function} func The function to invoke.\n * @param {*} thisArg The `this` binding of `func`.\n * @param {Array} args The arguments to invoke `func` with.\n * @returns {*} Returns the result of `func`.\n */\nfunction apply(func, thisArg, args) {\n switch (args.length) {\n case 0: return func.call(thisArg);\n case 1: return func.call(thisArg, args[0]);\n case 2: return func.call(thisArg, args[0], args[1]);\n case 3: return func.call(thisArg, args[0], args[1], args[2]);\n }\n return func.apply(thisArg, args);\n}\n\n/**\n * A specialized version of `_.includes` for arrays without support for\n * specifying an index to search from.\n *\n * @private\n * @param {Array} [array] The array to inspect.\n * @param {*} target The value to search for.\n * @returns {boolean} Returns `true` if `target` is found, else `false`.\n */\nfunction arrayIncludes(array, value) {\n var length = array ? array.length : 0;\n return !!length && baseIndexOf(array, value, 0) > -1;\n}\n\n/**\n * This function is like `arrayIncludes` except that it accepts a comparator.\n *\n * @private\n * @param {Array} [array] The array to inspect.\n * @param {*} target The value to search for.\n * @param {Function} comparator The comparator invoked per element.\n * @returns {boolean} Returns `true` if `target` is found, else `false`.\n */\nfunction arrayIncludesWith(array, value, comparator) {\n var index = -1,\n length = array ? array.length : 0;\n\n while (++index < length) {\n if (comparator(value, array[index])) {\n return true;\n }\n }\n return false;\n}\n\n/**\n * A specialized version of `_.map` for arrays without support for iteratee\n * shorthands.\n *\n * @private\n * @param {Array} [array] The array to iterate over.\n * @param {Function} iteratee The function invoked per iteration.\n * @returns {Array} Returns the new mapped array.\n */\nfunction arrayMap(array, iteratee) {\n var index = -1,\n length = array ? array.length : 0,\n result = Array(length);\n\n while (++index < length) {\n result[index] = iteratee(array[index], index, array);\n }\n return result;\n}\n\n/**\n * Appends the elements of `values` to `array`.\n *\n * @private\n * @param {Array} array The array to modify.\n * @param {Array} values The values to append.\n * @returns {Array} Returns `array`.\n */\nfunction arrayPush(array, values) {\n var index = -1,\n length = values.length,\n offset = array.length;\n\n while (++index < length) {\n array[offset + index] = values[index];\n }\n return array;\n}\n\n/**\n * The base implementation of `_.findIndex` and `_.findLastIndex` without\n * support for iteratee shorthands.\n *\n * @private\n * @param {Array} array The array to inspect.\n * @param {Function} predicate The function invoked per iteration.\n * @param {number} fromIndex The index to search from.\n * @param {boolean} [fromRight] Specify iterating from right to left.\n * @returns {number} Returns the index of the matched value, else `-1`.\n */\nfunction baseFindIndex(array, predicate, fromIndex, fromRight) {\n var length = array.length,\n index = fromIndex + (fromRight ? 1 : -1);\n\n while ((fromRight ? index-- : ++index < length)) {\n if (predicate(array[index], index, array)) {\n return index;\n }\n }\n return -1;\n}\n\n/**\n * The base implementation of `_.indexOf` without `fromIndex` bounds checks.\n *\n * @private\n * @param {Array} array The array to inspect.\n * @param {*} value The value to search for.\n * @param {number} fromIndex The index to search from.\n * @returns {number} Returns the index of the matched value, else `-1`.\n */\nfunction baseIndexOf(array, value, fromIndex) {\n if (value !== value) {\n return baseFindIndex(array, baseIsNaN, fromIndex);\n }\n var index = fromIndex - 1,\n length = array.length;\n\n while (++index < length) {\n if (array[index] === value) {\n return index;\n }\n }\n return -1;\n}\n\n/**\n * The base implementation of `_.isNaN` without support for number objects.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is `NaN`, else `false`.\n */\nfunction baseIsNaN(value) {\n return value !== value;\n}\n\n/**\n * The base implementation of `_.times` without support for iteratee shorthands\n * or max array length checks.\n *\n * @private\n * @param {number} n The number of times to invoke `iteratee`.\n * @param {Function} iteratee The function invoked per iteration.\n * @returns {Array} Returns the array of results.\n */\nfunction baseTimes(n, iteratee) {\n var index = -1,\n result = Array(n);\n\n while (++index < n) {\n result[index] = iteratee(index);\n }\n return result;\n}\n\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\n/**\n * Checks if a cache value for `key` exists.\n *\n * @private\n * @param {Object} cache The cache to query.\n * @param {string} key The key of the entry to check.\n * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.\n */\nfunction cacheHas(cache, key) {\n return cache.has(key);\n}\n\n/**\n * Gets the value at `key` of `object`.\n *\n * @private\n * @param {Object} [object] The object to query.\n * @param {string} key The key of the property to get.\n * @returns {*} Returns the property value.\n */\nfunction getValue(object, key) {\n return object == null ? undefined : object[key];\n}\n\n/**\n * Checks if `value` is a host object in IE < 9.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a host object, else `false`.\n */\nfunction isHostObject(value) {\n // Many host objects are `Object` objects that can coerce to strings\n // despite having improperly defined `toString` methods.\n var result = false;\n if (value != null && typeof value.toString != 'function') {\n try {\n result = !!(value + '');\n } catch (e) {}\n }\n return result;\n}\n\n/**\n * Creates a unary function that invokes `func` with its argument transformed.\n *\n * @private\n * @param {Function} func The function to wrap.\n * @param {Function} transform The argument transform.\n * @returns {Function} Returns the new function.\n */\nfunction overArg(func, transform) {\n return function(arg) {\n return func(transform(arg));\n };\n}\n\n/** Used for built-in method references. */\nvar arrayProto = Array.prototype,\n funcProto = Function.prototype,\n objectProto = Object.prototype;\n\n/** Used to detect overreaching core-js shims. */\nvar coreJsData = root['__core-js_shared__'];\n\n/** Used to detect methods masquerading as native. */\nvar maskSrcKey = (function() {\n var uid = /[^.]+$/.exec(coreJsData && coreJsData.keys && coreJsData.keys.IE_PROTO || '');\n return uid ? ('Symbol(src)_1.' + uid) : '';\n}());\n\n/** Used to resolve the decompiled source of functions. */\nvar funcToString = funcProto.toString;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\n\n/**\n * Used to resolve the\n * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)\n * of values.\n */\nvar objectToString = objectProto.toString;\n\n/** Used to detect if a method is native. */\nvar reIsNative = RegExp('^' +\n funcToString.call(hasOwnProperty).replace(reRegExpChar, '\\\\$&')\n .replace(/hasOwnProperty|(function).*?(?=\\\\\\()| for .+?(?=\\\\\\])/g, '$1.*?') + '$'\n);\n\n/** Built-in value references. */\nvar Symbol = root.Symbol,\n getPrototype = overArg(Object.getPrototypeOf, Object),\n propertyIsEnumerable = objectProto.propertyIsEnumerable,\n splice = arrayProto.splice,\n spreadableSymbol = Symbol ? Symbol.isConcatSpreadable : undefined;\n\n/* Built-in method references for those with the same name as other `lodash` methods. */\nvar nativeGetSymbols = Object.getOwnPropertySymbols,\n nativeMax = Math.max;\n\n/* Built-in method references that are verified to be native. */\nvar Map = getNative(root, 'Map'),\n nativeCreate = getNative(Object, 'create');\n\n/**\n * Creates a hash object.\n *\n * @private\n * @constructor\n * @param {Array} [entries] The key-value pairs to cache.\n */\nfunction Hash(entries) {\n var index = -1,\n length = entries ? entries.length : 0;\n\n this.clear();\n while (++index < length) {\n var entry = entries[index];\n this.set(entry[0], entry[1]);\n }\n}\n\n/**\n * Removes all key-value entries from the hash.\n *\n * @private\n * @name clear\n * @memberOf Hash\n */\nfunction hashClear() {\n this.__data__ = nativeCreate ? nativeCreate(null) : {};\n}\n\n/**\n * Removes `key` and its value from the hash.\n *\n * @private\n * @name delete\n * @memberOf Hash\n * @param {Object} hash The hash to modify.\n * @param {string} key The key of the value to remove.\n * @returns {boolean} Returns `true` if the entry was removed, else `false`.\n */\nfunction hashDelete(key) {\n return this.has(key) && delete this.__data__[key];\n}\n\n/**\n * Gets the hash value for `key`.\n *\n * @private\n * @name get\n * @memberOf Hash\n * @param {string} key The key of the value to get.\n * @returns {*} Returns the entry value.\n */\nfunction hashGet(key) {\n var data = this.__data__;\n if (nativeCreate) {\n var result = data[key];\n return result === HASH_UNDEFINED ? undefined : result;\n }\n return hasOwnProperty.call(data, key) ? data[key] : undefined;\n}\n\n/**\n * Checks if a hash value for `key` exists.\n *\n * @private\n * @name has\n * @memberOf Hash\n * @param {string} key The key of the entry to check.\n * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.\n */\nfunction hashHas(key) {\n var data = this.__data__;\n return nativeCreate ? data[key] !== undefined : hasOwnProperty.call(data, key);\n}\n\n/**\n * Sets the hash `key` to `value`.\n *\n * @private\n * @name set\n * @memberOf Hash\n * @param {string} key The key of the value to set.\n * @param {*} value The value to set.\n * @returns {Object} Returns the hash instance.\n */\nfunction hashSet(key, value) {\n var data = this.__data__;\n data[key] = (nativeCreate && value === undefined) ? HASH_UNDEFINED : value;\n return this;\n}\n\n// Add methods to `Hash`.\nHash.prototype.clear = hashClear;\nHash.prototype['delete'] = hashDelete;\nHash.prototype.get = hashGet;\nHash.prototype.has = hashHas;\nHash.prototype.set = hashSet;\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 ? entries.length : 0;\n\n this.clear();\n while (++index < length) {\n var entry = entries[index];\n this.set(entry[0], entry[1]);\n }\n}\n\n/**\n * Removes all key-value entries from the list cache.\n *\n * @private\n * @name clear\n * @memberOf ListCache\n */\nfunction listCacheClear() {\n this.__data__ = [];\n}\n\n/**\n * Removes `key` and its value from the list cache.\n *\n * @private\n * @name delete\n * @memberOf ListCache\n * @param {string} key The key of the value to remove.\n * @returns {boolean} Returns `true` if the entry was removed, else `false`.\n */\nfunction listCacheDelete(key) {\n var data = this.__data__,\n index = assocIndexOf(data, key);\n\n if (index < 0) {\n return false;\n }\n var lastIndex = data.length - 1;\n if (index == lastIndex) {\n data.pop();\n } else {\n splice.call(data, index, 1);\n }\n return true;\n}\n\n/**\n * Gets the list cache value for `key`.\n *\n * @private\n * @name get\n * @memberOf ListCache\n * @param {string} key The key of the value to get.\n * @returns {*} Returns the entry value.\n */\nfunction listCacheGet(key) {\n var data = this.__data__,\n index = assocIndexOf(data, key);\n\n return index < 0 ? undefined : data[index][1];\n}\n\n/**\n * Checks if a list cache value for `key` exists.\n *\n * @private\n * @name has\n * @memberOf ListCache\n * @param {string} key The key of the entry to check.\n * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.\n */\nfunction listCacheHas(key) {\n return assocIndexOf(this.__data__, key) > -1;\n}\n\n/**\n * Sets the list cache `key` to `value`.\n *\n * @private\n * @name set\n * @memberOf ListCache\n * @param {string} key The key of the value to set.\n * @param {*} value The value to set.\n * @returns {Object} Returns the list cache instance.\n */\nfunction listCacheSet(key, value) {\n var data = this.__data__,\n index = assocIndexOf(data, key);\n\n if (index < 0) {\n data.push([key, value]);\n } else {\n data[index][1] = value;\n }\n return this;\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\n/**\n * Creates a map cache object to store key-value pairs.\n *\n * @private\n * @constructor\n * @param {Array} [entries] The key-value pairs to cache.\n */\nfunction MapCache(entries) {\n var index = -1,\n length = entries ? entries.length : 0;\n\n this.clear();\n while (++index < length) {\n var entry = entries[index];\n this.set(entry[0], entry[1]);\n }\n}\n\n/**\n * Removes all key-value entries from the map.\n *\n * @private\n * @name clear\n * @memberOf MapCache\n */\nfunction mapCacheClear() {\n this.__data__ = {\n 'hash': new Hash,\n 'map': new (Map || ListCache),\n 'string': new Hash\n };\n}\n\n/**\n * Removes `key` and its value from the map.\n *\n * @private\n * @name delete\n * @memberOf MapCache\n * @param {string} key The key of the value to remove.\n * @returns {boolean} Returns `true` if the entry was removed, else `false`.\n */\nfunction mapCacheDelete(key) {\n return getMapData(this, key)['delete'](key);\n}\n\n/**\n * Gets the map value for `key`.\n *\n * @private\n * @name get\n * @memberOf MapCache\n * @param {string} key The key of the value to get.\n * @returns {*} Returns the entry value.\n */\nfunction mapCacheGet(key) {\n return getMapData(this, key).get(key);\n}\n\n/**\n * Checks if a map value for `key` exists.\n *\n * @private\n * @name has\n * @memberOf MapCache\n * @param {string} key The key of the entry to check.\n * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.\n */\nfunction mapCacheHas(key) {\n return getMapData(this, key).has(key);\n}\n\n/**\n * Sets the map `key` to `value`.\n *\n * @private\n * @name set\n * @memberOf MapCache\n * @param {string} key The key of the value to set.\n * @param {*} value The value to set.\n * @returns {Object} Returns the map cache instance.\n */\nfunction mapCacheSet(key, value) {\n getMapData(this, key).set(key, value);\n return this;\n}\n\n// Add methods to `MapCache`.\nMapCache.prototype.clear = mapCacheClear;\nMapCache.prototype['delete'] = mapCacheDelete;\nMapCache.prototype.get = mapCacheGet;\nMapCache.prototype.has = mapCacheHas;\nMapCache.prototype.set = mapCacheSet;\n\n/**\n *\n * Creates an array cache object to store unique values.\n *\n * @private\n * @constructor\n * @param {Array} [values] The values to cache.\n */\nfunction SetCache(values) {\n var index = -1,\n length = values ? values.length : 0;\n\n this.__data__ = new MapCache;\n while (++index < length) {\n this.add(values[index]);\n }\n}\n\n/**\n * Adds `value` to the array cache.\n *\n * @private\n * @name add\n * @memberOf SetCache\n * @alias push\n * @param {*} value The value to cache.\n * @returns {Object} Returns the cache instance.\n */\nfunction setCacheAdd(value) {\n this.__data__.set(value, HASH_UNDEFINED);\n return this;\n}\n\n/**\n * Checks if `value` is in the array cache.\n *\n * @private\n * @name has\n * @memberOf SetCache\n * @param {*} value The value to search for.\n * @returns {number} Returns `true` if `value` is found, else `false`.\n */\nfunction setCacheHas(value) {\n return this.__data__.has(value);\n}\n\n// Add methods to `SetCache`.\nSetCache.prototype.add = SetCache.prototype.push = setCacheAdd;\nSetCache.prototype.has = setCacheHas;\n\n/**\n * Creates an array of the enumerable property names of the array-like `value`.\n *\n * @private\n * @param {*} value The value to query.\n * @param {boolean} inherited Specify returning inherited property names.\n * @returns {Array} Returns the array of property names.\n */\nfunction arrayLikeKeys(value, inherited) {\n // Safari 8.1 makes `arguments.callee` enumerable in strict mode.\n // Safari 9 makes `arguments.length` enumerable in strict mode.\n var result = (isArray(value) || isArguments(value))\n ? baseTimes(value.length, String)\n : [];\n\n var length = result.length,\n skipIndexes = !!length;\n\n for (var key in value) {\n if ((inherited || hasOwnProperty.call(value, key)) &&\n !(skipIndexes && (key == 'length' || isIndex(key, length)))) {\n result.push(key);\n }\n }\n return result;\n}\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\n/**\n * The base implementation of methods like `_.difference` without support\n * for excluding multiple arrays or iteratee shorthands.\n *\n * @private\n * @param {Array} array The array to inspect.\n * @param {Array} values The values to exclude.\n * @param {Function} [iteratee] The iteratee invoked per element.\n * @param {Function} [comparator] The comparator invoked per element.\n * @returns {Array} Returns the new array of filtered values.\n */\nfunction baseDifference(array, values, iteratee, comparator) {\n var index = -1,\n includes = arrayIncludes,\n isCommon = true,\n length = array.length,\n result = [],\n valuesLength = values.length;\n\n if (!length) {\n return result;\n }\n if (iteratee) {\n values = arrayMap(values, baseUnary(iteratee));\n }\n if (comparator) {\n includes = arrayIncludesWith;\n isCommon = false;\n }\n else if (values.length >= LARGE_ARRAY_SIZE) {\n includes = cacheHas;\n isCommon = false;\n values = new SetCache(values);\n }\n outer:\n while (++index < length) {\n var value = array[index],\n computed = iteratee ? iteratee(value) : value;\n\n value = (comparator || value !== 0) ? value : 0;\n if (isCommon && computed === computed) {\n var valuesIndex = valuesLength;\n while (valuesIndex--) {\n if (values[valuesIndex] === computed) {\n continue outer;\n }\n }\n result.push(value);\n }\n else if (!includes(values, computed, comparator)) {\n result.push(value);\n }\n }\n return result;\n}\n\n/**\n * The base implementation of `_.flatten` with support for restricting flattening.\n *\n * @private\n * @param {Array} array The array to flatten.\n * @param {number} depth The maximum recursion depth.\n * @param {boolean} [predicate=isFlattenable] The function invoked per iteration.\n * @param {boolean} [isStrict] Restrict to values that pass `predicate` checks.\n * @param {Array} [result=[]] The initial result value.\n * @returns {Array} Returns the new flattened array.\n */\nfunction baseFlatten(array, depth, predicate, isStrict, result) {\n var index = -1,\n length = array.length;\n\n predicate || (predicate = isFlattenable);\n result || (result = []);\n\n while (++index < length) {\n var value = array[index];\n if (depth > 0 && predicate(value)) {\n if (depth > 1) {\n // Recursively flatten arrays (susceptible to call stack limits).\n baseFlatten(value, depth - 1, predicate, isStrict, result);\n } else {\n arrayPush(result, value);\n }\n } else if (!isStrict) {\n result[result.length] = value;\n }\n }\n return result;\n}\n\n/**\n * The base implementation of `getAllKeys` and `getAllKeysIn` which uses\n * `keysFunc` and `symbolsFunc` to get the enumerable property names and\n * symbols of `object`.\n *\n * @private\n * @param {Object} object The object to query.\n * @param {Function} keysFunc The function to get the keys of `object`.\n * @param {Function} symbolsFunc The function to get the symbols of `object`.\n * @returns {Array} Returns the array of property names and symbols.\n */\nfunction baseGetAllKeys(object, keysFunc, symbolsFunc) {\n var result = keysFunc(object);\n return isArray(object) ? result : arrayPush(result, symbolsFunc(object));\n}\n\n/**\n * The base implementation of `_.isNative` without bad shim checks.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a native function,\n * else `false`.\n */\nfunction baseIsNative(value) {\n if (!isObject(value) || isMasked(value)) {\n return false;\n }\n var pattern = (isFunction(value) || isHostObject(value)) ? reIsNative : reIsHostCtor;\n return pattern.test(toSource(value));\n}\n\n/**\n * The base implementation of `_.keysIn` which doesn't treat sparse arrays as dense.\n *\n * @private\n * @param {Object} object The object to query.\n * @returns {Array} Returns the array of property names.\n */\nfunction baseKeysIn(object) {\n if (!isObject(object)) {\n return nativeKeysIn(object);\n }\n var isProto = isPrototype(object),\n result = [];\n\n for (var key in object) {\n if (!(key == 'constructor' && (isProto || !hasOwnProperty.call(object, key)))) {\n result.push(key);\n }\n }\n return result;\n}\n\n/**\n * The base implementation of `_.pick` without support for individual\n * property identifiers.\n *\n * @private\n * @param {Object} object The source object.\n * @param {string[]} props The property identifiers to pick.\n * @returns {Object} Returns the new object.\n */\nfunction basePick(object, props) {\n object = Object(object);\n return basePickBy(object, props, function(value, key) {\n return key in object;\n });\n}\n\n/**\n * The base implementation of `_.pickBy` without support for iteratee shorthands.\n *\n * @private\n * @param {Object} object The source object.\n * @param {string[]} props The property identifiers to pick from.\n * @param {Function} predicate The function invoked per property.\n * @returns {Object} Returns the new object.\n */\nfunction basePickBy(object, props, predicate) {\n var index = -1,\n length = props.length,\n result = {};\n\n while (++index < length) {\n var key = props[index],\n value = object[key];\n\n if (predicate(value, key)) {\n result[key] = value;\n }\n }\n return result;\n}\n\n/**\n * The base implementation of `_.rest` which doesn't validate or coerce arguments.\n *\n * @private\n * @param {Function} func The function to apply a rest parameter to.\n * @param {number} [start=func.length-1] The start position of the rest parameter.\n * @returns {Function} Returns the new function.\n */\nfunction baseRest(func, start) {\n start = nativeMax(start === undefined ? (func.length - 1) : start, 0);\n return function() {\n var args = arguments,\n index = -1,\n length = nativeMax(args.length - start, 0),\n array = Array(length);\n\n while (++index < length) {\n array[index] = args[start + index];\n }\n index = -1;\n var otherArgs = Array(start + 1);\n while (++index < start) {\n otherArgs[index] = args[index];\n }\n otherArgs[start] = array;\n return apply(func, this, otherArgs);\n };\n}\n\n/**\n * Creates an array of own and inherited enumerable property names and\n * symbols of `object`.\n *\n * @private\n * @param {Object} object The object to query.\n * @returns {Array} Returns the array of property names and symbols.\n */\nfunction getAllKeysIn(object) {\n return baseGetAllKeys(object, keysIn, getSymbolsIn);\n}\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\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\n/**\n * Creates an array of the own enumerable symbol properties of `object`.\n *\n * @private\n * @param {Object} object The object to query.\n * @returns {Array} Returns the array of symbols.\n */\nvar getSymbols = nativeGetSymbols ? overArg(nativeGetSymbols, Object) : stubArray;\n\n/**\n * Creates an array of the own and inherited enumerable symbol properties\n * of `object`.\n *\n * @private\n * @param {Object} object The object to query.\n * @returns {Array} Returns the array of symbols.\n */\nvar getSymbolsIn = !nativeGetSymbols ? stubArray : function(object) {\n var result = [];\n while (object) {\n arrayPush(result, getSymbols(object));\n object = getPrototype(object);\n }\n return result;\n};\n\n/**\n * Checks if `value` is a flattenable `arguments` object or array.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is flattenable, else `false`.\n */\nfunction isFlattenable(value) {\n return isArray(value) || isArguments(value) ||\n !!(spreadableSymbol && value && value[spreadableSymbol]);\n}\n\n/**\n * Checks if `value` is a valid array-like index.\n *\n * @private\n * @param {*} value The value to check.\n * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index.\n * @returns {boolean} Returns `true` if `value` is a valid index, else `false`.\n */\nfunction isIndex(value, length) {\n length = length == null ? MAX_SAFE_INTEGER : length;\n return !!length &&\n (typeof value == 'number' || reIsUint.test(value)) &&\n (value > -1 && value % 1 == 0 && value < length);\n}\n\n/**\n * Checks if `value` is suitable for use as unique object key.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is suitable, else `false`.\n */\nfunction isKeyable(value) {\n var type = typeof value;\n return (type == 'string' || type == 'number' || type == 'symbol' || type == 'boolean')\n ? (value !== '__proto__')\n : (value === null);\n}\n\n/**\n * Checks if `func` has its source masked.\n *\n * @private\n * @param {Function} func The function to check.\n * @returns {boolean} Returns `true` if `func` is masked, else `false`.\n */\nfunction isMasked(func) {\n return !!maskSrcKey && (maskSrcKey in func);\n}\n\n/**\n * Checks if `value` is likely a prototype object.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a prototype, else `false`.\n */\nfunction isPrototype(value) {\n var Ctor = value && value.constructor,\n proto = (typeof Ctor == 'function' && Ctor.prototype) || objectProto;\n\n return value === proto;\n}\n\n/**\n * This function is like\n * [`Object.keys`](http://ecma-international.org/ecma-262/7.0/#sec-object.keys)\n * except that it includes inherited enumerable properties.\n *\n * @private\n * @param {Object} object The object to query.\n * @returns {Array} Returns the array of property names.\n */\nfunction nativeKeysIn(object) {\n var result = [];\n if (object != null) {\n for (var key in Object(object)) {\n result.push(key);\n }\n }\n return result;\n}\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\n/**\n * Converts `func` to its source code.\n *\n * @private\n * @param {Function} func The function to process.\n * @returns {string} Returns the source code.\n */\nfunction toSource(func) {\n if (func != null) {\n try {\n return funcToString.call(func);\n } catch (e) {}\n try {\n return (func + '');\n } catch (e) {}\n }\n return '';\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\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 */\nfunction isArguments(value) {\n // Safari 8.1 makes `arguments.callee` enumerable in strict mode.\n return isArrayLikeObject(value) && hasOwnProperty.call(value, 'callee') &&\n (!propertyIsEnumerable.call(value, 'callee') || objectToString.call(value) == argsTag);\n}\n\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\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\n/**\n * This method is like `_.isArrayLike` except that it also checks if `value`\n * is an 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 an array-like object,\n * else `false`.\n * @example\n *\n * _.isArrayLikeObject([1, 2, 3]);\n * // => true\n *\n * _.isArrayLikeObject(document.body.children);\n * // => true\n *\n * _.isArrayLikeObject('abc');\n * // => false\n *\n * _.isArrayLikeObject(_.noop);\n * // => false\n */\nfunction isArrayLikeObject(value) {\n return isObjectLike(value) && isArrayLike(value);\n}\n\n/**\n * Checks if `value` is classified as a `Function` 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 a function, else `false`.\n * @example\n *\n * _.isFunction(_);\n * // => true\n *\n * _.isFunction(/abc/);\n * // => false\n */\nfunction isFunction(value) {\n // The use of `Object#toString` avoids issues with the `typeof` operator\n // in Safari 8-9 which returns 'object' for typed array and other constructors.\n var tag = isObject(value) ? objectToString.call(value) : '';\n return tag == funcTag || tag == genTag;\n}\n\n/**\n * Checks if `value` is a valid array-like length.\n *\n * **Note:** This method is loosely based on\n * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength).\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 valid length, else `false`.\n * @example\n *\n * _.isLength(3);\n * // => true\n *\n * _.isLength(Number.MIN_VALUE);\n * // => false\n *\n * _.isLength(Infinity);\n * // => false\n *\n * _.isLength('3');\n * // => false\n */\nfunction isLength(value) {\n return typeof value == 'number' &&\n value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER;\n}\n\n/**\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 && (type == 'object' || type == 'function');\n}\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 && typeof value == 'object';\n}\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) && objectToString.call(value) == symbolTag);\n}\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\n/**\n * The opposite of `_.pick`; this method creates an object composed of the\n * own and inherited enumerable string keyed properties of `object` that are\n * not omitted.\n *\n * @static\n * @since 0.1.0\n * @memberOf _\n * @category Object\n * @param {Object} object The source object.\n * @param {...(string|string[])} [props] The property identifiers to omit.\n * @returns {Object} Returns the new object.\n * @example\n *\n * var object = { 'a': 1, 'b': '2', 'c': 3 };\n *\n * _.omit(object, ['a', 'c']);\n * // => { 'b': '2' }\n */\nvar omit = baseRest(function(object, props) {\n if (object == null) {\n return {};\n }\n props = arrayMap(baseFlatten(props, 1), toKey);\n return basePick(object, baseDifference(getAllKeysIn(object), props));\n});\n\n/**\n * This method returns a new empty array.\n *\n * @static\n * @memberOf _\n * @since 4.13.0\n * @category Util\n * @returns {Array} Returns the new empty array.\n * @example\n *\n * var arrays = _.times(2, _.stubArray);\n *\n * console.log(arrays);\n * // => [[], []]\n *\n * console.log(arrays[0] === arrays[1]);\n * // => false\n */\nfunction stubArray() {\n return [];\n}\n\nmodule.exports = omit;\n\n/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./../webpack/buildin/global.js */ \"./node_modules/webpack/buildin/global.js\")))\n\n//# sourceURL=webpack:///./node_modules/lodash.omit/index.js?");
/***/ }),
/***/ "./node_modules/mini-create-react-context/dist/esm/index.js":
/*!******************************************************************!*\
!*** ./node_modules/mini-create-react-context/dist/esm/index.js ***!
\******************************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
eval("__webpack_require__.r(__webpack_exports__);\n/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! react */ \"./node_modules/react/index.js\");\n/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);\n/* harmony import */ var _babel_runtime_helpers_inheritsLoose__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @babel/runtime/helpers/inheritsLoose */ \"./node_modules/@babel/runtime/helpers/inheritsLoose.js\");\n/* harmony import */ var _babel_runtime_helpers_inheritsLoose__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_inheritsLoose__WEBPACK_IMPORTED_MODULE_1__);\n/* harmony import */ var prop_types__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! prop-types */ \"./node_modules/prop-types/index.js\");\n/* harmony import */ var prop_types__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(prop_types__WEBPACK_IMPORTED_MODULE_2__);\n/* harmony import */ var gud__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! gud */ \"./node_modules/gud/index.js\");\n/* harmony import */ var gud__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(gud__WEBPACK_IMPORTED_MODULE_3__);\n/* harmony import */ var tiny_warning__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! tiny-warning */ \"./node_modules/tiny-warning/dist/tiny-warning.esm.js\");\n\n\n\n\n\n\nvar MAX_SIGNED_31_BIT_INT = 1073741823;\n\nfunction objectIs(x, y) {\n if (x === y) {\n return x !== 0 || 1 / x === 1 / y;\n } else {\n return x !== x && y !== y;\n }\n}\n\nfunction createEventEmitter(value) {\n var handlers = [];\n return {\n on: function on(handler) {\n handlers.push(handler);\n },\n off: function off(handler) {\n handlers = handlers.filter(function (h) {\n return h !== handler;\n });\n },\n get: function get() {\n return value;\n },\n set: function set(newValue, changedBits) {\n value = newValue;\n handlers.forEach(function (handler) {\n return handler(value, changedBits);\n });\n }\n };\n}\n\nfunction onlyChild(children) {\n return Array.isArray(children) ? children[0] : children;\n}\n\nfunction createReactContext(defaultValue, calculateChangedBits) {\n var _Provider$childContex, _Consumer$contextType;\n\n var contextProp = '__create-react-context-' + gud__WEBPACK_IMPORTED_MODULE_3___default()() + '__';\n\n var Provider =\n /*#__PURE__*/\n function (_Component) {\n _babel_runtime_helpers_inheritsLoose__WEBPACK_IMPORTED_MODULE_1___default()(Provider, _Component);\n\n function Provider() {\n var _this;\n\n _this = _Component.apply(this, arguments) || this;\n _this.emitter = createEventEmitter(_this.props.value);\n return _this;\n }\n\n var _proto = Provider.prototype;\n\n _proto.getChildContext = function getChildContext() {\n var _ref;\n\n return _ref = {}, _ref[contextProp] = this.emitter, _ref;\n };\n\n _proto.componentWillReceiveProps = function componentWillReceiveProps(nextProps) {\n if (this.props.value !== nextProps.value) {\n var oldValue = this.props.value;\n var newValue = nextProps.value;\n var changedBits;\n\n if (objectIs(oldValue, newValue)) {\n changedBits = 0;\n } else {\n changedBits = typeof calculateChangedBits === 'function' ? calculateChangedBits(oldValue, newValue) : MAX_SIGNED_31_BIT_INT;\n\n if (true) {\n Object(tiny_warning__WEBPACK_IMPORTED_MODULE_4__[\"default\"])((changedBits & MAX_SIGNED_31_BIT_INT) === changedBits, 'calculateChangedBits: Expected the return value to be a ' + '31-bit integer. Instead received: ' + changedBits);\n }\n\n changedBits |= 0;\n\n if (changedBits !== 0) {\n this.emitter.set(nextProps.value, changedBits);\n }\n }\n }\n };\n\n _proto.render = function render() {\n return this.props.children;\n };\n\n return Provider;\n }(react__WEBPACK_IMPORTED_MODULE_0__[\"Component\"]);\n\n Provider.childContextTypes = (_Provider$childContex = {}, _Provider$childContex[contextProp] = prop_types__WEBPACK_IMPORTED_MODULE_2___default.a.object.isRequired, _Provider$childContex);\n\n var Consumer =\n /*#__PURE__*/\n function (_Component2) {\n _babel_runtime_helpers_inheritsLoose__WEBPACK_IMPORTED_MODULE_1___default()(Consumer, _Component2);\n\n function Consumer() {\n var _this2;\n\n _this2 = _Component2.apply(this, arguments) || this;\n _this2.state = {\n value: _this2.getValue()\n };\n\n _this2.onUpdate = function (newValue, changedBits) {\n var observedBits = _this2.observedBits | 0;\n\n if ((observedBits & changedBits) !== 0) {\n _this2.setState({\n value: _this2.getValue()\n });\n }\n };\n\n return _this2;\n }\n\n var _proto2 = Consumer.prototype;\n\n _proto2.componentWillReceiveProps = function componentWillReceiveProps(nextProps) {\n var observedBits = nextProps.observedBits;\n this.observedBits = observedBits === undefined || observedBits === null ? MAX_SIGNED_31_BIT_INT : observedBits;\n };\n\n _proto2.componentDidMount = function componentDidMount() {\n if (this.context[contextProp]) {\n this.context[contextProp].on(this.onUpdate);\n }\n\n var observedBits = this.props.observedBits;\n this.observedBits = observedBits === undefined || observedBits === null ? MAX_SIGNED_31_BIT_INT : observedBits;\n };\n\n _proto2.componentWillUnmount = function componentWillUnmount() {\n if (this.context[contextProp]) {\n this.context[contextProp].off(this.onUpdate);\n }\n };\n\n _proto2.getValue = function getValue() {\n if (this.context[contextProp]) {\n return this.context[contextProp].get();\n } else {\n return defaultValue;\n }\n };\n\n _proto2.render = function render() {\n return onlyChild(this.props.children)(this.state.value);\n };\n\n return Consumer;\n }(react__WEBPACK_IMPORTED_MODULE_0__[\"Component\"]);\n\n Consumer.contextTypes = (_Consumer$contextType = {}, _Consumer$contextType[contextProp] = prop_types__WEBPACK_IMPORTED_MODULE_2___default.a.object, _Consumer$contextType);\n return {\n Provider: Provider,\n Consumer: Consumer\n };\n}\n\nvar index = react__WEBPACK_IMPORTED_MODULE_0___default.a.createContext || createReactContext;\n\n/* harmony default export */ __webpack_exports__[\"default\"] = (index);\n\n\n//# sourceURL=webpack:///./node_modules/mini-create-react-context/dist/esm/index.js?");
/***/ }),
/***/ "./node_modules/object-assign/index.js":
/*!*********************************************!*\
!*** ./node_modules/object-assign/index.js ***!
\*********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
eval("/*\nobject-assign\n(c) Sindre Sorhus\n@license MIT\n*/\n\n\n/* eslint-disable no-unused-vars */\nvar getOwnPropertySymbols = Object.getOwnPropertySymbols;\nvar hasOwnProperty = Object.prototype.hasOwnProperty;\nvar propIsEnumerable = Object.prototype.propertyIsEnumerable;\n\nfunction toObject(val) {\n\tif (val === null || val === undefined) {\n\t\tthrow new TypeError('Object.assign cannot be called with null or undefined');\n\t}\n\n\treturn Object(val);\n}\n\nfunction shouldUseNative() {\n\ttry {\n\t\tif (!Object.assign) {\n\t\t\treturn false;\n\t\t}\n\n\t\t// Detect buggy property enumeration order in older V8 versions.\n\n\t\t// https://bugs.chromium.org/p/v8/issues/detail?id=4118\n\t\tvar test1 = new String('abc'); // eslint-disable-line no-new-wrappers\n\t\ttest1[5] = 'de';\n\t\tif (Object.getOwnPropertyNames(test1)[0] === '5') {\n\t\t\treturn false;\n\t\t}\n\n\t\t// https://bugs.chromium.org/p/v8/issues/detail?id=3056\n\t\tvar test2 = {};\n\t\tfor (var i = 0; i < 10; i++) {\n\t\t\ttest2['_' + String.fromCharCode(i)] = i;\n\t\t}\n\t\tvar order2 = Object.getOwnPropertyNames(test2).map(function (n) {\n\t\t\treturn test2[n];\n\t\t});\n\t\tif (order2.join('') !== '0123456789') {\n\t\t\treturn false;\n\t\t}\n\n\t\t// https://bugs.chromium.org/p/v8/issues/detail?id=3056\n\t\tvar test3 = {};\n\t\t'abcdefghijklmnopqrst'.split('').forEach(function (letter) {\n\t\t\ttest3[letter] = letter;\n\t\t});\n\t\tif (Object.keys(Object.assign({}, test3)).join('') !==\n\t\t\t\t'abcdefghijklmnopqrst') {\n\t\t\treturn false;\n\t\t}\n\n\t\treturn true;\n\t} catch (err) {\n\t\t// We don't expect any of the above to throw, but better to be safe.\n\t\treturn false;\n\t}\n}\n\nmodule.exports = shouldUseNative() ? Object.assign : function (target, source) {\n\tvar from;\n\tvar to = toObject(target);\n\tvar symbols;\n\n\tfor (var s = 1; s < arguments.length; s++) {\n\t\tfrom = Object(arguments[s]);\n\n\t\tfor (var key in from) {\n\t\t\tif (hasOwnProperty.call(from, key)) {\n\t\t\t\tto[key] = from[key];\n\t\t\t}\n\t\t}\n\n\t\tif (getOwnPropertySymbols) {\n\t\t\tsymbols = getOwnPropertySymbols(from);\n\t\t\tfor (var i = 0; i < symbols.length; i++) {\n\t\t\t\tif (propIsEnumerable.call(from, symbols[i])) {\n\t\t\t\t\tto[symbols[i]] = from[symbols[i]];\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn to;\n};\n\n\n//# sourceURL=webpack:///./node_modules/object-assign/index.js?");
/***/ }),
/***/ "./node_modules/process/browser.js":
/*!*****************************************!*\
!*** ./node_modules/process/browser.js ***!
\*****************************************/
/*! no static exports found */
/***/ (function(module, exports) {
eval("// 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\n\n//# sourceURL=webpack:///./node_modules/process/browser.js?");
/***/ }),
/***/ "./node_modules/prop-types/checkPropTypes.js":
/*!***************************************************!*\
!*** ./node_modules/prop-types/checkPropTypes.js ***!
\***************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
eval("/**\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\n\n\nvar printWarning = function() {};\n\nif (true) {\n var ReactPropTypesSecret = __webpack_require__(/*! ./lib/ReactPropTypesSecret */ \"./node_modules/prop-types/lib/ReactPropTypesSecret.js\");\n var loggedTypeFailures = {};\n var has = Function.call.bind(Object.prototype.hasOwnProperty);\n\n printWarning = function(text) {\n var message = 'Warning: ' + text;\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\n/**\n * Assert that the values match with the type specs.\n * Error messages are memorized and will only be shown once.\n *\n * @param {object} typeSpecs Map of name to a ReactPropType\n * @param {object} values Runtime values that need to be type-checked\n * @param {string} location e.g. \"prop\", \"context\", \"child context\"\n * @param {string} componentName Name of the component for error messages.\n * @param {?Function} getStack Returns the component stack.\n * @private\n */\nfunction checkPropTypes(typeSpecs, values, location, componentName, getStack) {\n if (true) {\n for (var typeSpecName in typeSpecs) {\n if (has(typeSpecs, typeSpecName)) {\n var error;\n // Prop type validation may throw. In case they do, we don't want to\n // fail the render phase where it didn't fail before. So we log it.\n // After these have been cleaned up, we'll let them throw.\n try {\n // This is intentionally an invariant that gets caught. It's the same\n // behavior as without this statement except with a better message.\n if (typeof typeSpecs[typeSpecName] !== 'function') {\n var err = Error(\n (componentName || 'React class') + ': ' + location + ' type `' + typeSpecName + '` is invalid; ' +\n 'it must be a function, usually from the `prop-types` package, but received `' + typeof typeSpecs[typeSpecName] + '`.'\n );\n err.name = 'Invariant Violation';\n throw err;\n }\n error = typeSpecs[typeSpecName](values, typeSpecName, componentName, location, null, ReactPropTypesSecret);\n } catch (ex) {\n error = ex;\n }\n if (error && !(error instanceof Error)) {\n printWarning(\n (componentName || 'React class') + ': type specification of ' +\n location + ' `' + typeSpecName + '` is invalid; the type checker ' +\n 'function must return `null` or an `Error` but returned a ' + typeof error + '. ' +\n 'You may have forgotten to pass an argument to the type checker ' +\n 'creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and ' +\n 'shape all require an argument).'\n );\n }\n if (error instanceof Error && !(error.message in loggedTypeFailures)) {\n // Only monitor this failure once because there tends to be a lot of the\n // same error.\n loggedTypeFailures[error.message] = true;\n\n var stack = getStack ? getStack() : '';\n\n printWarning(\n 'Failed ' + location + ' type: ' + error.message + (stack != null ? stack : '')\n );\n }\n }\n }\n }\n}\n\n/**\n * Resets warning cache when testing.\n *\n * @private\n */\ncheckPropTypes.resetWarningCache = function() {\n if (true) {\n loggedTypeFailures = {};\n }\n}\n\nmodule.exports = checkPropTypes;\n\n\n//# sourceURL=webpack:///./node_modules/prop-types/checkPropTypes.js?");
/***/ }),
/***/ "./node_modules/prop-types/factoryWithTypeCheckers.js":
/*!************************************************************!*\
!*** ./node_modules/prop-types/factoryWithTypeCheckers.js ***!
\************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
eval("/**\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\n\n\nvar ReactIs = __webpack_require__(/*! react-is */ \"./node_modules/react-is/index.js\");\nvar assign = __webpack_require__(/*! object-assign */ \"./node_modules/object-assign/index.js\");\n\nvar ReactPropTypesSecret = __webpack_require__(/*! ./lib/ReactPropTypesSecret */ \"./node_modules/prop-types/lib/ReactPropTypesSecret.js\");\nvar checkPropTypes = __webpack_require__(/*! ./checkPropTypes */ \"./node_modules/prop-types/checkPropTypes.js\");\n\nvar has = Function.call.bind(Object.prototype.hasOwnProperty);\nvar printWarning = function() {};\n\nif (true) {\n printWarning = function(text) {\n var message = 'Warning: ' + text;\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\nfunction emptyFunctionThatReturnsNull() {\n return null;\n}\n\nmodule.exports = function(isValidElement, throwOnDirectAccess) {\n /* global Symbol */\n var ITERATOR_SYMBOL = typeof Symbol === 'function' && Symbol.iterator;\n var FAUX_ITERATOR_SYMBOL = '@@iterator'; // Before Symbol spec.\n\n /**\n * Returns the iterator method function contained on the iterable object.\n *\n * Be sure to invoke the function with the iterable as context:\n *\n * var iteratorFn = getIteratorFn(myIterable);\n * if (iteratorFn) {\n * var iterator = iteratorFn.call(myIterable);\n * ...\n * }\n *\n * @param {?object} maybeIterable\n * @return {?function}\n */\n function getIteratorFn(maybeIterable) {\n var iteratorFn = maybeIterable && (ITERATOR_SYMBOL && maybeIterable[ITERATOR_SYMBOL] || maybeIterable[FAUX_ITERATOR_SYMBOL]);\n if (typeof iteratorFn === 'function') {\n return iteratorFn;\n }\n }\n\n /**\n * Collection of methods that allow declaration and validation of props that are\n * supplied to React components. Example usage:\n *\n * var Props = require('ReactPropTypes');\n * var MyArticle = React.createClass({\n * propTypes: {\n * // An optional string prop named \"description\".\n * description: Props.string,\n *\n * // A required enum prop named \"category\".\n * category: Props.oneOf(['News','Photos']).isRequired,\n *\n * // A prop named \"dialog\" that requires an instance of Dialog.\n * dialog: Props.instanceOf(Dialog).isRequired\n * },\n * render: function() { ... }\n * });\n *\n * A more formal specification of how these methods are used:\n *\n * type := array|bool|func|object|number|string|oneOf([...])|instanceOf(...)\n * decl := ReactPropTypes.{type}(.isRequired)?\n *\n * Each and every declaration produces a function with the same signature. This\n * allows the creation of custom validation functions. For example:\n *\n * var MyLink = React.createClass({\n * propTypes: {\n * // An optional string or URI prop named \"href\".\n * href: function(props, propName, componentName) {\n * var propValue = props[propName];\n * if (propValue != null && typeof propValue !== 'string' &&\n * !(propValue instanceof URI)) {\n * return new Error(\n * 'Expected a string or an URI for ' + propName + ' in ' +\n * componentName\n * );\n * }\n * }\n * },\n * render: function() {...}\n * });\n *\n * @internal\n */\n\n var ANONYMOUS = '<<anonymous>>';\n\n // Important!\n // Keep this list in sync with production version in `./factoryWithThrowingShims.js`.\n var ReactPropTypes = {\n array: createPrimitiveTypeChecker('array'),\n bool: createPrimitiveTypeChecker('boolean'),\n func: createPrimitiveTypeChecker('function'),\n number: createPrimitiveTypeChecker('number'),\n object: createPrimitiveTypeChecker('object'),\n string: createPrimitiveTypeChecker('string'),\n symbol: createPrimitiveTypeChecker('symbol'),\n\n any: createAnyTypeChecker(),\n arrayOf: createArrayOfTypeChecker,\n element: createElementTypeChecker(),\n elementType: createElementTypeTypeChecker(),\n instanceOf: createInstanceTypeChecker,\n node: createNodeChecker(),\n objectOf: createObjectOfTypeChecker,\n oneOf: createEnumTypeChecker,\n oneOfType: createUnionTypeChecker,\n shape: createShapeTypeChecker,\n exact: createStrictShapeTypeChecker,\n };\n\n /**\n * inlined Object.is polyfill to avoid requiring consumers ship their own\n * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is\n */\n /*eslint-disable no-self-compare*/\n function is(x, y) {\n // SameValue algorithm\n if (x === y) {\n // Steps 1-5, 7-10\n // Steps 6.b-6.e: +0 != -0\n return x !== 0 || 1 / x === 1 / y;\n } else {\n // Step 6.a: NaN == NaN\n return x !== x && y !== y;\n }\n }\n /*eslint-enable no-self-compare*/\n\n /**\n * We use an Error-like object for backward compatibility as people may call\n * PropTypes directly and inspect their output. However, we don't use real\n * Errors anymore. We don't inspect their stack anyway, and creating them\n * is prohibitively expensive if they are created too often, such as what\n * happens in oneOfType() for any type before the one that matched.\n */\n function PropTypeError(message) {\n this.message = message;\n this.stack = '';\n }\n // Make `instanceof Error` still work for returned errors.\n PropTypeError.prototype = Error.prototype;\n\n function createChainableTypeChecker(validate) {\n if (true) {\n var manualPropTypeCallCache = {};\n var manualPropTypeWarningCount = 0;\n }\n function checkType(isRequired, props, propName, componentName, location, propFullName, secret) {\n componentName = componentName || ANONYMOUS;\n propFullName = propFullName || propName;\n\n if (secret !== ReactPropTypesSecret) {\n if (throwOnDirectAccess) {\n // New behavior only for users of `prop-types` package\n var err = new Error(\n 'Calling PropTypes validators directly is not supported by the `prop-types` package. ' +\n 'Use `PropTypes.checkPropTypes()` to call them. ' +\n 'Read more at http://fb.me/use-check-prop-types'\n );\n err.name = 'Invariant Violation';\n throw err;\n } else if ( true && typeof console !== 'undefined') {\n // Old behavior for people using React.PropTypes\n var cacheKey = componentName + ':' + propName;\n if (\n !manualPropTypeCallCache[cacheKey] &&\n // Avoid spamming the console because they are often not actionable except for lib authors\n manualPropTypeWarningCount < 3\n ) {\n printWarning(\n 'You are manually calling a React.PropTypes validation ' +\n 'function for the `' + propFullName + '` prop on `' + componentName + '`. This is deprecated ' +\n 'and will throw in the standalone `prop-types` package. ' +\n 'You may be seeing this warning due to a third-party PropTypes ' +\n 'library. See https://fb.me/react-warning-dont-call-proptypes ' + 'for details.'\n );\n manualPropTypeCallCache[cacheKey] = true;\n manualPropTypeWarningCount++;\n }\n }\n }\n if (props[propName] == null) {\n if (isRequired) {\n if (props[propName] === null) {\n return new PropTypeError('The ' + location + ' `' + propFullName + '` is marked as required ' + ('in `' + componentName + '`, but its value is `null`.'));\n }\n return new PropTypeError('The ' + location + ' `' + propFullName + '` is marked as required in ' + ('`' + componentName + '`, but its value is `undefined`.'));\n }\n return null;\n } else {\n return validate(props, propName, componentName, location, propFullName);\n }\n }\n\n var chainedCheckType = checkType.bind(null, false);\n chainedCheckType.isRequired = checkType.bind(null, true);\n\n return chainedCheckType;\n }\n\n function createPrimitiveTypeChecker(expectedType) {\n function validate(props, propName, componentName, location, propFullName, secret) {\n var propValue = props[propName];\n var propType = getPropType(propValue);\n if (propType !== expectedType) {\n // `propValue` being instance of, say, date/regexp, pass the 'object'\n // check, but we can offer a more precise error message here rather than\n // 'of type `object`'.\n var preciseType = getPreciseType(propValue);\n\n return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type ' + ('`' + preciseType + '` supplied to `' + componentName + '`, expected ') + ('`' + expectedType + '`.'));\n }\n return null;\n }\n return createChainableTypeChecker(validate);\n }\n\n function createAnyTypeChecker() {\n return createChainableTypeChecker(emptyFunctionThatReturnsNull);\n }\n\n function createArrayOfTypeChecker(typeChecker) {\n function validate(props, propName, componentName, location, propFullName) {\n if (typeof typeChecker !== 'function') {\n return new PropTypeError('Property `' + propFullName + '` of component `' + componentName + '` has invalid PropType notation inside arrayOf.');\n }\n var propValue = props[propName];\n if (!Array.isArray(propValue)) {\n var propType = getPropType(propValue);\n return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type ' + ('`' + propType + '` supplied to `' + componentName + '`, expected an array.'));\n }\n for (var i = 0; i < propValue.length; i++) {\n var error = typeChecker(propValue, i, componentName, location, propFullName + '[' + i + ']', ReactPropTypesSecret);\n if (error instanceof Error) {\n return error;\n }\n }\n return null;\n }\n return createChainableTypeChecker(validate);\n }\n\n function createElementTypeChecker() {\n function validate(props, propName, componentName, location, propFullName) {\n var propValue = props[propName];\n if (!isValidElement(propValue)) {\n var propType = getPropType(propValue);\n return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type ' + ('`' + propType + '` supplied to `' + componentName + '`, expected a single ReactElement.'));\n }\n return null;\n }\n return createChainableTypeChecker(validate);\n }\n\n function createElementTypeTypeChecker() {\n function validate(props, propName, componentName, location, propFullName) {\n var propValue = props[propName];\n if (!ReactIs.isValidElementType(propValue)) {\n var propType = getPropType(propValue);\n return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type ' + ('`' + propType + '` supplied to `' + componentName + '`, expected a single ReactElement type.'));\n }\n return null;\n }\n return createChainableTypeChecker(validate);\n }\n\n function createInstanceTypeChecker(expectedClass) {\n function validate(props, propName, componentName, location, propFullName) {\n if (!(props[propName] instanceof expectedClass)) {\n var expectedClassName = expectedClass.name || ANONYMOUS;\n var actualClassName = getClassName(props[propName]);\n return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type ' + ('`' + actualClassName + '` supplied to `' + componentName + '`, expected ') + ('instance of `' + expectedClassName + '`.'));\n }\n return null;\n }\n return createChainableTypeChecker(validate);\n }\n\n function createEnumTypeChecker(expectedValues) {\n if (!Array.isArray(expectedValues)) {\n if (true) {\n if (arguments.length > 1) {\n printWarning(\n 'Invalid arguments supplied to oneOf, expected an array, got ' + arguments.length + ' arguments. ' +\n 'A common mistake is to write oneOf(x, y, z) instead of oneOf([x, y, z]).'\n );\n } else {\n printWarning('Invalid argument supplied to oneOf, expected an array.');\n }\n }\n return emptyFunctionThatReturnsNull;\n }\n\n function validate(props, propName, componentName, location, propFullName) {\n var propValue = props[propName];\n for (var i = 0; i < expectedValues.length; i++) {\n if (is(propValue, expectedValues[i])) {\n return null;\n }\n }\n\n var valuesString = JSON.stringify(expectedValues, function replacer(key, value) {\n var type = getPreciseType(value);\n if (type === 'symbol') {\n return String(value);\n }\n return value;\n });\n return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of value `' + String(propValue) + '` ' + ('supplied to `' + componentName + '`, expected one of ' + valuesString + '.'));\n }\n return createChainableTypeChecker(validate);\n }\n\n function createObjectOfTypeChecker(typeChecker) {\n function validate(props, propName, componentName, location, propFullName) {\n if (typeof typeChecker !== 'function') {\n return new PropTypeError('Property `' + propFullName + '` of component `' + componentName + '` has invalid PropType notation inside objectOf.');\n }\n var propValue = props[propName];\n var propType = getPropType(propValue);\n if (propType !== 'object') {\n return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type ' + ('`' + propType + '` supplied to `' + componentName + '`, expected an object.'));\n }\n for (var key in propValue) {\n if (has(propValue, key)) {\n var error = typeChecker(propValue, key, componentName, location, propFullName + '.' + key, ReactPropTypesSecret);\n if (error instanceof Error) {\n return error;\n }\n }\n }\n return null;\n }\n return createChainableTypeChecker(validate);\n }\n\n function createUnionTypeChecker(arrayOfTypeCheckers) {\n if (!Array.isArray(arrayOfTypeCheckers)) {\n true ? printWarning('Invalid argument supplied to oneOfType, expected an instance of array.') : undefined;\n return emptyFunctionThatReturnsNull;\n }\n\n for (var i = 0; i < arrayOfTypeCheckers.length; i++) {\n var checker = arrayOfTypeCheckers[i];\n if (typeof checker !== 'function') {\n printWarning(\n 'Invalid argument supplied to oneOfType. Expected an array of check functions, but ' +\n 'received ' + getPostfixForTypeWarning(checker) + ' at index ' + i + '.'\n );\n return emptyFunctionThatReturnsNull;\n }\n }\n\n function validate(props, propName, componentName, location, propFullName) {\n for (var i = 0; i < arrayOfTypeCheckers.length; i++) {\n var checker = arrayOfTypeCheckers[i];\n if (checker(props, propName, componentName, location, propFullName, ReactPropTypesSecret) == null) {\n return null;\n }\n }\n\n return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` supplied to ' + ('`' + componentName + '`.'));\n }\n return createChainableTypeChecker(validate);\n }\n\n function createNodeChecker() {\n function validate(props, propName, componentName, location, propFullName) {\n if (!isNode(props[propName])) {\n return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` supplied to ' + ('`' + componentName + '`, expected a ReactNode.'));\n }\n return null;\n }\n return createChainableTypeChecker(validate);\n }\n\n function createShapeTypeChecker(shapeTypes) {\n function validate(props, propName, componentName, location, propFullName) {\n var propValue = props[propName];\n var propType = getPropType(propValue);\n if (propType !== 'object') {\n return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type `' + propType + '` ' + ('supplied to `' + componentName + '`, expected `object`.'));\n }\n for (var key in shapeTypes) {\n var checker = shapeTypes[key];\n if (!checker) {\n continue;\n }\n var error = checker(propValue, key, componentName, location, propFullName + '.' + key, ReactPropTypesSecret);\n if (error) {\n return error;\n }\n }\n return null;\n }\n return createChainableTypeChecker(validate);\n }\n\n function createStrictShapeTypeChecker(shapeTypes) {\n function validate(props, propName, componentName, location, propFullName) {\n var propValue = props[propName];\n var propType = getPropType(propValue);\n if (propType !== 'object') {\n return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type `' + propType + '` ' + ('supplied to `' + componentName + '`, expected `object`.'));\n }\n // We need to check all keys in case some are required but missing from\n // props.\n var allKeys = assign({}, props[propName], shapeTypes);\n for (var key in allKeys) {\n var checker = shapeTypes[key];\n if (!checker) {\n return new PropTypeError(\n 'Invalid ' + location + ' `' + propFullName + '` key `' + key + '` supplied to `' + componentName + '`.' +\n '\\nBad object: ' + JSON.stringify(props[propName], null, ' ') +\n '\\nValid keys: ' + JSON.stringify(Object.keys(shapeTypes), null, ' ')\n );\n }\n var error = checker(propValue, key, componentName, location, propFullName + '.' + key, ReactPropTypesSecret);\n if (error) {\n return error;\n }\n }\n return null;\n }\n\n return createChainableTypeChecker(validate);\n }\n\n function isNode(propValue) {\n switch (typeof propValue) {\n case 'number':\n case 'string':\n case 'undefined':\n return true;\n case 'boolean':\n return !propValue;\n case 'object':\n if (Array.isArray(propValue)) {\n return propValue.every(isNode);\n }\n if (propValue === null || isValidElement(propValue)) {\n return true;\n }\n\n var iteratorFn = getIteratorFn(propValue);\n if (iteratorFn) {\n var iterator = iteratorFn.call(propValue);\n var step;\n if (iteratorFn !== propValue.entries) {\n while (!(step = iterator.next()).done) {\n if (!isNode(step.value)) {\n return false;\n }\n }\n } else {\n // Iterator will provide entry [k,v] tuples rather than values.\n while (!(step = iterator.next()).done) {\n var entry = step.value;\n if (entry) {\n if (!isNode(entry[1])) {\n return false;\n }\n }\n }\n }\n } else {\n return false;\n }\n\n return true;\n default:\n return false;\n }\n }\n\n function isSymbol(propType, propValue) {\n // Native Symbol.\n if (propType === 'symbol') {\n return true;\n }\n\n // falsy value can't be a Symbol\n if (!propValue) {\n return false;\n }\n\n // 19.4.3.5 Symbol.prototype[@@toStringTag] === 'Symbol'\n if (propValue['@@toStringTag'] === 'Symbol') {\n return true;\n }\n\n // Fallback for non-spec compliant Symbols which are polyfilled.\n if (typeof Symbol === 'function' && propValue instanceof Symbol) {\n return true;\n }\n\n return false;\n }\n\n // Equivalent of `typeof` but with special handling for array and regexp.\n function getPropType(propValue) {\n var propType = typeof propValue;\n if (Array.isArray(propValue)) {\n return 'array';\n }\n if (propValue instanceof RegExp) {\n // Old webkits (at least until Android 4.0) return 'function' rather than\n // 'object' for typeof a RegExp. We'll normalize this here so that /bla/\n // passes PropTypes.object.\n return 'object';\n }\n if (isSymbol(propType, propValue)) {\n return 'symbol';\n }\n return propType;\n }\n\n // This handles more types than `getPropType`. Only used for error messages.\n // See `createPrimitiveTypeChecker`.\n function getPreciseType(propValue) {\n if (typeof propValue === 'undefined' || propValue === null) {\n return '' + propValue;\n }\n var propType = getPropType(propValue);\n if (propType === 'object') {\n if (propValue instanceof Date) {\n return 'date';\n } else if (propValue instanceof RegExp) {\n return 'regexp';\n }\n }\n return propType;\n }\n\n // Returns a string that is postfixed to a warning about an invalid type.\n // For example, \"undefined\" or \"of type array\"\n function getPostfixForTypeWarning(value) {\n var type = getPreciseType(value);\n switch (type) {\n case 'array':\n case 'object':\n return 'an ' + type;\n case 'boolean':\n case 'date':\n case 'regexp':\n return 'a ' + type;\n default:\n return type;\n }\n }\n\n // Returns class name of the object, if any.\n function getClassName(propValue) {\n if (!propValue.constructor || !propValue.constructor.name) {\n return ANONYMOUS;\n }\n return propValue.constructor.name;\n }\n\n ReactPropTypes.checkPropTypes = checkPropTypes;\n ReactPropTypes.resetWarningCache = checkPropTypes.resetWarningCache;\n ReactPropTypes.PropTypes = ReactPropTypes;\n\n return ReactPropTypes;\n};\n\n\n//# sourceURL=webpack:///./node_modules/prop-types/factoryWithTypeCheckers.js?");
/***/ }),
/***/ "./node_modules/prop-types/index.js":
/*!******************************************!*\
!*** ./node_modules/prop-types/index.js ***!
\******************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
eval("/**\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\nif (true) {\n var ReactIs = __webpack_require__(/*! react-is */ \"./node_modules/react-is/index.js\");\n\n // By explicitly using `prop-types` you are opting into new development behavior.\n // http://fb.me/prop-types-in-prod\n var throwOnDirectAccess = true;\n module.exports = __webpack_require__(/*! ./factoryWithTypeCheckers */ \"./node_modules/prop-types/factoryWithTypeCheckers.js\")(ReactIs.isElement, throwOnDirectAccess);\n} else {}\n\n\n//# sourceURL=webpack:///./node_modules/prop-types/index.js?");
/***/ }),
/***/ "./node_modules/prop-types/lib/ReactPropTypesSecret.js":
/*!*************************************************************!*\
!*** ./node_modules/prop-types/lib/ReactPropTypesSecret.js ***!
\*************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
eval("/**\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\n\n\nvar ReactPropTypesSecret = 'SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED';\n\nmodule.exports = ReactPropTypesSecret;\n\n\n//# sourceURL=webpack:///./node_modules/prop-types/lib/ReactPropTypesSecret.js?");
/***/ }),
/***/ "./node_modules/react-dom/cjs/react-dom.development.js":
/*!*************************************************************!*\
!*** ./node_modules/react-dom/cjs/react-dom.development.js ***!
\*************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
eval("/** @license React v16.13.1\n * react-dom.development.js\n *\n * Copyright (c) Facebook, Inc. and its affiliates.\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\n\n\n\nif (true) {\n (function() {\n'use strict';\n\nvar React = __webpack_require__(/*! react */ \"./node_modules/react/index.js\");\nvar _assign = __webpack_require__(/*! object-assign */ \"./node_modules/object-assign/index.js\");\nvar Scheduler = __webpack_require__(/*! scheduler */ \"./node_modules/scheduler/index.js\");\nvar checkPropTypes = __webpack_require__(/*! prop-types/checkPropTypes */ \"./node_modules/prop-types/checkPropTypes.js\");\nvar tracing = __webpack_require__(/*! scheduler/tracing */ \"./node_modules/scheduler/tracing.js\");\n\nvar ReactSharedInternals = React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED; // Prevent newer renderers from RTE when used with older react package versions.\n// Current owner and dispatcher used to share the same ref,\n// but PR #14548 split them out to better support the react-debug-tools package.\n\nif (!ReactSharedInternals.hasOwnProperty('ReactCurrentDispatcher')) {\n ReactSharedInternals.ReactCurrentDispatcher = {\n current: null\n };\n}\n\nif (!ReactSharedInternals.hasOwnProperty('ReactCurrentBatchConfig')) {\n ReactSharedInternals.ReactCurrentBatchConfig = {\n suspense: null\n };\n}\n\n// by calls to these methods by a Babel plugin.\n//\n// In PROD (or in packages without access to React internals),\n// they are left as they are instead.\n\nfunction warn(format) {\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 printWarning('warn', format, args);\n }\n}\nfunction error(format) {\n {\n for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {\n args[_key2 - 1] = arguments[_key2];\n }\n\n printWarning('error', format, args);\n }\n}\n\nfunction printWarning(level, format, args) {\n // When changing this logic, you might want to also\n // update consoleWithStackDev.www.js as well.\n {\n var hasExistingStack = args.length > 0 && typeof args[args.length - 1] === 'string' && args[args.length - 1].indexOf('\\n in') === 0;\n\n if (!hasExistingStack) {\n var ReactDebugCurrentFrame = ReactSharedInternals.ReactDebugCurrentFrame;\n var stack = ReactDebugCurrentFrame.getStackAddendum();\n\n if (stack !== '') {\n format += '%s';\n args = args.concat([stack]);\n }\n }\n\n var argsWithFormat = args.map(function (item) {\n return '' + item;\n }); // Careful: RN currently depends on this prefix\n\n argsWithFormat.unshift('Warning: ' + format); // We intentionally don't use spread (or .apply) directly because it\n // breaks IE9: https://github.com/facebook/react/issues/13610\n // eslint-disable-next-line react-internal/no-production-logging\n\n Function.prototype.apply.call(console[level], console, argsWithFormat);\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 var argIndex = 0;\n var message = 'Warning: ' + format.replace(/%s/g, function () {\n return args[argIndex++];\n });\n throw new Error(message);\n } catch (x) {}\n }\n}\n\nif (!React) {\n {\n throw Error( \"ReactDOM was loaded before React. Make sure you load the React package before loading ReactDOM.\" );\n }\n}\n\nvar invokeGuardedCallbackImpl = function (name, func, context, a, b, c, d, e, f) {\n var funcArgs = Array.prototype.slice.call(arguments, 3);\n\n try {\n func.apply(context, funcArgs);\n } catch (error) {\n this.onError(error);\n }\n};\n\n{\n // In DEV mode, we swap out invokeGuardedCallback for a special version\n // that plays more nicely with the browser's DevTools. The idea is to preserve\n // \"Pause on exceptions\" behavior. Because React wraps all user-provided\n // functions in invokeGuardedCallback, and the production version of\n // invokeGuardedCallback uses a try-catch, all user exceptions are treated\n // like caught exceptions, and the DevTools won't pause unless the developer\n // takes the extra step of enabling pause on caught exceptions. This is\n // unintuitive, though, because even though React has caught the error, from\n // the developer's perspective, the error is uncaught.\n //\n // To preserve the expected \"Pause on exceptions\" behavior, we don't use a\n // try-catch in DEV. Instead, we synchronously dispatch a fake event to a fake\n // DOM node, and call the user-provided callback from inside an event handler\n // for that fake event. If the callback throws, the error is \"captured\" using\n // a global event handler. But because the error happens in a different\n // event loop context, it does not interrupt the normal program flow.\n // Effectively, this gives us try-catch behavior without actually using\n // try-catch. Neat!\n // Check that the browser supports the APIs we need to implement our special\n // DEV version of invokeGuardedCallback\n if (typeof window !== 'undefined' && typeof window.dispatchEvent === 'function' && typeof document !== 'undefined' && typeof document.createEvent === 'function') {\n var fakeNode = document.createElement('react');\n\n var invokeGuardedCallbackDev = function (name, func, context, a, b, c, d, e, f) {\n // If document doesn't exist we know for sure we will crash in this method\n // when we call document.createEvent(). However this can cause confusing\n // errors: https://github.com/facebookincubator/create-react-app/issues/3482\n // So we preemptively throw with a better message instead.\n if (!(typeof document !== 'undefined')) {\n {\n throw Error( \"The `document` global was defined when React was initialized, but is not defined anymore. This can happen in a test environment if a component schedules an update from an asynchronous callback, but the test has already finished running. To solve this, you can either unmount the component at the end of your test (and ensure that any asynchronous operations get canceled in `componentWillUnmount`), or you can change the test itself to be asynchronous.\" );\n }\n }\n\n var evt = document.createEvent('Event'); // Keeps track of whether the user-provided callback threw an error. We\n // set this to true at the beginning, then set it to false right after\n // calling the function. If the function errors, `didError` will never be\n // set to false. This strategy works even if the browser is flaky and\n // fails to call our global error handler, because it doesn't rely on\n // the error event at all.\n\n var didError = true; // Keeps track of the value of window.event so that we can reset it\n // during the callback to let user code access window.event in the\n // browsers that support it.\n\n var windowEvent = window.event; // Keeps track of the descriptor of window.event to restore it after event\n // dispatching: https://github.com/facebook/react/issues/13688\n\n var windowEventDescriptor = Object.getOwnPropertyDescriptor(window, 'event'); // Create an event handler for our fake event. We will synchronously\n // dispatch our fake event using `dispatchEvent`. Inside the handler, we\n // call the user-provided callback.\n\n var funcArgs = Array.prototype.slice.call(arguments, 3);\n\n function callCallback() {\n // We immediately remove the callback from event listeners so that\n // nested `invokeGuardedCallback` calls do not clash. Otherwise, a\n // nested call would trigger the fake event handlers of any call higher\n // in the stack.\n fakeNode.removeEventListener(evtType, callCallback, false); // We check for window.hasOwnProperty('event') to prevent the\n // window.event assignment in both IE <= 10 as they throw an error\n // \"Member not found\" in strict mode, and in Firefox which does not\n // support window.event.\n\n if (typeof window.event !== 'undefined' && window.hasOwnProperty('event')) {\n window.event = windowEvent;\n }\n\n func.apply(context, funcArgs);\n didError = false;\n } // Create a global error event handler. We use this to capture the value\n // that was thrown. It's possible that this error handler will fire more\n // than once; for example, if non-React code also calls `dispatchEvent`\n // and a handler for that event throws. We should be resilient to most of\n // those cases. Even if our error event handler fires more than once, the\n // last error event is always used. If the callback actually does error,\n // we know that the last error event is the correct one, because it's not\n // possible for anything else to have happened in between our callback\n // erroring and the code that follows the `dispatchEvent` call below. If\n // the callback doesn't error, but the error event was fired, we know to\n // ignore it because `didError` will be false, as described above.\n\n\n var error; // Use this to track whether the error event is ever called.\n\n var didSetError = false;\n var isCrossOriginError = false;\n\n function handleWindowError(event) {\n error = event.error;\n didSetError = true;\n\n if (error === null && event.colno === 0 && event.lineno === 0) {\n isCrossOriginError = true;\n }\n\n if (event.defaultPrevented) {\n // Some other error handler has prevented default.\n // Browsers silence the error report if this happens.\n // We'll remember this to later decide whether to log it or not.\n if (error != null && typeof error === 'object') {\n try {\n error._suppressLogging = true;\n } catch (inner) {// Ignore.\n }\n }\n }\n } // Create a fake event type.\n\n\n var evtType = \"react-\" + (name ? name : 'invokeguardedcallback'); // Attach our event handlers\n\n window.addEventListener('error', handleWindowError);\n fakeNode.addEventListener(evtType, callCallback, false); // Synchronously dispatch our fake event. If the user-provided function\n // errors, it will trigger our global error handler.\n\n evt.initEvent(evtType, false, false);\n fakeNode.dispatchEvent(evt);\n\n if (windowEventDescriptor) {\n Object.defineProperty(window, 'event', windowEventDescriptor);\n }\n\n if (didError) {\n if (!didSetError) {\n // The callback errored, but the error event never fired.\n error = new Error('An error was thrown inside one of your components, but React ' + \"doesn't know what it was. This is likely due to browser \" + 'flakiness. React does its best to preserve the \"Pause on ' + 'exceptions\" behavior of the DevTools, which requires some ' + \"DEV-mode only tricks. It's possible that these don't work in \" + 'your browser. Try triggering the error in production mode, ' + 'or switching to a modern browser. If you suspect that this is ' + 'actually an issue with React, please file an issue.');\n } else if (isCrossOriginError) {\n error = new Error(\"A cross-origin error was thrown. React doesn't have access to \" + 'the actual error object in development. ' + 'See https://fb.me/react-crossorigin-error for more information.');\n }\n\n this.onError(error);\n } // Remove our event listeners\n\n\n window.removeEventListener('error', handleWindowError);\n };\n\n invokeGuardedCallbackImpl = invokeGuardedCallbackDev;\n }\n}\n\nvar invokeGuardedCallbackImpl$1 = invokeGuardedCallbackImpl;\n\nvar hasError = false;\nvar caughtError = null; // Used by event system to capture/rethrow the first error.\n\nvar hasRethrowError = false;\nvar rethrowError = null;\nvar reporter = {\n onError: function (error) {\n hasError = true;\n caughtError = error;\n }\n};\n/**\n * Call a function while guarding against errors that happens within it.\n * Returns an error if it throws, otherwise null.\n *\n * In production, this is implemented using a try-catch. The reason we don't\n * use a try-catch directly is so that we can swap out a different\n * implementation in DEV mode.\n *\n * @param {String} name of the guard to use for logging or debugging\n * @param {Function} func The function to invoke\n * @param {*} context The context to use when calling the function\n * @param {...*} args Arguments for function\n */\n\nfunction invokeGuardedCallback(name, func, context, a, b, c, d, e, f) {\n hasError = false;\n caughtError = null;\n invokeGuardedCallbackImpl$1.apply(reporter, arguments);\n}\n/**\n * Same as invokeGuardedCallback, but instead of returning an error, it stores\n * it in a global so it can be rethrown by `rethrowCaughtError` later.\n * TODO: See if caughtError and rethrowError can be unified.\n *\n * @param {String} name of the guard to use for logging or debugging\n * @param {Function} func The function to invoke\n * @param {*} context The context to use when calling the function\n * @param {...*} args Arguments for function\n */\n\nfunction invokeGuardedCallbackAndCatchFirstError(name, func, context, a, b, c, d, e, f) {\n invokeGuardedCallback.apply(this, arguments);\n\n if (hasError) {\n var error = clearCaughtError();\n\n if (!hasRethrowError) {\n hasRethrowError = true;\n rethrowError = error;\n }\n }\n}\n/**\n * During execution of guarded functions we will capture the first error which\n * we will rethrow to be handled by the top level error handler.\n */\n\nfunction rethrowCaughtError() {\n if (hasRethrowError) {\n var error = rethrowError;\n hasRethrowError = false;\n rethrowError = null;\n throw error;\n }\n}\nfunction hasCaughtError() {\n return hasError;\n}\nfunction clearCaughtError() {\n if (hasError) {\n var error = caughtError;\n hasError = false;\n caughtError = null;\n return error;\n } else {\n {\n {\n throw Error( \"clearCaughtError was called but no error was captured. This error is likely caused by a bug in React. Please file an issue.\" );\n }\n }\n }\n}\n\nvar getFiberCurrentPropsFromNode = null;\nvar getInstanceFromNode = null;\nvar getNodeFromInstance = null;\nfunction setComponentTree(getFiberCurrentPropsFromNodeImpl, getInstanceFromNodeImpl, getNodeFromInstanceImpl) {\n getFiberCurrentPropsFromNode = getFiberCurrentPropsFromNodeImpl;\n getInstanceFromNode = getInstanceFromNodeImpl;\n getNodeFromInstance = getNodeFromInstanceImpl;\n\n {\n if (!getNodeFromInstance || !getInstanceFromNode) {\n error('EventPluginUtils.setComponentTree(...): Injected ' + 'module is missing getNodeFromInstance or getInstanceFromNode.');\n }\n }\n}\nvar validateEventDispatches;\n\n{\n validateEventDispatches = function (event) {\n var dispatchListeners = event._dispatchListeners;\n var dispatchInstances = event._dispatchInstances;\n var listenersIsArr = Array.isArray(dispatchListeners);\n var listenersLen = listenersIsArr ? dispatchListeners.length : dispatchListeners ? 1 : 0;\n var instancesIsArr = Array.isArray(dispatchInstances);\n var instancesLen = instancesIsArr ? dispatchInstances.length : dispatchInstances ? 1 : 0;\n\n if (instancesIsArr !== listenersIsArr || instancesLen !== listenersLen) {\n error('EventPluginUtils: Invalid `event`.');\n }\n };\n}\n/**\n * Dispatch the event to the listener.\n * @param {SyntheticEvent} event SyntheticEvent to handle\n * @param {function} listener Application-level callback\n * @param {*} inst Internal component instance\n */\n\n\nfunction executeDispatch(event, listener, inst) {\n var type = event.type || 'unknown-event';\n event.currentTarget = getNodeFromInstance(inst);\n invokeGuardedCallbackAndCatchFirstError(type, listener, undefined, event);\n event.currentTarget = null;\n}\n/**\n * Standard/simple iteration through an event's collected dispatches.\n */\n\nfunction executeDispatchesInOrder(event) {\n var dispatchListeners = event._dispatchListeners;\n var dispatchInstances = event._dispatchInstances;\n\n {\n validateEventDispatches(event);\n }\n\n if (Array.isArray(dispatchListeners)) {\n for (var i = 0; i < dispatchListeners.length; i++) {\n if (event.isPropagationStopped()) {\n break;\n } // Listeners and Instances are two parallel arrays that are always in sync.\n\n\n executeDispatch(event, dispatchListeners[i], dispatchInstances[i]);\n }\n } else if (dispatchListeners) {\n executeDispatch(event, dispatchListeners, dispatchInstances);\n }\n\n event._dispatchListeners = null;\n event._dispatchInstances = null;\n}\n\nvar FunctionComponent = 0;\nvar ClassComponent = 1;\nvar IndeterminateComponent = 2; // Before we know whether it is function or class\n\nvar HostRoot = 3; // Root of a host tree. Could be nested inside another node.\n\nvar HostPortal = 4; // A subtree. Could be an entry point to a different renderer.\n\nvar HostComponent = 5;\nvar HostText = 6;\nvar Fragment = 7;\nvar Mode = 8;\nvar ContextConsumer = 9;\nvar ContextProvider = 10;\nvar ForwardRef = 11;\nvar Profiler = 12;\nvar SuspenseComponent = 13;\nvar MemoComponent = 14;\nvar SimpleMemoComponent = 15;\nvar LazyComponent = 16;\nvar IncompleteClassComponent = 17;\nvar DehydratedFragment = 18;\nvar SuspenseListComponent = 19;\nvar FundamentalComponent = 20;\nvar ScopeComponent = 21;\nvar Block = 22;\n\n/**\n * Injectable ordering of event plugins.\n */\nvar eventPluginOrder = null;\n/**\n * Injectable mapping from names to event plugin modules.\n */\n\nvar namesToPlugins = {};\n/**\n * Recomputes the plugin list using the injected plugins and plugin ordering.\n *\n * @private\n */\n\nfunction recomputePluginOrdering() {\n if (!eventPluginOrder) {\n // Wait until an `eventPluginOrder` is injected.\n return;\n }\n\n for (var pluginName in namesToPlugins) {\n var pluginModule = namesToPlugins[pluginName];\n var pluginIndex = eventPluginOrder.indexOf(pluginName);\n\n if (!(pluginIndex > -1)) {\n {\n throw Error( \"EventPluginRegistry: Cannot inject event plugins that do not exist in the plugin ordering, `\" + pluginName + \"`.\" );\n }\n }\n\n if (plugins[pluginIndex]) {\n continue;\n }\n\n if (!pluginModule.extractEvents) {\n {\n throw Error( \"EventPluginRegistry: Event plugins must implement an `extractEvents` method, but `\" + pluginName + \"` does not.\" );\n }\n }\n\n plugins[pluginIndex] = pluginModule;\n var publishedEvents = pluginModule.eventTypes;\n\n for (var eventName in publishedEvents) {\n if (!publishEventForPlugin(publishedEvents[eventName], pluginModule, eventName)) {\n {\n throw Error( \"EventPluginRegistry: Failed to publish event `\" + eventName + \"` for plugin `\" + pluginName + \"`.\" );\n }\n }\n }\n }\n}\n/**\n * Publishes an event so that it can be dispatched by the supplied plugin.\n *\n * @param {object} dispatchConfig Dispatch configuration for the event.\n * @param {object} PluginModule Plugin publishing the event.\n * @return {boolean} True if the event was successfully published.\n * @private\n */\n\n\nfunction publishEventForPlugin(dispatchConfig, pluginModule, eventName) {\n if (!!eventNameDispatchConfigs.hasOwnProperty(eventName)) {\n {\n throw Error( \"EventPluginRegistry: More than one plugin attempted to publish the same event name, `\" + eventName + \"`.\" );\n }\n }\n\n eventNameDispatchConfigs[eventName] = dispatchConfig;\n var phasedRegistrationNames = dispatchConfig.phasedRegistrationNames;\n\n if (phasedRegistrationNames) {\n for (var phaseName in phasedRegistrationNames) {\n if (phasedRegistrationNames.hasOwnProperty(phaseName)) {\n var phasedRegistrationName = phasedRegistrationNames[phaseName];\n publishRegistrationName(phasedRegistrationName, pluginModule, eventName);\n }\n }\n\n return true;\n } else if (dispatchConfig.registrationName) {\n publishRegistrationName(dispatchConfig.registrationName, pluginModule, eventName);\n return true;\n }\n\n return false;\n}\n/**\n * Publishes a registration name that is used to identify dispatched events.\n *\n * @param {string} registrationName Registration name to add.\n * @param {object} PluginModule Plugin publishing the event.\n * @private\n */\n\n\nfunction publishRegistrationName(registrationName, pluginModule, eventName) {\n if (!!registrationNameModules[registrationName]) {\n {\n throw Error( \"EventPluginRegistry: More than one plugin attempted to publish the same registration name, `\" + registrationName + \"`.\" );\n }\n }\n\n registrationNameModules[registrationName] = pluginModule;\n registrationNameDependencies[registrationName] = pluginModule.eventTypes[eventName].dependencies;\n\n {\n var lowerCasedName = registrationName.toLowerCase();\n possibleRegistrationNames[lowerCasedName] = registrationName;\n\n if (registrationName === 'onDoubleClick') {\n possibleRegistrationNames.ondblclick = registrationName;\n }\n }\n}\n/**\n * Registers plugins so that they can extract and dispatch events.\n */\n\n/**\n * Ordered list of injected plugins.\n */\n\n\nvar plugins = [];\n/**\n * Mapping from event name to dispatch config\n */\n\nvar eventNameDispatchConfigs = {};\n/**\n * Mapping from registration name to plugin module\n */\n\nvar registrationNameModules = {};\n/**\n * Mapping from registration name to event name\n */\n\nvar registrationNameDependencies = {};\n/**\n * Mapping from lowercase registration names to the properly cased version,\n * used to warn in the case of missing event handlers. Available\n * only in true.\n * @type {Object}\n */\n\nvar possibleRegistrationNames = {} ; // Trust the developer to only use possibleRegistrationNames in true\n\n/**\n * Injects an ordering of plugins (by plugin name). This allows the ordering\n * to be decoupled from injection of the actual plugins so that ordering is\n * always deterministic regardless of packaging, on-the-fly injection, etc.\n *\n * @param {array} InjectedEventPluginOrder\n * @internal\n */\n\nfunction injectEventPluginOrder(injectedEventPluginOrder) {\n if (!!eventPluginOrder) {\n {\n throw Error( \"EventPluginRegistry: Cannot inject event plugin ordering more than once. You are likely trying to load more than one copy of React.\" );\n }\n } // Clone the ordering so it cannot be dynamically mutated.\n\n\n eventPluginOrder = Array.prototype.slice.call(injectedEventPluginOrder);\n recomputePluginOrdering();\n}\n/**\n * Injects plugins to be used by plugin event system. The plugin names must be\n * in the ordering injected by `injectEventPluginOrder`.\n *\n * Plugins can be injected as part of page initialization or on-the-fly.\n *\n * @param {object} injectedNamesToPlugins Map from names to plugin modules.\n * @internal\n */\n\nfunction injectEventPluginsByName(injectedNamesToPlugins) {\n var isOrderingDirty = false;\n\n for (var pluginName in injectedNamesToPlugins) {\n if (!injectedNamesToPlugins.hasOwnProperty(pluginName)) {\n continue;\n }\n\n var pluginModule = injectedNamesToPlugins[pluginName];\n\n if (!namesToPlugins.hasOwnProperty(pluginName) || namesToPlugins[pluginName] !== pluginModule) {\n if (!!namesToPlugins[pluginName]) {\n {\n throw Error( \"EventPluginRegistry: Cannot inject two different event plugins using the same name, `\" + pluginName + \"`.\" );\n }\n }\n\n namesToPlugins[pluginName] = pluginModule;\n isOrderingDirty = true;\n }\n }\n\n if (isOrderingDirty) {\n recomputePluginOrdering();\n }\n}\n\nvar canUseDOM = !!(typeof window !== 'undefined' && typeof window.document !== 'undefined' && typeof window.document.createElement !== 'undefined');\n\nvar PLUGIN_EVENT_SYSTEM = 1;\nvar IS_REPLAYED = 1 << 5;\nvar IS_FIRST_ANCESTOR = 1 << 6;\n\nvar restoreImpl = null;\nvar restoreTarget = null;\nvar restoreQueue = null;\n\nfunction restoreStateOfTarget(target) {\n // We perform this translation at the end of the event loop so that we\n // always receive the correct fiber here\n var internalInstance = getInstanceFromNode(target);\n\n if (!internalInstance) {\n // Unmounted\n return;\n }\n\n if (!(typeof restoreImpl === 'function')) {\n {\n throw Error( \"setRestoreImplementation() needs to be called to handle a target for controlled events. This error is likely caused by a bug in React. Please file an issue.\" );\n }\n }\n\n var stateNode = internalInstance.stateNode; // Guard against Fiber being unmounted.\n\n if (stateNode) {\n var _props = getFiberCurrentPropsFromNode(stateNode);\n\n restoreImpl(internalInstance.stateNode, internalInstance.type, _props);\n }\n}\n\nfunction setRestoreImplementation(impl) {\n restoreImpl = impl;\n}\nfunction enqueueStateRestore(target) {\n if (restoreTarget) {\n if (restoreQueue) {\n restoreQueue.push(target);\n } else {\n restoreQueue = [target];\n }\n } else {\n restoreTarget = target;\n }\n}\nfunction needsStateRestore() {\n return restoreTarget !== null || restoreQueue !== null;\n}\nfunction restoreStateIfNeeded() {\n if (!restoreTarget) {\n return;\n }\n\n var target = restoreTarget;\n var queuedTargets = restoreQueue;\n restoreTarget = null;\n restoreQueue = null;\n restoreStateOfTarget(target);\n\n if (queuedTargets) {\n for (var i = 0; i < queuedTargets.length; i++) {\n restoreStateOfTarget(queuedTargets[i]);\n }\n }\n}\n\nvar enableProfilerTimer = true; // Trace which interactions trigger each commit.\n\nvar enableDeprecatedFlareAPI = false; // Experimental Host Component support.\n\nvar enableFundamentalAPI = false; // Experimental Scope support.\nvar warnAboutStringRefs = false;\n\n// the renderer. Such as when we're dispatching events or if third party\n// libraries need to call batchedUpdates. Eventually, this API will go away when\n// everything is batched by default. We'll then have a similar API to opt-out of\n// scheduled work and instead do synchronous work.\n// Defaults\n\nvar batchedUpdatesImpl = function (fn, bookkeeping) {\n return fn(bookkeeping);\n};\n\nvar discreteUpdatesImpl = function (fn, a, b, c, d) {\n return fn(a, b, c, d);\n};\n\nvar flushDiscreteUpdatesImpl = function () {};\n\nvar batchedEventUpdatesImpl = batchedUpdatesImpl;\nvar isInsideEventHandler = false;\nvar isBatchingEventUpdates = false;\n\nfunction finishEventHandler() {\n // Here we wait until all updates have propagated, which is important\n // when using controlled components within layers:\n // https://github.com/facebook/react/issues/1698\n // Then we restore state of any controlled component.\n var controlledComponentsHavePendingUpdates = needsStateRestore();\n\n if (controlledComponentsHavePendingUpdates) {\n // If a controlled event was fired, we may need to restore the state of\n // the DOM node back to the controlled value. This is necessary when React\n // bails out of the update without touching the DOM.\n flushDiscreteUpdatesImpl();\n restoreStateIfNeeded();\n }\n}\n\nfunction batchedUpdates(fn, bookkeeping) {\n if (isInsideEventHandler) {\n // If we are currently inside another batch, we need to wait until it\n // fully completes before restoring state.\n return fn(bookkeeping);\n }\n\n isInsideEventHandler = true;\n\n try {\n return batchedUpdatesImpl(fn, bookkeeping);\n } finally {\n isInsideEventHandler = false;\n finishEventHandler();\n }\n}\nfunction batchedEventUpdates(fn, a, b) {\n if (isBatchingEventUpdates) {\n // If we are currently inside another batch, we need to wait until it\n // fully completes before restoring state.\n return fn(a, b);\n }\n\n isBatchingEventUpdates = true;\n\n try {\n return batchedEventUpdatesImpl(fn, a, b);\n } finally {\n isBatchingEventUpdates = false;\n finishEventHandler();\n }\n} // This is for the React Flare event system\nfunction discreteUpdates(fn, a, b, c, d) {\n var prevIsInsideEventHandler = isInsideEventHandler;\n isInsideEventHandler = true;\n\n try {\n return discreteUpdatesImpl(fn, a, b, c, d);\n } finally {\n isInsideEventHandler = prevIsInsideEventHandler;\n\n if (!isInsideEventHandler) {\n finishEventHandler();\n }\n }\n}\nfunction flushDiscreteUpdatesIfNeeded(timeStamp) {\n // event.timeStamp isn't overly reliable due to inconsistencies in\n // how different browsers have historically provided the time stamp.\n // Some browsers provide high-resolution time stamps for all events,\n // some provide low-resolution time stamps for all events. FF < 52\n // even mixes both time stamps together. Some browsers even report\n // negative time stamps or time stamps that are 0 (iOS9) in some cases.\n // Given we are only comparing two time stamps with equality (!==),\n // we are safe from the resolution differences. If the time stamp is 0\n // we bail-out of preventing the flush, which can affect semantics,\n // such as if an earlier flush removes or adds event listeners that\n // are fired in the subsequent flush. However, this is the same\n // behaviour as we had before this change, so the risks are low.\n if (!isInsideEventHandler && (!enableDeprecatedFlareAPI )) {\n flushDiscreteUpdatesImpl();\n }\n}\nfunction setBatchingImplementation(_batchedUpdatesImpl, _discreteUpdatesImpl, _flushDiscreteUpdatesImpl, _batchedEventUpdatesImpl) {\n batchedUpdatesImpl = _batchedUpdatesImpl;\n discreteUpdatesImpl = _discreteUpdatesImpl;\n flushDiscreteUpdatesImpl = _flushDiscreteUpdatesImpl;\n batchedEventUpdatesImpl = _batchedEventUpdatesImpl;\n}\n\nvar DiscreteEvent = 0;\nvar UserBlockingEvent = 1;\nvar ContinuousEvent = 2;\n\n// A reserved attribute.\n// It is handled by React separately and shouldn't be written to the DOM.\nvar RESERVED = 0; // A simple string attribute.\n// Attributes that aren't in the whitelist are presumed to have this type.\n\nvar STRING = 1; // A string attribute that accepts booleans in React. In HTML, these are called\n// \"enumerated\" attributes with \"true\" and \"false\" as possible values.\n// When true, it should be set to a \"true\" string.\n// When false, it should be set to a \"false\" string.\n\nvar BOOLEANISH_STRING = 2; // A real boolean attribute.\n// When true, it should be present (set either to an empty string or its name).\n// When false, it should be omitted.\n\nvar BOOLEAN = 3; // An attribute that can be used as a flag as well as with a value.\n// When true, it should be present (set either to an empty string or its name).\n// When false, it should be omitted.\n// For any other value, should be present with that value.\n\nvar OVERLOADED_BOOLEAN = 4; // An attribute that must be numeric or parse as a numeric.\n// When falsy, it should be removed.\n\nvar NUMERIC = 5; // An attribute that must be positive numeric or parse as a positive numeric.\n// When falsy, it should be removed.\n\nvar POSITIVE_NUMERIC = 6;\n\n/* eslint-disable max-len */\nvar ATTRIBUTE_NAME_START_CHAR = \":A-Z_a-z\\\\u00C0-\\\\u00D6\\\\u00D8-\\\\u00F6\\\\u00F8-\\\\u02FF\\\\u0370-\\\\u037D\\\\u037F-\\\\u1FFF\\\\u200C-\\\\u200D\\\\u2070-\\\\u218F\\\\u2C00-\\\\u2FEF\\\\u3001-\\\\uD7FF\\\\uF900-\\\\uFDCF\\\\uFDF0-\\\\uFFFD\";\n/* eslint-enable max-len */\n\nvar ATTRIBUTE_NAME_CHAR = ATTRIBUTE_NAME_START_CHAR + \"\\\\-.0-9\\\\u00B7\\\\u0300-\\\\u036F\\\\u203F-\\\\u2040\";\nvar ROOT_ATTRIBUTE_NAME = 'data-reactroot';\nvar VALID_ATTRIBUTE_NAME_REGEX = new RegExp('^[' + ATTRIBUTE_NAME_START_CHAR + '][' + ATTRIBUTE_NAME_CHAR + ']*$');\nvar hasOwnProperty = Object.prototype.hasOwnProperty;\nvar illegalAttributeNameCache = {};\nvar validatedAttributeNameCache = {};\nfunction isAttributeNameSafe(attributeName) {\n if (hasOwnProperty.call(validatedAttributeNameCache, attributeName)) {\n return true;\n }\n\n if (hasOwnProperty.call(illegalAttributeNameCache, attributeName)) {\n return false;\n }\n\n if (VALID_ATTRIBUTE_NAME_REGEX.test(attributeName)) {\n validatedAttributeNameCache[attributeName] = true;\n return true;\n }\n\n illegalAttributeNameCache[attributeName] = true;\n\n {\n error('Invalid attribute name: `%s`', attributeName);\n }\n\n return false;\n}\nfunction shouldIgnoreAttribute(name, propertyInfo, isCustomComponentTag) {\n if (propertyInfo !== null) {\n return propertyInfo.type === RESERVED;\n }\n\n if (isCustomComponentTag) {\n return false;\n }\n\n if (name.length > 2 && (name[0] === 'o' || name[0] === 'O') && (name[1] === 'n' || name[1] === 'N')) {\n return true;\n }\n\n return false;\n}\nfunction shouldRemoveAttributeWithWarning(name, value, propertyInfo, isCustomComponentTag) {\n if (propertyInfo !== null && propertyInfo.type === RESERVED) {\n return false;\n }\n\n switch (typeof value) {\n case 'function': // $FlowIssue symbol is perfectly valid here\n\n case 'symbol':\n // eslint-disable-line\n return true;\n\n case 'boolean':\n {\n if (isCustomComponentTag) {\n return false;\n }\n\n if (propertyInfo !== null) {\n return !propertyInfo.acceptsBooleans;\n } else {\n var prefix = name.toLowerCase().slice(0, 5);\n return prefix !== 'data-' && prefix !== 'aria-';\n }\n }\n\n default:\n return false;\n }\n}\nfunction shouldRemoveAttribute(name, value, propertyInfo, isCustomComponentTag) {\n if (value === null || typeof value === 'undefined') {\n return true;\n }\n\n if (shouldRemoveAttributeWithWarning(name, value, propertyInfo, isCustomComponentTag)) {\n return true;\n }\n\n if (isCustomComponentTag) {\n return false;\n }\n\n if (propertyInfo !== null) {\n switch (propertyInfo.type) {\n case BOOLEAN:\n return !value;\n\n case OVERLOADED_BOOLEAN:\n return value === false;\n\n case NUMERIC:\n return isNaN(value);\n\n case POSITIVE_NUMERIC:\n return isNaN(value) || value < 1;\n }\n }\n\n return false;\n}\nfunction getPropertyInfo(name) {\n return properties.hasOwnProperty(name) ? properties[name] : null;\n}\n\nfunction PropertyInfoRecord(name, type, mustUseProperty, attributeName, attributeNamespace, sanitizeURL) {\n this.acceptsBooleans = type === BOOLEANISH_STRING || type === BOOLEAN || type === OVERLOADED_BOOLEAN;\n this.attributeName = attributeName;\n this.attributeNamespace = attributeNamespace;\n this.mustUseProperty = mustUseProperty;\n this.propertyName = name;\n this.type = type;\n this.sanitizeURL = sanitizeURL;\n} // When adding attributes to this list, be sure to also add them to\n// the `possibleStandardNames` module to ensure casing and incorrect\n// name warnings.\n\n\nvar properties = {}; // These props are reserved by React. They shouldn't be written to the DOM.\n\nvar reservedProps = ['children', 'dangerouslySetInnerHTML', // TODO: This prevents the assignment of defaultValue to regular\n// elements (not just inputs). Now that ReactDOMInput assigns to the\n// defaultValue property -- do we need this?\n'defaultValue', 'defaultChecked', 'innerHTML', 'suppressContentEditableWarning', 'suppressHydrationWarning', 'style'];\n\nreservedProps.forEach(function (name) {\n properties[name] = new PropertyInfoRecord(name, RESERVED, false, // mustUseProperty\n name, // attributeName\n null, // attributeNamespace\n false);\n}); // A few React string attributes have a different name.\n// This is a mapping from React prop names to the attribute names.\n\n[['acceptCharset', 'accept-charset'], ['className', 'class'], ['htmlFor', 'for'], ['httpEquiv', 'http-equiv']].forEach(function (_ref) {\n var name = _ref[0],\n attributeName = _ref[1];\n properties[name] = new PropertyInfoRecord(name, STRING, false, // mustUseProperty\n attributeName, // attributeName\n null, // attributeNamespace\n false);\n}); // These are \"enumerated\" HTML attributes that accept \"true\" and \"false\".\n// In React, we let users pass `true` and `false` even though technically\n// these aren't boolean attributes (they are coerced to strings).\n\n['contentEditable', 'draggable', 'spellCheck', 'value'].forEach(function (name) {\n properties[name] = new PropertyInfoRecord(name, BOOLEANISH_STRING, false, // mustUseProperty\n name.toLowerCase(), // attributeName\n null, // attributeNamespace\n false);\n}); // These are \"enumerated\" SVG attributes that accept \"true\" and \"false\".\n// In React, we let users pass `true` and `false` even though technically\n// these aren't boolean attributes (they are coerced to strings).\n// Since these are SVG attributes, their attribute names are case-sensitive.\n\n['autoReverse', 'externalResourcesRequired', 'focusable', 'preserveAlpha'].forEach(function (name) {\n properties[name] = new PropertyInfoRecord(name, BOOLEANISH_STRING, false, // mustUseProperty\n name, // attributeName\n null, // attributeNamespace\n false);\n}); // These are HTML boolean attributes.\n\n['allowFullScreen', 'async', // Note: there is a special case that prevents it from being written to the DOM\n// on the client side because the browsers are inconsistent. Instead we call focus().\n'autoFocus', 'autoPlay', 'controls', 'default', 'defer', 'disabled', 'disablePictureInPicture', 'formNoValidate', 'hidden', 'loop', 'noModule', 'noValidate', 'open', 'playsInline', 'readOnly', 'required', 'reversed', 'scoped', 'seamless', // Microdata\n'itemScope'].forEach(function (name) {\n properties[name] = new PropertyInfoRecord(name, BOOLEAN, false, // mustUseProperty\n name.toLowerCase(), // attributeName\n null, // attributeNamespace\n false);\n}); // These are the few React props that we set as DOM properties\n// rather than attributes. These are all booleans.\n\n['checked', // Note: `option.selected` is not updated if `select.multiple` is\n// disabled with `removeAttribute`. We have special logic for handling this.\n'multiple', 'muted', 'selected' // NOTE: if you add a camelCased prop to this list,\n// you'll need to set attributeName to name.toLowerCase()\n// instead in the assignment below.\n].forEach(function (name) {\n properties[name] = new PropertyInfoRecord(name, BOOLEAN, true, // mustUseProperty\n name, // attributeName\n null, // attributeNamespace\n false);\n}); // These are HTML attributes that are \"overloaded booleans\": they behave like\n// booleans, but can also accept a string value.\n\n['capture', 'download' // NOTE: if you add a camelCased prop to this list,\n// you'll need to set attributeName to name.toLowerCase()\n// instead in the assignment below.\n].forEach(function (name) {\n properties[name] = new PropertyInfoRecord(name, OVERLOADED_BOOLEAN, false, // mustUseProperty\n name, // attributeName\n null, // attributeNamespace\n false);\n}); // These are HTML attributes that must be positive numbers.\n\n['cols', 'rows', 'size', 'span' // NOTE: if you add a camelCased prop to this list,\n// you'll need to set attributeName to name.toLowerCase()\n// instead in the assignment below.\n].forEach(function (name) {\n properties[name] = new PropertyInfoRecord(name, POSITIVE_NUMERIC, false, // mustUseProperty\n name, // attributeName\n null, // attributeNamespace\n false);\n}); // These are HTML attributes that must be numbers.\n\n['rowSpan', 'start'].forEach(function (name) {\n properties[name] = new PropertyInfoRecord(name, NUMERIC, false, // mustUseProperty\n name.toLowerCase(), // attributeName\n null, // attributeNamespace\n false);\n});\nvar CAMELIZE = /[\\-\\:]([a-z])/g;\n\nvar capitalize = function (token) {\n return token[1].toUpperCase();\n}; // This is a list of all SVG attributes that need special casing, namespacing,\n// or boolean value assignment. Regular attributes that just accept strings\n// and have the same names are omitted, just like in the HTML whitelist.\n// Some of these attributes can be hard to find. This list was created by\n// scraping the MDN documentation.\n\n\n['accent-height', 'alignment-baseline', 'arabic-form', 'baseline-shift', 'cap-height', 'clip-path', 'clip-rule', 'color-interpolation', 'color-interpolation-filters', 'color-profile', 'color-rendering', 'dominant-baseline', 'enable-background', 'fill-opacity', 'fill-rule', 'flood-color', 'flood-opacity', 'font-family', 'font-size', 'font-size-adjust', 'font-stretch', 'font-style', 'font-variant', 'font-weight', 'glyph-name', 'glyph-orientation-horizontal', 'glyph-orientation-vertical', 'horiz-adv-x', 'horiz-origin-x', 'image-rendering', 'letter-spacing', 'lighting-color', 'marker-end', 'marker-mid', 'marker-start', 'overline-position', 'overline-thickness', 'paint-order', 'panose-1', 'pointer-events', 'rendering-intent', 'shape-rendering', 'stop-color', 'stop-opacity', 'strikethrough-position', 'strikethrough-thickness', 'stroke-dasharray', 'stroke-dashoffset', 'stroke-linecap', 'stroke-linejoin', 'stroke-miterlimit', 'stroke-opacity', 'stroke-width', 'text-anchor', 'text-decoration', 'text-rendering', 'underline-position', 'underline-thickness', 'unicode-bidi', 'unicode-range', 'units-per-em', 'v-alphabetic', 'v-hanging', 'v-ideographic', 'v-mathematical', 'vector-effect', 'vert-adv-y', 'vert-origin-x', 'vert-origin-y', 'word-spacing', 'writing-mode', 'xmlns:xlink', 'x-height' // NOTE: if you add a camelCased prop to this list,\n// you'll need to set attributeName to name.toLowerCase()\n// instead in the assignment below.\n].forEach(function (attributeName) {\n var name = attributeName.replace(CAMELIZE, capitalize);\n properties[name] = new PropertyInfoRecord(name, STRING, false, // mustUseProperty\n attributeName, null, // attributeNamespace\n false);\n}); // String SVG attributes with the xlink namespace.\n\n['xlink:actuate', 'xlink:arcrole', 'xlink:role', 'xlink:show', 'xlink:title', 'xlink:type' // NOTE: if you add a camelCased prop to this list,\n// you'll need to set attributeName to name.toLowerCase()\n// instead in the assignment below.\n].forEach(function (attributeName) {\n var name = attributeName.replace(CAMELIZE, capitalize);\n properties[name] = new PropertyInfoRecord(name, STRING, false, // mustUseProperty\n attributeName, 'http://www.w3.org/1999/xlink', false);\n}); // String SVG attributes with the xml namespace.\n\n['xml:base', 'xml:lang', 'xml:space' // NOTE: if you add a camelCased prop to this list,\n// you'll need to set attributeName to name.toLowerCase()\n// instead in the assignment below.\n].forEach(function (attributeName) {\n var name = attributeName.replace(CAMELIZE, capitalize);\n properties[name] = new PropertyInfoRecord(name, STRING, false, // mustUseProperty\n attributeName, 'http://www.w3.org/XML/1998/namespace', false);\n}); // These attribute exists both in HTML and SVG.\n// The attribute name is case-sensitive in SVG so we can't just use\n// the React name like we do for attributes that exist only in HTML.\n\n['tabIndex', 'crossOrigin'].forEach(function (attributeName) {\n properties[attributeName] = new PropertyInfoRecord(attributeName, STRING, false, // mustUseProperty\n attributeName.toLowerCase(), // attributeName\n null, // attributeNamespace\n false);\n}); // These attributes accept URLs. These must not allow javascript: URLS.\n// These will also need to accept Trusted Types object in the future.\n\nvar xlinkHref = 'xlinkHref';\nproperties[xlinkHref] = new PropertyInfoRecord('xlinkHref', STRING, false, // mustUseProperty\n'xlink:href', 'http://www.w3.org/1999/xlink', true);\n['src', 'href', 'action', 'formAction'].forEach(function (attributeName) {\n properties[attributeName] = new PropertyInfoRecord(attributeName, STRING, false, // mustUseProperty\n attributeName.toLowerCase(), // attributeName\n null, // attributeNamespace\n true);\n});\n\nvar ReactDebugCurrentFrame = null;\n\n{\n ReactDebugCurrentFrame = ReactSharedInternals.ReactDebugCurrentFrame;\n} // A javascript: URL can contain leading C0 control or \\u0020 SPACE,\n// and any newline or tab are filtered out as if they're not part of the URL.\n// https://url.spec.whatwg.org/#url-parsing\n// Tab or newline are defined as \\r\\n\\t:\n// https://infra.spec.whatwg.org/#ascii-tab-or-newline\n// A C0 control is a code point in the range \\u0000 NULL to \\u001F\n// INFORMATION SEPARATOR ONE, inclusive:\n// https://infra.spec.whatwg.org/#c0-control-or-space\n\n/* eslint-disable max-len */\n\n\nvar isJavaScriptProtocol = /^[\\u0000-\\u001F ]*j[\\r\\n\\t]*a[\\r\\n\\t]*v[\\r\\n\\t]*a[\\r\\n\\t]*s[\\r\\n\\t]*c[\\r\\n\\t]*r[\\r\\n\\t]*i[\\r\\n\\t]*p[\\r\\n\\t]*t[\\r\\n\\t]*\\:/i;\nvar didWarn = false;\n\nfunction sanitizeURL(url) {\n {\n if (!didWarn && isJavaScriptProtocol.test(url)) {\n didWarn = true;\n\n error('A future version of React will block javascript: URLs as a security precaution. ' + 'Use event handlers instead if you can. If you need to generate unsafe HTML try ' + 'using dangerouslySetInnerHTML instead. React was passed %s.', JSON.stringify(url));\n }\n }\n}\n\n/**\n * Get the value for a property on a node. Only used in DEV for SSR validation.\n * The \"expected\" argument is used as a hint of what the expected value is.\n * Some properties have multiple equivalent values.\n */\nfunction getValueForProperty(node, name, expected, propertyInfo) {\n {\n if (propertyInfo.mustUseProperty) {\n var propertyName = propertyInfo.propertyName;\n return node[propertyName];\n } else {\n if ( propertyInfo.sanitizeURL) {\n // If we haven't fully disabled javascript: URLs, and if\n // the hydration is successful of a javascript: URL, we\n // still want to warn on the client.\n sanitizeURL('' + expected);\n }\n\n var attributeName = propertyInfo.attributeName;\n var stringValue = null;\n\n if (propertyInfo.type === OVERLOADED_BOOLEAN) {\n if (node.hasAttribute(attributeName)) {\n var value = node.getAttribute(attributeName);\n\n if (value === '') {\n return true;\n }\n\n if (shouldRemoveAttribute(name, expected, propertyInfo, false)) {\n return value;\n }\n\n if (value === '' + expected) {\n return expected;\n }\n\n return value;\n }\n } else if (node.hasAttribute(attributeName)) {\n if (shouldRemoveAttribute(name, expected, propertyInfo, false)) {\n // We had an attribute but shouldn't have had one, so read it\n // for the error message.\n return node.getAttribute(attributeName);\n }\n\n if (propertyInfo.type === BOOLEAN) {\n // If this was a boolean, it doesn't matter what the value is\n // the fact that we have it is the same as the expected.\n return expected;\n } // Even if this property uses a namespace we use getAttribute\n // because we assume its namespaced name is the same as our config.\n // To use getAttributeNS we need the local name which we don't have\n // in our config atm.\n\n\n stringValue = node.getAttribute(attributeName);\n }\n\n if (shouldRemoveAttribute(name, expected, propertyInfo, false)) {\n return stringValue === null ? expected : stringValue;\n } else if (stringValue === '' + expected) {\n return expected;\n } else {\n return stringValue;\n }\n }\n }\n}\n/**\n * Get the value for a attribute on a node. Only used in DEV for SSR validation.\n * The third argument is used as a hint of what the expected value is. Some\n * attributes have multiple equivalent values.\n */\n\nfunction getValueForAttribute(node, name, expected) {\n {\n if (!isAttributeNameSafe(name)) {\n return;\n }\n\n if (!node.hasAttribute(name)) {\n return expected === undefined ? undefined : null;\n }\n\n var value = node.getAttribute(name);\n\n if (value === '' + expected) {\n return expected;\n }\n\n return value;\n }\n}\n/**\n * Sets the value for a property on a node.\n *\n * @param {DOMElement} node\n * @param {string} name\n * @param {*} value\n */\n\nfunction setValueForProperty(node, name, value, isCustomComponentTag) {\n var propertyInfo = getPropertyInfo(name);\n\n if (shouldIgnoreAttribute(name, propertyInfo, isCustomComponentTag)) {\n return;\n }\n\n if (shouldRemoveAttribute(name, value, propertyInfo, isCustomComponentTag)) {\n value = null;\n } // If the prop isn't in the special list, treat it as a simple attribute.\n\n\n if (isCustomComponentTag || propertyInfo === null) {\n if (isAttributeNameSafe(name)) {\n var _attributeName = name;\n\n if (value === null) {\n node.removeAttribute(_attributeName);\n } else {\n node.setAttribute(_attributeName, '' + value);\n }\n }\n\n return;\n }\n\n var mustUseProperty = propertyInfo.mustUseProperty;\n\n if (mustUseProperty) {\n var propertyName = propertyInfo.propertyName;\n\n if (value === null) {\n var type = propertyInfo.type;\n node[propertyName] = type === BOOLEAN ? false : '';\n } else {\n // Contrary to `setAttribute`, object properties are properly\n // `toString`ed by IE8/9.\n node[propertyName] = value;\n }\n\n return;\n } // The rest are treated as attributes with special cases.\n\n\n var attributeName = propertyInfo.attributeName,\n attributeNamespace = propertyInfo.attributeNamespace;\n\n if (value === null) {\n node.removeAttribute(attributeName);\n } else {\n var _type = propertyInfo.type;\n var attributeValue;\n\n if (_type === BOOLEAN || _type === OVERLOADED_BOOLEAN && value === true) {\n // If attribute type is boolean, we know for sure it won't be an execution sink\n // and we won't require Trusted Type here.\n attributeValue = '';\n } else {\n // `setAttribute` with objects becomes only `[object]` in IE8/9,\n // ('' + value) makes it output the correct toString()-value.\n {\n attributeValue = '' + value;\n }\n\n if (propertyInfo.sanitizeURL) {\n sanitizeURL(attributeValue.toString());\n }\n }\n\n if (attributeNamespace) {\n node.setAttributeNS(attributeNamespace, attributeName, attributeValue);\n } else {\n node.setAttribute(attributeName, attributeValue);\n }\n }\n}\n\nvar BEFORE_SLASH_RE = /^(.*)[\\\\\\/]/;\nfunction describeComponentFrame (name, source, ownerName) {\n var sourceInfo = '';\n\n if (source) {\n var path = source.fileName;\n var fileName = path.replace(BEFORE_SLASH_RE, '');\n\n {\n // In DEV, include code for a common special case:\n // prefer \"folder/index.js\" instead of just \"index.js\".\n if (/^index\\./.test(fileName)) {\n var match = path.match(BEFORE_SLASH_RE);\n\n if (match) {\n var pathBeforeSlash = match[1];\n\n if (pathBeforeSlash) {\n var folderName = pathBeforeSlash.replace(BEFORE_SLASH_RE, '');\n fileName = folderName + '/' + fileName;\n }\n }\n }\n }\n\n sourceInfo = ' (at ' + fileName + ':' + source.lineNumber + ')';\n } else if (ownerName) {\n sourceInfo = ' (created by ' + ownerName + ')';\n }\n\n return '\\n in ' + (name || 'Unknown') + sourceInfo;\n}\n\n// The Symbol used to tag the ReactElement-like types. If there is no native Symbol\n// nor polyfill, then a plain number is used for performance.\nvar hasSymbol = typeof Symbol === 'function' && Symbol.for;\nvar REACT_ELEMENT_TYPE = hasSymbol ? Symbol.for('react.element') : 0xeac7;\nvar REACT_PORTAL_TYPE = hasSymbol ? Symbol.for('react.portal') : 0xeaca;\nvar REACT_FRAGMENT_TYPE = hasSymbol ? Symbol.for('react.fragment') : 0xeacb;\nvar REACT_STRICT_MODE_TYPE = hasSymbol ? Symbol.for('react.strict_mode') : 0xeacc;\nvar REACT_PROFILER_TYPE = hasSymbol ? Symbol.for('react.profiler') : 0xead2;\nvar REACT_PROVIDER_TYPE = hasSymbol ? Symbol.for('react.provider') : 0xeacd;\nvar REACT_CONTEXT_TYPE = hasSymbol ? Symbol.for('react.context') : 0xeace; // TODO: We don't use AsyncMode or ConcurrentMode anymore. They were temporary\nvar REACT_CONCURRENT_MODE_TYPE = hasSymbol ? Symbol.for('react.concurrent_mode') : 0xeacf;\nvar REACT_FORWARD_REF_TYPE = hasSymbol ? Symbol.for('react.forward_ref') : 0xead0;\nvar REACT_SUSPENSE_TYPE = hasSymbol ? Symbol.for('react.suspense') : 0xead1;\nvar REACT_SUSPENSE_LIST_TYPE = hasSymbol ? Symbol.for('react.suspense_list') : 0xead8;\nvar REACT_MEMO_TYPE = hasSymbol ? Symbol.for('react.memo') : 0xead3;\nvar REACT_LAZY_TYPE = hasSymbol ? Symbol.for('react.lazy') : 0xead4;\nvar REACT_BLOCK_TYPE = hasSymbol ? Symbol.for('react.block') : 0xead9;\nvar MAYBE_ITERATOR_SYMBOL = typeof Symbol === 'function' && Symbol.iterator;\nvar FAUX_ITERATOR_SYMBOL = '@@iterator';\nfunction getIteratorFn(maybeIterable) {\n if (maybeIterable === null || typeof maybeIterable !== 'object') {\n return null;\n }\n\n var maybeIterator = MAYBE_ITERATOR_SYMBOL && maybeIterable[MAYBE_ITERATOR_SYMBOL] || maybeIterable[FAUX_ITERATOR_SYMBOL];\n\n if (typeof maybeIterator === 'function') {\n return maybeIterator;\n }\n\n return null;\n}\n\nvar Uninitialized = -1;\nvar Pending = 0;\nvar Resolved = 1;\nvar Rejected = 2;\nfunction refineResolvedLazyComponent(lazyComponent) {\n return lazyComponent._status === Resolved ? lazyComponent._result : null;\n}\nfunction initializeLazyComponentType(lazyComponent) {\n if (lazyComponent._status === Uninitialized) {\n lazyComponent._status = Pending;\n var ctor = lazyComponent._ctor;\n var thenable = ctor();\n lazyComponent._result = thenable;\n thenable.then(function (moduleObject) {\n if (lazyComponent._status === Pending) {\n var defaultExport = moduleObject.default;\n\n {\n if (defaultExport === undefined) {\n error('lazy: Expected the result of a dynamic import() call. ' + 'Instead received: %s\\n\\nYour code should look like: \\n ' + \"const MyComponent = lazy(() => import('./MyComponent'))\", moduleObject);\n }\n }\n\n lazyComponent._status = Resolved;\n lazyComponent._result = defaultExport;\n }\n }, function (error) {\n if (lazyComponent._status === Pending) {\n lazyComponent._status = Rejected;\n lazyComponent._result = error;\n }\n });\n }\n}\n\nfunction getWrappedName(outerType, innerType, wrapperName) {\n var functionName = innerType.displayName || innerType.name || '';\n return outerType.displayName || (functionName !== '' ? wrapperName + \"(\" + functionName + \")\" : wrapperName);\n}\n\nfunction getComponentName(type) {\n if (type == null) {\n // Host root, text node or just invalid type.\n return null;\n }\n\n {\n if (typeof type.tag === 'number') {\n error('Received an unexpected object in getComponentName(). ' + 'This is likely a bug in React. Please file an issue.');\n }\n }\n\n if (typeof type === 'function') {\n return type.displayName || type.name || null;\n }\n\n if (typeof type === 'string') {\n return type;\n }\n\n switch (type) {\n case REACT_FRAGMENT_TYPE:\n return 'Fragment';\n\n case REACT_PORTAL_TYPE:\n return 'Portal';\n\n case REACT_PROFILER_TYPE:\n return \"Profiler\";\n\n case REACT_STRICT_MODE_TYPE:\n return 'StrictMode';\n\n case REACT_SUSPENSE_TYPE:\n return 'Suspense';\n\n case REACT_SUSPENSE_LIST_TYPE:\n return 'SuspenseList';\n }\n\n if (typeof type === 'object') {\n switch (type.$$typeof) {\n case REACT_CONTEXT_TYPE:\n return 'Context.Consumer';\n\n case REACT_PROVIDER_TYPE:\n return 'Context.Provider';\n\n case REACT_FORWARD_REF_TYPE:\n return getWrappedName(type, type.render, 'ForwardRef');\n\n case REACT_MEMO_TYPE:\n return getComponentName(type.type);\n\n case REACT_BLOCK_TYPE:\n return getComponentName(type.render);\n\n case REACT_LAZY_TYPE:\n {\n var thenable = type;\n var resolvedThenable = refineResolvedLazyComponent(thenable);\n\n if (resolvedThenable) {\n return getComponentName(resolvedThenable);\n }\n\n break;\n }\n }\n }\n\n return null;\n}\n\nvar ReactDebugCurrentFrame$1 = ReactSharedInternals.ReactDebugCurrentFrame;\n\nfunction describeFiber(fiber) {\n switch (fiber.tag) {\n case HostRoot:\n case HostPortal:\n case HostText:\n case Fragment:\n case ContextProvider:\n case ContextConsumer:\n return '';\n\n default:\n var owner = fiber._debugOwner;\n var source = fiber._debugSource;\n var name = getComponentName(fiber.type);\n var ownerName = null;\n\n if (owner) {\n ownerName = getComponentName(owner.type);\n }\n\n return describeComponentFrame(name, source, ownerName);\n }\n}\n\nfunction getStackByFiberInDevAndProd(workInProgress) {\n var info = '';\n var node = workInProgress;\n\n do {\n info += describeFiber(node);\n node = node.return;\n } while (node);\n\n return info;\n}\nvar current = null;\nvar isRendering = false;\nfunction getCurrentFiberOwnerNameInDevOrNull() {\n {\n if (current === null) {\n return null;\n }\n\n var owner = current._debugOwner;\n\n if (owner !== null && typeof owner !== 'undefined') {\n return getComponentName(owner.type);\n }\n }\n\n return null;\n}\nfunction getCurrentFiberStackInDev() {\n {\n if (current === null) {\n return '';\n } // Safe because if current fiber exists, we are reconciling,\n // and it is guaranteed to be the work-in-progress version.\n\n\n return getStackByFiberInDevAndProd(current);\n }\n}\nfunction resetCurrentFiber() {\n {\n ReactDebugCurrentFrame$1.getCurrentStack = null;\n current = null;\n isRendering = false;\n }\n}\nfunction setCurrentFiber(fiber) {\n {\n ReactDebugCurrentFrame$1.getCurrentStack = getCurrentFiberStackInDev;\n current = fiber;\n isRendering = false;\n }\n}\nfunction setIsRendering(rendering) {\n {\n isRendering = rendering;\n }\n}\n\n// Flow does not allow string concatenation of most non-string types. To work\n// around this limitation, we use an opaque type that can only be obtained by\n// passing the value through getToStringValue first.\nfunction toString(value) {\n return '' + value;\n}\nfunction getToStringValue(value) {\n switch (typeof value) {\n case 'boolean':\n case 'number':\n case 'object':\n case 'string':\n case 'undefined':\n return value;\n\n default:\n // function, symbol are assigned as empty strings\n return '';\n }\n}\n\nvar ReactDebugCurrentFrame$2 = null;\nvar ReactControlledValuePropTypes = {\n checkPropTypes: null\n};\n\n{\n ReactDebugCurrentFrame$2 = ReactSharedInternals.ReactDebugCurrentFrame;\n var hasReadOnlyValue = {\n button: true,\n checkbox: true,\n image: true,\n hidden: true,\n radio: true,\n reset: true,\n submit: true\n };\n var propTypes = {\n value: function (props, propName, componentName) {\n if (hasReadOnlyValue[props.type] || props.onChange || props.readOnly || props.disabled || props[propName] == null || enableDeprecatedFlareAPI ) {\n return null;\n }\n\n return new Error('You provided a `value` prop to a form field without an ' + '`onChange` handler. This will render a read-only field. If ' + 'the field should be mutable use `defaultValue`. Otherwise, ' + 'set either `onChange` or `readOnly`.');\n },\n checked: function (props, propName, componentName) {\n if (props.onChange || props.readOnly || props.disabled || props[propName] == null || enableDeprecatedFlareAPI ) {\n return null;\n }\n\n return new Error('You provided a `checked` prop to a form field without an ' + '`onChange` handler. This will render a read-only field. If ' + 'the field should be mutable use `defaultChecked`. Otherwise, ' + 'set either `onChange` or `readOnly`.');\n }\n };\n /**\n * Provide a linked `value` attribute for controlled forms. You should not use\n * this outside of the ReactDOM controlled form components.\n */\n\n ReactControlledValuePropTypes.checkPropTypes = function (tagName, props) {\n checkPropTypes(propTypes, props, 'prop', tagName, ReactDebugCurrentFrame$2.getStackAddendum);\n };\n}\n\nfunction isCheckable(elem) {\n var type = elem.type;\n var nodeName = elem.nodeName;\n return nodeName && nodeName.toLowerCase() === 'input' && (type === 'checkbox' || type === 'radio');\n}\n\nfunction getTracker(node) {\n return node._valueTracker;\n}\n\nfunction detachTracker(node) {\n node._valueTracker = null;\n}\n\nfunction getValueFromNode(node) {\n var value = '';\n\n if (!node) {\n return value;\n }\n\n if (isCheckable(node)) {\n value = node.checked ? 'true' : 'false';\n } else {\n value = node.value;\n }\n\n return value;\n}\n\nfunction trackValueOnNode(node) {\n var valueField = isCheckable(node) ? 'checked' : 'value';\n var descriptor = Object.getOwnPropertyDescriptor(node.constructor.prototype, valueField);\n var currentValue = '' + node[valueField]; // if someone has already defined a value or Safari, then bail\n // and don't track value will cause over reporting of changes,\n // but it's better then a hard failure\n // (needed for certain tests that spyOn input values and Safari)\n\n if (node.hasOwnProperty(valueField) || typeof descriptor === 'undefined' || typeof descriptor.get !== 'function' || typeof descriptor.set !== 'function') {\n return;\n }\n\n var get = descriptor.get,\n set = descriptor.set;\n Object.defineProperty(node, valueField, {\n configurable: true,\n get: function () {\n return get.call(this);\n },\n set: function (value) {\n currentValue = '' + value;\n set.call(this, value);\n }\n }); // We could've passed this the first time\n // but it triggers a bug in IE11 and Edge 14/15.\n // Calling defineProperty() again should be equivalent.\n // https://github.com/facebook/react/issues/11768\n\n Object.defineProperty(node, valueField, {\n enumerable: descriptor.enumerable\n });\n var tracker = {\n getValue: function () {\n return currentValue;\n },\n setValue: function (value) {\n currentValue = '' + value;\n },\n stopTracking: function () {\n detachTracker(node);\n delete node[valueField];\n }\n };\n return tracker;\n}\n\nfunction track(node) {\n if (getTracker(node)) {\n return;\n } // TODO: Once it's just Fiber we can move this to node._wrapperState\n\n\n node._valueTracker = trackValueOnNode(node);\n}\nfunction updateValueIfChanged(node) {\n if (!node) {\n return false;\n }\n\n var tracker = getTracker(node); // if there is no tracker at this point it's unlikely\n // that trying again will succeed\n\n if (!tracker) {\n return true;\n }\n\n var lastValue = tracker.getValue();\n var nextValue = getValueFromNode(node);\n\n if (nextValue !== lastValue) {\n tracker.setValue(nextValue);\n return true;\n }\n\n return false;\n}\n\nvar didWarnValueDefaultValue = false;\nvar didWarnCheckedDefaultChecked = false;\nvar didWarnControlledToUncontrolled = false;\nvar didWarnUncontrolledToControlled = false;\n\nfunction isControlled(props) {\n var usesChecked = props.type === 'checkbox' || props.type === 'radio';\n return usesChecked ? props.checked != null : props.value != null;\n}\n/**\n * Implements an <input> host component that allows setting these optional\n * props: `checked`, `value`, `defaultChecked`, and `defaultValue`.\n *\n * If `checked` or `value` are not supplied (or null/undefined), user actions\n * that affect the checked state or value will trigger updates to the element.\n *\n * If they are supplied (and not null/undefined), the rendered element will not\n * trigger updates to the element. Instead, the props must change in order for\n * the rendered element to be updated.\n *\n * The rendered element will be initialized as unchecked (or `defaultChecked`)\n * with an empty value (or `defaultValue`).\n *\n * See http://www.w3.org/TR/2012/WD-html5-20121025/the-input-element.html\n */\n\n\nfunction getHostProps(element, props) {\n var node = element;\n var checked = props.checked;\n\n var hostProps = _assign({}, props, {\n defaultChecked: undefined,\n defaultValue: undefined,\n value: undefined,\n checked: checked != null ? checked : node._wrapperState.initialChecked\n });\n\n return hostProps;\n}\nfunction initWrapperState(element, props) {\n {\n ReactControlledValuePropTypes.checkPropTypes('input', props);\n\n if (props.checked !== undefined && props.defaultChecked !== undefined && !didWarnCheckedDefaultChecked) {\n error('%s contains an input of type %s with both checked and defaultChecked props. ' + 'Input elements must be either controlled or uncontrolled ' + '(specify either the checked prop, or the defaultChecked prop, but not ' + 'both). Decide between using a controlled or uncontrolled input ' + 'element and remove one of these props. More info: ' + 'https://fb.me/react-controlled-components', getCurrentFiberOwnerNameInDevOrNull() || 'A component', props.type);\n\n didWarnCheckedDefaultChecked = true;\n }\n\n if (props.value !== undefined && props.defaultValue !== undefined && !didWarnValueDefaultValue) {\n error('%s contains an input of type %s with both value and defaultValue props. ' + 'Input elements must be either controlled or uncontrolled ' + '(specify either the value prop, or the defaultValue prop, but not ' + 'both). Decide between using a controlled or uncontrolled input ' + 'element and remove one of these props. More info: ' + 'https://fb.me/react-controlled-components', getCurrentFiberOwnerNameInDevOrNull() || 'A component', props.type);\n\n didWarnValueDefaultValue = true;\n }\n }\n\n var node = element;\n var defaultValue = props.defaultValue == null ? '' : props.defaultValue;\n node._wrapperState = {\n initialChecked: props.checked != null ? props.checked : props.defaultChecked,\n initialValue: getToStringValue(props.value != null ? props.value : defaultValue),\n controlled: isControlled(props)\n };\n}\nfunction updateChecked(element, props) {\n var node = element;\n var checked = props.checked;\n\n if (checked != null) {\n setValueForProperty(node, 'checked', checked, false);\n }\n}\nfunction updateWrapper(element, props) {\n var node = element;\n\n {\n var controlled = isControlled(props);\n\n if (!node._wrapperState.controlled && controlled && !didWarnUncontrolledToControlled) {\n error('A component is changing an uncontrolled input of type %s to be controlled. ' + 'Input elements should not switch from uncontrolled to controlled (or vice versa). ' + 'Decide between using a controlled or uncontrolled input ' + 'element for the lifetime of the component. More info: https://fb.me/react-controlled-components', props.type);\n\n didWarnUncontrolledToControlled = true;\n }\n\n if (node._wrapperState.controlled && !controlled && !didWarnControlledToUncontrolled) {\n error('A component is changing a controlled input of type %s to be uncontrolled. ' + 'Input elements should not switch from controlled to uncontrolled (or vice versa). ' + 'Decide between using a controlled or uncontrolled input ' + 'element for the lifetime of the component. More info: https://fb.me/react-controlled-components', props.type);\n\n didWarnControlledToUncontrolled = true;\n }\n }\n\n updateChecked(element, props);\n var value = getToStringValue(props.value);\n var type = props.type;\n\n if (value != null) {\n if (type === 'number') {\n if (value === 0 && node.value === '' || // We explicitly want to coerce to number here if possible.\n // eslint-disable-next-line\n node.value != value) {\n node.value = toString(value);\n }\n } else if (node.value !== toString(value)) {\n node.value = toString(value);\n }\n } else if (type === 'submit' || type === 'reset') {\n // Submit/reset inputs need the attribute removed completely to avoid\n // blank-text buttons.\n node.removeAttribute('value');\n return;\n }\n\n {\n // When syncing the value attribute, the value comes from a cascade of\n // properties:\n // 1. The value React property\n // 2. The defaultValue React property\n // 3. Otherwise there should be no change\n if (props.hasOwnProperty('value')) {\n setDefaultValue(node, props.type, value);\n } else if (props.hasOwnProperty('defaultValue')) {\n setDefaultValue(node, props.type, getToStringValue(props.defaultValue));\n }\n }\n\n {\n // When syncing the checked attribute, it only changes when it needs\n // to be removed, such as transitioning from a checkbox into a text input\n if (props.checked == null && props.defaultChecked != null) {\n node.defaultChecked = !!props.defaultChecked;\n }\n }\n}\nfunction postMountWrapper(element, props, isHydrating) {\n var node = element; // Do not assign value if it is already set. This prevents user text input\n // from being lost during SSR hydration.\n\n if (props.hasOwnProperty('value') || props.hasOwnProperty('defaultValue')) {\n var type = props.type;\n var isButton = type === 'submit' || type === 'reset'; // Avoid setting value attribute on submit/reset inputs as it overrides the\n // default value provided by the browser. See: #12872\n\n if (isButton && (props.value === undefined || props.value === null)) {\n return;\n }\n\n var initialValue = toString(node._wrapperState.initialValue); // Do not assign value if it is already set. This prevents user text input\n // from being lost during SSR hydration.\n\n if (!isHydrating) {\n {\n // When syncing the value attribute, the value property should use\n // the wrapperState._initialValue property. This uses:\n //\n // 1. The value React property when present\n // 2. The defaultValue React property when present\n // 3. An empty string\n if (initialValue !== node.value) {\n node.value = initialValue;\n }\n }\n }\n\n {\n // Otherwise, the value attribute is synchronized to the property,\n // so we assign defaultValue to the same thing as the value property\n // assignment step above.\n node.defaultValue = initialValue;\n }\n } // Normally, we'd just do `node.checked = node.checked` upon initial mount, less this bug\n // this is needed to work around a chrome bug where setting defaultChecked\n // will sometimes influence the value of checked (even after detachment).\n // Reference: https://bugs.chromium.org/p/chromium/issues/detail?id=608416\n // We need to temporarily unset name to avoid disrupting radio button groups.\n\n\n var name = node.name;\n\n if (name !== '') {\n node.name = '';\n }\n\n {\n // When syncing the checked attribute, both the checked property and\n // attribute are assigned at the same time using defaultChecked. This uses:\n //\n // 1. The checked React property when present\n // 2. The defaultChecked React property when present\n // 3. Otherwise, false\n node.defaultChecked = !node.defaultChecked;\n node.defaultChecked = !!node._wrapperState.initialChecked;\n }\n\n if (name !== '') {\n node.name = name;\n }\n}\nfunction restoreControlledState(element, props) {\n var node = element;\n updateWrapper(node, props);\n updateNamedCousins(node, props);\n}\n\nfunction updateNamedCousins(rootNode, props) {\n var name = props.name;\n\n if (props.type === 'radio' && name != null) {\n var queryRoot = rootNode;\n\n while (queryRoot.parentNode) {\n queryRoot = queryRoot.parentNode;\n } // If `rootNode.form` was non-null, then we could try `form.elements`,\n // but that sometimes behaves strangely in IE8. We could also try using\n // `form.getElementsByName`, but that will only return direct children\n // and won't include inputs that use the HTML5 `form=` attribute. Since\n // the input might not even be in a form. It might not even be in the\n // document. Let's just use the local `querySelectorAll` to ensure we don't\n // miss anything.\n\n\n var group = queryRoot.querySelectorAll('input[name=' + JSON.stringify('' + name) + '][type=\"radio\"]');\n\n for (var i = 0; i < group.length; i++) {\n var otherNode = group[i];\n\n if (otherNode === rootNode || otherNode.form !== rootNode.form) {\n continue;\n } // This will throw if radio buttons rendered by different copies of React\n // and the same name are rendered into the same form (same as #1939).\n // That's probably okay; we don't support it just as we don't support\n // mixing React radio buttons with non-React ones.\n\n\n var otherProps = getFiberCurrentPropsFromNode$1(otherNode);\n\n if (!otherProps) {\n {\n throw Error( \"ReactDOMInput: Mixing React and non-React radio inputs with the same `name` is not supported.\" );\n }\n } // We need update the tracked value on the named cousin since the value\n // was changed but the input saw no event or value set\n\n\n updateValueIfChanged(otherNode); // If this is a controlled radio button group, forcing the input that\n // was previously checked to update will cause it to be come re-checked\n // as appropriate.\n\n updateWrapper(otherNode, otherProps);\n }\n }\n} // In Chrome, assigning defaultValue to certain input types triggers input validation.\n// For number inputs, the display value loses trailing decimal points. For email inputs,\n// Chrome raises \"The specified value <x> is not a valid email address\".\n//\n// Here we check to see if the defaultValue has actually changed, avoiding these problems\n// when the user is inputting text\n//\n// https://github.com/facebook/react/issues/7253\n\n\nfunction setDefaultValue(node, type, value) {\n if ( // Focused number inputs synchronize on blur. See ChangeEventPlugin.js\n type !== 'number' || node.ownerDocument.activeElement !== node) {\n if (value == null) {\n node.defaultValue = toString(node._wrapperState.initialValue);\n } else if (node.defaultValue !== toString(value)) {\n node.defaultValue = toString(value);\n }\n }\n}\n\nvar didWarnSelectedSetOnOption = false;\nvar didWarnInvalidChild = false;\n\nfunction flattenChildren(children) {\n var content = ''; // Flatten children. We'll warn if they are invalid\n // during validateProps() which runs for hydration too.\n // Note that this would throw on non-element objects.\n // Elements are stringified (which is normally irrelevant\n // but matters for <fbt>).\n\n React.Children.forEach(children, function (child) {\n if (child == null) {\n return;\n }\n\n content += child; // Note: we don't warn about invalid children here.\n // Instead, this is done separately below so that\n // it happens during the hydration codepath too.\n });\n return content;\n}\n/**\n * Implements an <option> host component that warns when `selected` is set.\n */\n\n\nfunction validateProps(element, props) {\n {\n // This mirrors the codepath above, but runs for hydration too.\n // Warn about invalid children here so that client and hydration are consistent.\n // TODO: this seems like it could cause a DEV-only throw for hydration\n // if children contains a non-element object. We should try to avoid that.\n if (typeof props.children === 'object' && props.children !== null) {\n React.Children.forEach(props.children, function (child) {\n if (child == null) {\n return;\n }\n\n if (typeof child === 'string' || typeof child === 'number') {\n return;\n }\n\n if (typeof child.type !== 'string') {\n return;\n }\n\n if (!didWarnInvalidChild) {\n didWarnInvalidChild = true;\n\n error('Only strings and numbers are supported as <option> children.');\n }\n });\n } // TODO: Remove support for `selected` in <option>.\n\n\n if (props.selected != null && !didWarnSelectedSetOnOption) {\n error('Use the `defaultValue` or `value` props on <select> instead of ' + 'setting `selected` on <option>.');\n\n didWarnSelectedSetOnOption = true;\n }\n }\n}\nfunction postMountWrapper$1(element, props) {\n // value=\"\" should make a value attribute (#6219)\n if (props.value != null) {\n element.setAttribute('value', toString(getToStringValue(props.value)));\n }\n}\nfunction getHostProps$1(element, props) {\n var hostProps = _assign({\n children: undefined\n }, props);\n\n var content = flattenChildren(props.children);\n\n if (content) {\n hostProps.children = content;\n }\n\n return hostProps;\n}\n\nvar didWarnValueDefaultValue$1;\n\n{\n didWarnValueDefaultValue$1 = false;\n}\n\nfunction getDeclarationErrorAddendum() {\n var ownerName = getCurrentFiberOwnerNameInDevOrNull();\n\n if (ownerName) {\n return '\\n\\nCheck the render method of `' + ownerName + '`.';\n }\n\n return '';\n}\n\nvar valuePropNames = ['value', 'defaultValue'];\n/**\n * Validation function for `value` and `defaultValue`.\n */\n\nfunction checkSelectPropTypes(props) {\n {\n ReactControlledValuePropTypes.checkPropTypes('select', props);\n\n for (var i = 0; i < valuePropNames.length; i++) {\n var propName = valuePropNames[i];\n\n if (props[propName] == null) {\n continue;\n }\n\n var isArray = Array.isArray(props[propName]);\n\n if (props.multiple && !isArray) {\n error('The `%s` prop supplied to <select> must be an array if ' + '`multiple` is true.%s', propName, getDeclarationErrorAddendum());\n } else if (!props.multiple && isArray) {\n error('The `%s` prop supplied to <select> must be a scalar ' + 'value if `multiple` is false.%s', propName, getDeclarationErrorAddendum());\n }\n }\n }\n}\n\nfunction updateOptions(node, multiple, propValue, setDefaultSelected) {\n var options = node.options;\n\n if (multiple) {\n var selectedValues = propValue;\n var selectedValue = {};\n\n for (var i = 0; i < selectedValues.length; i++) {\n // Prefix to avoid chaos with special keys.\n selectedValue['$' + selectedValues[i]] = true;\n }\n\n for (var _i = 0; _i < options.length; _i++) {\n var selected = selectedValue.hasOwnProperty('$' + options[_i].value);\n\n if (options[_i].selected !== selected) {\n options[_i].selected = selected;\n }\n\n if (selected && setDefaultSelected) {\n options[_i].defaultSelected = true;\n }\n }\n } else {\n // Do not set `select.value` as exact behavior isn't consistent across all\n // browsers for all cases.\n var _selectedValue = toString(getToStringValue(propValue));\n\n var defaultSelected = null;\n\n for (var _i2 = 0; _i2 < options.length; _i2++) {\n if (options[_i2].value === _selectedValue) {\n options[_i2].selected = true;\n\n if (setDefaultSelected) {\n options[_i2].defaultSelected = true;\n }\n\n return;\n }\n\n if (defaultSelected === null && !options[_i2].disabled) {\n defaultSelected = options[_i2];\n }\n }\n\n if (defaultSelected !== null) {\n defaultSelected.selected = true;\n }\n }\n}\n/**\n * Implements a <select> host component that allows optionally setting the\n * props `value` and `defaultValue`. If `multiple` is false, the prop must be a\n * stringable. If `multiple` is true, the prop must be an array of stringables.\n *\n * If `value` is not supplied (or null/undefined), user actions that change the\n * selected option will trigger updates to the rendered options.\n *\n * If it is supplied (and not null/undefined), the rendered options will not\n * update in response to user actions. Instead, the `value` prop must change in\n * order for the rendered options to update.\n *\n * If `defaultValue` is provided, any options with the supplied values will be\n * selected.\n */\n\n\nfunction getHostProps$2(element, props) {\n return _assign({}, props, {\n value: undefined\n });\n}\nfunction initWrapperState$1(element, props) {\n var node = element;\n\n {\n checkSelectPropTypes(props);\n }\n\n node._wrapperState = {\n wasMultiple: !!props.multiple\n };\n\n {\n if (props.value !== undefined && props.defaultValue !== undefined && !didWarnValueDefaultValue$1) {\n error('Select elements must be either controlled or uncontrolled ' + '(specify either the value prop, or the defaultValue prop, but not ' + 'both). Decide between using a controlled or uncontrolled select ' + 'element and remove one of these props. More info: ' + 'https://fb.me/react-controlled-components');\n\n didWarnValueDefaultValue$1 = true;\n }\n }\n}\nfunction postMountWrapper$2(element, props) {\n var node = element;\n node.multiple = !!props.multiple;\n var value = props.value;\n\n if (value != null) {\n updateOptions(node, !!props.multiple, value, false);\n } else if (props.defaultValue != null) {\n updateOptions(node, !!props.multiple, props.defaultValue, true);\n }\n}\nfunction postUpdateWrapper(element, props) {\n var node = element;\n var wasMultiple = node._wrapperState.wasMultiple;\n node._wrapperState.wasMultiple = !!props.multiple;\n var value = props.value;\n\n if (value != null) {\n updateOptions(node, !!props.multiple, value, false);\n } else if (wasMultiple !== !!props.multiple) {\n // For simplicity, reapply `defaultValue` if `multiple` is toggled.\n if (props.defaultValue != null) {\n updateOptions(node, !!props.multiple, props.defaultValue, true);\n } else {\n // Revert the select back to its default unselected state.\n updateOptions(node, !!props.multiple, props.multiple ? [] : '', false);\n }\n }\n}\nfunction restoreControlledState$1(element, props) {\n var node = element;\n var value = props.value;\n\n if (value != null) {\n updateOptions(node, !!props.multiple, value, false);\n }\n}\n\nvar didWarnValDefaultVal = false;\n\n/**\n * Implements a <textarea> host component that allows setting `value`, and\n * `defaultValue`. This differs from the traditional DOM API because value is\n * usually set as PCDATA children.\n *\n * If `value` is not supplied (or null/undefined), user actions that affect the\n * value will trigger updates to the element.\n *\n * If `value` is supplied (and not null/undefined), the rendered element will\n * not trigger updates to the element. Instead, the `value` prop must change in\n * order for the rendered element to be updated.\n *\n * The rendered element will be initialized with an empty value, the prop\n * `defaultValue` if specified, or the children content (deprecated).\n */\nfunction getHostProps$3(element, props) {\n var node = element;\n\n if (!(props.dangerouslySetInnerHTML == null)) {\n {\n throw Error( \"`dangerouslySetInnerHTML` does not make sense on <textarea>.\" );\n }\n } // Always set children to the same thing. In IE9, the selection range will\n // get reset if `textContent` is mutated. We could add a check in setTextContent\n // to only set the value if/when the value differs from the node value (which would\n // completely solve this IE9 bug), but Sebastian+Sophie seemed to like this\n // solution. The value can be a boolean or object so that's why it's forced\n // to be a string.\n\n\n var hostProps = _assign({}, props, {\n value: undefined,\n defaultValue: undefined,\n children: toString(node._wrapperState.initialValue)\n });\n\n return hostProps;\n}\nfunction initWrapperState$2(element, props) {\n var node = element;\n\n {\n ReactControlledValuePropTypes.checkPropTypes('textarea', props);\n\n if (props.value !== undefined && props.defaultValue !== undefined && !didWarnValDefaultVal) {\n error('%s contains a textarea with both value and defaultValue props. ' + 'Textarea elements must be either controlled or uncontrolled ' + '(specify either the value prop, or the defaultValue prop, but not ' + 'both). Decide between using a controlled or uncontrolled textarea ' + 'and remove one of these props. More info: ' + 'https://fb.me/react-controlled-components', getCurrentFiberOwnerNameInDevOrNull() || 'A component');\n\n didWarnValDefaultVal = true;\n }\n }\n\n var initialValue = props.value; // Only bother fetching default value if we're going to use it\n\n if (initialValue == null) {\n var children = props.children,\n defaultValue = props.defaultValue;\n\n if (children != null) {\n {\n error('Use the `defaultValue` or `value` props instead of setting ' + 'children on <textarea>.');\n }\n\n {\n if (!(defaultValue == null)) {\n {\n throw Error( \"If you supply `defaultValue` on a <textarea>, do not pass children.\" );\n }\n }\n\n if (Array.isArray(children)) {\n if (!(children.length <= 1)) {\n {\n throw Error( \"<textarea> can only have at most one child.\" );\n }\n }\n\n children = children[0];\n }\n\n defaultValue = children;\n }\n }\n\n if (defaultValue == null) {\n defaultValue = '';\n }\n\n initialValue = defaultValue;\n }\n\n node._wrapperState = {\n initialValue: getToStringValue(initialValue)\n };\n}\nfunction updateWrapper$1(element, props) {\n var node = element;\n var value = getToStringValue(props.value);\n var defaultValue = getToStringValue(props.defaultValue);\n\n if (value != null) {\n // Cast `value` to a string to ensure the value is set correctly. While\n // browsers typically do this as necessary, jsdom doesn't.\n var newValue = toString(value); // To avoid side effects (such as losing text selection), only set value if changed\n\n if (newValue !== node.value) {\n node.value = newValue;\n }\n\n if (props.defaultValue == null && node.defaultValue !== newValue) {\n node.defaultValue = newValue;\n }\n }\n\n if (defaultValue != null) {\n node.defaultValue = toString(defaultValue);\n }\n}\nfunction postMountWrapper$3(element, props) {\n var node = element; // This is in postMount because we need access to the DOM node, which is not\n // available until after the component has mounted.\n\n var textContent = node.textContent; // Only set node.value if textContent is equal to the expected\n // initial value. In IE10/IE11 there is a bug where the placeholder attribute\n // will populate textContent as well.\n // https://developer.microsoft.com/microsoft-edge/platform/issues/101525/\n\n if (textContent === node._wrapperState.initialValue) {\n if (textContent !== '' && textContent !== null) {\n node.value = textContent;\n }\n }\n}\nfunction restoreControlledState$2(element, props) {\n // DOM component is still mounted; update\n updateWrapper$1(element, props);\n}\n\nvar HTML_NAMESPACE = 'http://www.w3.org/1999/xhtml';\nvar MATH_NAMESPACE = 'http://www.w3.org/1998/Math/MathML';\nvar SVG_NAMESPACE = 'http://www.w3.org/2000/svg';\nvar Namespaces = {\n html: HTML_NAMESPACE,\n mathml: MATH_NAMESPACE,\n svg: SVG_NAMESPACE\n}; // Assumes there is no parent namespace.\n\nfunction getIntrinsicNamespace(type) {\n switch (type) {\n case 'svg':\n return SVG_NAMESPACE;\n\n case 'math':\n return MATH_NAMESPACE;\n\n default:\n return HTML_NAMESPACE;\n }\n}\nfunction getChildNamespace(parentNamespace, type) {\n if (parentNamespace == null || parentNamespace === HTML_NAMESPACE) {\n // No (or default) parent namespace: potential entry point.\n return getIntrinsicNamespace(type);\n }\n\n if (parentNamespace === SVG_NAMESPACE && type === 'foreignObject') {\n // We're leaving SVG.\n return HTML_NAMESPACE;\n } // By default, pass namespace below.\n\n\n return parentNamespace;\n}\n\n/* globals MSApp */\n\n/**\n * Create a function which has 'unsafe' privileges (required by windows8 apps)\n */\nvar createMicrosoftUnsafeLocalFunction = function (func) {\n if (typeof MSApp !== 'undefined' && MSApp.execUnsafeLocalFunction) {\n return function (arg0, arg1, arg2, arg3) {\n MSApp.execUnsafeLocalFunction(function () {\n return func(arg0, arg1, arg2, arg3);\n });\n };\n } else {\n return func;\n }\n};\n\nvar reusableSVGContainer;\n/**\n * Set the innerHTML property of a node\n *\n * @param {DOMElement} node\n * @param {string} html\n * @internal\n */\n\nvar setInnerHTML = createMicrosoftUnsafeLocalFunction(function (node, html) {\n if (node.namespaceURI === Namespaces.svg) {\n\n if (!('innerHTML' in node)) {\n // IE does not have innerHTML for SVG nodes, so instead we inject the\n // new markup in a temp node and then move the child nodes across into\n // the target node\n reusableSVGContainer = reusableSVGContainer || document.createElement('div');\n reusableSVGContainer.innerHTML = '<svg>' + html.valueOf().toString() + '</svg>';\n var svgNode = reusableSVGContainer.firstChild;\n\n while (node.firstChild) {\n node.removeChild(node.firstChild);\n }\n\n while (svgNode.firstChild) {\n node.appendChild(svgNode.firstChild);\n }\n\n return;\n }\n }\n\n node.innerHTML = html;\n});\n\n/**\n * HTML nodeType values that represent the type of the node\n */\nvar ELEMENT_NODE = 1;\nvar TEXT_NODE = 3;\nvar COMMENT_NODE = 8;\nvar DOCUMENT_NODE = 9;\nvar DOCUMENT_FRAGMENT_NODE = 11;\n\n/**\n * Set the textContent property of a node. For text updates, it's faster\n * to set the `nodeValue` of the Text node directly instead of using\n * `.textContent` which will remove the existing node and create a new one.\n *\n * @param {DOMElement} node\n * @param {string} text\n * @internal\n */\n\nvar setTextContent = function (node, text) {\n if (text) {\n var firstChild = node.firstChild;\n\n if (firstChild && firstChild === node.lastChild && firstChild.nodeType === TEXT_NODE) {\n firstChild.nodeValue = text;\n return;\n }\n }\n\n node.textContent = text;\n};\n\n// Do not use the below two methods directly!\n// Instead use constants exported from DOMTopLevelEventTypes in ReactDOM.\n// (It is the only module that is allowed to access these methods.)\nfunction unsafeCastStringToDOMTopLevelType(topLevelType) {\n return topLevelType;\n}\nfunction unsafeCastDOMTopLevelTypeToString(topLevelType) {\n return topLevelType;\n}\n\n/**\n * Generate a mapping of standard vendor prefixes using the defined style property and event name.\n *\n * @param {string} styleProp\n * @param {string} eventName\n * @returns {object}\n */\n\nfunction makePrefixMap(styleProp, eventName) {\n var prefixes = {};\n prefixes[styleProp.toLowerCase()] = eventName.toLowerCase();\n prefixes['Webkit' + styleProp] = 'webkit' + eventName;\n prefixes['Moz' + styleProp] = 'moz' + eventName;\n return prefixes;\n}\n/**\n * A list of event names to a configurable list of vendor prefixes.\n */\n\n\nvar vendorPrefixes = {\n animationend: makePrefixMap('Animation', 'AnimationEnd'),\n animationiteration: makePrefixMap('Animation', 'AnimationIteration'),\n animationstart: makePrefixMap('Animation', 'AnimationStart'),\n transitionend: makePrefixMap('Transition', 'TransitionEnd')\n};\n/**\n * Event names that have already been detected and prefixed (if applicable).\n */\n\nvar prefixedEventNames = {};\n/**\n * Element to check for prefixes on.\n */\n\nvar style = {};\n/**\n * Bootstrap if a DOM exists.\n */\n\nif (canUseDOM) {\n style = document.createElement('div').style; // On some platforms, in particular some releases of Android 4.x,\n // the un-prefixed \"animation\" and \"transition\" properties are defined on the\n // style object but the events that fire will still be prefixed, so we need\n // to check if the un-prefixed events are usable, and if not remove them from the map.\n\n if (!('AnimationEvent' in window)) {\n delete vendorPrefixes.animationend.animation;\n delete vendorPrefixes.animationiteration.animation;\n delete vendorPrefixes.animationstart.animation;\n } // Same as above\n\n\n if (!('TransitionEvent' in window)) {\n delete vendorPrefixes.transitionend.transition;\n }\n}\n/**\n * Attempts to determine the correct vendor prefixed event name.\n *\n * @param {string} eventName\n * @returns {string}\n */\n\n\nfunction getVendorPrefixedEventName(eventName) {\n if (prefixedEventNames[eventName]) {\n return prefixedEventNames[eventName];\n } else if (!vendorPrefixes[eventName]) {\n return eventName;\n }\n\n var prefixMap = vendorPrefixes[eventName];\n\n for (var styleProp in prefixMap) {\n if (prefixMap.hasOwnProperty(styleProp) && styleProp in style) {\n return prefixedEventNames[eventName] = prefixMap[styleProp];\n }\n }\n\n return eventName;\n}\n\n/**\n * To identify top level events in ReactDOM, we use constants defined by this\n * module. This is the only module that uses the unsafe* methods to express\n * that the constants actually correspond to the browser event names. This lets\n * us save some bundle size by avoiding a top level type -> event name map.\n * The rest of ReactDOM code should import top level types from this file.\n */\n\nvar TOP_ABORT = unsafeCastStringToDOMTopLevelType('abort');\nvar TOP_ANIMATION_END = unsafeCastStringToDOMTopLevelType(getVendorPrefixedEventName('animationend'));\nvar TOP_ANIMATION_ITERATION = unsafeCastStringToDOMTopLevelType(getVendorPrefixedEventName('animationiteration'));\nvar TOP_ANIMATION_START = unsafeCastStringToDOMTopLevelType(getVendorPrefixedEventName('animationstart'));\nvar TOP_BLUR = unsafeCastStringToDOMTopLevelType('blur');\nvar TOP_CAN_PLAY = unsafeCastStringToDOMTopLevelType('canplay');\nvar TOP_CAN_PLAY_THROUGH = unsafeCastStringToDOMTopLevelType('canplaythrough');\nvar TOP_CANCEL = unsafeCastStringToDOMTopLevelType('cancel');\nvar TOP_CHANGE = unsafeCastStringToDOMTopLevelType('change');\nvar TOP_CLICK = unsafeCastStringToDOMTopLevelType('click');\nvar TOP_CLOSE = unsafeCastStringToDOMTopLevelType('close');\nvar TOP_COMPOSITION_END = unsafeCastStringToDOMTopLevelType('compositionend');\nvar TOP_COMPOSITION_START = unsafeCastStringToDOMTopLevelType('compositionstart');\nvar TOP_COMPOSITION_UPDATE = unsafeCastStringToDOMTopLevelType('compositionupdate');\nvar TOP_CONTEXT_MENU = unsafeCastStringToDOMTopLevelType('contextmenu');\nvar TOP_COPY = unsafeCastStringToDOMTopLevelType('copy');\nvar TOP_CUT = unsafeCastStringToDOMTopLevelType('cut');\nvar TOP_DOUBLE_CLICK = unsafeCastStringToDOMTopLevelType('dblclick');\nvar TOP_AUX_CLICK = unsafeCastStringToDOMTopLevelType('auxclick');\nvar TOP_DRAG = unsafeCastStringToDOMTopLevelType('drag');\nvar TOP_DRAG_END = unsafeCastStringToDOMTopLevelType('dragend');\nvar TOP_DRAG_ENTER = unsafeCastStringToDOMTopLevelType('dragenter');\nvar TOP_DRAG_EXIT = unsafeCastStringToDOMTopLevelType('dragexit');\nvar TOP_DRAG_LEAVE = unsafeCastStringToDOMTopLevelType('dragleave');\nvar TOP_DRAG_OVER = unsafeCastStringToDOMTopLevelType('dragover');\nvar TOP_DRAG_START = unsafeCastStringToDOMTopLevelType('dragstart');\nvar TOP_DROP = unsafeCastStringToDOMTopLevelType('drop');\nvar TOP_DURATION_CHANGE = unsafeCastStringToDOMTopLevelType('durationchange');\nvar TOP_EMPTIED = unsafeCastStringToDOMTopLevelType('emptied');\nvar TOP_ENCRYPTED = unsafeCastStringToDOMTopLevelType('encrypted');\nvar TOP_ENDED = unsafeCastStringToDOMTopLevelType('ended');\nvar TOP_ERROR = unsafeCastStringToDOMTopLevelType('error');\nvar TOP_FOCUS = unsafeCastStringToDOMTopLevelType('focus');\nvar TOP_GOT_POINTER_CAPTURE = unsafeCastStringToDOMTopLevelType('gotpointercapture');\nvar TOP_INPUT = unsafeCastStringToDOMTopLevelType('input');\nvar TOP_INVALID = unsafeCastStringToDOMTopLevelType('invalid');\nvar TOP_KEY_DOWN = unsafeCastStringToDOMTopLevelType('keydown');\nvar TOP_KEY_PRESS = unsafeCastStringToDOMTopLevelType('keypress');\nvar TOP_KEY_UP = unsafeCastStringToDOMTopLevelType('keyup');\nvar TOP_LOAD = unsafeCastStringToDOMTopLevelType('load');\nvar TOP_LOAD_START = unsafeCastStringToDOMTopLevelType('loadstart');\nvar TOP_LOADED_DATA = unsafeCastStringToDOMTopLevelType('loadeddata');\nvar TOP_LOADED_METADATA = unsafeCastStringToDOMTopLevelType('loadedmetadata');\nvar TOP_LOST_POINTER_CAPTURE = unsafeCastStringToDOMTopLevelType('lostpointercapture');\nvar TOP_MOUSE_DOWN = unsafeCastStringToDOMTopLevelType('mousedown');\nvar TOP_MOUSE_MOVE = unsafeCastStringToDOMTopLevelType('mousemove');\nvar TOP_MOUSE_OUT = unsafeCastStringToDOMTopLevelType('mouseout');\nvar TOP_MOUSE_OVER = unsafeCastStringToDOMTopLevelType('mouseover');\nvar TOP_MOUSE_UP = unsafeCastStringToDOMTopLevelType('mouseup');\nvar TOP_PASTE = unsafeCastStringToDOMTopLevelType('paste');\nvar TOP_PAUSE = unsafeCastStringToDOMTopLevelType('pause');\nvar TOP_PLAY = unsafeCastStringToDOMTopLevelType('play');\nvar TOP_PLAYING = unsafeCastStringToDOMTopLevelType('playing');\nvar TOP_POINTER_CANCEL = unsafeCastStringToDOMTopLevelType('pointercancel');\nvar TOP_POINTER_DOWN = unsafeCastStringToDOMTopLevelType('pointerdown');\nvar TOP_POINTER_MOVE = unsafeCastStringToDOMTopLevelType('pointermove');\nvar TOP_POINTER_OUT = unsafeCastStringToDOMTopLevelType('pointerout');\nvar TOP_POINTER_OVER = unsafeCastStringToDOMTopLevelType('pointerover');\nvar TOP_POINTER_UP = unsafeCastStringToDOMTopLevelType('pointerup');\nvar TOP_PROGRESS = unsafeCastStringToDOMTopLevelType('progress');\nvar TOP_RATE_CHANGE = unsafeCastStringToDOMTopLevelType('ratechange');\nvar TOP_RESET = unsafeCastStringToDOMTopLevelType('reset');\nvar TOP_SCROLL = unsafeCastStringToDOMTopLevelType('scroll');\nvar TOP_SEEKED = unsafeCastStringToDOMTopLevelType('seeked');\nvar TOP_SEEKING = unsafeCastStringToDOMTopLevelType('seeking');\nvar TOP_SELECTION_CHANGE = unsafeCastStringToDOMTopLevelType('selectionchange');\nvar TOP_STALLED = unsafeCastStringToDOMTopLevelType('stalled');\nvar TOP_SUBMIT = unsafeCastStringToDOMTopLevelType('submit');\nvar TOP_SUSPEND = unsafeCastStringToDOMTopLevelType('suspend');\nvar TOP_TEXT_INPUT = unsafeCastStringToDOMTopLevelType('textInput');\nvar TOP_TIME_UPDATE = unsafeCastStringToDOMTopLevelType('timeupdate');\nvar TOP_TOGGLE = unsafeCastStringToDOMTopLevelType('toggle');\nvar TOP_TOUCH_CANCEL = unsafeCastStringToDOMTopLevelType('touchcancel');\nvar TOP_TOUCH_END = unsafeCastStringToDOMTopLevelType('touchend');\nvar TOP_TOUCH_MOVE = unsafeCastStringToDOMTopLevelType('touchmove');\nvar TOP_TOUCH_START = unsafeCastStringToDOMTopLevelType('touchstart');\nvar TOP_TRANSITION_END = unsafeCastStringToDOMTopLevelType(getVendorPrefixedEventName('transitionend'));\nvar TOP_VOLUME_CHANGE = unsafeCastStringToDOMTopLevelType('volumechange');\nvar TOP_WAITING = unsafeCastStringToDOMTopLevelType('waiting');\nvar TOP_WHEEL = unsafeCastStringToDOMTopLevelType('wheel'); // List of events that need to be individually attached to media elements.\n// Note that events in this list will *not* be listened to at the top level\n// unless they're explicitly whitelisted in `ReactBrowserEventEmitter.listenTo`.\n\nvar mediaEventTypes = [TOP_ABORT, TOP_CAN_PLAY, TOP_CAN_PLAY_THROUGH, TOP_DURATION_CHANGE, TOP_EMPTIED, TOP_ENCRYPTED, TOP_ENDED, TOP_ERROR, TOP_LOADED_DATA, TOP_LOADED_METADATA, TOP_LOAD_START, TOP_PAUSE, TOP_PLAY, TOP_PLAYING, TOP_PROGRESS, TOP_RATE_CHANGE, TOP_SEEKED, TOP_SEEKING, TOP_STALLED, TOP_SUSPEND, TOP_TIME_UPDATE, TOP_VOLUME_CHANGE, TOP_WAITING];\nfunction getRawEventName(topLevelType) {\n return unsafeCastDOMTopLevelTypeToString(topLevelType);\n}\n\nvar PossiblyWeakMap = typeof WeakMap === 'function' ? WeakMap : Map; // prettier-ignore\n\nvar elementListenerMap = new PossiblyWeakMap();\nfunction getListenerMapForElement(element) {\n var listenerMap = elementListenerMap.get(element);\n\n if (listenerMap === undefined) {\n listenerMap = new Map();\n elementListenerMap.set(element, listenerMap);\n }\n\n return listenerMap;\n}\n\n/**\n * `ReactInstanceMap` maintains a mapping from a public facing stateful\n * instance (key) and the internal representation (value). This allows public\n * methods to accept the user facing instance as an argument and map them back\n * to internal methods.\n *\n * Note that this module is currently shared and assumed to be stateless.\n * If this becomes an actual Map, that will break.\n */\nfunction get(key) {\n return key._reactInternalFiber;\n}\nfunction has(key) {\n return key._reactInternalFiber !== undefined;\n}\nfunction set(key, value) {\n key._reactInternalFiber = value;\n}\n\n// Don't change these two values. They're used by React Dev Tools.\nvar NoEffect =\n/* */\n0;\nvar PerformedWork =\n/* */\n1; // You can change the rest (and add more).\n\nvar Placement =\n/* */\n2;\nvar Update =\n/* */\n4;\nvar PlacementAndUpdate =\n/* */\n6;\nvar Deletion =\n/* */\n8;\nvar ContentReset =\n/* */\n16;\nvar Callback =\n/* */\n32;\nvar DidCapture =\n/* */\n64;\nvar Ref =\n/* */\n128;\nvar Snapshot =\n/* */\n256;\nvar Passive =\n/* */\n512;\nvar Hydrating =\n/* */\n1024;\nvar HydratingAndUpdate =\n/* */\n1028; // Passive & Update & Callback & Ref & Snapshot\n\nvar LifecycleEffectMask =\n/* */\n932; // Union of all host effects\n\nvar HostEffectMask =\n/* */\n2047;\nvar Incomplete =\n/* */\n2048;\nvar ShouldCapture =\n/* */\n4096;\n\nvar ReactCurrentOwner = ReactSharedInternals.ReactCurrentOwner;\nfunction getNearestMountedFiber(fiber) {\n var node = fiber;\n var nearestMounted = fiber;\n\n if (!fiber.alternate) {\n // If there is no alternate, this might be a new tree that isn't inserted\n // yet. If it is, then it will have a pending insertion effect on it.\n var nextNode = node;\n\n do {\n node = nextNode;\n\n if ((node.effectTag & (Placement | Hydrating)) !== NoEffect) {\n // This is an insertion or in-progress hydration. The nearest possible\n // mounted fiber is the parent but we need to continue to figure out\n // if that one is still mounted.\n nearestMounted = node.return;\n }\n\n nextNode = node.return;\n } while (nextNode);\n } else {\n while (node.return) {\n node = node.return;\n }\n }\n\n if (node.tag === HostRoot) {\n // TODO: Check if this was a nested HostRoot when used with\n // renderContainerIntoSubtree.\n return nearestMounted;\n } // If we didn't hit the root, that means that we're in an disconnected tree\n // that has been unmounted.\n\n\n return null;\n}\nfunction getSuspenseInstanceFromFiber(fiber) {\n if (fiber.tag === SuspenseComponent) {\n var suspenseState = fiber.memoizedState;\n\n if (suspenseState === null) {\n var current = fiber.alternate;\n\n if (current !== null) {\n suspenseState = current.memoizedState;\n }\n }\n\n if (suspenseState !== null) {\n return suspenseState.dehydrated;\n }\n }\n\n return null;\n}\nfunction getContainerFromFiber(fiber) {\n return fiber.tag === HostRoot ? fiber.stateNode.containerInfo : null;\n}\nfunction isFiberMounted(fiber) {\n return getNearestMountedFiber(fiber) === fiber;\n}\nfunction isMounted(component) {\n {\n var owner = ReactCurrentOwner.current;\n\n if (owner !== null && owner.tag === ClassComponent) {\n var ownerFiber = owner;\n var instance = ownerFiber.stateNode;\n\n if (!instance._warnedAboutRefsInRender) {\n error('%s is accessing isMounted inside its render() function. ' + 'render() should be a pure function of props and state. It should ' + 'never access something that requires stale data from the previous ' + 'render, such as refs. Move this logic to componentDidMount and ' + 'componentDidUpdate instead.', getComponentName(ownerFiber.type) || 'A component');\n }\n\n instance._warnedAboutRefsInRender = true;\n }\n }\n\n var fiber = get(component);\n\n if (!fiber) {\n return false;\n }\n\n return getNearestMountedFiber(fiber) === fiber;\n}\n\nfunction assertIsMounted(fiber) {\n if (!(getNearestMountedFiber(fiber) === fiber)) {\n {\n throw Error( \"Unable to find node on an unmounted component.\" );\n }\n }\n}\n\nfunction findCurrentFiberUsingSlowPath(fiber) {\n var alternate = fiber.alternate;\n\n if (!alternate) {\n // If there is no alternate, then we only need to check if it is mounted.\n var nearestMounted = getNearestMountedFiber(fiber);\n\n if (!(nearestMounted !== null)) {\n {\n throw Error( \"Unable to find node on an unmounted component.\" );\n }\n }\n\n if (nearestMounted !== fiber) {\n return null;\n }\n\n return fiber;\n } // If we have two possible branches, we'll walk backwards up to the root\n // to see what path the root points to. On the way we may hit one of the\n // special cases and we'll deal with them.\n\n\n var a = fiber;\n var b = alternate;\n\n while (true) {\n var parentA = a.return;\n\n if (parentA === null) {\n // We're at the root.\n break;\n }\n\n var parentB = parentA.alternate;\n\n if (parentB === null) {\n // There is no alternate. This is an unusual case. Currently, it only\n // happens when a Suspense component is hidden. An extra fragment fiber\n // is inserted in between the Suspense fiber and its children. Skip\n // over this extra fragment fiber and proceed to the next parent.\n var nextParent = parentA.return;\n\n if (nextParent !== null) {\n a = b = nextParent;\n continue;\n } // If there's no parent, we're at the root.\n\n\n break;\n } // If both copies of the parent fiber point to the same child, we can\n // assume that the child is current. This happens when we bailout on low\n // priority: the bailed out fiber's child reuses the current child.\n\n\n if (parentA.child === parentB.child) {\n var child = parentA.child;\n\n while (child) {\n if (child === a) {\n // We've determined that A is the current branch.\n assertIsMounted(parentA);\n return fiber;\n }\n\n if (child === b) {\n // We've determined that B is the current branch.\n assertIsMounted(parentA);\n return alternate;\n }\n\n child = child.sibling;\n } // We should never have an alternate for any mounting node. So the only\n // way this could possibly happen is if this was unmounted, if at all.\n\n\n {\n {\n throw Error( \"Unable to find node on an unmounted component.\" );\n }\n }\n }\n\n if (a.return !== b.return) {\n // The return pointer of A and the return pointer of B point to different\n // fibers. We assume that return pointers never criss-cross, so A must\n // belong to the child set of A.return, and B must belong to the child\n // set of B.return.\n a = parentA;\n b = parentB;\n } else {\n // The return pointers point to the same fiber. We'll have to use the\n // default, slow path: scan the child sets of each parent alternate to see\n // which child belongs to which set.\n //\n // Search parent A's child set\n var didFindChild = false;\n var _child = parentA.child;\n\n while (_child) {\n if (_child === a) {\n didFindChild = true;\n a = parentA;\n b = parentB;\n break;\n }\n\n if (_child === b) {\n didFindChild = true;\n b = parentA;\n a = parentB;\n break;\n }\n\n _child = _child.sibling;\n }\n\n if (!didFindChild) {\n // Search parent B's child set\n _child = parentB.child;\n\n while (_child) {\n if (_child === a) {\n didFindChild = true;\n a = parentB;\n b = parentA;\n break;\n }\n\n if (_child === b) {\n didFindChild = true;\n b = parentB;\n a = parentA;\n break;\n }\n\n _child = _child.sibling;\n }\n\n if (!didFindChild) {\n {\n throw Error( \"Child was not found in either parent set. This indicates a bug in React related to the return pointer. Please file an issue.\" );\n }\n }\n }\n }\n\n if (!(a.alternate === b)) {\n {\n throw Error( \"Return fibers should always be each others' alternates. This error is likely caused by a bug in React. Please file an issue.\" );\n }\n }\n } // If the root is not a host container, we're in a disconnected tree. I.e.\n // unmounted.\n\n\n if (!(a.tag === HostRoot)) {\n {\n throw Error( \"Unable to find node on an unmounted component.\" );\n }\n }\n\n if (a.stateNode.current === a) {\n // We've determined that A is the current branch.\n return fiber;\n } // Otherwise B has to be current branch.\n\n\n return alternate;\n}\nfunction findCurrentHostFiber(parent) {\n var currentParent = findCurrentFiberUsingSlowPath(parent);\n\n if (!currentParent) {\n return null;\n } // Next we'll drill down this component to find the first HostComponent/Text.\n\n\n var node = currentParent;\n\n while (true) {\n if (node.tag === HostComponent || node.tag === HostText) {\n return node;\n } else if (node.child) {\n node.child.return = node;\n node = node.child;\n continue;\n }\n\n if (node === currentParent) {\n return null;\n }\n\n while (!node.sibling) {\n if (!node.return || node.return === currentParent) {\n return null;\n }\n\n node = node.return;\n }\n\n node.sibling.return = node.return;\n node = node.sibling;\n } // Flow needs the return null here, but ESLint complains about it.\n // eslint-disable-next-line no-unreachable\n\n\n return null;\n}\nfunction findCurrentHostFiberWithNoPortals(parent) {\n var currentParent = findCurrentFiberUsingSlowPath(parent);\n\n if (!currentParent) {\n return null;\n } // Next we'll drill down this component to find the first HostComponent/Text.\n\n\n var node = currentParent;\n\n while (true) {\n if (node.tag === HostComponent || node.tag === HostText || enableFundamentalAPI ) {\n return node;\n } else if (node.child && node.tag !== HostPortal) {\n node.child.return = node;\n node = node.child;\n continue;\n }\n\n if (node === currentParent) {\n return null;\n }\n\n while (!node.sibling) {\n if (!node.return || node.return === currentParent) {\n return null;\n }\n\n node = node.return;\n }\n\n node.sibling.return = node.return;\n node = node.sibling;\n } // Flow needs the return null here, but ESLint complains about it.\n // eslint-disable-next-line no-unreachable\n\n\n return null;\n}\n\n/**\n * Accumulates items that must not be null or undefined into the first one. This\n * is used to conserve memory by avoiding array allocations, and thus sacrifices\n * API cleanness. Since `current` can be null before being passed in and not\n * null after this function, make sure to assign it back to `current`:\n *\n * `a = accumulateInto(a, b);`\n *\n * This API should be sparingly used. Try `accumulate` for something cleaner.\n *\n * @return {*|array<*>} An accumulation of items.\n */\n\nfunction accumulateInto(current, next) {\n if (!(next != null)) {\n {\n throw Error( \"accumulateInto(...): Accumulated items must not be null or undefined.\" );\n }\n }\n\n if (current == null) {\n return next;\n } // Both are not empty. Warning: Never call x.concat(y) when you are not\n // certain that x is an Array (x could be a string with concat method).\n\n\n if (Array.isArray(current)) {\n if (Array.isArray(next)) {\n current.push.apply(current, next);\n return current;\n }\n\n current.push(next);\n return current;\n }\n\n if (Array.isArray(next)) {\n // A bit too dangerous to mutate `next`.\n return [current].concat(next);\n }\n\n return [current, next];\n}\n\n/**\n * @param {array} arr an \"accumulation\" of items which is either an Array or\n * a single item. Useful when paired with the `accumulate` module. This is a\n * simple utility that allows us to reason about a collection of items, but\n * handling the case when there is exactly one item (and we do not need to\n * allocate an array).\n * @param {function} cb Callback invoked with each element or a collection.\n * @param {?} [scope] Scope used as `this` in a callback.\n */\nfunction forEachAccumulated(arr, cb, scope) {\n if (Array.isArray(arr)) {\n arr.forEach(cb, scope);\n } else if (arr) {\n cb.call(scope, arr);\n }\n}\n\n/**\n * Internal queue of events that have accumulated their dispatches and are\n * waiting to have their dispatches executed.\n */\n\nvar eventQueue = null;\n/**\n * Dispatches an event and releases it back into the pool, unless persistent.\n *\n * @param {?object} event Synthetic event to be dispatched.\n * @private\n */\n\nvar executeDispatchesAndRelease = function (event) {\n if (event) {\n executeDispatchesInOrder(event);\n\n if (!event.isPersistent()) {\n event.constructor.release(event);\n }\n }\n};\n\nvar executeDispatchesAndReleaseTopLevel = function (e) {\n return executeDispatchesAndRelease(e);\n};\n\nfunction runEventsInBatch(events) {\n if (events !== null) {\n eventQueue = accumulateInto(eventQueue, events);\n } // Set `eventQueue` to null before processing it so that we can tell if more\n // events get enqueued while processing.\n\n\n var processingEventQueue = eventQueue;\n eventQueue = null;\n\n if (!processingEventQueue) {\n return;\n }\n\n forEachAccumulated(processingEventQueue, executeDispatchesAndReleaseTopLevel);\n\n if (!!eventQueue) {\n {\n throw Error( \"processEventQueue(): Additional events were enqueued while processing an event queue. Support for this has not yet been implemented.\" );\n }\n } // This would be a good time to rethrow if any of the event handlers threw.\n\n\n rethrowCaughtError();\n}\n\n/**\n * Gets the target node from a native browser event by accounting for\n * inconsistencies in browser DOM APIs.\n *\n * @param {object} nativeEvent Native browser event.\n * @return {DOMEventTarget} Target node.\n */\n\nfunction getEventTarget(nativeEvent) {\n // Fallback to nativeEvent.srcElement for IE9\n // https://github.com/facebook/react/issues/12506\n var target = nativeEvent.target || nativeEvent.srcElement || window; // Normalize SVG <use> element events #4963\n\n if (target.correspondingUseElement) {\n target = target.correspondingUseElement;\n } // Safari may fire events on text nodes (Node.TEXT_NODE is 3).\n // @see http://www.quirksmode.org/js/events_properties.html\n\n\n return target.nodeType === TEXT_NODE ? target.parentNode : target;\n}\n\n/**\n * Checks if an event is supported in the current execution environment.\n *\n * NOTE: This will not work correctly for non-generic events such as `change`,\n * `reset`, `load`, `error`, and `select`.\n *\n * Borrows from Modernizr.\n *\n * @param {string} eventNameSuffix Event name, e.g. \"click\".\n * @return {boolean} True if the event is supported.\n * @internal\n * @license Modernizr 3.0.0pre (Custom Build) | MIT\n */\n\nfunction isEventSupported(eventNameSuffix) {\n if (!canUseDOM) {\n return false;\n }\n\n var eventName = 'on' + eventNameSuffix;\n var isSupported = eventName in document;\n\n if (!isSupported) {\n var element = document.createElement('div');\n element.setAttribute(eventName, 'return;');\n isSupported = typeof element[eventName] === 'function';\n }\n\n return isSupported;\n}\n\n/**\n * Summary of `DOMEventPluginSystem` event handling:\n *\n * - Top-level delegation is used to trap most native browser events. This\n * may only occur in the main thread and is the responsibility of\n * ReactDOMEventListener, which is injected and can therefore support\n * pluggable event sources. This is the only work that occurs in the main\n * thread.\n *\n * - We normalize and de-duplicate events to account for browser quirks. This\n * may be done in the worker thread.\n *\n * - Forward these native events (with the associated top-level type used to\n * trap it) to `EventPluginRegistry`, which in turn will ask plugins if they want\n * to extract any synthetic events.\n *\n * - The `EventPluginRegistry` will then process each event by annotating them with\n * \"dispatches\", a sequence of listeners and IDs that care about that event.\n *\n * - The `EventPluginRegistry` then dispatches the events.\n *\n * Overview of React and the event system:\n *\n * +------------+ .\n * | DOM | .\n * +------------+ .\n * | .\n * v .\n * +------------+ .\n * | ReactEvent | .\n * | Listener | .\n * +------------+ . +-----------+\n * | . +--------+|SimpleEvent|\n * | . | |Plugin |\n * +-----|------+ . v +-----------+\n * | | | . +--------------+ +------------+\n * | +-----------.--->|PluginRegistry| | Event |\n * | | . | | +-----------+ | Propagators|\n * | ReactEvent | . | | |TapEvent | |------------|\n * | Emitter | . | |<---+|Plugin | |other plugin|\n * | | . | | +-----------+ | utilities |\n * | +-----------.--->| | +------------+\n * | | | . +--------------+\n * +-----|------+ . ^ +-----------+\n * | . | |Enter/Leave|\n * + . +-------+|Plugin |\n * +-------------+ . +-----------+\n * | application | .\n * |-------------| .\n * | | .\n * | | .\n * +-------------+ .\n * .\n * React Core . General Purpose Event Plugin System\n */\n\nvar CALLBACK_BOOKKEEPING_POOL_SIZE = 10;\nvar callbackBookkeepingPool = [];\n\nfunction releaseTopLevelCallbackBookKeeping(instance) {\n instance.topLevelType = null;\n instance.nativeEvent = null;\n instance.targetInst = null;\n instance.ancestors.length = 0;\n\n if (callbackBookkeepingPool.length < CALLBACK_BOOKKEEPING_POOL_SIZE) {\n callbackBookkeepingPool.push(instance);\n }\n} // Used to store ancestor hierarchy in top level callback\n\n\nfunction getTopLevelCallbackBookKeeping(topLevelType, nativeEvent, targetInst, eventSystemFlags) {\n if (callbackBookkeepingPool.length) {\n var instance = callbackBookkeepingPool.pop();\n instance.topLevelType = topLevelType;\n instance.eventSystemFlags = eventSystemFlags;\n instance.nativeEvent = nativeEvent;\n instance.targetInst = targetInst;\n return instance;\n }\n\n return {\n topLevelType: topLevelType,\n eventSystemFlags: eventSystemFlags,\n nativeEvent: nativeEvent,\n targetInst: targetInst,\n ancestors: []\n };\n}\n/**\n * Find the deepest React component completely containing the root of the\n * passed-in instance (for use when entire React trees are nested within each\n * other). If React trees are not nested, returns null.\n */\n\n\nfunction findRootContainerNode(inst) {\n if (inst.tag === HostRoot) {\n return inst.stateNode.containerInfo;\n } // TODO: It may be a good idea to cache this to prevent unnecessary DOM\n // traversal, but caching is difficult to do correctly without using a\n // mutation observer to listen for all DOM changes.\n\n\n while (inst.return) {\n inst = inst.return;\n }\n\n if (inst.tag !== HostRoot) {\n // This can happen if we're in a detached tree.\n return null;\n }\n\n return inst.stateNode.containerInfo;\n}\n/**\n * Allows registered plugins an opportunity to extract events from top-level\n * native browser events.\n *\n * @return {*} An accumulation of synthetic events.\n * @internal\n */\n\n\nfunction extractPluginEvents(topLevelType, targetInst, nativeEvent, nativeEventTarget, eventSystemFlags) {\n var events = null;\n\n for (var i = 0; i < plugins.length; i++) {\n // Not every plugin in the ordering may be loaded at runtime.\n var possiblePlugin = plugins[i];\n\n if (possiblePlugin) {\n var extractedEvents = possiblePlugin.extractEvents(topLevelType, targetInst, nativeEvent, nativeEventTarget, eventSystemFlags);\n\n if (extractedEvents) {\n events = accumulateInto(events, extractedEvents);\n }\n }\n }\n\n return events;\n}\n\nfunction runExtractedPluginEventsInBatch(topLevelType, targetInst, nativeEvent, nativeEventTarget, eventSystemFlags) {\n var events = extractPluginEvents(topLevelType, targetInst, nativeEvent, nativeEventTarget, eventSystemFlags);\n runEventsInBatch(events);\n}\n\nfunction handleTopLevel(bookKeeping) {\n var targetInst = bookKeeping.targetInst; // Loop through the hierarchy, in case there's any nested components.\n // It's important that we build the array of ancestors before calling any\n // event handlers, because event handlers can modify the DOM, leading to\n // inconsistencies with ReactMount's node cache. See #1105.\n\n var ancestor = targetInst;\n\n do {\n if (!ancestor) {\n var ancestors = bookKeeping.ancestors;\n ancestors.push(ancestor);\n break;\n }\n\n var root = findRootContainerNode(ancestor);\n\n if (!root) {\n break;\n }\n\n var tag = ancestor.tag;\n\n if (tag === HostComponent || tag === HostText) {\n bookKeeping.ancestors.push(ancestor);\n }\n\n ancestor = getClosestInstanceFromNode(root);\n } while (ancestor);\n\n for (var i = 0; i < bookKeeping.ancestors.length; i++) {\n targetInst = bookKeeping.ancestors[i];\n var eventTarget = getEventTarget(bookKeeping.nativeEvent);\n var topLevelType = bookKeeping.topLevelType;\n var nativeEvent = bookKeeping.nativeEvent;\n var eventSystemFlags = bookKeeping.eventSystemFlags; // If this is the first ancestor, we mark it on the system flags\n\n if (i === 0) {\n eventSystemFlags |= IS_FIRST_ANCESTOR;\n }\n\n runExtractedPluginEventsInBatch(topLevelType, targetInst, nativeEvent, eventTarget, eventSystemFlags);\n }\n}\n\nfunction dispatchEventForLegacyPluginEventSystem(topLevelType, eventSystemFlags, nativeEvent, targetInst) {\n var bookKeeping = getTopLevelCallbackBookKeeping(topLevelType, nativeEvent, targetInst, eventSystemFlags);\n\n try {\n // Event queue being processed in the same cycle allows\n // `preventDefault`.\n batchedEventUpdates(handleTopLevel, bookKeeping);\n } finally {\n releaseTopLevelCallbackBookKeeping(bookKeeping);\n }\n}\n/**\n * We listen for bubbled touch events on the document object.\n *\n * Firefox v8.01 (and possibly others) exhibited strange behavior when\n * mounting `onmousemove` events at some node that was not the document\n * element. The symptoms were that if your mouse is not moving over something\n * contained within that mount point (for example on the background) the\n * top-level listeners for `onmousemove` won't be called. However, if you\n * register the `mousemove` on the document object, then it will of course\n * catch all `mousemove`s. This along with iOS quirks, justifies restricting\n * top-level listeners to the document object only, at least for these\n * movement types of events and possibly all events.\n *\n * @see http://www.quirksmode.org/blog/archives/2010/09/click_event_del.html\n *\n * Also, `keyup`/`keypress`/`keydown` do not bubble to the window on IE, but\n * they bubble to document.\n *\n * @param {string} registrationName Name of listener (e.g. `onClick`).\n * @param {object} mountAt Container where to mount the listener\n */\n\nfunction legacyListenToEvent(registrationName, mountAt) {\n var listenerMap = getListenerMapForElement(mountAt);\n var dependencies = registrationNameDependencies[registrationName];\n\n for (var i = 0; i < dependencies.length; i++) {\n var dependency = dependencies[i];\n legacyListenToTopLevelEvent(dependency, mountAt, listenerMap);\n }\n}\nfunction legacyListenToTopLevelEvent(topLevelType, mountAt, listenerMap) {\n if (!listenerMap.has(topLevelType)) {\n switch (topLevelType) {\n case TOP_SCROLL:\n trapCapturedEvent(TOP_SCROLL, mountAt);\n break;\n\n case TOP_FOCUS:\n case TOP_BLUR:\n trapCapturedEvent(TOP_FOCUS, mountAt);\n trapCapturedEvent(TOP_BLUR, mountAt); // We set the flag for a single dependency later in this function,\n // but this ensures we mark both as attached rather than just one.\n\n listenerMap.set(TOP_BLUR, null);\n listenerMap.set(TOP_FOCUS, null);\n break;\n\n case TOP_CANCEL:\n case TOP_CLOSE:\n if (isEventSupported(getRawEventName(topLevelType))) {\n trapCapturedEvent(topLevelType, mountAt);\n }\n\n break;\n\n case TOP_INVALID:\n case TOP_SUBMIT:\n case TOP_RESET:\n // We listen to them on the target DOM elements.\n // Some of them bubble so we don't want them to fire twice.\n break;\n\n default:\n // By default, listen on the top level to all non-media events.\n // Media events don't bubble so adding the listener wouldn't do anything.\n var isMediaEvent = mediaEventTypes.indexOf(topLevelType) !== -1;\n\n if (!isMediaEvent) {\n trapBubbledEvent(topLevelType, mountAt);\n }\n\n break;\n }\n\n listenerMap.set(topLevelType, null);\n }\n}\nfunction isListeningToAllDependencies(registrationName, mountAt) {\n var listenerMap = getListenerMapForElement(mountAt);\n var dependencies = registrationNameDependencies[registrationName];\n\n for (var i = 0; i < dependencies.length; i++) {\n var dependency = dependencies[i];\n\n if (!listenerMap.has(dependency)) {\n return false;\n }\n }\n\n return true;\n}\n\nvar attemptUserBlockingHydration;\nfunction setAttemptUserBlockingHydration(fn) {\n attemptUserBlockingHydration = fn;\n}\nvar attemptContinuousHydration;\nfunction setAttemptContinuousHydration(fn) {\n attemptContinuousHydration = fn;\n}\nvar attemptHydrationAtCurrentPriority;\nfunction setAttemptHydrationAtCurrentPriority(fn) {\n attemptHydrationAtCurrentPriority = fn;\n} // TODO: Upgrade this definition once we're on a newer version of Flow that\nvar hasScheduledReplayAttempt = false; // The queue of discrete events to be replayed.\n\nvar queuedDiscreteEvents = []; // Indicates if any continuous event targets are non-null for early bailout.\n// if the last target was dehydrated.\n\nvar queuedFocus = null;\nvar queuedDrag = null;\nvar queuedMouse = null; // For pointer events there can be one latest event per pointerId.\n\nvar queuedPointers = new Map();\nvar queuedPointerCaptures = new Map(); // We could consider replaying selectionchange and touchmoves too.\n\nvar queuedExplicitHydrationTargets = [];\nfunction hasQueuedDiscreteEvents() {\n return queuedDiscreteEvents.length > 0;\n}\nvar discreteReplayableEvents = [TOP_MOUSE_DOWN, TOP_MOUSE_UP, TOP_TOUCH_CANCEL, TOP_TOUCH_END, TOP_TOUCH_START, TOP_AUX_CLICK, TOP_DOUBLE_CLICK, TOP_POINTER_CANCEL, TOP_POINTER_DOWN, TOP_POINTER_UP, TOP_DRAG_END, TOP_DRAG_START, TOP_DROP, TOP_COMPOSITION_END, TOP_COMPOSITION_START, TOP_KEY_DOWN, TOP_KEY_PRESS, TOP_KEY_UP, TOP_INPUT, TOP_TEXT_INPUT, TOP_CLOSE, TOP_CANCEL, TOP_COPY, TOP_CUT, TOP_PASTE, TOP_CLICK, TOP_CHANGE, TOP_CONTEXT_MENU, TOP_RESET, TOP_SUBMIT];\nvar continuousReplayableEvents = [TOP_FOCUS, TOP_BLUR, TOP_DRAG_ENTER, TOP_DRAG_LEAVE, TOP_MOUSE_OVER, TOP_MOUSE_OUT, TOP_POINTER_OVER, TOP_POINTER_OUT, TOP_GOT_POINTER_CAPTURE, TOP_LOST_POINTER_CAPTURE];\nfunction isReplayableDiscreteEvent(eventType) {\n return discreteReplayableEvents.indexOf(eventType) > -1;\n}\n\nfunction trapReplayableEventForDocument(topLevelType, document, listenerMap) {\n legacyListenToTopLevelEvent(topLevelType, document, listenerMap);\n}\n\nfunction eagerlyTrapReplayableEvents(container, document) {\n var listenerMapForDoc = getListenerMapForElement(document); // Discrete\n\n discreteReplayableEvents.forEach(function (topLevelType) {\n trapReplayableEventForDocument(topLevelType, document, listenerMapForDoc);\n }); // Continuous\n\n continuousReplayableEvents.forEach(function (topLevelType) {\n trapReplayableEventForDocument(topLevelType, document, listenerMapForDoc);\n });\n}\n\nfunction createQueuedReplayableEvent(blockedOn, topLevelType, eventSystemFlags, container, nativeEvent) {\n return {\n blockedOn: blockedOn,\n topLevelType: topLevelType,\n eventSystemFlags: eventSystemFlags | IS_REPLAYED,\n nativeEvent: nativeEvent,\n container: container\n };\n}\n\nfunction queueDiscreteEvent(blockedOn, topLevelType, eventSystemFlags, container, nativeEvent) {\n var queuedEvent = createQueuedReplayableEvent(blockedOn, topLevelType, eventSystemFlags, container, nativeEvent);\n queuedDiscreteEvents.push(queuedEvent);\n} // Resets the replaying for this type of continuous event to no event.\n\nfunction clearIfContinuousEvent(topLevelType, nativeEvent) {\n switch (topLevelType) {\n case TOP_FOCUS:\n case TOP_BLUR:\n queuedFocus = null;\n break;\n\n case TOP_DRAG_ENTER:\n case TOP_DRAG_LEAVE:\n queuedDrag = null;\n break;\n\n case TOP_MOUSE_OVER:\n case TOP_MOUSE_OUT:\n queuedMouse = null;\n break;\n\n case TOP_POINTER_OVER:\n case TOP_POINTER_OUT:\n {\n var pointerId = nativeEvent.pointerId;\n queuedPointers.delete(pointerId);\n break;\n }\n\n case TOP_GOT_POINTER_CAPTURE:\n case TOP_LOST_POINTER_CAPTURE:\n {\n var _pointerId = nativeEvent.pointerId;\n queuedPointerCaptures.delete(_pointerId);\n break;\n }\n }\n}\n\nfunction accumulateOrCreateContinuousQueuedReplayableEvent(existingQueuedEvent, blockedOn, topLevelType, eventSystemFlags, container, nativeEvent) {\n if (existingQueuedEvent === null || existingQueuedEvent.nativeEvent !== nativeEvent) {\n var queuedEvent = createQueuedReplayableEvent(blockedOn, topLevelType, eventSystemFlags, container, nativeEvent);\n\n if (blockedOn !== null) {\n var _fiber2 = getInstanceFromNode$1(blockedOn);\n\n if (_fiber2 !== null) {\n // Attempt to increase the priority of this target.\n attemptContinuousHydration(_fiber2);\n }\n }\n\n return queuedEvent;\n } // If we have already queued this exact event, then it's because\n // the different event systems have different DOM event listeners.\n // We can accumulate the flags and store a single event to be\n // replayed.\n\n\n existingQueuedEvent.eventSystemFlags |= eventSystemFlags;\n return existingQueuedEvent;\n}\n\nfunction queueIfContinuousEvent(blockedOn, topLevelType, eventSystemFlags, container, nativeEvent) {\n // These set relatedTarget to null because the replayed event will be treated as if we\n // moved from outside the window (no target) onto the target once it hydrates.\n // Instead of mutating we could clone the event.\n switch (topLevelType) {\n case TOP_FOCUS:\n {\n var focusEvent = nativeEvent;\n queuedFocus = accumulateOrCreateContinuousQueuedReplayableEvent(queuedFocus, blockedOn, topLevelType, eventSystemFlags, container, focusEvent);\n return true;\n }\n\n case TOP_DRAG_ENTER:\n {\n var dragEvent = nativeEvent;\n queuedDrag = accumulateOrCreateContinuousQueuedReplayableEvent(queuedDrag, blockedOn, topLevelType, eventSystemFlags, container, dragEvent);\n return true;\n }\n\n case TOP_MOUSE_OVER:\n {\n var mouseEvent = nativeEvent;\n queuedMouse = accumulateOrCreateContinuousQueuedReplayableEvent(queuedMouse, blockedOn, topLevelType, eventSystemFlags, container, mouseEvent);\n return true;\n }\n\n case TOP_POINTER_OVER:\n {\n var pointerEvent = nativeEvent;\n var pointerId = pointerEvent.pointerId;\n queuedPointers.set(pointerId, accumulateOrCreateContinuousQueuedReplayableEvent(queuedPointers.get(pointerId) || null, blockedOn, topLevelType, eventSystemFlags, container, pointerEvent));\n return true;\n }\n\n case TOP_GOT_POINTER_CAPTURE:\n {\n var _pointerEvent = nativeEvent;\n var _pointerId2 = _pointerEvent.pointerId;\n queuedPointerCaptures.set(_pointerId2, accumulateOrCreateContinuousQueuedReplayableEvent(queuedPointerCaptures.get(_pointerId2) || null, blockedOn, topLevelType, eventSystemFlags, container, _pointerEvent));\n return true;\n }\n }\n\n return false;\n} // Check if this target is unblocked. Returns true if it's unblocked.\n\nfunction attemptExplicitHydrationTarget(queuedTarget) {\n // TODO: This function shares a lot of logic with attemptToDispatchEvent.\n // Try to unify them. It's a bit tricky since it would require two return\n // values.\n var targetInst = getClosestInstanceFromNode(queuedTarget.target);\n\n if (targetInst !== null) {\n var nearestMounted = getNearestMountedFiber(targetInst);\n\n if (nearestMounted !== null) {\n var tag = nearestMounted.tag;\n\n if (tag === SuspenseComponent) {\n var instance = getSuspenseInstanceFromFiber(nearestMounted);\n\n if (instance !== null) {\n // We're blocked on hydrating this boundary.\n // Increase its priority.\n queuedTarget.blockedOn = instance;\n Scheduler.unstable_runWithPriority(queuedTarget.priority, function () {\n attemptHydrationAtCurrentPriority(nearestMounted);\n });\n return;\n }\n } else if (tag === HostRoot) {\n var root = nearestMounted.stateNode;\n\n if (root.hydrate) {\n queuedTarget.blockedOn = getContainerFromFiber(nearestMounted); // We don't currently have a way to increase the priority of\n // a root other than sync.\n\n return;\n }\n }\n }\n }\n\n queuedTarget.blockedOn = null;\n}\n\nfunction attemptReplayContinuousQueuedEvent(queuedEvent) {\n if (queuedEvent.blockedOn !== null) {\n return false;\n }\n\n var nextBlockedOn = attemptToDispatchEvent(queuedEvent.topLevelType, queuedEvent.eventSystemFlags, queuedEvent.container, queuedEvent.nativeEvent);\n\n if (nextBlockedOn !== null) {\n // We're still blocked. Try again later.\n var _fiber3 = getInstanceFromNode$1(nextBlockedOn);\n\n if (_fiber3 !== null) {\n attemptContinuousHydration(_fiber3);\n }\n\n queuedEvent.blockedOn = nextBlockedOn;\n return false;\n }\n\n return true;\n}\n\nfunction attemptReplayContinuousQueuedEventInMap(queuedEvent, key, map) {\n if (attemptReplayContinuousQueuedEvent(queuedEvent)) {\n map.delete(key);\n }\n}\n\nfunction replayUnblockedEvents() {\n hasScheduledReplayAttempt = false; // First replay discrete events.\n\n while (queuedDiscreteEvents.length > 0) {\n var nextDiscreteEvent = queuedDiscreteEvents[0];\n\n if (nextDiscreteEvent.blockedOn !== null) {\n // We're still blocked.\n // Increase the priority of this boundary to unblock\n // the next discrete event.\n var _fiber4 = getInstanceFromNode$1(nextDiscreteEvent.blockedOn);\n\n if (_fiber4 !== null) {\n attemptUserBlockingHydration(_fiber4);\n }\n\n break;\n }\n\n var nextBlockedOn = attemptToDispatchEvent(nextDiscreteEvent.topLevelType, nextDiscreteEvent.eventSystemFlags, nextDiscreteEvent.container, nextDiscreteEvent.nativeEvent);\n\n if (nextBlockedOn !== null) {\n // We're still blocked. Try again later.\n nextDiscreteEvent.blockedOn = nextBlockedOn;\n } else {\n // We've successfully replayed the first event. Let's try the next one.\n queuedDiscreteEvents.shift();\n }\n } // Next replay any continuous events.\n\n\n if (queuedFocus !== null && attemptReplayContinuousQueuedEvent(queuedFocus)) {\n queuedFocus = null;\n }\n\n if (queuedDrag !== null && attemptReplayContinuousQueuedEvent(queuedDrag)) {\n queuedDrag = null;\n }\n\n if (queuedMouse !== null && attemptReplayContinuousQueuedEvent(queuedMouse)) {\n queuedMouse = null;\n }\n\n queuedPointers.forEach(attemptReplayContinuousQueuedEventInMap);\n queuedPointerCaptures.forEach(attemptReplayContinuousQueuedEventInMap);\n}\n\nfunction scheduleCallbackIfUnblocked(queuedEvent, unblocked) {\n if (queuedEvent.blockedOn === unblocked) {\n queuedEvent.blockedOn = null;\n\n if (!hasScheduledReplayAttempt) {\n hasScheduledReplayAttempt = true; // Schedule a callback to attempt replaying as many events as are\n // now unblocked. This first might not actually be unblocked yet.\n // We could check it early to avoid scheduling an unnecessary callback.\n\n Scheduler.unstable_scheduleCallback(Scheduler.unstable_NormalPriority, replayUnblockedEvents);\n }\n }\n}\n\nfunction retryIfBlockedOn(unblocked) {\n // Mark anything that was blocked on this as no longer blocked\n // and eligible for a replay.\n if (queuedDiscreteEvents.length > 0) {\n scheduleCallbackIfUnblocked(queuedDiscreteEvents[0], unblocked); // This is a exponential search for each boundary that commits. I think it's\n // worth it because we expect very few discrete events to queue up and once\n // we are actually fully unblocked it will be fast to replay them.\n\n for (var i = 1; i < queuedDiscreteEvents.length; i++) {\n var queuedEvent = queuedDiscreteEvents[i];\n\n if (queuedEvent.blockedOn === unblocked) {\n queuedEvent.blockedOn = null;\n }\n }\n }\n\n if (queuedFocus !== null) {\n scheduleCallbackIfUnblocked(queuedFocus, unblocked);\n }\n\n if (queuedDrag !== null) {\n scheduleCallbackIfUnblocked(queuedDrag, unblocked);\n }\n\n if (queuedMouse !== null) {\n scheduleCallbackIfUnblocked(queuedMouse, unblocked);\n }\n\n var unblock = function (queuedEvent) {\n return scheduleCallbackIfUnblocked(queuedEvent, unblocked);\n };\n\n queuedPointers.forEach(unblock);\n queuedPointerCaptures.forEach(unblock);\n\n for (var _i = 0; _i < queuedExplicitHydrationTargets.length; _i++) {\n var queuedTarget = queuedExplicitHydrationTargets[_i];\n\n if (queuedTarget.blockedOn === unblocked) {\n queuedTarget.blockedOn = null;\n }\n }\n\n while (queuedExplicitHydrationTargets.length > 0) {\n var nextExplicitTarget = queuedExplicitHydrationTargets[0];\n\n if (nextExplicitTarget.blockedOn !== null) {\n // We're still blocked.\n break;\n } else {\n attemptExplicitHydrationTarget(nextExplicitTarget);\n\n if (nextExplicitTarget.blockedOn === null) {\n // We're unblocked.\n queuedExplicitHydrationTargets.shift();\n }\n }\n }\n}\n\nfunction addEventBubbleListener(element, eventType, listener) {\n element.addEventListener(eventType, listener, false);\n}\nfunction addEventCaptureListener(element, eventType, listener) {\n element.addEventListener(eventType, listener, true);\n}\n\n// do it in two places, which duplicates logic\n// and increases the bundle size, we do it all\n// here once. If we remove or refactor the\n// SimpleEventPlugin, we should also remove or\n// update the below line.\n\nvar simpleEventPluginEventTypes = {};\nvar topLevelEventsToDispatchConfig = new Map();\nvar eventPriorities = new Map(); // We store most of the events in this module in pairs of two strings so we can re-use\n// the code required to apply the same logic for event prioritization and that of the\n// SimpleEventPlugin. This complicates things slightly, but the aim is to reduce code\n// duplication (for which there would be quite a bit). For the events that are not needed\n// for the SimpleEventPlugin (otherDiscreteEvents) we process them separately as an\n// array of top level events.\n// Lastly, we ignore prettier so we can keep the formatting sane.\n// prettier-ignore\n\nvar discreteEventPairsForSimpleEventPlugin = [TOP_BLUR, 'blur', TOP_CANCEL, 'cancel', TOP_CLICK, 'click', TOP_CLOSE, 'close', TOP_CONTEXT_MENU, 'contextMenu', TOP_COPY, 'copy', TOP_CUT, 'cut', TOP_AUX_CLICK, 'auxClick', TOP_DOUBLE_CLICK, 'doubleClick', TOP_DRAG_END, 'dragEnd', TOP_DRAG_START, 'dragStart', TOP_DROP, 'drop', TOP_FOCUS, 'focus', TOP_INPUT, 'input', TOP_INVALID, 'invalid', TOP_KEY_DOWN, 'keyDown', TOP_KEY_PRESS, 'keyPress', TOP_KEY_UP, 'keyUp', TOP_MOUSE_DOWN, 'mouseDown', TOP_MOUSE_UP, 'mouseUp', TOP_PASTE, 'paste', TOP_PAUSE, 'pause', TOP_PLAY, 'play', TOP_POINTER_CANCEL, 'pointerCancel', TOP_POINTER_DOWN, 'pointerDown', TOP_POINTER_UP, 'pointerUp', TOP_RATE_CHANGE, 'rateChange', TOP_RESET, 'reset', TOP_SEEKED, 'seeked', TOP_SUBMIT, 'submit', TOP_TOUCH_CANCEL, 'touchCancel', TOP_TOUCH_END, 'touchEnd', TOP_TOUCH_START, 'touchStart', TOP_VOLUME_CHANGE, 'volumeChange'];\nvar otherDiscreteEvents = [TOP_CHANGE, TOP_SELECTION_CHANGE, TOP_TEXT_INPUT, TOP_COMPOSITION_START, TOP_COMPOSITION_END, TOP_COMPOSITION_UPDATE]; // prettier-ignore\n\nvar userBlockingPairsForSimpleEventPlugin = [TOP_DRAG, 'drag', TOP_DRAG_ENTER, 'dragEnter', TOP_DRAG_EXIT, 'dragExit', TOP_DRAG_LEAVE, 'dragLeave', TOP_DRAG_OVER, 'dragOver', TOP_MOUSE_MOVE, 'mouseMove', TOP_MOUSE_OUT, 'mouseOut', TOP_MOUSE_OVER, 'mouseOver', TOP_POINTER_MOVE, 'pointerMove', TOP_POINTER_OUT, 'pointerOut', TOP_POINTER_OVER, 'pointerOver', TOP_SCROLL, 'scroll', TOP_TOGGLE, 'toggle', TOP_TOUCH_MOVE, 'touchMove', TOP_WHEEL, 'wheel']; // prettier-ignore\n\nvar continuousPairsForSimpleEventPlugin = [TOP_ABORT, 'abort', TOP_ANIMATION_END, 'animationEnd', TOP_ANIMATION_ITERATION, 'animationIteration', TOP_ANIMATION_START, 'animationStart', TOP_CAN_PLAY, 'canPlay', TOP_CAN_PLAY_THROUGH, 'canPlayThrough', TOP_DURATION_CHANGE, 'durationChange', TOP_EMPTIED, 'emptied', TOP_ENCRYPTED, 'encrypted', TOP_ENDED, 'ended', TOP_ERROR, 'error', TOP_GOT_POINTER_CAPTURE, 'gotPointerCapture', TOP_LOAD, 'load', TOP_LOADED_DATA, 'loadedData', TOP_LOADED_METADATA, 'loadedMetadata', TOP_LOAD_START, 'loadStart', TOP_LOST_POINTER_CAPTURE, 'lostPointerCapture', TOP_PLAYING, 'playing', TOP_PROGRESS, 'progress', TOP_SEEKING, 'seeking', TOP_STALLED, 'stalled', TOP_SUSPEND, 'suspend', TOP_TIME_UPDATE, 'timeUpdate', TOP_TRANSITION_END, 'transitionEnd', TOP_WAITING, 'waiting'];\n/**\n * Turns\n * ['abort', ...]\n * into\n * eventTypes = {\n * 'abort': {\n * phasedRegistrationNames: {\n * bubbled: 'onAbort',\n * captured: 'onAbortCapture',\n * },\n * dependencies: [TOP_ABORT],\n * },\n * ...\n * };\n * topLevelEventsToDispatchConfig = new Map([\n * [TOP_ABORT, { sameConfig }],\n * ]);\n */\n\nfunction processSimpleEventPluginPairsByPriority(eventTypes, priority) {\n // As the event types are in pairs of two, we need to iterate\n // through in twos. The events are in pairs of two to save code\n // and improve init perf of processing this array, as it will\n // result in far fewer object allocations and property accesses\n // if we only use three arrays to process all the categories of\n // instead of tuples.\n for (var i = 0; i < eventTypes.length; i += 2) {\n var topEvent = eventTypes[i];\n var event = eventTypes[i + 1];\n var capitalizedEvent = event[0].toUpperCase() + event.slice(1);\n var onEvent = 'on' + capitalizedEvent;\n var config = {\n phasedRegistrationNames: {\n bubbled: onEvent,\n captured: onEvent + 'Capture'\n },\n dependencies: [topEvent],\n eventPriority: priority\n };\n eventPriorities.set(topEvent, priority);\n topLevelEventsToDispatchConfig.set(topEvent, config);\n simpleEventPluginEventTypes[event] = config;\n }\n}\n\nfunction processTopEventPairsByPriority(eventTypes, priority) {\n for (var i = 0; i < eventTypes.length; i++) {\n eventPriorities.set(eventTypes[i], priority);\n }\n} // SimpleEventPlugin\n\n\nprocessSimpleEventPluginPairsByPriority(discreteEventPairsForSimpleEventPlugin, DiscreteEvent);\nprocessSimpleEventPluginPairsByPriority(userBlockingPairsForSimpleEventPlugin, UserBlockingEvent);\nprocessSimpleEventPluginPairsByPriority(continuousPairsForSimpleEventPlugin, ContinuousEvent); // Not used by SimpleEventPlugin\n\nprocessTopEventPairsByPriority(otherDiscreteEvents, DiscreteEvent);\nfunction getEventPriorityForPluginSystem(topLevelType) {\n var priority = eventPriorities.get(topLevelType); // Default to a ContinuousEvent. Note: we might\n // want to warn if we can't detect the priority\n // for the event.\n\n return priority === undefined ? ContinuousEvent : priority;\n}\n\n// Intentionally not named imports because Rollup would use dynamic dispatch for\nvar UserBlockingPriority = Scheduler.unstable_UserBlockingPriority,\n runWithPriority = Scheduler.unstable_runWithPriority; // TODO: can we stop exporting these?\n\nvar _enabled = true;\nfunction setEnabled(enabled) {\n _enabled = !!enabled;\n}\nfunction isEnabled() {\n return _enabled;\n}\nfunction trapBubbledEvent(topLevelType, element) {\n trapEventForPluginEventSystem(element, topLevelType, false);\n}\nfunction trapCapturedEvent(topLevelType, element) {\n trapEventForPluginEventSystem(element, topLevelType, true);\n}\n\nfunction trapEventForPluginEventSystem(container, topLevelType, capture) {\n var listener;\n\n switch (getEventPriorityForPluginSystem(topLevelType)) {\n case DiscreteEvent:\n listener = dispatchDiscreteEvent.bind(null, topLevelType, PLUGIN_EVENT_SYSTEM, container);\n break;\n\n case UserBlockingEvent:\n listener = dispatchUserBlockingUpdate.bind(null, topLevelType, PLUGIN_EVENT_SYSTEM, container);\n break;\n\n case ContinuousEvent:\n default:\n listener = dispatchEvent.bind(null, topLevelType, PLUGIN_EVENT_SYSTEM, container);\n break;\n }\n\n var rawEventName = getRawEventName(topLevelType);\n\n if (capture) {\n addEventCaptureListener(container, rawEventName, listener);\n } else {\n addEventBubbleListener(container, rawEventName, listener);\n }\n}\n\nfunction dispatchDiscreteEvent(topLevelType, eventSystemFlags, container, nativeEvent) {\n flushDiscreteUpdatesIfNeeded(nativeEvent.timeStamp);\n discreteUpdates(dispatchEvent, topLevelType, eventSystemFlags, container, nativeEvent);\n}\n\nfunction dispatchUserBlockingUpdate(topLevelType, eventSystemFlags, container, nativeEvent) {\n runWithPriority(UserBlockingPriority, dispatchEvent.bind(null, topLevelType, eventSystemFlags, container, nativeEvent));\n}\n\nfunction dispatchEvent(topLevelType, eventSystemFlags, container, nativeEvent) {\n if (!_enabled) {\n return;\n }\n\n if (hasQueuedDiscreteEvents() && isReplayableDiscreteEvent(topLevelType)) {\n // If we already have a queue of discrete events, and this is another discrete\n // event, then we can't dispatch it regardless of its target, since they\n // need to dispatch in order.\n queueDiscreteEvent(null, // Flags that we're not actually blocked on anything as far as we know.\n topLevelType, eventSystemFlags, container, nativeEvent);\n return;\n }\n\n var blockedOn = attemptToDispatchEvent(topLevelType, eventSystemFlags, container, nativeEvent);\n\n if (blockedOn === null) {\n // We successfully dispatched this event.\n clearIfContinuousEvent(topLevelType, nativeEvent);\n return;\n }\n\n if (isReplayableDiscreteEvent(topLevelType)) {\n // This this to be replayed later once the target is available.\n queueDiscreteEvent(blockedOn, topLevelType, eventSystemFlags, container, nativeEvent);\n return;\n }\n\n if (queueIfContinuousEvent(blockedOn, topLevelType, eventSystemFlags, container, nativeEvent)) {\n return;\n } // We need to clear only if we didn't queue because\n // queueing is accummulative.\n\n\n clearIfContinuousEvent(topLevelType, nativeEvent); // This is not replayable so we'll invoke it but without a target,\n // in case the event system needs to trace it.\n\n {\n dispatchEventForLegacyPluginEventSystem(topLevelType, eventSystemFlags, nativeEvent, null);\n }\n} // Attempt dispatching an event. Returns a SuspenseInstance or Container if it's blocked.\n\nfunction attemptToDispatchEvent(topLevelType, eventSystemFlags, container, nativeEvent) {\n // TODO: Warn if _enabled is false.\n var nativeEventTarget = getEventTarget(nativeEvent);\n var targetInst = getClosestInstanceFromNode(nativeEventTarget);\n\n if (targetInst !== null) {\n var nearestMounted = getNearestMountedFiber(targetInst);\n\n if (nearestMounted === null) {\n // This tree has been unmounted already. Dispatch without a target.\n targetInst = null;\n } else {\n var tag = nearestMounted.tag;\n\n if (tag === SuspenseComponent) {\n var instance = getSuspenseInstanceFromFiber(nearestMounted);\n\n if (instance !== null) {\n // Queue the event to be replayed later. Abort dispatching since we\n // don't want this event dispatched twice through the event system.\n // TODO: If this is the first discrete event in the queue. Schedule an increased\n // priority for this boundary.\n return instance;\n } // This shouldn't happen, something went wrong but to avoid blocking\n // the whole system, dispatch the event without a target.\n // TODO: Warn.\n\n\n targetInst = null;\n } else if (tag === HostRoot) {\n var root = nearestMounted.stateNode;\n\n if (root.hydrate) {\n // If this happens during a replay something went wrong and it might block\n // the whole system.\n return getContainerFromFiber(nearestMounted);\n }\n\n targetInst = null;\n } else if (nearestMounted !== targetInst) {\n // If we get an event (ex: img onload) before committing that\n // component's mount, ignore it for now (that is, treat it as if it was an\n // event on a non-React tree). We might also consider queueing events and\n // dispatching them after the mount.\n targetInst = null;\n }\n }\n }\n\n {\n dispatchEventForLegacyPluginEventSystem(topLevelType, eventSystemFlags, nativeEvent, targetInst);\n } // We're not blocked on anything.\n\n\n return null;\n}\n\n// List derived from Gecko source code:\n// https://github.com/mozilla/gecko-dev/blob/4e638efc71/layout/style/test/property_database.js\nvar shorthandToLonghand = {\n animation: ['animationDelay', 'animationDirection', 'animationDuration', 'animationFillMode', 'animationIterationCount', 'animationName', 'animationPlayState', 'animationTimingFunction'],\n background: ['backgroundAttachment', 'backgroundClip', 'backgroundColor', 'backgroundImage', 'backgroundOrigin', 'backgroundPositionX', 'backgroundPositionY', 'backgroundRepeat', 'backgroundSize'],\n backgroundPosition: ['backgroundPositionX', 'backgroundPositionY'],\n border: ['borderBottomColor', 'borderBottomStyle', 'borderBottomWidth', 'borderImageOutset', 'borderImageRepeat', 'borderImageSlice', 'borderImageSource', 'borderImageWidth', 'borderLeftColor', 'borderLeftStyle', 'borderLeftWidth', 'borderRightColor', 'borderRightStyle', 'borderRightWidth', 'borderTopColor', 'borderTopStyle', 'borderTopWidth'],\n borderBlockEnd: ['borderBlockEndColor', 'borderBlockEndStyle', 'borderBlockEndWidth'],\n borderBlockStart: ['borderBlockStartColor', 'borderBlockStartStyle', 'borderBlockStartWidth'],\n borderBottom: ['borderBottomColor', 'borderBottomStyle', 'borderBottomWidth'],\n borderColor: ['borderBottomColor', 'borderLeftColor', 'borderRightColor', 'borderTopColor'],\n borderImage: ['borderImageOutset', 'borderImageRepeat', 'borderImageSlice', 'borderImageSource', 'borderImageWidth'],\n borderInlineEnd: ['borderInlineEndColor', 'borderInlineEndStyle', 'borderInlineEndWidth'],\n borderInlineStart: ['borderInlineStartColor', 'borderInlineStartStyle', 'borderInlineStartWidth'],\n borderLeft: ['borderLeftColor', 'borderLeftStyle', 'borderLeftWidth'],\n borderRadius: ['borderBottomLeftRadius', 'borderBottomRightRadius', 'borderTopLeftRadius', 'borderTopRightRadius'],\n borderRight: ['borderRightColor', 'borderRightStyle', 'borderRightWidth'],\n borderStyle: ['borderBottomStyle', 'borderLeftStyle', 'borderRightStyle', 'borderTopStyle'],\n borderTop: ['borderTopColor', 'borderTopStyle', 'borderTopWidth'],\n borderWidth: ['borderBottomWidth', 'borderLeftWidth', 'borderRightWidth', 'borderTopWidth'],\n columnRule: ['columnRuleColor', 'columnRuleStyle', 'columnRuleWidth'],\n columns: ['columnCount', 'columnWidth'],\n flex: ['flexBasis', 'flexGrow', 'flexShrink'],\n flexFlow: ['flexDirection', 'flexWrap'],\n font: ['fontFamily', 'fontFeatureSettings', 'fontKerning', 'fontLanguageOverride', 'fontSize', 'fontSizeAdjust', 'fontStretch', 'fontStyle', 'fontVariant', 'fontVariantAlternates', 'fontVariantCaps', 'fontVariantEastAsian', 'fontVariantLigatures', 'fontVariantNumeric', 'fontVariantPosition', 'fontWeight', 'lineHeight'],\n fontVariant: ['fontVariantAlternates', 'fontVariantCaps', 'fontVariantEastAsian', 'fontVariantLigatures', 'fontVariantNumeric', 'fontVariantPosition'],\n gap: ['columnGap', 'rowGap'],\n grid: ['gridAutoColumns', 'gridAutoFlow', 'gridAutoRows', 'gridTemplateAreas', 'gridTemplateColumns', 'gridTemplateRows'],\n gridArea: ['gridColumnEnd', 'gridColumnStart', 'gridRowEnd', 'gridRowStart'],\n gridColumn: ['gridColumnEnd', 'gridColumnStart'],\n gridColumnGap: ['columnGap'],\n gridGap: ['columnGap', 'rowGap'],\n gridRow: ['gridRowEnd', 'gridRowStart'],\n gridRowGap: ['rowGap'],\n gridTemplate: ['gridTemplateAreas', 'gridTemplateColumns', 'gridTemplateRows'],\n listStyle: ['listStyleImage', 'listStylePosition', 'listStyleType'],\n margin: ['marginBottom', 'marginLeft', 'marginRight', 'marginTop'],\n marker: ['markerEnd', 'markerMid', 'markerStart'],\n mask: ['maskClip', 'maskComposite', 'maskImage', 'maskMode', 'maskOrigin', 'maskPositionX', 'maskPositionY', 'maskRepeat', 'maskSize'],\n maskPosition: ['maskPositionX', 'maskPositionY'],\n outline: ['outlineColor', 'outlineStyle', 'outlineWidth'],\n overflow: ['overflowX', 'overflowY'],\n padding: ['paddingBottom', 'paddingLeft', 'paddingRight', 'paddingTop'],\n placeContent: ['alignContent', 'justifyContent'],\n placeItems: ['alignItems', 'justifyItems'],\n placeSelf: ['alignSelf', 'justifySelf'],\n textDecoration: ['textDecorationColor', 'textDecorationLine', 'textDecorationStyle'],\n textEmphasis: ['textEmphasisColor', 'textEmphasisStyle'],\n transition: ['transitionDelay', 'transitionDuration', 'transitionProperty', 'transitionTimingFunction'],\n wordWrap: ['overflowWrap']\n};\n\n/**\n * CSS properties which accept numbers but are not in units of \"px\".\n */\nvar isUnitlessNumber = {\n animationIterationCount: true,\n borderImageOutset: true,\n borderImageSlice: true,\n borderImageWidth: true,\n boxFlex: true,\n boxFlexGroup: true,\n boxOrdinalGroup: true,\n columnCount: true,\n columns: true,\n flex: true,\n flexGrow: true,\n flexPositive: true,\n flexShrink: true,\n flexNegative: true,\n flexOrder: true,\n gridArea: true,\n gridRow: true,\n gridRowEnd: true,\n gridRowSpan: true,\n gridRowStart: true,\n gridColumn: true,\n gridColumnEnd: true,\n gridColumnSpan: true,\n gridColumnStart: true,\n fontWeight: true,\n lineClamp: true,\n lineHeight: true,\n opacity: true,\n order: true,\n orphans: true,\n tabSize: true,\n widows: true,\n zIndex: true,\n zoom: true,\n // SVG-related properties\n fillOpacity: true,\n floodOpacity: true,\n stopOpacity: true,\n strokeDasharray: true,\n strokeDashoffset: true,\n strokeMiterlimit: true,\n strokeOpacity: true,\n strokeWidth: true\n};\n/**\n * @param {string} prefix vendor-specific prefix, eg: Webkit\n * @param {string} key style name, eg: transitionDuration\n * @return {string} style name prefixed with `prefix`, properly camelCased, eg:\n * WebkitTransitionDuration\n */\n\nfunction prefixKey(prefix, key) {\n return prefix + key.charAt(0).toUpperCase() + key.substring(1);\n}\n/**\n * Support style names that may come passed in prefixed by adding permutations\n * of vendor prefixes.\n */\n\n\nvar prefixes = ['Webkit', 'ms', 'Moz', 'O']; // Using Object.keys here, or else the vanilla for-in loop makes IE8 go into an\n// infinite loop, because it iterates over the newly added props too.\n\nObject.keys(isUnitlessNumber).forEach(function (prop) {\n prefixes.forEach(function (prefix) {\n isUnitlessNumber[prefixKey(prefix, prop)] = isUnitlessNumber[prop];\n });\n});\n\n/**\n * Convert a value into the proper css writable value. The style name `name`\n * should be logical (no hyphens), as specified\n * in `CSSProperty.isUnitlessNumber`.\n *\n * @param {string} name CSS property name such as `topMargin`.\n * @param {*} value CSS property value such as `10px`.\n * @return {string} Normalized style value with dimensions applied.\n */\n\nfunction dangerousStyleValue(name, value, isCustomProperty) {\n // Note that we've removed escapeTextForBrowser() calls here since the\n // whole string will be escaped when the attribute is injected into\n // the markup. If you provide unsafe user data here they can inject\n // arbitrary CSS which may be problematic (I couldn't repro this):\n // https://www.owasp.org/index.php/XSS_Filter_Evasion_Cheat_Sheet\n // http://www.thespanner.co.uk/2007/11/26/ultimate-xss-css-injection/\n // This is not an XSS hole but instead a potential CSS injection issue\n // which has lead to a greater discussion about how we're going to\n // trust URLs moving forward. See #2115901\n var isEmpty = value == null || typeof value === 'boolean' || value === '';\n\n if (isEmpty) {\n return '';\n }\n\n if (!isCustomProperty && typeof value === 'number' && value !== 0 && !(isUnitlessNumber.hasOwnProperty(name) && isUnitlessNumber[name])) {\n return value + 'px'; // Presumes implicit 'px' suffix for unitless numbers\n }\n\n return ('' + value).trim();\n}\n\nvar uppercasePattern = /([A-Z])/g;\nvar msPattern = /^ms-/;\n/**\n * Hyphenates a camelcased CSS property name, for example:\n *\n * > hyphenateStyleName('backgroundColor')\n * < \"background-color\"\n * > hyphenateStyleName('MozTransition')\n * < \"-moz-transition\"\n * > hyphenateStyleName('msTransition')\n * < \"-ms-transition\"\n *\n * As Modernizr suggests (http://modernizr.com/docs/#prefixed), an `ms` prefix\n * is converted to `-ms-`.\n */\n\nfunction hyphenateStyleName(name) {\n return name.replace(uppercasePattern, '-$1').toLowerCase().replace(msPattern, '-ms-');\n}\n\nvar warnValidStyle = function () {};\n\n{\n // 'msTransform' is correct, but the other prefixes should be capitalized\n var badVendoredStyleNamePattern = /^(?:webkit|moz|o)[A-Z]/;\n var msPattern$1 = /^-ms-/;\n var hyphenPattern = /-(.)/g; // style values shouldn't contain a semicolon\n\n var badStyleValueWithSemicolonPattern = /;\\s*$/;\n var warnedStyleNames = {};\n var warnedStyleValues = {};\n var warnedForNaNValue = false;\n var warnedForInfinityValue = false;\n\n var camelize = function (string) {\n return string.replace(hyphenPattern, function (_, character) {\n return character.toUpperCase();\n });\n };\n\n var warnHyphenatedStyleName = function (name) {\n if (warnedStyleNames.hasOwnProperty(name) && warnedStyleNames[name]) {\n return;\n }\n\n warnedStyleNames[name] = true;\n\n error('Unsupported style property %s. Did you mean %s?', name, // As Andi Smith suggests\n // (http://www.andismith.com/blog/2012/02/modernizr-prefixed/), an `-ms` prefix\n // is converted to lowercase `ms`.\n camelize(name.replace(msPattern$1, 'ms-')));\n };\n\n var warnBadVendoredStyleName = function (name) {\n if (warnedStyleNames.hasOwnProperty(name) && warnedStyleNames[name]) {\n return;\n }\n\n warnedStyleNames[name] = true;\n\n error('Unsupported vendor-prefixed style property %s. Did you mean %s?', name, name.charAt(0).toUpperCase() + name.slice(1));\n };\n\n var warnStyleValueWithSemicolon = function (name, value) {\n if (warnedStyleValues.hasOwnProperty(value) && warnedStyleValues[value]) {\n return;\n }\n\n warnedStyleValues[value] = true;\n\n error(\"Style property values shouldn't contain a semicolon. \" + 'Try \"%s: %s\" instead.', name, value.replace(badStyleValueWithSemicolonPattern, ''));\n };\n\n var warnStyleValueIsNaN = function (name, value) {\n if (warnedForNaNValue) {\n return;\n }\n\n warnedForNaNValue = true;\n\n error('`NaN` is an invalid value for the `%s` css style property.', name);\n };\n\n var warnStyleValueIsInfinity = function (name, value) {\n if (warnedForInfinityValue) {\n return;\n }\n\n warnedForInfinityValue = true;\n\n error('`Infinity` is an invalid value for the `%s` css style property.', name);\n };\n\n warnValidStyle = function (name, value) {\n if (name.indexOf('-') > -1) {\n warnHyphenatedStyleName(name);\n } else if (badVendoredStyleNamePattern.test(name)) {\n warnBadVendoredStyleName(name);\n } else if (badStyleValueWithSemicolonPattern.test(value)) {\n warnStyleValueWithSemicolon(name, value);\n }\n\n if (typeof value === 'number') {\n if (isNaN(value)) {\n warnStyleValueIsNaN(name, value);\n } else if (!isFinite(value)) {\n warnStyleValueIsInfinity(name, value);\n }\n }\n };\n}\n\nvar warnValidStyle$1 = warnValidStyle;\n\n/**\n * Operations for dealing with CSS properties.\n */\n\n/**\n * This creates a string that is expected to be equivalent to the style\n * attribute generated by server-side rendering. It by-passes warnings and\n * security checks so it's not safe to use this value for anything other than\n * comparison. It is only used in DEV for SSR validation.\n */\n\nfunction createDangerousStringForStyles(styles) {\n {\n var serialized = '';\n var delimiter = '';\n\n for (var styleName in styles) {\n if (!styles.hasOwnProperty(styleName)) {\n continue;\n }\n\n var styleValue = styles[styleName];\n\n if (styleValue != null) {\n var isCustomProperty = styleName.indexOf('--') === 0;\n serialized += delimiter + (isCustomProperty ? styleName : hyphenateStyleName(styleName)) + ':';\n serialized += dangerousStyleValue(styleName, styleValue, isCustomProperty);\n delimiter = ';';\n }\n }\n\n return serialized || null;\n }\n}\n/**\n * Sets the value for multiple styles on a node. If a value is specified as\n * '' (empty string), the corresponding style property will be unset.\n *\n * @param {DOMElement} node\n * @param {object} styles\n */\n\nfunction setValueForStyles(node, styles) {\n var style = node.style;\n\n for (var styleName in styles) {\n if (!styles.hasOwnProperty(styleName)) {\n continue;\n }\n\n var isCustomProperty = styleName.indexOf('--') === 0;\n\n {\n if (!isCustomProperty) {\n warnValidStyle$1(styleName, styles[styleName]);\n }\n }\n\n var styleValue = dangerousStyleValue(styleName, styles[styleName], isCustomProperty);\n\n if (styleName === 'float') {\n styleName = 'cssFloat';\n }\n\n if (isCustomProperty) {\n style.setProperty(styleName, styleValue);\n } else {\n style[styleName] = styleValue;\n }\n }\n}\n\nfunction isValueEmpty(value) {\n return value == null || typeof value === 'boolean' || value === '';\n}\n/**\n * Given {color: 'red', overflow: 'hidden'} returns {\n * color: 'color',\n * overflowX: 'overflow',\n * overflowY: 'overflow',\n * }. This can be read as \"the overflowY property was set by the overflow\n * shorthand\". That is, the values are the property that each was derived from.\n */\n\n\nfunction expandShorthandMap(styles) {\n var expanded = {};\n\n for (var key in styles) {\n var longhands = shorthandToLonghand[key] || [key];\n\n for (var i = 0; i < longhands.length; i++) {\n expanded[longhands[i]] = key;\n }\n }\n\n return expanded;\n}\n/**\n * When mixing shorthand and longhand property names, we warn during updates if\n * we expect an incorrect result to occur. In particular, we warn for:\n *\n * Updating a shorthand property (longhand gets overwritten):\n * {font: 'foo', fontVariant: 'bar'} -> {font: 'baz', fontVariant: 'bar'}\n * becomes .style.font = 'baz'\n * Removing a shorthand property (longhand gets lost too):\n * {font: 'foo', fontVariant: 'bar'} -> {fontVariant: 'bar'}\n * becomes .style.font = ''\n * Removing a longhand property (should revert to shorthand; doesn't):\n * {font: 'foo', fontVariant: 'bar'} -> {font: 'foo'}\n * becomes .style.fontVariant = ''\n */\n\n\nfunction validateShorthandPropertyCollisionInDev(styleUpdates, nextStyles) {\n {\n\n if (!nextStyles) {\n return;\n }\n\n var expandedUpdates = expandShorthandMap(styleUpdates);\n var expandedStyles = expandShorthandMap(nextStyles);\n var warnedAbout = {};\n\n for (var key in expandedUpdates) {\n var originalKey = expandedUpdates[key];\n var correctOriginalKey = expandedStyles[key];\n\n if (correctOriginalKey && originalKey !== correctOriginalKey) {\n var warningKey = originalKey + ',' + correctOriginalKey;\n\n if (warnedAbout[warningKey]) {\n continue;\n }\n\n warnedAbout[warningKey] = true;\n\n error('%s a style property during rerender (%s) when a ' + 'conflicting property is set (%s) can lead to styling bugs. To ' + \"avoid this, don't mix shorthand and non-shorthand properties \" + 'for the same value; instead, replace the shorthand with ' + 'separate values.', isValueEmpty(styleUpdates[originalKey]) ? 'Removing' : 'Updating', originalKey, correctOriginalKey);\n }\n }\n }\n}\n\n// For HTML, certain tags should omit their close tag. We keep a whitelist for\n// those special-case tags.\nvar omittedCloseTags = {\n area: true,\n base: true,\n br: true,\n col: true,\n embed: true,\n hr: true,\n img: true,\n input: true,\n keygen: true,\n link: true,\n meta: true,\n param: true,\n source: true,\n track: true,\n wbr: true // NOTE: menuitem's close tag should be omitted, but that causes problems.\n\n};\n\n// `omittedCloseTags` except that `menuitem` should still have its closing tag.\n\nvar voidElementTags = _assign({\n menuitem: true\n}, omittedCloseTags);\n\nvar HTML = '__html';\nvar ReactDebugCurrentFrame$3 = null;\n\n{\n ReactDebugCurrentFrame$3 = ReactSharedInternals.ReactDebugCurrentFrame;\n}\n\nfunction assertValidProps(tag, props) {\n if (!props) {\n return;\n } // Note the use of `==` which checks for null or undefined.\n\n\n if (voidElementTags[tag]) {\n if (!(props.children == null && props.dangerouslySetInnerHTML == null)) {\n {\n throw Error( tag + \" is a void element tag and must neither have `children` nor use `dangerouslySetInnerHTML`.\" + ( ReactDebugCurrentFrame$3.getStackAddendum() ) );\n }\n }\n }\n\n if (props.dangerouslySetInnerHTML != null) {\n if (!(props.children == null)) {\n {\n throw Error( \"Can only set one of `children` or `props.dangerouslySetInnerHTML`.\" );\n }\n }\n\n if (!(typeof props.dangerouslySetInnerHTML === 'object' && HTML in props.dangerouslySetInnerHTML)) {\n {\n throw Error( \"`props.dangerouslySetInnerHTML` must be in the form `{__html: ...}`. Please visit https://fb.me/react-invariant-dangerously-set-inner-html for more information.\" );\n }\n }\n }\n\n {\n if (!props.suppressContentEditableWarning && props.contentEditable && props.children != null) {\n error('A component is `contentEditable` and contains `children` managed by ' + 'React. It is now your responsibility to guarantee that none of ' + 'those nodes are unexpectedly modified or duplicated. This is ' + 'probably not intentional.');\n }\n }\n\n if (!(props.style == null || typeof props.style === 'object')) {\n {\n throw Error( \"The `style` prop expects a mapping from style properties to values, not a string. For example, style={{marginRight: spacing + 'em'}} when using JSX.\" + ( ReactDebugCurrentFrame$3.getStackAddendum() ) );\n }\n }\n}\n\nfunction isCustomComponent(tagName, props) {\n if (tagName.indexOf('-') === -1) {\n return typeof props.is === 'string';\n }\n\n switch (tagName) {\n // These are reserved SVG and MathML elements.\n // We don't mind this whitelist too much because we expect it to never grow.\n // The alternative is to track the namespace in a few places which is convoluted.\n // https://w3c.github.io/webcomponents/spec/custom/#custom-elements-core-concepts\n case 'annotation-xml':\n case 'color-profile':\n case 'font-face':\n case 'font-face-src':\n case 'font-face-uri':\n case 'font-face-format':\n case 'font-face-name':\n case 'missing-glyph':\n return false;\n\n default:\n return true;\n }\n}\n\n// When adding attributes to the HTML or SVG whitelist, be sure to\n// also add them to this module to ensure casing and incorrect name\n// warnings.\nvar possibleStandardNames = {\n // HTML\n accept: 'accept',\n acceptcharset: 'acceptCharset',\n 'accept-charset': 'acceptCharset',\n accesskey: 'accessKey',\n action: 'action',\n allowfullscreen: 'allowFullScreen',\n alt: 'alt',\n as: 'as',\n async: 'async',\n autocapitalize: 'autoCapitalize',\n autocomplete: 'autoComplete',\n autocorrect: 'autoCorrect',\n autofocus: 'autoFocus',\n autoplay: 'autoPlay',\n autosave: 'autoSave',\n capture: 'capture',\n cellpadding: 'cellPadding',\n cellspacing: 'cellSpacing',\n challenge: 'challenge',\n charset: 'charSet',\n checked: 'checked',\n children: 'children',\n cite: 'cite',\n class: 'className',\n classid: 'classID',\n classname: 'className',\n cols: 'cols',\n colspan: 'colSpan',\n content: 'content',\n contenteditable: 'contentEditable',\n contextmenu: 'contextMenu',\n controls: 'controls',\n controlslist: 'controlsList',\n coords: 'coords',\n crossorigin: 'crossOrigin',\n dangerouslysetinnerhtml: 'dangerouslySetInnerHTML',\n data: 'data',\n datetime: 'dateTime',\n default: 'default',\n defaultchecked: 'defaultChecked',\n defaultvalue: 'defaultValue',\n defer: 'defer',\n dir: 'dir',\n disabled: 'disabled',\n disablepictureinpicture: 'disablePictureInPicture',\n download: 'download',\n draggable: 'draggable',\n enctype: 'encType',\n for: 'htmlFor',\n form: 'form',\n formmethod: 'formMethod',\n formaction: 'formAction',\n formenctype: 'formEncType',\n formnovalidate: 'formNoValidate',\n formtarget: 'formTarget',\n frameborder: 'frameBorder',\n headers: 'headers',\n height: 'height',\n hidden: 'hidden',\n high: 'high',\n href: 'href',\n hreflang: 'hrefLang',\n htmlfor: 'htmlFor',\n httpequiv: 'httpEquiv',\n 'http-equiv': 'httpEquiv',\n icon: 'icon',\n id: 'id',\n innerhtml: 'innerHTML',\n inputmode: 'inputMode',\n integrity: 'integrity',\n is: 'is',\n itemid: 'itemID',\n itemprop: 'itemProp',\n itemref: 'itemRef',\n itemscope: 'itemScope',\n itemtype: 'itemType',\n keyparams: 'keyParams',\n keytype: 'keyType',\n kind: 'kind',\n label: 'label',\n lang: 'lang',\n list: 'list',\n loop: 'loop',\n low: 'low',\n manifest: 'manifest',\n marginwidth: 'marginWidth',\n marginheight: 'marginHeight',\n max: 'max',\n maxlength: 'maxLength',\n media: 'media',\n mediagroup: 'mediaGroup',\n method: 'method',\n min: 'min',\n minlength: 'minLength',\n multiple: 'multiple',\n muted: 'muted',\n name: 'name',\n nomodule: 'noModule',\n nonce: 'nonce',\n novalidate: 'noValidate',\n open: 'open',\n optimum: 'optimum',\n pattern: 'pattern',\n placeholder: 'placeholder',\n playsinline: 'playsInline',\n poster: 'poster',\n preload: 'preload',\n profile: 'profile',\n radiogroup: 'radioGroup',\n readonly: 'readOnly',\n referrerpolicy: 'referrerPolicy',\n rel: 'rel',\n required: 'required',\n reversed: 'reversed',\n role: 'role',\n rows: 'rows',\n rowspan: 'rowSpan',\n sandbox: 'sandbox',\n scope: 'scope',\n scoped: 'scoped',\n scrolling: 'scrolling',\n seamless: 'seamless',\n selected: 'selected',\n shape: 'shape',\n size: 'size',\n sizes: 'sizes',\n span: 'span',\n spellcheck: 'spellCheck',\n src: 'src',\n srcdoc: 'srcDoc',\n srclang: 'srcLang',\n srcset: 'srcSet',\n start: 'start',\n step: 'step',\n style: 'style',\n summary: 'summary',\n tabindex: 'tabIndex',\n target: 'target',\n title: 'title',\n type: 'type',\n usemap: 'useMap',\n value: 'value',\n width: 'width',\n wmode: 'wmode',\n wrap: 'wrap',\n // SVG\n about: 'about',\n accentheight: 'accentHeight',\n 'accent-height': 'accentHeight',\n accumulate: 'accumulate',\n additive: 'additive',\n alignmentbaseline: 'alignmentBaseline',\n 'alignment-baseline': 'alignmentBaseline',\n allowreorder: 'allowReorder',\n alphabetic: 'alphabetic',\n amplitude: 'amplitude',\n arabicform: 'arabicForm',\n 'arabic-form': 'arabicForm',\n ascent: 'ascent',\n attributename: 'attributeName',\n attributetype: 'attributeType',\n autoreverse: 'autoReverse',\n azimuth: 'azimuth',\n basefrequency: 'baseFrequency',\n baselineshift: 'baselineShift',\n 'baseline-shift': 'baselineShift',\n baseprofile: 'baseProfile',\n bbox: 'bbox',\n begin: 'begin',\n bias: 'bias',\n by: 'by',\n calcmode: 'calcMode',\n capheight: 'capHeight',\n 'cap-height': 'capHeight',\n clip: 'clip',\n clippath: 'clipPath',\n 'clip-path': 'clipPath',\n clippathunits: 'clipPathUnits',\n cliprule: 'clipRule',\n 'clip-rule': 'clipRule',\n color: 'color',\n colorinterpolation: 'colorInterpolation',\n 'color-interpolation': 'colorInterpolation',\n colorinterpolationfilters: 'colorInterpolationFilters',\n 'color-interpolation-filters': 'colorInterpolationFilters',\n colorprofile: 'colorProfile',\n 'color-profile': 'colorProfile',\n colorrendering: 'colorRendering',\n 'color-rendering': 'colorRendering',\n contentscripttype: 'contentScriptType',\n contentstyletype: 'contentStyleType',\n cursor: 'cursor',\n cx: 'cx',\n cy: 'cy',\n d: 'd',\n datatype: 'datatype',\n decelerate: 'decelerate',\n descent: 'descent',\n diffuseconstant: 'diffuseConstant',\n direction: 'direction',\n display: 'display',\n divisor: 'divisor',\n dominantbaseline: 'dominantBaseline',\n 'dominant-baseline': 'dominantBaseline',\n dur: 'dur',\n dx: 'dx',\n dy: 'dy',\n edgemode: 'edgeMode',\n elevation: 'elevation',\n enablebackground: 'enableBackground',\n 'enable-background': 'enableBackground',\n end: 'end',\n exponent: 'exponent',\n externalresourcesrequired: 'externalResourcesRequired',\n fill: 'fill',\n fillopacity: 'fillOpacity',\n 'fill-opacity': 'fillOpacity',\n fillrule: 'fillRule',\n 'fill-rule': 'fillRule',\n filter: 'filter',\n filterres: 'filterRes',\n filterunits: 'filterUnits',\n floodopacity: 'floodOpacity',\n 'flood-opacity': 'floodOpacity',\n floodcolor: 'floodColor',\n 'flood-color': 'floodColor',\n focusable: 'focusable',\n fontfamily: 'fontFamily',\n 'font-family': 'fontFamily',\n fontsize: 'fontSize',\n 'font-size': 'fontSize',\n fontsizeadjust: 'fontSizeAdjust',\n 'font-size-adjust': 'fontSizeAdjust',\n fontstretch: 'fontStretch',\n 'font-stretch': 'fontStretch',\n fontstyle: 'fontStyle',\n 'font-style': 'fontStyle',\n fontvariant: 'fontVariant',\n 'font-variant': 'fontVariant',\n fontweight: 'fontWeight',\n 'font-weight': 'fontWeight',\n format: 'format',\n from: 'from',\n fx: 'fx',\n fy: 'fy',\n g1: 'g1',\n g2: 'g2',\n glyphname: 'glyphName',\n 'glyph-name': 'glyphName',\n glyphorientationhorizontal: 'glyphOrientationHorizontal',\n 'glyph-orientation-horizontal': 'glyphOrientationHorizontal',\n glyphorientationvertical: 'glyphOrientationVertical',\n 'glyph-orientation-vertical': 'glyphOrientationVertical',\n glyphref: 'glyphRef',\n gradienttransform: 'gradientTransform',\n gradientunits: 'gradientUnits',\n hanging: 'hanging',\n horizadvx: 'horizAdvX',\n 'horiz-adv-x': 'horizAdvX',\n horizoriginx: 'horizOriginX',\n 'horiz-origin-x': 'horizOriginX',\n ideographic: 'ideographic',\n imagerendering: 'imageRendering',\n 'image-rendering': 'imageRendering',\n in2: 'in2',\n in: 'in',\n inlist: 'inlist',\n intercept: 'intercept',\n k1: 'k1',\n k2: 'k2',\n k3: 'k3',\n k4: 'k4',\n k: 'k',\n kernelmatrix: 'kernelMatrix',\n kernelunitlength: 'kernelUnitLength',\n kerning: 'kerning',\n keypoints: 'keyPoints',\n keysplines: 'keySplines',\n keytimes: 'keyTimes',\n lengthadjust: 'lengthAdjust',\n letterspacing: 'letterSpacing',\n 'letter-spacing': 'letterSpacing',\n lightingcolor: 'lightingColor',\n 'lighting-color': 'lightingColor',\n limitingconeangle: 'limitingConeAngle',\n local: 'local',\n markerend: 'markerEnd',\n 'marker-end': 'markerEnd',\n markerheight: 'markerHeight',\n markermid: 'markerMid',\n 'marker-mid': 'markerMid',\n markerstart: 'markerStart',\n 'marker-start': 'markerStart',\n markerunits: 'markerUnits',\n markerwidth: 'markerWidth',\n mask: 'mask',\n maskcontentunits: 'maskContentUnits',\n maskunits: 'maskUnits',\n mathematical: 'mathematical',\n mode: 'mode',\n numoctaves: 'numOctaves',\n offset: 'offset',\n opacity: 'opacity',\n operator: 'operator',\n order: 'order',\n orient: 'orient',\n orientation: 'orientation',\n origin: 'origin',\n overflow: 'overflow',\n overlineposition: 'overlinePosition',\n 'overline-position': 'overlinePosition',\n overlinethickness: 'overlineThickness',\n 'overline-thickness': 'overlineThickness',\n paintorder: 'paintOrder',\n 'paint-order': 'paintOrder',\n panose1: 'panose1',\n 'panose-1': 'panose1',\n pathlength: 'pathLength',\n patterncontentunits: 'patternContentUnits',\n patterntransform: 'patternTransform',\n patternunits: 'patternUnits',\n pointerevents: 'pointerEvents',\n 'pointer-events': 'pointerEvents',\n points: 'points',\n pointsatx: 'pointsAtX',\n pointsaty: 'pointsAtY',\n pointsatz: 'pointsAtZ',\n prefix: 'prefix',\n preservealpha: 'preserveAlpha',\n preserveaspectratio: 'preserveAspectRatio',\n primitiveunits: 'primitiveUnits',\n property: 'property',\n r: 'r',\n radius: 'radius',\n refx: 'refX',\n refy: 'refY',\n renderingintent: 'renderingIntent',\n 'rendering-intent': 'renderingIntent',\n repeatcount: 'repeatCount',\n repeatdur: 'repeatDur',\n requiredextensions: 'requiredExtensions',\n requiredfeatures: 'requiredFeatures',\n resource: 'resource',\n restart: 'restart',\n result: 'result',\n results: 'results',\n rotate: 'rotate',\n rx: 'rx',\n ry: 'ry',\n scale: 'scale',\n security: 'security',\n seed: 'seed',\n shaperendering: 'shapeRendering',\n 'shape-rendering': 'shapeRendering',\n slope: 'slope',\n spacing: 'spacing',\n specularconstant: 'specularConstant',\n specularexponent: 'specularExponent',\n speed: 'speed',\n spreadmethod: 'spreadMethod',\n startoffset: 'startOffset',\n stddeviation: 'stdDeviation',\n stemh: 'stemh',\n stemv: 'stemv',\n stitchtiles: 'stitchTiles',\n stopcolor: 'stopColor',\n 'stop-color': 'stopColor',\n stopopacity: 'stopOpacity',\n 'stop-opacity': 'stopOpacity',\n strikethroughposition: 'strikethroughPosition',\n 'strikethrough-position': 'strikethroughPosition',\n strikethroughthickness: 'strikethroughThickness',\n 'strikethrough-thickness': 'strikethroughThickness',\n string: 'string',\n stroke: 'stroke',\n strokedasharray: 'strokeDasharray',\n 'stroke-dasharray': 'strokeDasharray',\n strokedashoffset: 'strokeDashoffset',\n 'stroke-dashoffset': 'strokeDashoffset',\n strokelinecap: 'strokeLinecap',\n 'stroke-linecap': 'strokeLinecap',\n strokelinejoin: 'strokeLinejoin',\n 'stroke-linejoin': 'strokeLinejoin',\n strokemiterlimit: 'strokeMiterlimit',\n 'stroke-miterlimit': 'strokeMiterlimit',\n strokewidth: 'strokeWidth',\n 'stroke-width': 'strokeWidth',\n strokeopacity: 'strokeOpacity',\n 'stroke-opacity': 'strokeOpacity',\n suppresscontenteditablewarning: 'suppressContentEditableWarning',\n suppresshydrationwarning: 'suppressHydrationWarning',\n surfacescale: 'surfaceScale',\n systemlanguage: 'systemLanguage',\n tablevalues: 'tableValues',\n targetx: 'targetX',\n targety: 'targetY',\n textanchor: 'textAnchor',\n 'text-anchor': 'textAnchor',\n textdecoration: 'textDecoration',\n 'text-decoration': 'textDecoration',\n textlength: 'textLength',\n textrendering: 'textRendering',\n 'text-rendering': 'textRendering',\n to: 'to',\n transform: 'transform',\n typeof: 'typeof',\n u1: 'u1',\n u2: 'u2',\n underlineposition: 'underlinePosition',\n 'underline-position': 'underlinePosition',\n underlinethickness: 'underlineThickness',\n 'underline-thickness': 'underlineThickness',\n unicode: 'unicode',\n unicodebidi: 'unicodeBidi',\n 'unicode-bidi': 'unicodeBidi',\n unicoderange: 'unicodeRange',\n 'unicode-range': 'unicodeRange',\n unitsperem: 'unitsPerEm',\n 'units-per-em': 'unitsPerEm',\n unselectable: 'unselectable',\n valphabetic: 'vAlphabetic',\n 'v-alphabetic': 'vAlphabetic',\n values: 'values',\n vectoreffect: 'vectorEffect',\n 'vector-effect': 'vectorEffect',\n version: 'version',\n vertadvy: 'vertAdvY',\n 'vert-adv-y': 'vertAdvY',\n vertoriginx: 'vertOriginX',\n 'vert-origin-x': 'vertOriginX',\n vertoriginy: 'vertOriginY',\n 'vert-origin-y': 'vertOriginY',\n vhanging: 'vHanging',\n 'v-hanging': 'vHanging',\n videographic: 'vIdeographic',\n 'v-ideographic': 'vIdeographic',\n viewbox: 'viewBox',\n viewtarget: 'viewTarget',\n visibility: 'visibility',\n vmathematical: 'vMathematical',\n 'v-mathematical': 'vMathematical',\n vocab: 'vocab',\n widths: 'widths',\n wordspacing: 'wordSpacing',\n 'word-spacing': 'wordSpacing',\n writingmode: 'writingMode',\n 'writing-mode': 'writingMode',\n x1: 'x1',\n x2: 'x2',\n x: 'x',\n xchannelselector: 'xChannelSelector',\n xheight: 'xHeight',\n 'x-height': 'xHeight',\n xlinkactuate: 'xlinkActuate',\n 'xlink:actuate': 'xlinkActuate',\n xlinkarcrole: 'xlinkArcrole',\n 'xlink:arcrole': 'xlinkArcrole',\n xlinkhref: 'xlinkHref',\n 'xlink:href': 'xlinkHref',\n xlinkrole: 'xlinkRole',\n 'xlink:role': 'xlinkRole',\n xlinkshow: 'xlinkShow',\n 'xlink:show': 'xlinkShow',\n xlinktitle: 'xlinkTitle',\n 'xlink:title': 'xlinkTitle',\n xlinktype: 'xlinkType',\n 'xlink:type': 'xlinkType',\n xmlbase: 'xmlBase',\n 'xml:base': 'xmlBase',\n xmllang: 'xmlLang',\n 'xml:lang': 'xmlLang',\n xmlns: 'xmlns',\n 'xml:space': 'xmlSpace',\n xmlnsxlink: 'xmlnsXlink',\n 'xmlns:xlink': 'xmlnsXlink',\n xmlspace: 'xmlSpace',\n y1: 'y1',\n y2: 'y2',\n y: 'y',\n ychannelselector: 'yChannelSelector',\n z: 'z',\n zoomandpan: 'zoomAndPan'\n};\n\nvar ariaProperties = {\n 'aria-current': 0,\n // state\n 'aria-details': 0,\n 'aria-disabled': 0,\n // state\n 'aria-hidden': 0,\n // state\n 'aria-invalid': 0,\n // state\n 'aria-keyshortcuts': 0,\n 'aria-label': 0,\n 'aria-roledescription': 0,\n // Widget Attributes\n 'aria-autocomplete': 0,\n 'aria-checked': 0,\n 'aria-expanded': 0,\n 'aria-haspopup': 0,\n 'aria-level': 0,\n 'aria-modal': 0,\n 'aria-multiline': 0,\n 'aria-multiselectable': 0,\n 'aria-orientation': 0,\n 'aria-placeholder': 0,\n 'aria-pressed': 0,\n 'aria-readonly': 0,\n 'aria-required': 0,\n 'aria-selected': 0,\n 'aria-sort': 0,\n 'aria-valuemax': 0,\n 'aria-valuemin': 0,\n 'aria-valuenow': 0,\n 'aria-valuetext': 0,\n // Live Region Attributes\n 'aria-atomic': 0,\n 'aria-busy': 0,\n 'aria-live': 0,\n 'aria-relevant': 0,\n // Drag-and-Drop Attributes\n 'aria-dropeffect': 0,\n 'aria-grabbed': 0,\n // Relationship Attributes\n 'aria-activedescendant': 0,\n 'aria-colcount': 0,\n 'aria-colindex': 0,\n 'aria-colspan': 0,\n 'aria-controls': 0,\n 'aria-describedby': 0,\n 'aria-errormessage': 0,\n 'aria-flowto': 0,\n 'aria-labelledby': 0,\n 'aria-owns': 0,\n 'aria-posinset': 0,\n 'aria-rowcount': 0,\n 'aria-rowindex': 0,\n 'aria-rowspan': 0,\n 'aria-setsize': 0\n};\n\nvar warnedProperties = {};\nvar rARIA = new RegExp('^(aria)-[' + ATTRIBUTE_NAME_CHAR + ']*$');\nvar rARIACamel = new RegExp('^(aria)[A-Z][' + ATTRIBUTE_NAME_CHAR + ']*$');\nvar hasOwnProperty$1 = Object.prototype.hasOwnProperty;\n\nfunction validateProperty(tagName, name) {\n {\n if (hasOwnProperty$1.call(warnedProperties, name) && warnedProperties[name]) {\n return true;\n }\n\n if (rARIACamel.test(name)) {\n var ariaName = 'aria-' + name.slice(4).toLowerCase();\n var correctName = ariaProperties.hasOwnProperty(ariaName) ? ariaName : null; // If this is an aria-* attribute, but is not listed in the known DOM\n // DOM properties, then it is an invalid aria-* attribute.\n\n if (correctName == null) {\n error('Invalid ARIA attribute `%s`. ARIA attributes follow the pattern aria-* and must be lowercase.', name);\n\n warnedProperties[name] = true;\n return true;\n } // aria-* attributes should be lowercase; suggest the lowercase version.\n\n\n if (name !== correctName) {\n error('Invalid ARIA attribute `%s`. Did you mean `%s`?', name, correctName);\n\n warnedProperties[name] = true;\n return true;\n }\n }\n\n if (rARIA.test(name)) {\n var lowerCasedName = name.toLowerCase();\n var standardName = ariaProperties.hasOwnProperty(lowerCasedName) ? lowerCasedName : null; // If this is an aria-* attribute, but is not listed in the known DOM\n // DOM properties, then it is an invalid aria-* attribute.\n\n if (standardName == null) {\n warnedProperties[name] = true;\n return false;\n } // aria-* attributes should be lowercase; suggest the lowercase version.\n\n\n if (name !== standardName) {\n error('Unknown ARIA attribute `%s`. Did you mean `%s`?', name, standardName);\n\n warnedProperties[name] = true;\n return true;\n }\n }\n }\n\n return true;\n}\n\nfunction warnInvalidARIAProps(type, props) {\n {\n var invalidProps = [];\n\n for (var key in props) {\n var isValid = validateProperty(type, key);\n\n if (!isValid) {\n invalidProps.push(key);\n }\n }\n\n var unknownPropString = invalidProps.map(function (prop) {\n return '`' + prop + '`';\n }).join(', ');\n\n if (invalidProps.length === 1) {\n error('Invalid aria prop %s on <%s> tag. ' + 'For details, see https://fb.me/invalid-aria-prop', unknownPropString, type);\n } else if (invalidProps.length > 1) {\n error('Invalid aria props %s on <%s> tag. ' + 'For details, see https://fb.me/invalid-aria-prop', unknownPropString, type);\n }\n }\n}\n\nfunction validateProperties(type, props) {\n if (isCustomComponent(type, props)) {\n return;\n }\n\n warnInvalidARIAProps(type, props);\n}\n\nvar didWarnValueNull = false;\nfunction validateProperties$1(type, props) {\n {\n if (type !== 'input' && type !== 'textarea' && type !== 'select') {\n return;\n }\n\n if (props != null && props.value === null && !didWarnValueNull) {\n didWarnValueNull = true;\n\n if (type === 'select' && props.multiple) {\n error('`value` prop on `%s` should not be null. ' + 'Consider using an empty array when `multiple` is set to `true` ' + 'to clear the component or `undefined` for uncontrolled components.', type);\n } else {\n error('`value` prop on `%s` should not be null. ' + 'Consider using an empty string to clear the component or `undefined` ' + 'for uncontrolled components.', type);\n }\n }\n }\n}\n\nvar validateProperty$1 = function () {};\n\n{\n var warnedProperties$1 = {};\n var _hasOwnProperty = Object.prototype.hasOwnProperty;\n var EVENT_NAME_REGEX = /^on./;\n var INVALID_EVENT_NAME_REGEX = /^on[^A-Z]/;\n var rARIA$1 = new RegExp('^(aria)-[' + ATTRIBUTE_NAME_CHAR + ']*$');\n var rARIACamel$1 = new RegExp('^(aria)[A-Z][' + ATTRIBUTE_NAME_CHAR + ']*$');\n\n validateProperty$1 = function (tagName, name, value, canUseEventSystem) {\n if (_hasOwnProperty.call(warnedProperties$1, name) && warnedProperties$1[name]) {\n return true;\n }\n\n var lowerCasedName = name.toLowerCase();\n\n if (lowerCasedName === 'onfocusin' || lowerCasedName === 'onfocusout') {\n error('React uses onFocus and onBlur instead of onFocusIn and onFocusOut. ' + 'All React events are normalized to bubble, so onFocusIn and onFocusOut ' + 'are not needed/supported by React.');\n\n warnedProperties$1[name] = true;\n return true;\n } // We can't rely on the event system being injected on the server.\n\n\n if (canUseEventSystem) {\n if (registrationNameModules.hasOwnProperty(name)) {\n return true;\n }\n\n var registrationName = possibleRegistrationNames.hasOwnProperty(lowerCasedName) ? possibleRegistrationNames[lowerCasedName] : null;\n\n if (registrationName != null) {\n error('Invalid event handler property `%s`. Did you mean `%s`?', name, registrationName);\n\n warnedProperties$1[name] = true;\n return true;\n }\n\n if (EVENT_NAME_REGEX.test(name)) {\n error('Unknown event handler property `%s`. It will be ignored.', name);\n\n warnedProperties$1[name] = true;\n return true;\n }\n } else if (EVENT_NAME_REGEX.test(name)) {\n // If no event plugins have been injected, we are in a server environment.\n // So we can't tell if the event name is correct for sure, but we can filter\n // out known bad ones like `onclick`. We can't suggest a specific replacement though.\n if (INVALID_EVENT_NAME_REGEX.test(name)) {\n error('Invalid event handler property `%s`. ' + 'React events use the camelCase naming convention, for example `onClick`.', name);\n }\n\n warnedProperties$1[name] = true;\n return true;\n } // Let the ARIA attribute hook validate ARIA attributes\n\n\n if (rARIA$1.test(name) || rARIACamel$1.test(name)) {\n return true;\n }\n\n if (lowerCasedName === 'innerhtml') {\n error('Directly setting property `innerHTML` is not permitted. ' + 'For more information, lookup documentation on `dangerouslySetInnerHTML`.');\n\n warnedProperties$1[name] = true;\n return true;\n }\n\n if (lowerCasedName === 'aria') {\n error('The `aria` attribute is reserved for future use in React. ' + 'Pass individual `aria-` attributes instead.');\n\n warnedProperties$1[name] = true;\n return true;\n }\n\n if (lowerCasedName === 'is' && value !== null && value !== undefined && typeof value !== 'string') {\n error('Received a `%s` for a string attribute `is`. If this is expected, cast ' + 'the value to a string.', typeof value);\n\n warnedProperties$1[name] = true;\n return true;\n }\n\n if (typeof value === 'number' && isNaN(value)) {\n error('Received NaN for the `%s` attribute. If this is expected, cast ' + 'the value to a string.', name);\n\n warnedProperties$1[name] = true;\n return true;\n }\n\n var propertyInfo = getPropertyInfo(name);\n var isReserved = propertyInfo !== null && propertyInfo.type === RESERVED; // Known attributes should match the casing specified in the property config.\n\n if (possibleStandardNames.hasOwnProperty(lowerCasedName)) {\n var standardName = possibleStandardNames[lowerCasedName];\n\n if (standardName !== name) {\n error('Invalid DOM property `%s`. Did you mean `%s`?', name, standardName);\n\n warnedProperties$1[name] = true;\n return true;\n }\n } else if (!isReserved && name !== lowerCasedName) {\n // Unknown attributes should have lowercase casing since that's how they\n // will be cased anyway with server rendering.\n error('React does not recognize the `%s` prop on a DOM element. If you ' + 'intentionally want it to appear in the DOM as a custom ' + 'attribute, spell it as lowercase `%s` instead. ' + 'If you accidentally passed it from a parent component, remove ' + 'it from the DOM element.', name, lowerCasedName);\n\n warnedProperties$1[name] = true;\n return true;\n }\n\n if (typeof value === 'boolean' && shouldRemoveAttributeWithWarning(name, value, propertyInfo, false)) {\n if (value) {\n error('Received `%s` for a non-boolean attribute `%s`.\\n\\n' + 'If you want to write it to the DOM, pass a string instead: ' + '%s=\"%s\" or %s={value.toString()}.', value, name, name, value, name);\n } else {\n error('Received `%s` for a non-boolean attribute `%s`.\\n\\n' + 'If you want to write it to the DOM, pass a string instead: ' + '%s=\"%s\" or %s={value.toString()}.\\n\\n' + 'If you used to conditionally omit it with %s={condition && value}, ' + 'pass %s={condition ? value : undefined} instead.', value, name, name, value, name, name, name);\n }\n\n warnedProperties$1[name] = true;\n return true;\n } // Now that we've validated casing, do not validate\n // data types for reserved props\n\n\n if (isReserved) {\n return true;\n } // Warn when a known attribute is a bad type\n\n\n if (shouldRemoveAttributeWithWarning(name, value, propertyInfo, false)) {\n warnedProperties$1[name] = true;\n return false;\n } // Warn when passing the strings 'false' or 'true' into a boolean prop\n\n\n if ((value === 'false' || value === 'true') && propertyInfo !== null && propertyInfo.type === BOOLEAN) {\n error('Received the string `%s` for the boolean attribute `%s`. ' + '%s ' + 'Did you mean %s={%s}?', value, name, value === 'false' ? 'The browser will interpret it as a truthy value.' : 'Although this works, it will not work as expected if you pass the string \"false\".', name, value);\n\n warnedProperties$1[name] = true;\n return true;\n }\n\n return true;\n };\n}\n\nvar warnUnknownProperties = function (type, props, canUseEventSystem) {\n {\n var unknownProps = [];\n\n for (var key in props) {\n var isValid = validateProperty$1(type, key, props[key], canUseEventSystem);\n\n if (!isValid) {\n unknownProps.push(key);\n }\n }\n\n var unknownPropString = unknownProps.map(function (prop) {\n return '`' + prop + '`';\n }).join(', ');\n\n if (unknownProps.length === 1) {\n error('Invalid value for prop %s on <%s> tag. Either remove it from the element, ' + 'or pass a string or number value to keep it in the DOM. ' + 'For details, see https://fb.me/react-attribute-behavior', unknownPropString, type);\n } else if (unknownProps.length > 1) {\n error('Invalid values for props %s on <%s> tag. Either remove them from the element, ' + 'or pass a string or number value to keep them in the DOM. ' + 'For details, see https://fb.me/react-attribute-behavior', unknownPropString, type);\n }\n }\n};\n\nfunction validateProperties$2(type, props, canUseEventSystem) {\n if (isCustomComponent(type, props)) {\n return;\n }\n\n warnUnknownProperties(type, props, canUseEventSystem);\n}\n\nvar didWarnInvalidHydration = false;\nvar DANGEROUSLY_SET_INNER_HTML = 'dangerouslySetInnerHTML';\nvar SUPPRESS_CONTENT_EDITABLE_WARNING = 'suppressContentEditableWarning';\nvar SUPPRESS_HYDRATION_WARNING = 'suppressHydrationWarning';\nvar AUTOFOCUS = 'autoFocus';\nvar CHILDREN = 'children';\nvar STYLE = 'style';\nvar HTML$1 = '__html';\nvar HTML_NAMESPACE$1 = Namespaces.html;\nvar warnedUnknownTags;\nvar suppressHydrationWarning;\nvar validatePropertiesInDevelopment;\nvar warnForTextDifference;\nvar warnForPropDifference;\nvar warnForExtraAttributes;\nvar warnForInvalidEventListener;\nvar canDiffStyleForHydrationWarning;\nvar normalizeMarkupForTextOrAttribute;\nvar normalizeHTML;\n\n{\n warnedUnknownTags = {\n // Chrome is the only major browser not shipping <time>. But as of July\n // 2017 it intends to ship it due to widespread usage. We intentionally\n // *don't* warn for <time> even if it's unrecognized by Chrome because\n // it soon will be, and many apps have been using it anyway.\n time: true,\n // There are working polyfills for <dialog>. Let people use it.\n dialog: true,\n // Electron ships a custom <webview> tag to display external web content in\n // an isolated frame and process.\n // This tag is not present in non Electron environments such as JSDom which\n // is often used for testing purposes.\n // @see https://electronjs.org/docs/api/webview-tag\n webview: true\n };\n\n validatePropertiesInDevelopment = function (type, props) {\n validateProperties(type, props);\n validateProperties$1(type, props);\n validateProperties$2(type, props,\n /* canUseEventSystem */\n true);\n }; // IE 11 parses & normalizes the style attribute as opposed to other\n // browsers. It adds spaces and sorts the properties in some\n // non-alphabetical order. Handling that would require sorting CSS\n // properties in the client & server versions or applying\n // `expectedStyle` to a temporary DOM node to read its `style` attribute\n // normalized. Since it only affects IE, we're skipping style warnings\n // in that browser completely in favor of doing all that work.\n // See https://github.com/facebook/react/issues/11807\n\n\n canDiffStyleForHydrationWarning = canUseDOM && !document.documentMode; // HTML parsing normalizes CR and CRLF to LF.\n // It also can turn \\u0000 into \\uFFFD inside attributes.\n // https://www.w3.org/TR/html5/single-page.html#preprocessing-the-input-stream\n // If we have a mismatch, it might be caused by that.\n // We will still patch up in this case but not fire the warning.\n\n var NORMALIZE_NEWLINES_REGEX = /\\r\\n?/g;\n var NORMALIZE_NULL_AND_REPLACEMENT_REGEX = /\\u0000|\\uFFFD/g;\n\n normalizeMarkupForTextOrAttribute = function (markup) {\n var markupString = typeof markup === 'string' ? markup : '' + markup;\n return markupString.replace(NORMALIZE_NEWLINES_REGEX, '\\n').replace(NORMALIZE_NULL_AND_REPLACEMENT_REGEX, '');\n };\n\n warnForTextDifference = function (serverText, clientText) {\n if (didWarnInvalidHydration) {\n return;\n }\n\n var normalizedClientText = normalizeMarkupForTextOrAttribute(clientText);\n var normalizedServerText = normalizeMarkupForTextOrAttribute(serverText);\n\n if (normalizedServerText === normalizedClientText) {\n return;\n }\n\n didWarnInvalidHydration = true;\n\n error('Text content did not match. Server: \"%s\" Client: \"%s\"', normalizedServerText, normalizedClientText);\n };\n\n warnForPropDifference = function (propName, serverValue, clientValue) {\n if (didWarnInvalidHydration) {\n return;\n }\n\n var normalizedClientValue = normalizeMarkupForTextOrAttribute(clientValue);\n var normalizedServerValue = normalizeMarkupForTextOrAttribute(serverValue);\n\n if (normalizedServerValue === normalizedClientValue) {\n return;\n }\n\n didWarnInvalidHydration = true;\n\n error('Prop `%s` did not match. Server: %s Client: %s', propName, JSON.stringify(normalizedServerValue), JSON.stringify(normalizedClientValue));\n };\n\n warnForExtraAttributes = function (attributeNames) {\n if (didWarnInvalidHydration) {\n return;\n }\n\n didWarnInvalidHydration = true;\n var names = [];\n attributeNames.forEach(function (name) {\n names.push(name);\n });\n\n error('Extra attributes from the server: %s', names);\n };\n\n warnForInvalidEventListener = function (registrationName, listener) {\n if (listener === false) {\n error('Expected `%s` listener to be a function, instead got `false`.\\n\\n' + 'If you used to conditionally omit it with %s={condition && value}, ' + 'pass %s={condition ? value : undefined} instead.', registrationName, registrationName, registrationName);\n } else {\n error('Expected `%s` listener to be a function, instead got a value of `%s` type.', registrationName, typeof listener);\n }\n }; // Parse the HTML and read it back to normalize the HTML string so that it\n // can be used for comparison.\n\n\n normalizeHTML = function (parent, html) {\n // We could have created a separate document here to avoid\n // re-initializing custom elements if they exist. But this breaks\n // how <noscript> is being handled. So we use the same document.\n // See the discussion in https://github.com/facebook/react/pull/11157.\n var testElement = parent.namespaceURI === HTML_NAMESPACE$1 ? parent.ownerDocument.createElement(parent.tagName) : parent.ownerDocument.createElementNS(parent.namespaceURI, parent.tagName);\n testElement.innerHTML = html;\n return testElement.innerHTML;\n };\n}\n\nfunction ensureListeningTo(rootContainerElement, registrationName) {\n var isDocumentOrFragment = rootContainerElement.nodeType === DOCUMENT_NODE || rootContainerElement.nodeType === DOCUMENT_FRAGMENT_NODE;\n var doc = isDocumentOrFragment ? rootContainerElement : rootContainerElement.ownerDocument;\n legacyListenToEvent(registrationName, doc);\n}\n\nfunction getOwnerDocumentFromRootContainer(rootContainerElement) {\n return rootContainerElement.nodeType === DOCUMENT_NODE ? rootContainerElement : rootContainerElement.ownerDocument;\n}\n\nfunction noop() {}\n\nfunction trapClickOnNonInteractiveElement(node) {\n // Mobile Safari does not fire properly bubble click events on\n // non-interactive elements, which means delegated click listeners do not\n // fire. The workaround for this bug involves attaching an empty click\n // listener on the target node.\n // http://www.quirksmode.org/blog/archives/2010/09/click_event_del.html\n // Just set it using the onclick property so that we don't have to manage any\n // bookkeeping for it. Not sure if we need to clear it when the listener is\n // removed.\n // TODO: Only do this for the relevant Safaris maybe?\n node.onclick = noop;\n}\n\nfunction setInitialDOMProperties(tag, domElement, rootContainerElement, nextProps, isCustomComponentTag) {\n for (var propKey in nextProps) {\n if (!nextProps.hasOwnProperty(propKey)) {\n continue;\n }\n\n var nextProp = nextProps[propKey];\n\n if (propKey === STYLE) {\n {\n if (nextProp) {\n // Freeze the next style object so that we can assume it won't be\n // mutated. We have already warned for this in the past.\n Object.freeze(nextProp);\n }\n } // Relies on `updateStylesByID` not mutating `styleUpdates`.\n\n\n setValueForStyles(domElement, nextProp);\n } else if (propKey === DANGEROUSLY_SET_INNER_HTML) {\n var nextHtml = nextProp ? nextProp[HTML$1] : undefined;\n\n if (nextHtml != null) {\n setInnerHTML(domElement, nextHtml);\n }\n } else if (propKey === CHILDREN) {\n if (typeof nextProp === 'string') {\n // Avoid setting initial textContent when the text is empty. In IE11 setting\n // textContent on a <textarea> will cause the placeholder to not\n // show within the <textarea> until it has been focused and blurred again.\n // https://github.com/facebook/react/issues/6731#issuecomment-254874553\n var canSetTextContent = tag !== 'textarea' || nextProp !== '';\n\n if (canSetTextContent) {\n setTextContent(domElement, nextProp);\n }\n } else if (typeof nextProp === 'number') {\n setTextContent(domElement, '' + nextProp);\n }\n } else if ( propKey === SUPPRESS_CONTENT_EDITABLE_WARNING || propKey === SUPPRESS_HYDRATION_WARNING) ; else if (propKey === AUTOFOCUS) ; else if (registrationNameModules.hasOwnProperty(propKey)) {\n if (nextProp != null) {\n if ( typeof nextProp !== 'function') {\n warnForInvalidEventListener(propKey, nextProp);\n }\n\n ensureListeningTo(rootContainerElement, propKey);\n }\n } else if (nextProp != null) {\n setValueForProperty(domElement, propKey, nextProp, isCustomComponentTag);\n }\n }\n}\n\nfunction updateDOMProperties(domElement, updatePayload, wasCustomComponentTag, isCustomComponentTag) {\n // TODO: Handle wasCustomComponentTag\n for (var i = 0; i < updatePayload.length; i += 2) {\n var propKey = updatePayload[i];\n var propValue = updatePayload[i + 1];\n\n if (propKey === STYLE) {\n setValueForStyles(domElement, propValue);\n } else if (propKey === DANGEROUSLY_SET_INNER_HTML) {\n setInnerHTML(domElement, propValue);\n } else if (propKey === CHILDREN) {\n setTextContent(domElement, propValue);\n } else {\n setValueForProperty(domElement, propKey, propValue, isCustomComponentTag);\n }\n }\n}\n\nfunction createElement(type, props, rootContainerElement, parentNamespace) {\n var isCustomComponentTag; // We create tags in the namespace of their parent container, except HTML\n // tags get no namespace.\n\n var ownerDocument = getOwnerDocumentFromRootContainer(rootContainerElement);\n var domElement;\n var namespaceURI = parentNamespace;\n\n if (namespaceURI === HTML_NAMESPACE$1) {\n namespaceURI = getIntrinsicNamespace(type);\n }\n\n if (namespaceURI === HTML_NAMESPACE$1) {\n {\n isCustomComponentTag = isCustomComponent(type, props); // Should this check be gated by parent namespace? Not sure we want to\n // allow <SVG> or <mATH>.\n\n if (!isCustomComponentTag && type !== type.toLowerCase()) {\n error('<%s /> is using incorrect casing. ' + 'Use PascalCase for React components, ' + 'or lowercase for HTML elements.', type);\n }\n }\n\n if (type === 'script') {\n // Create the script via .innerHTML so its \"parser-inserted\" flag is\n // set to true and it does not execute\n var div = ownerDocument.createElement('div');\n\n div.innerHTML = '<script><' + '/script>'; // eslint-disable-line\n // This is guaranteed to yield a script element.\n\n var firstChild = div.firstChild;\n domElement = div.removeChild(firstChild);\n } else if (typeof props.is === 'string') {\n // $FlowIssue `createElement` should be updated for Web Components\n domElement = ownerDocument.createElement(type, {\n is: props.is\n });\n } else {\n // Separate else branch instead of using `props.is || undefined` above because of a Firefox bug.\n // See discussion in https://github.com/facebook/react/pull/6896\n // and discussion in https://bugzilla.mozilla.org/show_bug.cgi?id=1276240\n domElement = ownerDocument.createElement(type); // Normally attributes are assigned in `setInitialDOMProperties`, however the `multiple` and `size`\n // attributes on `select`s needs to be added before `option`s are inserted.\n // This prevents:\n // - a bug where the `select` does not scroll to the correct option because singular\n // `select` elements automatically pick the first item #13222\n // - a bug where the `select` set the first item as selected despite the `size` attribute #14239\n // See https://github.com/facebook/react/issues/13222\n // and https://github.com/facebook/react/issues/14239\n\n if (type === 'select') {\n var node = domElement;\n\n if (props.multiple) {\n node.multiple = true;\n } else if (props.size) {\n // Setting a size greater than 1 causes a select to behave like `multiple=true`, where\n // it is possible that no option is selected.\n //\n // This is only necessary when a select in \"single selection mode\".\n node.size = props.size;\n }\n }\n }\n } else {\n domElement = ownerDocument.createElementNS(namespaceURI, type);\n }\n\n {\n if (namespaceURI === HTML_NAMESPACE$1) {\n if (!isCustomComponentTag && Object.prototype.toString.call(domElement) === '[object HTMLUnknownElement]' && !Object.prototype.hasOwnProperty.call(warnedUnknownTags, type)) {\n warnedUnknownTags[type] = true;\n\n error('The tag <%s> is unrecognized in this browser. ' + 'If you meant to render a React component, start its name with ' + 'an uppercase letter.', type);\n }\n }\n }\n\n return domElement;\n}\nfunction createTextNode(text, rootContainerElement) {\n return getOwnerDocumentFromRootContainer(rootContainerElement).createTextNode(text);\n}\nfunction setInitialProperties(domElement, tag, rawProps, rootContainerElement) {\n var isCustomComponentTag = isCustomComponent(tag, rawProps);\n\n {\n validatePropertiesInDevelopment(tag, rawProps);\n } // TODO: Make sure that we check isMounted before firing any of these events.\n\n\n var props;\n\n switch (tag) {\n case 'iframe':\n case 'object':\n case 'embed':\n trapBubbledEvent(TOP_LOAD, domElement);\n props = rawProps;\n break;\n\n case 'video':\n case 'audio':\n // Create listener for each media event\n for (var i = 0; i < mediaEventTypes.length; i++) {\n trapBubbledEvent(mediaEventTypes[i], domElement);\n }\n\n props = rawProps;\n break;\n\n case 'source':\n trapBubbledEvent(TOP_ERROR, domElement);\n props = rawProps;\n break;\n\n case 'img':\n case 'image':\n case 'link':\n trapBubbledEvent(TOP_ERROR, domElement);\n trapBubbledEvent(TOP_LOAD, domElement);\n props = rawProps;\n break;\n\n case 'form':\n trapBubbledEvent(TOP_RESET, domElement);\n trapBubbledEvent(TOP_SUBMIT, domElement);\n props = rawProps;\n break;\n\n case 'details':\n trapBubbledEvent(TOP_TOGGLE, domElement);\n props = rawProps;\n break;\n\n case 'input':\n initWrapperState(domElement, rawProps);\n props = getHostProps(domElement, rawProps);\n trapBubbledEvent(TOP_INVALID, domElement); // For controlled components we always need to ensure we're listening\n // to onChange. Even if there is no listener.\n\n ensureListeningTo(rootContainerElement, 'onChange');\n break;\n\n case 'option':\n validateProps(domElement, rawProps);\n props = getHostProps$1(domElement, rawProps);\n break;\n\n case 'select':\n initWrapperState$1(domElement, rawProps);\n props = getHostProps$2(domElement, rawProps);\n trapBubbledEvent(TOP_INVALID, domElement); // For controlled components we always need to ensure we're listening\n // to onChange. Even if there is no listener.\n\n ensureListeningTo(rootContainerElement, 'onChange');\n break;\n\n case 'textarea':\n initWrapperState$2(domElement, rawProps);\n props = getHostProps$3(domElement, rawProps);\n trapBubbledEvent(TOP_INVALID, domElement); // For controlled components we always need to ensure we're listening\n // to onChange. Even if there is no listener.\n\n ensureListeningTo(rootContainerElement, 'onChange');\n break;\n\n default:\n props = rawProps;\n }\n\n assertValidProps(tag, props);\n setInitialDOMProperties(tag, domElement, rootContainerElement, props, isCustomComponentTag);\n\n switch (tag) {\n case 'input':\n // TODO: Make sure we check if this is still unmounted or do any clean\n // up necessary since we never stop tracking anymore.\n track(domElement);\n postMountWrapper(domElement, rawProps, false);\n break;\n\n case 'textarea':\n // TODO: Make sure we check if this is still unmounted or do any clean\n // up necessary since we never stop tracking anymore.\n track(domElement);\n postMountWrapper$3(domElement);\n break;\n\n case 'option':\n postMountWrapper$1(domElement, rawProps);\n break;\n\n case 'select':\n postMountWrapper$2(domElement, rawProps);\n break;\n\n default:\n if (typeof props.onClick === 'function') {\n // TODO: This cast may not be sound for SVG, MathML or custom elements.\n trapClickOnNonInteractiveElement(domElement);\n }\n\n break;\n }\n} // Calculate the diff between the two objects.\n\nfunction diffProperties(domElement, tag, lastRawProps, nextRawProps, rootContainerElement) {\n {\n validatePropertiesInDevelopment(tag, nextRawProps);\n }\n\n var updatePayload = null;\n var lastProps;\n var nextProps;\n\n switch (tag) {\n case 'input':\n lastProps = getHostProps(domElement, lastRawProps);\n nextProps = getHostProps(domElement, nextRawProps);\n updatePayload = [];\n break;\n\n case 'option':\n lastProps = getHostProps$1(domElement, lastRawProps);\n nextProps = getHostProps$1(domElement, nextRawProps);\n updatePayload = [];\n break;\n\n case 'select':\n lastProps = getHostProps$2(domElement, lastRawProps);\n nextProps = getHostProps$2(domElement, nextRawProps);\n updatePayload = [];\n break;\n\n case 'textarea':\n lastProps = getHostProps$3(domElement, lastRawProps);\n nextProps = getHostProps$3(domElement, nextRawProps);\n updatePayload = [];\n break;\n\n default:\n lastProps = lastRawProps;\n nextProps = nextRawProps;\n\n if (typeof lastProps.onClick !== 'function' && typeof nextProps.onClick === 'function') {\n // TODO: This cast may not be sound for SVG, MathML or custom elements.\n trapClickOnNonInteractiveElement(domElement);\n }\n\n break;\n }\n\n assertValidProps(tag, nextProps);\n var propKey;\n var styleName;\n var styleUpdates = null;\n\n for (propKey in lastProps) {\n if (nextProps.hasOwnProperty(propKey) || !lastProps.hasOwnProperty(propKey) || lastProps[propKey] == null) {\n continue;\n }\n\n if (propKey === STYLE) {\n var lastStyle = lastProps[propKey];\n\n for (styleName in lastStyle) {\n if (lastStyle.hasOwnProperty(styleName)) {\n if (!styleUpdates) {\n styleUpdates = {};\n }\n\n styleUpdates[styleName] = '';\n }\n }\n } else if (propKey === DANGEROUSLY_SET_INNER_HTML || propKey === CHILDREN) ; else if ( propKey === SUPPRESS_CONTENT_EDITABLE_WARNING || propKey === SUPPRESS_HYDRATION_WARNING) ; else if (propKey === AUTOFOCUS) ; else if (registrationNameModules.hasOwnProperty(propKey)) {\n // This is a special case. If any listener updates we need to ensure\n // that the \"current\" fiber pointer gets updated so we need a commit\n // to update this element.\n if (!updatePayload) {\n updatePayload = [];\n }\n } else {\n // For all other deleted properties we add it to the queue. We use\n // the whitelist in the commit phase instead.\n (updatePayload = updatePayload || []).push(propKey, null);\n }\n }\n\n for (propKey in nextProps) {\n var nextProp = nextProps[propKey];\n var lastProp = lastProps != null ? lastProps[propKey] : undefined;\n\n if (!nextProps.hasOwnProperty(propKey) || nextProp === lastProp || nextProp == null && lastProp == null) {\n continue;\n }\n\n if (propKey === STYLE) {\n {\n if (nextProp) {\n // Freeze the next style object so that we can assume it won't be\n // mutated. We have already warned for this in the past.\n Object.freeze(nextProp);\n }\n }\n\n if (lastProp) {\n // Unset styles on `lastProp` but not on `nextProp`.\n for (styleName in lastProp) {\n if (lastProp.hasOwnProperty(styleName) && (!nextProp || !nextProp.hasOwnProperty(styleName))) {\n if (!styleUpdates) {\n styleUpdates = {};\n }\n\n styleUpdates[styleName] = '';\n }\n } // Update styles that changed since `lastProp`.\n\n\n for (styleName in nextProp) {\n if (nextProp.hasOwnProperty(styleName) && lastProp[styleName] !== nextProp[styleName]) {\n if (!styleUpdates) {\n styleUpdates = {};\n }\n\n styleUpdates[styleName] = nextProp[styleName];\n }\n }\n } else {\n // Relies on `updateStylesByID` not mutating `styleUpdates`.\n if (!styleUpdates) {\n if (!updatePayload) {\n updatePayload = [];\n }\n\n updatePayload.push(propKey, styleUpdates);\n }\n\n styleUpdates = nextProp;\n }\n } else if (propKey === DANGEROUSLY_SET_INNER_HTML) {\n var nextHtml = nextProp ? nextProp[HTML$1] : undefined;\n var lastHtml = lastProp ? lastProp[HTML$1] : undefined;\n\n if (nextHtml != null) {\n if (lastHtml !== nextHtml) {\n (updatePayload = updatePayload || []).push(propKey, nextHtml);\n }\n }\n } else if (propKey === CHILDREN) {\n if (lastProp !== nextProp && (typeof nextProp === 'string' || typeof nextProp === 'number')) {\n (updatePayload = updatePayload || []).push(propKey, '' + nextProp);\n }\n } else if ( propKey === SUPPRESS_CONTENT_EDITABLE_WARNING || propKey === SUPPRESS_HYDRATION_WARNING) ; else if (registrationNameModules.hasOwnProperty(propKey)) {\n if (nextProp != null) {\n // We eagerly listen to this even though we haven't committed yet.\n if ( typeof nextProp !== 'function') {\n warnForInvalidEventListener(propKey, nextProp);\n }\n\n ensureListeningTo(rootContainerElement, propKey);\n }\n\n if (!updatePayload && lastProp !== nextProp) {\n // This is a special case. If any listener updates we need to ensure\n // that the \"current\" props pointer gets updated so we need a commit\n // to update this element.\n updatePayload = [];\n }\n } else {\n // For any other property we always add it to the queue and then we\n // filter it out using the whitelist during the commit.\n (updatePayload = updatePayload || []).push(propKey, nextProp);\n }\n }\n\n if (styleUpdates) {\n {\n validateShorthandPropertyCollisionInDev(styleUpdates, nextProps[STYLE]);\n }\n\n (updatePayload = updatePayload || []).push(STYLE, styleUpdates);\n }\n\n return updatePayload;\n} // Apply the diff.\n\nfunction updateProperties(domElement, updatePayload, tag, lastRawProps, nextRawProps) {\n // Update checked *before* name.\n // In the middle of an update, it is possible to have multiple checked.\n // When a checked radio tries to change name, browser makes another radio's checked false.\n if (tag === 'input' && nextRawProps.type === 'radio' && nextRawProps.name != null) {\n updateChecked(domElement, nextRawProps);\n }\n\n var wasCustomComponentTag = isCustomComponent(tag, lastRawProps);\n var isCustomComponentTag = isCustomComponent(tag, nextRawProps); // Apply the diff.\n\n updateDOMProperties(domElement, updatePayload, wasCustomComponentTag, isCustomComponentTag); // TODO: Ensure that an update gets scheduled if any of the special props\n // changed.\n\n switch (tag) {\n case 'input':\n // Update the wrapper around inputs *after* updating props. This has to\n // happen after `updateDOMProperties`. Otherwise HTML5 input validations\n // raise warnings and prevent the new value from being assigned.\n updateWrapper(domElement, nextRawProps);\n break;\n\n case 'textarea':\n updateWrapper$1(domElement, nextRawProps);\n break;\n\n case 'select':\n // <select> value update needs to occur after <option> children\n // reconciliation\n postUpdateWrapper(domElement, nextRawProps);\n break;\n }\n}\n\nfunction getPossibleStandardName(propName) {\n {\n var lowerCasedName = propName.toLowerCase();\n\n if (!possibleStandardNames.hasOwnProperty(lowerCasedName)) {\n return null;\n }\n\n return possibleStandardNames[lowerCasedName] || null;\n }\n}\n\nfunction diffHydratedProperties(domElement, tag, rawProps, parentNamespace, rootContainerElement) {\n var isCustomComponentTag;\n var extraAttributeNames;\n\n {\n suppressHydrationWarning = rawProps[SUPPRESS_HYDRATION_WARNING] === true;\n isCustomComponentTag = isCustomComponent(tag, rawProps);\n validatePropertiesInDevelopment(tag, rawProps);\n } // TODO: Make sure that we check isMounted before firing any of these events.\n\n\n switch (tag) {\n case 'iframe':\n case 'object':\n case 'embed':\n trapBubbledEvent(TOP_LOAD, domElement);\n break;\n\n case 'video':\n case 'audio':\n // Create listener for each media event\n for (var i = 0; i < mediaEventTypes.length; i++) {\n trapBubbledEvent(mediaEventTypes[i], domElement);\n }\n\n break;\n\n case 'source':\n trapBubbledEvent(TOP_ERROR, domElement);\n break;\n\n case 'img':\n case 'image':\n case 'link':\n trapBubbledEvent(TOP_ERROR, domElement);\n trapBubbledEvent(TOP_LOAD, domElement);\n break;\n\n case 'form':\n trapBubbledEvent(TOP_RESET, domElement);\n trapBubbledEvent(TOP_SUBMIT, domElement);\n break;\n\n case 'details':\n trapBubbledEvent(TOP_TOGGLE, domElement);\n break;\n\n case 'input':\n initWrapperState(domElement, rawProps);\n trapBubbledEvent(TOP_INVALID, domElement); // For controlled components we always need to ensure we're listening\n // to onChange. Even if there is no listener.\n\n ensureListeningTo(rootContainerElement, 'onChange');\n break;\n\n case 'option':\n validateProps(domElement, rawProps);\n break;\n\n case 'select':\n initWrapperState$1(domElement, rawProps);\n trapBubbledEvent(TOP_INVALID, domElement); // For controlled components we always need to ensure we're listening\n // to onChange. Even if there is no listener.\n\n ensureListeningTo(rootContainerElement, 'onChange');\n break;\n\n case 'textarea':\n initWrapperState$2(domElement, rawProps);\n trapBubbledEvent(TOP_INVALID, domElement); // For controlled components we always need to ensure we're listening\n // to onChange. Even if there is no listener.\n\n ensureListeningTo(rootContainerElement, 'onChange');\n break;\n }\n\n assertValidProps(tag, rawProps);\n\n {\n extraAttributeNames = new Set();\n var attributes = domElement.attributes;\n\n for (var _i = 0; _i < attributes.length; _i++) {\n var name = attributes[_i].name.toLowerCase();\n\n switch (name) {\n // Built-in SSR attribute is whitelisted\n case 'data-reactroot':\n break;\n // Controlled attributes are not validated\n // TODO: Only ignore them on controlled tags.\n\n case 'value':\n break;\n\n case 'checked':\n break;\n\n case 'selected':\n break;\n\n default:\n // Intentionally use the original name.\n // See discussion in https://github.com/facebook/react/pull/10676.\n extraAttributeNames.add(attributes[_i].name);\n }\n }\n }\n\n var updatePayload = null;\n\n for (var propKey in rawProps) {\n if (!rawProps.hasOwnProperty(propKey)) {\n continue;\n }\n\n var nextProp = rawProps[propKey];\n\n if (propKey === CHILDREN) {\n // For text content children we compare against textContent. This\n // might match additional HTML that is hidden when we read it using\n // textContent. E.g. \"foo\" will match \"f<span>oo</span>\" but that still\n // satisfies our requirement. Our requirement is not to produce perfect\n // HTML and attributes. Ideally we should preserve structure but it's\n // ok not to if the visible content is still enough to indicate what\n // even listeners these nodes might be wired up to.\n // TODO: Warn if there is more than a single textNode as a child.\n // TODO: Should we use domElement.firstChild.nodeValue to compare?\n if (typeof nextProp === 'string') {\n if (domElement.textContent !== nextProp) {\n if ( !suppressHydrationWarning) {\n warnForTextDifference(domElement.textContent, nextProp);\n }\n\n updatePayload = [CHILDREN, nextProp];\n }\n } else if (typeof nextProp === 'number') {\n if (domElement.textContent !== '' + nextProp) {\n if ( !suppressHydrationWarning) {\n warnForTextDifference(domElement.textContent, nextProp);\n }\n\n updatePayload = [CHILDREN, '' + nextProp];\n }\n }\n } else if (registrationNameModules.hasOwnProperty(propKey)) {\n if (nextProp != null) {\n if ( typeof nextProp !== 'function') {\n warnForInvalidEventListener(propKey, nextProp);\n }\n\n ensureListeningTo(rootContainerElement, propKey);\n }\n } else if ( // Convince Flow we've calculated it (it's DEV-only in this method.)\n typeof isCustomComponentTag === 'boolean') {\n // Validate that the properties correspond to their expected values.\n var serverValue = void 0;\n var propertyInfo = getPropertyInfo(propKey);\n\n if (suppressHydrationWarning) ; else if ( propKey === SUPPRESS_CONTENT_EDITABLE_WARNING || propKey === SUPPRESS_HYDRATION_WARNING || // Controlled attributes are not validated\n // TODO: Only ignore them on controlled tags.\n propKey === 'value' || propKey === 'checked' || propKey === 'selected') ; else if (propKey === DANGEROUSLY_SET_INNER_HTML) {\n var serverHTML = domElement.innerHTML;\n var nextHtml = nextProp ? nextProp[HTML$1] : undefined;\n var expectedHTML = normalizeHTML(domElement, nextHtml != null ? nextHtml : '');\n\n if (expectedHTML !== serverHTML) {\n warnForPropDifference(propKey, serverHTML, expectedHTML);\n }\n } else if (propKey === STYLE) {\n // $FlowFixMe - Should be inferred as not undefined.\n extraAttributeNames.delete(propKey);\n\n if (canDiffStyleForHydrationWarning) {\n var expectedStyle = createDangerousStringForStyles(nextProp);\n serverValue = domElement.getAttribute('style');\n\n if (expectedStyle !== serverValue) {\n warnForPropDifference(propKey, serverValue, expectedStyle);\n }\n }\n } else if (isCustomComponentTag) {\n // $FlowFixMe - Should be inferred as not undefined.\n extraAttributeNames.delete(propKey.toLowerCase());\n serverValue = getValueForAttribute(domElement, propKey, nextProp);\n\n if (nextProp !== serverValue) {\n warnForPropDifference(propKey, serverValue, nextProp);\n }\n } else if (!shouldIgnoreAttribute(propKey, propertyInfo, isCustomComponentTag) && !shouldRemoveAttribute(propKey, nextProp, propertyInfo, isCustomComponentTag)) {\n var isMismatchDueToBadCasing = false;\n\n if (propertyInfo !== null) {\n // $FlowFixMe - Should be inferred as not undefined.\n extraAttributeNames.delete(propertyInfo.attributeName);\n serverValue = getValueForProperty(domElement, propKey, nextProp, propertyInfo);\n } else {\n var ownNamespace = parentNamespace;\n\n if (ownNamespace === HTML_NAMESPACE$1) {\n ownNamespace = getIntrinsicNamespace(tag);\n }\n\n if (ownNamespace === HTML_NAMESPACE$1) {\n // $FlowFixMe - Should be inferred as not undefined.\n extraAttributeNames.delete(propKey.toLowerCase());\n } else {\n var standardName = getPossibleStandardName(propKey);\n\n if (standardName !== null && standardName !== propKey) {\n // If an SVG prop is supplied with bad casing, it will\n // be successfully parsed from HTML, but will produce a mismatch\n // (and would be incorrectly rendered on the client).\n // However, we already warn about bad casing elsewhere.\n // So we'll skip the misleading extra mismatch warning in this case.\n isMismatchDueToBadCasing = true; // $FlowFixMe - Should be inferred as not undefined.\n\n extraAttributeNames.delete(standardName);\n } // $FlowFixMe - Should be inferred as not undefined.\n\n\n extraAttributeNames.delete(propKey);\n }\n\n serverValue = getValueForAttribute(domElement, propKey, nextProp);\n }\n\n if (nextProp !== serverValue && !isMismatchDueToBadCasing) {\n warnForPropDifference(propKey, serverValue, nextProp);\n }\n }\n }\n }\n\n {\n // $FlowFixMe - Should be inferred as not undefined.\n if (extraAttributeNames.size > 0 && !suppressHydrationWarning) {\n // $FlowFixMe - Should be inferred as not undefined.\n warnForExtraAttributes(extraAttributeNames);\n }\n }\n\n switch (tag) {\n case 'input':\n // TODO: Make sure we check if this is still unmounted or do any clean\n // up necessary since we never stop tracking anymore.\n track(domElement);\n postMountWrapper(domElement, rawProps, true);\n break;\n\n case 'textarea':\n // TODO: Make sure we check if this is still unmounted or do any clean\n // up necessary since we never stop tracking anymore.\n track(domElement);\n postMountWrapper$3(domElement);\n break;\n\n case 'select':\n case 'option':\n // For input and textarea we current always set the value property at\n // post mount to force it to diverge from attributes. However, for\n // option and select we don't quite do the same thing and select\n // is not resilient to the DOM state changing so we don't do that here.\n // TODO: Consider not doing this for input and textarea.\n break;\n\n default:\n if (typeof rawProps.onClick === 'function') {\n // TODO: This cast may not be sound for SVG, MathML or custom elements.\n trapClickOnNonInteractiveElement(domElement);\n }\n\n break;\n }\n\n return updatePayload;\n}\nfunction diffHydratedText(textNode, text) {\n var isDifferent = textNode.nodeValue !== text;\n return isDifferent;\n}\nfunction warnForUnmatchedText(textNode, text) {\n {\n warnForTextDifference(textNode.nodeValue, text);\n }\n}\nfunction warnForDeletedHydratableElement(parentNode, child) {\n {\n if (didWarnInvalidHydration) {\n return;\n }\n\n didWarnInvalidHydration = true;\n\n error('Did not expect server HTML to contain a <%s> in <%s>.', child.nodeName.toLowerCase(), parentNode.nodeName.toLowerCase());\n }\n}\nfunction warnForDeletedHydratableText(parentNode, child) {\n {\n if (didWarnInvalidHydration) {\n return;\n }\n\n didWarnInvalidHydration = true;\n\n error('Did not expect server HTML to contain the text node \"%s\" in <%s>.', child.nodeValue, parentNode.nodeName.toLowerCase());\n }\n}\nfunction warnForInsertedHydratedElement(parentNode, tag, props) {\n {\n if (didWarnInvalidHydration) {\n return;\n }\n\n didWarnInvalidHydration = true;\n\n error('Expected server HTML to contain a matching <%s> in <%s>.', tag, parentNode.nodeName.toLowerCase());\n }\n}\nfunction warnForInsertedHydratedText(parentNode, text) {\n {\n if (text === '') {\n // We expect to insert empty text nodes since they're not represented in\n // the HTML.\n // TODO: Remove this special case if we can just avoid inserting empty\n // text nodes.\n return;\n }\n\n if (didWarnInvalidHydration) {\n return;\n }\n\n didWarnInvalidHydration = true;\n\n error('Expected server HTML to contain a matching text node for \"%s\" in <%s>.', text, parentNode.nodeName.toLowerCase());\n }\n}\nfunction restoreControlledState$3(domElement, tag, props) {\n switch (tag) {\n case 'input':\n restoreControlledState(domElement, props);\n return;\n\n case 'textarea':\n restoreControlledState$2(domElement, props);\n return;\n\n case 'select':\n restoreControlledState$1(domElement, props);\n return;\n }\n}\n\nfunction getActiveElement(doc) {\n doc = doc || (typeof document !== 'undefined' ? document : undefined);\n\n if (typeof doc === 'undefined') {\n return null;\n }\n\n try {\n return doc.activeElement || doc.body;\n } catch (e) {\n return doc.body;\n }\n}\n\n/**\n * Given any node return the first leaf node without children.\n *\n * @param {DOMElement|DOMTextNode} node\n * @return {DOMElement|DOMTextNode}\n */\n\nfunction getLeafNode(node) {\n while (node && node.firstChild) {\n node = node.firstChild;\n }\n\n return node;\n}\n/**\n * Get the next sibling within a container. This will walk up the\n * DOM if a node's siblings have been exhausted.\n *\n * @param {DOMElement|DOMTextNode} node\n * @return {?DOMElement|DOMTextNode}\n */\n\n\nfunction getSiblingNode(node) {\n while (node) {\n if (node.nextSibling) {\n return node.nextSibling;\n }\n\n node = node.parentNode;\n }\n}\n/**\n * Get object describing the nodes which contain characters at offset.\n *\n * @param {DOMElement|DOMTextNode} root\n * @param {number} offset\n * @return {?object}\n */\n\n\nfunction getNodeForCharacterOffset(root, offset) {\n var node = getLeafNode(root);\n var nodeStart = 0;\n var nodeEnd = 0;\n\n while (node) {\n if (node.nodeType === TEXT_NODE) {\n nodeEnd = nodeStart + node.textContent.length;\n\n if (nodeStart <= offset && nodeEnd >= offset) {\n return {\n node: node,\n offset: offset - nodeStart\n };\n }\n\n nodeStart = nodeEnd;\n }\n\n node = getLeafNode(getSiblingNode(node));\n }\n}\n\n/**\n * @param {DOMElement} outerNode\n * @return {?object}\n */\n\nfunction getOffsets(outerNode) {\n var ownerDocument = outerNode.ownerDocument;\n var win = ownerDocument && ownerDocument.defaultView || window;\n var selection = win.getSelection && win.getSelection();\n\n if (!selection || selection.rangeCount === 0) {\n return null;\n }\n\n var anchorNode = selection.anchorNode,\n anchorOffset = selection.anchorOffset,\n focusNode = selection.focusNode,\n focusOffset = selection.focusOffset; // In Firefox, anchorNode and focusNode can be \"anonymous divs\", e.g. the\n // up/down buttons on an <input type=\"number\">. Anonymous divs do not seem to\n // expose properties, triggering a \"Permission denied error\" if any of its\n // properties are accessed. The only seemingly possible way to avoid erroring\n // is to access a property that typically works for non-anonymous divs and\n // catch any error that may otherwise arise. See\n // https://bugzilla.mozilla.org/show_bug.cgi?id=208427\n\n try {\n /* eslint-disable no-unused-expressions */\n anchorNode.nodeType;\n focusNode.nodeType;\n /* eslint-enable no-unused-expressions */\n } catch (e) {\n return null;\n }\n\n return getModernOffsetsFromPoints(outerNode, anchorNode, anchorOffset, focusNode, focusOffset);\n}\n/**\n * Returns {start, end} where `start` is the character/codepoint index of\n * (anchorNode, anchorOffset) within the textContent of `outerNode`, and\n * `end` is the index of (focusNode, focusOffset).\n *\n * Returns null if you pass in garbage input but we should probably just crash.\n *\n * Exported only for testing.\n */\n\nfunction getModernOffsetsFromPoints(outerNode, anchorNode, anchorOffset, focusNode, focusOffset) {\n var length = 0;\n var start = -1;\n var end = -1;\n var indexWithinAnchor = 0;\n var indexWithinFocus = 0;\n var node = outerNode;\n var parentNode = null;\n\n outer: while (true) {\n var next = null;\n\n while (true) {\n if (node === anchorNode && (anchorOffset === 0 || node.nodeType === TEXT_NODE)) {\n start = length + anchorOffset;\n }\n\n if (node === focusNode && (focusOffset === 0 || node.nodeType === TEXT_NODE)) {\n end = length + focusOffset;\n }\n\n if (node.nodeType === TEXT_NODE) {\n length += node.nodeValue.length;\n }\n\n if ((next = node.firstChild) === null) {\n break;\n } // Moving from `node` to its first child `next`.\n\n\n parentNode = node;\n node = next;\n }\n\n while (true) {\n if (node === outerNode) {\n // If `outerNode` has children, this is always the second time visiting\n // it. If it has no children, this is still the first loop, and the only\n // valid selection is anchorNode and focusNode both equal to this node\n // and both offsets 0, in which case we will have handled above.\n break outer;\n }\n\n if (parentNode === anchorNode && ++indexWithinAnchor === anchorOffset) {\n start = length;\n }\n\n if (parentNode === focusNode && ++indexWithinFocus === focusOffset) {\n end = length;\n }\n\n if ((next = node.nextSibling) !== null) {\n break;\n }\n\n node = parentNode;\n parentNode = node.parentNode;\n } // Moving from `node` to its next sibling `next`.\n\n\n node = next;\n }\n\n if (start === -1 || end === -1) {\n // This should never happen. (Would happen if the anchor/focus nodes aren't\n // actually inside the passed-in node.)\n return null;\n }\n\n return {\n start: start,\n end: end\n };\n}\n/**\n * In modern non-IE browsers, we can support both forward and backward\n * selections.\n *\n * Note: IE10+ supports the Selection object, but it does not support\n * the `extend` method, which means that even in modern IE, it's not possible\n * to programmatically create a backward selection. Thus, for all IE\n * versions, we use the old IE API to create our selections.\n *\n * @param {DOMElement|DOMTextNode} node\n * @param {object} offsets\n */\n\nfunction setOffsets(node, offsets) {\n var doc = node.ownerDocument || document;\n var win = doc && doc.defaultView || window; // Edge fails with \"Object expected\" in some scenarios.\n // (For instance: TinyMCE editor used in a list component that supports pasting to add more,\n // fails when pasting 100+ items)\n\n if (!win.getSelection) {\n return;\n }\n\n var selection = win.getSelection();\n var length = node.textContent.length;\n var start = Math.min(offsets.start, length);\n var end = offsets.end === undefined ? start : Math.min(offsets.end, length); // IE 11 uses modern selection, but doesn't support the extend method.\n // Flip backward selections, so we can set with a single range.\n\n if (!selection.extend && start > end) {\n var temp = end;\n end = start;\n start = temp;\n }\n\n var startMarker = getNodeForCharacterOffset(node, start);\n var endMarker = getNodeForCharacterOffset(node, end);\n\n if (startMarker && endMarker) {\n if (selection.rangeCount === 1 && selection.anchorNode === startMarker.node && selection.anchorOffset === startMarker.offset && selection.focusNode === endMarker.node && selection.focusOffset === endMarker.offset) {\n return;\n }\n\n var range = doc.createRange();\n range.setStart(startMarker.node, startMarker.offset);\n selection.removeAllRanges();\n\n if (start > end) {\n selection.addRange(range);\n selection.extend(endMarker.node, endMarker.offset);\n } else {\n range.setEnd(endMarker.node, endMarker.offset);\n selection.addRange(range);\n }\n }\n}\n\nfunction isTextNode(node) {\n return node && node.nodeType === TEXT_NODE;\n}\n\nfunction containsNode(outerNode, innerNode) {\n if (!outerNode || !innerNode) {\n return false;\n } else if (outerNode === innerNode) {\n return true;\n } else if (isTextNode(outerNode)) {\n return false;\n } else if (isTextNode(innerNode)) {\n return containsNode(outerNode, innerNode.parentNode);\n } else if ('contains' in outerNode) {\n return outerNode.contains(innerNode);\n } else if (outerNode.compareDocumentPosition) {\n return !!(outerNode.compareDocumentPosition(innerNode) & 16);\n } else {\n return false;\n }\n}\n\nfunction isInDocument(node) {\n return node && node.ownerDocument && containsNode(node.ownerDocument.documentElement, node);\n}\n\nfunction isSameOriginFrame(iframe) {\n try {\n // Accessing the contentDocument of a HTMLIframeElement can cause the browser\n // to throw, e.g. if it has a cross-origin src attribute.\n // Safari will show an error in the console when the access results in \"Blocked a frame with origin\". e.g:\n // iframe.contentDocument.defaultView;\n // A safety way is to access one of the cross origin properties: Window or Location\n // Which might result in \"SecurityError\" DOM Exception and it is compatible to Safari.\n // https://html.spec.whatwg.org/multipage/browsers.html#integration-with-idl\n return typeof iframe.contentWindow.location.href === 'string';\n } catch (err) {\n return false;\n }\n}\n\nfunction getActiveElementDeep() {\n var win = window;\n var element = getActiveElement();\n\n while (element instanceof win.HTMLIFrameElement) {\n if (isSameOriginFrame(element)) {\n win = element.contentWindow;\n } else {\n return element;\n }\n\n element = getActiveElement(win.document);\n }\n\n return element;\n}\n/**\n * @ReactInputSelection: React input selection module. Based on Selection.js,\n * but modified to be suitable for react and has a couple of bug fixes (doesn't\n * assume buttons have range selections allowed).\n * Input selection module for React.\n */\n\n/**\n * @hasSelectionCapabilities: we get the element types that support selection\n * from https://html.spec.whatwg.org/#do-not-apply, looking at `selectionStart`\n * and `selectionEnd` rows.\n */\n\n\nfunction hasSelectionCapabilities(elem) {\n var nodeName = elem && elem.nodeName && elem.nodeName.toLowerCase();\n return nodeName && (nodeName === 'input' && (elem.type === 'text' || elem.type === 'search' || elem.type === 'tel' || elem.type === 'url' || elem.type === 'password') || nodeName === 'textarea' || elem.contentEditable === 'true');\n}\nfunction getSelectionInformation() {\n var focusedElem = getActiveElementDeep();\n return {\n // Used by Flare\n activeElementDetached: null,\n focusedElem: focusedElem,\n selectionRange: hasSelectionCapabilities(focusedElem) ? getSelection(focusedElem) : null\n };\n}\n/**\n * @restoreSelection: If any selection information was potentially lost,\n * restore it. This is useful when performing operations that could remove dom\n * nodes and place them back in, resulting in focus being lost.\n */\n\nfunction restoreSelection(priorSelectionInformation) {\n var curFocusedElem = getActiveElementDeep();\n var priorFocusedElem = priorSelectionInformation.focusedElem;\n var priorSelectionRange = priorSelectionInformation.selectionRange;\n\n if (curFocusedElem !== priorFocusedElem && isInDocument(priorFocusedElem)) {\n if (priorSelectionRange !== null && hasSelectionCapabilities(priorFocusedElem)) {\n setSelection(priorFocusedElem, priorSelectionRange);\n } // Focusing a node can change the scroll position, which is undesirable\n\n\n var ancestors = [];\n var ancestor = priorFocusedElem;\n\n while (ancestor = ancestor.parentNode) {\n if (ancestor.nodeType === ELEMENT_NODE) {\n ancestors.push({\n element: ancestor,\n left: ancestor.scrollLeft,\n top: ancestor.scrollTop\n });\n }\n }\n\n if (typeof priorFocusedElem.focus === 'function') {\n priorFocusedElem.focus();\n }\n\n for (var i = 0; i < ancestors.length; i++) {\n var info = ancestors[i];\n info.element.scrollLeft = info.left;\n info.element.scrollTop = info.top;\n }\n }\n}\n/**\n * @getSelection: Gets the selection bounds of a focused textarea, input or\n * contentEditable node.\n * -@input: Look up selection bounds of this input\n * -@return {start: selectionStart, end: selectionEnd}\n */\n\nfunction getSelection(input) {\n var selection;\n\n if ('selectionStart' in input) {\n // Modern browser with input or textarea.\n selection = {\n start: input.selectionStart,\n end: input.selectionEnd\n };\n } else {\n // Content editable or old IE textarea.\n selection = getOffsets(input);\n }\n\n return selection || {\n start: 0,\n end: 0\n };\n}\n/**\n * @setSelection: Sets the selection bounds of a textarea or input and focuses\n * the input.\n * -@input Set selection bounds of this input or textarea\n * -@offsets Object of same form that is returned from get*\n */\n\nfunction setSelection(input, offsets) {\n var start = offsets.start,\n end = offsets.end;\n\n if (end === undefined) {\n end = start;\n }\n\n if ('selectionStart' in input) {\n input.selectionStart = start;\n input.selectionEnd = Math.min(end, input.value.length);\n } else {\n setOffsets(input, offsets);\n }\n}\n\nvar validateDOMNesting = function () {};\n\nvar updatedAncestorInfo = function () {};\n\n{\n // This validation code was written based on the HTML5 parsing spec:\n // https://html.spec.whatwg.org/multipage/syntax.html#has-an-element-in-scope\n //\n // Note: this does not catch all invalid nesting, nor does it try to (as it's\n // not clear what practical benefit doing so provides); instead, we warn only\n // for cases where the parser will give a parse tree differing from what React\n // intended. For example, <b><div></div></b> is invalid but we don't warn\n // because it still parses correctly; we do warn for other cases like nested\n // <p> tags where the beginning of the second element implicitly closes the\n // first, causing a confusing mess.\n // https://html.spec.whatwg.org/multipage/syntax.html#special\n var specialTags = ['address', 'applet', 'area', 'article', 'aside', 'base', 'basefont', 'bgsound', 'blockquote', 'body', 'br', 'button', 'caption', 'center', 'col', 'colgroup', 'dd', 'details', 'dir', 'div', 'dl', 'dt', 'embed', 'fieldset', 'figcaption', 'figure', 'footer', 'form', 'frame', 'frameset', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'head', 'header', 'hgroup', 'hr', 'html', 'iframe', 'img', 'input', 'isindex', 'li', 'link', 'listing', 'main', 'marquee', 'menu', 'menuitem', 'meta', 'nav', 'noembed', 'noframes', 'noscript', 'object', 'ol', 'p', 'param', 'plaintext', 'pre', 'script', 'section', 'select', 'source', 'style', 'summary', 'table', 'tbody', 'td', 'template', 'textarea', 'tfoot', 'th', 'thead', 'title', 'tr', 'track', 'ul', 'wbr', 'xmp']; // https://html.spec.whatwg.org/multipage/syntax.html#has-an-element-in-scope\n\n var inScopeTags = ['applet', 'caption', 'html', 'table', 'td', 'th', 'marquee', 'object', 'template', // https://html.spec.whatwg.org/multipage/syntax.html#html-integration-point\n // TODO: Distinguish by namespace here -- for <title>, including it here\n // errs on the side of fewer warnings\n 'foreignObject', 'desc', 'title']; // https://html.spec.whatwg.org/multipage/syntax.html#has-an-element-in-button-scope\n\n var buttonScopeTags = inScopeTags.concat(['button']); // https://html.spec.whatwg.org/multipage/syntax.html#generate-implied-end-tags\n\n var impliedEndTags = ['dd', 'dt', 'li', 'option', 'optgroup', 'p', 'rp', 'rt'];\n var emptyAncestorInfo = {\n current: null,\n formTag: null,\n aTagInScope: null,\n buttonTagInScope: null,\n nobrTagInScope: null,\n pTagInButtonScope: null,\n listItemTagAutoclosing: null,\n dlItemTagAutoclosing: null\n };\n\n updatedAncestorInfo = function (oldInfo, tag) {\n var ancestorInfo = _assign({}, oldInfo || emptyAncestorInfo);\n\n var info = {\n tag: tag\n };\n\n if (inScopeTags.indexOf(tag) !== -1) {\n ancestorInfo.aTagInScope = null;\n ancestorInfo.buttonTagInScope = null;\n ancestorInfo.nobrTagInScope = null;\n }\n\n if (buttonScopeTags.indexOf(tag) !== -1) {\n ancestorInfo.pTagInButtonScope = null;\n } // See rules for 'li', 'dd', 'dt' start tags in\n // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-inbody\n\n\n if (specialTags.indexOf(tag) !== -1 && tag !== 'address' && tag !== 'div' && tag !== 'p') {\n ancestorInfo.listItemTagAutoclosing = null;\n ancestorInfo.dlItemTagAutoclosing = null;\n }\n\n ancestorInfo.current = info;\n\n if (tag === 'form') {\n ancestorInfo.formTag = info;\n }\n\n if (tag === 'a') {\n ancestorInfo.aTagInScope = info;\n }\n\n if (tag === 'button') {\n ancestorInfo.buttonTagInScope = info;\n }\n\n if (tag === 'nobr') {\n ancestorInfo.nobrTagInScope = info;\n }\n\n if (tag === 'p') {\n ancestorInfo.pTagInButtonScope = info;\n }\n\n if (tag === 'li') {\n ancestorInfo.listItemTagAutoclosing = info;\n }\n\n if (tag === 'dd' || tag === 'dt') {\n ancestorInfo.dlItemTagAutoclosing = info;\n }\n\n return ancestorInfo;\n };\n /**\n * Returns whether\n */\n\n\n var isTagValidWithParent = function (tag, parentTag) {\n // First, let's check if we're in an unusual parsing mode...\n switch (parentTag) {\n // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-inselect\n case 'select':\n return tag === 'option' || tag === 'optgroup' || tag === '#text';\n\n case 'optgroup':\n return tag === 'option' || tag === '#text';\n // Strictly speaking, seeing an <option> doesn't mean we're in a <select>\n // but\n\n case 'option':\n return tag === '#text';\n // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-intd\n // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-incaption\n // No special behavior since these rules fall back to \"in body\" mode for\n // all except special table nodes which cause bad parsing behavior anyway.\n // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-intr\n\n case 'tr':\n return tag === 'th' || tag === 'td' || tag === 'style' || tag === 'script' || tag === 'template';\n // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-intbody\n\n case 'tbody':\n case 'thead':\n case 'tfoot':\n return tag === 'tr' || tag === 'style' || tag === 'script' || tag === 'template';\n // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-incolgroup\n\n case 'colgroup':\n return tag === 'col' || tag === 'template';\n // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-intable\n\n case 'table':\n return tag === 'caption' || tag === 'colgroup' || tag === 'tbody' || tag === 'tfoot' || tag === 'thead' || tag === 'style' || tag === 'script' || tag === 'template';\n // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-inhead\n\n case 'head':\n return tag === 'base' || tag === 'basefont' || tag === 'bgsound' || tag === 'link' || tag === 'meta' || tag === 'title' || tag === 'noscript' || tag === 'noframes' || tag === 'style' || tag === 'script' || tag === 'template';\n // https://html.spec.whatwg.org/multipage/semantics.html#the-html-element\n\n case 'html':\n return tag === 'head' || tag === 'body' || tag === 'frameset';\n\n case 'frameset':\n return tag === 'frame';\n\n case '#document':\n return tag === 'html';\n } // Probably in the \"in body\" parsing mode, so we outlaw only tag combos\n // where the parsing rules cause implicit opens or closes to be added.\n // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-inbody\n\n\n switch (tag) {\n case 'h1':\n case 'h2':\n case 'h3':\n case 'h4':\n case 'h5':\n case 'h6':\n return parentTag !== 'h1' && parentTag !== 'h2' && parentTag !== 'h3' && parentTag !== 'h4' && parentTag !== 'h5' && parentTag !== 'h6';\n\n case 'rp':\n case 'rt':\n return impliedEndTags.indexOf(parentTag) === -1;\n\n case 'body':\n case 'caption':\n case 'col':\n case 'colgroup':\n case 'frameset':\n case 'frame':\n case 'head':\n case 'html':\n case 'tbody':\n case 'td':\n case 'tfoot':\n case 'th':\n case 'thead':\n case 'tr':\n // These tags are only valid with a few parents that have special child\n // parsing rules -- if we're down here, then none of those matched and\n // so we allow it only if we don't know what the parent is, as all other\n // cases are invalid.\n return parentTag == null;\n }\n\n return true;\n };\n /**\n * Returns whether\n */\n\n\n var findInvalidAncestorForTag = function (tag, ancestorInfo) {\n switch (tag) {\n case 'address':\n case 'article':\n case 'aside':\n case 'blockquote':\n case 'center':\n case 'details':\n case 'dialog':\n case 'dir':\n case 'div':\n case 'dl':\n case 'fieldset':\n case 'figcaption':\n case 'figure':\n case 'footer':\n case 'header':\n case 'hgroup':\n case 'main':\n case 'menu':\n case 'nav':\n case 'ol':\n case 'p':\n case 'section':\n case 'summary':\n case 'ul':\n case 'pre':\n case 'listing':\n case 'table':\n case 'hr':\n case 'xmp':\n case 'h1':\n case 'h2':\n case 'h3':\n case 'h4':\n case 'h5':\n case 'h6':\n return ancestorInfo.pTagInButtonScope;\n\n case 'form':\n return ancestorInfo.formTag || ancestorInfo.pTagInButtonScope;\n\n case 'li':\n return ancestorInfo.listItemTagAutoclosing;\n\n case 'dd':\n case 'dt':\n return ancestorInfo.dlItemTagAutoclosing;\n\n case 'button':\n return ancestorInfo.buttonTagInScope;\n\n case 'a':\n // Spec says something about storing a list of markers, but it sounds\n // equivalent to this check.\n return ancestorInfo.aTagInScope;\n\n case 'nobr':\n return ancestorInfo.nobrTagInScope;\n }\n\n return null;\n };\n\n var didWarn$1 = {};\n\n validateDOMNesting = function (childTag, childText, ancestorInfo) {\n ancestorInfo = ancestorInfo || emptyAncestorInfo;\n var parentInfo = ancestorInfo.current;\n var parentTag = parentInfo && parentInfo.tag;\n\n if (childText != null) {\n if (childTag != null) {\n error('validateDOMNesting: when childText is passed, childTag should be null');\n }\n\n childTag = '#text';\n }\n\n var invalidParent = isTagValidWithParent(childTag, parentTag) ? null : parentInfo;\n var invalidAncestor = invalidParent ? null : findInvalidAncestorForTag(childTag, ancestorInfo);\n var invalidParentOrAncestor = invalidParent || invalidAncestor;\n\n if (!invalidParentOrAncestor) {\n return;\n }\n\n var ancestorTag = invalidParentOrAncestor.tag;\n var addendum = getCurrentFiberStackInDev();\n var warnKey = !!invalidParent + '|' + childTag + '|' + ancestorTag + '|' + addendum;\n\n if (didWarn$1[warnKey]) {\n return;\n }\n\n didWarn$1[warnKey] = true;\n var tagDisplayName = childTag;\n var whitespaceInfo = '';\n\n if (childTag === '#text') {\n if (/\\S/.test(childText)) {\n tagDisplayName = 'Text nodes';\n } else {\n tagDisplayName = 'Whitespace text nodes';\n whitespaceInfo = \" Make sure you don't have any extra whitespace between tags on \" + 'each line of your source code.';\n }\n } else {\n tagDisplayName = '<' + childTag + '>';\n }\n\n if (invalidParent) {\n var info = '';\n\n if (ancestorTag === 'table' && childTag === 'tr') {\n info += ' Add a <tbody>, <thead> or <tfoot> to your code to match the DOM tree generated by ' + 'the browser.';\n }\n\n error('validateDOMNesting(...): %s cannot appear as a child of <%s>.%s%s', tagDisplayName, ancestorTag, whitespaceInfo, info);\n } else {\n error('validateDOMNesting(...): %s cannot appear as a descendant of ' + '<%s>.', tagDisplayName, ancestorTag);\n }\n };\n}\n\nvar SUPPRESS_HYDRATION_WARNING$1;\n\n{\n SUPPRESS_HYDRATION_WARNING$1 = 'suppressHydrationWarning';\n}\n\nvar SUSPENSE_START_DATA = '$';\nvar SUSPENSE_END_DATA = '/$';\nvar SUSPENSE_PENDING_START_DATA = '$?';\nvar SUSPENSE_FALLBACK_START_DATA = '$!';\nvar STYLE$1 = 'style';\nvar eventsEnabled = null;\nvar selectionInformation = null;\n\nfunction shouldAutoFocusHostComponent(type, props) {\n switch (type) {\n case 'button':\n case 'input':\n case 'select':\n case 'textarea':\n return !!props.autoFocus;\n }\n\n return false;\n}\nfunction getRootHostContext(rootContainerInstance) {\n var type;\n var namespace;\n var nodeType = rootContainerInstance.nodeType;\n\n switch (nodeType) {\n case DOCUMENT_NODE:\n case DOCUMENT_FRAGMENT_NODE:\n {\n type = nodeType === DOCUMENT_NODE ? '#document' : '#fragment';\n var root = rootContainerInstance.documentElement;\n namespace = root ? root.namespaceURI : getChildNamespace(null, '');\n break;\n }\n\n default:\n {\n var container = nodeType === COMMENT_NODE ? rootContainerInstance.parentNode : rootContainerInstance;\n var ownNamespace = container.namespaceURI || null;\n type = container.tagName;\n namespace = getChildNamespace(ownNamespace, type);\n break;\n }\n }\n\n {\n var validatedTag = type.toLowerCase();\n var ancestorInfo = updatedAncestorInfo(null, validatedTag);\n return {\n namespace: namespace,\n ancestorInfo: ancestorInfo\n };\n }\n}\nfunction getChildHostContext(parentHostContext, type, rootContainerInstance) {\n {\n var parentHostContextDev = parentHostContext;\n var namespace = getChildNamespace(parentHostContextDev.namespace, type);\n var ancestorInfo = updatedAncestorInfo(parentHostContextDev.ancestorInfo, type);\n return {\n namespace: namespace,\n ancestorInfo: ancestorInfo\n };\n }\n}\nfunction getPublicInstance(instance) {\n return instance;\n}\nfunction prepareForCommit(containerInfo) {\n eventsEnabled = isEnabled();\n selectionInformation = getSelectionInformation();\n setEnabled(false);\n}\nfunction resetAfterCommit(containerInfo) {\n restoreSelection(selectionInformation);\n setEnabled(eventsEnabled);\n eventsEnabled = null;\n\n selectionInformation = null;\n}\nfunction createInstance(type, props, rootContainerInstance, hostContext, internalInstanceHandle) {\n var parentNamespace;\n\n {\n // TODO: take namespace into account when validating.\n var hostContextDev = hostContext;\n validateDOMNesting(type, null, hostContextDev.ancestorInfo);\n\n if (typeof props.children === 'string' || typeof props.children === 'number') {\n var string = '' + props.children;\n var ownAncestorInfo = updatedAncestorInfo(hostContextDev.ancestorInfo, type);\n validateDOMNesting(null, string, ownAncestorInfo);\n }\n\n parentNamespace = hostContextDev.namespace;\n }\n\n var domElement = createElement(type, props, rootContainerInstance, parentNamespace);\n precacheFiberNode(internalInstanceHandle, domElement);\n updateFiberProps(domElement, props);\n return domElement;\n}\nfunction appendInitialChild(parentInstance, child) {\n parentInstance.appendChild(child);\n}\nfunction finalizeInitialChildren(domElement, type, props, rootContainerInstance, hostContext) {\n setInitialProperties(domElement, type, props, rootContainerInstance);\n return shouldAutoFocusHostComponent(type, props);\n}\nfunction prepareUpdate(domElement, type, oldProps, newProps, rootContainerInstance, hostContext) {\n {\n var hostContextDev = hostContext;\n\n if (typeof newProps.children !== typeof oldProps.children && (typeof newProps.children === 'string' || typeof newProps.children === 'number')) {\n var string = '' + newProps.children;\n var ownAncestorInfo = updatedAncestorInfo(hostContextDev.ancestorInfo, type);\n validateDOMNesting(null, string, ownAncestorInfo);\n }\n }\n\n return diffProperties(domElement, type, oldProps, newProps, rootContainerInstance);\n}\nfunction shouldSetTextContent(type, props) {\n return type === 'textarea' || type === 'option' || type === 'noscript' || typeof props.children === 'string' || typeof props.children === 'number' || typeof props.dangerouslySetInnerHTML === 'object' && props.dangerouslySetInnerHTML !== null && props.dangerouslySetInnerHTML.__html != null;\n}\nfunction shouldDeprioritizeSubtree(type, props) {\n return !!props.hidden;\n}\nfunction createTextInstance(text, rootContainerInstance, hostContext, internalInstanceHandle) {\n {\n var hostContextDev = hostContext;\n validateDOMNesting(null, text, hostContextDev.ancestorInfo);\n }\n\n var textNode = createTextNode(text, rootContainerInstance);\n precacheFiberNode(internalInstanceHandle, textNode);\n return textNode;\n}\n// if a component just imports ReactDOM (e.g. for findDOMNode).\n// Some environments might not have setTimeout or clearTimeout.\n\nvar scheduleTimeout = typeof setTimeout === 'function' ? setTimeout : undefined;\nvar cancelTimeout = typeof clearTimeout === 'function' ? clearTimeout : undefined;\nvar noTimeout = -1; // -------------------\nfunction commitMount(domElement, type, newProps, internalInstanceHandle) {\n // Despite the naming that might imply otherwise, this method only\n // fires if there is an `Update` effect scheduled during mounting.\n // This happens if `finalizeInitialChildren` returns `true` (which it\n // does to implement the `autoFocus` attribute on the client). But\n // there are also other cases when this might happen (such as patching\n // up text content during hydration mismatch). So we'll check this again.\n if (shouldAutoFocusHostComponent(type, newProps)) {\n domElement.focus();\n }\n}\nfunction commitUpdate(domElement, updatePayload, type, oldProps, newProps, internalInstanceHandle) {\n // Update the props handle so that we know which props are the ones with\n // with current event handlers.\n updateFiberProps(domElement, newProps); // Apply the diff to the DOM node.\n\n updateProperties(domElement, updatePayload, type, oldProps, newProps);\n}\nfunction resetTextContent(domElement) {\n setTextContent(domElement, '');\n}\nfunction commitTextUpdate(textInstance, oldText, newText) {\n textInstance.nodeValue = newText;\n}\nfunction appendChild(parentInstance, child) {\n parentInstance.appendChild(child);\n}\nfunction appendChildToContainer(container, child) {\n var parentNode;\n\n if (container.nodeType === COMMENT_NODE) {\n parentNode = container.parentNode;\n parentNode.insertBefore(child, container);\n } else {\n parentNode = container;\n parentNode.appendChild(child);\n } // This container might be used for a portal.\n // If something inside a portal is clicked, that click should bubble\n // through the React tree. However, on Mobile Safari the click would\n // never bubble through the *DOM* tree unless an ancestor with onclick\n // event exists. So we wouldn't see it and dispatch it.\n // This is why we ensure that non React root containers have inline onclick\n // defined.\n // https://github.com/facebook/react/issues/11918\n\n\n var reactRootContainer = container._reactRootContainer;\n\n if ((reactRootContainer === null || reactRootContainer === undefined) && parentNode.onclick === null) {\n // TODO: This cast may not be sound for SVG, MathML or custom elements.\n trapClickOnNonInteractiveElement(parentNode);\n }\n}\nfunction insertBefore(parentInstance, child, beforeChild) {\n parentInstance.insertBefore(child, beforeChild);\n}\nfunction insertInContainerBefore(container, child, beforeChild) {\n if (container.nodeType === COMMENT_NODE) {\n container.parentNode.insertBefore(child, beforeChild);\n } else {\n container.insertBefore(child, beforeChild);\n }\n}\nfunction removeChild(parentInstance, child) {\n parentInstance.removeChild(child);\n}\nfunction removeChildFromContainer(container, child) {\n if (container.nodeType === COMMENT_NODE) {\n container.parentNode.removeChild(child);\n } else {\n container.removeChild(child);\n }\n}\n\nfunction hideInstance(instance) {\n // pass host context to this method?\n\n\n instance = instance;\n var style = instance.style;\n\n if (typeof style.setProperty === 'function') {\n style.setProperty('display', 'none', 'important');\n } else {\n style.display = 'none';\n }\n}\nfunction hideTextInstance(textInstance) {\n textInstance.nodeValue = '';\n}\nfunction unhideInstance(instance, props) {\n instance = instance;\n var styleProp = props[STYLE$1];\n var display = styleProp !== undefined && styleProp !== null && styleProp.hasOwnProperty('display') ? styleProp.display : null;\n instance.style.display = dangerousStyleValue('display', display);\n}\nfunction unhideTextInstance(textInstance, text) {\n textInstance.nodeValue = text;\n} // -------------------\nfunction canHydrateInstance(instance, type, props) {\n if (instance.nodeType !== ELEMENT_NODE || type.toLowerCase() !== instance.nodeName.toLowerCase()) {\n return null;\n } // This has now been refined to an element node.\n\n\n return instance;\n}\nfunction canHydrateTextInstance(instance, text) {\n if (text === '' || instance.nodeType !== TEXT_NODE) {\n // Empty strings are not parsed by HTML so there won't be a correct match here.\n return null;\n } // This has now been refined to a text node.\n\n\n return instance;\n}\nfunction isSuspenseInstancePending(instance) {\n return instance.data === SUSPENSE_PENDING_START_DATA;\n}\nfunction isSuspenseInstanceFallback(instance) {\n return instance.data === SUSPENSE_FALLBACK_START_DATA;\n}\n\nfunction getNextHydratable(node) {\n // Skip non-hydratable nodes.\n for (; node != null; node = node.nextSibling) {\n var nodeType = node.nodeType;\n\n if (nodeType === ELEMENT_NODE || nodeType === TEXT_NODE) {\n break;\n }\n }\n\n return node;\n}\n\nfunction getNextHydratableSibling(instance) {\n return getNextHydratable(instance.nextSibling);\n}\nfunction getFirstHydratableChild(parentInstance) {\n return getNextHydratable(parentInstance.firstChild);\n}\nfunction hydrateInstance(instance, type, props, rootContainerInstance, hostContext, internalInstanceHandle) {\n precacheFiberNode(internalInstanceHandle, instance); // TODO: Possibly defer this until the commit phase where all the events\n // get attached.\n\n updateFiberProps(instance, props);\n var parentNamespace;\n\n {\n var hostContextDev = hostContext;\n parentNamespace = hostContextDev.namespace;\n }\n\n return diffHydratedProperties(instance, type, props, parentNamespace, rootContainerInstance);\n}\nfunction hydrateTextInstance(textInstance, text, internalInstanceHandle) {\n precacheFiberNode(internalInstanceHandle, textInstance);\n return diffHydratedText(textInstance, text);\n}\nfunction getNextHydratableInstanceAfterSuspenseInstance(suspenseInstance) {\n var node = suspenseInstance.nextSibling; // Skip past all nodes within this suspense boundary.\n // There might be nested nodes so we need to keep track of how\n // deep we are and only break out when we're back on top.\n\n var depth = 0;\n\n while (node) {\n if (node.nodeType === COMMENT_NODE) {\n var data = node.data;\n\n if (data === SUSPENSE_END_DATA) {\n if (depth === 0) {\n return getNextHydratableSibling(node);\n } else {\n depth--;\n }\n } else if (data === SUSPENSE_START_DATA || data === SUSPENSE_FALLBACK_START_DATA || data === SUSPENSE_PENDING_START_DATA) {\n depth++;\n }\n }\n\n node = node.nextSibling;\n } // TODO: Warn, we didn't find the end comment boundary.\n\n\n return null;\n} // Returns the SuspenseInstance if this node is a direct child of a\n// SuspenseInstance. I.e. if its previous sibling is a Comment with\n// SUSPENSE_x_START_DATA. Otherwise, null.\n\nfunction getParentSuspenseInstance(targetInstance) {\n var node = targetInstance.previousSibling; // Skip past all nodes within this suspense boundary.\n // There might be nested nodes so we need to keep track of how\n // deep we are and only break out when we're back on top.\n\n var depth = 0;\n\n while (node) {\n if (node.nodeType === COMMENT_NODE) {\n var data = node.data;\n\n if (data === SUSPENSE_START_DATA || data === SUSPENSE_FALLBACK_START_DATA || data === SUSPENSE_PENDING_START_DATA) {\n if (depth === 0) {\n return node;\n } else {\n depth--;\n }\n } else if (data === SUSPENSE_END_DATA) {\n depth++;\n }\n }\n\n node = node.previousSibling;\n }\n\n return null;\n}\nfunction commitHydratedContainer(container) {\n // Retry if any event replaying was blocked on this.\n retryIfBlockedOn(container);\n}\nfunction commitHydratedSuspenseInstance(suspenseInstance) {\n // Retry if any event replaying was blocked on this.\n retryIfBlockedOn(suspenseInstance);\n}\nfunction didNotMatchHydratedContainerTextInstance(parentContainer, textInstance, text) {\n {\n warnForUnmatchedText(textInstance, text);\n }\n}\nfunction didNotMatchHydratedTextInstance(parentType, parentProps, parentInstance, textInstance, text) {\n if ( parentProps[SUPPRESS_HYDRATION_WARNING$1] !== true) {\n warnForUnmatchedText(textInstance, text);\n }\n}\nfunction didNotHydrateContainerInstance(parentContainer, instance) {\n {\n if (instance.nodeType === ELEMENT_NODE) {\n warnForDeletedHydratableElement(parentContainer, instance);\n } else if (instance.nodeType === COMMENT_NODE) ; else {\n warnForDeletedHydratableText(parentContainer, instance);\n }\n }\n}\nfunction didNotHydrateInstance(parentType, parentProps, parentInstance, instance) {\n if ( parentProps[SUPPRESS_HYDRATION_WARNING$1] !== true) {\n if (instance.nodeType === ELEMENT_NODE) {\n warnForDeletedHydratableElement(parentInstance, instance);\n } else if (instance.nodeType === COMMENT_NODE) ; else {\n warnForDeletedHydratableText(parentInstance, instance);\n }\n }\n}\nfunction didNotFindHydratableContainerInstance(parentContainer, type, props) {\n {\n warnForInsertedHydratedElement(parentContainer, type);\n }\n}\nfunction didNotFindHydratableContainerTextInstance(parentContainer, text) {\n {\n warnForInsertedHydratedText(parentContainer, text);\n }\n}\nfunction didNotFindHydratableInstance(parentType, parentProps, parentInstance, type, props) {\n if ( parentProps[SUPPRESS_HYDRATION_WARNING$1] !== true) {\n warnForInsertedHydratedElement(parentInstance, type);\n }\n}\nfunction didNotFindHydratableTextInstance(parentType, parentProps, parentInstance, text) {\n if ( parentProps[SUPPRESS_HYDRATION_WARNING$1] !== true) {\n warnForInsertedHydratedText(parentInstance, text);\n }\n}\nfunction didNotFindHydratableSuspenseInstance(parentType, parentProps, parentInstance) {\n if ( parentProps[SUPPRESS_HYDRATION_WARNING$1] !== true) ;\n}\n\nvar randomKey = Math.random().toString(36).slice(2);\nvar internalInstanceKey = '__reactInternalInstance$' + randomKey;\nvar internalEventHandlersKey = '__reactEventHandlers$' + randomKey;\nvar internalContainerInstanceKey = '__reactContainere$' + randomKey;\nfunction precacheFiberNode(hostInst, node) {\n node[internalInstanceKey] = hostInst;\n}\nfunction markContainerAsRoot(hostRoot, node) {\n node[internalContainerInstanceKey] = hostRoot;\n}\nfunction unmarkContainerAsRoot(node) {\n node[internalContainerInstanceKey] = null;\n}\nfunction isContainerMarkedAsRoot(node) {\n return !!node[internalContainerInstanceKey];\n} // Given a DOM node, return the closest HostComponent or HostText fiber ancestor.\n// If the target node is part of a hydrated or not yet rendered subtree, then\n// this may also return a SuspenseComponent or HostRoot to indicate that.\n// Conceptually the HostRoot fiber is a child of the Container node. So if you\n// pass the Container node as the targetNode, you will not actually get the\n// HostRoot back. To get to the HostRoot, you need to pass a child of it.\n// The same thing applies to Suspense boundaries.\n\nfunction getClosestInstanceFromNode(targetNode) {\n var targetInst = targetNode[internalInstanceKey];\n\n if (targetInst) {\n // Don't return HostRoot or SuspenseComponent here.\n return targetInst;\n } // If the direct event target isn't a React owned DOM node, we need to look\n // to see if one of its parents is a React owned DOM node.\n\n\n var parentNode = targetNode.parentNode;\n\n while (parentNode) {\n // We'll check if this is a container root that could include\n // React nodes in the future. We need to check this first because\n // if we're a child of a dehydrated container, we need to first\n // find that inner container before moving on to finding the parent\n // instance. Note that we don't check this field on the targetNode\n // itself because the fibers are conceptually between the container\n // node and the first child. It isn't surrounding the container node.\n // If it's not a container, we check if it's an instance.\n targetInst = parentNode[internalContainerInstanceKey] || parentNode[internalInstanceKey];\n\n if (targetInst) {\n // Since this wasn't the direct target of the event, we might have\n // stepped past dehydrated DOM nodes to get here. However they could\n // also have been non-React nodes. We need to answer which one.\n // If we the instance doesn't have any children, then there can't be\n // a nested suspense boundary within it. So we can use this as a fast\n // bailout. Most of the time, when people add non-React children to\n // the tree, it is using a ref to a child-less DOM node.\n // Normally we'd only need to check one of the fibers because if it\n // has ever gone from having children to deleting them or vice versa\n // it would have deleted the dehydrated boundary nested inside already.\n // However, since the HostRoot starts out with an alternate it might\n // have one on the alternate so we need to check in case this was a\n // root.\n var alternate = targetInst.alternate;\n\n if (targetInst.child !== null || alternate !== null && alternate.child !== null) {\n // Next we need to figure out if the node that skipped past is\n // nested within a dehydrated boundary and if so, which one.\n var suspenseInstance = getParentSuspenseInstance(targetNode);\n\n while (suspenseInstance !== null) {\n // We found a suspense instance. That means that we haven't\n // hydrated it yet. Even though we leave the comments in the\n // DOM after hydrating, and there are boundaries in the DOM\n // that could already be hydrated, we wouldn't have found them\n // through this pass since if the target is hydrated it would\n // have had an internalInstanceKey on it.\n // Let's get the fiber associated with the SuspenseComponent\n // as the deepest instance.\n var targetSuspenseInst = suspenseInstance[internalInstanceKey];\n\n if (targetSuspenseInst) {\n return targetSuspenseInst;\n } // If we don't find a Fiber on the comment, it might be because\n // we haven't gotten to hydrate it yet. There might still be a\n // parent boundary that hasn't above this one so we need to find\n // the outer most that is known.\n\n\n suspenseInstance = getParentSuspenseInstance(suspenseInstance); // If we don't find one, then that should mean that the parent\n // host component also hasn't hydrated yet. We can return it\n // below since it will bail out on the isMounted check later.\n }\n }\n\n return targetInst;\n }\n\n targetNode = parentNode;\n parentNode = targetNode.parentNode;\n }\n\n return null;\n}\n/**\n * Given a DOM node, return the ReactDOMComponent or ReactDOMTextComponent\n * instance, or null if the node was not rendered by this React.\n */\n\nfunction getInstanceFromNode$1(node) {\n var inst = node[internalInstanceKey] || node[internalContainerInstanceKey];\n\n if (inst) {\n if (inst.tag === HostComponent || inst.tag === HostText || inst.tag === SuspenseComponent || inst.tag === HostRoot) {\n return inst;\n } else {\n return null;\n }\n }\n\n return null;\n}\n/**\n * Given a ReactDOMComponent or ReactDOMTextComponent, return the corresponding\n * DOM node.\n */\n\nfunction getNodeFromInstance$1(inst) {\n if (inst.tag === HostComponent || inst.tag === HostText) {\n // In Fiber this, is just the state node right now. We assume it will be\n // a host component or host text.\n return inst.stateNode;\n } // Without this first invariant, passing a non-DOM-component triggers the next\n // invariant for a missing parent, which is super confusing.\n\n\n {\n {\n throw Error( \"getNodeFromInstance: Invalid argument.\" );\n }\n }\n}\nfunction getFiberCurrentPropsFromNode$1(node) {\n return node[internalEventHandlersKey] || null;\n}\nfunction updateFiberProps(node, props) {\n node[internalEventHandlersKey] = props;\n}\n\nfunction getParent(inst) {\n do {\n inst = inst.return; // TODO: If this is a HostRoot we might want to bail out.\n // That is depending on if we want nested subtrees (layers) to bubble\n // events to their parent. We could also go through parentNode on the\n // host node but that wouldn't work for React Native and doesn't let us\n // do the portal feature.\n } while (inst && inst.tag !== HostComponent);\n\n if (inst) {\n return inst;\n }\n\n return null;\n}\n/**\n * Return the lowest common ancestor of A and B, or null if they are in\n * different trees.\n */\n\n\nfunction getLowestCommonAncestor(instA, instB) {\n var depthA = 0;\n\n for (var tempA = instA; tempA; tempA = getParent(tempA)) {\n depthA++;\n }\n\n var depthB = 0;\n\n for (var tempB = instB; tempB; tempB = getParent(tempB)) {\n depthB++;\n } // If A is deeper, crawl up.\n\n\n while (depthA - depthB > 0) {\n instA = getParent(instA);\n depthA--;\n } // If B is deeper, crawl up.\n\n\n while (depthB - depthA > 0) {\n instB = getParent(instB);\n depthB--;\n } // Walk in lockstep until we find a match.\n\n\n var depth = depthA;\n\n while (depth--) {\n if (instA === instB || instA === instB.alternate) {\n return instA;\n }\n\n instA = getParent(instA);\n instB = getParent(instB);\n }\n\n return null;\n}\n/**\n * Simulates the traversal of a two-phase, capture/bubble event dispatch.\n */\n\nfunction traverseTwoPhase(inst, fn, arg) {\n var path = [];\n\n while (inst) {\n path.push(inst);\n inst = getParent(inst);\n }\n\n var i;\n\n for (i = path.length; i-- > 0;) {\n fn(path[i], 'captured', arg);\n }\n\n for (i = 0; i < path.length; i++) {\n fn(path[i], 'bubbled', arg);\n }\n}\n/**\n * Traverses the ID hierarchy and invokes the supplied `cb` on any IDs that\n * should would receive a `mouseEnter` or `mouseLeave` event.\n *\n * Does not invoke the callback on the nearest common ancestor because nothing\n * \"entered\" or \"left\" that element.\n */\n\nfunction traverseEnterLeave(from, to, fn, argFrom, argTo) {\n var common = from && to ? getLowestCommonAncestor(from, to) : null;\n var pathFrom = [];\n\n while (true) {\n if (!from) {\n break;\n }\n\n if (from === common) {\n break;\n }\n\n var alternate = from.alternate;\n\n if (alternate !== null && alternate === common) {\n break;\n }\n\n pathFrom.push(from);\n from = getParent(from);\n }\n\n var pathTo = [];\n\n while (true) {\n if (!to) {\n break;\n }\n\n if (to === common) {\n break;\n }\n\n var _alternate = to.alternate;\n\n if (_alternate !== null && _alternate === common) {\n break;\n }\n\n pathTo.push(to);\n to = getParent(to);\n }\n\n for (var i = 0; i < pathFrom.length; i++) {\n fn(pathFrom[i], 'bubbled', argFrom);\n }\n\n for (var _i = pathTo.length; _i-- > 0;) {\n fn(pathTo[_i], 'captured', argTo);\n }\n}\n\nfunction isInteractive(tag) {\n return tag === 'button' || tag === 'input' || tag === 'select' || tag === 'textarea';\n}\n\nfunction shouldPreventMouseEvent(name, type, props) {\n switch (name) {\n case 'onClick':\n case 'onClickCapture':\n case 'onDoubleClick':\n case 'onDoubleClickCapture':\n case 'onMouseDown':\n case 'onMouseDownCapture':\n case 'onMouseMove':\n case 'onMouseMoveCapture':\n case 'onMouseUp':\n case 'onMouseUpCapture':\n case 'onMouseEnter':\n return !!(props.disabled && isInteractive(type));\n\n default:\n return false;\n }\n}\n/**\n * @param {object} inst The instance, which is the source of events.\n * @param {string} registrationName Name of listener (e.g. `onClick`).\n * @return {?function} The stored callback.\n */\n\n\nfunction getListener(inst, registrationName) {\n var listener; // TODO: shouldPreventMouseEvent is DOM-specific and definitely should not\n // live here; needs to be moved to a better place soon\n\n var stateNode = inst.stateNode;\n\n if (!stateNode) {\n // Work in progress (ex: onload events in incremental mode).\n return null;\n }\n\n var props = getFiberCurrentPropsFromNode(stateNode);\n\n if (!props) {\n // Work in progress.\n return null;\n }\n\n listener = props[registrationName];\n\n if (shouldPreventMouseEvent(registrationName, inst.type, props)) {\n return null;\n }\n\n if (!(!listener || typeof listener === 'function')) {\n {\n throw Error( \"Expected `\" + registrationName + \"` listener to be a function, instead got a value of `\" + typeof listener + \"` type.\" );\n }\n }\n\n return listener;\n}\n\n/**\n * Some event types have a notion of different registration names for different\n * \"phases\" of propagation. This finds listeners by a given phase.\n */\nfunction listenerAtPhase(inst, event, propagationPhase) {\n var registrationName = event.dispatchConfig.phasedRegistrationNames[propagationPhase];\n return getListener(inst, registrationName);\n}\n/**\n * A small set of propagation patterns, each of which will accept a small amount\n * of information, and generate a set of \"dispatch ready event objects\" - which\n * are sets of events that have already been annotated with a set of dispatched\n * listener functions/ids. The API is designed this way to discourage these\n * propagation strategies from actually executing the dispatches, since we\n * always want to collect the entire set of dispatches before executing even a\n * single one.\n */\n\n/**\n * Tags a `SyntheticEvent` with dispatched listeners. Creating this function\n * here, allows us to not have to bind or create functions for each event.\n * Mutating the event's members allows us to not have to create a wrapping\n * \"dispatch\" object that pairs the event with the listener.\n */\n\n\nfunction accumulateDirectionalDispatches(inst, phase, event) {\n {\n if (!inst) {\n error('Dispatching inst must not be null');\n }\n }\n\n var listener = listenerAtPhase(inst, event, phase);\n\n if (listener) {\n event._dispatchListeners = accumulateInto(event._dispatchListeners, listener);\n event._dispatchInstances = accumulateInto(event._dispatchInstances, inst);\n }\n}\n/**\n * Collect dispatches (must be entirely collected before dispatching - see unit\n * tests). Lazily allocate the array to conserve memory. We must loop through\n * each event and perform the traversal for each one. We cannot perform a\n * single traversal for the entire collection of events because each event may\n * have a different target.\n */\n\n\nfunction accumulateTwoPhaseDispatchesSingle(event) {\n if (event && event.dispatchConfig.phasedRegistrationNames) {\n traverseTwoPhase(event._targetInst, accumulateDirectionalDispatches, event);\n }\n}\n/**\n * Accumulates without regard to direction, does not look for phased\n * registration names. Same as `accumulateDirectDispatchesSingle` but without\n * requiring that the `dispatchMarker` be the same as the dispatched ID.\n */\n\n\nfunction accumulateDispatches(inst, ignoredDirection, event) {\n if (inst && event && event.dispatchConfig.registrationName) {\n var registrationName = event.dispatchConfig.registrationName;\n var listener = getListener(inst, registrationName);\n\n if (listener) {\n event._dispatchListeners = accumulateInto(event._dispatchListeners, listener);\n event._dispatchInstances = accumulateInto(event._dispatchInstances, inst);\n }\n }\n}\n/**\n * Accumulates dispatches on an `SyntheticEvent`, but only for the\n * `dispatchMarker`.\n * @param {SyntheticEvent} event\n */\n\n\nfunction accumulateDirectDispatchesSingle(event) {\n if (event && event.dispatchConfig.registrationName) {\n accumulateDispatches(event._targetInst, null, event);\n }\n}\n\nfunction accumulateTwoPhaseDispatches(events) {\n forEachAccumulated(events, accumulateTwoPhaseDispatchesSingle);\n}\nfunction accumulateEnterLeaveDispatches(leave, enter, from, to) {\n traverseEnterLeave(from, to, accumulateDispatches, leave, enter);\n}\nfunction accumulateDirectDispatches(events) {\n forEachAccumulated(events, accumulateDirectDispatchesSingle);\n}\n\n/**\n * These variables store information about text content of a target node,\n * allowing comparison of content before and after a given event.\n *\n * Identify the node where selection currently begins, then observe\n * both its text content and its current position in the DOM. Since the\n * browser may natively replace the target node during composition, we can\n * use its position to find its replacement.\n *\n *\n */\nvar root = null;\nvar startText = null;\nvar fallbackText = null;\nfunction initialize(nativeEventTarget) {\n root = nativeEventTarget;\n startText = getText();\n return true;\n}\nfunction reset() {\n root = null;\n startText = null;\n fallbackText = null;\n}\nfunction getData() {\n if (fallbackText) {\n return fallbackText;\n }\n\n var start;\n var startValue = startText;\n var startLength = startValue.length;\n var end;\n var endValue = getText();\n var endLength = endValue.length;\n\n for (start = 0; start < startLength; start++) {\n if (startValue[start] !== endValue[start]) {\n break;\n }\n }\n\n var minEnd = startLength - start;\n\n for (end = 1; end <= minEnd; end++) {\n if (startValue[startLength - end] !== endValue[endLength - end]) {\n break;\n }\n }\n\n var sliceTail = end > 1 ? 1 - end : undefined;\n fallbackText = endValue.slice(start, sliceTail);\n return fallbackText;\n}\nfunction getText() {\n if ('value' in root) {\n return root.value;\n }\n\n return root.textContent;\n}\n\nvar EVENT_POOL_SIZE = 10;\n/**\n * @interface Event\n * @see http://www.w3.org/TR/DOM-Level-3-Events/\n */\n\nvar EventInterface = {\n type: null,\n target: null,\n // currentTarget is set when dispatching; no use in copying it here\n currentTarget: function () {\n return null;\n },\n eventPhase: null,\n bubbles: null,\n cancelable: null,\n timeStamp: function (event) {\n return event.timeStamp || Date.now();\n },\n defaultPrevented: null,\n isTrusted: null\n};\n\nfunction functionThatReturnsTrue() {\n return true;\n}\n\nfunction functionThatReturnsFalse() {\n return false;\n}\n/**\n * Synthetic events are dispatched by event plugins, typically in response to a\n * top-level event delegation handler.\n *\n * These systems should generally use pooling to reduce the frequency of garbage\n * collection. The system should check `isPersistent` to determine whether the\n * event should be released into the pool after being dispatched. Users that\n * need a persisted event should invoke `persist`.\n *\n * Synthetic events (and subclasses) implement the DOM Level 3 Events API by\n * normalizing browser quirks. Subclasses do not necessarily have to implement a\n * DOM interface; custom application-specific events can also subclass this.\n *\n * @param {object} dispatchConfig Configuration used to dispatch this event.\n * @param {*} targetInst Marker identifying the event target.\n * @param {object} nativeEvent Native browser event.\n * @param {DOMEventTarget} nativeEventTarget Target node.\n */\n\n\nfunction SyntheticEvent(dispatchConfig, targetInst, nativeEvent, nativeEventTarget) {\n {\n // these have a getter/setter for warnings\n delete this.nativeEvent;\n delete this.preventDefault;\n delete this.stopPropagation;\n delete this.isDefaultPrevented;\n delete this.isPropagationStopped;\n }\n\n this.dispatchConfig = dispatchConfig;\n this._targetInst = targetInst;\n this.nativeEvent = nativeEvent;\n var Interface = this.constructor.Interface;\n\n for (var propName in Interface) {\n if (!Interface.hasOwnProperty(propName)) {\n continue;\n }\n\n {\n delete this[propName]; // this has a getter/setter for warnings\n }\n\n var normalize = Interface[propName];\n\n if (normalize) {\n this[propName] = normalize(nativeEvent);\n } else {\n if (propName === 'target') {\n this.target = nativeEventTarget;\n } else {\n this[propName] = nativeEvent[propName];\n }\n }\n }\n\n var defaultPrevented = nativeEvent.defaultPrevented != null ? nativeEvent.defaultPrevented : nativeEvent.returnValue === false;\n\n if (defaultPrevented) {\n this.isDefaultPrevented = functionThatReturnsTrue;\n } else {\n this.isDefaultPrevented = functionThatReturnsFalse;\n }\n\n this.isPropagationStopped = functionThatReturnsFalse;\n return this;\n}\n\n_assign(SyntheticEvent.prototype, {\n preventDefault: function () {\n this.defaultPrevented = true;\n var event = this.nativeEvent;\n\n if (!event) {\n return;\n }\n\n if (event.preventDefault) {\n event.preventDefault();\n } else if (typeof event.returnValue !== 'unknown') {\n event.returnValue = false;\n }\n\n this.isDefaultPrevented = functionThatReturnsTrue;\n },\n stopPropagation: function () {\n var event = this.nativeEvent;\n\n if (!event) {\n return;\n }\n\n if (event.stopPropagation) {\n event.stopPropagation();\n } else if (typeof event.cancelBubble !== 'unknown') {\n // The ChangeEventPlugin registers a \"propertychange\" event for\n // IE. This event does not support bubbling or cancelling, and\n // any references to cancelBubble throw \"Member not found\". A\n // typeof check of \"unknown\" circumvents this issue (and is also\n // IE specific).\n event.cancelBubble = true;\n }\n\n this.isPropagationStopped = functionThatReturnsTrue;\n },\n\n /**\n * We release all dispatched `SyntheticEvent`s after each event loop, adding\n * them back into the pool. This allows a way to hold onto a reference that\n * won't be added back into the pool.\n */\n persist: function () {\n this.isPersistent = functionThatReturnsTrue;\n },\n\n /**\n * Checks if this event should be released back into the pool.\n *\n * @return {boolean} True if this should not be released, false otherwise.\n */\n isPersistent: functionThatReturnsFalse,\n\n /**\n * `PooledClass` looks for `destructor` on each instance it releases.\n */\n destructor: function () {\n var Interface = this.constructor.Interface;\n\n for (var propName in Interface) {\n {\n Object.defineProperty(this, propName, getPooledWarningPropertyDefinition(propName, Interface[propName]));\n }\n }\n\n this.dispatchConfig = null;\n this._targetInst = null;\n this.nativeEvent = null;\n this.isDefaultPrevented = functionThatReturnsFalse;\n this.isPropagationStopped = functionThatReturnsFalse;\n this._dispatchListeners = null;\n this._dispatchInstances = null;\n\n {\n Object.defineProperty(this, 'nativeEvent', getPooledWarningPropertyDefinition('nativeEvent', null));\n Object.defineProperty(this, 'isDefaultPrevented', getPooledWarningPropertyDefinition('isDefaultPrevented', functionThatReturnsFalse));\n Object.defineProperty(this, 'isPropagationStopped', getPooledWarningPropertyDefinition('isPropagationStopped', functionThatReturnsFalse));\n Object.defineProperty(this, 'preventDefault', getPooledWarningPropertyDefinition('preventDefault', function () {}));\n Object.defineProperty(this, 'stopPropagation', getPooledWarningPropertyDefinition('stopPropagation', function () {}));\n }\n }\n});\n\nSyntheticEvent.Interface = EventInterface;\n/**\n * Helper to reduce boilerplate when creating subclasses.\n */\n\nSyntheticEvent.extend = function (Interface) {\n var Super = this;\n\n var E = function () {};\n\n E.prototype = Super.prototype;\n var prototype = new E();\n\n function Class() {\n return Super.apply(this, arguments);\n }\n\n _assign(prototype, Class.prototype);\n\n Class.prototype = prototype;\n Class.prototype.constructor = Class;\n Class.Interface = _assign({}, Super.Interface, Interface);\n Class.extend = Super.extend;\n addEventPoolingTo(Class);\n return Class;\n};\n\naddEventPoolingTo(SyntheticEvent);\n/**\n * Helper to nullify syntheticEvent instance properties when destructing\n *\n * @param {String} propName\n * @param {?object} getVal\n * @return {object} defineProperty object\n */\n\nfunction getPooledWarningPropertyDefinition(propName, getVal) {\n var isFunction = typeof getVal === 'function';\n return {\n configurable: true,\n set: set,\n get: get\n };\n\n function set(val) {\n var action = isFunction ? 'setting the method' : 'setting the property';\n warn(action, 'This is effectively a no-op');\n return val;\n }\n\n function get() {\n var action = isFunction ? 'accessing the method' : 'accessing the property';\n var result = isFunction ? 'This is a no-op function' : 'This is set to null';\n warn(action, result);\n return getVal;\n }\n\n function warn(action, result) {\n {\n error(\"This synthetic event is reused for performance reasons. If you're seeing this, \" + \"you're %s `%s` on a released/nullified synthetic event. %s. \" + 'If you must keep the original synthetic event around, use event.persist(). ' + 'See https://fb.me/react-event-pooling for more information.', action, propName, result);\n }\n }\n}\n\nfunction getPooledEvent(dispatchConfig, targetInst, nativeEvent, nativeInst) {\n var EventConstructor = this;\n\n if (EventConstructor.eventPool.length) {\n var instance = EventConstructor.eventPool.pop();\n EventConstructor.call(instance, dispatchConfig, targetInst, nativeEvent, nativeInst);\n return instance;\n }\n\n return new EventConstructor(dispatchConfig, targetInst, nativeEvent, nativeInst);\n}\n\nfunction releasePooledEvent(event) {\n var EventConstructor = this;\n\n if (!(event instanceof EventConstructor)) {\n {\n throw Error( \"Trying to release an event instance into a pool of a different type.\" );\n }\n }\n\n event.destructor();\n\n if (EventConstructor.eventPool.length < EVENT_POOL_SIZE) {\n EventConstructor.eventPool.push(event);\n }\n}\n\nfunction addEventPoolingTo(EventConstructor) {\n EventConstructor.eventPool = [];\n EventConstructor.getPooled = getPooledEvent;\n EventConstructor.release = releasePooledEvent;\n}\n\n/**\n * @interface Event\n * @see http://www.w3.org/TR/DOM-Level-3-Events/#events-compositionevents\n */\n\nvar SyntheticCompositionEvent = SyntheticEvent.extend({\n data: null\n});\n\n/**\n * @interface Event\n * @see http://www.w3.org/TR/2013/WD-DOM-Level-3-Events-20131105\n * /#events-inputevents\n */\n\nvar SyntheticInputEvent = SyntheticEvent.extend({\n data: null\n});\n\nvar END_KEYCODES = [9, 13, 27, 32]; // Tab, Return, Esc, Space\n\nvar START_KEYCODE = 229;\nvar canUseCompositionEvent = canUseDOM && 'CompositionEvent' in window;\nvar documentMode = null;\n\nif (canUseDOM && 'documentMode' in document) {\n documentMode = document.documentMode;\n} // Webkit offers a very useful `textInput` event that can be used to\n// directly represent `beforeInput`. The IE `textinput` event is not as\n// useful, so we don't use it.\n\n\nvar canUseTextInputEvent = canUseDOM && 'TextEvent' in window && !documentMode; // In IE9+, we have access to composition events, but the data supplied\n// by the native compositionend event may be incorrect. Japanese ideographic\n// spaces, for instance (\\u3000) are not recorded correctly.\n\nvar useFallbackCompositionData = canUseDOM && (!canUseCompositionEvent || documentMode && documentMode > 8 && documentMode <= 11);\nvar SPACEBAR_CODE = 32;\nvar SPACEBAR_CHAR = String.fromCharCode(SPACEBAR_CODE); // Events and their corresponding property names.\n\nvar eventTypes = {\n beforeInput: {\n phasedRegistrationNames: {\n bubbled: 'onBeforeInput',\n captured: 'onBeforeInputCapture'\n },\n dependencies: [TOP_COMPOSITION_END, TOP_KEY_PRESS, TOP_TEXT_INPUT, TOP_PASTE]\n },\n compositionEnd: {\n phasedRegistrationNames: {\n bubbled: 'onCompositionEnd',\n captured: 'onCompositionEndCapture'\n },\n dependencies: [TOP_BLUR, TOP_COMPOSITION_END, TOP_KEY_DOWN, TOP_KEY_PRESS, TOP_KEY_UP, TOP_MOUSE_DOWN]\n },\n compositionStart: {\n phasedRegistrationNames: {\n bubbled: 'onCompositionStart',\n captured: 'onCompositionStartCapture'\n },\n dependencies: [TOP_BLUR, TOP_COMPOSITION_START, TOP_KEY_DOWN, TOP_KEY_PRESS, TOP_KEY_UP, TOP_MOUSE_DOWN]\n },\n compositionUpdate: {\n phasedRegistrationNames: {\n bubbled: 'onCompositionUpdate',\n captured: 'onCompositionUpdateCapture'\n },\n dependencies: [TOP_BLUR, TOP_COMPOSITION_UPDATE, TOP_KEY_DOWN, TOP_KEY_PRESS, TOP_KEY_UP, TOP_MOUSE_DOWN]\n }\n}; // Track whether we've ever handled a keypress on the space key.\n\nvar hasSpaceKeypress = false;\n/**\n * Return whether a native keypress event is assumed to be a command.\n * This is required because Firefox fires `keypress` events for key commands\n * (cut, copy, select-all, etc.) even though no character is inserted.\n */\n\nfunction isKeypressCommand(nativeEvent) {\n return (nativeEvent.ctrlKey || nativeEvent.altKey || nativeEvent.metaKey) && // ctrlKey && altKey is equivalent to AltGr, and is not a command.\n !(nativeEvent.ctrlKey && nativeEvent.altKey);\n}\n/**\n * Translate native top level events into event types.\n *\n * @param {string} topLevelType\n * @return {object}\n */\n\n\nfunction getCompositionEventType(topLevelType) {\n switch (topLevelType) {\n case TOP_COMPOSITION_START:\n return eventTypes.compositionStart;\n\n case TOP_COMPOSITION_END:\n return eventTypes.compositionEnd;\n\n case TOP_COMPOSITION_UPDATE:\n return eventTypes.compositionUpdate;\n }\n}\n/**\n * Does our fallback best-guess model think this event signifies that\n * composition has begun?\n *\n * @param {string} topLevelType\n * @param {object} nativeEvent\n * @return {boolean}\n */\n\n\nfunction isFallbackCompositionStart(topLevelType, nativeEvent) {\n return topLevelType === TOP_KEY_DOWN && nativeEvent.keyCode === START_KEYCODE;\n}\n/**\n * Does our fallback mode think that this event is the end of composition?\n *\n * @param {string} topLevelType\n * @param {object} nativeEvent\n * @return {boolean}\n */\n\n\nfunction isFallbackCompositionEnd(topLevelType, nativeEvent) {\n switch (topLevelType) {\n case TOP_KEY_UP:\n // Command keys insert or clear IME input.\n return END_KEYCODES.indexOf(nativeEvent.keyCode) !== -1;\n\n case TOP_KEY_DOWN:\n // Expect IME keyCode on each keydown. If we get any other\n // code we must have exited earlier.\n return nativeEvent.keyCode !== START_KEYCODE;\n\n case TOP_KEY_PRESS:\n case TOP_MOUSE_DOWN:\n case TOP_BLUR:\n // Events are not possible without cancelling IME.\n return true;\n\n default:\n return false;\n }\n}\n/**\n * Google Input Tools provides composition data via a CustomEvent,\n * with the `data` property populated in the `detail` object. If this\n * is available on the event object, use it. If not, this is a plain\n * composition event and we have nothing special to extract.\n *\n * @param {object} nativeEvent\n * @return {?string}\n */\n\n\nfunction getDataFromCustomEvent(nativeEvent) {\n var detail = nativeEvent.detail;\n\n if (typeof detail === 'object' && 'data' in detail) {\n return detail.data;\n }\n\n return null;\n}\n/**\n * Check if a composition event was triggered by Korean IME.\n * Our fallback mode does not work well with IE's Korean IME,\n * so just use native composition events when Korean IME is used.\n * Although CompositionEvent.locale property is deprecated,\n * it is available in IE, where our fallback mode is enabled.\n *\n * @param {object} nativeEvent\n * @return {boolean}\n */\n\n\nfunction isUsingKoreanIME(nativeEvent) {\n return nativeEvent.locale === 'ko';\n} // Track the current IME composition status, if any.\n\n\nvar isComposing = false;\n/**\n * @return {?object} A SyntheticCompositionEvent.\n */\n\nfunction extractCompositionEvent(topLevelType, targetInst, nativeEvent, nativeEventTarget) {\n var eventType;\n var fallbackData;\n\n if (canUseCompositionEvent) {\n eventType = getCompositionEventType(topLevelType);\n } else if (!isComposing) {\n if (isFallbackCompositionStart(topLevelType, nativeEvent)) {\n eventType = eventTypes.compositionStart;\n }\n } else if (isFallbackCompositionEnd(topLevelType, nativeEvent)) {\n eventType = eventTypes.compositionEnd;\n }\n\n if (!eventType) {\n return null;\n }\n\n if (useFallbackCompositionData && !isUsingKoreanIME(nativeEvent)) {\n // The current composition is stored statically and must not be\n // overwritten while composition continues.\n if (!isComposing && eventType === eventTypes.compositionStart) {\n isComposing = initialize(nativeEventTarget);\n } else if (eventType === eventTypes.compositionEnd) {\n if (isComposing) {\n fallbackData = getData();\n }\n }\n }\n\n var event = SyntheticCompositionEvent.getPooled(eventType, targetInst, nativeEvent, nativeEventTarget);\n\n if (fallbackData) {\n // Inject data generated from fallback path into the synthetic event.\n // This matches the property of native CompositionEventInterface.\n event.data = fallbackData;\n } else {\n var customData = getDataFromCustomEvent(nativeEvent);\n\n if (customData !== null) {\n event.data = customData;\n }\n }\n\n accumulateTwoPhaseDispatches(event);\n return event;\n}\n/**\n * @param {TopLevelType} topLevelType Number from `TopLevelType`.\n * @param {object} nativeEvent Native browser event.\n * @return {?string} The string corresponding to this `beforeInput` event.\n */\n\n\nfunction getNativeBeforeInputChars(topLevelType, nativeEvent) {\n switch (topLevelType) {\n case TOP_COMPOSITION_END:\n return getDataFromCustomEvent(nativeEvent);\n\n case TOP_KEY_PRESS:\n /**\n * If native `textInput` events are available, our goal is to make\n * use of them. However, there is a special case: the spacebar key.\n * In Webkit, preventing default on a spacebar `textInput` event\n * cancels character insertion, but it *also* causes the browser\n * to fall back to its default spacebar behavior of scrolling the\n * page.\n *\n * Tracking at:\n * https://code.google.com/p/chromium/issues/detail?id=355103\n *\n * To avoid this issue, use the keypress event as if no `textInput`\n * event is available.\n */\n var which = nativeEvent.which;\n\n if (which !== SPACEBAR_CODE) {\n return null;\n }\n\n hasSpaceKeypress = true;\n return SPACEBAR_CHAR;\n\n case TOP_TEXT_INPUT:\n // Record the characters to be added to the DOM.\n var chars = nativeEvent.data; // If it's a spacebar character, assume that we have already handled\n // it at the keypress level and bail immediately. Android Chrome\n // doesn't give us keycodes, so we need to ignore it.\n\n if (chars === SPACEBAR_CHAR && hasSpaceKeypress) {\n return null;\n }\n\n return chars;\n\n default:\n // For other native event types, do nothing.\n return null;\n }\n}\n/**\n * For browsers that do not provide the `textInput` event, extract the\n * appropriate string to use for SyntheticInputEvent.\n *\n * @param {number} topLevelType Number from `TopLevelEventTypes`.\n * @param {object} nativeEvent Native browser event.\n * @return {?string} The fallback string for this `beforeInput` event.\n */\n\n\nfunction getFallbackBeforeInputChars(topLevelType, nativeEvent) {\n // If we are currently composing (IME) and using a fallback to do so,\n // try to extract the composed characters from the fallback object.\n // If composition event is available, we extract a string only at\n // compositionevent, otherwise extract it at fallback events.\n if (isComposing) {\n if (topLevelType === TOP_COMPOSITION_END || !canUseCompositionEvent && isFallbackCompositionEnd(topLevelType, nativeEvent)) {\n var chars = getData();\n reset();\n isComposing = false;\n return chars;\n }\n\n return null;\n }\n\n switch (topLevelType) {\n case TOP_PASTE:\n // If a paste event occurs after a keypress, throw out the input\n // chars. Paste events should not lead to BeforeInput events.\n return null;\n\n case TOP_KEY_PRESS:\n /**\n * As of v27, Firefox may fire keypress events even when no character\n * will be inserted. A few possibilities:\n *\n * - `which` is `0`. Arrow keys, Esc key, etc.\n *\n * - `which` is the pressed key code, but no char is available.\n * Ex: 'AltGr + d` in Polish. There is no modified character for\n * this key combination and no character is inserted into the\n * document, but FF fires the keypress for char code `100` anyway.\n * No `input` event will occur.\n *\n * - `which` is the pressed key code, but a command combination is\n * being used. Ex: `Cmd+C`. No character is inserted, and no\n * `input` event will occur.\n */\n if (!isKeypressCommand(nativeEvent)) {\n // IE fires the `keypress` event when a user types an emoji via\n // Touch keyboard of Windows. In such a case, the `char` property\n // holds an emoji character like `\\uD83D\\uDE0A`. Because its length\n // is 2, the property `which` does not represent an emoji correctly.\n // In such a case, we directly return the `char` property instead of\n // using `which`.\n if (nativeEvent.char && nativeEvent.char.length > 1) {\n return nativeEvent.char;\n } else if (nativeEvent.which) {\n return String.fromCharCode(nativeEvent.which);\n }\n }\n\n return null;\n\n case TOP_COMPOSITION_END:\n return useFallbackCompositionData && !isUsingKoreanIME(nativeEvent) ? null : nativeEvent.data;\n\n default:\n return null;\n }\n}\n/**\n * Extract a SyntheticInputEvent for `beforeInput`, based on either native\n * `textInput` or fallback behavior.\n *\n * @return {?object} A SyntheticInputEvent.\n */\n\n\nfunction extractBeforeInputEvent(topLevelType, targetInst, nativeEvent, nativeEventTarget) {\n var chars;\n\n if (canUseTextInputEvent) {\n chars = getNativeBeforeInputChars(topLevelType, nativeEvent);\n } else {\n chars = getFallbackBeforeInputChars(topLevelType, nativeEvent);\n } // If no characters are being inserted, no BeforeInput event should\n // be fired.\n\n\n if (!chars) {\n return null;\n }\n\n var event = SyntheticInputEvent.getPooled(eventTypes.beforeInput, targetInst, nativeEvent, nativeEventTarget);\n event.data = chars;\n accumulateTwoPhaseDispatches(event);\n return event;\n}\n/**\n * Create an `onBeforeInput` event to match\n * http://www.w3.org/TR/2013/WD-DOM-Level-3-Events-20131105/#events-inputevents.\n *\n * This event plugin is based on the native `textInput` event\n * available in Chrome, Safari, Opera, and IE. This event fires after\n * `onKeyPress` and `onCompositionEnd`, but before `onInput`.\n *\n * `beforeInput` is spec'd but not implemented in any browsers, and\n * the `input` event does not provide any useful information about what has\n * actually been added, contrary to the spec. Thus, `textInput` is the best\n * available event to identify the characters that have actually been inserted\n * into the target node.\n *\n * This plugin is also responsible for emitting `composition` events, thus\n * allowing us to share composition fallback code for both `beforeInput` and\n * `composition` event types.\n */\n\n\nvar BeforeInputEventPlugin = {\n eventTypes: eventTypes,\n extractEvents: function (topLevelType, targetInst, nativeEvent, nativeEventTarget, eventSystemFlags) {\n var composition = extractCompositionEvent(topLevelType, targetInst, nativeEvent, nativeEventTarget);\n var beforeInput = extractBeforeInputEvent(topLevelType, targetInst, nativeEvent, nativeEventTarget);\n\n if (composition === null) {\n return beforeInput;\n }\n\n if (beforeInput === null) {\n return composition;\n }\n\n return [composition, beforeInput];\n }\n};\n\n/**\n * @see http://www.whatwg.org/specs/web-apps/current-work/multipage/the-input-element.html#input-type-attr-summary\n */\nvar supportedInputTypes = {\n color: true,\n date: true,\n datetime: true,\n 'datetime-local': true,\n email: true,\n month: true,\n number: true,\n password: true,\n range: true,\n search: true,\n tel: true,\n text: true,\n time: true,\n url: true,\n week: true\n};\n\nfunction isTextInputElement(elem) {\n var nodeName = elem && elem.nodeName && elem.nodeName.toLowerCase();\n\n if (nodeName === 'input') {\n return !!supportedInputTypes[elem.type];\n }\n\n if (nodeName === 'textarea') {\n return true;\n }\n\n return false;\n}\n\nvar eventTypes$1 = {\n change: {\n phasedRegistrationNames: {\n bubbled: 'onChange',\n captured: 'onChangeCapture'\n },\n dependencies: [TOP_BLUR, TOP_CHANGE, TOP_CLICK, TOP_FOCUS, TOP_INPUT, TOP_KEY_DOWN, TOP_KEY_UP, TOP_SELECTION_CHANGE]\n }\n};\n\nfunction createAndAccumulateChangeEvent(inst, nativeEvent, target) {\n var event = SyntheticEvent.getPooled(eventTypes$1.change, inst, nativeEvent, target);\n event.type = 'change'; // Flag this event loop as needing state restore.\n\n enqueueStateRestore(target);\n accumulateTwoPhaseDispatches(event);\n return event;\n}\n/**\n * For IE shims\n */\n\n\nvar activeElement = null;\nvar activeElementInst = null;\n/**\n * SECTION: handle `change` event\n */\n\nfunction shouldUseChangeEvent(elem) {\n var nodeName = elem.nodeName && elem.nodeName.toLowerCase();\n return nodeName === 'select' || nodeName === 'input' && elem.type === 'file';\n}\n\nfunction manualDispatchChangeEvent(nativeEvent) {\n var event = createAndAccumulateChangeEvent(activeElementInst, nativeEvent, getEventTarget(nativeEvent)); // If change and propertychange bubbled, we'd just bind to it like all the\n // other events and have it go through ReactBrowserEventEmitter. Since it\n // doesn't, we manually listen for the events and so we have to enqueue and\n // process the abstract event manually.\n //\n // Batching is necessary here in order to ensure that all event handlers run\n // before the next rerender (including event handlers attached to ancestor\n // elements instead of directly on the input). Without this, controlled\n // components don't work properly in conjunction with event bubbling because\n // the component is rerendered and the value reverted before all the event\n // handlers can run. See https://github.com/facebook/react/issues/708.\n\n batchedUpdates(runEventInBatch, event);\n}\n\nfunction runEventInBatch(event) {\n runEventsInBatch(event);\n}\n\nfunction getInstIfValueChanged(targetInst) {\n var targetNode = getNodeFromInstance$1(targetInst);\n\n if (updateValueIfChanged(targetNode)) {\n return targetInst;\n }\n}\n\nfunction getTargetInstForChangeEvent(topLevelType, targetInst) {\n if (topLevelType === TOP_CHANGE) {\n return targetInst;\n }\n}\n/**\n * SECTION: handle `input` event\n */\n\n\nvar isInputEventSupported = false;\n\nif (canUseDOM) {\n // IE9 claims to support the input event but fails to trigger it when\n // deleting text, so we ignore its input events.\n isInputEventSupported = isEventSupported('input') && (!document.documentMode || document.documentMode > 9);\n}\n/**\n * (For IE <=9) Starts tracking propertychange events on the passed-in element\n * and override the value property so that we can distinguish user events from\n * value changes in JS.\n */\n\n\nfunction startWatchingForValueChange(target, targetInst) {\n activeElement = target;\n activeElementInst = targetInst;\n activeElement.attachEvent('onpropertychange', handlePropertyChange);\n}\n/**\n * (For IE <=9) Removes the event listeners from the currently-tracked element,\n * if any exists.\n */\n\n\nfunction stopWatchingForValueChange() {\n if (!activeElement) {\n return;\n }\n\n activeElement.detachEvent('onpropertychange', handlePropertyChange);\n activeElement = null;\n activeElementInst = null;\n}\n/**\n * (For IE <=9) Handles a propertychange event, sending a `change` event if\n * the value of the active element has changed.\n */\n\n\nfunction handlePropertyChange(nativeEvent) {\n if (nativeEvent.propertyName !== 'value') {\n return;\n }\n\n if (getInstIfValueChanged(activeElementInst)) {\n manualDispatchChangeEvent(nativeEvent);\n }\n}\n\nfunction handleEventsForInputEventPolyfill(topLevelType, target, targetInst) {\n if (topLevelType === TOP_FOCUS) {\n // In IE9, propertychange fires for most input events but is buggy and\n // doesn't fire when text is deleted, but conveniently, selectionchange\n // appears to fire in all of the remaining cases so we catch those and\n // forward the event if the value has changed\n // In either case, we don't want to call the event handler if the value\n // is changed from JS so we redefine a setter for `.value` that updates\n // our activeElementValue variable, allowing us to ignore those changes\n //\n // stopWatching() should be a noop here but we call it just in case we\n // missed a blur event somehow.\n stopWatchingForValueChange();\n startWatchingForValueChange(target, targetInst);\n } else if (topLevelType === TOP_BLUR) {\n stopWatchingForValueChange();\n }\n} // For IE8 and IE9.\n\n\nfunction getTargetInstForInputEventPolyfill(topLevelType, targetInst) {\n if (topLevelType === TOP_SELECTION_CHANGE || topLevelType === TOP_KEY_UP || topLevelType === TOP_KEY_DOWN) {\n // On the selectionchange event, the target is just document which isn't\n // helpful for us so just check activeElement instead.\n //\n // 99% of the time, keydown and keyup aren't necessary. IE8 fails to fire\n // propertychange on the first input event after setting `value` from a\n // script and fires only keydown, keypress, keyup. Catching keyup usually\n // gets it and catching keydown lets us fire an event for the first\n // keystroke if user does a key repeat (it'll be a little delayed: right\n // before the second keystroke). Other input methods (e.g., paste) seem to\n // fire selectionchange normally.\n return getInstIfValueChanged(activeElementInst);\n }\n}\n/**\n * SECTION: handle `click` event\n */\n\n\nfunction shouldUseClickEvent(elem) {\n // Use the `click` event to detect changes to checkbox and radio inputs.\n // This approach works across all browsers, whereas `change` does not fire\n // until `blur` in IE8.\n var nodeName = elem.nodeName;\n return nodeName && nodeName.toLowerCase() === 'input' && (elem.type === 'checkbox' || elem.type === 'radio');\n}\n\nfunction getTargetInstForClickEvent(topLevelType, targetInst) {\n if (topLevelType === TOP_CLICK) {\n return getInstIfValueChanged(targetInst);\n }\n}\n\nfunction getTargetInstForInputOrChangeEvent(topLevelType, targetInst) {\n if (topLevelType === TOP_INPUT || topLevelType === TOP_CHANGE) {\n return getInstIfValueChanged(targetInst);\n }\n}\n\nfunction handleControlledInputBlur(node) {\n var state = node._wrapperState;\n\n if (!state || !state.controlled || node.type !== 'number') {\n return;\n }\n\n {\n // If controlled, assign the value attribute to the current value on blur\n setDefaultValue(node, 'number', node.value);\n }\n}\n/**\n * This plugin creates an `onChange` event that normalizes change events\n * across form elements. This event fires at a time when it's possible to\n * change the element's value without seeing a flicker.\n *\n * Supported elements are:\n * - input (see `isTextInputElement`)\n * - textarea\n * - select\n */\n\n\nvar ChangeEventPlugin = {\n eventTypes: eventTypes$1,\n _isInputEventSupported: isInputEventSupported,\n extractEvents: function (topLevelType, targetInst, nativeEvent, nativeEventTarget, eventSystemFlags) {\n var targetNode = targetInst ? getNodeFromInstance$1(targetInst) : window;\n var getTargetInstFunc, handleEventFunc;\n\n if (shouldUseChangeEvent(targetNode)) {\n getTargetInstFunc = getTargetInstForChangeEvent;\n } else if (isTextInputElement(targetNode)) {\n if (isInputEventSupported) {\n getTargetInstFunc = getTargetInstForInputOrChangeEvent;\n } else {\n getTargetInstFunc = getTargetInstForInputEventPolyfill;\n handleEventFunc = handleEventsForInputEventPolyfill;\n }\n } else if (shouldUseClickEvent(targetNode)) {\n getTargetInstFunc = getTargetInstForClickEvent;\n }\n\n if (getTargetInstFunc) {\n var inst = getTargetInstFunc(topLevelType, targetInst);\n\n if (inst) {\n var event = createAndAccumulateChangeEvent(inst, nativeEvent, nativeEventTarget);\n return event;\n }\n }\n\n if (handleEventFunc) {\n handleEventFunc(topLevelType, targetNode, targetInst);\n } // When blurring, set the value attribute for number inputs\n\n\n if (topLevelType === TOP_BLUR) {\n handleControlledInputBlur(targetNode);\n }\n }\n};\n\nvar SyntheticUIEvent = SyntheticEvent.extend({\n view: null,\n detail: null\n});\n\n/**\n * Translation from modifier key to the associated property in the event.\n * @see http://www.w3.org/TR/DOM-Level-3-Events/#keys-Modifiers\n */\nvar modifierKeyToProp = {\n Alt: 'altKey',\n Control: 'ctrlKey',\n Meta: 'metaKey',\n Shift: 'shiftKey'\n}; // Older browsers (Safari <= 10, iOS Safari <= 10.2) do not support\n// getModifierState. If getModifierState is not supported, we map it to a set of\n// modifier keys exposed by the event. In this case, Lock-keys are not supported.\n\nfunction modifierStateGetter(keyArg) {\n var syntheticEvent = this;\n var nativeEvent = syntheticEvent.nativeEvent;\n\n if (nativeEvent.getModifierState) {\n return nativeEvent.getModifierState(keyArg);\n }\n\n var keyProp = modifierKeyToProp[keyArg];\n return keyProp ? !!nativeEvent[keyProp] : false;\n}\n\nfunction getEventModifierState(nativeEvent) {\n return modifierStateGetter;\n}\n\nvar previousScreenX = 0;\nvar previousScreenY = 0; // Use flags to signal movementX/Y has already been set\n\nvar isMovementXSet = false;\nvar isMovementYSet = false;\n/**\n * @interface MouseEvent\n * @see http://www.w3.org/TR/DOM-Level-3-Events/\n */\n\nvar SyntheticMouseEvent = SyntheticUIEvent.extend({\n screenX: null,\n screenY: null,\n clientX: null,\n clientY: null,\n pageX: null,\n pageY: null,\n ctrlKey: null,\n shiftKey: null,\n altKey: null,\n metaKey: null,\n getModifierState: getEventModifierState,\n button: null,\n buttons: null,\n relatedTarget: function (event) {\n return event.relatedTarget || (event.fromElement === event.srcElement ? event.toElement : event.fromElement);\n },\n movementX: function (event) {\n if ('movementX' in event) {\n return event.movementX;\n }\n\n var screenX = previousScreenX;\n previousScreenX = event.screenX;\n\n if (!isMovementXSet) {\n isMovementXSet = true;\n return 0;\n }\n\n return event.type === 'mousemove' ? event.screenX - screenX : 0;\n },\n movementY: function (event) {\n if ('movementY' in event) {\n return event.movementY;\n }\n\n var screenY = previousScreenY;\n previousScreenY = event.screenY;\n\n if (!isMovementYSet) {\n isMovementYSet = true;\n return 0;\n }\n\n return event.type === 'mousemove' ? event.screenY - screenY : 0;\n }\n});\n\n/**\n * @interface PointerEvent\n * @see http://www.w3.org/TR/pointerevents/\n */\n\nvar SyntheticPointerEvent = SyntheticMouseEvent.extend({\n pointerId: null,\n width: null,\n height: null,\n pressure: null,\n tangentialPressure: null,\n tiltX: null,\n tiltY: null,\n twist: null,\n pointerType: null,\n isPrimary: null\n});\n\nvar eventTypes$2 = {\n mouseEnter: {\n registrationName: 'onMouseEnter',\n dependencies: [TOP_MOUSE_OUT, TOP_MOUSE_OVER]\n },\n mouseLeave: {\n registrationName: 'onMouseLeave',\n dependencies: [TOP_MOUSE_OUT, TOP_MOUSE_OVER]\n },\n pointerEnter: {\n registrationName: 'onPointerEnter',\n dependencies: [TOP_POINTER_OUT, TOP_POINTER_OVER]\n },\n pointerLeave: {\n registrationName: 'onPointerLeave',\n dependencies: [TOP_POINTER_OUT, TOP_POINTER_OVER]\n }\n};\nvar EnterLeaveEventPlugin = {\n eventTypes: eventTypes$2,\n\n /**\n * For almost every interaction we care about, there will be both a top-level\n * `mouseover` and `mouseout` event that occurs. Only use `mouseout` so that\n * we do not extract duplicate events. However, moving the mouse into the\n * browser from outside will not fire a `mouseout` event. In this case, we use\n * the `mouseover` top-level event.\n */\n extractEvents: function (topLevelType, targetInst, nativeEvent, nativeEventTarget, eventSystemFlags) {\n var isOverEvent = topLevelType === TOP_MOUSE_OVER || topLevelType === TOP_POINTER_OVER;\n var isOutEvent = topLevelType === TOP_MOUSE_OUT || topLevelType === TOP_POINTER_OUT;\n\n if (isOverEvent && (eventSystemFlags & IS_REPLAYED) === 0 && (nativeEvent.relatedTarget || nativeEvent.fromElement)) {\n // If this is an over event with a target, then we've already dispatched\n // the event in the out event of the other target. If this is replayed,\n // then it's because we couldn't dispatch against this target previously\n // so we have to do it now instead.\n return null;\n }\n\n if (!isOutEvent && !isOverEvent) {\n // Must not be a mouse or pointer in or out - ignoring.\n return null;\n }\n\n var win;\n\n if (nativeEventTarget.window === nativeEventTarget) {\n // `nativeEventTarget` is probably a window object.\n win = nativeEventTarget;\n } else {\n // TODO: Figure out why `ownerDocument` is sometimes undefined in IE8.\n var doc = nativeEventTarget.ownerDocument;\n\n if (doc) {\n win = doc.defaultView || doc.parentWindow;\n } else {\n win = window;\n }\n }\n\n var from;\n var to;\n\n if (isOutEvent) {\n from = targetInst;\n var related = nativeEvent.relatedTarget || nativeEvent.toElement;\n to = related ? getClosestInstanceFromNode(related) : null;\n\n if (to !== null) {\n var nearestMounted = getNearestMountedFiber(to);\n\n if (to !== nearestMounted || to.tag !== HostComponent && to.tag !== HostText) {\n to = null;\n }\n }\n } else {\n // Moving to a node from outside the window.\n from = null;\n to = targetInst;\n }\n\n if (from === to) {\n // Nothing pertains to our managed components.\n return null;\n }\n\n var eventInterface, leaveEventType, enterEventType, eventTypePrefix;\n\n if (topLevelType === TOP_MOUSE_OUT || topLevelType === TOP_MOUSE_OVER) {\n eventInterface = SyntheticMouseEvent;\n leaveEventType = eventTypes$2.mouseLeave;\n enterEventType = eventTypes$2.mouseEnter;\n eventTypePrefix = 'mouse';\n } else if (topLevelType === TOP_POINTER_OUT || topLevelType === TOP_POINTER_OVER) {\n eventInterface = SyntheticPointerEvent;\n leaveEventType = eventTypes$2.pointerLeave;\n enterEventType = eventTypes$2.pointerEnter;\n eventTypePrefix = 'pointer';\n }\n\n var fromNode = from == null ? win : getNodeFromInstance$1(from);\n var toNode = to == null ? win : getNodeFromInstance$1(to);\n var leave = eventInterface.getPooled(leaveEventType, from, nativeEvent, nativeEventTarget);\n leave.type = eventTypePrefix + 'leave';\n leave.target = fromNode;\n leave.relatedTarget = toNode;\n var enter = eventInterface.getPooled(enterEventType, to, nativeEvent, nativeEventTarget);\n enter.type = eventTypePrefix + 'enter';\n enter.target = toNode;\n enter.relatedTarget = fromNode;\n accumulateEnterLeaveDispatches(leave, enter, from, to); // If we are not processing the first ancestor, then we\n // should not process the same nativeEvent again, as we\n // will have already processed it in the first ancestor.\n\n if ((eventSystemFlags & IS_FIRST_ANCESTOR) === 0) {\n return [leave];\n }\n\n return [leave, enter];\n }\n};\n\n/**\n * inlined Object.is polyfill to avoid requiring consumers ship their own\n * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is\n */\nfunction is(x, y) {\n return x === y && (x !== 0 || 1 / x === 1 / y) || x !== x && y !== y // eslint-disable-line no-self-compare\n ;\n}\n\nvar objectIs = typeof Object.is === 'function' ? Object.is : is;\n\nvar hasOwnProperty$2 = Object.prototype.hasOwnProperty;\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 * Returns true when the values of all keys are strictly equal.\n */\n\nfunction shallowEqual(objA, objB) {\n if (objectIs(objA, objB)) {\n return true;\n }\n\n if (typeof objA !== 'object' || objA === null || typeof objB !== 'object' || objB === null) {\n return false;\n }\n\n var keysA = Object.keys(objA);\n var keysB = Object.keys(objB);\n\n if (keysA.length !== keysB.length) {\n return false;\n } // Test for A's keys different from B.\n\n\n for (var i = 0; i < keysA.length; i++) {\n if (!hasOwnProperty$2.call(objB, keysA[i]) || !objectIs(objA[keysA[i]], objB[keysA[i]])) {\n return false;\n }\n }\n\n return true;\n}\n\nvar skipSelectionChangeEvent = canUseDOM && 'documentMode' in document && document.documentMode <= 11;\nvar eventTypes$3 = {\n select: {\n phasedRegistrationNames: {\n bubbled: 'onSelect',\n captured: 'onSelectCapture'\n },\n dependencies: [TOP_BLUR, TOP_CONTEXT_MENU, TOP_DRAG_END, TOP_FOCUS, TOP_KEY_DOWN, TOP_KEY_UP, TOP_MOUSE_DOWN, TOP_MOUSE_UP, TOP_SELECTION_CHANGE]\n }\n};\nvar activeElement$1 = null;\nvar activeElementInst$1 = null;\nvar lastSelection = null;\nvar mouseDown = false;\n/**\n * Get an object which is a unique representation of the current selection.\n *\n * The return value will not be consistent across nodes or browsers, but\n * two identical selections on the same node will return identical objects.\n *\n * @param {DOMElement} node\n * @return {object}\n */\n\nfunction getSelection$1(node) {\n if ('selectionStart' in node && hasSelectionCapabilities(node)) {\n return {\n start: node.selectionStart,\n end: node.selectionEnd\n };\n } else {\n var win = node.ownerDocument && node.ownerDocument.defaultView || window;\n var selection = win.getSelection();\n return {\n anchorNode: selection.anchorNode,\n anchorOffset: selection.anchorOffset,\n focusNode: selection.focusNode,\n focusOffset: selection.focusOffset\n };\n }\n}\n/**\n * Get document associated with the event target.\n *\n * @param {object} nativeEventTarget\n * @return {Document}\n */\n\n\nfunction getEventTargetDocument(eventTarget) {\n return eventTarget.window === eventTarget ? eventTarget.document : eventTarget.nodeType === DOCUMENT_NODE ? eventTarget : eventTarget.ownerDocument;\n}\n/**\n * Poll selection to see whether it's changed.\n *\n * @param {object} nativeEvent\n * @param {object} nativeEventTarget\n * @return {?SyntheticEvent}\n */\n\n\nfunction constructSelectEvent(nativeEvent, nativeEventTarget) {\n // Ensure we have the right element, and that the user is not dragging a\n // selection (this matches native `select` event behavior). In HTML5, select\n // fires only on input and textarea thus if there's no focused element we\n // won't dispatch.\n var doc = getEventTargetDocument(nativeEventTarget);\n\n if (mouseDown || activeElement$1 == null || activeElement$1 !== getActiveElement(doc)) {\n return null;\n } // Only fire when selection has actually changed.\n\n\n var currentSelection = getSelection$1(activeElement$1);\n\n if (!lastSelection || !shallowEqual(lastSelection, currentSelection)) {\n lastSelection = currentSelection;\n var syntheticEvent = SyntheticEvent.getPooled(eventTypes$3.select, activeElementInst$1, nativeEvent, nativeEventTarget);\n syntheticEvent.type = 'select';\n syntheticEvent.target = activeElement$1;\n accumulateTwoPhaseDispatches(syntheticEvent);\n return syntheticEvent;\n }\n\n return null;\n}\n/**\n * This plugin creates an `onSelect` event that normalizes select events\n * across form elements.\n *\n * Supported elements are:\n * - input (see `isTextInputElement`)\n * - textarea\n * - contentEditable\n *\n * This differs from native browser implementations in the following ways:\n * - Fires on contentEditable fields as well as inputs.\n * - Fires for collapsed selection.\n * - Fires after user input.\n */\n\n\nvar SelectEventPlugin = {\n eventTypes: eventTypes$3,\n extractEvents: function (topLevelType, targetInst, nativeEvent, nativeEventTarget, eventSystemFlags, container) {\n var containerOrDoc = container || getEventTargetDocument(nativeEventTarget); // Track whether all listeners exists for this plugin. If none exist, we do\n // not extract events. See #3639.\n\n if (!containerOrDoc || !isListeningToAllDependencies('onSelect', containerOrDoc)) {\n return null;\n }\n\n var targetNode = targetInst ? getNodeFromInstance$1(targetInst) : window;\n\n switch (topLevelType) {\n // Track the input node that has focus.\n case TOP_FOCUS:\n if (isTextInputElement(targetNode) || targetNode.contentEditable === 'true') {\n activeElement$1 = targetNode;\n activeElementInst$1 = targetInst;\n lastSelection = null;\n }\n\n break;\n\n case TOP_BLUR:\n activeElement$1 = null;\n activeElementInst$1 = null;\n lastSelection = null;\n break;\n // Don't fire the event while the user is dragging. This matches the\n // semantics of the native select event.\n\n case TOP_MOUSE_DOWN:\n mouseDown = true;\n break;\n\n case TOP_CONTEXT_MENU:\n case TOP_MOUSE_UP:\n case TOP_DRAG_END:\n mouseDown = false;\n return constructSelectEvent(nativeEvent, nativeEventTarget);\n // Chrome and IE fire non-standard event when selection is changed (and\n // sometimes when it hasn't). IE's event fires out of order with respect\n // to key and input events on deletion, so we discard it.\n //\n // Firefox doesn't support selectionchange, so check selection status\n // after each key entry. The selection changes after keydown and before\n // keyup, but we check on keydown as well in the case of holding down a\n // key, when multiple keydown events are fired but only one keyup is.\n // This is also our approach for IE handling, for the reason above.\n\n case TOP_SELECTION_CHANGE:\n if (skipSelectionChangeEvent) {\n break;\n }\n\n // falls through\n\n case TOP_KEY_DOWN:\n case TOP_KEY_UP:\n return constructSelectEvent(nativeEvent, nativeEventTarget);\n }\n\n return null;\n }\n};\n\n/**\n * @interface Event\n * @see http://www.w3.org/TR/css3-animations/#AnimationEvent-interface\n * @see https://developer.mozilla.org/en-US/docs/Web/API/AnimationEvent\n */\n\nvar SyntheticAnimationEvent = SyntheticEvent.extend({\n animationName: null,\n elapsedTime: null,\n pseudoElement: null\n});\n\n/**\n * @interface Event\n * @see http://www.w3.org/TR/clipboard-apis/\n */\n\nvar SyntheticClipboardEvent = SyntheticEvent.extend({\n clipboardData: function (event) {\n return 'clipboardData' in event ? event.clipboardData : window.clipboardData;\n }\n});\n\n/**\n * @interface FocusEvent\n * @see http://www.w3.org/TR/DOM-Level-3-Events/\n */\n\nvar SyntheticFocusEvent = SyntheticUIEvent.extend({\n relatedTarget: null\n});\n\n/**\n * `charCode` represents the actual \"character code\" and is safe to use with\n * `String.fromCharCode`. As such, only keys that correspond to printable\n * characters produce a valid `charCode`, the only exception to this is Enter.\n * The Tab-key is considered non-printable and does not have a `charCode`,\n * presumably because it does not produce a tab-character in browsers.\n *\n * @param {object} nativeEvent Native browser event.\n * @return {number} Normalized `charCode` property.\n */\nfunction getEventCharCode(nativeEvent) {\n var charCode;\n var keyCode = nativeEvent.keyCode;\n\n if ('charCode' in nativeEvent) {\n charCode = nativeEvent.charCode; // FF does not set `charCode` for the Enter-key, check against `keyCode`.\n\n if (charCode === 0 && keyCode === 13) {\n charCode = 13;\n }\n } else {\n // IE8 does not implement `charCode`, but `keyCode` has the correct value.\n charCode = keyCode;\n } // IE and Edge (on Windows) and Chrome / Safari (on Windows and Linux)\n // report Enter as charCode 10 when ctrl is pressed.\n\n\n if (charCode === 10) {\n charCode = 13;\n } // Some non-printable keys are reported in `charCode`/`keyCode`, discard them.\n // Must not discard the (non-)printable Enter-key.\n\n\n if (charCode >= 32 || charCode === 13) {\n return charCode;\n }\n\n return 0;\n}\n\n/**\n * Normalization of deprecated HTML5 `key` values\n * @see https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent#Key_names\n */\n\nvar normalizeKey = {\n Esc: 'Escape',\n Spacebar: ' ',\n Left: 'ArrowLeft',\n Up: 'ArrowUp',\n Right: 'ArrowRight',\n Down: 'ArrowDown',\n Del: 'Delete',\n Win: 'OS',\n Menu: 'ContextMenu',\n Apps: 'ContextMenu',\n Scroll: 'ScrollLock',\n MozPrintableKey: 'Unidentified'\n};\n/**\n * Translation from legacy `keyCode` to HTML5 `key`\n * Only special keys supported, all others depend on keyboard layout or browser\n * @see https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent#Key_names\n */\n\nvar translateToKey = {\n '8': 'Backspace',\n '9': 'Tab',\n '12': 'Clear',\n '13': 'Enter',\n '16': 'Shift',\n '17': 'Control',\n '18': 'Alt',\n '19': 'Pause',\n '20': 'CapsLock',\n '27': 'Escape',\n '32': ' ',\n '33': 'PageUp',\n '34': 'PageDown',\n '35': 'End',\n '36': 'Home',\n '37': 'ArrowLeft',\n '38': 'ArrowUp',\n '39': 'ArrowRight',\n '40': 'ArrowDown',\n '45': 'Insert',\n '46': 'Delete',\n '112': 'F1',\n '113': 'F2',\n '114': 'F3',\n '115': 'F4',\n '116': 'F5',\n '117': 'F6',\n '118': 'F7',\n '119': 'F8',\n '120': 'F9',\n '121': 'F10',\n '122': 'F11',\n '123': 'F12',\n '144': 'NumLock',\n '145': 'ScrollLock',\n '224': 'Meta'\n};\n/**\n * @param {object} nativeEvent Native browser event.\n * @return {string} Normalized `key` property.\n */\n\nfunction getEventKey(nativeEvent) {\n if (nativeEvent.key) {\n // Normalize inconsistent values reported by browsers due to\n // implementations of a working draft specification.\n // FireFox implements `key` but returns `MozPrintableKey` for all\n // printable characters (normalized to `Unidentified`), ignore it.\n var key = normalizeKey[nativeEvent.key] || nativeEvent.key;\n\n if (key !== 'Unidentified') {\n return key;\n }\n } // Browser does not implement `key`, polyfill as much of it as we can.\n\n\n if (nativeEvent.type === 'keypress') {\n var charCode = getEventCharCode(nativeEvent); // The enter-key is technically both printable and non-printable and can\n // thus be captured by `keypress`, no other non-printable key should.\n\n return charCode === 13 ? 'Enter' : String.fromCharCode(charCode);\n }\n\n if (nativeEvent.type === 'keydown' || nativeEvent.type === 'keyup') {\n // While user keyboard layout determines the actual meaning of each\n // `keyCode` value, almost all function keys have a universal value.\n return translateToKey[nativeEvent.keyCode] || 'Unidentified';\n }\n\n return '';\n}\n\n/**\n * @interface KeyboardEvent\n * @see http://www.w3.org/TR/DOM-Level-3-Events/\n */\n\nvar SyntheticKeyboardEvent = SyntheticUIEvent.extend({\n key: getEventKey,\n location: null,\n ctrlKey: null,\n shiftKey: null,\n altKey: null,\n metaKey: null,\n repeat: null,\n locale: null,\n getModifierState: getEventModifierState,\n // Legacy Interface\n charCode: function (event) {\n // `charCode` is the result of a KeyPress event and represents the value of\n // the actual printable character.\n // KeyPress is deprecated, but its replacement is not yet final and not\n // implemented in any major browser. Only KeyPress has charCode.\n if (event.type === 'keypress') {\n return getEventCharCode(event);\n }\n\n return 0;\n },\n keyCode: function (event) {\n // `keyCode` is the result of a KeyDown/Up event and represents the value of\n // physical keyboard key.\n // The actual meaning of the value depends on the users' keyboard layout\n // which cannot be detected. Assuming that it is a US keyboard layout\n // provides a surprisingly accurate mapping for US and European users.\n // Due to this, it is left to the user to implement at this time.\n if (event.type === 'keydown' || event.type === 'keyup') {\n return event.keyCode;\n }\n\n return 0;\n },\n which: function (event) {\n // `which` is an alias for either `keyCode` or `charCode` depending on the\n // type of the event.\n if (event.type === 'keypress') {\n return getEventCharCode(event);\n }\n\n if (event.type === 'keydown' || event.type === 'keyup') {\n return event.keyCode;\n }\n\n return 0;\n }\n});\n\n/**\n * @interface DragEvent\n * @see http://www.w3.org/TR/DOM-Level-3-Events/\n */\n\nvar SyntheticDragEvent = SyntheticMouseEvent.extend({\n dataTransfer: null\n});\n\n/**\n * @interface TouchEvent\n * @see http://www.w3.org/TR/touch-events/\n */\n\nvar SyntheticTouchEvent = SyntheticUIEvent.extend({\n touches: null,\n targetTouches: null,\n changedTouches: null,\n altKey: null,\n metaKey: null,\n ctrlKey: null,\n shiftKey: null,\n getModifierState: getEventModifierState\n});\n\n/**\n * @interface Event\n * @see http://www.w3.org/TR/2009/WD-css3-transitions-20090320/#transition-events-\n * @see https://developer.mozilla.org/en-US/docs/Web/API/TransitionEvent\n */\n\nvar SyntheticTransitionEvent = SyntheticEvent.extend({\n propertyName: null,\n elapsedTime: null,\n pseudoElement: null\n});\n\n/**\n * @interface WheelEvent\n * @see http://www.w3.org/TR/DOM-Level-3-Events/\n */\n\nvar SyntheticWheelEvent = SyntheticMouseEvent.extend({\n deltaX: function (event) {\n return 'deltaX' in event ? event.deltaX : // Fallback to `wheelDeltaX` for Webkit and normalize (right is positive).\n 'wheelDeltaX' in event ? -event.wheelDeltaX : 0;\n },\n deltaY: function (event) {\n return 'deltaY' in event ? event.deltaY : // Fallback to `wheelDeltaY` for Webkit and normalize (down is positive).\n 'wheelDeltaY' in event ? -event.wheelDeltaY : // Fallback to `wheelDelta` for IE<9 and normalize (down is positive).\n 'wheelDelta' in event ? -event.wheelDelta : 0;\n },\n deltaZ: null,\n // Browsers without \"deltaMode\" is reporting in raw wheel delta where one\n // notch on the scroll is always +/- 120, roughly equivalent to pixels.\n // A good approximation of DOM_DELTA_LINE (1) is 5% of viewport size or\n // ~40 pixels, for DOM_DELTA_SCREEN (2) it is 87.5% of viewport size.\n deltaMode: null\n});\n\nvar knownHTMLTopLevelTypes = [TOP_ABORT, TOP_CANCEL, TOP_CAN_PLAY, TOP_CAN_PLAY_THROUGH, TOP_CLOSE, TOP_DURATION_CHANGE, TOP_EMPTIED, TOP_ENCRYPTED, TOP_ENDED, TOP_ERROR, TOP_INPUT, TOP_INVALID, TOP_LOAD, TOP_LOADED_DATA, TOP_LOADED_METADATA, TOP_LOAD_START, TOP_PAUSE, TOP_PLAY, TOP_PLAYING, TOP_PROGRESS, TOP_RATE_CHANGE, TOP_RESET, TOP_SEEKED, TOP_SEEKING, TOP_STALLED, TOP_SUBMIT, TOP_SUSPEND, TOP_TIME_UPDATE, TOP_TOGGLE, TOP_VOLUME_CHANGE, TOP_WAITING];\nvar SimpleEventPlugin = {\n // simpleEventPluginEventTypes gets populated from\n // the DOMEventProperties module.\n eventTypes: simpleEventPluginEventTypes,\n extractEvents: function (topLevelType, targetInst, nativeEvent, nativeEventTarget, eventSystemFlags) {\n var dispatchConfig = topLevelEventsToDispatchConfig.get(topLevelType);\n\n if (!dispatchConfig) {\n return null;\n }\n\n var EventConstructor;\n\n switch (topLevelType) {\n case TOP_KEY_PRESS:\n // Firefox creates a keypress event for function keys too. This removes\n // the unwanted keypress events. Enter is however both printable and\n // non-printable. One would expect Tab to be as well (but it isn't).\n if (getEventCharCode(nativeEvent) === 0) {\n return null;\n }\n\n /* falls through */\n\n case TOP_KEY_DOWN:\n case TOP_KEY_UP:\n EventConstructor = SyntheticKeyboardEvent;\n break;\n\n case TOP_BLUR:\n case TOP_FOCUS:\n EventConstructor = SyntheticFocusEvent;\n break;\n\n case TOP_CLICK:\n // Firefox creates a click event on right mouse clicks. This removes the\n // unwanted click events.\n if (nativeEvent.button === 2) {\n return null;\n }\n\n /* falls through */\n\n case TOP_AUX_CLICK:\n case TOP_DOUBLE_CLICK:\n case TOP_MOUSE_DOWN:\n case TOP_MOUSE_MOVE:\n case TOP_MOUSE_UP: // TODO: Disabled elements should not respond to mouse events\n\n /* falls through */\n\n case TOP_MOUSE_OUT:\n case TOP_MOUSE_OVER:\n case TOP_CONTEXT_MENU:\n EventConstructor = SyntheticMouseEvent;\n break;\n\n case TOP_DRAG:\n case TOP_DRAG_END:\n case TOP_DRAG_ENTER:\n case TOP_DRAG_EXIT:\n case TOP_DRAG_LEAVE:\n case TOP_DRAG_OVER:\n case TOP_DRAG_START:\n case TOP_DROP:\n EventConstructor = SyntheticDragEvent;\n break;\n\n case TOP_TOUCH_CANCEL:\n case TOP_TOUCH_END:\n case TOP_TOUCH_MOVE:\n case TOP_TOUCH_START:\n EventConstructor = SyntheticTouchEvent;\n break;\n\n case TOP_ANIMATION_END:\n case TOP_ANIMATION_ITERATION:\n case TOP_ANIMATION_START:\n EventConstructor = SyntheticAnimationEvent;\n break;\n\n case TOP_TRANSITION_END:\n EventConstructor = SyntheticTransitionEvent;\n break;\n\n case TOP_SCROLL:\n EventConstructor = SyntheticUIEvent;\n break;\n\n case TOP_WHEEL:\n EventConstructor = SyntheticWheelEvent;\n break;\n\n case TOP_COPY:\n case TOP_CUT:\n case TOP_PASTE:\n EventConstructor = SyntheticClipboardEvent;\n break;\n\n case TOP_GOT_POINTER_CAPTURE:\n case TOP_LOST_POINTER_CAPTURE:\n case TOP_POINTER_CANCEL:\n case TOP_POINTER_DOWN:\n case TOP_POINTER_MOVE:\n case TOP_POINTER_OUT:\n case TOP_POINTER_OVER:\n case TOP_POINTER_UP:\n EventConstructor = SyntheticPointerEvent;\n break;\n\n default:\n {\n if (knownHTMLTopLevelTypes.indexOf(topLevelType) === -1) {\n error('SimpleEventPlugin: Unhandled event type, `%s`. This warning ' + 'is likely caused by a bug in React. Please file an issue.', topLevelType);\n }\n } // HTML Events\n // @see http://www.w3.org/TR/html5/index.html#events-0\n\n\n EventConstructor = SyntheticEvent;\n break;\n }\n\n var event = EventConstructor.getPooled(dispatchConfig, targetInst, nativeEvent, nativeEventTarget);\n accumulateTwoPhaseDispatches(event);\n return event;\n }\n};\n\n/**\n * Specifies a deterministic ordering of `EventPlugin`s. A convenient way to\n * reason about plugins, without having to package every one of them. This\n * is better than having plugins be ordered in the same order that they\n * are injected because that ordering would be influenced by the packaging order.\n * `ResponderEventPlugin` must occur before `SimpleEventPlugin` so that\n * preventing default on events is convenient in `SimpleEventPlugin` handlers.\n */\n\nvar DOMEventPluginOrder = ['ResponderEventPlugin', 'SimpleEventPlugin', 'EnterLeaveEventPlugin', 'ChangeEventPlugin', 'SelectEventPlugin', 'BeforeInputEventPlugin'];\n/**\n * Inject modules for resolving DOM hierarchy and plugin ordering.\n */\n\ninjectEventPluginOrder(DOMEventPluginOrder);\nsetComponentTree(getFiberCurrentPropsFromNode$1, getInstanceFromNode$1, getNodeFromInstance$1);\n/**\n * Some important event plugins included by default (without having to require\n * them).\n */\n\ninjectEventPluginsByName({\n SimpleEventPlugin: SimpleEventPlugin,\n EnterLeaveEventPlugin: EnterLeaveEventPlugin,\n ChangeEventPlugin: ChangeEventPlugin,\n SelectEventPlugin: SelectEventPlugin,\n BeforeInputEventPlugin: BeforeInputEventPlugin\n});\n\n// Prefix measurements so that it's possible to filter them.\n// Longer prefixes are hard to read in DevTools.\nvar reactEmoji = \"\\u269B\";\nvar warningEmoji = \"\\u26D4\";\nvar supportsUserTiming = typeof performance !== 'undefined' && typeof performance.mark === 'function' && typeof performance.clearMarks === 'function' && typeof performance.measure === 'function' && typeof performance.clearMeasures === 'function'; // Keep track of current fiber so that we know the path to unwind on pause.\n// TODO: this looks the same as nextUnitOfWork in scheduler. Can we unify them?\n\nvar currentFiber = null; // If we're in the middle of user code, which fiber and method is it?\n// Reusing `currentFiber` would be confusing for this because user code fiber\n// can change during commit phase too, but we don't need to unwind it (since\n// lifecycles in the commit phase don't resemble a tree).\n\nvar currentPhase = null;\nvar currentPhaseFiber = null; // Did lifecycle hook schedule an update? This is often a performance problem,\n// so we will keep track of it, and include it in the report.\n// Track commits caused by cascading updates.\n\nvar isCommitting = false;\nvar hasScheduledUpdateInCurrentCommit = false;\nvar hasScheduledUpdateInCurrentPhase = false;\nvar commitCountInCurrentWorkLoop = 0;\nvar effectCountInCurrentCommit = 0;\n// to avoid stretch the commit phase with measurement overhead.\n\nvar labelsInCurrentCommit = new Set();\n\nvar formatMarkName = function (markName) {\n return reactEmoji + \" \" + markName;\n};\n\nvar formatLabel = function (label, warning) {\n var prefix = warning ? warningEmoji + \" \" : reactEmoji + \" \";\n var suffix = warning ? \" Warning: \" + warning : '';\n return \"\" + prefix + label + suffix;\n};\n\nvar beginMark = function (markName) {\n performance.mark(formatMarkName(markName));\n};\n\nvar clearMark = function (markName) {\n performance.clearMarks(formatMarkName(markName));\n};\n\nvar endMark = function (label, markName, warning) {\n var formattedMarkName = formatMarkName(markName);\n var formattedLabel = formatLabel(label, warning);\n\n try {\n performance.measure(formattedLabel, formattedMarkName);\n } catch (err) {} // If previous mark was missing for some reason, this will throw.\n // This could only happen if React crashed in an unexpected place earlier.\n // Don't pile on with more errors.\n // Clear marks immediately to avoid growing buffer.\n\n\n performance.clearMarks(formattedMarkName);\n performance.clearMeasures(formattedLabel);\n};\n\nvar getFiberMarkName = function (label, debugID) {\n return label + \" (#\" + debugID + \")\";\n};\n\nvar getFiberLabel = function (componentName, isMounted, phase) {\n if (phase === null) {\n // These are composite component total time measurements.\n return componentName + \" [\" + (isMounted ? 'update' : 'mount') + \"]\";\n } else {\n // Composite component methods.\n return componentName + \".\" + phase;\n }\n};\n\nvar beginFiberMark = function (fiber, phase) {\n var componentName = getComponentName(fiber.type) || 'Unknown';\n var debugID = fiber._debugID;\n var isMounted = fiber.alternate !== null;\n var label = getFiberLabel(componentName, isMounted, phase);\n\n if (isCommitting && labelsInCurrentCommit.has(label)) {\n // During the commit phase, we don't show duplicate labels because\n // there is a fixed overhead for every measurement, and we don't\n // want to stretch the commit phase beyond necessary.\n return false;\n }\n\n labelsInCurrentCommit.add(label);\n var markName = getFiberMarkName(label, debugID);\n beginMark(markName);\n return true;\n};\n\nvar clearFiberMark = function (fiber, phase) {\n var componentName = getComponentName(fiber.type) || 'Unknown';\n var debugID = fiber._debugID;\n var isMounted = fiber.alternate !== null;\n var label = getFiberLabel(componentName, isMounted, phase);\n var markName = getFiberMarkName(label, debugID);\n clearMark(markName);\n};\n\nvar endFiberMark = function (fiber, phase, warning) {\n var componentName = getComponentName(fiber.type) || 'Unknown';\n var debugID = fiber._debugID;\n var isMounted = fiber.alternate !== null;\n var label = getFiberLabel(componentName, isMounted, phase);\n var markName = getFiberMarkName(label, debugID);\n endMark(label, markName, warning);\n};\n\nvar shouldIgnoreFiber = function (fiber) {\n // Host components should be skipped in the timeline.\n // We could check typeof fiber.type, but does this work with RN?\n switch (fiber.tag) {\n case HostRoot:\n case HostComponent:\n case HostText:\n case HostPortal:\n case Fragment:\n case ContextProvider:\n case ContextConsumer:\n case Mode:\n return true;\n\n default:\n return false;\n }\n};\n\nvar clearPendingPhaseMeasurement = function () {\n if (currentPhase !== null && currentPhaseFiber !== null) {\n clearFiberMark(currentPhaseFiber, currentPhase);\n }\n\n currentPhaseFiber = null;\n currentPhase = null;\n hasScheduledUpdateInCurrentPhase = false;\n};\n\nvar pauseTimers = function () {\n // Stops all currently active measurements so that they can be resumed\n // if we continue in a later deferred loop from the same unit of work.\n var fiber = currentFiber;\n\n while (fiber) {\n if (fiber._debugIsCurrentlyTiming) {\n endFiberMark(fiber, null, null);\n }\n\n fiber = fiber.return;\n }\n};\n\nvar resumeTimersRecursively = function (fiber) {\n if (fiber.return !== null) {\n resumeTimersRecursively(fiber.return);\n }\n\n if (fiber._debugIsCurrentlyTiming) {\n beginFiberMark(fiber, null);\n }\n};\n\nvar resumeTimers = function () {\n // Resumes all measurements that were active during the last deferred loop.\n if (currentFiber !== null) {\n resumeTimersRecursively(currentFiber);\n }\n};\n\nfunction recordEffect() {\n {\n effectCountInCurrentCommit++;\n }\n}\nfunction recordScheduleUpdate() {\n {\n if (isCommitting) {\n hasScheduledUpdateInCurrentCommit = true;\n }\n\n if (currentPhase !== null && currentPhase !== 'componentWillMount' && currentPhase !== 'componentWillReceiveProps') {\n hasScheduledUpdateInCurrentPhase = true;\n }\n }\n}\nfunction startWorkTimer(fiber) {\n {\n if (!supportsUserTiming || shouldIgnoreFiber(fiber)) {\n return;\n } // If we pause, this is the fiber to unwind from.\n\n\n currentFiber = fiber;\n\n if (!beginFiberMark(fiber, null)) {\n return;\n }\n\n fiber._debugIsCurrentlyTiming = true;\n }\n}\nfunction cancelWorkTimer(fiber) {\n {\n if (!supportsUserTiming || shouldIgnoreFiber(fiber)) {\n return;\n } // Remember we shouldn't complete measurement for this fiber.\n // Otherwise flamechart will be deep even for small updates.\n\n\n fiber._debugIsCurrentlyTiming = false;\n clearFiberMark(fiber, null);\n }\n}\nfunction stopWorkTimer(fiber) {\n {\n if (!supportsUserTiming || shouldIgnoreFiber(fiber)) {\n return;\n } // If we pause, its parent is the fiber to unwind from.\n\n\n currentFiber = fiber.return;\n\n if (!fiber._debugIsCurrentlyTiming) {\n return;\n }\n\n fiber._debugIsCurrentlyTiming = false;\n endFiberMark(fiber, null, null);\n }\n}\nfunction stopFailedWorkTimer(fiber) {\n {\n if (!supportsUserTiming || shouldIgnoreFiber(fiber)) {\n return;\n } // If we pause, its parent is the fiber to unwind from.\n\n\n currentFiber = fiber.return;\n\n if (!fiber._debugIsCurrentlyTiming) {\n return;\n }\n\n fiber._debugIsCurrentlyTiming = false;\n var warning = fiber.tag === SuspenseComponent ? 'Rendering was suspended' : 'An error was thrown inside this error boundary';\n endFiberMark(fiber, null, warning);\n }\n}\nfunction startPhaseTimer(fiber, phase) {\n {\n if (!supportsUserTiming) {\n return;\n }\n\n clearPendingPhaseMeasurement();\n\n if (!beginFiberMark(fiber, phase)) {\n return;\n }\n\n currentPhaseFiber = fiber;\n currentPhase = phase;\n }\n}\nfunction stopPhaseTimer() {\n {\n if (!supportsUserTiming) {\n return;\n }\n\n if (currentPhase !== null && currentPhaseFiber !== null) {\n var warning = hasScheduledUpdateInCurrentPhase ? 'Scheduled a cascading update' : null;\n endFiberMark(currentPhaseFiber, currentPhase, warning);\n }\n\n currentPhase = null;\n currentPhaseFiber = null;\n }\n}\nfunction startWorkLoopTimer(nextUnitOfWork) {\n {\n currentFiber = nextUnitOfWork;\n\n if (!supportsUserTiming) {\n return;\n }\n\n commitCountInCurrentWorkLoop = 0; // This is top level call.\n // Any other measurements are performed within.\n\n beginMark('(React Tree Reconciliation)'); // Resume any measurements that were in progress during the last loop.\n\n resumeTimers();\n }\n}\nfunction stopWorkLoopTimer(interruptedBy, didCompleteRoot) {\n {\n if (!supportsUserTiming) {\n return;\n }\n\n var warning = null;\n\n if (interruptedBy !== null) {\n if (interruptedBy.tag === HostRoot) {\n warning = 'A top-level update interrupted the previous render';\n } else {\n var componentName = getComponentName(interruptedBy.type) || 'Unknown';\n warning = \"An update to \" + componentName + \" interrupted the previous render\";\n }\n } else if (commitCountInCurrentWorkLoop > 1) {\n warning = 'There were cascading updates';\n }\n\n commitCountInCurrentWorkLoop = 0;\n var label = didCompleteRoot ? '(React Tree Reconciliation: Completed Root)' : '(React Tree Reconciliation: Yielded)'; // Pause any measurements until the next loop.\n\n pauseTimers();\n endMark(label, '(React Tree Reconciliation)', warning);\n }\n}\nfunction startCommitTimer() {\n {\n if (!supportsUserTiming) {\n return;\n }\n\n isCommitting = true;\n hasScheduledUpdateInCurrentCommit = false;\n labelsInCurrentCommit.clear();\n beginMark('(Committing Changes)');\n }\n}\nfunction stopCommitTimer() {\n {\n if (!supportsUserTiming) {\n return;\n }\n\n var warning = null;\n\n if (hasScheduledUpdateInCurrentCommit) {\n warning = 'Lifecycle hook scheduled a cascading update';\n } else if (commitCountInCurrentWorkLoop > 0) {\n warning = 'Caused by a cascading update in earlier commit';\n }\n\n hasScheduledUpdateInCurrentCommit = false;\n commitCountInCurrentWorkLoop++;\n isCommitting = false;\n labelsInCurrentCommit.clear();\n endMark('(Committing Changes)', '(Committing Changes)', warning);\n }\n}\nfunction startCommitSnapshotEffectsTimer() {\n {\n if (!supportsUserTiming) {\n return;\n }\n\n effectCountInCurrentCommit = 0;\n beginMark('(Committing Snapshot Effects)');\n }\n}\nfunction stopCommitSnapshotEffectsTimer() {\n {\n if (!supportsUserTiming) {\n return;\n }\n\n var count = effectCountInCurrentCommit;\n effectCountInCurrentCommit = 0;\n endMark(\"(Committing Snapshot Effects: \" + count + \" Total)\", '(Committing Snapshot Effects)', null);\n }\n}\nfunction startCommitHostEffectsTimer() {\n {\n if (!supportsUserTiming) {\n return;\n }\n\n effectCountInCurrentCommit = 0;\n beginMark('(Committing Host Effects)');\n }\n}\nfunction stopCommitHostEffectsTimer() {\n {\n if (!supportsUserTiming) {\n return;\n }\n\n var count = effectCountInCurrentCommit;\n effectCountInCurrentCommit = 0;\n endMark(\"(Committing Host Effects: \" + count + \" Total)\", '(Committing Host Effects)', null);\n }\n}\nfunction startCommitLifeCyclesTimer() {\n {\n if (!supportsUserTiming) {\n return;\n }\n\n effectCountInCurrentCommit = 0;\n beginMark('(Calling Lifecycle Methods)');\n }\n}\nfunction stopCommitLifeCyclesTimer() {\n {\n if (!supportsUserTiming) {\n return;\n }\n\n var count = effectCountInCurrentCommit;\n effectCountInCurrentCommit = 0;\n endMark(\"(Calling Lifecycle Methods: \" + count + \" Total)\", '(Calling Lifecycle Methods)', null);\n }\n}\n\nvar valueStack = [];\nvar fiberStack;\n\n{\n fiberStack = [];\n}\n\nvar index = -1;\n\nfunction createCursor(defaultValue) {\n return {\n current: defaultValue\n };\n}\n\nfunction pop(cursor, fiber) {\n if (index < 0) {\n {\n error('Unexpected pop.');\n }\n\n return;\n }\n\n {\n if (fiber !== fiberStack[index]) {\n error('Unexpected Fiber popped.');\n }\n }\n\n cursor.current = valueStack[index];\n valueStack[index] = null;\n\n {\n fiberStack[index] = null;\n }\n\n index--;\n}\n\nfunction push(cursor, value, fiber) {\n index++;\n valueStack[index] = cursor.current;\n\n {\n fiberStack[index] = fiber;\n }\n\n cursor.current = value;\n}\n\nvar warnedAboutMissingGetChildContext;\n\n{\n warnedAboutMissingGetChildContext = {};\n}\n\nvar emptyContextObject = {};\n\n{\n Object.freeze(emptyContextObject);\n} // A cursor to the current merged context object on the stack.\n\n\nvar contextStackCursor = createCursor(emptyContextObject); // A cursor to a boolean indicating whether the context has changed.\n\nvar didPerformWorkStackCursor = createCursor(false); // Keep track of the previous context object that was on the stack.\n// We use this to get access to the parent context after we have already\n// pushed the next context provider, and now need to merge their contexts.\n\nvar previousContext = emptyContextObject;\n\nfunction getUnmaskedContext(workInProgress, Component, didPushOwnContextIfProvider) {\n {\n if (didPushOwnContextIfProvider && isContextProvider(Component)) {\n // If the fiber is a context provider itself, when we read its context\n // we may have already pushed its own child context on the stack. A context\n // provider should not \"see\" its own child context. Therefore we read the\n // previous (parent) context instead for a context provider.\n return previousContext;\n }\n\n return contextStackCursor.current;\n }\n}\n\nfunction cacheContext(workInProgress, unmaskedContext, maskedContext) {\n {\n var instance = workInProgress.stateNode;\n instance.__reactInternalMemoizedUnmaskedChildContext = unmaskedContext;\n instance.__reactInternalMemoizedMaskedChildContext = maskedContext;\n }\n}\n\nfunction getMaskedContext(workInProgress, unmaskedContext) {\n {\n var type = workInProgress.type;\n var contextTypes = type.contextTypes;\n\n if (!contextTypes) {\n return emptyContextObject;\n } // Avoid recreating masked context unless unmasked context has changed.\n // Failing to do this will result in unnecessary calls to componentWillReceiveProps.\n // This may trigger infinite loops if componentWillReceiveProps calls setState.\n\n\n var instance = workInProgress.stateNode;\n\n if (instance && instance.__reactInternalMemoizedUnmaskedChildContext === unmaskedContext) {\n return instance.__reactInternalMemoizedMaskedChildContext;\n }\n\n var context = {};\n\n for (var key in contextTypes) {\n context[key] = unmaskedContext[key];\n }\n\n {\n var name = getComponentName(type) || 'Unknown';\n checkPropTypes(contextTypes, context, 'context', name, getCurrentFiberStackInDev);\n } // Cache unmasked context so we can avoid recreating masked context unless necessary.\n // Context is created before the class component is instantiated so check for instance.\n\n\n if (instance) {\n cacheContext(workInProgress, unmaskedContext, context);\n }\n\n return context;\n }\n}\n\nfunction hasContextChanged() {\n {\n return didPerformWorkStackCursor.current;\n }\n}\n\nfunction isContextProvider(type) {\n {\n var childContextTypes = type.childContextTypes;\n return childContextTypes !== null && childContextTypes !== undefined;\n }\n}\n\nfunction popContext(fiber) {\n {\n pop(didPerformWorkStackCursor, fiber);\n pop(contextStackCursor, fiber);\n }\n}\n\nfunction popTopLevelContextObject(fiber) {\n {\n pop(didPerformWorkStackCursor, fiber);\n pop(contextStackCursor, fiber);\n }\n}\n\nfunction pushTopLevelContextObject(fiber, context, didChange) {\n {\n if (!(contextStackCursor.current === emptyContextObject)) {\n {\n throw Error( \"Unexpected context found on stack. This error is likely caused by a bug in React. Please file an issue.\" );\n }\n }\n\n push(contextStackCursor, context, fiber);\n push(didPerformWorkStackCursor, didChange, fiber);\n }\n}\n\nfunction processChildContext(fiber, type, parentContext) {\n {\n var instance = fiber.stateNode;\n var childContextTypes = type.childContextTypes; // TODO (bvaughn) Replace this behavior with an invariant() in the future.\n // It has only been added in Fiber to match the (unintentional) behavior in Stack.\n\n if (typeof instance.getChildContext !== 'function') {\n {\n var componentName = getComponentName(type) || 'Unknown';\n\n if (!warnedAboutMissingGetChildContext[componentName]) {\n warnedAboutMissingGetChildContext[componentName] = true;\n\n error('%s.childContextTypes is specified but there is no getChildContext() method ' + 'on the instance. You can either define getChildContext() on %s or remove ' + 'childContextTypes from it.', componentName, componentName);\n }\n }\n\n return parentContext;\n }\n\n var childContext;\n startPhaseTimer(fiber, 'getChildContext');\n childContext = instance.getChildContext();\n stopPhaseTimer();\n\n for (var contextKey in childContext) {\n if (!(contextKey in childContextTypes)) {\n {\n throw Error( (getComponentName(type) || 'Unknown') + \".getChildContext(): key \\\"\" + contextKey + \"\\\" is not defined in childContextTypes.\" );\n }\n }\n }\n\n {\n var name = getComponentName(type) || 'Unknown';\n checkPropTypes(childContextTypes, childContext, 'child context', name, // In practice, there is one case in which we won't get a stack. It's when\n // somebody calls unstable_renderSubtreeIntoContainer() and we process\n // context from the parent component instance. The stack will be missing\n // because it's outside of the reconciliation, and so the pointer has not\n // been set. This is rare and doesn't matter. We'll also remove that API.\n getCurrentFiberStackInDev);\n }\n\n return _assign({}, parentContext, {}, childContext);\n }\n}\n\nfunction pushContextProvider(workInProgress) {\n {\n var instance = workInProgress.stateNode; // We push the context as early as possible to ensure stack integrity.\n // If the instance does not exist yet, we will push null at first,\n // and replace it on the stack later when invalidating the context.\n\n var memoizedMergedChildContext = instance && instance.__reactInternalMemoizedMergedChildContext || emptyContextObject; // Remember the parent context so we can merge with it later.\n // Inherit the parent's did-perform-work value to avoid inadvertently blocking updates.\n\n previousContext = contextStackCursor.current;\n push(contextStackCursor, memoizedMergedChildContext, workInProgress);\n push(didPerformWorkStackCursor, didPerformWorkStackCursor.current, workInProgress);\n return true;\n }\n}\n\nfunction invalidateContextProvider(workInProgress, type, didChange) {\n {\n var instance = workInProgress.stateNode;\n\n if (!instance) {\n {\n throw Error( \"Expected to have an instance by this point. This error is likely caused by a bug in React. Please file an issue.\" );\n }\n }\n\n if (didChange) {\n // Merge parent and own context.\n // Skip this if we're not updating due to sCU.\n // This avoids unnecessarily recomputing memoized values.\n var mergedContext = processChildContext(workInProgress, type, previousContext);\n instance.__reactInternalMemoizedMergedChildContext = mergedContext; // Replace the old (or empty) context with the new one.\n // It is important to unwind the context in the reverse order.\n\n pop(didPerformWorkStackCursor, workInProgress);\n pop(contextStackCursor, workInProgress); // Now push the new context and mark that it has changed.\n\n push(contextStackCursor, mergedContext, workInProgress);\n push(didPerformWorkStackCursor, didChange, workInProgress);\n } else {\n pop(didPerformWorkStackCursor, workInProgress);\n push(didPerformWorkStackCursor, didChange, workInProgress);\n }\n }\n}\n\nfunction findCurrentUnmaskedContext(fiber) {\n {\n // Currently this is only used with renderSubtreeIntoContainer; not sure if it\n // makes sense elsewhere\n if (!(isFiberMounted(fiber) && fiber.tag === ClassComponent)) {\n {\n throw Error( \"Expected subtree parent to be a mounted class component. This error is likely caused by a bug in React. Please file an issue.\" );\n }\n }\n\n var node = fiber;\n\n do {\n switch (node.tag) {\n case HostRoot:\n return node.stateNode.context;\n\n case ClassComponent:\n {\n var Component = node.type;\n\n if (isContextProvider(Component)) {\n return node.stateNode.__reactInternalMemoizedMergedChildContext;\n }\n\n break;\n }\n }\n\n node = node.return;\n } while (node !== null);\n\n {\n {\n throw Error( \"Found unexpected detached subtree parent. This error is likely caused by a bug in React. Please file an issue.\" );\n }\n }\n }\n}\n\nvar LegacyRoot = 0;\nvar BlockingRoot = 1;\nvar ConcurrentRoot = 2;\n\nvar Scheduler_runWithPriority = Scheduler.unstable_runWithPriority,\n Scheduler_scheduleCallback = Scheduler.unstable_scheduleCallback,\n Scheduler_cancelCallback = Scheduler.unstable_cancelCallback,\n Scheduler_shouldYield = Scheduler.unstable_shouldYield,\n Scheduler_requestPaint = Scheduler.unstable_requestPaint,\n Scheduler_now = Scheduler.unstable_now,\n Scheduler_getCurrentPriorityLevel = Scheduler.unstable_getCurrentPriorityLevel,\n Scheduler_ImmediatePriority = Scheduler.unstable_ImmediatePriority,\n Scheduler_UserBlockingPriority = Scheduler.unstable_UserBlockingPriority,\n Scheduler_NormalPriority = Scheduler.unstable_NormalPriority,\n Scheduler_LowPriority = Scheduler.unstable_LowPriority,\n Scheduler_IdlePriority = Scheduler.unstable_IdlePriority;\n\n{\n // Provide explicit error message when production+profiling bundle of e.g.\n // react-dom is used with production (non-profiling) bundle of\n // scheduler/tracing\n if (!(tracing.__interactionsRef != null && tracing.__interactionsRef.current != null)) {\n {\n throw Error( \"It is not supported to run the profiling version of a renderer (for example, `react-dom/profiling`) without also replacing the `scheduler/tracing` module with `scheduler/tracing-profiling`. Your bundler might have a setting for aliasing both modules. Learn more at http://fb.me/react-profiling\" );\n }\n }\n}\n\nvar fakeCallbackNode = {}; // Except for NoPriority, these correspond to Scheduler priorities. We use\n// ascending numbers so we can compare them like numbers. They start at 90 to\n// avoid clashing with Scheduler's priorities.\n\nvar ImmediatePriority = 99;\nvar UserBlockingPriority$1 = 98;\nvar NormalPriority = 97;\nvar LowPriority = 96;\nvar IdlePriority = 95; // NoPriority is the absence of priority. Also React-only.\n\nvar NoPriority = 90;\nvar shouldYield = Scheduler_shouldYield;\nvar requestPaint = // Fall back gracefully if we're running an older version of Scheduler.\nScheduler_requestPaint !== undefined ? Scheduler_requestPaint : function () {};\nvar syncQueue = null;\nvar immediateQueueCallbackNode = null;\nvar isFlushingSyncQueue = false;\nvar initialTimeMs = Scheduler_now(); // If the initial timestamp is reasonably small, use Scheduler's `now` directly.\n// This will be the case for modern browsers that support `performance.now`. In\n// older browsers, Scheduler falls back to `Date.now`, which returns a Unix\n// timestamp. In that case, subtract the module initialization time to simulate\n// the behavior of performance.now and keep our times small enough to fit\n// within 32 bits.\n// TODO: Consider lifting this into Scheduler.\n\nvar now = initialTimeMs < 10000 ? Scheduler_now : function () {\n return Scheduler_now() - initialTimeMs;\n};\nfunction getCurrentPriorityLevel() {\n switch (Scheduler_getCurrentPriorityLevel()) {\n case Scheduler_ImmediatePriority:\n return ImmediatePriority;\n\n case Scheduler_UserBlockingPriority:\n return UserBlockingPriority$1;\n\n case Scheduler_NormalPriority:\n return NormalPriority;\n\n case Scheduler_LowPriority:\n return LowPriority;\n\n case Scheduler_IdlePriority:\n return IdlePriority;\n\n default:\n {\n {\n throw Error( \"Unknown priority level.\" );\n }\n }\n\n }\n}\n\nfunction reactPriorityToSchedulerPriority(reactPriorityLevel) {\n switch (reactPriorityLevel) {\n case ImmediatePriority:\n return Scheduler_ImmediatePriority;\n\n case UserBlockingPriority$1:\n return Scheduler_UserBlockingPriority;\n\n case NormalPriority:\n return Scheduler_NormalPriority;\n\n case LowPriority:\n return Scheduler_LowPriority;\n\n case IdlePriority:\n return Scheduler_IdlePriority;\n\n default:\n {\n {\n throw Error( \"Unknown priority level.\" );\n }\n }\n\n }\n}\n\nfunction runWithPriority$1(reactPriorityLevel, fn) {\n var priorityLevel = reactPriorityToSchedulerPriority(reactPriorityLevel);\n return Scheduler_runWithPriority(priorityLevel, fn);\n}\nfunction scheduleCallback(reactPriorityLevel, callback, options) {\n var priorityLevel = reactPriorityToSchedulerPriority(reactPriorityLevel);\n return Scheduler_scheduleCallback(priorityLevel, callback, options);\n}\nfunction scheduleSyncCallback(callback) {\n // Push this callback into an internal queue. We'll flush these either in\n // the next tick, or earlier if something calls `flushSyncCallbackQueue`.\n if (syncQueue === null) {\n syncQueue = [callback]; // Flush the queue in the next tick, at the earliest.\n\n immediateQueueCallbackNode = Scheduler_scheduleCallback(Scheduler_ImmediatePriority, flushSyncCallbackQueueImpl);\n } else {\n // Push onto existing queue. Don't need to schedule a callback because\n // we already scheduled one when we created the queue.\n syncQueue.push(callback);\n }\n\n return fakeCallbackNode;\n}\nfunction cancelCallback(callbackNode) {\n if (callbackNode !== fakeCallbackNode) {\n Scheduler_cancelCallback(callbackNode);\n }\n}\nfunction flushSyncCallbackQueue() {\n if (immediateQueueCallbackNode !== null) {\n var node = immediateQueueCallbackNode;\n immediateQueueCallbackNode = null;\n Scheduler_cancelCallback(node);\n }\n\n flushSyncCallbackQueueImpl();\n}\n\nfunction flushSyncCallbackQueueImpl() {\n if (!isFlushingSyncQueue && syncQueue !== null) {\n // Prevent re-entrancy.\n isFlushingSyncQueue = true;\n var i = 0;\n\n try {\n var _isSync = true;\n var queue = syncQueue;\n runWithPriority$1(ImmediatePriority, function () {\n for (; i < queue.length; i++) {\n var callback = queue[i];\n\n do {\n callback = callback(_isSync);\n } while (callback !== null);\n }\n });\n syncQueue = null;\n } catch (error) {\n // If something throws, leave the remaining callbacks on the queue.\n if (syncQueue !== null) {\n syncQueue = syncQueue.slice(i + 1);\n } // Resume flushing in the next tick\n\n\n Scheduler_scheduleCallback(Scheduler_ImmediatePriority, flushSyncCallbackQueue);\n throw error;\n } finally {\n isFlushingSyncQueue = false;\n }\n }\n}\n\nvar NoMode = 0;\nvar StrictMode = 1; // TODO: Remove BlockingMode and ConcurrentMode by reading from the root\n// tag instead\n\nvar BlockingMode = 2;\nvar ConcurrentMode = 4;\nvar ProfileMode = 8;\n\n// Max 31 bit integer. The max integer size in V8 for 32-bit systems.\n// Math.pow(2, 30) - 1\n// 0b111111111111111111111111111111\nvar MAX_SIGNED_31_BIT_INT = 1073741823;\n\nvar NoWork = 0; // TODO: Think of a better name for Never. The key difference with Idle is that\n// Never work can be committed in an inconsistent state without tearing the UI.\n// The main example is offscreen content, like a hidden subtree. So one possible\n// name is Offscreen. However, it also includes dehydrated Suspense boundaries,\n// which are inconsistent in the sense that they haven't finished yet, but\n// aren't visibly inconsistent because the server rendered HTML matches what the\n// hydrated tree would look like.\n\nvar Never = 1; // Idle is slightly higher priority than Never. It must completely finish in\n// order to be consistent.\n\nvar Idle = 2; // Continuous Hydration is slightly higher than Idle and is used to increase\n// priority of hover targets.\n\nvar ContinuousHydration = 3;\nvar Sync = MAX_SIGNED_31_BIT_INT;\nvar Batched = Sync - 1;\nvar UNIT_SIZE = 10;\nvar MAGIC_NUMBER_OFFSET = Batched - 1; // 1 unit of expiration time represents 10ms.\n\nfunction msToExpirationTime(ms) {\n // Always subtract from the offset so that we don't clash with the magic number for NoWork.\n return MAGIC_NUMBER_OFFSET - (ms / UNIT_SIZE | 0);\n}\nfunction expirationTimeToMs(expirationTime) {\n return (MAGIC_NUMBER_OFFSET - expirationTime) * UNIT_SIZE;\n}\n\nfunction ceiling(num, precision) {\n return ((num / precision | 0) + 1) * precision;\n}\n\nfunction computeExpirationBucket(currentTime, expirationInMs, bucketSizeMs) {\n return MAGIC_NUMBER_OFFSET - ceiling(MAGIC_NUMBER_OFFSET - currentTime + expirationInMs / UNIT_SIZE, bucketSizeMs / UNIT_SIZE);\n} // TODO: This corresponds to Scheduler's NormalPriority, not LowPriority. Update\n// the names to reflect.\n\n\nvar LOW_PRIORITY_EXPIRATION = 5000;\nvar LOW_PRIORITY_BATCH_SIZE = 250;\nfunction computeAsyncExpiration(currentTime) {\n return computeExpirationBucket(currentTime, LOW_PRIORITY_EXPIRATION, LOW_PRIORITY_BATCH_SIZE);\n}\nfunction computeSuspenseExpiration(currentTime, timeoutMs) {\n // TODO: Should we warn if timeoutMs is lower than the normal pri expiration time?\n return computeExpirationBucket(currentTime, timeoutMs, LOW_PRIORITY_BATCH_SIZE);\n} // We intentionally set a higher expiration time for interactive updates in\n// dev than in production.\n//\n// If the main thread is being blocked so long that you hit the expiration,\n// it's a problem that could be solved with better scheduling.\n//\n// People will be more likely to notice this and fix it with the long\n// expiration time in development.\n//\n// In production we opt for better UX at the risk of masking scheduling\n// problems, by expiring fast.\n\nvar HIGH_PRIORITY_EXPIRATION = 500 ;\nvar HIGH_PRIORITY_BATCH_SIZE = 100;\nfunction computeInteractiveExpiration(currentTime) {\n return computeExpirationBucket(currentTime, HIGH_PRIORITY_EXPIRATION, HIGH_PRIORITY_BATCH_SIZE);\n}\nfunction inferPriorityFromExpirationTime(currentTime, expirationTime) {\n if (expirationTime === Sync) {\n return ImmediatePriority;\n }\n\n if (expirationTime === Never || expirationTime === Idle) {\n return IdlePriority;\n }\n\n var msUntil = expirationTimeToMs(expirationTime) - expirationTimeToMs(currentTime);\n\n if (msUntil <= 0) {\n return ImmediatePriority;\n }\n\n if (msUntil <= HIGH_PRIORITY_EXPIRATION + HIGH_PRIORITY_BATCH_SIZE) {\n return UserBlockingPriority$1;\n }\n\n if (msUntil <= LOW_PRIORITY_EXPIRATION + LOW_PRIORITY_BATCH_SIZE) {\n return NormalPriority;\n } // TODO: Handle LowPriority\n // Assume anything lower has idle priority\n\n\n return IdlePriority;\n}\n\nvar ReactStrictModeWarnings = {\n recordUnsafeLifecycleWarnings: function (fiber, instance) {},\n flushPendingUnsafeLifecycleWarnings: function () {},\n recordLegacyContextWarning: function (fiber, instance) {},\n flushLegacyContextWarning: function () {},\n discardPendingWarnings: function () {}\n};\n\n{\n var findStrictRoot = function (fiber) {\n var maybeStrictRoot = null;\n var node = fiber;\n\n while (node !== null) {\n if (node.mode & StrictMode) {\n maybeStrictRoot = node;\n }\n\n node = node.return;\n }\n\n return maybeStrictRoot;\n };\n\n var setToSortedString = function (set) {\n var array = [];\n set.forEach(function (value) {\n array.push(value);\n });\n return array.sort().join(', ');\n };\n\n var pendingComponentWillMountWarnings = [];\n var pendingUNSAFE_ComponentWillMountWarnings = [];\n var pendingComponentWillReceivePropsWarnings = [];\n var pendingUNSAFE_ComponentWillReceivePropsWarnings = [];\n var pendingComponentWillUpdateWarnings = [];\n var pendingUNSAFE_ComponentWillUpdateWarnings = []; // Tracks components we have already warned about.\n\n var didWarnAboutUnsafeLifecycles = new Set();\n\n ReactStrictModeWarnings.recordUnsafeLifecycleWarnings = function (fiber, instance) {\n // Dedup strategy: Warn once per component.\n if (didWarnAboutUnsafeLifecycles.has(fiber.type)) {\n return;\n }\n\n if (typeof instance.componentWillMount === 'function' && // Don't warn about react-lifecycles-compat polyfilled components.\n instance.componentWillMount.__suppressDeprecationWarning !== true) {\n pendingComponentWillMountWarnings.push(fiber);\n }\n\n if (fiber.mode & StrictMode && typeof instance.UNSAFE_componentWillMount === 'function') {\n pendingUNSAFE_ComponentWillMountWarnings.push(fiber);\n }\n\n if (typeof instance.componentWillReceiveProps === 'function' && instance.componentWillReceiveProps.__suppressDeprecationWarning !== true) {\n pendingComponentWillReceivePropsWarnings.push(fiber);\n }\n\n if (fiber.mode & StrictMode && typeof instance.UNSAFE_componentWillReceiveProps === 'function') {\n pendingUNSAFE_ComponentWillReceivePropsWarnings.push(fiber);\n }\n\n if (typeof instance.componentWillUpdate === 'function' && instance.componentWillUpdate.__suppressDeprecationWarning !== true) {\n pendingComponentWillUpdateWarnings.push(fiber);\n }\n\n if (fiber.mode & StrictMode && typeof instance.UNSAFE_componentWillUpdate === 'function') {\n pendingUNSAFE_ComponentWillUpdateWarnings.push(fiber);\n }\n };\n\n ReactStrictModeWarnings.flushPendingUnsafeLifecycleWarnings = function () {\n // We do an initial pass to gather component names\n var componentWillMountUniqueNames = new Set();\n\n if (pendingComponentWillMountWarnings.length > 0) {\n pendingComponentWillMountWarnings.forEach(function (fiber) {\n componentWillMountUniqueNames.add(getComponentName(fiber.type) || 'Component');\n didWarnAboutUnsafeLifecycles.add(fiber.type);\n });\n pendingComponentWillMountWarnings = [];\n }\n\n var UNSAFE_componentWillMountUniqueNames = new Set();\n\n if (pendingUNSAFE_ComponentWillMountWarnings.length > 0) {\n pendingUNSAFE_ComponentWillMountWarnings.forEach(function (fiber) {\n UNSAFE_componentWillMountUniqueNames.add(getComponentName(fiber.type) || 'Component');\n didWarnAboutUnsafeLifecycles.add(fiber.type);\n });\n pendingUNSAFE_ComponentWillMountWarnings = [];\n }\n\n var componentWillReceivePropsUniqueNames = new Set();\n\n if (pendingComponentWillReceivePropsWarnings.length > 0) {\n pendingComponentWillReceivePropsWarnings.forEach(function (fiber) {\n componentWillReceivePropsUniqueNames.add(getComponentName(fiber.type) || 'Component');\n didWarnAboutUnsafeLifecycles.add(fiber.type);\n });\n pendingComponentWillReceivePropsWarnings = [];\n }\n\n var UNSAFE_componentWillReceivePropsUniqueNames = new Set();\n\n if (pendingUNSAFE_ComponentWillReceivePropsWarnings.length > 0) {\n pendingUNSAFE_ComponentWillReceivePropsWarnings.forEach(function (fiber) {\n UNSAFE_componentWillReceivePropsUniqueNames.add(getComponentName(fiber.type) || 'Component');\n didWarnAboutUnsafeLifecycles.add(fiber.type);\n });\n pendingUNSAFE_ComponentWillReceivePropsWarnings = [];\n }\n\n var componentWillUpdateUniqueNames = new Set();\n\n if (pendingComponentWillUpdateWarnings.length > 0) {\n pendingComponentWillUpdateWarnings.forEach(function (fiber) {\n componentWillUpdateUniqueNames.add(getComponentName(fiber.type) || 'Component');\n didWarnAboutUnsafeLifecycles.add(fiber.type);\n });\n pendingComponentWillUpdateWarnings = [];\n }\n\n var UNSAFE_componentWillUpdateUniqueNames = new Set();\n\n if (pendingUNSAFE_ComponentWillUpdateWarnings.length > 0) {\n pendingUNSAFE_ComponentWillUpdateWarnings.forEach(function (fiber) {\n UNSAFE_componentWillUpdateUniqueNames.add(getComponentName(fiber.type) || 'Component');\n didWarnAboutUnsafeLifecycles.add(fiber.type);\n });\n pendingUNSAFE_ComponentWillUpdateWarnings = [];\n } // Finally, we flush all the warnings\n // UNSAFE_ ones before the deprecated ones, since they'll be 'louder'\n\n\n if (UNSAFE_componentWillMountUniqueNames.size > 0) {\n var sortedNames = setToSortedString(UNSAFE_componentWillMountUniqueNames);\n\n error('Using UNSAFE_componentWillMount in strict mode is not recommended and may indicate bugs in your code. ' + 'See https://fb.me/react-unsafe-component-lifecycles for details.\\n\\n' + '* Move code with side effects to componentDidMount, and set initial state in the constructor.\\n' + '\\nPlease update the following components: %s', sortedNames);\n }\n\n if (UNSAFE_componentWillReceivePropsUniqueNames.size > 0) {\n var _sortedNames = setToSortedString(UNSAFE_componentWillReceivePropsUniqueNames);\n\n error('Using UNSAFE_componentWillReceiveProps in strict mode is not recommended ' + 'and may indicate bugs in your code. ' + 'See https://fb.me/react-unsafe-component-lifecycles for details.\\n\\n' + '* Move data fetching code or side effects to componentDidUpdate.\\n' + \"* If you're updating state whenever props change, \" + 'refactor your code to use memoization techniques or move it to ' + 'static getDerivedStateFromProps. Learn more at: https://fb.me/react-derived-state\\n' + '\\nPlease update the following components: %s', _sortedNames);\n }\n\n if (UNSAFE_componentWillUpdateUniqueNames.size > 0) {\n var _sortedNames2 = setToSortedString(UNSAFE_componentWillUpdateUniqueNames);\n\n error('Using UNSAFE_componentWillUpdate in strict mode is not recommended ' + 'and may indicate bugs in your code. ' + 'See https://fb.me/react-unsafe-component-lifecycles for details.\\n\\n' + '* Move data fetching code or side effects to componentDidUpdate.\\n' + '\\nPlease update the following components: %s', _sortedNames2);\n }\n\n if (componentWillMountUniqueNames.size > 0) {\n var _sortedNames3 = setToSortedString(componentWillMountUniqueNames);\n\n warn('componentWillMount has been renamed, and is not recommended for use. ' + 'See https://fb.me/react-unsafe-component-lifecycles for details.\\n\\n' + '* Move code with side effects to componentDidMount, and set initial state in the constructor.\\n' + '* Rename componentWillMount to UNSAFE_componentWillMount to suppress ' + 'this warning in non-strict mode. In React 17.x, only the UNSAFE_ name will work. ' + 'To rename all deprecated lifecycles to their new names, you can run ' + '`npx react-codemod rename-unsafe-lifecycles` in your project source folder.\\n' + '\\nPlease update the following components: %s', _sortedNames3);\n }\n\n if (componentWillReceivePropsUniqueNames.size > 0) {\n var _sortedNames4 = setToSortedString(componentWillReceivePropsUniqueNames);\n\n warn('componentWillReceiveProps has been renamed, and is not recommended for use. ' + 'See https://fb.me/react-unsafe-component-lifecycles for details.\\n\\n' + '* Move data fetching code or side effects to componentDidUpdate.\\n' + \"* If you're updating state whenever props change, refactor your \" + 'code to use memoization techniques or move it to ' + 'static getDerivedStateFromProps. Learn more at: https://fb.me/react-derived-state\\n' + '* Rename componentWillReceiveProps to UNSAFE_componentWillReceiveProps to suppress ' + 'this warning in non-strict mode. In React 17.x, only the UNSAFE_ name will work. ' + 'To rename all deprecated lifecycles to their new names, you can run ' + '`npx react-codemod rename-unsafe-lifecycles` in your project source folder.\\n' + '\\nPlease update the following components: %s', _sortedNames4);\n }\n\n if (componentWillUpdateUniqueNames.size > 0) {\n var _sortedNames5 = setToSortedString(componentWillUpdateUniqueNames);\n\n warn('componentWillUpdate has been renamed, and is not recommended for use. ' + 'See https://fb.me/react-unsafe-component-lifecycles for details.\\n\\n' + '* Move data fetching code or side effects to componentDidUpdate.\\n' + '* Rename componentWillUpdate to UNSAFE_componentWillUpdate to suppress ' + 'this warning in non-strict mode. In React 17.x, only the UNSAFE_ name will work. ' + 'To rename all deprecated lifecycles to their new names, you can run ' + '`npx react-codemod rename-unsafe-lifecycles` in your project source folder.\\n' + '\\nPlease update the following components: %s', _sortedNames5);\n }\n };\n\n var pendingLegacyContextWarning = new Map(); // Tracks components we have already warned about.\n\n var didWarnAboutLegacyContext = new Set();\n\n ReactStrictModeWarnings.recordLegacyContextWarning = function (fiber, instance) {\n var strictRoot = findStrictRoot(fiber);\n\n if (strictRoot === null) {\n error('Expected to find a StrictMode component in a strict mode tree. ' + 'This error is likely caused by a bug in React. Please file an issue.');\n\n return;\n } // Dedup strategy: Warn once per component.\n\n\n if (didWarnAboutLegacyContext.has(fiber.type)) {\n return;\n }\n\n var warningsForRoot = pendingLegacyContextWarning.get(strictRoot);\n\n if (fiber.type.contextTypes != null || fiber.type.childContextTypes != null || instance !== null && typeof instance.getChildContext === 'function') {\n if (warningsForRoot === undefined) {\n warningsForRoot = [];\n pendingLegacyContextWarning.set(strictRoot, warningsForRoot);\n }\n\n warningsForRoot.push(fiber);\n }\n };\n\n ReactStrictModeWarnings.flushLegacyContextWarning = function () {\n pendingLegacyContextWarning.forEach(function (fiberArray, strictRoot) {\n if (fiberArray.length === 0) {\n return;\n }\n\n var firstFiber = fiberArray[0];\n var uniqueNames = new Set();\n fiberArray.forEach(function (fiber) {\n uniqueNames.add(getComponentName(fiber.type) || 'Component');\n didWarnAboutLegacyContext.add(fiber.type);\n });\n var sortedNames = setToSortedString(uniqueNames);\n var firstComponentStack = getStackByFiberInDevAndProd(firstFiber);\n\n error('Legacy context API has been detected within a strict-mode tree.' + '\\n\\nThe old API will be supported in all 16.x releases, but applications ' + 'using it should migrate to the new version.' + '\\n\\nPlease update the following components: %s' + '\\n\\nLearn more about this warning here: https://fb.me/react-legacy-context' + '%s', sortedNames, firstComponentStack);\n });\n };\n\n ReactStrictModeWarnings.discardPendingWarnings = function () {\n pendingComponentWillMountWarnings = [];\n pendingUNSAFE_ComponentWillMountWarnings = [];\n pendingComponentWillReceivePropsWarnings = [];\n pendingUNSAFE_ComponentWillReceivePropsWarnings = [];\n pendingComponentWillUpdateWarnings = [];\n pendingUNSAFE_ComponentWillUpdateWarnings = [];\n pendingLegacyContextWarning = new Map();\n };\n}\n\nvar resolveFamily = null; // $FlowFixMe Flow gets confused by a WeakSet feature check below.\n\nvar failedBoundaries = null;\nvar setRefreshHandler = function (handler) {\n {\n resolveFamily = handler;\n }\n};\nfunction resolveFunctionForHotReloading(type) {\n {\n if (resolveFamily === null) {\n // Hot reloading is disabled.\n return type;\n }\n\n var family = resolveFamily(type);\n\n if (family === undefined) {\n return type;\n } // Use the latest known implementation.\n\n\n return family.current;\n }\n}\nfunction resolveClassForHotReloading(type) {\n // No implementation differences.\n return resolveFunctionForHotReloading(type);\n}\nfunction resolveForwardRefForHotReloading(type) {\n {\n if (resolveFamily === null) {\n // Hot reloading is disabled.\n return type;\n }\n\n var family = resolveFamily(type);\n\n if (family === undefined) {\n // Check if we're dealing with a real forwardRef. Don't want to crash early.\n if (type !== null && type !== undefined && typeof type.render === 'function') {\n // ForwardRef is special because its resolved .type is an object,\n // but it's possible that we only have its inner render function in the map.\n // If that inner render function is different, we'll build a new forwardRef type.\n var currentRender = resolveFunctionForHotReloading(type.render);\n\n if (type.render !== currentRender) {\n var syntheticType = {\n $$typeof: REACT_FORWARD_REF_TYPE,\n render: currentRender\n };\n\n if (type.displayName !== undefined) {\n syntheticType.displayName = type.displayName;\n }\n\n return syntheticType;\n }\n }\n\n return type;\n } // Use the latest known implementation.\n\n\n return family.current;\n }\n}\nfunction isCompatibleFamilyForHotReloading(fiber, element) {\n {\n if (resolveFamily === null) {\n // Hot reloading is disabled.\n return false;\n }\n\n var prevType = fiber.elementType;\n var nextType = element.type; // If we got here, we know types aren't === equal.\n\n var needsCompareFamilies = false;\n var $$typeofNextType = typeof nextType === 'object' && nextType !== null ? nextType.$$typeof : null;\n\n switch (fiber.tag) {\n case ClassComponent:\n {\n if (typeof nextType === 'function') {\n needsCompareFamilies = true;\n }\n\n break;\n }\n\n case FunctionComponent:\n {\n if (typeof nextType === 'function') {\n needsCompareFamilies = true;\n } else if ($$typeofNextType === REACT_LAZY_TYPE) {\n // We don't know the inner type yet.\n // We're going to assume that the lazy inner type is stable,\n // and so it is sufficient to avoid reconciling it away.\n // We're not going to unwrap or actually use the new lazy type.\n needsCompareFamilies = true;\n }\n\n break;\n }\n\n case ForwardRef:\n {\n if ($$typeofNextType === REACT_FORWARD_REF_TYPE) {\n needsCompareFamilies = true;\n } else if ($$typeofNextType === REACT_LAZY_TYPE) {\n needsCompareFamilies = true;\n }\n\n break;\n }\n\n case MemoComponent:\n case SimpleMemoComponent:\n {\n if ($$typeofNextType === REACT_MEMO_TYPE) {\n // TODO: if it was but can no longer be simple,\n // we shouldn't set this.\n needsCompareFamilies = true;\n } else if ($$typeofNextType === REACT_LAZY_TYPE) {\n needsCompareFamilies = true;\n }\n\n break;\n }\n\n default:\n return false;\n } // Check if both types have a family and it's the same one.\n\n\n if (needsCompareFamilies) {\n // Note: memo() and forwardRef() we'll compare outer rather than inner type.\n // This means both of them need to be registered to preserve state.\n // If we unwrapped and compared the inner types for wrappers instead,\n // then we would risk falsely saying two separate memo(Foo)\n // calls are equivalent because they wrap the same Foo function.\n var prevFamily = resolveFamily(prevType);\n\n if (prevFamily !== undefined && prevFamily === resolveFamily(nextType)) {\n return true;\n }\n }\n\n return false;\n }\n}\nfunction markFailedErrorBoundaryForHotReloading(fiber) {\n {\n if (resolveFamily === null) {\n // Hot reloading is disabled.\n return;\n }\n\n if (typeof WeakSet !== 'function') {\n return;\n }\n\n if (failedBoundaries === null) {\n failedBoundaries = new WeakSet();\n }\n\n failedBoundaries.add(fiber);\n }\n}\nvar scheduleRefresh = function (root, update) {\n {\n if (resolveFamily === null) {\n // Hot reloading is disabled.\n return;\n }\n\n var staleFamilies = update.staleFamilies,\n updatedFamilies = update.updatedFamilies;\n flushPassiveEffects();\n flushSync(function () {\n scheduleFibersWithFamiliesRecursively(root.current, updatedFamilies, staleFamilies);\n });\n }\n};\nvar scheduleRoot = function (root, element) {\n {\n if (root.context !== emptyContextObject) {\n // Super edge case: root has a legacy _renderSubtree context\n // but we don't know the parentComponent so we can't pass it.\n // Just ignore. We'll delete this with _renderSubtree code path later.\n return;\n }\n\n flushPassiveEffects();\n syncUpdates(function () {\n updateContainer(element, root, null, null);\n });\n }\n};\n\nfunction scheduleFibersWithFamiliesRecursively(fiber, updatedFamilies, staleFamilies) {\n {\n var alternate = fiber.alternate,\n child = fiber.child,\n sibling = fiber.sibling,\n tag = fiber.tag,\n type = fiber.type;\n var candidateType = null;\n\n switch (tag) {\n case FunctionComponent:\n case SimpleMemoComponent:\n case ClassComponent:\n candidateType = type;\n break;\n\n case ForwardRef:\n candidateType = type.render;\n break;\n }\n\n if (resolveFamily === null) {\n throw new Error('Expected resolveFamily to be set during hot reload.');\n }\n\n var needsRender = false;\n var needsRemount = false;\n\n if (candidateType !== null) {\n var family = resolveFamily(candidateType);\n\n if (family !== undefined) {\n if (staleFamilies.has(family)) {\n needsRemount = true;\n } else if (updatedFamilies.has(family)) {\n if (tag === ClassComponent) {\n needsRemount = true;\n } else {\n needsRender = true;\n }\n }\n }\n }\n\n if (failedBoundaries !== null) {\n if (failedBoundaries.has(fiber) || alternate !== null && failedBoundaries.has(alternate)) {\n needsRemount = true;\n }\n }\n\n if (needsRemount) {\n fiber._debugNeedsRemount = true;\n }\n\n if (needsRemount || needsRender) {\n scheduleWork(fiber, Sync);\n }\n\n if (child !== null && !needsRemount) {\n scheduleFibersWithFamiliesRecursively(child, updatedFamilies, staleFamilies);\n }\n\n if (sibling !== null) {\n scheduleFibersWithFamiliesRecursively(sibling, updatedFamilies, staleFamilies);\n }\n }\n}\n\nvar findHostInstancesForRefresh = function (root, families) {\n {\n var hostInstances = new Set();\n var types = new Set(families.map(function (family) {\n return family.current;\n }));\n findHostInstancesForMatchingFibersRecursively(root.current, types, hostInstances);\n return hostInstances;\n }\n};\n\nfunction findHostInstancesForMatchingFibersRecursively(fiber, types, hostInstances) {\n {\n var child = fiber.child,\n sibling = fiber.sibling,\n tag = fiber.tag,\n type = fiber.type;\n var candidateType = null;\n\n switch (tag) {\n case FunctionComponent:\n case SimpleMemoComponent:\n case ClassComponent:\n candidateType = type;\n break;\n\n case ForwardRef:\n candidateType = type.render;\n break;\n }\n\n var didMatch = false;\n\n if (candidateType !== null) {\n if (types.has(candidateType)) {\n didMatch = true;\n }\n }\n\n if (didMatch) {\n // We have a match. This only drills down to the closest host components.\n // There's no need to search deeper because for the purpose of giving\n // visual feedback, \"flashing\" outermost parent rectangles is sufficient.\n findHostInstancesForFiberShallowly(fiber, hostInstances);\n } else {\n // If there's no match, maybe there will be one further down in the child tree.\n if (child !== null) {\n findHostInstancesForMatchingFibersRecursively(child, types, hostInstances);\n }\n }\n\n if (sibling !== null) {\n findHostInstancesForMatchingFibersRecursively(sibling, types, hostInstances);\n }\n }\n}\n\nfunction findHostInstancesForFiberShallowly(fiber, hostInstances) {\n {\n var foundHostInstances = findChildHostInstancesForFiberShallowly(fiber, hostInstances);\n\n if (foundHostInstances) {\n return;\n } // If we didn't find any host children, fallback to closest host parent.\n\n\n var node = fiber;\n\n while (true) {\n switch (node.tag) {\n case HostComponent:\n hostInstances.add(node.stateNode);\n return;\n\n case HostPortal:\n hostInstances.add(node.stateNode.containerInfo);\n return;\n\n case HostRoot:\n hostInstances.add(node.stateNode.containerInfo);\n return;\n }\n\n if (node.return === null) {\n throw new Error('Expected to reach root first.');\n }\n\n node = node.return;\n }\n }\n}\n\nfunction findChildHostInstancesForFiberShallowly(fiber, hostInstances) {\n {\n var node = fiber;\n var foundHostInstances = false;\n\n while (true) {\n if (node.tag === HostComponent) {\n // We got a match.\n foundHostInstances = true;\n hostInstances.add(node.stateNode); // There may still be more, so keep searching.\n } else if (node.child !== null) {\n node.child.return = node;\n node = node.child;\n continue;\n }\n\n if (node === fiber) {\n return foundHostInstances;\n }\n\n while (node.sibling === null) {\n if (node.return === null || node.return === fiber) {\n return foundHostInstances;\n }\n\n node = node.return;\n }\n\n node.sibling.return = node.return;\n node = node.sibling;\n }\n }\n\n return false;\n}\n\nfunction resolveDefaultProps(Component, baseProps) {\n if (Component && Component.defaultProps) {\n // Resolve default props. Taken from ReactElement\n var props = _assign({}, baseProps);\n\n var defaultProps = Component.defaultProps;\n\n for (var propName in defaultProps) {\n if (props[propName] === undefined) {\n props[propName] = defaultProps[propName];\n }\n }\n\n return props;\n }\n\n return baseProps;\n}\nfunction readLazyComponentType(lazyComponent) {\n initializeLazyComponentType(lazyComponent);\n\n if (lazyComponent._status !== Resolved) {\n throw lazyComponent._result;\n }\n\n return lazyComponent._result;\n}\n\nvar valueCursor = createCursor(null);\nvar rendererSigil;\n\n{\n // Use this to detect multiple renderers using the same context\n rendererSigil = {};\n}\n\nvar currentlyRenderingFiber = null;\nvar lastContextDependency = null;\nvar lastContextWithAllBitsObserved = null;\nvar isDisallowedContextReadInDEV = false;\nfunction resetContextDependencies() {\n // This is called right before React yields execution, to ensure `readContext`\n // cannot be called outside the render phase.\n currentlyRenderingFiber = null;\n lastContextDependency = null;\n lastContextWithAllBitsObserved = null;\n\n {\n isDisallowedContextReadInDEV = false;\n }\n}\nfunction enterDisallowedContextReadInDEV() {\n {\n isDisallowedContextReadInDEV = true;\n }\n}\nfunction exitDisallowedContextReadInDEV() {\n {\n isDisallowedContextReadInDEV = false;\n }\n}\nfunction pushProvider(providerFiber, nextValue) {\n var context = providerFiber.type._context;\n\n {\n push(valueCursor, context._currentValue, providerFiber);\n context._currentValue = nextValue;\n\n {\n if (context._currentRenderer !== undefined && context._currentRenderer !== null && context._currentRenderer !== rendererSigil) {\n error('Detected multiple renderers concurrently rendering the ' + 'same context provider. This is currently unsupported.');\n }\n\n context._currentRenderer = rendererSigil;\n }\n }\n}\nfunction popProvider(providerFiber) {\n var currentValue = valueCursor.current;\n pop(valueCursor, providerFiber);\n var context = providerFiber.type._context;\n\n {\n context._currentValue = currentValue;\n }\n}\nfunction calculateChangedBits(context, newValue, oldValue) {\n if (objectIs(oldValue, newValue)) {\n // No change\n return 0;\n } else {\n var changedBits = typeof context._calculateChangedBits === 'function' ? context._calculateChangedBits(oldValue, newValue) : MAX_SIGNED_31_BIT_INT;\n\n {\n if ((changedBits & MAX_SIGNED_31_BIT_INT) !== changedBits) {\n error('calculateChangedBits: Expected the return value to be a ' + '31-bit integer. Instead received: %s', changedBits);\n }\n }\n\n return changedBits | 0;\n }\n}\nfunction scheduleWorkOnParentPath(parent, renderExpirationTime) {\n // Update the child expiration time of all the ancestors, including\n // the alternates.\n var node = parent;\n\n while (node !== null) {\n var alternate = node.alternate;\n\n if (node.childExpirationTime < renderExpirationTime) {\n node.childExpirationTime = renderExpirationTime;\n\n if (alternate !== null && alternate.childExpirationTime < renderExpirationTime) {\n alternate.childExpirationTime = renderExpirationTime;\n }\n } else if (alternate !== null && alternate.childExpirationTime < renderExpirationTime) {\n alternate.childExpirationTime = renderExpirationTime;\n } else {\n // Neither alternate was updated, which means the rest of the\n // ancestor path already has sufficient priority.\n break;\n }\n\n node = node.return;\n }\n}\nfunction propagateContextChange(workInProgress, context, changedBits, renderExpirationTime) {\n var fiber = workInProgress.child;\n\n if (fiber !== null) {\n // Set the return pointer of the child to the work-in-progress fiber.\n fiber.return = workInProgress;\n }\n\n while (fiber !== null) {\n var nextFiber = void 0; // Visit this fiber.\n\n var list = fiber.dependencies;\n\n if (list !== null) {\n nextFiber = fiber.child;\n var dependency = list.firstContext;\n\n while (dependency !== null) {\n // Check if the context matches.\n if (dependency.context === context && (dependency.observedBits & changedBits) !== 0) {\n // Match! Schedule an update on this fiber.\n if (fiber.tag === ClassComponent) {\n // Schedule a force update on the work-in-progress.\n var update = createUpdate(renderExpirationTime, null);\n update.tag = ForceUpdate; // TODO: Because we don't have a work-in-progress, this will add the\n // update to the current fiber, too, which means it will persist even if\n // this render is thrown away. Since it's a race condition, not sure it's\n // worth fixing.\n\n enqueueUpdate(fiber, update);\n }\n\n if (fiber.expirationTime < renderExpirationTime) {\n fiber.expirationTime = renderExpirationTime;\n }\n\n var alternate = fiber.alternate;\n\n if (alternate !== null && alternate.expirationTime < renderExpirationTime) {\n alternate.expirationTime = renderExpirationTime;\n }\n\n scheduleWorkOnParentPath(fiber.return, renderExpirationTime); // Mark the expiration time on the list, too.\n\n if (list.expirationTime < renderExpirationTime) {\n list.expirationTime = renderExpirationTime;\n } // Since we already found a match, we can stop traversing the\n // dependency list.\n\n\n break;\n }\n\n dependency = dependency.next;\n }\n } else if (fiber.tag === ContextProvider) {\n // Don't scan deeper if this is a matching provider\n nextFiber = fiber.type === workInProgress.type ? null : fiber.child;\n } else {\n // Traverse down.\n nextFiber = fiber.child;\n }\n\n if (nextFiber !== null) {\n // Set the return pointer of the child to the work-in-progress fiber.\n nextFiber.return = fiber;\n } else {\n // No child. Traverse to next sibling.\n nextFiber = fiber;\n\n while (nextFiber !== null) {\n if (nextFiber === workInProgress) {\n // We're back to the root of this subtree. Exit.\n nextFiber = null;\n break;\n }\n\n var sibling = nextFiber.sibling;\n\n if (sibling !== null) {\n // Set the return pointer of the sibling to the work-in-progress fiber.\n sibling.return = nextFiber.return;\n nextFiber = sibling;\n break;\n } // No more siblings. Traverse up.\n\n\n nextFiber = nextFiber.return;\n }\n }\n\n fiber = nextFiber;\n }\n}\nfunction prepareToReadContext(workInProgress, renderExpirationTime) {\n currentlyRenderingFiber = workInProgress;\n lastContextDependency = null;\n lastContextWithAllBitsObserved = null;\n var dependencies = workInProgress.dependencies;\n\n if (dependencies !== null) {\n var firstContext = dependencies.firstContext;\n\n if (firstContext !== null) {\n if (dependencies.expirationTime >= renderExpirationTime) {\n // Context list has a pending update. Mark that this fiber performed work.\n markWorkInProgressReceivedUpdate();\n } // Reset the work-in-progress list\n\n\n dependencies.firstContext = null;\n }\n }\n}\nfunction readContext(context, observedBits) {\n {\n // This warning would fire if you read context inside a Hook like useMemo.\n // Unlike the class check below, it's not enforced in production for perf.\n if (isDisallowedContextReadInDEV) {\n error('Context can only be read while React is rendering. ' + 'In classes, you can read it in the render method or getDerivedStateFromProps. ' + 'In function components, you can read it directly in the function body, but not ' + 'inside Hooks like useReducer() or useMemo().');\n }\n }\n\n if (lastContextWithAllBitsObserved === context) ; else if (observedBits === false || observedBits === 0) ; else {\n var resolvedObservedBits; // Avoid deopting on observable arguments or heterogeneous types.\n\n if (typeof observedBits !== 'number' || observedBits === MAX_SIGNED_31_BIT_INT) {\n // Observe all updates.\n lastContextWithAllBitsObserved = context;\n resolvedObservedBits = MAX_SIGNED_31_BIT_INT;\n } else {\n resolvedObservedBits = observedBits;\n }\n\n var contextItem = {\n context: context,\n observedBits: resolvedObservedBits,\n next: null\n };\n\n if (lastContextDependency === null) {\n if (!(currentlyRenderingFiber !== null)) {\n {\n throw Error( \"Context can only be read while React is rendering. In classes, you can read it in the render method or getDerivedStateFromProps. In function components, you can read it directly in the function body, but not inside Hooks like useReducer() or useMemo().\" );\n }\n } // This is the first dependency for this component. Create a new list.\n\n\n lastContextDependency = contextItem;\n currentlyRenderingFiber.dependencies = {\n expirationTime: NoWork,\n firstContext: contextItem,\n responders: null\n };\n } else {\n // Append a new context item.\n lastContextDependency = lastContextDependency.next = contextItem;\n }\n }\n\n return context._currentValue ;\n}\n\nvar UpdateState = 0;\nvar ReplaceState = 1;\nvar ForceUpdate = 2;\nvar CaptureUpdate = 3; // Global state that is reset at the beginning of calling `processUpdateQueue`.\n// It should only be read right after calling `processUpdateQueue`, via\n// `checkHasForceUpdateAfterProcessing`.\n\nvar hasForceUpdate = false;\nvar didWarnUpdateInsideUpdate;\nvar currentlyProcessingQueue;\n\n{\n didWarnUpdateInsideUpdate = false;\n currentlyProcessingQueue = null;\n}\n\nfunction initializeUpdateQueue(fiber) {\n var queue = {\n baseState: fiber.memoizedState,\n baseQueue: null,\n shared: {\n pending: null\n },\n effects: null\n };\n fiber.updateQueue = queue;\n}\nfunction cloneUpdateQueue(current, workInProgress) {\n // Clone the update queue from current. Unless it's already a clone.\n var queue = workInProgress.updateQueue;\n var currentQueue = current.updateQueue;\n\n if (queue === currentQueue) {\n var clone = {\n baseState: currentQueue.baseState,\n baseQueue: currentQueue.baseQueue,\n shared: currentQueue.shared,\n effects: currentQueue.effects\n };\n workInProgress.updateQueue = clone;\n }\n}\nfunction createUpdate(expirationTime, suspenseConfig) {\n var update = {\n expirationTime: expirationTime,\n suspenseConfig: suspenseConfig,\n tag: UpdateState,\n payload: null,\n callback: null,\n next: null\n };\n update.next = update;\n\n {\n update.priority = getCurrentPriorityLevel();\n }\n\n return update;\n}\nfunction enqueueUpdate(fiber, update) {\n var updateQueue = fiber.updateQueue;\n\n if (updateQueue === null) {\n // Only occurs if the fiber has been unmounted.\n return;\n }\n\n var sharedQueue = updateQueue.shared;\n var pending = sharedQueue.pending;\n\n if (pending === null) {\n // This is the first update. Create a circular list.\n update.next = update;\n } else {\n update.next = pending.next;\n pending.next = update;\n }\n\n sharedQueue.pending = update;\n\n {\n if (currentlyProcessingQueue === sharedQueue && !didWarnUpdateInsideUpdate) {\n error('An update (setState, replaceState, or forceUpdate) was scheduled ' + 'from inside an update function. Update functions should be pure, ' + 'with zero side-effects. Consider using componentDidUpdate or a ' + 'callback.');\n\n didWarnUpdateInsideUpdate = true;\n }\n }\n}\nfunction enqueueCapturedUpdate(workInProgress, update) {\n var current = workInProgress.alternate;\n\n if (current !== null) {\n // Ensure the work-in-progress queue is a clone\n cloneUpdateQueue(current, workInProgress);\n } // Captured updates go only on the work-in-progress queue.\n\n\n var queue = workInProgress.updateQueue; // Append the update to the end of the list.\n\n var last = queue.baseQueue;\n\n if (last === null) {\n queue.baseQueue = update.next = update;\n update.next = update;\n } else {\n update.next = last.next;\n last.next = update;\n }\n}\n\nfunction getStateFromUpdate(workInProgress, queue, update, prevState, nextProps, instance) {\n switch (update.tag) {\n case ReplaceState:\n {\n var payload = update.payload;\n\n if (typeof payload === 'function') {\n // Updater function\n {\n enterDisallowedContextReadInDEV();\n\n if ( workInProgress.mode & StrictMode) {\n payload.call(instance, prevState, nextProps);\n }\n }\n\n var nextState = payload.call(instance, prevState, nextProps);\n\n {\n exitDisallowedContextReadInDEV();\n }\n\n return nextState;\n } // State object\n\n\n return payload;\n }\n\n case CaptureUpdate:\n {\n workInProgress.effectTag = workInProgress.effectTag & ~ShouldCapture | DidCapture;\n }\n // Intentional fallthrough\n\n case UpdateState:\n {\n var _payload = update.payload;\n var partialState;\n\n if (typeof _payload === 'function') {\n // Updater function\n {\n enterDisallowedContextReadInDEV();\n\n if ( workInProgress.mode & StrictMode) {\n _payload.call(instance, prevState, nextProps);\n }\n }\n\n partialState = _payload.call(instance, prevState, nextProps);\n\n {\n exitDisallowedContextReadInDEV();\n }\n } else {\n // Partial state object\n partialState = _payload;\n }\n\n if (partialState === null || partialState === undefined) {\n // Null and undefined are treated as no-ops.\n return prevState;\n } // Merge the partial state and the previous state.\n\n\n return _assign({}, prevState, partialState);\n }\n\n case ForceUpdate:\n {\n hasForceUpdate = true;\n return prevState;\n }\n }\n\n return prevState;\n}\n\nfunction processUpdateQueue(workInProgress, props, instance, renderExpirationTime) {\n // This is always non-null on a ClassComponent or HostRoot\n var queue = workInProgress.updateQueue;\n hasForceUpdate = false;\n\n {\n currentlyProcessingQueue = queue.shared;\n } // The last rebase update that is NOT part of the base state.\n\n\n var baseQueue = queue.baseQueue; // The last pending update that hasn't been processed yet.\n\n var pendingQueue = queue.shared.pending;\n\n if (pendingQueue !== null) {\n // We have new updates that haven't been processed yet.\n // We'll add them to the base queue.\n if (baseQueue !== null) {\n // Merge the pending queue and the base queue.\n var baseFirst = baseQueue.next;\n var pendingFirst = pendingQueue.next;\n baseQueue.next = pendingFirst;\n pendingQueue.next = baseFirst;\n }\n\n baseQueue = pendingQueue;\n queue.shared.pending = null; // TODO: Pass `current` as argument\n\n var current = workInProgress.alternate;\n\n if (current !== null) {\n var currentQueue = current.updateQueue;\n\n if (currentQueue !== null) {\n currentQueue.baseQueue = pendingQueue;\n }\n }\n } // These values may change as we process the queue.\n\n\n if (baseQueue !== null) {\n var first = baseQueue.next; // Iterate through the list of updates to compute the result.\n\n var newState = queue.baseState;\n var newExpirationTime = NoWork;\n var newBaseState = null;\n var newBaseQueueFirst = null;\n var newBaseQueueLast = null;\n\n if (first !== null) {\n var update = first;\n\n do {\n var updateExpirationTime = update.expirationTime;\n\n if (updateExpirationTime < renderExpirationTime) {\n // Priority is insufficient. Skip this update. If this is the first\n // skipped update, the previous update/state is the new base\n // update/state.\n var clone = {\n expirationTime: update.expirationTime,\n suspenseConfig: update.suspenseConfig,\n tag: update.tag,\n payload: update.payload,\n callback: update.callback,\n next: null\n };\n\n if (newBaseQueueLast === null) {\n newBaseQueueFirst = newBaseQueueLast = clone;\n newBaseState = newState;\n } else {\n newBaseQueueLast = newBaseQueueLast.next = clone;\n } // Update the remaining priority in the queue.\n\n\n if (updateExpirationTime > newExpirationTime) {\n newExpirationTime = updateExpirationTime;\n }\n } else {\n // This update does have sufficient priority.\n if (newBaseQueueLast !== null) {\n var _clone = {\n expirationTime: Sync,\n // This update is going to be committed so we never want uncommit it.\n suspenseConfig: update.suspenseConfig,\n tag: update.tag,\n payload: update.payload,\n callback: update.callback,\n next: null\n };\n newBaseQueueLast = newBaseQueueLast.next = _clone;\n } // Mark the event time of this update as relevant to this render pass.\n // TODO: This should ideally use the true event time of this update rather than\n // its priority which is a derived and not reverseable value.\n // TODO: We should skip this update if it was already committed but currently\n // we have no way of detecting the difference between a committed and suspended\n // update here.\n\n\n markRenderEventTimeAndConfig(updateExpirationTime, update.suspenseConfig); // Process this update.\n\n newState = getStateFromUpdate(workInProgress, queue, update, newState, props, instance);\n var callback = update.callback;\n\n if (callback !== null) {\n workInProgress.effectTag |= Callback;\n var effects = queue.effects;\n\n if (effects === null) {\n queue.effects = [update];\n } else {\n effects.push(update);\n }\n }\n }\n\n update = update.next;\n\n if (update === null || update === first) {\n pendingQueue = queue.shared.pending;\n\n if (pendingQueue === null) {\n break;\n } else {\n // An update was scheduled from inside a reducer. Add the new\n // pending updates to the end of the list and keep processing.\n update = baseQueue.next = pendingQueue.next;\n pendingQueue.next = first;\n queue.baseQueue = baseQueue = pendingQueue;\n queue.shared.pending = null;\n }\n }\n } while (true);\n }\n\n if (newBaseQueueLast === null) {\n newBaseState = newState;\n } else {\n newBaseQueueLast.next = newBaseQueueFirst;\n }\n\n queue.baseState = newBaseState;\n queue.baseQueue = newBaseQueueLast; // Set the remaining expiration time to be whatever is remaining in the queue.\n // This should be fine because the only two other things that contribute to\n // expiration time are props and context. We're already in the middle of the\n // begin phase by the time we start processing the queue, so we've already\n // dealt with the props. Context in components that specify\n // shouldComponentUpdate is tricky; but we'll have to account for\n // that regardless.\n\n markUnprocessedUpdateTime(newExpirationTime);\n workInProgress.expirationTime = newExpirationTime;\n workInProgress.memoizedState = newState;\n }\n\n {\n currentlyProcessingQueue = null;\n }\n}\n\nfunction callCallback(callback, context) {\n if (!(typeof callback === 'function')) {\n {\n throw Error( \"Invalid argument passed as callback. Expected a function. Instead received: \" + callback );\n }\n }\n\n callback.call(context);\n}\n\nfunction resetHasForceUpdateBeforeProcessing() {\n hasForceUpdate = false;\n}\nfunction checkHasForceUpdateAfterProcessing() {\n return hasForceUpdate;\n}\nfunction commitUpdateQueue(finishedWork, finishedQueue, instance) {\n // Commit the effects\n var effects = finishedQueue.effects;\n finishedQueue.effects = null;\n\n if (effects !== null) {\n for (var i = 0; i < effects.length; i++) {\n var effect = effects[i];\n var callback = effect.callback;\n\n if (callback !== null) {\n effect.callback = null;\n callCallback(callback, instance);\n }\n }\n }\n}\n\nvar ReactCurrentBatchConfig = ReactSharedInternals.ReactCurrentBatchConfig;\nfunction requestCurrentSuspenseConfig() {\n return ReactCurrentBatchConfig.suspense;\n}\n\nvar fakeInternalInstance = {};\nvar isArray = Array.isArray; // React.Component uses a shared frozen object by default.\n// We'll use it to determine whether we need to initialize legacy refs.\n\nvar emptyRefsObject = new React.Component().refs;\nvar didWarnAboutStateAssignmentForComponent;\nvar didWarnAboutUninitializedState;\nvar didWarnAboutGetSnapshotBeforeUpdateWithoutDidUpdate;\nvar didWarnAboutLegacyLifecyclesAndDerivedState;\nvar didWarnAboutUndefinedDerivedState;\nvar warnOnUndefinedDerivedState;\nvar warnOnInvalidCallback;\nvar didWarnAboutDirectlyAssigningPropsToState;\nvar didWarnAboutContextTypeAndContextTypes;\nvar didWarnAboutInvalidateContextType;\n\n{\n didWarnAboutStateAssignmentForComponent = new Set();\n didWarnAboutUninitializedState = new Set();\n didWarnAboutGetSnapshotBeforeUpdateWithoutDidUpdate = new Set();\n didWarnAboutLegacyLifecyclesAndDerivedState = new Set();\n didWarnAboutDirectlyAssigningPropsToState = new Set();\n didWarnAboutUndefinedDerivedState = new Set();\n didWarnAboutContextTypeAndContextTypes = new Set();\n didWarnAboutInvalidateContextType = new Set();\n var didWarnOnInvalidCallback = new Set();\n\n warnOnInvalidCallback = function (callback, callerName) {\n if (callback === null || typeof callback === 'function') {\n return;\n }\n\n var key = callerName + \"_\" + callback;\n\n if (!didWarnOnInvalidCallback.has(key)) {\n didWarnOnInvalidCallback.add(key);\n\n error('%s(...): Expected the last optional `callback` argument to be a ' + 'function. Instead received: %s.', callerName, callback);\n }\n };\n\n warnOnUndefinedDerivedState = function (type, partialState) {\n if (partialState === undefined) {\n var componentName = getComponentName(type) || 'Component';\n\n if (!didWarnAboutUndefinedDerivedState.has(componentName)) {\n didWarnAboutUndefinedDerivedState.add(componentName);\n\n error('%s.getDerivedStateFromProps(): A valid state object (or null) must be returned. ' + 'You have returned undefined.', componentName);\n }\n }\n }; // This is so gross but it's at least non-critical and can be removed if\n // it causes problems. This is meant to give a nicer error message for\n // ReactDOM15.unstable_renderSubtreeIntoContainer(reactDOM16Component,\n // ...)) which otherwise throws a \"_processChildContext is not a function\"\n // exception.\n\n\n Object.defineProperty(fakeInternalInstance, '_processChildContext', {\n enumerable: false,\n value: function () {\n {\n {\n throw Error( \"_processChildContext is not available in React 16+. This likely means you have multiple copies of React and are attempting to nest a React 15 tree inside a React 16 tree using unstable_renderSubtreeIntoContainer, which isn't supported. Try to make sure you have only one copy of React (and ideally, switch to ReactDOM.createPortal).\" );\n }\n }\n }\n });\n Object.freeze(fakeInternalInstance);\n}\n\nfunction applyDerivedStateFromProps(workInProgress, ctor, getDerivedStateFromProps, nextProps) {\n var prevState = workInProgress.memoizedState;\n\n {\n if ( workInProgress.mode & StrictMode) {\n // Invoke the function an extra time to help detect side-effects.\n getDerivedStateFromProps(nextProps, prevState);\n }\n }\n\n var partialState = getDerivedStateFromProps(nextProps, prevState);\n\n {\n warnOnUndefinedDerivedState(ctor, partialState);\n } // Merge the partial state and the previous state.\n\n\n var memoizedState = partialState === null || partialState === undefined ? prevState : _assign({}, prevState, partialState);\n workInProgress.memoizedState = memoizedState; // Once the update queue is empty, persist the derived state onto the\n // base state.\n\n if (workInProgress.expirationTime === NoWork) {\n // Queue is always non-null for classes\n var updateQueue = workInProgress.updateQueue;\n updateQueue.baseState = memoizedState;\n }\n}\nvar classComponentUpdater = {\n isMounted: isMounted,\n enqueueSetState: function (inst, payload, callback) {\n var fiber = get(inst);\n var currentTime = requestCurrentTimeForUpdate();\n var suspenseConfig = requestCurrentSuspenseConfig();\n var expirationTime = computeExpirationForFiber(currentTime, fiber, suspenseConfig);\n var update = createUpdate(expirationTime, suspenseConfig);\n update.payload = payload;\n\n if (callback !== undefined && callback !== null) {\n {\n warnOnInvalidCallback(callback, 'setState');\n }\n\n update.callback = callback;\n }\n\n enqueueUpdate(fiber, update);\n scheduleWork(fiber, expirationTime);\n },\n enqueueReplaceState: function (inst, payload, callback) {\n var fiber = get(inst);\n var currentTime = requestCurrentTimeForUpdate();\n var suspenseConfig = requestCurrentSuspenseConfig();\n var expirationTime = computeExpirationForFiber(currentTime, fiber, suspenseConfig);\n var update = createUpdate(expirationTime, suspenseConfig);\n update.tag = ReplaceState;\n update.payload = payload;\n\n if (callback !== undefined && callback !== null) {\n {\n warnOnInvalidCallback(callback, 'replaceState');\n }\n\n update.callback = callback;\n }\n\n enqueueUpdate(fiber, update);\n scheduleWork(fiber, expirationTime);\n },\n enqueueForceUpdate: function (inst, callback) {\n var fiber = get(inst);\n var currentTime = requestCurrentTimeForUpdate();\n var suspenseConfig = requestCurrentSuspenseConfig();\n var expirationTime = computeExpirationForFiber(currentTime, fiber, suspenseConfig);\n var update = createUpdate(expirationTime, suspenseConfig);\n update.tag = ForceUpdate;\n\n if (callback !== undefined && callback !== null) {\n {\n warnOnInvalidCallback(callback, 'forceUpdate');\n }\n\n update.callback = callback;\n }\n\n enqueueUpdate(fiber, update);\n scheduleWork(fiber, expirationTime);\n }\n};\n\nfunction checkShouldComponentUpdate(workInProgress, ctor, oldProps, newProps, oldState, newState, nextContext) {\n var instance = workInProgress.stateNode;\n\n if (typeof instance.shouldComponentUpdate === 'function') {\n {\n if ( workInProgress.mode & StrictMode) {\n // Invoke the function an extra time to help detect side-effects.\n instance.shouldComponentUpdate(newProps, newState, nextContext);\n }\n }\n\n startPhaseTimer(workInProgress, 'shouldComponentUpdate');\n var shouldUpdate = instance.shouldComponentUpdate(newProps, newState, nextContext);\n stopPhaseTimer();\n\n {\n if (shouldUpdate === undefined) {\n error('%s.shouldComponentUpdate(): Returned undefined instead of a ' + 'boolean value. Make sure to return true or false.', getComponentName(ctor) || 'Component');\n }\n }\n\n return shouldUpdate;\n }\n\n if (ctor.prototype && ctor.prototype.isPureReactComponent) {\n return !shallowEqual(oldProps, newProps) || !shallowEqual(oldState, newState);\n }\n\n return true;\n}\n\nfunction checkClassInstance(workInProgress, ctor, newProps) {\n var instance = workInProgress.stateNode;\n\n {\n var name = getComponentName(ctor) || 'Component';\n var renderPresent = instance.render;\n\n if (!renderPresent) {\n if (ctor.prototype && typeof ctor.prototype.render === 'function') {\n error('%s(...): No `render` method found on the returned component ' + 'instance: did you accidentally return an object from the constructor?', name);\n } else {\n error('%s(...): No `render` method found on the returned component ' + 'instance: you may have forgotten to define `render`.', name);\n }\n }\n\n if (instance.getInitialState && !instance.getInitialState.isReactClassApproved && !instance.state) {\n error('getInitialState was defined on %s, a plain JavaScript class. ' + 'This is only supported for classes created using React.createClass. ' + 'Did you mean to define a state property instead?', name);\n }\n\n if (instance.getDefaultProps && !instance.getDefaultProps.isReactClassApproved) {\n error('getDefaultProps was defined on %s, a plain JavaScript class. ' + 'This is only supported for classes created using React.createClass. ' + 'Use a static property to define defaultProps instead.', name);\n }\n\n if (instance.propTypes) {\n error('propTypes was defined as an instance property on %s. Use a static ' + 'property to define propTypes instead.', name);\n }\n\n if (instance.contextType) {\n error('contextType was defined as an instance property on %s. Use a static ' + 'property to define contextType instead.', name);\n }\n\n {\n if (instance.contextTypes) {\n error('contextTypes was defined as an instance property on %s. Use a static ' + 'property to define contextTypes instead.', name);\n }\n\n if (ctor.contextType && ctor.contextTypes && !didWarnAboutContextTypeAndContextTypes.has(ctor)) {\n didWarnAboutContextTypeAndContextTypes.add(ctor);\n\n error('%s declares both contextTypes and contextType static properties. ' + 'The legacy contextTypes property will be ignored.', name);\n }\n }\n\n if (typeof instance.componentShouldUpdate === 'function') {\n error('%s has a method called ' + 'componentShouldUpdate(). Did you mean shouldComponentUpdate()? ' + 'The name is phrased as a question because the function is ' + 'expected to return a value.', name);\n }\n\n if (ctor.prototype && ctor.prototype.isPureReactComponent && typeof instance.shouldComponentUpdate !== 'undefined') {\n error('%s has a method called shouldComponentUpdate(). ' + 'shouldComponentUpdate should not be used when extending React.PureComponent. ' + 'Please extend React.Component if shouldComponentUpdate is used.', getComponentName(ctor) || 'A pure component');\n }\n\n if (typeof instance.componentDidUnmount === 'function') {\n error('%s has a method called ' + 'componentDidUnmount(). But there is no such lifecycle method. ' + 'Did you mean componentWillUnmount()?', name);\n }\n\n if (typeof instance.componentDidReceiveProps === 'function') {\n error('%s has a method called ' + 'componentDidReceiveProps(). But there is no such lifecycle method. ' + 'If you meant to update the state in response to changing props, ' + 'use componentWillReceiveProps(). If you meant to fetch data or ' + 'run side-effects or mutations after React has updated the UI, use componentDidUpdate().', name);\n }\n\n if (typeof instance.componentWillRecieveProps === 'function') {\n error('%s has a method called ' + 'componentWillRecieveProps(). Did you mean componentWillReceiveProps()?', name);\n }\n\n if (typeof instance.UNSAFE_componentWillRecieveProps === 'function') {\n error('%s has a method called ' + 'UNSAFE_componentWillRecieveProps(). Did you mean UNSAFE_componentWillReceiveProps()?', name);\n }\n\n var hasMutatedProps = instance.props !== newProps;\n\n if (instance.props !== undefined && hasMutatedProps) {\n error('%s(...): When calling super() in `%s`, make sure to pass ' + \"up the same props that your component's constructor was passed.\", name, name);\n }\n\n if (instance.defaultProps) {\n error('Setting defaultProps as an instance property on %s is not supported and will be ignored.' + ' Instead, define defaultProps as a static property on %s.', name, name);\n }\n\n if (typeof instance.getSnapshotBeforeUpdate === 'function' && typeof instance.componentDidUpdate !== 'function' && !didWarnAboutGetSnapshotBeforeUpdateWithoutDidUpdate.has(ctor)) {\n didWarnAboutGetSnapshotBeforeUpdateWithoutDidUpdate.add(ctor);\n\n error('%s: getSnapshotBeforeUpdate() should be used with componentDidUpdate(). ' + 'This component defines getSnapshotBeforeUpdate() only.', getComponentName(ctor));\n }\n\n if (typeof instance.getDerivedStateFromProps === 'function') {\n error('%s: getDerivedStateFromProps() is defined as an instance method ' + 'and will be ignored. Instead, declare it as a static method.', name);\n }\n\n if (typeof instance.getDerivedStateFromError === 'function') {\n error('%s: getDerivedStateFromError() is defined as an instance method ' + 'and will be ignored. Instead, declare it as a static method.', name);\n }\n\n if (typeof ctor.getSnapshotBeforeUpdate === 'function') {\n error('%s: getSnapshotBeforeUpdate() is defined as a static method ' + 'and will be ignored. Instead, declare it as an instance method.', name);\n }\n\n var _state = instance.state;\n\n if (_state && (typeof _state !== 'object' || isArray(_state))) {\n error('%s.state: must be set to an object or null', name);\n }\n\n if (typeof instance.getChildContext === 'function' && typeof ctor.childContextTypes !== 'object') {\n error('%s.getChildContext(): childContextTypes must be defined in order to ' + 'use getChildContext().', name);\n }\n }\n}\n\nfunction adoptClassInstance(workInProgress, instance) {\n instance.updater = classComponentUpdater;\n workInProgress.stateNode = instance; // The instance needs access to the fiber so that it can schedule updates\n\n set(instance, workInProgress);\n\n {\n instance._reactInternalInstance = fakeInternalInstance;\n }\n}\n\nfunction constructClassInstance(workInProgress, ctor, props) {\n var isLegacyContextConsumer = false;\n var unmaskedContext = emptyContextObject;\n var context = emptyContextObject;\n var contextType = ctor.contextType;\n\n {\n if ('contextType' in ctor) {\n var isValid = // Allow null for conditional declaration\n contextType === null || contextType !== undefined && contextType.$$typeof === REACT_CONTEXT_TYPE && contextType._context === undefined; // Not a <Context.Consumer>\n\n if (!isValid && !didWarnAboutInvalidateContextType.has(ctor)) {\n didWarnAboutInvalidateContextType.add(ctor);\n var addendum = '';\n\n if (contextType === undefined) {\n addendum = ' However, it is set to undefined. ' + 'This can be caused by a typo or by mixing up named and default imports. ' + 'This can also happen due to a circular dependency, so ' + 'try moving the createContext() call to a separate file.';\n } else if (typeof contextType !== 'object') {\n addendum = ' However, it is set to a ' + typeof contextType + '.';\n } else if (contextType.$$typeof === REACT_PROVIDER_TYPE) {\n addendum = ' Did you accidentally pass the Context.Provider instead?';\n } else if (contextType._context !== undefined) {\n // <Context.Consumer>\n addendum = ' Did you accidentally pass the Context.Consumer instead?';\n } else {\n addendum = ' However, it is set to an object with keys {' + Object.keys(contextType).join(', ') + '}.';\n }\n\n error('%s defines an invalid contextType. ' + 'contextType should point to the Context object returned by React.createContext().%s', getComponentName(ctor) || 'Component', addendum);\n }\n }\n }\n\n if (typeof contextType === 'object' && contextType !== null) {\n context = readContext(contextType);\n } else {\n unmaskedContext = getUnmaskedContext(workInProgress, ctor, true);\n var contextTypes = ctor.contextTypes;\n isLegacyContextConsumer = contextTypes !== null && contextTypes !== undefined;\n context = isLegacyContextConsumer ? getMaskedContext(workInProgress, unmaskedContext) : emptyContextObject;\n } // Instantiate twice to help detect side-effects.\n\n\n {\n if ( workInProgress.mode & StrictMode) {\n new ctor(props, context); // eslint-disable-line no-new\n }\n }\n\n var instance = new ctor(props, context);\n var state = workInProgress.memoizedState = instance.state !== null && instance.state !== undefined ? instance.state : null;\n adoptClassInstance(workInProgress, instance);\n\n {\n if (typeof ctor.getDerivedStateFromProps === 'function' && state === null) {\n var componentName = getComponentName(ctor) || 'Component';\n\n if (!didWarnAboutUninitializedState.has(componentName)) {\n didWarnAboutUninitializedState.add(componentName);\n\n error('`%s` uses `getDerivedStateFromProps` but its initial state is ' + '%s. This is not recommended. Instead, define the initial state by ' + 'assigning an object to `this.state` in the constructor of `%s`. ' + 'This ensures that `getDerivedStateFromProps` arguments have a consistent shape.', componentName, instance.state === null ? 'null' : 'undefined', componentName);\n }\n } // If new component APIs are defined, \"unsafe\" lifecycles won't be called.\n // Warn about these lifecycles if they are present.\n // Don't warn about react-lifecycles-compat polyfilled methods though.\n\n\n if (typeof ctor.getDerivedStateFromProps === 'function' || typeof instance.getSnapshotBeforeUpdate === 'function') {\n var foundWillMountName = null;\n var foundWillReceivePropsName = null;\n var foundWillUpdateName = null;\n\n if (typeof instance.componentWillMount === 'function' && instance.componentWillMount.__suppressDeprecationWarning !== true) {\n foundWillMountName = 'componentWillMount';\n } else if (typeof instance.UNSAFE_componentWillMount === 'function') {\n foundWillMountName = 'UNSAFE_componentWillMount';\n }\n\n if (typeof instance.componentWillReceiveProps === 'function' && instance.componentWillReceiveProps.__suppressDeprecationWarning !== true) {\n foundWillReceivePropsName = 'componentWillReceiveProps';\n } else if (typeof instance.UNSAFE_componentWillReceiveProps === 'function') {\n foundWillReceivePropsName = 'UNSAFE_componentWillReceiveProps';\n }\n\n if (typeof instance.componentWillUpdate === 'function' && instance.componentWillUpdate.__suppressDeprecationWarning !== true) {\n foundWillUpdateName = 'componentWillUpdate';\n } else if (typeof instance.UNSAFE_componentWillUpdate === 'function') {\n foundWillUpdateName = 'UNSAFE_componentWillUpdate';\n }\n\n if (foundWillMountName !== null || foundWillReceivePropsName !== null || foundWillUpdateName !== null) {\n var _componentName = getComponentName(ctor) || 'Component';\n\n var newApiName = typeof ctor.getDerivedStateFromProps === 'function' ? 'getDerivedStateFromProps()' : 'getSnapshotBeforeUpdate()';\n\n if (!didWarnAboutLegacyLifecyclesAndDerivedState.has(_componentName)) {\n didWarnAboutLegacyLifecyclesAndDerivedState.add(_componentName);\n\n error('Unsafe legacy lifecycles will not be called for components using new component APIs.\\n\\n' + '%s uses %s but also contains the following legacy lifecycles:%s%s%s\\n\\n' + 'The above lifecycles should be removed. Learn more about this warning here:\\n' + 'https://fb.me/react-unsafe-component-lifecycles', _componentName, newApiName, foundWillMountName !== null ? \"\\n \" + foundWillMountName : '', foundWillReceivePropsName !== null ? \"\\n \" + foundWillReceivePropsName : '', foundWillUpdateName !== null ? \"\\n \" + foundWillUpdateName : '');\n }\n }\n }\n } // Cache unmasked context so we can avoid recreating masked context unless necessary.\n // ReactFiberContext usually updates this cache but can't for newly-created instances.\n\n\n if (isLegacyContextConsumer) {\n cacheContext(workInProgress, unmaskedContext, context);\n }\n\n return instance;\n}\n\nfunction callComponentWillMount(workInProgress, instance) {\n startPhaseTimer(workInProgress, 'componentWillMount');\n var oldState = instance.state;\n\n if (typeof instance.componentWillMount === 'function') {\n instance.componentWillMount();\n }\n\n if (typeof instance.UNSAFE_componentWillMount === 'function') {\n instance.UNSAFE_componentWillMount();\n }\n\n stopPhaseTimer();\n\n if (oldState !== instance.state) {\n {\n error('%s.componentWillMount(): Assigning directly to this.state is ' + \"deprecated (except inside a component's \" + 'constructor). Use setState instead.', getComponentName(workInProgress.type) || 'Component');\n }\n\n classComponentUpdater.enqueueReplaceState(instance, instance.state, null);\n }\n}\n\nfunction callComponentWillReceiveProps(workInProgress, instance, newProps, nextContext) {\n var oldState = instance.state;\n startPhaseTimer(workInProgress, 'componentWillReceiveProps');\n\n if (typeof instance.componentWillReceiveProps === 'function') {\n instance.componentWillReceiveProps(newProps, nextContext);\n }\n\n if (typeof instance.UNSAFE_componentWillReceiveProps === 'function') {\n instance.UNSAFE_componentWillReceiveProps(newProps, nextContext);\n }\n\n stopPhaseTimer();\n\n if (instance.state !== oldState) {\n {\n var componentName = getComponentName(workInProgress.type) || 'Component';\n\n if (!didWarnAboutStateAssignmentForComponent.has(componentName)) {\n didWarnAboutStateAssignmentForComponent.add(componentName);\n\n error('%s.componentWillReceiveProps(): Assigning directly to ' + \"this.state is deprecated (except inside a component's \" + 'constructor). Use setState instead.', componentName);\n }\n }\n\n classComponentUpdater.enqueueReplaceState(instance, instance.state, null);\n }\n} // Invokes the mount life-cycles on a previously never rendered instance.\n\n\nfunction mountClassInstance(workInProgress, ctor, newProps, renderExpirationTime) {\n {\n checkClassInstance(workInProgress, ctor, newProps);\n }\n\n var instance = workInProgress.stateNode;\n instance.props = newProps;\n instance.state = workInProgress.memoizedState;\n instance.refs = emptyRefsObject;\n initializeUpdateQueue(workInProgress);\n var contextType = ctor.contextType;\n\n if (typeof contextType === 'object' && contextType !== null) {\n instance.context = readContext(contextType);\n } else {\n var unmaskedContext = getUnmaskedContext(workInProgress, ctor, true);\n instance.context = getMaskedContext(workInProgress, unmaskedContext);\n }\n\n {\n if (instance.state === newProps) {\n var componentName = getComponentName(ctor) || 'Component';\n\n if (!didWarnAboutDirectlyAssigningPropsToState.has(componentName)) {\n didWarnAboutDirectlyAssigningPropsToState.add(componentName);\n\n error('%s: It is not recommended to assign props directly to state ' + \"because updates to props won't be reflected in state. \" + 'In most cases, it is better to use props directly.', componentName);\n }\n }\n\n if (workInProgress.mode & StrictMode) {\n ReactStrictModeWarnings.recordLegacyContextWarning(workInProgress, instance);\n }\n\n {\n ReactStrictModeWarnings.recordUnsafeLifecycleWarnings(workInProgress, instance);\n }\n }\n\n processUpdateQueue(workInProgress, newProps, instance, renderExpirationTime);\n instance.state = workInProgress.memoizedState;\n var getDerivedStateFromProps = ctor.getDerivedStateFromProps;\n\n if (typeof getDerivedStateFromProps === 'function') {\n applyDerivedStateFromProps(workInProgress, ctor, getDerivedStateFromProps, newProps);\n instance.state = workInProgress.memoizedState;\n } // In order to support react-lifecycles-compat polyfilled components,\n // Unsafe lifecycles should not be invoked for components using the new APIs.\n\n\n if (typeof ctor.getDerivedStateFromProps !== 'function' && typeof instance.getSnapshotBeforeUpdate !== 'function' && (typeof instance.UNSAFE_componentWillMount === 'function' || typeof instance.componentWillMount === 'function')) {\n callComponentWillMount(workInProgress, instance); // If we had additional state updates during this life-cycle, let's\n // process them now.\n\n processUpdateQueue(workInProgress, newProps, instance, renderExpirationTime);\n instance.state = workInProgress.memoizedState;\n }\n\n if (typeof instance.componentDidMount === 'function') {\n workInProgress.effectTag |= Update;\n }\n}\n\nfunction resumeMountClassInstance(workInProgress, ctor, newProps, renderExpirationTime) {\n var instance = workInProgress.stateNode;\n var oldProps = workInProgress.memoizedProps;\n instance.props = oldProps;\n var oldContext = instance.context;\n var contextType = ctor.contextType;\n var nextContext = emptyContextObject;\n\n if (typeof contextType === 'object' && contextType !== null) {\n nextContext = readContext(contextType);\n } else {\n var nextLegacyUnmaskedContext = getUnmaskedContext(workInProgress, ctor, true);\n nextContext = getMaskedContext(workInProgress, nextLegacyUnmaskedContext);\n }\n\n var getDerivedStateFromProps = ctor.getDerivedStateFromProps;\n var hasNewLifecycles = typeof getDerivedStateFromProps === 'function' || typeof instance.getSnapshotBeforeUpdate === 'function'; // Note: During these life-cycles, instance.props/instance.state are what\n // ever the previously attempted to render - not the \"current\". However,\n // during componentDidUpdate we pass the \"current\" props.\n // In order to support react-lifecycles-compat polyfilled components,\n // Unsafe lifecycles should not be invoked for components using the new APIs.\n\n if (!hasNewLifecycles && (typeof instance.UNSAFE_componentWillReceiveProps === 'function' || typeof instance.componentWillReceiveProps === 'function')) {\n if (oldProps !== newProps || oldContext !== nextContext) {\n callComponentWillReceiveProps(workInProgress, instance, newProps, nextContext);\n }\n }\n\n resetHasForceUpdateBeforeProcessing();\n var oldState = workInProgress.memoizedState;\n var newState = instance.state = oldState;\n processUpdateQueue(workInProgress, newProps, instance, renderExpirationTime);\n newState = workInProgress.memoizedState;\n\n if (oldProps === newProps && oldState === newState && !hasContextChanged() && !checkHasForceUpdateAfterProcessing()) {\n // If an update was already in progress, we should schedule an Update\n // effect even though we're bailing out, so that cWU/cDU are called.\n if (typeof instance.componentDidMount === 'function') {\n workInProgress.effectTag |= Update;\n }\n\n return false;\n }\n\n if (typeof getDerivedStateFromProps === 'function') {\n applyDerivedStateFromProps(workInProgress, ctor, getDerivedStateFromProps, newProps);\n newState = workInProgress.memoizedState;\n }\n\n var shouldUpdate = checkHasForceUpdateAfterProcessing() || checkShouldComponentUpdate(workInProgress, ctor, oldProps, newProps, oldState, newState, nextContext);\n\n if (shouldUpdate) {\n // In order to support react-lifecycles-compat polyfilled components,\n // Unsafe lifecycles should not be invoked for components using the new APIs.\n if (!hasNewLifecycles && (typeof instance.UNSAFE_componentWillMount === 'function' || typeof instance.componentWillMount === 'function')) {\n startPhaseTimer(workInProgress, 'componentWillMount');\n\n if (typeof instance.componentWillMount === 'function') {\n instance.componentWillMount();\n }\n\n if (typeof instance.UNSAFE_componentWillMount === 'function') {\n instance.UNSAFE_componentWillMount();\n }\n\n stopPhaseTimer();\n }\n\n if (typeof instance.componentDidMount === 'function') {\n workInProgress.effectTag |= Update;\n }\n } else {\n // If an update was already in progress, we should schedule an Update\n // effect even though we're bailing out, so that cWU/cDU are called.\n if (typeof instance.componentDidMount === 'function') {\n workInProgress.effectTag |= Update;\n } // If shouldComponentUpdate returned false, we should still update the\n // memoized state to indicate that this work can be reused.\n\n\n workInProgress.memoizedProps = newProps;\n workInProgress.memoizedState = newState;\n } // Update the existing instance's state, props, and context pointers even\n // if shouldComponentUpdate returns false.\n\n\n instance.props = newProps;\n instance.state = newState;\n instance.context = nextContext;\n return shouldUpdate;\n} // Invokes the update life-cycles and returns false if it shouldn't rerender.\n\n\nfunction updateClassInstance(current, workInProgress, ctor, newProps, renderExpirationTime) {\n var instance = workInProgress.stateNode;\n cloneUpdateQueue(current, workInProgress);\n var oldProps = workInProgress.memoizedProps;\n instance.props = workInProgress.type === workInProgress.elementType ? oldProps : resolveDefaultProps(workInProgress.type, oldProps);\n var oldContext = instance.context;\n var contextType = ctor.contextType;\n var nextContext = emptyContextObject;\n\n if (typeof contextType === 'object' && contextType !== null) {\n nextContext = readContext(contextType);\n } else {\n var nextUnmaskedContext = getUnmaskedContext(workInProgress, ctor, true);\n nextContext = getMaskedContext(workInProgress, nextUnmaskedContext);\n }\n\n var getDerivedStateFromProps = ctor.getDerivedStateFromProps;\n var hasNewLifecycles = typeof getDerivedStateFromProps === 'function' || typeof instance.getSnapshotBeforeUpdate === 'function'; // Note: During these life-cycles, instance.props/instance.state are what\n // ever the previously attempted to render - not the \"current\". However,\n // during componentDidUpdate we pass the \"current\" props.\n // In order to support react-lifecycles-compat polyfilled components,\n // Unsafe lifecycles should not be invoked for components using the new APIs.\n\n if (!hasNewLifecycles && (typeof instance.UNSAFE_componentWillReceiveProps === 'function' || typeof instance.componentWillReceiveProps === 'function')) {\n if (oldProps !== newProps || oldContext !== nextContext) {\n callComponentWillReceiveProps(workInProgress, instance, newProps, nextContext);\n }\n }\n\n resetHasForceUpdateBeforeProcessing();\n var oldState = workInProgress.memoizedState;\n var newState = instance.state = oldState;\n processUpdateQueue(workInProgress, newProps, instance, renderExpirationTime);\n newState = workInProgress.memoizedState;\n\n if (oldProps === newProps && oldState === newState && !hasContextChanged() && !checkHasForceUpdateAfterProcessing()) {\n // If an update was already in progress, we should schedule an Update\n // effect even though we're bailing out, so that cWU/cDU are called.\n if (typeof instance.componentDidUpdate === 'function') {\n if (oldProps !== current.memoizedProps || oldState !== current.memoizedState) {\n workInProgress.effectTag |= Update;\n }\n }\n\n if (typeof instance.getSnapshotBeforeUpdate === 'function') {\n if (oldProps !== current.memoizedProps || oldState !== current.memoizedState) {\n workInProgress.effectTag |= Snapshot;\n }\n }\n\n return false;\n }\n\n if (typeof getDerivedStateFromProps === 'function') {\n applyDerivedStateFromProps(workInProgress, ctor, getDerivedStateFromProps, newProps);\n newState = workInProgress.memoizedState;\n }\n\n var shouldUpdate = checkHasForceUpdateAfterProcessing() || checkShouldComponentUpdate(workInProgress, ctor, oldProps, newProps, oldState, newState, nextContext);\n\n if (shouldUpdate) {\n // In order to support react-lifecycles-compat polyfilled components,\n // Unsafe lifecycles should not be invoked for components using the new APIs.\n if (!hasNewLifecycles && (typeof instance.UNSAFE_componentWillUpdate === 'function' || typeof instance.componentWillUpdate === 'function')) {\n startPhaseTimer(workInProgress, 'componentWillUpdate');\n\n if (typeof instance.componentWillUpdate === 'function') {\n instance.componentWillUpdate(newProps, newState, nextContext);\n }\n\n if (typeof instance.UNSAFE_componentWillUpdate === 'function') {\n instance.UNSAFE_componentWillUpdate(newProps, newState, nextContext);\n }\n\n stopPhaseTimer();\n }\n\n if (typeof instance.componentDidUpdate === 'function') {\n workInProgress.effectTag |= Update;\n }\n\n if (typeof instance.getSnapshotBeforeUpdate === 'function') {\n workInProgress.effectTag |= Snapshot;\n }\n } else {\n // If an update was already in progress, we should schedule an Update\n // effect even though we're bailing out, so that cWU/cDU are called.\n if (typeof instance.componentDidUpdate === 'function') {\n if (oldProps !== current.memoizedProps || oldState !== current.memoizedState) {\n workInProgress.effectTag |= Update;\n }\n }\n\n if (typeof instance.getSnapshotBeforeUpdate === 'function') {\n if (oldProps !== current.memoizedProps || oldState !== current.memoizedState) {\n workInProgress.effectTag |= Snapshot;\n }\n } // If shouldComponentUpdate returned false, we should still update the\n // memoized props/state to indicate that this work can be reused.\n\n\n workInProgress.memoizedProps = newProps;\n workInProgress.memoizedState = newState;\n } // Update the existing instance's state, props, and context pointers even\n // if shouldComponentUpdate returns false.\n\n\n instance.props = newProps;\n instance.state = newState;\n instance.context = nextContext;\n return shouldUpdate;\n}\n\nvar didWarnAboutMaps;\nvar didWarnAboutGenerators;\nvar didWarnAboutStringRefs;\nvar ownerHasKeyUseWarning;\nvar ownerHasFunctionTypeWarning;\n\nvar warnForMissingKey = function (child) {};\n\n{\n didWarnAboutMaps = false;\n didWarnAboutGenerators = false;\n didWarnAboutStringRefs = {};\n /**\n * Warn if there's no key explicitly set on dynamic arrays of children or\n * object keys are not valid. This allows us to keep track of children between\n * updates.\n */\n\n ownerHasKeyUseWarning = {};\n ownerHasFunctionTypeWarning = {};\n\n warnForMissingKey = function (child) {\n if (child === null || typeof child !== 'object') {\n return;\n }\n\n if (!child._store || child._store.validated || child.key != null) {\n return;\n }\n\n if (!(typeof child._store === 'object')) {\n {\n throw Error( \"React Component in warnForMissingKey should have a _store. This error is likely caused by a bug in React. Please file an issue.\" );\n }\n }\n\n child._store.validated = true;\n var currentComponentErrorInfo = 'Each child in a list should have a unique ' + '\"key\" prop. See https://fb.me/react-warning-keys for ' + 'more information.' + getCurrentFiberStackInDev();\n\n if (ownerHasKeyUseWarning[currentComponentErrorInfo]) {\n return;\n }\n\n ownerHasKeyUseWarning[currentComponentErrorInfo] = true;\n\n error('Each child in a list should have a unique ' + '\"key\" prop. See https://fb.me/react-warning-keys for ' + 'more information.');\n };\n}\n\nvar isArray$1 = Array.isArray;\n\nfunction coerceRef(returnFiber, current, element) {\n var mixedRef = element.ref;\n\n if (mixedRef !== null && typeof mixedRef !== 'function' && typeof mixedRef !== 'object') {\n {\n // TODO: Clean this up once we turn on the string ref warning for\n // everyone, because the strict mode case will no longer be relevant\n if ((returnFiber.mode & StrictMode || warnAboutStringRefs) && // We warn in ReactElement.js if owner and self are equal for string refs\n // because these cannot be automatically converted to an arrow function\n // using a codemod. Therefore, we don't have to warn about string refs again.\n !(element._owner && element._self && element._owner.stateNode !== element._self)) {\n var componentName = getComponentName(returnFiber.type) || 'Component';\n\n if (!didWarnAboutStringRefs[componentName]) {\n {\n error('A string ref, \"%s\", has been found within a strict mode tree. ' + 'String refs are a source of potential bugs and should be avoided. ' + 'We recommend using useRef() or createRef() instead. ' + 'Learn more about using refs safely here: ' + 'https://fb.me/react-strict-mode-string-ref%s', mixedRef, getStackByFiberInDevAndProd(returnFiber));\n }\n\n didWarnAboutStringRefs[componentName] = true;\n }\n }\n }\n\n if (element._owner) {\n var owner = element._owner;\n var inst;\n\n if (owner) {\n var ownerFiber = owner;\n\n if (!(ownerFiber.tag === ClassComponent)) {\n {\n throw Error( \"Function components cannot have string refs. We recommend using useRef() instead. Learn more about using refs safely here: https://fb.me/react-strict-mode-string-ref\" );\n }\n }\n\n inst = ownerFiber.stateNode;\n }\n\n if (!inst) {\n {\n throw Error( \"Missing owner for string ref \" + mixedRef + \". This error is likely caused by a bug in React. Please file an issue.\" );\n }\n }\n\n var stringRef = '' + mixedRef; // Check if previous string ref matches new string ref\n\n if (current !== null && current.ref !== null && typeof current.ref === 'function' && current.ref._stringRef === stringRef) {\n return current.ref;\n }\n\n var ref = function (value) {\n var refs = inst.refs;\n\n if (refs === emptyRefsObject) {\n // This is a lazy pooled frozen object, so we need to initialize.\n refs = inst.refs = {};\n }\n\n if (value === null) {\n delete refs[stringRef];\n } else {\n refs[stringRef] = value;\n }\n };\n\n ref._stringRef = stringRef;\n return ref;\n } else {\n if (!(typeof mixedRef === 'string')) {\n {\n throw Error( \"Expected ref to be a function, a string, an object returned by React.createRef(), or null.\" );\n }\n }\n\n if (!element._owner) {\n {\n throw Error( \"Element ref was specified as a string (\" + mixedRef + \") but no owner was set. This could happen for one of the following reasons:\\n1. You may be adding a ref to a function component\\n2. You may be adding a ref to a component that was not created inside a component's render method\\n3. You have multiple copies of React loaded\\nSee https://fb.me/react-refs-must-have-owner for more information.\" );\n }\n }\n }\n }\n\n return mixedRef;\n}\n\nfunction throwOnInvalidObjectType(returnFiber, newChild) {\n if (returnFiber.type !== 'textarea') {\n var addendum = '';\n\n {\n addendum = ' If you meant to render a collection of children, use an array ' + 'instead.' + getCurrentFiberStackInDev();\n }\n\n {\n {\n throw Error( \"Objects are not valid as a React child (found: \" + (Object.prototype.toString.call(newChild) === '[object Object]' ? 'object with keys {' + Object.keys(newChild).join(', ') + '}' : newChild) + \").\" + addendum );\n }\n }\n }\n}\n\nfunction warnOnFunctionType() {\n {\n var currentComponentErrorInfo = 'Functions are not valid as a React child. This may happen if ' + 'you return a Component instead of <Component /> from render. ' + 'Or maybe you meant to call this function rather than return it.' + getCurrentFiberStackInDev();\n\n if (ownerHasFunctionTypeWarning[currentComponentErrorInfo]) {\n return;\n }\n\n ownerHasFunctionTypeWarning[currentComponentErrorInfo] = true;\n\n error('Functions are not valid as a React child. This may happen if ' + 'you return a Component instead of <Component /> from render. ' + 'Or maybe you meant to call this function rather than return it.');\n }\n} // This wrapper function exists because I expect to clone the code in each path\n// to be able to optimize each path individually by branching early. This needs\n// a compiler or we can do it manually. Helpers that don't need this branching\n// live outside of this function.\n\n\nfunction ChildReconciler(shouldTrackSideEffects) {\n function deleteChild(returnFiber, childToDelete) {\n if (!shouldTrackSideEffects) {\n // Noop.\n return;\n } // Deletions are added in reversed order so we add it to the front.\n // At this point, the return fiber's effect list is empty except for\n // deletions, so we can just append the deletion to the list. The remaining\n // effects aren't added until the complete phase. Once we implement\n // resuming, this may not be true.\n\n\n var last = returnFiber.lastEffect;\n\n if (last !== null) {\n last.nextEffect = childToDelete;\n returnFiber.lastEffect = childToDelete;\n } else {\n returnFiber.firstEffect = returnFiber.lastEffect = childToDelete;\n }\n\n childToDelete.nextEffect = null;\n childToDelete.effectTag = Deletion;\n }\n\n function deleteRemainingChildren(returnFiber, currentFirstChild) {\n if (!shouldTrackSideEffects) {\n // Noop.\n return null;\n } // TODO: For the shouldClone case, this could be micro-optimized a bit by\n // assuming that after the first child we've already added everything.\n\n\n var childToDelete = currentFirstChild;\n\n while (childToDelete !== null) {\n deleteChild(returnFiber, childToDelete);\n childToDelete = childToDelete.sibling;\n }\n\n return null;\n }\n\n function mapRemainingChildren(returnFiber, currentFirstChild) {\n // Add the remaining children to a temporary map so that we can find them by\n // keys quickly. Implicit (null) keys get added to this set with their index\n // instead.\n var existingChildren = new Map();\n var existingChild = currentFirstChild;\n\n while (existingChild !== null) {\n if (existingChild.key !== null) {\n existingChildren.set(existingChild.key, existingChild);\n } else {\n existingChildren.set(existingChild.index, existingChild);\n }\n\n existingChild = existingChild.sibling;\n }\n\n return existingChildren;\n }\n\n function useFiber(fiber, pendingProps) {\n // We currently set sibling to null and index to 0 here because it is easy\n // to forget to do before returning it. E.g. for the single child case.\n var clone = createWorkInProgress(fiber, pendingProps);\n clone.index = 0;\n clone.sibling = null;\n return clone;\n }\n\n function placeChild(newFiber, lastPlacedIndex, newIndex) {\n newFiber.index = newIndex;\n\n if (!shouldTrackSideEffects) {\n // Noop.\n return lastPlacedIndex;\n }\n\n var current = newFiber.alternate;\n\n if (current !== null) {\n var oldIndex = current.index;\n\n if (oldIndex < lastPlacedIndex) {\n // This is a move.\n newFiber.effectTag = Placement;\n return lastPlacedIndex;\n } else {\n // This item can stay in place.\n return oldIndex;\n }\n } else {\n // This is an insertion.\n newFiber.effectTag = Placement;\n return lastPlacedIndex;\n }\n }\n\n function placeSingleChild(newFiber) {\n // This is simpler for the single child case. We only need to do a\n // placement for inserting new children.\n if (shouldTrackSideEffects && newFiber.alternate === null) {\n newFiber.effectTag = Placement;\n }\n\n return newFiber;\n }\n\n function updateTextNode(returnFiber, current, textContent, expirationTime) {\n if (current === null || current.tag !== HostText) {\n // Insert\n var created = createFiberFromText(textContent, returnFiber.mode, expirationTime);\n created.return = returnFiber;\n return created;\n } else {\n // Update\n var existing = useFiber(current, textContent);\n existing.return = returnFiber;\n return existing;\n }\n }\n\n function updateElement(returnFiber, current, element, expirationTime) {\n if (current !== null) {\n if (current.elementType === element.type || ( // Keep this check inline so it only runs on the false path:\n isCompatibleFamilyForHotReloading(current, element) )) {\n // Move based on index\n var existing = useFiber(current, element.props);\n existing.ref = coerceRef(returnFiber, current, element);\n existing.return = returnFiber;\n\n {\n existing._debugSource = element._source;\n existing._debugOwner = element._owner;\n }\n\n return existing;\n }\n } // Insert\n\n\n var created = createFiberFromElement(element, returnFiber.mode, expirationTime);\n created.ref = coerceRef(returnFiber, current, element);\n created.return = returnFiber;\n return created;\n }\n\n function updatePortal(returnFiber, current, portal, expirationTime) {\n if (current === null || current.tag !== HostPortal || current.stateNode.containerInfo !== portal.containerInfo || current.stateNode.implementation !== portal.implementation) {\n // Insert\n var created = createFiberFromPortal(portal, returnFiber.mode, expirationTime);\n created.return = returnFiber;\n return created;\n } else {\n // Update\n var existing = useFiber(current, portal.children || []);\n existing.return = returnFiber;\n return existing;\n }\n }\n\n function updateFragment(returnFiber, current, fragment, expirationTime, key) {\n if (current === null || current.tag !== Fragment) {\n // Insert\n var created = createFiberFromFragment(fragment, returnFiber.mode, expirationTime, key);\n created.return = returnFiber;\n return created;\n } else {\n // Update\n var existing = useFiber(current, fragment);\n existing.return = returnFiber;\n return existing;\n }\n }\n\n function createChild(returnFiber, newChild, expirationTime) {\n if (typeof newChild === 'string' || typeof newChild === 'number') {\n // Text nodes don't have keys. If the previous node is implicitly keyed\n // we can continue to replace it without aborting even if it is not a text\n // node.\n var created = createFiberFromText('' + newChild, returnFiber.mode, expirationTime);\n created.return = returnFiber;\n return created;\n }\n\n if (typeof newChild === 'object' && newChild !== null) {\n switch (newChild.$$typeof) {\n case REACT_ELEMENT_TYPE:\n {\n var _created = createFiberFromElement(newChild, returnFiber.mode, expirationTime);\n\n _created.ref = coerceRef(returnFiber, null, newChild);\n _created.return = returnFiber;\n return _created;\n }\n\n case REACT_PORTAL_TYPE:\n {\n var _created2 = createFiberFromPortal(newChild, returnFiber.mode, expirationTime);\n\n _created2.return = returnFiber;\n return _created2;\n }\n }\n\n if (isArray$1(newChild) || getIteratorFn(newChild)) {\n var _created3 = createFiberFromFragment(newChild, returnFiber.mode, expirationTime, null);\n\n _created3.return = returnFiber;\n return _created3;\n }\n\n throwOnInvalidObjectType(returnFiber, newChild);\n }\n\n {\n if (typeof newChild === 'function') {\n warnOnFunctionType();\n }\n }\n\n return null;\n }\n\n function updateSlot(returnFiber, oldFiber, newChild, expirationTime) {\n // Update the fiber if the keys match, otherwise return null.\n var key = oldFiber !== null ? oldFiber.key : null;\n\n if (typeof newChild === 'string' || typeof newChild === 'number') {\n // Text nodes don't have keys. If the previous node is implicitly keyed\n // we can continue to replace it without aborting even if it is not a text\n // node.\n if (key !== null) {\n return null;\n }\n\n return updateTextNode(returnFiber, oldFiber, '' + newChild, expirationTime);\n }\n\n if (typeof newChild === 'object' && newChild !== null) {\n switch (newChild.$$typeof) {\n case REACT_ELEMENT_TYPE:\n {\n if (newChild.key === key) {\n if (newChild.type === REACT_FRAGMENT_TYPE) {\n return updateFragment(returnFiber, oldFiber, newChild.props.children, expirationTime, key);\n }\n\n return updateElement(returnFiber, oldFiber, newChild, expirationTime);\n } else {\n return null;\n }\n }\n\n case REACT_PORTAL_TYPE:\n {\n if (newChild.key === key) {\n return updatePortal(returnFiber, oldFiber, newChild, expirationTime);\n } else {\n return null;\n }\n }\n }\n\n if (isArray$1(newChild) || getIteratorFn(newChild)) {\n if (key !== null) {\n return null;\n }\n\n return updateFragment(returnFiber, oldFiber, newChild, expirationTime, null);\n }\n\n throwOnInvalidObjectType(returnFiber, newChild);\n }\n\n {\n if (typeof newChild === 'function') {\n warnOnFunctionType();\n }\n }\n\n return null;\n }\n\n function updateFromMap(existingChildren, returnFiber, newIdx, newChild, expirationTime) {\n if (typeof newChild === 'string' || typeof newChild === 'number') {\n // Text nodes don't have keys, so we neither have to check the old nor\n // new node for the key. If both are text nodes, they match.\n var matchedFiber = existingChildren.get(newIdx) || null;\n return updateTextNode(returnFiber, matchedFiber, '' + newChild, expirationTime);\n }\n\n if (typeof newChild === 'object' && newChild !== null) {\n switch (newChild.$$typeof) {\n case REACT_ELEMENT_TYPE:\n {\n var _matchedFiber = existingChildren.get(newChild.key === null ? newIdx : newChild.key) || null;\n\n if (newChild.type === REACT_FRAGMENT_TYPE) {\n return updateFragment(returnFiber, _matchedFiber, newChild.props.children, expirationTime, newChild.key);\n }\n\n return updateElement(returnFiber, _matchedFiber, newChild, expirationTime);\n }\n\n case REACT_PORTAL_TYPE:\n {\n var _matchedFiber2 = existingChildren.get(newChild.key === null ? newIdx : newChild.key) || null;\n\n return updatePortal(returnFiber, _matchedFiber2, newChild, expirationTime);\n }\n }\n\n if (isArray$1(newChild) || getIteratorFn(newChild)) {\n var _matchedFiber3 = existingChildren.get(newIdx) || null;\n\n return updateFragment(returnFiber, _matchedFiber3, newChild, expirationTime, null);\n }\n\n throwOnInvalidObjectType(returnFiber, newChild);\n }\n\n {\n if (typeof newChild === 'function') {\n warnOnFunctionType();\n }\n }\n\n return null;\n }\n /**\n * Warns if there is a duplicate or missing key\n */\n\n\n function warnOnInvalidKey(child, knownKeys) {\n {\n if (typeof child !== 'object' || child === null) {\n return knownKeys;\n }\n\n switch (child.$$typeof) {\n case REACT_ELEMENT_TYPE:\n case REACT_PORTAL_TYPE:\n warnForMissingKey(child);\n var key = child.key;\n\n if (typeof key !== 'string') {\n break;\n }\n\n if (knownKeys === null) {\n knownKeys = new Set();\n knownKeys.add(key);\n break;\n }\n\n if (!knownKeys.has(key)) {\n knownKeys.add(key);\n break;\n }\n\n error('Encountered two children with the same key, `%s`. ' + 'Keys should be unique so that components maintain their identity ' + 'across updates. Non-unique keys may cause children to be ' + 'duplicated and/or omitted — the behavior is unsupported and ' + 'could change in a future version.', key);\n\n break;\n }\n }\n\n return knownKeys;\n }\n\n function reconcileChildrenArray(returnFiber, currentFirstChild, newChildren, expirationTime) {\n // This algorithm can't optimize by searching from both ends since we\n // don't have backpointers on fibers. I'm trying to see how far we can get\n // with that model. If it ends up not being worth the tradeoffs, we can\n // add it later.\n // Even with a two ended optimization, we'd want to optimize for the case\n // where there are few changes and brute force the comparison instead of\n // going for the Map. It'd like to explore hitting that path first in\n // forward-only mode and only go for the Map once we notice that we need\n // lots of look ahead. This doesn't handle reversal as well as two ended\n // search but that's unusual. Besides, for the two ended optimization to\n // work on Iterables, we'd need to copy the whole set.\n // In this first iteration, we'll just live with hitting the bad case\n // (adding everything to a Map) in for every insert/move.\n // If you change this code, also update reconcileChildrenIterator() which\n // uses the same algorithm.\n {\n // First, validate keys.\n var knownKeys = null;\n\n for (var i = 0; i < newChildren.length; i++) {\n var child = newChildren[i];\n knownKeys = warnOnInvalidKey(child, knownKeys);\n }\n }\n\n var resultingFirstChild = null;\n var previousNewFiber = null;\n var oldFiber = currentFirstChild;\n var lastPlacedIndex = 0;\n var newIdx = 0;\n var nextOldFiber = null;\n\n for (; oldFiber !== null && newIdx < newChildren.length; newIdx++) {\n if (oldFiber.index > newIdx) {\n nextOldFiber = oldFiber;\n oldFiber = null;\n } else {\n nextOldFiber = oldFiber.sibling;\n }\n\n var newFiber = updateSlot(returnFiber, oldFiber, newChildren[newIdx], expirationTime);\n\n if (newFiber === null) {\n // TODO: This breaks on empty slots like null children. That's\n // unfortunate because it triggers the slow path all the time. We need\n // a better way to communicate whether this was a miss or null,\n // boolean, undefined, etc.\n if (oldFiber === null) {\n oldFiber = nextOldFiber;\n }\n\n break;\n }\n\n if (shouldTrackSideEffects) {\n if (oldFiber && newFiber.alternate === null) {\n // We matched the slot, but we didn't reuse the existing fiber, so we\n // need to delete the existing child.\n deleteChild(returnFiber, oldFiber);\n }\n }\n\n lastPlacedIndex = placeChild(newFiber, lastPlacedIndex, newIdx);\n\n if (previousNewFiber === null) {\n // TODO: Move out of the loop. This only happens for the first run.\n resultingFirstChild = newFiber;\n } else {\n // TODO: Defer siblings if we're not at the right index for this slot.\n // I.e. if we had null values before, then we want to defer this\n // for each null value. However, we also don't want to call updateSlot\n // with the previous one.\n previousNewFiber.sibling = newFiber;\n }\n\n previousNewFiber = newFiber;\n oldFiber = nextOldFiber;\n }\n\n if (newIdx === newChildren.length) {\n // We've reached the end of the new children. We can delete the rest.\n deleteRemainingChildren(returnFiber, oldFiber);\n return resultingFirstChild;\n }\n\n if (oldFiber === null) {\n // If we don't have any more existing children we can choose a fast path\n // since the rest will all be insertions.\n for (; newIdx < newChildren.length; newIdx++) {\n var _newFiber = createChild(returnFiber, newChildren[newIdx], expirationTime);\n\n if (_newFiber === null) {\n continue;\n }\n\n lastPlacedIndex = placeChild(_newFiber, lastPlacedIndex, newIdx);\n\n if (previousNewFiber === null) {\n // TODO: Move out of the loop. This only happens for the first run.\n resultingFirstChild = _newFiber;\n } else {\n previousNewFiber.sibling = _newFiber;\n }\n\n previousNewFiber = _newFiber;\n }\n\n return resultingFirstChild;\n } // Add all children to a key map for quick lookups.\n\n\n var existingChildren = mapRemainingChildren(returnFiber, oldFiber); // Keep scanning and use the map to restore deleted items as moves.\n\n for (; newIdx < newChildren.length; newIdx++) {\n var _newFiber2 = updateFromMap(existingChildren, returnFiber, newIdx, newChildren[newIdx], expirationTime);\n\n if (_newFiber2 !== null) {\n if (shouldTrackSideEffects) {\n if (_newFiber2.alternate !== null) {\n // The new fiber is a work in progress, but if there exists a\n // current, that means that we reused the fiber. We need to delete\n // it from the child list so that we don't add it to the deletion\n // list.\n existingChildren.delete(_newFiber2.key === null ? newIdx : _newFiber2.key);\n }\n }\n\n lastPlacedIndex = placeChild(_newFiber2, lastPlacedIndex, newIdx);\n\n if (previousNewFiber === null) {\n resultingFirstChild = _newFiber2;\n } else {\n previousNewFiber.sibling = _newFiber2;\n }\n\n previousNewFiber = _newFiber2;\n }\n }\n\n if (shouldTrackSideEffects) {\n // Any existing children that weren't consumed above were deleted. We need\n // to add them to the deletion list.\n existingChildren.forEach(function (child) {\n return deleteChild(returnFiber, child);\n });\n }\n\n return resultingFirstChild;\n }\n\n function reconcileChildrenIterator(returnFiber, currentFirstChild, newChildrenIterable, expirationTime) {\n // This is the same implementation as reconcileChildrenArray(),\n // but using the iterator instead.\n var iteratorFn = getIteratorFn(newChildrenIterable);\n\n if (!(typeof iteratorFn === 'function')) {\n {\n throw Error( \"An object is not an iterable. This error is likely caused by a bug in React. Please file an issue.\" );\n }\n }\n\n {\n // We don't support rendering Generators because it's a mutation.\n // See https://github.com/facebook/react/issues/12995\n if (typeof Symbol === 'function' && // $FlowFixMe Flow doesn't know about toStringTag\n newChildrenIterable[Symbol.toStringTag] === 'Generator') {\n if (!didWarnAboutGenerators) {\n error('Using Generators as children is unsupported and will likely yield ' + 'unexpected results because enumerating a generator mutates it. ' + 'You may convert it to an array with `Array.from()` or the ' + '`[...spread]` operator before rendering. Keep in mind ' + 'you might need to polyfill these features for older browsers.');\n }\n\n didWarnAboutGenerators = true;\n } // Warn about using Maps as children\n\n\n if (newChildrenIterable.entries === iteratorFn) {\n if (!didWarnAboutMaps) {\n error('Using Maps as children is unsupported and will likely yield ' + 'unexpected results. Convert it to a sequence/iterable of keyed ' + 'ReactElements instead.');\n }\n\n didWarnAboutMaps = true;\n } // First, validate keys.\n // We'll get a different iterator later for the main pass.\n\n\n var _newChildren = iteratorFn.call(newChildrenIterable);\n\n if (_newChildren) {\n var knownKeys = null;\n\n var _step = _newChildren.next();\n\n for (; !_step.done; _step = _newChildren.next()) {\n var child = _step.value;\n knownKeys = warnOnInvalidKey(child, knownKeys);\n }\n }\n }\n\n var newChildren = iteratorFn.call(newChildrenIterable);\n\n if (!(newChildren != null)) {\n {\n throw Error( \"An iterable object provided no iterator.\" );\n }\n }\n\n var resultingFirstChild = null;\n var previousNewFiber = null;\n var oldFiber = currentFirstChild;\n var lastPlacedIndex = 0;\n var newIdx = 0;\n var nextOldFiber = null;\n var step = newChildren.next();\n\n for (; oldFiber !== null && !step.done; newIdx++, step = newChildren.next()) {\n if (oldFiber.index > newIdx) {\n nextOldFiber = oldFiber;\n oldFiber = null;\n } else {\n nextOldFiber = oldFiber.sibling;\n }\n\n var newFiber = updateSlot(returnFiber, oldFiber, step.value, expirationTime);\n\n if (newFiber === null) {\n // TODO: This breaks on empty slots like null children. That's\n // unfortunate because it triggers the slow path all the time. We need\n // a better way to communicate whether this was a miss or null,\n // boolean, undefined, etc.\n if (oldFiber === null) {\n oldFiber = nextOldFiber;\n }\n\n break;\n }\n\n if (shouldTrackSideEffects) {\n if (oldFiber && newFiber.alternate === null) {\n // We matched the slot, but we didn't reuse the existing fiber, so we\n // need to delete the existing child.\n deleteChild(returnFiber, oldFiber);\n }\n }\n\n lastPlacedIndex = placeChild(newFiber, lastPlacedIndex, newIdx);\n\n if (previousNewFiber === null) {\n // TODO: Move out of the loop. This only happens for the first run.\n resultingFirstChild = newFiber;\n } else {\n // TODO: Defer siblings if we're not at the right index for this slot.\n // I.e. if we had null values before, then we want to defer this\n // for each null value. However, we also don't want to call updateSlot\n // with the previous one.\n previousNewFiber.sibling = newFiber;\n }\n\n previousNewFiber = newFiber;\n oldFiber = nextOldFiber;\n }\n\n if (step.done) {\n // We've reached the end of the new children. We can delete the rest.\n deleteRemainingChildren(returnFiber, oldFiber);\n return resultingFirstChild;\n }\n\n if (oldFiber === null) {\n // If we don't have any more existing children we can choose a fast path\n // since the rest will all be insertions.\n for (; !step.done; newIdx++, step = newChildren.next()) {\n var _newFiber3 = createChild(returnFiber, step.value, expirationTime);\n\n if (_newFiber3 === null) {\n continue;\n }\n\n lastPlacedIndex = placeChild(_newFiber3, lastPlacedIndex, newIdx);\n\n if (previousNewFiber === null) {\n // TODO: Move out of the loop. This only happens for the first run.\n resultingFirstChild = _newFiber3;\n } else {\n previousNewFiber.sibling = _newFiber3;\n }\n\n previousNewFiber = _newFiber3;\n }\n\n return resultingFirstChild;\n } // Add all children to a key map for quick lookups.\n\n\n var existingChildren = mapRemainingChildren(returnFiber, oldFiber); // Keep scanning and use the map to restore deleted items as moves.\n\n for (; !step.done; newIdx++, step = newChildren.next()) {\n var _newFiber4 = updateFromMap(existingChildren, returnFiber, newIdx, step.value, expirationTime);\n\n if (_newFiber4 !== null) {\n if (shouldTrackSideEffects) {\n if (_newFiber4.alternate !== null) {\n // The new fiber is a work in progress, but if there exists a\n // current, that means that we reused the fiber. We need to delete\n // it from the child list so that we don't add it to the deletion\n // list.\n existingChildren.delete(_newFiber4.key === null ? newIdx : _newFiber4.key);\n }\n }\n\n lastPlacedIndex = placeChild(_newFiber4, lastPlacedIndex, newIdx);\n\n if (previousNewFiber === null) {\n resultingFirstChild = _newFiber4;\n } else {\n previousNewFiber.sibling = _newFiber4;\n }\n\n previousNewFiber = _newFiber4;\n }\n }\n\n if (shouldTrackSideEffects) {\n // Any existing children that weren't consumed above were deleted. We need\n // to add them to the deletion list.\n existingChildren.forEach(function (child) {\n return deleteChild(returnFiber, child);\n });\n }\n\n return resultingFirstChild;\n }\n\n function reconcileSingleTextNode(returnFiber, currentFirstChild, textContent, expirationTime) {\n // There's no need to check for keys on text nodes since we don't have a\n // way to define them.\n if (currentFirstChild !== null && currentFirstChild.tag === HostText) {\n // We already have an existing node so let's just update it and delete\n // the rest.\n deleteRemainingChildren(returnFiber, currentFirstChild.sibling);\n var existing = useFiber(currentFirstChild, textContent);\n existing.return = returnFiber;\n return existing;\n } // The existing first child is not a text node so we need to create one\n // and delete the existing ones.\n\n\n deleteRemainingChildren(returnFiber, currentFirstChild);\n var created = createFiberFromText(textContent, returnFiber.mode, expirationTime);\n created.return = returnFiber;\n return created;\n }\n\n function reconcileSingleElement(returnFiber, currentFirstChild, element, expirationTime) {\n var key = element.key;\n var child = currentFirstChild;\n\n while (child !== null) {\n // TODO: If key === null and child.key === null, then this only applies to\n // the first item in the list.\n if (child.key === key) {\n switch (child.tag) {\n case Fragment:\n {\n if (element.type === REACT_FRAGMENT_TYPE) {\n deleteRemainingChildren(returnFiber, child.sibling);\n var existing = useFiber(child, element.props.children);\n existing.return = returnFiber;\n\n {\n existing._debugSource = element._source;\n existing._debugOwner = element._owner;\n }\n\n return existing;\n }\n\n break;\n }\n\n case Block:\n\n // We intentionally fallthrough here if enableBlocksAPI is not on.\n // eslint-disable-next-lined no-fallthrough\n\n default:\n {\n if (child.elementType === element.type || ( // Keep this check inline so it only runs on the false path:\n isCompatibleFamilyForHotReloading(child, element) )) {\n deleteRemainingChildren(returnFiber, child.sibling);\n\n var _existing3 = useFiber(child, element.props);\n\n _existing3.ref = coerceRef(returnFiber, child, element);\n _existing3.return = returnFiber;\n\n {\n _existing3._debugSource = element._source;\n _existing3._debugOwner = element._owner;\n }\n\n return _existing3;\n }\n\n break;\n }\n } // Didn't match.\n\n\n deleteRemainingChildren(returnFiber, child);\n break;\n } else {\n deleteChild(returnFiber, child);\n }\n\n child = child.sibling;\n }\n\n if (element.type === REACT_FRAGMENT_TYPE) {\n var created = createFiberFromFragment(element.props.children, returnFiber.mode, expirationTime, element.key);\n created.return = returnFiber;\n return created;\n } else {\n var _created4 = createFiberFromElement(element, returnFiber.mode, expirationTime);\n\n _created4.ref = coerceRef(returnFiber, currentFirstChild, element);\n _created4.return = returnFiber;\n return _created4;\n }\n }\n\n function reconcileSinglePortal(returnFiber, currentFirstChild, portal, expirationTime) {\n var key = portal.key;\n var child = currentFirstChild;\n\n while (child !== null) {\n // TODO: If key === null and child.key === null, then this only applies to\n // the first item in the list.\n if (child.key === key) {\n if (child.tag === HostPortal && child.stateNode.containerInfo === portal.containerInfo && child.stateNode.implementation === portal.implementation) {\n deleteRemainingChildren(returnFiber, child.sibling);\n var existing = useFiber(child, portal.children || []);\n existing.return = returnFiber;\n return existing;\n } else {\n deleteRemainingChildren(returnFiber, child);\n break;\n }\n } else {\n deleteChild(returnFiber, child);\n }\n\n child = child.sibling;\n }\n\n var created = createFiberFromPortal(portal, returnFiber.mode, expirationTime);\n created.return = returnFiber;\n return created;\n } // This API will tag the children with the side-effect of the reconciliation\n // itself. They will be added to the side-effect list as we pass through the\n // children and the parent.\n\n\n function reconcileChildFibers(returnFiber, currentFirstChild, newChild, expirationTime) {\n // This function is not recursive.\n // If the top level item is an array, we treat it as a set of children,\n // not as a fragment. Nested arrays on the other hand will be treated as\n // fragment nodes. Recursion happens at the normal flow.\n // Handle top level unkeyed fragments as if they were arrays.\n // This leads to an ambiguity between <>{[...]}</> and <>...</>.\n // We treat the ambiguous cases above the same.\n var isUnkeyedTopLevelFragment = typeof newChild === 'object' && newChild !== null && newChild.type === REACT_FRAGMENT_TYPE && newChild.key === null;\n\n if (isUnkeyedTopLevelFragment) {\n newChild = newChild.props.children;\n } // Handle object types\n\n\n var isObject = typeof newChild === 'object' && newChild !== null;\n\n if (isObject) {\n switch (newChild.$$typeof) {\n case REACT_ELEMENT_TYPE:\n return placeSingleChild(reconcileSingleElement(returnFiber, currentFirstChild, newChild, expirationTime));\n\n case REACT_PORTAL_TYPE:\n return placeSingleChild(reconcileSinglePortal(returnFiber, currentFirstChild, newChild, expirationTime));\n }\n }\n\n if (typeof newChild === 'string' || typeof newChild === 'number') {\n return placeSingleChild(reconcileSingleTextNode(returnFiber, currentFirstChild, '' + newChild, expirationTime));\n }\n\n if (isArray$1(newChild)) {\n return reconcileChildrenArray(returnFiber, currentFirstChild, newChild, expirationTime);\n }\n\n if (getIteratorFn(newChild)) {\n return reconcileChildrenIterator(returnFiber, currentFirstChild, newChild, expirationTime);\n }\n\n if (isObject) {\n throwOnInvalidObjectType(returnFiber, newChild);\n }\n\n {\n if (typeof newChild === 'function') {\n warnOnFunctionType();\n }\n }\n\n if (typeof newChild === 'undefined' && !isUnkeyedTopLevelFragment) {\n // If the new child is undefined, and the return fiber is a composite\n // component, throw an error. If Fiber return types are disabled,\n // we already threw above.\n switch (returnFiber.tag) {\n case ClassComponent:\n {\n {\n var instance = returnFiber.stateNode;\n\n if (instance.render._isMockFunction) {\n // We allow auto-mocks to proceed as if they're returning null.\n break;\n }\n }\n }\n // Intentionally fall through to the next case, which handles both\n // functions and classes\n // eslint-disable-next-lined no-fallthrough\n\n case FunctionComponent:\n {\n var Component = returnFiber.type;\n\n {\n {\n throw Error( (Component.displayName || Component.name || 'Component') + \"(...): Nothing was returned from render. This usually means a return statement is missing. Or, to render nothing, return null.\" );\n }\n }\n }\n }\n } // Remaining cases are all treated as empty.\n\n\n return deleteRemainingChildren(returnFiber, currentFirstChild);\n }\n\n return reconcileChildFibers;\n}\n\nvar reconcileChildFibers = ChildReconciler(true);\nvar mountChildFibers = ChildReconciler(false);\nfunction cloneChildFibers(current, workInProgress) {\n if (!(current === null || workInProgress.child === current.child)) {\n {\n throw Error( \"Resuming work not yet implemented.\" );\n }\n }\n\n if (workInProgress.child === null) {\n return;\n }\n\n var currentChild = workInProgress.child;\n var newChild = createWorkInProgress(currentChild, currentChild.pendingProps);\n workInProgress.child = newChild;\n newChild.return = workInProgress;\n\n while (currentChild.sibling !== null) {\n currentChild = currentChild.sibling;\n newChild = newChild.sibling = createWorkInProgress(currentChild, currentChild.pendingProps);\n newChild.return = workInProgress;\n }\n\n newChild.sibling = null;\n} // Reset a workInProgress child set to prepare it for a second pass.\n\nfunction resetChildFibers(workInProgress, renderExpirationTime) {\n var child = workInProgress.child;\n\n while (child !== null) {\n resetWorkInProgress(child, renderExpirationTime);\n child = child.sibling;\n }\n}\n\nvar NO_CONTEXT = {};\nvar contextStackCursor$1 = createCursor(NO_CONTEXT);\nvar contextFiberStackCursor = createCursor(NO_CONTEXT);\nvar rootInstanceStackCursor = createCursor(NO_CONTEXT);\n\nfunction requiredContext(c) {\n if (!(c !== NO_CONTEXT)) {\n {\n throw Error( \"Expected host context to exist. This error is likely caused by a bug in React. Please file an issue.\" );\n }\n }\n\n return c;\n}\n\nfunction getRootHostContainer() {\n var rootInstance = requiredContext(rootInstanceStackCursor.current);\n return rootInstance;\n}\n\nfunction pushHostContainer(fiber, nextRootInstance) {\n // Push current root instance onto the stack;\n // This allows us to reset root when portals are popped.\n push(rootInstanceStackCursor, nextRootInstance, fiber); // Track the context and the Fiber that provided it.\n // This enables us to pop only Fibers that provide unique contexts.\n\n push(contextFiberStackCursor, fiber, fiber); // Finally, we need to push the host context to the stack.\n // However, we can't just call getRootHostContext() and push it because\n // we'd have a different number of entries on the stack depending on\n // whether getRootHostContext() throws somewhere in renderer code or not.\n // So we push an empty value first. This lets us safely unwind on errors.\n\n push(contextStackCursor$1, NO_CONTEXT, fiber);\n var nextRootContext = getRootHostContext(nextRootInstance); // Now that we know this function doesn't throw, replace it.\n\n pop(contextStackCursor$1, fiber);\n push(contextStackCursor$1, nextRootContext, fiber);\n}\n\nfunction popHostContainer(fiber) {\n pop(contextStackCursor$1, fiber);\n pop(contextFiberStackCursor, fiber);\n pop(rootInstanceStackCursor, fiber);\n}\n\nfunction getHostContext() {\n var context = requiredContext(contextStackCursor$1.current);\n return context;\n}\n\nfunction pushHostContext(fiber) {\n var rootInstance = requiredContext(rootInstanceStackCursor.current);\n var context = requiredContext(contextStackCursor$1.current);\n var nextContext = getChildHostContext(context, fiber.type); // Don't push this Fiber's context unless it's unique.\n\n if (context === nextContext) {\n return;\n } // Track the context and the Fiber that provided it.\n // This enables us to pop only Fibers that provide unique contexts.\n\n\n push(contextFiberStackCursor, fiber, fiber);\n push(contextStackCursor$1, nextContext, fiber);\n}\n\nfunction popHostContext(fiber) {\n // Do not pop unless this Fiber provided the current context.\n // pushHostContext() only pushes Fibers that provide unique contexts.\n if (contextFiberStackCursor.current !== fiber) {\n return;\n }\n\n pop(contextStackCursor$1, fiber);\n pop(contextFiberStackCursor, fiber);\n}\n\nvar DefaultSuspenseContext = 0; // The Suspense Context is split into two parts. The lower bits is\n// inherited deeply down the subtree. The upper bits only affect\n// this immediate suspense boundary and gets reset each new\n// boundary or suspense list.\n\nvar SubtreeSuspenseContextMask = 1; // Subtree Flags:\n// InvisibleParentSuspenseContext indicates that one of our parent Suspense\n// boundaries is not currently showing visible main content.\n// Either because it is already showing a fallback or is not mounted at all.\n// We can use this to determine if it is desirable to trigger a fallback at\n// the parent. If not, then we might need to trigger undesirable boundaries\n// and/or suspend the commit to avoid hiding the parent content.\n\nvar InvisibleParentSuspenseContext = 1; // Shallow Flags:\n// ForceSuspenseFallback can be used by SuspenseList to force newly added\n// items into their fallback state during one of the render passes.\n\nvar ForceSuspenseFallback = 2;\nvar suspenseStackCursor = createCursor(DefaultSuspenseContext);\nfunction hasSuspenseContext(parentContext, flag) {\n return (parentContext & flag) !== 0;\n}\nfunction setDefaultShallowSuspenseContext(parentContext) {\n return parentContext & SubtreeSuspenseContextMask;\n}\nfunction setShallowSuspenseContext(parentContext, shallowContext) {\n return parentContext & SubtreeSuspenseContextMask | shallowContext;\n}\nfunction addSubtreeSuspenseContext(parentContext, subtreeContext) {\n return parentContext | subtreeContext;\n}\nfunction pushSuspenseContext(fiber, newContext) {\n push(suspenseStackCursor, newContext, fiber);\n}\nfunction popSuspenseContext(fiber) {\n pop(suspenseStackCursor, fiber);\n}\n\nfunction shouldCaptureSuspense(workInProgress, hasInvisibleParent) {\n // If it was the primary children that just suspended, capture and render the\n // fallback. Otherwise, don't capture and bubble to the next boundary.\n var nextState = workInProgress.memoizedState;\n\n if (nextState !== null) {\n if (nextState.dehydrated !== null) {\n // A dehydrated boundary always captures.\n return true;\n }\n\n return false;\n }\n\n var props = workInProgress.memoizedProps; // In order to capture, the Suspense component must have a fallback prop.\n\n if (props.fallback === undefined) {\n return false;\n } // Regular boundaries always capture.\n\n\n if (props.unstable_avoidThisFallback !== true) {\n return true;\n } // If it's a boundary we should avoid, then we prefer to bubble up to the\n // parent boundary if it is currently invisible.\n\n\n if (hasInvisibleParent) {\n return false;\n } // If the parent is not able to handle it, we must handle it.\n\n\n return true;\n}\nfunction findFirstSuspended(row) {\n var node = row;\n\n while (node !== null) {\n if (node.tag === SuspenseComponent) {\n var state = node.memoizedState;\n\n if (state !== null) {\n var dehydrated = state.dehydrated;\n\n if (dehydrated === null || isSuspenseInstancePending(dehydrated) || isSuspenseInstanceFallback(dehydrated)) {\n return node;\n }\n }\n } else if (node.tag === SuspenseListComponent && // revealOrder undefined can't be trusted because it don't\n // keep track of whether it suspended or not.\n node.memoizedProps.revealOrder !== undefined) {\n var didSuspend = (node.effectTag & DidCapture) !== NoEffect;\n\n if (didSuspend) {\n return node;\n }\n } else if (node.child !== null) {\n node.child.return = node;\n node = node.child;\n continue;\n }\n\n if (node === row) {\n return null;\n }\n\n while (node.sibling === null) {\n if (node.return === null || node.return === row) {\n return null;\n }\n\n node = node.return;\n }\n\n node.sibling.return = node.return;\n node = node.sibling;\n }\n\n return null;\n}\n\nfunction createDeprecatedResponderListener(responder, props) {\n var eventResponderListener = {\n responder: responder,\n props: props\n };\n\n {\n Object.freeze(eventResponderListener);\n }\n\n return eventResponderListener;\n}\n\nvar HasEffect =\n/* */\n1; // Represents the phase in which the effect (not the clean-up) fires.\n\nvar Layout =\n/* */\n2;\nvar Passive$1 =\n/* */\n4;\n\nvar ReactCurrentDispatcher = ReactSharedInternals.ReactCurrentDispatcher,\n ReactCurrentBatchConfig$1 = ReactSharedInternals.ReactCurrentBatchConfig;\nvar didWarnAboutMismatchedHooksForComponent;\n\n{\n didWarnAboutMismatchedHooksForComponent = new Set();\n}\n\n// These are set right before calling the component.\nvar renderExpirationTime = NoWork; // The work-in-progress fiber. I've named it differently to distinguish it from\n// the work-in-progress hook.\n\nvar currentlyRenderingFiber$1 = null; // Hooks are stored as a linked list on the fiber's memoizedState field. The\n// current hook list is the list that belongs to the current fiber. The\n// work-in-progress hook list is a new list that will be added to the\n// work-in-progress fiber.\n\nvar currentHook = null;\nvar workInProgressHook = null; // Whether an update was scheduled at any point during the render phase. This\n// does not get reset if we do another render pass; only when we're completely\n// finished evaluating this component. This is an optimization so we know\n// whether we need to clear render phase updates after a throw.\n\nvar didScheduleRenderPhaseUpdate = false;\nvar RE_RENDER_LIMIT = 25; // In DEV, this is the name of the currently executing primitive hook\n\nvar currentHookNameInDev = null; // In DEV, this list ensures that hooks are called in the same order between renders.\n// The list stores the order of hooks used during the initial render (mount).\n// Subsequent renders (updates) reference this list.\n\nvar hookTypesDev = null;\nvar hookTypesUpdateIndexDev = -1; // In DEV, this tracks whether currently rendering component needs to ignore\n// the dependencies for Hooks that need them (e.g. useEffect or useMemo).\n// When true, such Hooks will always be \"remounted\". Only used during hot reload.\n\nvar ignorePreviousDependencies = false;\n\nfunction mountHookTypesDev() {\n {\n var hookName = currentHookNameInDev;\n\n if (hookTypesDev === null) {\n hookTypesDev = [hookName];\n } else {\n hookTypesDev.push(hookName);\n }\n }\n}\n\nfunction updateHookTypesDev() {\n {\n var hookName = currentHookNameInDev;\n\n if (hookTypesDev !== null) {\n hookTypesUpdateIndexDev++;\n\n if (hookTypesDev[hookTypesUpdateIndexDev] !== hookName) {\n warnOnHookMismatchInDev(hookName);\n }\n }\n }\n}\n\nfunction checkDepsAreArrayDev(deps) {\n {\n if (deps !== undefined && deps !== null && !Array.isArray(deps)) {\n // Verify deps, but only on mount to avoid extra checks.\n // It's unlikely their type would change as usually you define them inline.\n error('%s received a final argument that is not an array (instead, received `%s`). When ' + 'specified, the final argument must be an array.', currentHookNameInDev, typeof deps);\n }\n }\n}\n\nfunction warnOnHookMismatchInDev(currentHookName) {\n {\n var componentName = getComponentName(currentlyRenderingFiber$1.type);\n\n if (!didWarnAboutMismatchedHooksForComponent.has(componentName)) {\n didWarnAboutMismatchedHooksForComponent.add(componentName);\n\n if (hookTypesDev !== null) {\n var table = '';\n var secondColumnStart = 30;\n\n for (var i = 0; i <= hookTypesUpdateIndexDev; i++) {\n var oldHookName = hookTypesDev[i];\n var newHookName = i === hookTypesUpdateIndexDev ? currentHookName : oldHookName;\n var row = i + 1 + \". \" + oldHookName; // Extra space so second column lines up\n // lol @ IE not supporting String#repeat\n\n while (row.length < secondColumnStart) {\n row += ' ';\n }\n\n row += newHookName + '\\n';\n table += row;\n }\n\n error('React has detected a change in the order of Hooks called by %s. ' + 'This will lead to bugs and errors if not fixed. ' + 'For more information, read the Rules of Hooks: https://fb.me/rules-of-hooks\\n\\n' + ' Previous render Next render\\n' + ' ------------------------------------------------------\\n' + '%s' + ' ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\\n', componentName, table);\n }\n }\n }\n}\n\nfunction throwInvalidHookError() {\n {\n {\n throw Error( \"Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:\\n1. You might have mismatching versions of React and the renderer (such as React DOM)\\n2. You might be breaking the Rules of Hooks\\n3. You might have more than one copy of React in the same app\\nSee https://fb.me/react-invalid-hook-call for tips about how to debug and fix this problem.\" );\n }\n }\n}\n\nfunction areHookInputsEqual(nextDeps, prevDeps) {\n {\n if (ignorePreviousDependencies) {\n // Only true when this component is being hot reloaded.\n return false;\n }\n }\n\n if (prevDeps === null) {\n {\n error('%s received a final argument during this render, but not during ' + 'the previous render. Even though the final argument is optional, ' + 'its type cannot change between renders.', currentHookNameInDev);\n }\n\n return false;\n }\n\n {\n // Don't bother comparing lengths in prod because these arrays should be\n // passed inline.\n if (nextDeps.length !== prevDeps.length) {\n error('The final argument passed to %s changed size between renders. The ' + 'order and size of this array must remain constant.\\n\\n' + 'Previous: %s\\n' + 'Incoming: %s', currentHookNameInDev, \"[\" + prevDeps.join(', ') + \"]\", \"[\" + nextDeps.join(', ') + \"]\");\n }\n }\n\n for (var i = 0; i < prevDeps.length && i < nextDeps.length; i++) {\n if (objectIs(nextDeps[i], prevDeps[i])) {\n continue;\n }\n\n return false;\n }\n\n return true;\n}\n\nfunction renderWithHooks(current, workInProgress, Component, props, secondArg, nextRenderExpirationTime) {\n renderExpirationTime = nextRenderExpirationTime;\n currentlyRenderingFiber$1 = workInProgress;\n\n {\n hookTypesDev = current !== null ? current._debugHookTypes : null;\n hookTypesUpdateIndexDev = -1; // Used for hot reloading:\n\n ignorePreviousDependencies = current !== null && current.type !== workInProgress.type;\n }\n\n workInProgress.memoizedState = null;\n workInProgress.updateQueue = null;\n workInProgress.expirationTime = NoWork; // The following should have already been reset\n // currentHook = null;\n // workInProgressHook = null;\n // didScheduleRenderPhaseUpdate = false;\n // TODO Warn if no hooks are used at all during mount, then some are used during update.\n // Currently we will identify the update render as a mount because memoizedState === null.\n // This is tricky because it's valid for certain types of components (e.g. React.lazy)\n // Using memoizedState to differentiate between mount/update only works if at least one stateful hook is used.\n // Non-stateful hooks (e.g. context) don't get added to memoizedState,\n // so memoizedState would be null during updates and mounts.\n\n {\n if (current !== null && current.memoizedState !== null) {\n ReactCurrentDispatcher.current = HooksDispatcherOnUpdateInDEV;\n } else if (hookTypesDev !== null) {\n // This dispatcher handles an edge case where a component is updating,\n // but no stateful hooks have been used.\n // We want to match the production code behavior (which will use HooksDispatcherOnMount),\n // but with the extra DEV validation to ensure hooks ordering hasn't changed.\n // This dispatcher does that.\n ReactCurrentDispatcher.current = HooksDispatcherOnMountWithHookTypesInDEV;\n } else {\n ReactCurrentDispatcher.current = HooksDispatcherOnMountInDEV;\n }\n }\n\n var children = Component(props, secondArg); // Check if there was a render phase update\n\n if (workInProgress.expirationTime === renderExpirationTime) {\n // Keep rendering in a loop for as long as render phase updates continue to\n // be scheduled. Use a counter to prevent infinite loops.\n var numberOfReRenders = 0;\n\n do {\n workInProgress.expirationTime = NoWork;\n\n if (!(numberOfReRenders < RE_RENDER_LIMIT)) {\n {\n throw Error( \"Too many re-renders. React limits the number of renders to prevent an infinite loop.\" );\n }\n }\n\n numberOfReRenders += 1;\n\n {\n // Even when hot reloading, allow dependencies to stabilize\n // after first render to prevent infinite render phase updates.\n ignorePreviousDependencies = false;\n } // Start over from the beginning of the list\n\n\n currentHook = null;\n workInProgressHook = null;\n workInProgress.updateQueue = null;\n\n {\n // Also validate hook order for cascading updates.\n hookTypesUpdateIndexDev = -1;\n }\n\n ReactCurrentDispatcher.current = HooksDispatcherOnRerenderInDEV ;\n children = Component(props, secondArg);\n } while (workInProgress.expirationTime === renderExpirationTime);\n } // We can assume the previous dispatcher is always this one, since we set it\n // at the beginning of the render phase and there's no re-entrancy.\n\n\n ReactCurrentDispatcher.current = ContextOnlyDispatcher;\n\n {\n workInProgress._debugHookTypes = hookTypesDev;\n } // This check uses currentHook so that it works the same in DEV and prod bundles.\n // hookTypesDev could catch more cases (e.g. context) but only in DEV bundles.\n\n\n var didRenderTooFewHooks = currentHook !== null && currentHook.next !== null;\n renderExpirationTime = NoWork;\n currentlyRenderingFiber$1 = null;\n currentHook = null;\n workInProgressHook = null;\n\n {\n currentHookNameInDev = null;\n hookTypesDev = null;\n hookTypesUpdateIndexDev = -1;\n }\n\n didScheduleRenderPhaseUpdate = false;\n\n if (!!didRenderTooFewHooks) {\n {\n throw Error( \"Rendered fewer hooks than expected. This may be caused by an accidental early return statement.\" );\n }\n }\n\n return children;\n}\nfunction bailoutHooks(current, workInProgress, expirationTime) {\n workInProgress.updateQueue = current.updateQueue;\n workInProgress.effectTag &= ~(Passive | Update);\n\n if (current.expirationTime <= expirationTime) {\n current.expirationTime = NoWork;\n }\n}\nfunction resetHooksAfterThrow() {\n // We can assume the previous dispatcher is always this one, since we set it\n // at the beginning of the render phase and there's no re-entrancy.\n ReactCurrentDispatcher.current = ContextOnlyDispatcher;\n\n if (didScheduleRenderPhaseUpdate) {\n // There were render phase updates. These are only valid for this render\n // phase, which we are now aborting. Remove the updates from the queues so\n // they do not persist to the next render. Do not remove updates from hooks\n // that weren't processed.\n //\n // Only reset the updates from the queue if it has a clone. If it does\n // not have a clone, that means it wasn't processed, and the updates were\n // scheduled before we entered the render phase.\n var hook = currentlyRenderingFiber$1.memoizedState;\n\n while (hook !== null) {\n var queue = hook.queue;\n\n if (queue !== null) {\n queue.pending = null;\n }\n\n hook = hook.next;\n }\n }\n\n renderExpirationTime = NoWork;\n currentlyRenderingFiber$1 = null;\n currentHook = null;\n workInProgressHook = null;\n\n {\n hookTypesDev = null;\n hookTypesUpdateIndexDev = -1;\n currentHookNameInDev = null;\n }\n\n didScheduleRenderPhaseUpdate = false;\n}\n\nfunction mountWorkInProgressHook() {\n var hook = {\n memoizedState: null,\n baseState: null,\n baseQueue: null,\n queue: null,\n next: null\n };\n\n if (workInProgressHook === null) {\n // This is the first hook in the list\n currentlyRenderingFiber$1.memoizedState = workInProgressHook = hook;\n } else {\n // Append to the end of the list\n workInProgressHook = workInProgressHook.next = hook;\n }\n\n return workInProgressHook;\n}\n\nfunction updateWorkInProgressHook() {\n // This function is used both for updates and for re-renders triggered by a\n // render phase update. It assumes there is either a current hook we can\n // clone, or a work-in-progress hook from a previous render pass that we can\n // use as a base. When we reach the end of the base list, we must switch to\n // the dispatcher used for mounts.\n var nextCurrentHook;\n\n if (currentHook === null) {\n var current = currentlyRenderingFiber$1.alternate;\n\n if (current !== null) {\n nextCurrentHook = current.memoizedState;\n } else {\n nextCurrentHook = null;\n }\n } else {\n nextCurrentHook = currentHook.next;\n }\n\n var nextWorkInProgressHook;\n\n if (workInProgressHook === null) {\n nextWorkInProgressHook = currentlyRenderingFiber$1.memoizedState;\n } else {\n nextWorkInProgressHook = workInProgressHook.next;\n }\n\n if (nextWorkInProgressHook !== null) {\n // There's already a work-in-progress. Reuse it.\n workInProgressHook = nextWorkInProgressHook;\n nextWorkInProgressHook = workInProgressHook.next;\n currentHook = nextCurrentHook;\n } else {\n // Clone from the current hook.\n if (!(nextCurrentHook !== null)) {\n {\n throw Error( \"Rendered more hooks than during the previous render.\" );\n }\n }\n\n currentHook = nextCurrentHook;\n var newHook = {\n memoizedState: currentHook.memoizedState,\n baseState: currentHook.baseState,\n baseQueue: currentHook.baseQueue,\n queue: currentHook.queue,\n next: null\n };\n\n if (workInProgressHook === null) {\n // This is the first hook in the list.\n currentlyRenderingFiber$1.memoizedState = workInProgressHook = newHook;\n } else {\n // Append to the end of the list.\n workInProgressHook = workInProgressHook.next = newHook;\n }\n }\n\n return workInProgressHook;\n}\n\nfunction createFunctionComponentUpdateQueue() {\n return {\n lastEffect: null\n };\n}\n\nfunction basicStateReducer(state, action) {\n // $FlowFixMe: Flow doesn't like mixed types\n return typeof action === 'function' ? action(state) : action;\n}\n\nfunction mountReducer(reducer, initialArg, init) {\n var hook = mountWorkInProgressHook();\n var initialState;\n\n if (init !== undefined) {\n initialState = init(initialArg);\n } else {\n initialState = initialArg;\n }\n\n hook.memoizedState = hook.baseState = initialState;\n var queue = hook.queue = {\n pending: null,\n dispatch: null,\n lastRenderedReducer: reducer,\n lastRenderedState: initialState\n };\n var dispatch = queue.dispatch = dispatchAction.bind(null, currentlyRenderingFiber$1, queue);\n return [hook.memoizedState, dispatch];\n}\n\nfunction updateReducer(reducer, initialArg, init) {\n var hook = updateWorkInProgressHook();\n var queue = hook.queue;\n\n if (!(queue !== null)) {\n {\n throw Error( \"Should have a queue. This is likely a bug in React. Please file an issue.\" );\n }\n }\n\n queue.lastRenderedReducer = reducer;\n var current = currentHook; // The last rebase update that is NOT part of the base state.\n\n var baseQueue = current.baseQueue; // The last pending update that hasn't been processed yet.\n\n var pendingQueue = queue.pending;\n\n if (pendingQueue !== null) {\n // We have new updates that haven't been processed yet.\n // We'll add them to the base queue.\n if (baseQueue !== null) {\n // Merge the pending queue and the base queue.\n var baseFirst = baseQueue.next;\n var pendingFirst = pendingQueue.next;\n baseQueue.next = pendingFirst;\n pendingQueue.next = baseFirst;\n }\n\n current.baseQueue = baseQueue = pendingQueue;\n queue.pending = null;\n }\n\n if (baseQueue !== null) {\n // We have a queue to process.\n var first = baseQueue.next;\n var newState = current.baseState;\n var newBaseState = null;\n var newBaseQueueFirst = null;\n var newBaseQueueLast = null;\n var update = first;\n\n do {\n var updateExpirationTime = update.expirationTime;\n\n if (updateExpirationTime < renderExpirationTime) {\n // Priority is insufficient. Skip this update. If this is the first\n // skipped update, the previous update/state is the new base\n // update/state.\n var clone = {\n expirationTime: update.expirationTime,\n suspenseConfig: update.suspenseConfig,\n action: update.action,\n eagerReducer: update.eagerReducer,\n eagerState: update.eagerState,\n next: null\n };\n\n if (newBaseQueueLast === null) {\n newBaseQueueFirst = newBaseQueueLast = clone;\n newBaseState = newState;\n } else {\n newBaseQueueLast = newBaseQueueLast.next = clone;\n } // Update the remaining priority in the queue.\n\n\n if (updateExpirationTime > currentlyRenderingFiber$1.expirationTime) {\n currentlyRenderingFiber$1.expirationTime = updateExpirationTime;\n markUnprocessedUpdateTime(updateExpirationTime);\n }\n } else {\n // This update does have sufficient priority.\n if (newBaseQueueLast !== null) {\n var _clone = {\n expirationTime: Sync,\n // This update is going to be committed so we never want uncommit it.\n suspenseConfig: update.suspenseConfig,\n action: update.action,\n eagerReducer: update.eagerReducer,\n eagerState: update.eagerState,\n next: null\n };\n newBaseQueueLast = newBaseQueueLast.next = _clone;\n } // Mark the event time of this update as relevant to this render pass.\n // TODO: This should ideally use the true event time of this update rather than\n // its priority which is a derived and not reverseable value.\n // TODO: We should skip this update if it was already committed but currently\n // we have no way of detecting the difference between a committed and suspended\n // update here.\n\n\n markRenderEventTimeAndConfig(updateExpirationTime, update.suspenseConfig); // Process this update.\n\n if (update.eagerReducer === reducer) {\n // If this update was processed eagerly, and its reducer matches the\n // current reducer, we can use the eagerly computed state.\n newState = update.eagerState;\n } else {\n var action = update.action;\n newState = reducer(newState, action);\n }\n }\n\n update = update.next;\n } while (update !== null && update !== first);\n\n if (newBaseQueueLast === null) {\n newBaseState = newState;\n } else {\n newBaseQueueLast.next = newBaseQueueFirst;\n } // Mark that the fiber performed work, but only if the new state is\n // different from the current state.\n\n\n if (!objectIs(newState, hook.memoizedState)) {\n markWorkInProgressReceivedUpdate();\n }\n\n hook.memoizedState = newState;\n hook.baseState = newBaseState;\n hook.baseQueue = newBaseQueueLast;\n queue.lastRenderedState = newState;\n }\n\n var dispatch = queue.dispatch;\n return [hook.memoizedState, dispatch];\n}\n\nfunction rerenderReducer(reducer, initialArg, init) {\n var hook = updateWorkInProgressHook();\n var queue = hook.queue;\n\n if (!(queue !== null)) {\n {\n throw Error( \"Should have a queue. This is likely a bug in React. Please file an issue.\" );\n }\n }\n\n queue.lastRenderedReducer = reducer; // This is a re-render. Apply the new render phase updates to the previous\n // work-in-progress hook.\n\n var dispatch = queue.dispatch;\n var lastRenderPhaseUpdate = queue.pending;\n var newState = hook.memoizedState;\n\n if (lastRenderPhaseUpdate !== null) {\n // The queue doesn't persist past this render pass.\n queue.pending = null;\n var firstRenderPhaseUpdate = lastRenderPhaseUpdate.next;\n var update = firstRenderPhaseUpdate;\n\n do {\n // Process this render phase update. We don't have to check the\n // priority because it will always be the same as the current\n // render's.\n var action = update.action;\n newState = reducer(newState, action);\n update = update.next;\n } while (update !== firstRenderPhaseUpdate); // Mark that the fiber performed work, but only if the new state is\n // different from the current state.\n\n\n if (!objectIs(newState, hook.memoizedState)) {\n markWorkInProgressReceivedUpdate();\n }\n\n hook.memoizedState = newState; // Don't persist the state accumulated from the render phase updates to\n // the base state unless the queue is empty.\n // TODO: Not sure if this is the desired semantics, but it's what we\n // do for gDSFP. I can't remember why.\n\n if (hook.baseQueue === null) {\n hook.baseState = newState;\n }\n\n queue.lastRenderedState = newState;\n }\n\n return [newState, dispatch];\n}\n\nfunction mountState(initialState) {\n var hook = mountWorkInProgressHook();\n\n if (typeof initialState === 'function') {\n // $FlowFixMe: Flow doesn't like mixed types\n initialState = initialState();\n }\n\n hook.memoizedState = hook.baseState = initialState;\n var queue = hook.queue = {\n pending: null,\n dispatch: null,\n lastRenderedReducer: basicStateReducer,\n lastRenderedState: initialState\n };\n var dispatch = queue.dispatch = dispatchAction.bind(null, currentlyRenderingFiber$1, queue);\n return [hook.memoizedState, dispatch];\n}\n\nfunction updateState(initialState) {\n return updateReducer(basicStateReducer);\n}\n\nfunction rerenderState(initialState) {\n return rerenderReducer(basicStateReducer);\n}\n\nfunction pushEffect(tag, create, destroy, deps) {\n var effect = {\n tag: tag,\n create: create,\n destroy: destroy,\n deps: deps,\n // Circular\n next: null\n };\n var componentUpdateQueue = currentlyRenderingFiber$1.updateQueue;\n\n if (componentUpdateQueue === null) {\n componentUpdateQueue = createFunctionComponentUpdateQueue();\n currentlyRenderingFiber$1.updateQueue = componentUpdateQueue;\n componentUpdateQueue.lastEffect = effect.next = effect;\n } else {\n var lastEffect = componentUpdateQueue.lastEffect;\n\n if (lastEffect === null) {\n componentUpdateQueue.lastEffect = effect.next = effect;\n } else {\n var firstEffect = lastEffect.next;\n lastEffect.next = effect;\n effect.next = firstEffect;\n componentUpdateQueue.lastEffect = effect;\n }\n }\n\n return effect;\n}\n\nfunction mountRef(initialValue) {\n var hook = mountWorkInProgressHook();\n var ref = {\n current: initialValue\n };\n\n {\n Object.seal(ref);\n }\n\n hook.memoizedState = ref;\n return ref;\n}\n\nfunction updateRef(initialValue) {\n var hook = updateWorkInProgressHook();\n return hook.memoizedState;\n}\n\nfunction mountEffectImpl(fiberEffectTag, hookEffectTag, create, deps) {\n var hook = mountWorkInProgressHook();\n var nextDeps = deps === undefined ? null : deps;\n currentlyRenderingFiber$1.effectTag |= fiberEffectTag;\n hook.memoizedState = pushEffect(HasEffect | hookEffectTag, create, undefined, nextDeps);\n}\n\nfunction updateEffectImpl(fiberEffectTag, hookEffectTag, create, deps) {\n var hook = updateWorkInProgressHook();\n var nextDeps = deps === undefined ? null : deps;\n var destroy = undefined;\n\n if (currentHook !== null) {\n var prevEffect = currentHook.memoizedState;\n destroy = prevEffect.destroy;\n\n if (nextDeps !== null) {\n var prevDeps = prevEffect.deps;\n\n if (areHookInputsEqual(nextDeps, prevDeps)) {\n pushEffect(hookEffectTag, create, destroy, nextDeps);\n return;\n }\n }\n }\n\n currentlyRenderingFiber$1.effectTag |= fiberEffectTag;\n hook.memoizedState = pushEffect(HasEffect | hookEffectTag, create, destroy, nextDeps);\n}\n\nfunction mountEffect(create, deps) {\n {\n // $FlowExpectedError - jest isn't a global, and isn't recognized outside of tests\n if ('undefined' !== typeof jest) {\n warnIfNotCurrentlyActingEffectsInDEV(currentlyRenderingFiber$1);\n }\n }\n\n return mountEffectImpl(Update | Passive, Passive$1, create, deps);\n}\n\nfunction updateEffect(create, deps) {\n {\n // $FlowExpectedError - jest isn't a global, and isn't recognized outside of tests\n if ('undefined' !== typeof jest) {\n warnIfNotCurrentlyActingEffectsInDEV(currentlyRenderingFiber$1);\n }\n }\n\n return updateEffectImpl(Update | Passive, Passive$1, create, deps);\n}\n\nfunction mountLayoutEffect(create, deps) {\n return mountEffectImpl(Update, Layout, create, deps);\n}\n\nfunction updateLayoutEffect(create, deps) {\n return updateEffectImpl(Update, Layout, create, deps);\n}\n\nfunction imperativeHandleEffect(create, ref) {\n if (typeof ref === 'function') {\n var refCallback = ref;\n\n var _inst = create();\n\n refCallback(_inst);\n return function () {\n refCallback(null);\n };\n } else if (ref !== null && ref !== undefined) {\n var refObject = ref;\n\n {\n if (!refObject.hasOwnProperty('current')) {\n error('Expected useImperativeHandle() first argument to either be a ' + 'ref callback or React.createRef() object. Instead received: %s.', 'an object with keys {' + Object.keys(refObject).join(', ') + '}');\n }\n }\n\n var _inst2 = create();\n\n refObject.current = _inst2;\n return function () {\n refObject.current = null;\n };\n }\n}\n\nfunction mountImperativeHandle(ref, create, deps) {\n {\n if (typeof create !== 'function') {\n error('Expected useImperativeHandle() second argument to be a function ' + 'that creates a handle. Instead received: %s.', create !== null ? typeof create : 'null');\n }\n } // TODO: If deps are provided, should we skip comparing the ref itself?\n\n\n var effectDeps = deps !== null && deps !== undefined ? deps.concat([ref]) : null;\n return mountEffectImpl(Update, Layout, imperativeHandleEffect.bind(null, create, ref), effectDeps);\n}\n\nfunction updateImperativeHandle(ref, create, deps) {\n {\n if (typeof create !== 'function') {\n error('Expected useImperativeHandle() second argument to be a function ' + 'that creates a handle. Instead received: %s.', create !== null ? typeof create : 'null');\n }\n } // TODO: If deps are provided, should we skip comparing the ref itself?\n\n\n var effectDeps = deps !== null && deps !== undefined ? deps.concat([ref]) : null;\n return updateEffectImpl(Update, Layout, imperativeHandleEffect.bind(null, create, ref), effectDeps);\n}\n\nfunction mountDebugValue(value, formatterFn) {// This hook is normally a no-op.\n // The react-debug-hooks package injects its own implementation\n // so that e.g. DevTools can display custom hook values.\n}\n\nvar updateDebugValue = mountDebugValue;\n\nfunction mountCallback(callback, deps) {\n var hook = mountWorkInProgressHook();\n var nextDeps = deps === undefined ? null : deps;\n hook.memoizedState = [callback, nextDeps];\n return callback;\n}\n\nfunction updateCallback(callback, deps) {\n var hook = updateWorkInProgressHook();\n var nextDeps = deps === undefined ? null : deps;\n var prevState = hook.memoizedState;\n\n if (prevState !== null) {\n if (nextDeps !== null) {\n var prevDeps = prevState[1];\n\n if (areHookInputsEqual(nextDeps, prevDeps)) {\n return prevState[0];\n }\n }\n }\n\n hook.memoizedState = [callback, nextDeps];\n return callback;\n}\n\nfunction mountMemo(nextCreate, deps) {\n var hook = mountWorkInProgressHook();\n var nextDeps = deps === undefined ? null : deps;\n var nextValue = nextCreate();\n hook.memoizedState = [nextValue, nextDeps];\n return nextValue;\n}\n\nfunction updateMemo(nextCreate, deps) {\n var hook = updateWorkInProgressHook();\n var nextDeps = deps === undefined ? null : deps;\n var prevState = hook.memoizedState;\n\n if (prevState !== null) {\n // Assume these are defined. If they're not, areHookInputsEqual will warn.\n if (nextDeps !== null) {\n var prevDeps = prevState[1];\n\n if (areHookInputsEqual(nextDeps, prevDeps)) {\n return prevState[0];\n }\n }\n }\n\n var nextValue = nextCreate();\n hook.memoizedState = [nextValue, nextDeps];\n return nextValue;\n}\n\nfunction mountDeferredValue(value, config) {\n var _mountState = mountState(value),\n prevValue = _mountState[0],\n setValue = _mountState[1];\n\n mountEffect(function () {\n var previousConfig = ReactCurrentBatchConfig$1.suspense;\n ReactCurrentBatchConfig$1.suspense = config === undefined ? null : config;\n\n try {\n setValue(value);\n } finally {\n ReactCurrentBatchConfig$1.suspense = previousConfig;\n }\n }, [value, config]);\n return prevValue;\n}\n\nfunction updateDeferredValue(value, config) {\n var _updateState = updateState(),\n prevValue = _updateState[0],\n setValue = _updateState[1];\n\n updateEffect(function () {\n var previousConfig = ReactCurrentBatchConfig$1.suspense;\n ReactCurrentBatchConfig$1.suspense = config === undefined ? null : config;\n\n try {\n setValue(value);\n } finally {\n ReactCurrentBatchConfig$1.suspense = previousConfig;\n }\n }, [value, config]);\n return prevValue;\n}\n\nfunction rerenderDeferredValue(value, config) {\n var _rerenderState = rerenderState(),\n prevValue = _rerenderState[0],\n setValue = _rerenderState[1];\n\n updateEffect(function () {\n var previousConfig = ReactCurrentBatchConfig$1.suspense;\n ReactCurrentBatchConfig$1.suspense = config === undefined ? null : config;\n\n try {\n setValue(value);\n } finally {\n ReactCurrentBatchConfig$1.suspense = previousConfig;\n }\n }, [value, config]);\n return prevValue;\n}\n\nfunction startTransition(setPending, config, callback) {\n var priorityLevel = getCurrentPriorityLevel();\n runWithPriority$1(priorityLevel < UserBlockingPriority$1 ? UserBlockingPriority$1 : priorityLevel, function () {\n setPending(true);\n });\n runWithPriority$1(priorityLevel > NormalPriority ? NormalPriority : priorityLevel, function () {\n var previousConfig = ReactCurrentBatchConfig$1.suspense;\n ReactCurrentBatchConfig$1.suspense = config === undefined ? null : config;\n\n try {\n setPending(false);\n callback();\n } finally {\n ReactCurrentBatchConfig$1.suspense = previousConfig;\n }\n });\n}\n\nfunction mountTransition(config) {\n var _mountState2 = mountState(false),\n isPending = _mountState2[0],\n setPending = _mountState2[1];\n\n var start = mountCallback(startTransition.bind(null, setPending, config), [setPending, config]);\n return [start, isPending];\n}\n\nfunction updateTransition(config) {\n var _updateState2 = updateState(),\n isPending = _updateState2[0],\n setPending = _updateState2[1];\n\n var start = updateCallback(startTransition.bind(null, setPending, config), [setPending, config]);\n return [start, isPending];\n}\n\nfunction rerenderTransition(config) {\n var _rerenderState2 = rerenderState(),\n isPending = _rerenderState2[0],\n setPending = _rerenderState2[1];\n\n var start = updateCallback(startTransition.bind(null, setPending, config), [setPending, config]);\n return [start, isPending];\n}\n\nfunction dispatchAction(fiber, queue, action) {\n {\n if (typeof arguments[3] === 'function') {\n error(\"State updates from the useState() and useReducer() Hooks don't support the \" + 'second callback argument. To execute a side effect after ' + 'rendering, declare it in the component body with useEffect().');\n }\n }\n\n var currentTime = requestCurrentTimeForUpdate();\n var suspenseConfig = requestCurrentSuspenseConfig();\n var expirationTime = computeExpirationForFiber(currentTime, fiber, suspenseConfig);\n var update = {\n expirationTime: expirationTime,\n suspenseConfig: suspenseConfig,\n action: action,\n eagerReducer: null,\n eagerState: null,\n next: null\n };\n\n {\n update.priority = getCurrentPriorityLevel();\n } // Append the update to the end of the list.\n\n\n var pending = queue.pending;\n\n if (pending === null) {\n // This is the first update. Create a circular list.\n update.next = update;\n } else {\n update.next = pending.next;\n pending.next = update;\n }\n\n queue.pending = update;\n var alternate = fiber.alternate;\n\n if (fiber === currentlyRenderingFiber$1 || alternate !== null && alternate === currentlyRenderingFiber$1) {\n // This is a render phase update. Stash it in a lazily-created map of\n // queue -> linked list of updates. After this render pass, we'll restart\n // and apply the stashed updates on top of the work-in-progress hook.\n didScheduleRenderPhaseUpdate = true;\n update.expirationTime = renderExpirationTime;\n currentlyRenderingFiber$1.expirationTime = renderExpirationTime;\n } else {\n if (fiber.expirationTime === NoWork && (alternate === null || alternate.expirationTime === NoWork)) {\n // The queue is currently empty, which means we can eagerly compute the\n // next state before entering the render phase. If the new state is the\n // same as the current state, we may be able to bail out entirely.\n var lastRenderedReducer = queue.lastRenderedReducer;\n\n if (lastRenderedReducer !== null) {\n var prevDispatcher;\n\n {\n prevDispatcher = ReactCurrentDispatcher.current;\n ReactCurrentDispatcher.current = InvalidNestedHooksDispatcherOnUpdateInDEV;\n }\n\n try {\n var currentState = queue.lastRenderedState;\n var eagerState = lastRenderedReducer(currentState, action); // Stash the eagerly computed state, and the reducer used to compute\n // it, on the update object. If the reducer hasn't changed by the\n // time we enter the render phase, then the eager state can be used\n // without calling the reducer again.\n\n update.eagerReducer = lastRenderedReducer;\n update.eagerState = eagerState;\n\n if (objectIs(eagerState, currentState)) {\n // Fast path. We can bail out without scheduling React to re-render.\n // It's still possible that we'll need to rebase this update later,\n // if the component re-renders for a different reason and by that\n // time the reducer has changed.\n return;\n }\n } catch (error) {// Suppress the error. It will throw again in the render phase.\n } finally {\n {\n ReactCurrentDispatcher.current = prevDispatcher;\n }\n }\n }\n }\n\n {\n // $FlowExpectedError - jest isn't a global, and isn't recognized outside of tests\n if ('undefined' !== typeof jest) {\n warnIfNotScopedWithMatchingAct(fiber);\n warnIfNotCurrentlyActingUpdatesInDev(fiber);\n }\n }\n\n scheduleWork(fiber, expirationTime);\n }\n}\n\nvar ContextOnlyDispatcher = {\n readContext: readContext,\n useCallback: throwInvalidHookError,\n useContext: throwInvalidHookError,\n useEffect: throwInvalidHookError,\n useImperativeHandle: throwInvalidHookError,\n useLayoutEffect: throwInvalidHookError,\n useMemo: throwInvalidHookError,\n useReducer: throwInvalidHookError,\n useRef: throwInvalidHookError,\n useState: throwInvalidHookError,\n useDebugValue: throwInvalidHookError,\n useResponder: throwInvalidHookError,\n useDeferredValue: throwInvalidHookError,\n useTransition: throwInvalidHookError\n};\nvar HooksDispatcherOnMountInDEV = null;\nvar HooksDispatcherOnMountWithHookTypesInDEV = null;\nvar HooksDispatcherOnUpdateInDEV = null;\nvar HooksDispatcherOnRerenderInDEV = null;\nvar InvalidNestedHooksDispatcherOnMountInDEV = null;\nvar InvalidNestedHooksDispatcherOnUpdateInDEV = null;\nvar InvalidNestedHooksDispatcherOnRerenderInDEV = null;\n\n{\n var warnInvalidContextAccess = function () {\n error('Context can only be read while React is rendering. ' + 'In classes, you can read it in the render method or getDerivedStateFromProps. ' + 'In function components, you can read it directly in the function body, but not ' + 'inside Hooks like useReducer() or useMemo().');\n };\n\n var warnInvalidHookAccess = function () {\n error('Do not call Hooks inside useEffect(...), useMemo(...), or other built-in Hooks. ' + 'You can only call Hooks at the top level of your React function. ' + 'For more information, see ' + 'https://fb.me/rules-of-hooks');\n };\n\n HooksDispatcherOnMountInDEV = {\n readContext: function (context, observedBits) {\n return readContext(context, observedBits);\n },\n useCallback: function (callback, deps) {\n currentHookNameInDev = 'useCallback';\n mountHookTypesDev();\n checkDepsAreArrayDev(deps);\n return mountCallback(callback, deps);\n },\n useContext: function (context, observedBits) {\n currentHookNameInDev = 'useContext';\n mountHookTypesDev();\n return readContext(context, observedBits);\n },\n useEffect: function (create, deps) {\n currentHookNameInDev = 'useEffect';\n mountHookTypesDev();\n checkDepsAreArrayDev(deps);\n return mountEffect(create, deps);\n },\n useImperativeHandle: function (ref, create, deps) {\n currentHookNameInDev = 'useImperativeHandle';\n mountHookTypesDev();\n checkDepsAreArrayDev(deps);\n return mountImperativeHandle(ref, create, deps);\n },\n useLayoutEffect: function (create, deps) {\n currentHookNameInDev = 'useLayoutEffect';\n mountHookTypesDev();\n checkDepsAreArrayDev(deps);\n return mountLayoutEffect(create, deps);\n },\n useMemo: function (create, deps) {\n currentHookNameInDev = 'useMemo';\n mountHookTypesDev();\n checkDepsAreArrayDev(deps);\n var prevDispatcher = ReactCurrentDispatcher.current;\n ReactCurrentDispatcher.current = InvalidNestedHooksDispatcherOnMountInDEV;\n\n try {\n return mountMemo(create, deps);\n } finally {\n ReactCurrentDispatcher.current = prevDispatcher;\n }\n },\n useReducer: function (reducer, initialArg, init) {\n currentHookNameInDev = 'useReducer';\n mountHookTypesDev();\n var prevDispatcher = ReactCurrentDispatcher.current;\n ReactCurrentDispatcher.current = InvalidNestedHooksDispatcherOnMountInDEV;\n\n try {\n return mountReducer(reducer, initialArg, init);\n } finally {\n ReactCurrentDispatcher.current = prevDispatcher;\n }\n },\n useRef: function (initialValue) {\n currentHookNameInDev = 'useRef';\n mountHookTypesDev();\n return mountRef(initialValue);\n },\n useState: function (initialState) {\n currentHookNameInDev = 'useState';\n mountHookTypesDev();\n var prevDispatcher = ReactCurrentDispatcher.current;\n ReactCurrentDispatcher.current = InvalidNestedHooksDispatcherOnMountInDEV;\n\n try {\n return mountState(initialState);\n } finally {\n ReactCurrentDispatcher.current = prevDispatcher;\n }\n },\n useDebugValue: function (value, formatterFn) {\n currentHookNameInDev = 'useDebugValue';\n mountHookTypesDev();\n return mountDebugValue();\n },\n useResponder: function (responder, props) {\n currentHookNameInDev = 'useResponder';\n mountHookTypesDev();\n return createDeprecatedResponderListener(responder, props);\n },\n useDeferredValue: function (value, config) {\n currentHookNameInDev = 'useDeferredValue';\n mountHookTypesDev();\n return mountDeferredValue(value, config);\n },\n useTransition: function (config) {\n currentHookNameInDev = 'useTransition';\n mountHookTypesDev();\n return mountTransition(config);\n }\n };\n HooksDispatcherOnMountWithHookTypesInDEV = {\n readContext: function (context, observedBits) {\n return readContext(context, observedBits);\n },\n useCallback: function (callback, deps) {\n currentHookNameInDev = 'useCallback';\n updateHookTypesDev();\n return mountCallback(callback, deps);\n },\n useContext: function (context, observedBits) {\n currentHookNameInDev = 'useContext';\n updateHookTypesDev();\n return readContext(context, observedBits);\n },\n useEffect: function (create, deps) {\n currentHookNameInDev = 'useEffect';\n updateHookTypesDev();\n return mountEffect(create, deps);\n },\n useImperativeHandle: function (ref, create, deps) {\n currentHookNameInDev = 'useImperativeHandle';\n updateHookTypesDev();\n return mountImperativeHandle(ref, create, deps);\n },\n useLayoutEffect: function (create, deps) {\n currentHookNameInDev = 'useLayoutEffect';\n updateHookTypesDev();\n return mountLayoutEffect(create, deps);\n },\n useMemo: function (create, deps) {\n currentHookNameInDev = 'useMemo';\n updateHookTypesDev();\n var prevDispatcher = ReactCurrentDispatcher.current;\n ReactCurrentDispatcher.current = InvalidNestedHooksDispatcherOnMountInDEV;\n\n try {\n return mountMemo(create, deps);\n } finally {\n ReactCurrentDispatcher.current = prevDispatcher;\n }\n },\n useReducer: function (reducer, initialArg, init) {\n currentHookNameInDev = 'useReducer';\n updateHookTypesDev();\n var prevDispatcher = ReactCurrentDispatcher.current;\n ReactCurrentDispatcher.current = InvalidNestedHooksDispatcherOnMountInDEV;\n\n try {\n return mountReducer(reducer, initialArg, init);\n } finally {\n ReactCurrentDispatcher.current = prevDispatcher;\n }\n },\n useRef: function (initialValue) {\n currentHookNameInDev = 'useRef';\n updateHookTypesDev();\n return mountRef(initialValue);\n },\n useState: function (initialState) {\n currentHookNameInDev = 'useState';\n updateHookTypesDev();\n var prevDispatcher = ReactCurrentDispatcher.current;\n ReactCurrentDispatcher.current = InvalidNestedHooksDispatcherOnMountInDEV;\n\n try {\n return mountState(initialState);\n } finally {\n ReactCurrentDispatcher.current = prevDispatcher;\n }\n },\n useDebugValue: function (value, formatterFn) {\n currentHookNameInDev = 'useDebugValue';\n updateHookTypesDev();\n return mountDebugValue();\n },\n useResponder: function (responder, props) {\n currentHookNameInDev = 'useResponder';\n updateHookTypesDev();\n return createDeprecatedResponderListener(responder, props);\n },\n useDeferredValue: function (value, config) {\n currentHookNameInDev = 'useDeferredValue';\n updateHookTypesDev();\n return mountDeferredValue(value, config);\n },\n useTransition: function (config) {\n currentHookNameInDev = 'useTransition';\n updateHookTypesDev();\n return mountTransition(config);\n }\n };\n HooksDispatcherOnUpdateInDEV = {\n readContext: function (context, observedBits) {\n return readContext(context, observedBits);\n },\n useCallback: function (callback, deps) {\n currentHookNameInDev = 'useCallback';\n updateHookTypesDev();\n return updateCallback(callback, deps);\n },\n useContext: function (context, observedBits) {\n currentHookNameInDev = 'useContext';\n updateHookTypesDev();\n return readContext(context, observedBits);\n },\n useEffect: function (create, deps) {\n currentHookNameInDev = 'useEffect';\n updateHookTypesDev();\n return updateEffect(create, deps);\n },\n useImperativeHandle: function (ref, create, deps) {\n currentHookNameInDev = 'useImperativeHandle';\n updateHookTypesDev();\n return updateImperativeHandle(ref, create, deps);\n },\n useLayoutEffect: function (create, deps) {\n currentHookNameInDev = 'useLayoutEffect';\n updateHookTypesDev();\n return updateLayoutEffect(create, deps);\n },\n useMemo: function (create, deps) {\n currentHookNameInDev = 'useMemo';\n updateHookTypesDev();\n var prevDispatcher = ReactCurrentDispatcher.current;\n ReactCurrentDispatcher.current = InvalidNestedHooksDispatcherOnUpdateInDEV;\n\n try {\n return updateMemo(create, deps);\n } finally {\n ReactCurrentDispatcher.current = prevDispatcher;\n }\n },\n useReducer: function (reducer, initialArg, init) {\n currentHookNameInDev = 'useReducer';\n updateHookTypesDev();\n var prevDispatcher = ReactCurrentDispatcher.current;\n ReactCurrentDispatcher.current = InvalidNestedHooksDispatcherOnUpdateInDEV;\n\n try {\n return updateReducer(reducer, initialArg, init);\n } finally {\n ReactCurrentDispatcher.current = prevDispatcher;\n }\n },\n useRef: function (initialValue) {\n currentHookNameInDev = 'useRef';\n updateHookTypesDev();\n return updateRef();\n },\n useState: function (initialState) {\n currentHookNameInDev = 'useState';\n updateHookTypesDev();\n var prevDispatcher = ReactCurrentDispatcher.current;\n ReactCurrentDispatcher.current = InvalidNestedHooksDispatcherOnUpdateInDEV;\n\n try {\n return updateState(initialState);\n } finally {\n ReactCurrentDispatcher.current = prevDispatcher;\n }\n },\n useDebugValue: function (value, formatterFn) {\n currentHookNameInDev = 'useDebugValue';\n updateHookTypesDev();\n return updateDebugValue();\n },\n useResponder: function (responder, props) {\n currentHookNameInDev = 'useResponder';\n updateHookTypesDev();\n return createDeprecatedResponderListener(responder, props);\n },\n useDeferredValue: function (value, config) {\n currentHookNameInDev = 'useDeferredValue';\n updateHookTypesDev();\n return updateDeferredValue(value, config);\n },\n useTransition: function (config) {\n currentHookNameInDev = 'useTransition';\n updateHookTypesDev();\n return updateTransition(config);\n }\n };\n HooksDispatcherOnRerenderInDEV = {\n readContext: function (context, observedBits) {\n return readContext(context, observedBits);\n },\n useCallback: function (callback, deps) {\n currentHookNameInDev = 'useCallback';\n updateHookTypesDev();\n return updateCallback(callback, deps);\n },\n useContext: function (context, observedBits) {\n currentHookNameInDev = 'useContext';\n updateHookTypesDev();\n return readContext(context, observedBits);\n },\n useEffect: function (create, deps) {\n currentHookNameInDev = 'useEffect';\n updateHookTypesDev();\n return updateEffect(create, deps);\n },\n useImperativeHandle: function (ref, create, deps) {\n currentHookNameInDev = 'useImperativeHandle';\n updateHookTypesDev();\n return updateImperativeHandle(ref, create, deps);\n },\n useLayoutEffect: function (create, deps) {\n currentHookNameInDev = 'useLayoutEffect';\n updateHookTypesDev();\n return updateLayoutEffect(create, deps);\n },\n useMemo: function (create, deps) {\n currentHookNameInDev = 'useMemo';\n updateHookTypesDev();\n var prevDispatcher = ReactCurrentDispatcher.current;\n ReactCurrentDispatcher.current = InvalidNestedHooksDispatcherOnRerenderInDEV;\n\n try {\n return updateMemo(create, deps);\n } finally {\n ReactCurrentDispatcher.current = prevDispatcher;\n }\n },\n useReducer: function (reducer, initialArg, init) {\n currentHookNameInDev = 'useReducer';\n updateHookTypesDev();\n var prevDispatcher = ReactCurrentDispatcher.current;\n ReactCurrentDispatcher.current = InvalidNestedHooksDispatcherOnRerenderInDEV;\n\n try {\n return rerenderReducer(reducer, initialArg, init);\n } finally {\n ReactCurrentDispatcher.current = prevDispatcher;\n }\n },\n useRef: function (initialValue) {\n currentHookNameInDev = 'useRef';\n updateHookTypesDev();\n return updateRef();\n },\n useState: function (initialState) {\n currentHookNameInDev = 'useState';\n updateHookTypesDev();\n var prevDispatcher = ReactCurrentDispatcher.current;\n ReactCurrentDispatcher.current = InvalidNestedHooksDispatcherOnRerenderInDEV;\n\n try {\n return rerenderState(initialState);\n } finally {\n ReactCurrentDispatcher.current = prevDispatcher;\n }\n },\n useDebugValue: function (value, formatterFn) {\n currentHookNameInDev = 'useDebugValue';\n updateHookTypesDev();\n return updateDebugValue();\n },\n useResponder: function (responder, props) {\n currentHookNameInDev = 'useResponder';\n updateHookTypesDev();\n return createDeprecatedResponderListener(responder, props);\n },\n useDeferredValue: function (value, config) {\n currentHookNameInDev = 'useDeferredValue';\n updateHookTypesDev();\n return rerenderDeferredValue(value, config);\n },\n useTransition: function (config) {\n currentHookNameInDev = 'useTransition';\n updateHookTypesDev();\n return rerenderTransition(config);\n }\n };\n InvalidNestedHooksDispatcherOnMountInDEV = {\n readContext: function (context, observedBits) {\n warnInvalidContextAccess();\n return readContext(context, observedBits);\n },\n useCallback: function (callback, deps) {\n currentHookNameInDev = 'useCallback';\n warnInvalidHookAccess();\n mountHookTypesDev();\n return mountCallback(callback, deps);\n },\n useContext: function (context, observedBits) {\n currentHookNameInDev = 'useContext';\n warnInvalidHookAccess();\n mountHookTypesDev();\n return readContext(context, observedBits);\n },\n useEffect: function (create, deps) {\n currentHookNameInDev = 'useEffect';\n warnInvalidHookAccess();\n mountHookTypesDev();\n return mountEffect(create, deps);\n },\n useImperativeHandle: function (ref, create, deps) {\n currentHookNameInDev = 'useImperativeHandle';\n warnInvalidHookAccess();\n mountHookTypesDev();\n return mountImperativeHandle(ref, create, deps);\n },\n useLayoutEffect: function (create, deps) {\n currentHookNameInDev = 'useLayoutEffect';\n warnInvalidHookAccess();\n mountHookTypesDev();\n return mountLayoutEffect(create, deps);\n },\n useMemo: function (create, deps) {\n currentHookNameInDev = 'useMemo';\n warnInvalidHookAccess();\n mountHookTypesDev();\n var prevDispatcher = ReactCurrentDispatcher.current;\n ReactCurrentDispatcher.current = InvalidNestedHooksDispatcherOnMountInDEV;\n\n try {\n return mountMemo(create, deps);\n } finally {\n ReactCurrentDispatcher.current = prevDispatcher;\n }\n },\n useReducer: function (reducer, initialArg, init) {\n currentHookNameInDev = 'useReducer';\n warnInvalidHookAccess();\n mountHookTypesDev();\n var prevDispatcher = ReactCurrentDispatcher.current;\n ReactCurrentDispatcher.current = InvalidNestedHooksDispatcherOnMountInDEV;\n\n try {\n return mountReducer(reducer, initialArg, init);\n } finally {\n ReactCurrentDispatcher.current = prevDispatcher;\n }\n },\n useRef: function (initialValue) {\n currentHookNameInDev = 'useRef';\n warnInvalidHookAccess();\n mountHookTypesDev();\n return mountRef(initialValue);\n },\n useState: function (initialState) {\n currentHookNameInDev = 'useState';\n warnInvalidHookAccess();\n mountHookTypesDev();\n var prevDispatcher = ReactCurrentDispatcher.current;\n ReactCurrentDispatcher.current = InvalidNestedHooksDispatcherOnMountInDEV;\n\n try {\n return mountState(initialState);\n } finally {\n ReactCurrentDispatcher.current = prevDispatcher;\n }\n },\n useDebugValue: function (value, formatterFn) {\n currentHookNameInDev = 'useDebugValue';\n warnInvalidHookAccess();\n mountHookTypesDev();\n return mountDebugValue();\n },\n useResponder: function (responder, props) {\n currentHookNameInDev = 'useResponder';\n warnInvalidHookAccess();\n mountHookTypesDev();\n return createDeprecatedResponderListener(responder, props);\n },\n useDeferredValue: function (value, config) {\n currentHookNameInDev = 'useDeferredValue';\n warnInvalidHookAccess();\n mountHookTypesDev();\n return mountDeferredValue(value, config);\n },\n useTransition: function (config) {\n currentHookNameInDev = 'useTransition';\n warnInvalidHookAccess();\n mountHookTypesDev();\n return mountTransition(config);\n }\n };\n InvalidNestedHooksDispatcherOnUpdateInDEV = {\n readContext: function (context, observedBits) {\n warnInvalidContextAccess();\n return readContext(context, observedBits);\n },\n useCallback: function (callback, deps) {\n currentHookNameInDev = 'useCallback';\n warnInvalidHookAccess();\n updateHookTypesDev();\n return updateCallback(callback, deps);\n },\n useContext: function (context, observedBits) {\n currentHookNameInDev = 'useContext';\n warnInvalidHookAccess();\n updateHookTypesDev();\n return readContext(context, observedBits);\n },\n useEffect: function (create, deps) {\n currentHookNameInDev = 'useEffect';\n warnInvalidHookAccess();\n updateHookTypesDev();\n return updateEffect(create, deps);\n },\n useImperativeHandle: function (ref, create, deps) {\n currentHookNameInDev = 'useImperativeHandle';\n warnInvalidHookAccess();\n updateHookTypesDev();\n return updateImperativeHandle(ref, create, deps);\n },\n useLayoutEffect: function (create, deps) {\n currentHookNameInDev = 'useLayoutEffect';\n warnInvalidHookAccess();\n updateHookTypesDev();\n return updateLayoutEffect(create, deps);\n },\n useMemo: function (create, deps) {\n currentHookNameInDev = 'useMemo';\n warnInvalidHookAccess();\n updateHookTypesDev();\n var prevDispatcher = ReactCurrentDispatcher.current;\n ReactCurrentDispatcher.current = InvalidNestedHooksDispatcherOnUpdateInDEV;\n\n try {\n return updateMemo(create, deps);\n } finally {\n ReactCurrentDispatcher.current = prevDispatcher;\n }\n },\n useReducer: function (reducer, initialArg, init) {\n currentHookNameInDev = 'useReducer';\n warnInvalidHookAccess();\n updateHookTypesDev();\n var prevDispatcher = ReactCurrentDispatcher.current;\n ReactCurrentDispatcher.current = InvalidNestedHooksDispatcherOnUpdateInDEV;\n\n try {\n return updateReducer(reducer, initialArg, init);\n } finally {\n ReactCurrentDispatcher.current = prevDispatcher;\n }\n },\n useRef: function (initialValue) {\n currentHookNameInDev = 'useRef';\n warnInvalidHookAccess();\n updateHookTypesDev();\n return updateRef();\n },\n useState: function (initialState) {\n currentHookNameInDev = 'useState';\n warnInvalidHookAccess();\n updateHookTypesDev();\n var prevDispatcher = ReactCurrentDispatcher.current;\n ReactCurrentDispatcher.current = InvalidNestedHooksDispatcherOnUpdateInDEV;\n\n try {\n return updateState(initialState);\n } finally {\n ReactCurrentDispatcher.current = prevDispatcher;\n }\n },\n useDebugValue: function (value, formatterFn) {\n currentHookNameInDev = 'useDebugValue';\n warnInvalidHookAccess();\n updateHookTypesDev();\n return updateDebugValue();\n },\n useResponder: function (responder, props) {\n currentHookNameInDev = 'useResponder';\n warnInvalidHookAccess();\n updateHookTypesDev();\n return createDeprecatedResponderListener(responder, props);\n },\n useDeferredValue: function (value, config) {\n currentHookNameInDev = 'useDeferredValue';\n warnInvalidHookAccess();\n updateHookTypesDev();\n return updateDeferredValue(value, config);\n },\n useTransition: function (config) {\n currentHookNameInDev = 'useTransition';\n warnInvalidHookAccess();\n updateHookTypesDev();\n return updateTransition(config);\n }\n };\n InvalidNestedHooksDispatcherOnRerenderInDEV = {\n readContext: function (context, observedBits) {\n warnInvalidContextAccess();\n return readContext(context, observedBits);\n },\n useCallback: function (callback, deps) {\n currentHookNameInDev = 'useCallback';\n warnInvalidHookAccess();\n updateHookTypesDev();\n return updateCallback(callback, deps);\n },\n useContext: function (context, observedBits) {\n currentHookNameInDev = 'useContext';\n warnInvalidHookAccess();\n updateHookTypesDev();\n return readContext(context, observedBits);\n },\n useEffect: function (create, deps) {\n currentHookNameInDev = 'useEffect';\n warnInvalidHookAccess();\n updateHookTypesDev();\n return updateEffect(create, deps);\n },\n useImperativeHandle: function (ref, create, deps) {\n currentHookNameInDev = 'useImperativeHandle';\n warnInvalidHookAccess();\n updateHookTypesDev();\n return updateImperativeHandle(ref, create, deps);\n },\n useLayoutEffect: function (create, deps) {\n currentHookNameInDev = 'useLayoutEffect';\n warnInvalidHookAccess();\n updateHookTypesDev();\n return updateLayoutEffect(create, deps);\n },\n useMemo: function (create, deps) {\n currentHookNameInDev = 'useMemo';\n warnInvalidHookAccess();\n updateHookTypesDev();\n var prevDispatcher = ReactCurrentDispatcher.current;\n ReactCurrentDispatcher.current = InvalidNestedHooksDispatcherOnUpdateInDEV;\n\n try {\n return updateMemo(create, deps);\n } finally {\n ReactCurrentDispatcher.current = prevDispatcher;\n }\n },\n useReducer: function (reducer, initialArg, init) {\n currentHookNameInDev = 'useReducer';\n warnInvalidHookAccess();\n updateHookTypesDev();\n var prevDispatcher = ReactCurrentDispatcher.current;\n ReactCurrentDispatcher.current = InvalidNestedHooksDispatcherOnUpdateInDEV;\n\n try {\n return rerenderReducer(reducer, initialArg, init);\n } finally {\n ReactCurrentDispatcher.current = prevDispatcher;\n }\n },\n useRef: function (initialValue) {\n currentHookNameInDev = 'useRef';\n warnInvalidHookAccess();\n updateHookTypesDev();\n return updateRef();\n },\n useState: function (initialState) {\n currentHookNameInDev = 'useState';\n warnInvalidHookAccess();\n updateHookTypesDev();\n var prevDispatcher = ReactCurrentDispatcher.current;\n ReactCurrentDispatcher.current = InvalidNestedHooksDispatcherOnUpdateInDEV;\n\n try {\n return rerenderState(initialState);\n } finally {\n ReactCurrentDispatcher.current = prevDispatcher;\n }\n },\n useDebugValue: function (value, formatterFn) {\n currentHookNameInDev = 'useDebugValue';\n warnInvalidHookAccess();\n updateHookTypesDev();\n return updateDebugValue();\n },\n useResponder: function (responder, props) {\n currentHookNameInDev = 'useResponder';\n warnInvalidHookAccess();\n updateHookTypesDev();\n return createDeprecatedResponderListener(responder, props);\n },\n useDeferredValue: function (value, config) {\n currentHookNameInDev = 'useDeferredValue';\n warnInvalidHookAccess();\n updateHookTypesDev();\n return rerenderDeferredValue(value, config);\n },\n useTransition: function (config) {\n currentHookNameInDev = 'useTransition';\n warnInvalidHookAccess();\n updateHookTypesDev();\n return rerenderTransition(config);\n }\n };\n}\n\nvar now$1 = Scheduler.unstable_now;\nvar commitTime = 0;\nvar profilerStartTime = -1;\n\nfunction getCommitTime() {\n return commitTime;\n}\n\nfunction recordCommitTime() {\n\n commitTime = now$1();\n}\n\nfunction startProfilerTimer(fiber) {\n\n profilerStartTime = now$1();\n\n if (fiber.actualStartTime < 0) {\n fiber.actualStartTime = now$1();\n }\n}\n\nfunction stopProfilerTimerIfRunning(fiber) {\n\n profilerStartTime = -1;\n}\n\nfunction stopProfilerTimerIfRunningAndRecordDelta(fiber, overrideBaseTime) {\n\n if (profilerStartTime >= 0) {\n var elapsedTime = now$1() - profilerStartTime;\n fiber.actualDuration += elapsedTime;\n\n if (overrideBaseTime) {\n fiber.selfBaseDuration = elapsedTime;\n }\n\n profilerStartTime = -1;\n }\n}\n\n// This may have been an insertion or a hydration.\n\nvar hydrationParentFiber = null;\nvar nextHydratableInstance = null;\nvar isHydrating = false;\n\nfunction enterHydrationState(fiber) {\n\n var parentInstance = fiber.stateNode.containerInfo;\n nextHydratableInstance = getFirstHydratableChild(parentInstance);\n hydrationParentFiber = fiber;\n isHydrating = true;\n return true;\n}\n\nfunction deleteHydratableInstance(returnFiber, instance) {\n {\n switch (returnFiber.tag) {\n case HostRoot:\n didNotHydrateContainerInstance(returnFiber.stateNode.containerInfo, instance);\n break;\n\n case HostComponent:\n didNotHydrateInstance(returnFiber.type, returnFiber.memoizedProps, returnFiber.stateNode, instance);\n break;\n }\n }\n\n var childToDelete = createFiberFromHostInstanceForDeletion();\n childToDelete.stateNode = instance;\n childToDelete.return = returnFiber;\n childToDelete.effectTag = Deletion; // This might seem like it belongs on progressedFirstDeletion. However,\n // these children are not part of the reconciliation list of children.\n // Even if we abort and rereconcile the children, that will try to hydrate\n // again and the nodes are still in the host tree so these will be\n // recreated.\n\n if (returnFiber.lastEffect !== null) {\n returnFiber.lastEffect.nextEffect = childToDelete;\n returnFiber.lastEffect = childToDelete;\n } else {\n returnFiber.firstEffect = returnFiber.lastEffect = childToDelete;\n }\n}\n\nfunction insertNonHydratedInstance(returnFiber, fiber) {\n fiber.effectTag = fiber.effectTag & ~Hydrating | Placement;\n\n {\n switch (returnFiber.tag) {\n case HostRoot:\n {\n var parentContainer = returnFiber.stateNode.containerInfo;\n\n switch (fiber.tag) {\n case HostComponent:\n var type = fiber.type;\n var props = fiber.pendingProps;\n didNotFindHydratableContainerInstance(parentContainer, type);\n break;\n\n case HostText:\n var text = fiber.pendingProps;\n didNotFindHydratableContainerTextInstance(parentContainer, text);\n break;\n }\n\n break;\n }\n\n case HostComponent:\n {\n var parentType = returnFiber.type;\n var parentProps = returnFiber.memoizedProps;\n var parentInstance = returnFiber.stateNode;\n\n switch (fiber.tag) {\n case HostComponent:\n var _type = fiber.type;\n var _props = fiber.pendingProps;\n didNotFindHydratableInstance(parentType, parentProps, parentInstance, _type);\n break;\n\n case HostText:\n var _text = fiber.pendingProps;\n didNotFindHydratableTextInstance(parentType, parentProps, parentInstance, _text);\n break;\n\n case SuspenseComponent:\n didNotFindHydratableSuspenseInstance(parentType, parentProps);\n break;\n }\n\n break;\n }\n\n default:\n return;\n }\n }\n}\n\nfunction tryHydrate(fiber, nextInstance) {\n switch (fiber.tag) {\n case HostComponent:\n {\n var type = fiber.type;\n var props = fiber.pendingProps;\n var instance = canHydrateInstance(nextInstance, type);\n\n if (instance !== null) {\n fiber.stateNode = instance;\n return true;\n }\n\n return false;\n }\n\n case HostText:\n {\n var text = fiber.pendingProps;\n var textInstance = canHydrateTextInstance(nextInstance, text);\n\n if (textInstance !== null) {\n fiber.stateNode = textInstance;\n return true;\n }\n\n return false;\n }\n\n case SuspenseComponent:\n {\n\n return false;\n }\n\n default:\n return false;\n }\n}\n\nfunction tryToClaimNextHydratableInstance(fiber) {\n if (!isHydrating) {\n return;\n }\n\n var nextInstance = nextHydratableInstance;\n\n if (!nextInstance) {\n // Nothing to hydrate. Make it an insertion.\n insertNonHydratedInstance(hydrationParentFiber, fiber);\n isHydrating = false;\n hydrationParentFiber = fiber;\n return;\n }\n\n var firstAttemptedInstance = nextInstance;\n\n if (!tryHydrate(fiber, nextInstance)) {\n // If we can't hydrate this instance let's try the next one.\n // We use this as a heuristic. It's based on intuition and not data so it\n // might be flawed or unnecessary.\n nextInstance = getNextHydratableSibling(firstAttemptedInstance);\n\n if (!nextInstance || !tryHydrate(fiber, nextInstance)) {\n // Nothing to hydrate. Make it an insertion.\n insertNonHydratedInstance(hydrationParentFiber, fiber);\n isHydrating = false;\n hydrationParentFiber = fiber;\n return;\n } // We matched the next one, we'll now assume that the first one was\n // superfluous and we'll delete it. Since we can't eagerly delete it\n // we'll have to schedule a deletion. To do that, this node needs a dummy\n // fiber associated with it.\n\n\n deleteHydratableInstance(hydrationParentFiber, firstAttemptedInstance);\n }\n\n hydrationParentFiber = fiber;\n nextHydratableInstance = getFirstHydratableChild(nextInstance);\n}\n\nfunction prepareToHydrateHostInstance(fiber, rootContainerInstance, hostContext) {\n\n var instance = fiber.stateNode;\n var updatePayload = hydrateInstance(instance, fiber.type, fiber.memoizedProps, rootContainerInstance, hostContext, fiber); // TODO: Type this specific to this type of component.\n\n fiber.updateQueue = updatePayload; // If the update payload indicates that there is a change or if there\n // is a new ref we mark this as an update.\n\n if (updatePayload !== null) {\n return true;\n }\n\n return false;\n}\n\nfunction prepareToHydrateHostTextInstance(fiber) {\n\n var textInstance = fiber.stateNode;\n var textContent = fiber.memoizedProps;\n var shouldUpdate = hydrateTextInstance(textInstance, textContent, fiber);\n\n {\n if (shouldUpdate) {\n // We assume that prepareToHydrateHostTextInstance is called in a context where the\n // hydration parent is the parent host component of this host text.\n var returnFiber = hydrationParentFiber;\n\n if (returnFiber !== null) {\n switch (returnFiber.tag) {\n case HostRoot:\n {\n var parentContainer = returnFiber.stateNode.containerInfo;\n didNotMatchHydratedContainerTextInstance(parentContainer, textInstance, textContent);\n break;\n }\n\n case HostComponent:\n {\n var parentType = returnFiber.type;\n var parentProps = returnFiber.memoizedProps;\n var parentInstance = returnFiber.stateNode;\n didNotMatchHydratedTextInstance(parentType, parentProps, parentInstance, textInstance, textContent);\n break;\n }\n }\n }\n }\n }\n\n return shouldUpdate;\n}\n\nfunction skipPastDehydratedSuspenseInstance(fiber) {\n\n var suspenseState = fiber.memoizedState;\n var suspenseInstance = suspenseState !== null ? suspenseState.dehydrated : null;\n\n if (!suspenseInstance) {\n {\n throw Error( \"Expected to have a hydrated suspense instance. This error is likely caused by a bug in React. Please file an issue.\" );\n }\n }\n\n return getNextHydratableInstanceAfterSuspenseInstance(suspenseInstance);\n}\n\nfunction popToNextHostParent(fiber) {\n var parent = fiber.return;\n\n while (parent !== null && parent.tag !== HostComponent && parent.tag !== HostRoot && parent.tag !== SuspenseComponent) {\n parent = parent.return;\n }\n\n hydrationParentFiber = parent;\n}\n\nfunction popHydrationState(fiber) {\n\n if (fiber !== hydrationParentFiber) {\n // We're deeper than the current hydration context, inside an inserted\n // tree.\n return false;\n }\n\n if (!isHydrating) {\n // If we're not currently hydrating but we're in a hydration context, then\n // we were an insertion and now need to pop up reenter hydration of our\n // siblings.\n popToNextHostParent(fiber);\n isHydrating = true;\n return false;\n }\n\n var type = fiber.type; // If we have any remaining hydratable nodes, we need to delete them now.\n // We only do this deeper than head and body since they tend to have random\n // other nodes in them. We also ignore components with pure text content in\n // side of them.\n // TODO: Better heuristic.\n\n if (fiber.tag !== HostComponent || type !== 'head' && type !== 'body' && !shouldSetTextContent(type, fiber.memoizedProps)) {\n var nextInstance = nextHydratableInstance;\n\n while (nextInstance) {\n deleteHydratableInstance(fiber, nextInstance);\n nextInstance = getNextHydratableSibling(nextInstance);\n }\n }\n\n popToNextHostParent(fiber);\n\n if (fiber.tag === SuspenseComponent) {\n nextHydratableInstance = skipPastDehydratedSuspenseInstance(fiber);\n } else {\n nextHydratableInstance = hydrationParentFiber ? getNextHydratableSibling(fiber.stateNode) : null;\n }\n\n return true;\n}\n\nfunction resetHydrationState() {\n\n hydrationParentFiber = null;\n nextHydratableInstance = null;\n isHydrating = false;\n}\n\nvar ReactCurrentOwner$1 = ReactSharedInternals.ReactCurrentOwner;\nvar didReceiveUpdate = false;\nvar didWarnAboutBadClass;\nvar didWarnAboutModulePatternComponent;\nvar didWarnAboutContextTypeOnFunctionComponent;\nvar didWarnAboutGetDerivedStateOnFunctionComponent;\nvar didWarnAboutFunctionRefs;\nvar didWarnAboutReassigningProps;\nvar didWarnAboutRevealOrder;\nvar didWarnAboutTailOptions;\n\n{\n didWarnAboutBadClass = {};\n didWarnAboutModulePatternComponent = {};\n didWarnAboutContextTypeOnFunctionComponent = {};\n didWarnAboutGetDerivedStateOnFunctionComponent = {};\n didWarnAboutFunctionRefs = {};\n didWarnAboutReassigningProps = false;\n didWarnAboutRevealOrder = {};\n didWarnAboutTailOptions = {};\n}\n\nfunction reconcileChildren(current, workInProgress, nextChildren, renderExpirationTime) {\n if (current === null) {\n // If this is a fresh new component that hasn't been rendered yet, we\n // won't update its child set by applying minimal side-effects. Instead,\n // we will add them all to the child before it gets rendered. That means\n // we can optimize this reconciliation pass by not tracking side-effects.\n workInProgress.child = mountChildFibers(workInProgress, null, nextChildren, renderExpirationTime);\n } else {\n // If the current child is the same as the work in progress, it means that\n // we haven't yet started any work on these children. Therefore, we use\n // the clone algorithm to create a copy of all the current children.\n // If we had any progressed work already, that is invalid at this point so\n // let's throw it out.\n workInProgress.child = reconcileChildFibers(workInProgress, current.child, nextChildren, renderExpirationTime);\n }\n}\n\nfunction forceUnmountCurrentAndReconcile(current, workInProgress, nextChildren, renderExpirationTime) {\n // This function is fork of reconcileChildren. It's used in cases where we\n // want to reconcile without matching against the existing set. This has the\n // effect of all current children being unmounted; even if the type and key\n // are the same, the old child is unmounted and a new child is created.\n //\n // To do this, we're going to go through the reconcile algorithm twice. In\n // the first pass, we schedule a deletion for all the current children by\n // passing null.\n workInProgress.child = reconcileChildFibers(workInProgress, current.child, null, renderExpirationTime); // In the second pass, we mount the new children. The trick here is that we\n // pass null in place of where we usually pass the current child set. This has\n // the effect of remounting all children regardless of whether their\n // identities match.\n\n workInProgress.child = reconcileChildFibers(workInProgress, null, nextChildren, renderExpirationTime);\n}\n\nfunction updateForwardRef(current, workInProgress, Component, nextProps, renderExpirationTime) {\n // TODO: current can be non-null here even if the component\n // hasn't yet mounted. This happens after the first render suspends.\n // We'll need to figure out if this is fine or can cause issues.\n {\n if (workInProgress.type !== workInProgress.elementType) {\n // Lazy component props can't be validated in createElement\n // because they're only guaranteed to be resolved here.\n var innerPropTypes = Component.propTypes;\n\n if (innerPropTypes) {\n checkPropTypes(innerPropTypes, nextProps, // Resolved props\n 'prop', getComponentName(Component), getCurrentFiberStackInDev);\n }\n }\n }\n\n var render = Component.render;\n var ref = workInProgress.ref; // The rest is a fork of updateFunctionComponent\n\n var nextChildren;\n prepareToReadContext(workInProgress, renderExpirationTime);\n\n {\n ReactCurrentOwner$1.current = workInProgress;\n setIsRendering(true);\n nextChildren = renderWithHooks(current, workInProgress, render, nextProps, ref, renderExpirationTime);\n\n if ( workInProgress.mode & StrictMode) {\n // Only double-render components with Hooks\n if (workInProgress.memoizedState !== null) {\n nextChildren = renderWithHooks(current, workInProgress, render, nextProps, ref, renderExpirationTime);\n }\n }\n\n setIsRendering(false);\n }\n\n if (current !== null && !didReceiveUpdate) {\n bailoutHooks(current, workInProgress, renderExpirationTime);\n return bailoutOnAlreadyFinishedWork(current, workInProgress, renderExpirationTime);\n } // React DevTools reads this flag.\n\n\n workInProgress.effectTag |= PerformedWork;\n reconcileChildren(current, workInProgress, nextChildren, renderExpirationTime);\n return workInProgress.child;\n}\n\nfunction updateMemoComponent(current, workInProgress, Component, nextProps, updateExpirationTime, renderExpirationTime) {\n if (current === null) {\n var type = Component.type;\n\n if (isSimpleFunctionComponent(type) && Component.compare === null && // SimpleMemoComponent codepath doesn't resolve outer props either.\n Component.defaultProps === undefined) {\n var resolvedType = type;\n\n {\n resolvedType = resolveFunctionForHotReloading(type);\n } // If this is a plain function component without default props,\n // and with only the default shallow comparison, we upgrade it\n // to a SimpleMemoComponent to allow fast path updates.\n\n\n workInProgress.tag = SimpleMemoComponent;\n workInProgress.type = resolvedType;\n\n {\n validateFunctionComponentInDev(workInProgress, type);\n }\n\n return updateSimpleMemoComponent(current, workInProgress, resolvedType, nextProps, updateExpirationTime, renderExpirationTime);\n }\n\n {\n var innerPropTypes = type.propTypes;\n\n if (innerPropTypes) {\n // Inner memo component props aren't currently validated in createElement.\n // We could move it there, but we'd still need this for lazy code path.\n checkPropTypes(innerPropTypes, nextProps, // Resolved props\n 'prop', getComponentName(type), getCurrentFiberStackInDev);\n }\n }\n\n var child = createFiberFromTypeAndProps(Component.type, null, nextProps, null, workInProgress.mode, renderExpirationTime);\n child.ref = workInProgress.ref;\n child.return = workInProgress;\n workInProgress.child = child;\n return child;\n }\n\n {\n var _type = Component.type;\n var _innerPropTypes = _type.propTypes;\n\n if (_innerPropTypes) {\n // Inner memo component props aren't currently validated in createElement.\n // We could move it there, but we'd still need this for lazy code path.\n checkPropTypes(_innerPropTypes, nextProps, // Resolved props\n 'prop', getComponentName(_type), getCurrentFiberStackInDev);\n }\n }\n\n var currentChild = current.child; // This is always exactly one child\n\n if (updateExpirationTime < renderExpirationTime) {\n // This will be the props with resolved defaultProps,\n // unlike current.memoizedProps which will be the unresolved ones.\n var prevProps = currentChild.memoizedProps; // Default to shallow comparison\n\n var compare = Component.compare;\n compare = compare !== null ? compare : shallowEqual;\n\n if (compare(prevProps, nextProps) && current.ref === workInProgress.ref) {\n return bailoutOnAlreadyFinishedWork(current, workInProgress, renderExpirationTime);\n }\n } // React DevTools reads this flag.\n\n\n workInProgress.effectTag |= PerformedWork;\n var newChild = createWorkInProgress(currentChild, nextProps);\n newChild.ref = workInProgress.ref;\n newChild.return = workInProgress;\n workInProgress.child = newChild;\n return newChild;\n}\n\nfunction updateSimpleMemoComponent(current, workInProgress, Component, nextProps, updateExpirationTime, renderExpirationTime) {\n // TODO: current can be non-null here even if the component\n // hasn't yet mounted. This happens when the inner render suspends.\n // We'll need to figure out if this is fine or can cause issues.\n {\n if (workInProgress.type !== workInProgress.elementType) {\n // Lazy component props can't be validated in createElement\n // because they're only guaranteed to be resolved here.\n var outerMemoType = workInProgress.elementType;\n\n if (outerMemoType.$$typeof === REACT_LAZY_TYPE) {\n // We warn when you define propTypes on lazy()\n // so let's just skip over it to find memo() outer wrapper.\n // Inner props for memo are validated later.\n outerMemoType = refineResolvedLazyComponent(outerMemoType);\n }\n\n var outerPropTypes = outerMemoType && outerMemoType.propTypes;\n\n if (outerPropTypes) {\n checkPropTypes(outerPropTypes, nextProps, // Resolved (SimpleMemoComponent has no defaultProps)\n 'prop', getComponentName(outerMemoType), getCurrentFiberStackInDev);\n } // Inner propTypes will be validated in the function component path.\n\n }\n }\n\n if (current !== null) {\n var prevProps = current.memoizedProps;\n\n if (shallowEqual(prevProps, nextProps) && current.ref === workInProgress.ref && ( // Prevent bailout if the implementation changed due to hot reload.\n workInProgress.type === current.type )) {\n didReceiveUpdate = false;\n\n if (updateExpirationTime < renderExpirationTime) {\n // The pending update priority was cleared at the beginning of\n // beginWork. We're about to bail out, but there might be additional\n // updates at a lower priority. Usually, the priority level of the\n // remaining updates is accumlated during the evaluation of the\n // component (i.e. when processing the update queue). But since since\n // we're bailing out early *without* evaluating the component, we need\n // to account for it here, too. Reset to the value of the current fiber.\n // NOTE: This only applies to SimpleMemoComponent, not MemoComponent,\n // because a MemoComponent fiber does not have hooks or an update queue;\n // rather, it wraps around an inner component, which may or may not\n // contains hooks.\n // TODO: Move the reset at in beginWork out of the common path so that\n // this is no longer necessary.\n workInProgress.expirationTime = current.expirationTime;\n return bailoutOnAlreadyFinishedWork(current, workInProgress, renderExpirationTime);\n }\n }\n }\n\n return updateFunctionComponent(current, workInProgress, Component, nextProps, renderExpirationTime);\n}\n\nfunction updateFragment(current, workInProgress, renderExpirationTime) {\n var nextChildren = workInProgress.pendingProps;\n reconcileChildren(current, workInProgress, nextChildren, renderExpirationTime);\n return workInProgress.child;\n}\n\nfunction updateMode(current, workInProgress, renderExpirationTime) {\n var nextChildren = workInProgress.pendingProps.children;\n reconcileChildren(current, workInProgress, nextChildren, renderExpirationTime);\n return workInProgress.child;\n}\n\nfunction updateProfiler(current, workInProgress, renderExpirationTime) {\n {\n workInProgress.effectTag |= Update;\n }\n\n var nextProps = workInProgress.pendingProps;\n var nextChildren = nextProps.children;\n reconcileChildren(current, workInProgress, nextChildren, renderExpirationTime);\n return workInProgress.child;\n}\n\nfunction markRef(current, workInProgress) {\n var ref = workInProgress.ref;\n\n if (current === null && ref !== null || current !== null && current.ref !== ref) {\n // Schedule a Ref effect\n workInProgress.effectTag |= Ref;\n }\n}\n\nfunction updateFunctionComponent(current, workInProgress, Component, nextProps, renderExpirationTime) {\n {\n if (workInProgress.type !== workInProgress.elementType) {\n // Lazy component props can't be validated in createElement\n // because they're only guaranteed to be resolved here.\n var innerPropTypes = Component.propTypes;\n\n if (innerPropTypes) {\n checkPropTypes(innerPropTypes, nextProps, // Resolved props\n 'prop', getComponentName(Component), getCurrentFiberStackInDev);\n }\n }\n }\n\n var context;\n\n {\n var unmaskedContext = getUnmaskedContext(workInProgress, Component, true);\n context = getMaskedContext(workInProgress, unmaskedContext);\n }\n\n var nextChildren;\n prepareToReadContext(workInProgress, renderExpirationTime);\n\n {\n ReactCurrentOwner$1.current = workInProgress;\n setIsRendering(true);\n nextChildren = renderWithHooks(current, workInProgress, Component, nextProps, context, renderExpirationTime);\n\n if ( workInProgress.mode & StrictMode) {\n // Only double-render components with Hooks\n if (workInProgress.memoizedState !== null) {\n nextChildren = renderWithHooks(current, workInProgress, Component, nextProps, context, renderExpirationTime);\n }\n }\n\n setIsRendering(false);\n }\n\n if (current !== null && !didReceiveUpdate) {\n bailoutHooks(current, workInProgress, renderExpirationTime);\n return bailoutOnAlreadyFinishedWork(current, workInProgress, renderExpirationTime);\n } // React DevTools reads this flag.\n\n\n workInProgress.effectTag |= PerformedWork;\n reconcileChildren(current, workInProgress, nextChildren, renderExpirationTime);\n return workInProgress.child;\n}\n\nfunction updateClassComponent(current, workInProgress, Component, nextProps, renderExpirationTime) {\n {\n if (workInProgress.type !== workInProgress.elementType) {\n // Lazy component props can't be validated in createElement\n // because they're only guaranteed to be resolved here.\n var innerPropTypes = Component.propTypes;\n\n if (innerPropTypes) {\n checkPropTypes(innerPropTypes, nextProps, // Resolved props\n 'prop', getComponentName(Component), getCurrentFiberStackInDev);\n }\n }\n } // Push context providers early to prevent context stack mismatches.\n // During mounting we don't know the child context yet as the instance doesn't exist.\n // We will invalidate the child context in finishClassComponent() right after rendering.\n\n\n var hasContext;\n\n if (isContextProvider(Component)) {\n hasContext = true;\n pushContextProvider(workInProgress);\n } else {\n hasContext = false;\n }\n\n prepareToReadContext(workInProgress, renderExpirationTime);\n var instance = workInProgress.stateNode;\n var shouldUpdate;\n\n if (instance === null) {\n if (current !== null) {\n // A class component without an instance only mounts if it suspended\n // inside a non-concurrent tree, in an inconsistent state. We want to\n // treat it like a new mount, even though an empty version of it already\n // committed. Disconnect the alternate pointers.\n current.alternate = null;\n workInProgress.alternate = null; // Since this is conceptually a new fiber, schedule a Placement effect\n\n workInProgress.effectTag |= Placement;\n } // In the initial pass we might need to construct the instance.\n\n\n constructClassInstance(workInProgress, Component, nextProps);\n mountClassInstance(workInProgress, Component, nextProps, renderExpirationTime);\n shouldUpdate = true;\n } else if (current === null) {\n // In a resume, we'll already have an instance we can reuse.\n shouldUpdate = resumeMountClassInstance(workInProgress, Component, nextProps, renderExpirationTime);\n } else {\n shouldUpdate = updateClassInstance(current, workInProgress, Component, nextProps, renderExpirationTime);\n }\n\n var nextUnitOfWork = finishClassComponent(current, workInProgress, Component, shouldUpdate, hasContext, renderExpirationTime);\n\n {\n var inst = workInProgress.stateNode;\n\n if (inst.props !== nextProps) {\n if (!didWarnAboutReassigningProps) {\n error('It looks like %s is reassigning its own `this.props` while rendering. ' + 'This is not supported and can lead to confusing bugs.', getComponentName(workInProgress.type) || 'a component');\n }\n\n didWarnAboutReassigningProps = true;\n }\n }\n\n return nextUnitOfWork;\n}\n\nfunction finishClassComponent(current, workInProgress, Component, shouldUpdate, hasContext, renderExpirationTime) {\n // Refs should update even if shouldComponentUpdate returns false\n markRef(current, workInProgress);\n var didCaptureError = (workInProgress.effectTag & DidCapture) !== NoEffect;\n\n if (!shouldUpdate && !didCaptureError) {\n // Context providers should defer to sCU for rendering\n if (hasContext) {\n invalidateContextProvider(workInProgress, Component, false);\n }\n\n return bailoutOnAlreadyFinishedWork(current, workInProgress, renderExpirationTime);\n }\n\n var instance = workInProgress.stateNode; // Rerender\n\n ReactCurrentOwner$1.current = workInProgress;\n var nextChildren;\n\n if (didCaptureError && typeof Component.getDerivedStateFromError !== 'function') {\n // If we captured an error, but getDerivedStateFromError is not defined,\n // unmount all the children. componentDidCatch will schedule an update to\n // re-render a fallback. This is temporary until we migrate everyone to\n // the new API.\n // TODO: Warn in a future release.\n nextChildren = null;\n\n {\n stopProfilerTimerIfRunning();\n }\n } else {\n {\n setIsRendering(true);\n nextChildren = instance.render();\n\n if ( workInProgress.mode & StrictMode) {\n instance.render();\n }\n\n setIsRendering(false);\n }\n } // React DevTools reads this flag.\n\n\n workInProgress.effectTag |= PerformedWork;\n\n if (current !== null && didCaptureError) {\n // If we're recovering from an error, reconcile without reusing any of\n // the existing children. Conceptually, the normal children and the children\n // that are shown on error are two different sets, so we shouldn't reuse\n // normal children even if their identities match.\n forceUnmountCurrentAndReconcile(current, workInProgress, nextChildren, renderExpirationTime);\n } else {\n reconcileChildren(current, workInProgress, nextChildren, renderExpirationTime);\n } // Memoize state using the values we just used to render.\n // TODO: Restructure so we never read values from the instance.\n\n\n workInProgress.memoizedState = instance.state; // The context might have changed so we need to recalculate it.\n\n if (hasContext) {\n invalidateContextProvider(workInProgress, Component, true);\n }\n\n return workInProgress.child;\n}\n\nfunction pushHostRootContext(workInProgress) {\n var root = workInProgress.stateNode;\n\n if (root.pendingContext) {\n pushTopLevelContextObject(workInProgress, root.pendingContext, root.pendingContext !== root.context);\n } else if (root.context) {\n // Should always be set\n pushTopLevelContextObject(workInProgress, root.context, false);\n }\n\n pushHostContainer(workInProgress, root.containerInfo);\n}\n\nfunction updateHostRoot(current, workInProgress, renderExpirationTime) {\n pushHostRootContext(workInProgress);\n var updateQueue = workInProgress.updateQueue;\n\n if (!(current !== null && updateQueue !== null)) {\n {\n throw Error( \"If the root does not have an updateQueue, we should have already bailed out. This error is likely caused by a bug in React. Please file an issue.\" );\n }\n }\n\n var nextProps = workInProgress.pendingProps;\n var prevState = workInProgress.memoizedState;\n var prevChildren = prevState !== null ? prevState.element : null;\n cloneUpdateQueue(current, workInProgress);\n processUpdateQueue(workInProgress, nextProps, null, renderExpirationTime);\n var nextState = workInProgress.memoizedState; // Caution: React DevTools currently depends on this property\n // being called \"element\".\n\n var nextChildren = nextState.element;\n\n if (nextChildren === prevChildren) {\n // If the state is the same as before, that's a bailout because we had\n // no work that expires at this time.\n resetHydrationState();\n return bailoutOnAlreadyFinishedWork(current, workInProgress, renderExpirationTime);\n }\n\n var root = workInProgress.stateNode;\n\n if (root.hydrate && enterHydrationState(workInProgress)) {\n // If we don't have any current children this might be the first pass.\n // We always try to hydrate. If this isn't a hydration pass there won't\n // be any children to hydrate which is effectively the same thing as\n // not hydrating.\n var child = mountChildFibers(workInProgress, null, nextChildren, renderExpirationTime);\n workInProgress.child = child;\n var node = child;\n\n while (node) {\n // Mark each child as hydrating. This is a fast path to know whether this\n // tree is part of a hydrating tree. This is used to determine if a child\n // node has fully mounted yet, and for scheduling event replaying.\n // Conceptually this is similar to Placement in that a new subtree is\n // inserted into the React tree here. It just happens to not need DOM\n // mutations because it already exists.\n node.effectTag = node.effectTag & ~Placement | Hydrating;\n node = node.sibling;\n }\n } else {\n // Otherwise reset hydration state in case we aborted and resumed another\n // root.\n reconcileChildren(current, workInProgress, nextChildren, renderExpirationTime);\n resetHydrationState();\n }\n\n return workInProgress.child;\n}\n\nfunction updateHostComponent(current, workInProgress, renderExpirationTime) {\n pushHostContext(workInProgress);\n\n if (current === null) {\n tryToClaimNextHydratableInstance(workInProgress);\n }\n\n var type = workInProgress.type;\n var nextProps = workInProgress.pendingProps;\n var prevProps = current !== null ? current.memoizedProps : null;\n var nextChildren = nextProps.children;\n var isDirectTextChild = shouldSetTextContent(type, nextProps);\n\n if (isDirectTextChild) {\n // We special case a direct text child of a host node. This is a common\n // case. We won't handle it as a reified child. We will instead handle\n // this in the host environment that also has access to this prop. That\n // avoids allocating another HostText fiber and traversing it.\n nextChildren = null;\n } else if (prevProps !== null && shouldSetTextContent(type, prevProps)) {\n // If we're switching from a direct text child to a normal child, or to\n // empty, we need to schedule the text content to be reset.\n workInProgress.effectTag |= ContentReset;\n }\n\n markRef(current, workInProgress); // Check the host config to see if the children are offscreen/hidden.\n\n if (workInProgress.mode & ConcurrentMode && renderExpirationTime !== Never && shouldDeprioritizeSubtree(type, nextProps)) {\n {\n markSpawnedWork(Never);\n } // Schedule this fiber to re-render at offscreen priority. Then bailout.\n\n\n workInProgress.expirationTime = workInProgress.childExpirationTime = Never;\n return null;\n }\n\n reconcileChildren(current, workInProgress, nextChildren, renderExpirationTime);\n return workInProgress.child;\n}\n\nfunction updateHostText(current, workInProgress) {\n if (current === null) {\n tryToClaimNextHydratableInstance(workInProgress);\n } // Nothing to do here. This is terminal. We'll do the completion step\n // immediately after.\n\n\n return null;\n}\n\nfunction mountLazyComponent(_current, workInProgress, elementType, updateExpirationTime, renderExpirationTime) {\n if (_current !== null) {\n // A lazy component only mounts if it suspended inside a non-\n // concurrent tree, in an inconsistent state. We want to treat it like\n // a new mount, even though an empty version of it already committed.\n // Disconnect the alternate pointers.\n _current.alternate = null;\n workInProgress.alternate = null; // Since this is conceptually a new fiber, schedule a Placement effect\n\n workInProgress.effectTag |= Placement;\n }\n\n var props = workInProgress.pendingProps; // We can't start a User Timing measurement with correct label yet.\n // Cancel and resume right after we know the tag.\n\n cancelWorkTimer(workInProgress);\n var Component = readLazyComponentType(elementType); // Store the unwrapped component in the type.\n\n workInProgress.type = Component;\n var resolvedTag = workInProgress.tag = resolveLazyComponentTag(Component);\n startWorkTimer(workInProgress);\n var resolvedProps = resolveDefaultProps(Component, props);\n var child;\n\n switch (resolvedTag) {\n case FunctionComponent:\n {\n {\n validateFunctionComponentInDev(workInProgress, Component);\n workInProgress.type = Component = resolveFunctionForHotReloading(Component);\n }\n\n child = updateFunctionComponent(null, workInProgress, Component, resolvedProps, renderExpirationTime);\n return child;\n }\n\n case ClassComponent:\n {\n {\n workInProgress.type = Component = resolveClassForHotReloading(Component);\n }\n\n child = updateClassComponent(null, workInProgress, Component, resolvedProps, renderExpirationTime);\n return child;\n }\n\n case ForwardRef:\n {\n {\n workInProgress.type = Component = resolveForwardRefForHotReloading(Component);\n }\n\n child = updateForwardRef(null, workInProgress, Component, resolvedProps, renderExpirationTime);\n return child;\n }\n\n case MemoComponent:\n {\n {\n if (workInProgress.type !== workInProgress.elementType) {\n var outerPropTypes = Component.propTypes;\n\n if (outerPropTypes) {\n checkPropTypes(outerPropTypes, resolvedProps, // Resolved for outer only\n 'prop', getComponentName(Component), getCurrentFiberStackInDev);\n }\n }\n }\n\n child = updateMemoComponent(null, workInProgress, Component, resolveDefaultProps(Component.type, resolvedProps), // The inner type can have defaults too\n updateExpirationTime, renderExpirationTime);\n return child;\n }\n }\n\n var hint = '';\n\n {\n if (Component !== null && typeof Component === 'object' && Component.$$typeof === REACT_LAZY_TYPE) {\n hint = ' Did you wrap a component in React.lazy() more than once?';\n }\n } // This message intentionally doesn't mention ForwardRef or MemoComponent\n // because the fact that it's a separate type of work is an\n // implementation detail.\n\n\n {\n {\n throw Error( \"Element type is invalid. Received a promise that resolves to: \" + Component + \". Lazy element type must resolve to a class or function.\" + hint );\n }\n }\n}\n\nfunction mountIncompleteClassComponent(_current, workInProgress, Component, nextProps, renderExpirationTime) {\n if (_current !== null) {\n // An incomplete component only mounts if it suspended inside a non-\n // concurrent tree, in an inconsistent state. We want to treat it like\n // a new mount, even though an empty version of it already committed.\n // Disconnect the alternate pointers.\n _current.alternate = null;\n workInProgress.alternate = null; // Since this is conceptually a new fiber, schedule a Placement effect\n\n workInProgress.effectTag |= Placement;\n } // Promote the fiber to a class and try rendering again.\n\n\n workInProgress.tag = ClassComponent; // The rest of this function is a fork of `updateClassComponent`\n // Push context providers early to prevent context stack mismatches.\n // During mounting we don't know the child context yet as the instance doesn't exist.\n // We will invalidate the child context in finishClassComponent() right after rendering.\n\n var hasContext;\n\n if (isContextProvider(Component)) {\n hasContext = true;\n pushContextProvider(workInProgress);\n } else {\n hasContext = false;\n }\n\n prepareToReadContext(workInProgress, renderExpirationTime);\n constructClassInstance(workInProgress, Component, nextProps);\n mountClassInstance(workInProgress, Component, nextProps, renderExpirationTime);\n return finishClassComponent(null, workInProgress, Component, true, hasContext, renderExpirationTime);\n}\n\nfunction mountIndeterminateComponent(_current, workInProgress, Component, renderExpirationTime) {\n if (_current !== null) {\n // An indeterminate component only mounts if it suspended inside a non-\n // concurrent tree, in an inconsistent state. We want to treat it like\n // a new mount, even though an empty version of it already committed.\n // Disconnect the alternate pointers.\n _current.alternate = null;\n workInProgress.alternate = null; // Since this is conceptually a new fiber, schedule a Placement effect\n\n workInProgress.effectTag |= Placement;\n }\n\n var props = workInProgress.pendingProps;\n var context;\n\n {\n var unmaskedContext = getUnmaskedContext(workInProgress, Component, false);\n context = getMaskedContext(workInProgress, unmaskedContext);\n }\n\n prepareToReadContext(workInProgress, renderExpirationTime);\n var value;\n\n {\n if (Component.prototype && typeof Component.prototype.render === 'function') {\n var componentName = getComponentName(Component) || 'Unknown';\n\n if (!didWarnAboutBadClass[componentName]) {\n error(\"The <%s /> component appears to have a render method, but doesn't extend React.Component. \" + 'This is likely to cause errors. Change %s to extend React.Component instead.', componentName, componentName);\n\n didWarnAboutBadClass[componentName] = true;\n }\n }\n\n if (workInProgress.mode & StrictMode) {\n ReactStrictModeWarnings.recordLegacyContextWarning(workInProgress, null);\n }\n\n setIsRendering(true);\n ReactCurrentOwner$1.current = workInProgress;\n value = renderWithHooks(null, workInProgress, Component, props, context, renderExpirationTime);\n setIsRendering(false);\n } // React DevTools reads this flag.\n\n\n workInProgress.effectTag |= PerformedWork;\n\n if (typeof value === 'object' && value !== null && typeof value.render === 'function' && value.$$typeof === undefined) {\n {\n var _componentName = getComponentName(Component) || 'Unknown';\n\n if (!didWarnAboutModulePatternComponent[_componentName]) {\n error('The <%s /> component appears to be a function component that returns a class instance. ' + 'Change %s to a class that extends React.Component instead. ' + \"If you can't use a class try assigning the prototype on the function as a workaround. \" + \"`%s.prototype = React.Component.prototype`. Don't use an arrow function since it \" + 'cannot be called with `new` by React.', _componentName, _componentName, _componentName);\n\n didWarnAboutModulePatternComponent[_componentName] = true;\n }\n } // Proceed under the assumption that this is a class instance\n\n\n workInProgress.tag = ClassComponent; // Throw out any hooks that were used.\n\n workInProgress.memoizedState = null;\n workInProgress.updateQueue = null; // Push context providers early to prevent context stack mismatches.\n // During mounting we don't know the child context yet as the instance doesn't exist.\n // We will invalidate the child context in finishClassComponent() right after rendering.\n\n var hasContext = false;\n\n if (isContextProvider(Component)) {\n hasContext = true;\n pushContextProvider(workInProgress);\n } else {\n hasContext = false;\n }\n\n workInProgress.memoizedState = value.state !== null && value.state !== undefined ? value.state : null;\n initializeUpdateQueue(workInProgress);\n var getDerivedStateFromProps = Component.getDerivedStateFromProps;\n\n if (typeof getDerivedStateFromProps === 'function') {\n applyDerivedStateFromProps(workInProgress, Component, getDerivedStateFromProps, props);\n }\n\n adoptClassInstance(workInProgress, value);\n mountClassInstance(workInProgress, Component, props, renderExpirationTime);\n return finishClassComponent(null, workInProgress, Component, true, hasContext, renderExpirationTime);\n } else {\n // Proceed under the assumption that this is a function component\n workInProgress.tag = FunctionComponent;\n\n {\n\n if ( workInProgress.mode & StrictMode) {\n // Only double-render components with Hooks\n if (workInProgress.memoizedState !== null) {\n value = renderWithHooks(null, workInProgress, Component, props, context, renderExpirationTime);\n }\n }\n }\n\n reconcileChildren(null, workInProgress, value, renderExpirationTime);\n\n {\n validateFunctionComponentInDev(workInProgress, Component);\n }\n\n return workInProgress.child;\n }\n}\n\nfunction validateFunctionComponentInDev(workInProgress, Component) {\n {\n if (Component) {\n if (Component.childContextTypes) {\n error('%s(...): childContextTypes cannot be defined on a function component.', Component.displayName || Component.name || 'Component');\n }\n }\n\n if (workInProgress.ref !== null) {\n var info = '';\n var ownerName = getCurrentFiberOwnerNameInDevOrNull();\n\n if (ownerName) {\n info += '\\n\\nCheck the render method of `' + ownerName + '`.';\n }\n\n var warningKey = ownerName || workInProgress._debugID || '';\n var debugSource = workInProgress._debugSource;\n\n if (debugSource) {\n warningKey = debugSource.fileName + ':' + debugSource.lineNumber;\n }\n\n if (!didWarnAboutFunctionRefs[warningKey]) {\n didWarnAboutFunctionRefs[warningKey] = true;\n\n error('Function components cannot be given refs. ' + 'Attempts to access this ref will fail. ' + 'Did you mean to use React.forwardRef()?%s', info);\n }\n }\n\n if (typeof Component.getDerivedStateFromProps === 'function') {\n var _componentName2 = getComponentName(Component) || 'Unknown';\n\n if (!didWarnAboutGetDerivedStateOnFunctionComponent[_componentName2]) {\n error('%s: Function components do not support getDerivedStateFromProps.', _componentName2);\n\n didWarnAboutGetDerivedStateOnFunctionComponent[_componentName2] = true;\n }\n }\n\n if (typeof Component.contextType === 'object' && Component.contextType !== null) {\n var _componentName3 = getComponentName(Component) || 'Unknown';\n\n if (!didWarnAboutContextTypeOnFunctionComponent[_componentName3]) {\n error('%s: Function components do not support contextType.', _componentName3);\n\n didWarnAboutContextTypeOnFunctionComponent[_componentName3] = true;\n }\n }\n }\n}\n\nvar SUSPENDED_MARKER = {\n dehydrated: null,\n retryTime: NoWork\n};\n\nfunction shouldRemainOnFallback(suspenseContext, current, workInProgress) {\n // If the context is telling us that we should show a fallback, and we're not\n // already showing content, then we should show the fallback instead.\n return hasSuspenseContext(suspenseContext, ForceSuspenseFallback) && (current === null || current.memoizedState !== null);\n}\n\nfunction updateSuspenseComponent(current, workInProgress, renderExpirationTime) {\n var mode = workInProgress.mode;\n var nextProps = workInProgress.pendingProps; // This is used by DevTools to force a boundary to suspend.\n\n {\n if (shouldSuspend(workInProgress)) {\n workInProgress.effectTag |= DidCapture;\n }\n }\n\n var suspenseContext = suspenseStackCursor.current;\n var nextDidTimeout = false;\n var didSuspend = (workInProgress.effectTag & DidCapture) !== NoEffect;\n\n if (didSuspend || shouldRemainOnFallback(suspenseContext, current)) {\n // Something in this boundary's subtree already suspended. Switch to\n // rendering the fallback children.\n nextDidTimeout = true;\n workInProgress.effectTag &= ~DidCapture;\n } else {\n // Attempting the main content\n if (current === null || current.memoizedState !== null) {\n // This is a new mount or this boundary is already showing a fallback state.\n // Mark this subtree context as having at least one invisible parent that could\n // handle the fallback state.\n // Boundaries without fallbacks or should be avoided are not considered since\n // they cannot handle preferred fallback states.\n if (nextProps.fallback !== undefined && nextProps.unstable_avoidThisFallback !== true) {\n suspenseContext = addSubtreeSuspenseContext(suspenseContext, InvisibleParentSuspenseContext);\n }\n }\n }\n\n suspenseContext = setDefaultShallowSuspenseContext(suspenseContext);\n pushSuspenseContext(workInProgress, suspenseContext); // This next part is a bit confusing. If the children timeout, we switch to\n // showing the fallback children in place of the \"primary\" children.\n // However, we don't want to delete the primary children because then their\n // state will be lost (both the React state and the host state, e.g.\n // uncontrolled form inputs). Instead we keep them mounted and hide them.\n // Both the fallback children AND the primary children are rendered at the\n // same time. Once the primary children are un-suspended, we can delete\n // the fallback children — don't need to preserve their state.\n //\n // The two sets of children are siblings in the host environment, but\n // semantically, for purposes of reconciliation, they are two separate sets.\n // So we store them using two fragment fibers.\n //\n // However, we want to avoid allocating extra fibers for every placeholder.\n // They're only necessary when the children time out, because that's the\n // only time when both sets are mounted.\n //\n // So, the extra fragment fibers are only used if the children time out.\n // Otherwise, we render the primary children directly. This requires some\n // custom reconciliation logic to preserve the state of the primary\n // children. It's essentially a very basic form of re-parenting.\n\n if (current === null) {\n // If we're currently hydrating, try to hydrate this boundary.\n // But only if this has a fallback.\n if (nextProps.fallback !== undefined) {\n tryToClaimNextHydratableInstance(workInProgress); // This could've been a dehydrated suspense component.\n } // This is the initial mount. This branch is pretty simple because there's\n // no previous state that needs to be preserved.\n\n\n if (nextDidTimeout) {\n // Mount separate fragments for primary and fallback children.\n var nextFallbackChildren = nextProps.fallback;\n var primaryChildFragment = createFiberFromFragment(null, mode, NoWork, null);\n primaryChildFragment.return = workInProgress;\n\n if ((workInProgress.mode & BlockingMode) === NoMode) {\n // Outside of blocking mode, we commit the effects from the\n // partially completed, timed-out tree, too.\n var progressedState = workInProgress.memoizedState;\n var progressedPrimaryChild = progressedState !== null ? workInProgress.child.child : workInProgress.child;\n primaryChildFragment.child = progressedPrimaryChild;\n var progressedChild = progressedPrimaryChild;\n\n while (progressedChild !== null) {\n progressedChild.return = primaryChildFragment;\n progressedChild = progressedChild.sibling;\n }\n }\n\n var fallbackChildFragment = createFiberFromFragment(nextFallbackChildren, mode, renderExpirationTime, null);\n fallbackChildFragment.return = workInProgress;\n primaryChildFragment.sibling = fallbackChildFragment; // Skip the primary children, and continue working on the\n // fallback children.\n\n workInProgress.memoizedState = SUSPENDED_MARKER;\n workInProgress.child = primaryChildFragment;\n return fallbackChildFragment;\n } else {\n // Mount the primary children without an intermediate fragment fiber.\n var nextPrimaryChildren = nextProps.children;\n workInProgress.memoizedState = null;\n return workInProgress.child = mountChildFibers(workInProgress, null, nextPrimaryChildren, renderExpirationTime);\n }\n } else {\n // This is an update. This branch is more complicated because we need to\n // ensure the state of the primary children is preserved.\n var prevState = current.memoizedState;\n\n if (prevState !== null) {\n // wrapped in a fragment fiber.\n\n\n var currentPrimaryChildFragment = current.child;\n var currentFallbackChildFragment = currentPrimaryChildFragment.sibling;\n\n if (nextDidTimeout) {\n // Still timed out. Reuse the current primary children by cloning\n // its fragment. We're going to skip over these entirely.\n var _nextFallbackChildren2 = nextProps.fallback;\n\n var _primaryChildFragment2 = createWorkInProgress(currentPrimaryChildFragment, currentPrimaryChildFragment.pendingProps);\n\n _primaryChildFragment2.return = workInProgress;\n\n if ((workInProgress.mode & BlockingMode) === NoMode) {\n // Outside of blocking mode, we commit the effects from the\n // partially completed, timed-out tree, too.\n var _progressedState = workInProgress.memoizedState;\n\n var _progressedPrimaryChild = _progressedState !== null ? workInProgress.child.child : workInProgress.child;\n\n if (_progressedPrimaryChild !== currentPrimaryChildFragment.child) {\n _primaryChildFragment2.child = _progressedPrimaryChild;\n var _progressedChild2 = _progressedPrimaryChild;\n\n while (_progressedChild2 !== null) {\n _progressedChild2.return = _primaryChildFragment2;\n _progressedChild2 = _progressedChild2.sibling;\n }\n }\n } // Because primaryChildFragment is a new fiber that we're inserting as the\n // parent of a new tree, we need to set its treeBaseDuration.\n\n\n if ( workInProgress.mode & ProfileMode) {\n // treeBaseDuration is the sum of all the child tree base durations.\n var _treeBaseDuration = 0;\n var _hiddenChild = _primaryChildFragment2.child;\n\n while (_hiddenChild !== null) {\n _treeBaseDuration += _hiddenChild.treeBaseDuration;\n _hiddenChild = _hiddenChild.sibling;\n }\n\n _primaryChildFragment2.treeBaseDuration = _treeBaseDuration;\n } // Clone the fallback child fragment, too. These we'll continue\n // working on.\n\n\n var _fallbackChildFragment2 = createWorkInProgress(currentFallbackChildFragment, _nextFallbackChildren2);\n\n _fallbackChildFragment2.return = workInProgress;\n _primaryChildFragment2.sibling = _fallbackChildFragment2;\n _primaryChildFragment2.childExpirationTime = NoWork; // Skip the primary children, and continue working on the\n // fallback children.\n\n workInProgress.memoizedState = SUSPENDED_MARKER;\n workInProgress.child = _primaryChildFragment2;\n return _fallbackChildFragment2;\n } else {\n // No longer suspended. Switch back to showing the primary children,\n // and remove the intermediate fragment fiber.\n var _nextPrimaryChildren = nextProps.children;\n var currentPrimaryChild = currentPrimaryChildFragment.child;\n var primaryChild = reconcileChildFibers(workInProgress, currentPrimaryChild, _nextPrimaryChildren, renderExpirationTime); // If this render doesn't suspend, we need to delete the fallback\n // children. Wait until the complete phase, after we've confirmed the\n // fallback is no longer needed.\n // TODO: Would it be better to store the fallback fragment on\n // the stateNode?\n // Continue rendering the children, like we normally do.\n\n workInProgress.memoizedState = null;\n return workInProgress.child = primaryChild;\n }\n } else {\n // The current tree has not already timed out. That means the primary\n // children are not wrapped in a fragment fiber.\n var _currentPrimaryChild = current.child;\n\n if (nextDidTimeout) {\n // Timed out. Wrap the children in a fragment fiber to keep them\n // separate from the fallback children.\n var _nextFallbackChildren3 = nextProps.fallback;\n\n var _primaryChildFragment3 = createFiberFromFragment( // It shouldn't matter what the pending props are because we aren't\n // going to render this fragment.\n null, mode, NoWork, null);\n\n _primaryChildFragment3.return = workInProgress;\n _primaryChildFragment3.child = _currentPrimaryChild;\n\n if (_currentPrimaryChild !== null) {\n _currentPrimaryChild.return = _primaryChildFragment3;\n } // Even though we're creating a new fiber, there are no new children,\n // because we're reusing an already mounted tree. So we don't need to\n // schedule a placement.\n // primaryChildFragment.effectTag |= Placement;\n\n\n if ((workInProgress.mode & BlockingMode) === NoMode) {\n // Outside of blocking mode, we commit the effects from the\n // partially completed, timed-out tree, too.\n var _progressedState2 = workInProgress.memoizedState;\n\n var _progressedPrimaryChild2 = _progressedState2 !== null ? workInProgress.child.child : workInProgress.child;\n\n _primaryChildFragment3.child = _progressedPrimaryChild2;\n var _progressedChild3 = _progressedPrimaryChild2;\n\n while (_progressedChild3 !== null) {\n _progressedChild3.return = _primaryChildFragment3;\n _progressedChild3 = _progressedChild3.sibling;\n }\n } // Because primaryChildFragment is a new fiber that we're inserting as the\n // parent of a new tree, we need to set its treeBaseDuration.\n\n\n if ( workInProgress.mode & ProfileMode) {\n // treeBaseDuration is the sum of all the child tree base durations.\n var _treeBaseDuration2 = 0;\n var _hiddenChild2 = _primaryChildFragment3.child;\n\n while (_hiddenChild2 !== null) {\n _treeBaseDuration2 += _hiddenChild2.treeBaseDuration;\n _hiddenChild2 = _hiddenChild2.sibling;\n }\n\n _primaryChildFragment3.treeBaseDuration = _treeBaseDuration2;\n } // Create a fragment from the fallback children, too.\n\n\n var _fallbackChildFragment3 = createFiberFromFragment(_nextFallbackChildren3, mode, renderExpirationTime, null);\n\n _fallbackChildFragment3.return = workInProgress;\n _primaryChildFragment3.sibling = _fallbackChildFragment3;\n _fallbackChildFragment3.effectTag |= Placement;\n _primaryChildFragment3.childExpirationTime = NoWork; // Skip the primary children, and continue working on the\n // fallback children.\n\n workInProgress.memoizedState = SUSPENDED_MARKER;\n workInProgress.child = _primaryChildFragment3;\n return _fallbackChildFragment3;\n } else {\n // Still haven't timed out. Continue rendering the children, like we\n // normally do.\n workInProgress.memoizedState = null;\n var _nextPrimaryChildren2 = nextProps.children;\n return workInProgress.child = reconcileChildFibers(workInProgress, _currentPrimaryChild, _nextPrimaryChildren2, renderExpirationTime);\n }\n }\n }\n}\n\nfunction scheduleWorkOnFiber(fiber, renderExpirationTime) {\n if (fiber.expirationTime < renderExpirationTime) {\n fiber.expirationTime = renderExpirationTime;\n }\n\n var alternate = fiber.alternate;\n\n if (alternate !== null && alternate.expirationTime < renderExpirationTime) {\n alternate.expirationTime = renderExpirationTime;\n }\n\n scheduleWorkOnParentPath(fiber.return, renderExpirationTime);\n}\n\nfunction propagateSuspenseContextChange(workInProgress, firstChild, renderExpirationTime) {\n // Mark any Suspense boundaries with fallbacks as having work to do.\n // If they were previously forced into fallbacks, they may now be able\n // to unblock.\n var node = firstChild;\n\n while (node !== null) {\n if (node.tag === SuspenseComponent) {\n var state = node.memoizedState;\n\n if (state !== null) {\n scheduleWorkOnFiber(node, renderExpirationTime);\n }\n } else if (node.tag === SuspenseListComponent) {\n // If the tail is hidden there might not be an Suspense boundaries\n // to schedule work on. In this case we have to schedule it on the\n // list itself.\n // We don't have to traverse to the children of the list since\n // the list will propagate the change when it rerenders.\n scheduleWorkOnFiber(node, renderExpirationTime);\n } else if (node.child !== null) {\n node.child.return = node;\n node = node.child;\n continue;\n }\n\n if (node === workInProgress) {\n return;\n }\n\n while (node.sibling === null) {\n if (node.return === null || node.return === workInProgress) {\n return;\n }\n\n node = node.return;\n }\n\n node.sibling.return = node.return;\n node = node.sibling;\n }\n}\n\nfunction findLastContentRow(firstChild) {\n // This is going to find the last row among these children that is already\n // showing content on the screen, as opposed to being in fallback state or\n // new. If a row has multiple Suspense boundaries, any of them being in the\n // fallback state, counts as the whole row being in a fallback state.\n // Note that the \"rows\" will be workInProgress, but any nested children\n // will still be current since we haven't rendered them yet. The mounted\n // order may not be the same as the new order. We use the new order.\n var row = firstChild;\n var lastContentRow = null;\n\n while (row !== null) {\n var currentRow = row.alternate; // New rows can't be content rows.\n\n if (currentRow !== null && findFirstSuspended(currentRow) === null) {\n lastContentRow = row;\n }\n\n row = row.sibling;\n }\n\n return lastContentRow;\n}\n\nfunction validateRevealOrder(revealOrder) {\n {\n if (revealOrder !== undefined && revealOrder !== 'forwards' && revealOrder !== 'backwards' && revealOrder !== 'together' && !didWarnAboutRevealOrder[revealOrder]) {\n didWarnAboutRevealOrder[revealOrder] = true;\n\n if (typeof revealOrder === 'string') {\n switch (revealOrder.toLowerCase()) {\n case 'together':\n case 'forwards':\n case 'backwards':\n {\n error('\"%s\" is not a valid value for revealOrder on <SuspenseList />. ' + 'Use lowercase \"%s\" instead.', revealOrder, revealOrder.toLowerCase());\n\n break;\n }\n\n case 'forward':\n case 'backward':\n {\n error('\"%s\" is not a valid value for revealOrder on <SuspenseList />. ' + 'React uses the -s suffix in the spelling. Use \"%ss\" instead.', revealOrder, revealOrder.toLowerCase());\n\n break;\n }\n\n default:\n error('\"%s\" is not a supported revealOrder on <SuspenseList />. ' + 'Did you mean \"together\", \"forwards\" or \"backwards\"?', revealOrder);\n\n break;\n }\n } else {\n error('%s is not a supported value for revealOrder on <SuspenseList />. ' + 'Did you mean \"together\", \"forwards\" or \"backwards\"?', revealOrder);\n }\n }\n }\n}\n\nfunction validateTailOptions(tailMode, revealOrder) {\n {\n if (tailMode !== undefined && !didWarnAboutTailOptions[tailMode]) {\n if (tailMode !== 'collapsed' && tailMode !== 'hidden') {\n didWarnAboutTailOptions[tailMode] = true;\n\n error('\"%s\" is not a supported value for tail on <SuspenseList />. ' + 'Did you mean \"collapsed\" or \"hidden\"?', tailMode);\n } else if (revealOrder !== 'forwards' && revealOrder !== 'backwards') {\n didWarnAboutTailOptions[tailMode] = true;\n\n error('<SuspenseList tail=\"%s\" /> is only valid if revealOrder is ' + '\"forwards\" or \"backwards\". ' + 'Did you mean to specify revealOrder=\"forwards\"?', tailMode);\n }\n }\n }\n}\n\nfunction validateSuspenseListNestedChild(childSlot, index) {\n {\n var isArray = Array.isArray(childSlot);\n var isIterable = !isArray && typeof getIteratorFn(childSlot) === 'function';\n\n if (isArray || isIterable) {\n var type = isArray ? 'array' : 'iterable';\n\n error('A nested %s was passed to row #%s in <SuspenseList />. Wrap it in ' + 'an additional SuspenseList to configure its revealOrder: ' + '<SuspenseList revealOrder=...> ... ' + '<SuspenseList revealOrder=...>{%s}</SuspenseList> ... ' + '</SuspenseList>', type, index, type);\n\n return false;\n }\n }\n\n return true;\n}\n\nfunction validateSuspenseListChildren(children, revealOrder) {\n {\n if ((revealOrder === 'forwards' || revealOrder === 'backwards') && children !== undefined && children !== null && children !== false) {\n if (Array.isArray(children)) {\n for (var i = 0; i < children.length; i++) {\n if (!validateSuspenseListNestedChild(children[i], i)) {\n return;\n }\n }\n } else {\n var iteratorFn = getIteratorFn(children);\n\n if (typeof iteratorFn === 'function') {\n var childrenIterator = iteratorFn.call(children);\n\n if (childrenIterator) {\n var step = childrenIterator.next();\n var _i = 0;\n\n for (; !step.done; step = childrenIterator.next()) {\n if (!validateSuspenseListNestedChild(step.value, _i)) {\n return;\n }\n\n _i++;\n }\n }\n } else {\n error('A single row was passed to a <SuspenseList revealOrder=\"%s\" />. ' + 'This is not useful since it needs multiple rows. ' + 'Did you mean to pass multiple children or an array?', revealOrder);\n }\n }\n }\n }\n}\n\nfunction initSuspenseListRenderState(workInProgress, isBackwards, tail, lastContentRow, tailMode, lastEffectBeforeRendering) {\n var renderState = workInProgress.memoizedState;\n\n if (renderState === null) {\n workInProgress.memoizedState = {\n isBackwards: isBackwards,\n rendering: null,\n renderingStartTime: 0,\n last: lastContentRow,\n tail: tail,\n tailExpiration: 0,\n tailMode: tailMode,\n lastEffect: lastEffectBeforeRendering\n };\n } else {\n // We can reuse the existing object from previous renders.\n renderState.isBackwards = isBackwards;\n renderState.rendering = null;\n renderState.renderingStartTime = 0;\n renderState.last = lastContentRow;\n renderState.tail = tail;\n renderState.tailExpiration = 0;\n renderState.tailMode = tailMode;\n renderState.lastEffect = lastEffectBeforeRendering;\n }\n} // This can end up rendering this component multiple passes.\n// The first pass splits the children fibers into two sets. A head and tail.\n// We first render the head. If anything is in fallback state, we do another\n// pass through beginWork to rerender all children (including the tail) with\n// the force suspend context. If the first render didn't have anything in\n// in fallback state. Then we render each row in the tail one-by-one.\n// That happens in the completeWork phase without going back to beginWork.\n\n\nfunction updateSuspenseListComponent(current, workInProgress, renderExpirationTime) {\n var nextProps = workInProgress.pendingProps;\n var revealOrder = nextProps.revealOrder;\n var tailMode = nextProps.tail;\n var newChildren = nextProps.children;\n validateRevealOrder(revealOrder);\n validateTailOptions(tailMode, revealOrder);\n validateSuspenseListChildren(newChildren, revealOrder);\n reconcileChildren(current, workInProgress, newChildren, renderExpirationTime);\n var suspenseContext = suspenseStackCursor.current;\n var shouldForceFallback = hasSuspenseContext(suspenseContext, ForceSuspenseFallback);\n\n if (shouldForceFallback) {\n suspenseContext = setShallowSuspenseContext(suspenseContext, ForceSuspenseFallback);\n workInProgress.effectTag |= DidCapture;\n } else {\n var didSuspendBefore = current !== null && (current.effectTag & DidCapture) !== NoEffect;\n\n if (didSuspendBefore) {\n // If we previously forced a fallback, we need to schedule work\n // on any nested boundaries to let them know to try to render\n // again. This is the same as context updating.\n propagateSuspenseContextChange(workInProgress, workInProgress.child, renderExpirationTime);\n }\n\n suspenseContext = setDefaultShallowSuspenseContext(suspenseContext);\n }\n\n pushSuspenseContext(workInProgress, suspenseContext);\n\n if ((workInProgress.mode & BlockingMode) === NoMode) {\n // Outside of blocking mode, SuspenseList doesn't work so we just\n // use make it a noop by treating it as the default revealOrder.\n workInProgress.memoizedState = null;\n } else {\n switch (revealOrder) {\n case 'forwards':\n {\n var lastContentRow = findLastContentRow(workInProgress.child);\n var tail;\n\n if (lastContentRow === null) {\n // The whole list is part of the tail.\n // TODO: We could fast path by just rendering the tail now.\n tail = workInProgress.child;\n workInProgress.child = null;\n } else {\n // Disconnect the tail rows after the content row.\n // We're going to render them separately later.\n tail = lastContentRow.sibling;\n lastContentRow.sibling = null;\n }\n\n initSuspenseListRenderState(workInProgress, false, // isBackwards\n tail, lastContentRow, tailMode, workInProgress.lastEffect);\n break;\n }\n\n case 'backwards':\n {\n // We're going to find the first row that has existing content.\n // At the same time we're going to reverse the list of everything\n // we pass in the meantime. That's going to be our tail in reverse\n // order.\n var _tail = null;\n var row = workInProgress.child;\n workInProgress.child = null;\n\n while (row !== null) {\n var currentRow = row.alternate; // New rows can't be content rows.\n\n if (currentRow !== null && findFirstSuspended(currentRow) === null) {\n // This is the beginning of the main content.\n workInProgress.child = row;\n break;\n }\n\n var nextRow = row.sibling;\n row.sibling = _tail;\n _tail = row;\n row = nextRow;\n } // TODO: If workInProgress.child is null, we can continue on the tail immediately.\n\n\n initSuspenseListRenderState(workInProgress, true, // isBackwards\n _tail, null, // last\n tailMode, workInProgress.lastEffect);\n break;\n }\n\n case 'together':\n {\n initSuspenseListRenderState(workInProgress, false, // isBackwards\n null, // tail\n null, // last\n undefined, workInProgress.lastEffect);\n break;\n }\n\n default:\n {\n // The default reveal order is the same as not having\n // a boundary.\n workInProgress.memoizedState = null;\n }\n }\n }\n\n return workInProgress.child;\n}\n\nfunction updatePortalComponent(current, workInProgress, renderExpirationTime) {\n pushHostContainer(workInProgress, workInProgress.stateNode.containerInfo);\n var nextChildren = workInProgress.pendingProps;\n\n if (current === null) {\n // Portals are special because we don't append the children during mount\n // but at commit. Therefore we need to track insertions which the normal\n // flow doesn't do during mount. This doesn't happen at the root because\n // the root always starts with a \"current\" with a null child.\n // TODO: Consider unifying this with how the root works.\n workInProgress.child = reconcileChildFibers(workInProgress, null, nextChildren, renderExpirationTime);\n } else {\n reconcileChildren(current, workInProgress, nextChildren, renderExpirationTime);\n }\n\n return workInProgress.child;\n}\n\nfunction updateContextProvider(current, workInProgress, renderExpirationTime) {\n var providerType = workInProgress.type;\n var context = providerType._context;\n var newProps = workInProgress.pendingProps;\n var oldProps = workInProgress.memoizedProps;\n var newValue = newProps.value;\n\n {\n var providerPropTypes = workInProgress.type.propTypes;\n\n if (providerPropTypes) {\n checkPropTypes(providerPropTypes, newProps, 'prop', 'Context.Provider', getCurrentFiberStackInDev);\n }\n }\n\n pushProvider(workInProgress, newValue);\n\n if (oldProps !== null) {\n var oldValue = oldProps.value;\n var changedBits = calculateChangedBits(context, newValue, oldValue);\n\n if (changedBits === 0) {\n // No change. Bailout early if children are the same.\n if (oldProps.children === newProps.children && !hasContextChanged()) {\n return bailoutOnAlreadyFinishedWork(current, workInProgress, renderExpirationTime);\n }\n } else {\n // The context value changed. Search for matching consumers and schedule\n // them to update.\n propagateContextChange(workInProgress, context, changedBits, renderExpirationTime);\n }\n }\n\n var newChildren = newProps.children;\n reconcileChildren(current, workInProgress, newChildren, renderExpirationTime);\n return workInProgress.child;\n}\n\nvar hasWarnedAboutUsingContextAsConsumer = false;\n\nfunction updateContextConsumer(current, workInProgress, renderExpirationTime) {\n var context = workInProgress.type; // The logic below for Context differs depending on PROD or DEV mode. In\n // DEV mode, we create a separate object for Context.Consumer that acts\n // like a proxy to Context. This proxy object adds unnecessary code in PROD\n // so we use the old behaviour (Context.Consumer references Context) to\n // reduce size and overhead. The separate object references context via\n // a property called \"_context\", which also gives us the ability to check\n // in DEV mode if this property exists or not and warn if it does not.\n\n {\n if (context._context === undefined) {\n // This may be because it's a Context (rather than a Consumer).\n // Or it may be because it's older React where they're the same thing.\n // We only want to warn if we're sure it's a new React.\n if (context !== context.Consumer) {\n if (!hasWarnedAboutUsingContextAsConsumer) {\n hasWarnedAboutUsingContextAsConsumer = true;\n\n error('Rendering <Context> directly is not supported and will be removed in ' + 'a future major release. Did you mean to render <Context.Consumer> instead?');\n }\n }\n } else {\n context = context._context;\n }\n }\n\n var newProps = workInProgress.pendingProps;\n var render = newProps.children;\n\n {\n if (typeof render !== 'function') {\n error('A context consumer was rendered with multiple children, or a child ' + \"that isn't a function. A context consumer expects a single child \" + 'that is a function. If you did pass a function, make sure there ' + 'is no trailing or leading whitespace around it.');\n }\n }\n\n prepareToReadContext(workInProgress, renderExpirationTime);\n var newValue = readContext(context, newProps.unstable_observedBits);\n var newChildren;\n\n {\n ReactCurrentOwner$1.current = workInProgress;\n setIsRendering(true);\n newChildren = render(newValue);\n setIsRendering(false);\n } // React DevTools reads this flag.\n\n\n workInProgress.effectTag |= PerformedWork;\n reconcileChildren(current, workInProgress, newChildren, renderExpirationTime);\n return workInProgress.child;\n}\n\nfunction markWorkInProgressReceivedUpdate() {\n didReceiveUpdate = true;\n}\n\nfunction bailoutOnAlreadyFinishedWork(current, workInProgress, renderExpirationTime) {\n cancelWorkTimer(workInProgress);\n\n if (current !== null) {\n // Reuse previous dependencies\n workInProgress.dependencies = current.dependencies;\n }\n\n {\n // Don't update \"base\" render times for bailouts.\n stopProfilerTimerIfRunning();\n }\n\n var updateExpirationTime = workInProgress.expirationTime;\n\n if (updateExpirationTime !== NoWork) {\n markUnprocessedUpdateTime(updateExpirationTime);\n } // Check if the children have any pending work.\n\n\n var childExpirationTime = workInProgress.childExpirationTime;\n\n if (childExpirationTime < renderExpirationTime) {\n // The children don't have any work either. We can skip them.\n // TODO: Once we add back resuming, we should check if the children are\n // a work-in-progress set. If so, we need to transfer their effects.\n return null;\n } else {\n // This fiber doesn't have work, but its subtree does. Clone the child\n // fibers and continue.\n cloneChildFibers(current, workInProgress);\n return workInProgress.child;\n }\n}\n\nfunction remountFiber(current, oldWorkInProgress, newWorkInProgress) {\n {\n var returnFiber = oldWorkInProgress.return;\n\n if (returnFiber === null) {\n throw new Error('Cannot swap the root fiber.');\n } // Disconnect from the old current.\n // It will get deleted.\n\n\n current.alternate = null;\n oldWorkInProgress.alternate = null; // Connect to the new tree.\n\n newWorkInProgress.index = oldWorkInProgress.index;\n newWorkInProgress.sibling = oldWorkInProgress.sibling;\n newWorkInProgress.return = oldWorkInProgress.return;\n newWorkInProgress.ref = oldWorkInProgress.ref; // Replace the child/sibling pointers above it.\n\n if (oldWorkInProgress === returnFiber.child) {\n returnFiber.child = newWorkInProgress;\n } else {\n var prevSibling = returnFiber.child;\n\n if (prevSibling === null) {\n throw new Error('Expected parent to have a child.');\n }\n\n while (prevSibling.sibling !== oldWorkInProgress) {\n prevSibling = prevSibling.sibling;\n\n if (prevSibling === null) {\n throw new Error('Expected to find the previous sibling.');\n }\n }\n\n prevSibling.sibling = newWorkInProgress;\n } // Delete the old fiber and place the new one.\n // Since the old fiber is disconnected, we have to schedule it manually.\n\n\n var last = returnFiber.lastEffect;\n\n if (last !== null) {\n last.nextEffect = current;\n returnFiber.lastEffect = current;\n } else {\n returnFiber.firstEffect = returnFiber.lastEffect = current;\n }\n\n current.nextEffect = null;\n current.effectTag = Deletion;\n newWorkInProgress.effectTag |= Placement; // Restart work from the new fiber.\n\n return newWorkInProgress;\n }\n}\n\nfunction beginWork(current, workInProgress, renderExpirationTime) {\n var updateExpirationTime = workInProgress.expirationTime;\n\n {\n if (workInProgress._debugNeedsRemount && current !== null) {\n // This will restart the begin phase with a new fiber.\n return remountFiber(current, workInProgress, createFiberFromTypeAndProps(workInProgress.type, workInProgress.key, workInProgress.pendingProps, workInProgress._debugOwner || null, workInProgress.mode, workInProgress.expirationTime));\n }\n }\n\n if (current !== null) {\n var oldProps = current.memoizedProps;\n var newProps = workInProgress.pendingProps;\n\n if (oldProps !== newProps || hasContextChanged() || ( // Force a re-render if the implementation changed due to hot reload:\n workInProgress.type !== current.type )) {\n // If props or context changed, mark the fiber as having performed work.\n // This may be unset if the props are determined to be equal later (memo).\n didReceiveUpdate = true;\n } else if (updateExpirationTime < renderExpirationTime) {\n didReceiveUpdate = false; // This fiber does not have any pending work. Bailout without entering\n // the begin phase. There's still some bookkeeping we that needs to be done\n // in this optimized path, mostly pushing stuff onto the stack.\n\n switch (workInProgress.tag) {\n case HostRoot:\n pushHostRootContext(workInProgress);\n resetHydrationState();\n break;\n\n case HostComponent:\n pushHostContext(workInProgress);\n\n if (workInProgress.mode & ConcurrentMode && renderExpirationTime !== Never && shouldDeprioritizeSubtree(workInProgress.type, newProps)) {\n {\n markSpawnedWork(Never);\n } // Schedule this fiber to re-render at offscreen priority. Then bailout.\n\n\n workInProgress.expirationTime = workInProgress.childExpirationTime = Never;\n return null;\n }\n\n break;\n\n case ClassComponent:\n {\n var Component = workInProgress.type;\n\n if (isContextProvider(Component)) {\n pushContextProvider(workInProgress);\n }\n\n break;\n }\n\n case HostPortal:\n pushHostContainer(workInProgress, workInProgress.stateNode.containerInfo);\n break;\n\n case ContextProvider:\n {\n var newValue = workInProgress.memoizedProps.value;\n pushProvider(workInProgress, newValue);\n break;\n }\n\n case Profiler:\n {\n // Profiler should only call onRender when one of its descendants actually rendered.\n var hasChildWork = workInProgress.childExpirationTime >= renderExpirationTime;\n\n if (hasChildWork) {\n workInProgress.effectTag |= Update;\n }\n }\n\n break;\n\n case SuspenseComponent:\n {\n var state = workInProgress.memoizedState;\n\n if (state !== null) {\n // whether to retry the primary children, or to skip over it and\n // go straight to the fallback. Check the priority of the primary\n // child fragment.\n\n\n var primaryChildFragment = workInProgress.child;\n var primaryChildExpirationTime = primaryChildFragment.childExpirationTime;\n\n if (primaryChildExpirationTime !== NoWork && primaryChildExpirationTime >= renderExpirationTime) {\n // The primary children have pending work. Use the normal path\n // to attempt to render the primary children again.\n return updateSuspenseComponent(current, workInProgress, renderExpirationTime);\n } else {\n pushSuspenseContext(workInProgress, setDefaultShallowSuspenseContext(suspenseStackCursor.current)); // The primary children do not have pending work with sufficient\n // priority. Bailout.\n\n var child = bailoutOnAlreadyFinishedWork(current, workInProgress, renderExpirationTime);\n\n if (child !== null) {\n // The fallback children have pending work. Skip over the\n // primary children and work on the fallback.\n return child.sibling;\n } else {\n return null;\n }\n }\n } else {\n pushSuspenseContext(workInProgress, setDefaultShallowSuspenseContext(suspenseStackCursor.current));\n }\n\n break;\n }\n\n case SuspenseListComponent:\n {\n var didSuspendBefore = (current.effectTag & DidCapture) !== NoEffect;\n\n var _hasChildWork = workInProgress.childExpirationTime >= renderExpirationTime;\n\n if (didSuspendBefore) {\n if (_hasChildWork) {\n // If something was in fallback state last time, and we have all the\n // same children then we're still in progressive loading state.\n // Something might get unblocked by state updates or retries in the\n // tree which will affect the tail. So we need to use the normal\n // path to compute the correct tail.\n return updateSuspenseListComponent(current, workInProgress, renderExpirationTime);\n } // If none of the children had any work, that means that none of\n // them got retried so they'll still be blocked in the same way\n // as before. We can fast bail out.\n\n\n workInProgress.effectTag |= DidCapture;\n } // If nothing suspended before and we're rendering the same children,\n // then the tail doesn't matter. Anything new that suspends will work\n // in the \"together\" mode, so we can continue from the state we had.\n\n\n var renderState = workInProgress.memoizedState;\n\n if (renderState !== null) {\n // Reset to the \"together\" mode in case we've started a different\n // update in the past but didn't complete it.\n renderState.rendering = null;\n renderState.tail = null;\n }\n\n pushSuspenseContext(workInProgress, suspenseStackCursor.current);\n\n if (_hasChildWork) {\n break;\n } else {\n // If none of the children had any work, that means that none of\n // them got retried so they'll still be blocked in the same way\n // as before. We can fast bail out.\n return null;\n }\n }\n }\n\n return bailoutOnAlreadyFinishedWork(current, workInProgress, renderExpirationTime);\n } else {\n // An update was scheduled on this fiber, but there are no new props\n // nor legacy context. Set this to false. If an update queue or context\n // consumer produces a changed value, it will set this to true. Otherwise,\n // the component will assume the children have not changed and bail out.\n didReceiveUpdate = false;\n }\n } else {\n didReceiveUpdate = false;\n } // Before entering the begin phase, clear pending update priority.\n // TODO: This assumes that we're about to evaluate the component and process\n // the update queue. However, there's an exception: SimpleMemoComponent\n // sometimes bails out later in the begin phase. This indicates that we should\n // move this assignment out of the common path and into each branch.\n\n\n workInProgress.expirationTime = NoWork;\n\n switch (workInProgress.tag) {\n case IndeterminateComponent:\n {\n return mountIndeterminateComponent(current, workInProgress, workInProgress.type, renderExpirationTime);\n }\n\n case LazyComponent:\n {\n var elementType = workInProgress.elementType;\n return mountLazyComponent(current, workInProgress, elementType, updateExpirationTime, renderExpirationTime);\n }\n\n case FunctionComponent:\n {\n var _Component = workInProgress.type;\n var unresolvedProps = workInProgress.pendingProps;\n var resolvedProps = workInProgress.elementType === _Component ? unresolvedProps : resolveDefaultProps(_Component, unresolvedProps);\n return updateFunctionComponent(current, workInProgress, _Component, resolvedProps, renderExpirationTime);\n }\n\n case ClassComponent:\n {\n var _Component2 = workInProgress.type;\n var _unresolvedProps = workInProgress.pendingProps;\n\n var _resolvedProps = workInProgress.elementType === _Component2 ? _unresolvedProps : resolveDefaultProps(_Component2, _unresolvedProps);\n\n return updateClassComponent(current, workInProgress, _Component2, _resolvedProps, renderExpirationTime);\n }\n\n case HostRoot:\n return updateHostRoot(current, workInProgress, renderExpirationTime);\n\n case HostComponent:\n return updateHostComponent(current, workInProgress, renderExpirationTime);\n\n case HostText:\n return updateHostText(current, workInProgress);\n\n case SuspenseComponent:\n return updateSuspenseComponent(current, workInProgress, renderExpirationTime);\n\n case HostPortal:\n return updatePortalComponent(current, workInProgress, renderExpirationTime);\n\n case ForwardRef:\n {\n var type = workInProgress.type;\n var _unresolvedProps2 = workInProgress.pendingProps;\n\n var _resolvedProps2 = workInProgress.elementType === type ? _unresolvedProps2 : resolveDefaultProps(type, _unresolvedProps2);\n\n return updateForwardRef(current, workInProgress, type, _resolvedProps2, renderExpirationTime);\n }\n\n case Fragment:\n return updateFragment(current, workInProgress, renderExpirationTime);\n\n case Mode:\n return updateMode(current, workInProgress, renderExpirationTime);\n\n case Profiler:\n return updateProfiler(current, workInProgress, renderExpirationTime);\n\n case ContextProvider:\n return updateContextProvider(current, workInProgress, renderExpirationTime);\n\n case ContextConsumer:\n return updateContextConsumer(current, workInProgress, renderExpirationTime);\n\n case MemoComponent:\n {\n var _type2 = workInProgress.type;\n var _unresolvedProps3 = workInProgress.pendingProps; // Resolve outer props first, then resolve inner props.\n\n var _resolvedProps3 = resolveDefaultProps(_type2, _unresolvedProps3);\n\n {\n if (workInProgress.type !== workInProgress.elementType) {\n var outerPropTypes = _type2.propTypes;\n\n if (outerPropTypes) {\n checkPropTypes(outerPropTypes, _resolvedProps3, // Resolved for outer only\n 'prop', getComponentName(_type2), getCurrentFiberStackInDev);\n }\n }\n }\n\n _resolvedProps3 = resolveDefaultProps(_type2.type, _resolvedProps3);\n return updateMemoComponent(current, workInProgress, _type2, _resolvedProps3, updateExpirationTime, renderExpirationTime);\n }\n\n case SimpleMemoComponent:\n {\n return updateSimpleMemoComponent(current, workInProgress, workInProgress.type, workInProgress.pendingProps, updateExpirationTime, renderExpirationTime);\n }\n\n case IncompleteClassComponent:\n {\n var _Component3 = workInProgress.type;\n var _unresolvedProps4 = workInProgress.pendingProps;\n\n var _resolvedProps4 = workInProgress.elementType === _Component3 ? _unresolvedProps4 : resolveDefaultProps(_Component3, _unresolvedProps4);\n\n return mountIncompleteClassComponent(current, workInProgress, _Component3, _resolvedProps4, renderExpirationTime);\n }\n\n case SuspenseListComponent:\n {\n return updateSuspenseListComponent(current, workInProgress, renderExpirationTime);\n }\n }\n\n {\n {\n throw Error( \"Unknown unit of work tag (\" + workInProgress.tag + \"). This error is likely caused by a bug in React. Please file an issue.\" );\n }\n }\n}\n\nfunction markUpdate(workInProgress) {\n // Tag the fiber with an update effect. This turns a Placement into\n // a PlacementAndUpdate.\n workInProgress.effectTag |= Update;\n}\n\nfunction markRef$1(workInProgress) {\n workInProgress.effectTag |= Ref;\n}\n\nvar appendAllChildren;\nvar updateHostContainer;\nvar updateHostComponent$1;\nvar updateHostText$1;\n\n{\n // Mutation mode\n appendAllChildren = function (parent, workInProgress, needsVisibilityToggle, isHidden) {\n // We only have the top Fiber that was created but we need recurse down its\n // children to find all the terminal nodes.\n var node = workInProgress.child;\n\n while (node !== null) {\n if (node.tag === HostComponent || node.tag === HostText) {\n appendInitialChild(parent, node.stateNode);\n } else if (node.tag === HostPortal) ; else if (node.child !== null) {\n node.child.return = node;\n node = node.child;\n continue;\n }\n\n if (node === workInProgress) {\n return;\n }\n\n while (node.sibling === null) {\n if (node.return === null || node.return === workInProgress) {\n return;\n }\n\n node = node.return;\n }\n\n node.sibling.return = node.return;\n node = node.sibling;\n }\n };\n\n updateHostContainer = function (workInProgress) {// Noop\n };\n\n updateHostComponent$1 = function (current, workInProgress, type, newProps, rootContainerInstance) {\n // If we have an alternate, that means this is an update and we need to\n // schedule a side-effect to do the updates.\n var oldProps = current.memoizedProps;\n\n if (oldProps === newProps) {\n // In mutation mode, this is sufficient for a bailout because\n // we won't touch this node even if children changed.\n return;\n } // If we get updated because one of our children updated, we don't\n // have newProps so we'll have to reuse them.\n // TODO: Split the update API as separate for the props vs. children.\n // Even better would be if children weren't special cased at all tho.\n\n\n var instance = workInProgress.stateNode;\n var currentHostContext = getHostContext(); // TODO: Experiencing an error where oldProps is null. Suggests a host\n // component is hitting the resume path. Figure out why. Possibly\n // related to `hidden`.\n\n var updatePayload = prepareUpdate(instance, type, oldProps, newProps, rootContainerInstance, currentHostContext); // TODO: Type this specific to this type of component.\n\n workInProgress.updateQueue = updatePayload; // If the update payload indicates that there is a change or if there\n // is a new ref we mark this as an update. All the work is done in commitWork.\n\n if (updatePayload) {\n markUpdate(workInProgress);\n }\n };\n\n updateHostText$1 = function (current, workInProgress, oldText, newText) {\n // If the text differs, mark it as an update. All the work in done in commitWork.\n if (oldText !== newText) {\n markUpdate(workInProgress);\n }\n };\n}\n\nfunction cutOffTailIfNeeded(renderState, hasRenderedATailFallback) {\n switch (renderState.tailMode) {\n case 'hidden':\n {\n // Any insertions at the end of the tail list after this point\n // should be invisible. If there are already mounted boundaries\n // anything before them are not considered for collapsing.\n // Therefore we need to go through the whole tail to find if\n // there are any.\n var tailNode = renderState.tail;\n var lastTailNode = null;\n\n while (tailNode !== null) {\n if (tailNode.alternate !== null) {\n lastTailNode = tailNode;\n }\n\n tailNode = tailNode.sibling;\n } // Next we're simply going to delete all insertions after the\n // last rendered item.\n\n\n if (lastTailNode === null) {\n // All remaining items in the tail are insertions.\n renderState.tail = null;\n } else {\n // Detach the insertion after the last node that was already\n // inserted.\n lastTailNode.sibling = null;\n }\n\n break;\n }\n\n case 'collapsed':\n {\n // Any insertions at the end of the tail list after this point\n // should be invisible. If there are already mounted boundaries\n // anything before them are not considered for collapsing.\n // Therefore we need to go through the whole tail to find if\n // there are any.\n var _tailNode = renderState.tail;\n var _lastTailNode = null;\n\n while (_tailNode !== null) {\n if (_tailNode.alternate !== null) {\n _lastTailNode = _tailNode;\n }\n\n _tailNode = _tailNode.sibling;\n } // Next we're simply going to delete all insertions after the\n // last rendered item.\n\n\n if (_lastTailNode === null) {\n // All remaining items in the tail are insertions.\n if (!hasRenderedATailFallback && renderState.tail !== null) {\n // We suspended during the head. We want to show at least one\n // row at the tail. So we'll keep on and cut off the rest.\n renderState.tail.sibling = null;\n } else {\n renderState.tail = null;\n }\n } else {\n // Detach the insertion after the last node that was already\n // inserted.\n _lastTailNode.sibling = null;\n }\n\n break;\n }\n }\n}\n\nfunction completeWork(current, workInProgress, renderExpirationTime) {\n var newProps = workInProgress.pendingProps;\n\n switch (workInProgress.tag) {\n case IndeterminateComponent:\n case LazyComponent:\n case SimpleMemoComponent:\n case FunctionComponent:\n case ForwardRef:\n case Fragment:\n case Mode:\n case Profiler:\n case ContextConsumer:\n case MemoComponent:\n return null;\n\n case ClassComponent:\n {\n var Component = workInProgress.type;\n\n if (isContextProvider(Component)) {\n popContext(workInProgress);\n }\n\n return null;\n }\n\n case HostRoot:\n {\n popHostContainer(workInProgress);\n popTopLevelContextObject(workInProgress);\n var fiberRoot = workInProgress.stateNode;\n\n if (fiberRoot.pendingContext) {\n fiberRoot.context = fiberRoot.pendingContext;\n fiberRoot.pendingContext = null;\n }\n\n if (current === null || current.child === null) {\n // If we hydrated, pop so that we can delete any remaining children\n // that weren't hydrated.\n var wasHydrated = popHydrationState(workInProgress);\n\n if (wasHydrated) {\n // If we hydrated, then we'll need to schedule an update for\n // the commit side-effects on the root.\n markUpdate(workInProgress);\n }\n }\n\n updateHostContainer(workInProgress);\n return null;\n }\n\n case HostComponent:\n {\n popHostContext(workInProgress);\n var rootContainerInstance = getRootHostContainer();\n var type = workInProgress.type;\n\n if (current !== null && workInProgress.stateNode != null) {\n updateHostComponent$1(current, workInProgress, type, newProps, rootContainerInstance);\n\n if (current.ref !== workInProgress.ref) {\n markRef$1(workInProgress);\n }\n } else {\n if (!newProps) {\n if (!(workInProgress.stateNode !== null)) {\n {\n throw Error( \"We must have new props for new mounts. This error is likely caused by a bug in React. Please file an issue.\" );\n }\n } // This can happen when we abort work.\n\n\n return null;\n }\n\n var currentHostContext = getHostContext(); // TODO: Move createInstance to beginWork and keep it on a context\n // \"stack\" as the parent. Then append children as we go in beginWork\n // or completeWork depending on whether we want to add them top->down or\n // bottom->up. Top->down is faster in IE11.\n\n var _wasHydrated = popHydrationState(workInProgress);\n\n if (_wasHydrated) {\n // TODO: Move this and createInstance step into the beginPhase\n // to consolidate.\n if (prepareToHydrateHostInstance(workInProgress, rootContainerInstance, currentHostContext)) {\n // If changes to the hydrated node need to be applied at the\n // commit-phase we mark this as such.\n markUpdate(workInProgress);\n }\n } else {\n var instance = createInstance(type, newProps, rootContainerInstance, currentHostContext, workInProgress);\n appendAllChildren(instance, workInProgress, false, false); // This needs to be set before we mount Flare event listeners\n\n workInProgress.stateNode = instance;\n // (eg DOM renderer supports auto-focus for certain elements).\n // Make sure such renderers get scheduled for later work.\n\n\n if (finalizeInitialChildren(instance, type, newProps, rootContainerInstance)) {\n markUpdate(workInProgress);\n }\n }\n\n if (workInProgress.ref !== null) {\n // If there is a ref on a host node we need to schedule a callback\n markRef$1(workInProgress);\n }\n }\n\n return null;\n }\n\n case HostText:\n {\n var newText = newProps;\n\n if (current && workInProgress.stateNode != null) {\n var oldText = current.memoizedProps; // If we have an alternate, that means this is an update and we need\n // to schedule a side-effect to do the updates.\n\n updateHostText$1(current, workInProgress, oldText, newText);\n } else {\n if (typeof newText !== 'string') {\n if (!(workInProgress.stateNode !== null)) {\n {\n throw Error( \"We must have new props for new mounts. This error is likely caused by a bug in React. Please file an issue.\" );\n }\n } // This can happen when we abort work.\n\n }\n\n var _rootContainerInstance = getRootHostContainer();\n\n var _currentHostContext = getHostContext();\n\n var _wasHydrated2 = popHydrationState(workInProgress);\n\n if (_wasHydrated2) {\n if (prepareToHydrateHostTextInstance(workInProgress)) {\n markUpdate(workInProgress);\n }\n } else {\n workInProgress.stateNode = createTextInstance(newText, _rootContainerInstance, _currentHostContext, workInProgress);\n }\n }\n\n return null;\n }\n\n case SuspenseComponent:\n {\n popSuspenseContext(workInProgress);\n var nextState = workInProgress.memoizedState;\n\n if ((workInProgress.effectTag & DidCapture) !== NoEffect) {\n // Something suspended. Re-render with the fallback children.\n workInProgress.expirationTime = renderExpirationTime; // Do not reset the effect list.\n\n return workInProgress;\n }\n\n var nextDidTimeout = nextState !== null;\n var prevDidTimeout = false;\n\n if (current === null) {\n if (workInProgress.memoizedProps.fallback !== undefined) {\n popHydrationState(workInProgress);\n }\n } else {\n var prevState = current.memoizedState;\n prevDidTimeout = prevState !== null;\n\n if (!nextDidTimeout && prevState !== null) {\n // We just switched from the fallback to the normal children.\n // Delete the fallback.\n // TODO: Would it be better to store the fallback fragment on\n // the stateNode during the begin phase?\n var currentFallbackChild = current.child.sibling;\n\n if (currentFallbackChild !== null) {\n // Deletions go at the beginning of the return fiber's effect list\n var first = workInProgress.firstEffect;\n\n if (first !== null) {\n workInProgress.firstEffect = currentFallbackChild;\n currentFallbackChild.nextEffect = first;\n } else {\n workInProgress.firstEffect = workInProgress.lastEffect = currentFallbackChild;\n currentFallbackChild.nextEffect = null;\n }\n\n currentFallbackChild.effectTag = Deletion;\n }\n }\n }\n\n if (nextDidTimeout && !prevDidTimeout) {\n // If this subtreee is running in blocking mode we can suspend,\n // otherwise we won't suspend.\n // TODO: This will still suspend a synchronous tree if anything\n // in the concurrent tree already suspended during this render.\n // This is a known bug.\n if ((workInProgress.mode & BlockingMode) !== NoMode) {\n // TODO: Move this back to throwException because this is too late\n // if this is a large tree which is common for initial loads. We\n // don't know if we should restart a render or not until we get\n // this marker, and this is too late.\n // If this render already had a ping or lower pri updates,\n // and this is the first time we know we're going to suspend we\n // should be able to immediately restart from within throwException.\n var hasInvisibleChildContext = current === null && workInProgress.memoizedProps.unstable_avoidThisFallback !== true;\n\n if (hasInvisibleChildContext || hasSuspenseContext(suspenseStackCursor.current, InvisibleParentSuspenseContext)) {\n // If this was in an invisible tree or a new render, then showing\n // this boundary is ok.\n renderDidSuspend();\n } else {\n // Otherwise, we're going to have to hide content so we should\n // suspend for longer if possible.\n renderDidSuspendDelayIfPossible();\n }\n }\n }\n\n {\n // TODO: Only schedule updates if these values are non equal, i.e. it changed.\n if (nextDidTimeout || prevDidTimeout) {\n // If this boundary just timed out, schedule an effect to attach a\n // retry listener to the promise. This flag is also used to hide the\n // primary children. In mutation mode, we also need the flag to\n // *unhide* children that were previously hidden, so check if this\n // is currently timed out, too.\n workInProgress.effectTag |= Update;\n }\n }\n\n return null;\n }\n\n case HostPortal:\n popHostContainer(workInProgress);\n updateHostContainer(workInProgress);\n return null;\n\n case ContextProvider:\n // Pop provider fiber\n popProvider(workInProgress);\n return null;\n\n case IncompleteClassComponent:\n {\n // Same as class component case. I put it down here so that the tags are\n // sequential to ensure this switch is compiled to a jump table.\n var _Component = workInProgress.type;\n\n if (isContextProvider(_Component)) {\n popContext(workInProgress);\n }\n\n return null;\n }\n\n case SuspenseListComponent:\n {\n popSuspenseContext(workInProgress);\n var renderState = workInProgress.memoizedState;\n\n if (renderState === null) {\n // We're running in the default, \"independent\" mode.\n // We don't do anything in this mode.\n return null;\n }\n\n var didSuspendAlready = (workInProgress.effectTag & DidCapture) !== NoEffect;\n var renderedTail = renderState.rendering;\n\n if (renderedTail === null) {\n // We just rendered the head.\n if (!didSuspendAlready) {\n // This is the first pass. We need to figure out if anything is still\n // suspended in the rendered set.\n // If new content unsuspended, but there's still some content that\n // didn't. Then we need to do a second pass that forces everything\n // to keep showing their fallbacks.\n // We might be suspended if something in this render pass suspended, or\n // something in the previous committed pass suspended. Otherwise,\n // there's no chance so we can skip the expensive call to\n // findFirstSuspended.\n var cannotBeSuspended = renderHasNotSuspendedYet() && (current === null || (current.effectTag & DidCapture) === NoEffect);\n\n if (!cannotBeSuspended) {\n var row = workInProgress.child;\n\n while (row !== null) {\n var suspended = findFirstSuspended(row);\n\n if (suspended !== null) {\n didSuspendAlready = true;\n workInProgress.effectTag |= DidCapture;\n cutOffTailIfNeeded(renderState, false); // If this is a newly suspended tree, it might not get committed as\n // part of the second pass. In that case nothing will subscribe to\n // its thennables. Instead, we'll transfer its thennables to the\n // SuspenseList so that it can retry if they resolve.\n // There might be multiple of these in the list but since we're\n // going to wait for all of them anyway, it doesn't really matter\n // which ones gets to ping. In theory we could get clever and keep\n // track of how many dependencies remain but it gets tricky because\n // in the meantime, we can add/remove/change items and dependencies.\n // We might bail out of the loop before finding any but that\n // doesn't matter since that means that the other boundaries that\n // we did find already has their listeners attached.\n\n var newThennables = suspended.updateQueue;\n\n if (newThennables !== null) {\n workInProgress.updateQueue = newThennables;\n workInProgress.effectTag |= Update;\n } // Rerender the whole list, but this time, we'll force fallbacks\n // to stay in place.\n // Reset the effect list before doing the second pass since that's now invalid.\n\n\n if (renderState.lastEffect === null) {\n workInProgress.firstEffect = null;\n }\n\n workInProgress.lastEffect = renderState.lastEffect; // Reset the child fibers to their original state.\n\n resetChildFibers(workInProgress, renderExpirationTime); // Set up the Suspense Context to force suspense and immediately\n // rerender the children.\n\n pushSuspenseContext(workInProgress, setShallowSuspenseContext(suspenseStackCursor.current, ForceSuspenseFallback));\n return workInProgress.child;\n }\n\n row = row.sibling;\n }\n }\n } else {\n cutOffTailIfNeeded(renderState, false);\n } // Next we're going to render the tail.\n\n } else {\n // Append the rendered row to the child list.\n if (!didSuspendAlready) {\n var _suspended = findFirstSuspended(renderedTail);\n\n if (_suspended !== null) {\n workInProgress.effectTag |= DidCapture;\n didSuspendAlready = true; // Ensure we transfer the update queue to the parent so that it doesn't\n // get lost if this row ends up dropped during a second pass.\n\n var _newThennables = _suspended.updateQueue;\n\n if (_newThennables !== null) {\n workInProgress.updateQueue = _newThennables;\n workInProgress.effectTag |= Update;\n }\n\n cutOffTailIfNeeded(renderState, true); // This might have been modified.\n\n if (renderState.tail === null && renderState.tailMode === 'hidden' && !renderedTail.alternate) {\n // We need to delete the row we just rendered.\n // Reset the effect list to what it was before we rendered this\n // child. The nested children have already appended themselves.\n var lastEffect = workInProgress.lastEffect = renderState.lastEffect; // Remove any effects that were appended after this point.\n\n if (lastEffect !== null) {\n lastEffect.nextEffect = null;\n } // We're done.\n\n\n return null;\n }\n } else if ( // The time it took to render last row is greater than time until\n // the expiration.\n now() * 2 - renderState.renderingStartTime > renderState.tailExpiration && renderExpirationTime > Never) {\n // We have now passed our CPU deadline and we'll just give up further\n // attempts to render the main content and only render fallbacks.\n // The assumption is that this is usually faster.\n workInProgress.effectTag |= DidCapture;\n didSuspendAlready = true;\n cutOffTailIfNeeded(renderState, false); // Since nothing actually suspended, there will nothing to ping this\n // to get it started back up to attempt the next item. If we can show\n // them, then they really have the same priority as this render.\n // So we'll pick it back up the very next render pass once we've had\n // an opportunity to yield for paint.\n\n var nextPriority = renderExpirationTime - 1;\n workInProgress.expirationTime = workInProgress.childExpirationTime = nextPriority;\n\n {\n markSpawnedWork(nextPriority);\n }\n }\n }\n\n if (renderState.isBackwards) {\n // The effect list of the backwards tail will have been added\n // to the end. This breaks the guarantee that life-cycles fire in\n // sibling order but that isn't a strong guarantee promised by React.\n // Especially since these might also just pop in during future commits.\n // Append to the beginning of the list.\n renderedTail.sibling = workInProgress.child;\n workInProgress.child = renderedTail;\n } else {\n var previousSibling = renderState.last;\n\n if (previousSibling !== null) {\n previousSibling.sibling = renderedTail;\n } else {\n workInProgress.child = renderedTail;\n }\n\n renderState.last = renderedTail;\n }\n }\n\n if (renderState.tail !== null) {\n // We still have tail rows to render.\n if (renderState.tailExpiration === 0) {\n // Heuristic for how long we're willing to spend rendering rows\n // until we just give up and show what we have so far.\n var TAIL_EXPIRATION_TIMEOUT_MS = 500;\n renderState.tailExpiration = now() + TAIL_EXPIRATION_TIMEOUT_MS; // TODO: This is meant to mimic the train model or JND but this\n // is a per component value. It should really be since the start\n // of the total render or last commit. Consider using something like\n // globalMostRecentFallbackTime. That doesn't account for being\n // suspended for part of the time or when it's a new render.\n // It should probably use a global start time value instead.\n } // Pop a row.\n\n\n var next = renderState.tail;\n renderState.rendering = next;\n renderState.tail = next.sibling;\n renderState.lastEffect = workInProgress.lastEffect;\n renderState.renderingStartTime = now();\n next.sibling = null; // Restore the context.\n // TODO: We can probably just avoid popping it instead and only\n // setting it the first time we go from not suspended to suspended.\n\n var suspenseContext = suspenseStackCursor.current;\n\n if (didSuspendAlready) {\n suspenseContext = setShallowSuspenseContext(suspenseContext, ForceSuspenseFallback);\n } else {\n suspenseContext = setDefaultShallowSuspenseContext(suspenseContext);\n }\n\n pushSuspenseContext(workInProgress, suspenseContext); // Do a pass over the next row.\n\n return next;\n }\n\n return null;\n }\n }\n\n {\n {\n throw Error( \"Unknown unit of work tag (\" + workInProgress.tag + \"). This error is likely caused by a bug in React. Please file an issue.\" );\n }\n }\n}\n\nfunction unwindWork(workInProgress, renderExpirationTime) {\n switch (workInProgress.tag) {\n case ClassComponent:\n {\n var Component = workInProgress.type;\n\n if (isContextProvider(Component)) {\n popContext(workInProgress);\n }\n\n var effectTag = workInProgress.effectTag;\n\n if (effectTag & ShouldCapture) {\n workInProgress.effectTag = effectTag & ~ShouldCapture | DidCapture;\n return workInProgress;\n }\n\n return null;\n }\n\n case HostRoot:\n {\n popHostContainer(workInProgress);\n popTopLevelContextObject(workInProgress);\n var _effectTag = workInProgress.effectTag;\n\n if (!((_effectTag & DidCapture) === NoEffect)) {\n {\n throw Error( \"The root failed to unmount after an error. This is likely a bug in React. Please file an issue.\" );\n }\n }\n\n workInProgress.effectTag = _effectTag & ~ShouldCapture | DidCapture;\n return workInProgress;\n }\n\n case HostComponent:\n {\n // TODO: popHydrationState\n popHostContext(workInProgress);\n return null;\n }\n\n case SuspenseComponent:\n {\n popSuspenseContext(workInProgress);\n\n var _effectTag2 = workInProgress.effectTag;\n\n if (_effectTag2 & ShouldCapture) {\n workInProgress.effectTag = _effectTag2 & ~ShouldCapture | DidCapture; // Captured a suspense effect. Re-render the boundary.\n\n return workInProgress;\n }\n\n return null;\n }\n\n case SuspenseListComponent:\n {\n popSuspenseContext(workInProgress); // SuspenseList doesn't actually catch anything. It should've been\n // caught by a nested boundary. If not, it should bubble through.\n\n return null;\n }\n\n case HostPortal:\n popHostContainer(workInProgress);\n return null;\n\n case ContextProvider:\n popProvider(workInProgress);\n return null;\n\n default:\n return null;\n }\n}\n\nfunction unwindInterruptedWork(interruptedWork) {\n switch (interruptedWork.tag) {\n case ClassComponent:\n {\n var childContextTypes = interruptedWork.type.childContextTypes;\n\n if (childContextTypes !== null && childContextTypes !== undefined) {\n popContext(interruptedWork);\n }\n\n break;\n }\n\n case HostRoot:\n {\n popHostContainer(interruptedWork);\n popTopLevelContextObject(interruptedWork);\n break;\n }\n\n case HostComponent:\n {\n popHostContext(interruptedWork);\n break;\n }\n\n case HostPortal:\n popHostContainer(interruptedWork);\n break;\n\n case SuspenseComponent:\n popSuspenseContext(interruptedWork);\n break;\n\n case SuspenseListComponent:\n popSuspenseContext(interruptedWork);\n break;\n\n case ContextProvider:\n popProvider(interruptedWork);\n break;\n }\n}\n\nfunction createCapturedValue(value, source) {\n // If the value is an error, call this function immediately after it is thrown\n // so the stack is accurate.\n return {\n value: value,\n source: source,\n stack: getStackByFiberInDevAndProd(source)\n };\n}\n\nfunction logCapturedError(capturedError) {\n\n var error = capturedError.error;\n\n {\n var componentName = capturedError.componentName,\n componentStack = capturedError.componentStack,\n errorBoundaryName = capturedError.errorBoundaryName,\n errorBoundaryFound = capturedError.errorBoundaryFound,\n willRetry = capturedError.willRetry; // Browsers support silencing uncaught errors by calling\n // `preventDefault()` in window `error` handler.\n // We record this information as an expando on the error.\n\n if (error != null && error._suppressLogging) {\n if (errorBoundaryFound && willRetry) {\n // The error is recoverable and was silenced.\n // Ignore it and don't print the stack addendum.\n // This is handy for testing error boundaries without noise.\n return;\n } // The error is fatal. Since the silencing might have\n // been accidental, we'll surface it anyway.\n // However, the browser would have silenced the original error\n // so we'll print it first, and then print the stack addendum.\n\n\n console['error'](error); // Don't transform to our wrapper\n // For a more detailed description of this block, see:\n // https://github.com/facebook/react/pull/13384\n }\n\n var componentNameMessage = componentName ? \"The above error occurred in the <\" + componentName + \"> component:\" : 'The above error occurred in one of your React components:';\n var errorBoundaryMessage; // errorBoundaryFound check is sufficient; errorBoundaryName check is to satisfy Flow.\n\n if (errorBoundaryFound && errorBoundaryName) {\n if (willRetry) {\n errorBoundaryMessage = \"React will try to recreate this component tree from scratch \" + (\"using the error boundary you provided, \" + errorBoundaryName + \".\");\n } else {\n errorBoundaryMessage = \"This error was initially handled by the error boundary \" + errorBoundaryName + \".\\n\" + \"Recreating the tree from scratch failed so React will unmount the tree.\";\n }\n } else {\n errorBoundaryMessage = 'Consider adding an error boundary to your tree to customize error handling behavior.\\n' + 'Visit https://fb.me/react-error-boundaries to learn more about error boundaries.';\n }\n\n var combinedMessage = \"\" + componentNameMessage + componentStack + \"\\n\\n\" + (\"\" + errorBoundaryMessage); // In development, we provide our own message with just the component stack.\n // We don't include the original error message and JS stack because the browser\n // has already printed it. Even if the application swallows the error, it is still\n // displayed by the browser thanks to the DEV-only fake event trick in ReactErrorUtils.\n\n console['error'](combinedMessage); // Don't transform to our wrapper\n }\n}\n\nvar didWarnAboutUndefinedSnapshotBeforeUpdate = null;\n\n{\n didWarnAboutUndefinedSnapshotBeforeUpdate = new Set();\n}\n\nvar PossiblyWeakSet = typeof WeakSet === 'function' ? WeakSet : Set;\nfunction logError(boundary, errorInfo) {\n var source = errorInfo.source;\n var stack = errorInfo.stack;\n\n if (stack === null && source !== null) {\n stack = getStackByFiberInDevAndProd(source);\n }\n\n var capturedError = {\n componentName: source !== null ? getComponentName(source.type) : null,\n componentStack: stack !== null ? stack : '',\n error: errorInfo.value,\n errorBoundary: null,\n errorBoundaryName: null,\n errorBoundaryFound: false,\n willRetry: false\n };\n\n if (boundary !== null && boundary.tag === ClassComponent) {\n capturedError.errorBoundary = boundary.stateNode;\n capturedError.errorBoundaryName = getComponentName(boundary.type);\n capturedError.errorBoundaryFound = true;\n capturedError.willRetry = true;\n }\n\n try {\n logCapturedError(capturedError);\n } catch (e) {\n // This method must not throw, or React internal state will get messed up.\n // If console.error is overridden, or logCapturedError() shows a dialog that throws,\n // we want to report this error outside of the normal stack as a last resort.\n // https://github.com/facebook/react/issues/13188\n setTimeout(function () {\n throw e;\n });\n }\n}\n\nvar callComponentWillUnmountWithTimer = function (current, instance) {\n startPhaseTimer(current, 'componentWillUnmount');\n instance.props = current.memoizedProps;\n instance.state = current.memoizedState;\n instance.componentWillUnmount();\n stopPhaseTimer();\n}; // Capture errors so they don't interrupt unmounting.\n\n\nfunction safelyCallComponentWillUnmount(current, instance) {\n {\n invokeGuardedCallback(null, callComponentWillUnmountWithTimer, null, current, instance);\n\n if (hasCaughtError()) {\n var unmountError = clearCaughtError();\n captureCommitPhaseError(current, unmountError);\n }\n }\n}\n\nfunction safelyDetachRef(current) {\n var ref = current.ref;\n\n if (ref !== null) {\n if (typeof ref === 'function') {\n {\n invokeGuardedCallback(null, ref, null, null);\n\n if (hasCaughtError()) {\n var refError = clearCaughtError();\n captureCommitPhaseError(current, refError);\n }\n }\n } else {\n ref.current = null;\n }\n }\n}\n\nfunction safelyCallDestroy(current, destroy) {\n {\n invokeGuardedCallback(null, destroy, null);\n\n if (hasCaughtError()) {\n var error = clearCaughtError();\n captureCommitPhaseError(current, error);\n }\n }\n}\n\nfunction commitBeforeMutationLifeCycles(current, finishedWork) {\n switch (finishedWork.tag) {\n case FunctionComponent:\n case ForwardRef:\n case SimpleMemoComponent:\n case Block:\n {\n return;\n }\n\n case ClassComponent:\n {\n if (finishedWork.effectTag & Snapshot) {\n if (current !== null) {\n var prevProps = current.memoizedProps;\n var prevState = current.memoizedState;\n startPhaseTimer(finishedWork, 'getSnapshotBeforeUpdate');\n var instance = finishedWork.stateNode; // We could update instance props and state here,\n // but instead we rely on them being set during last render.\n // TODO: revisit this when we implement resuming.\n\n {\n if (finishedWork.type === finishedWork.elementType && !didWarnAboutReassigningProps) {\n if (instance.props !== finishedWork.memoizedProps) {\n error('Expected %s props to match memoized props before ' + 'getSnapshotBeforeUpdate. ' + 'This might either be because of a bug in React, or because ' + 'a component reassigns its own `this.props`. ' + 'Please file an issue.', getComponentName(finishedWork.type) || 'instance');\n }\n\n if (instance.state !== finishedWork.memoizedState) {\n error('Expected %s state to match memoized state before ' + 'getSnapshotBeforeUpdate. ' + 'This might either be because of a bug in React, or because ' + 'a component reassigns its own `this.props`. ' + 'Please file an issue.', getComponentName(finishedWork.type) || 'instance');\n }\n }\n }\n\n var snapshot = instance.getSnapshotBeforeUpdate(finishedWork.elementType === finishedWork.type ? prevProps : resolveDefaultProps(finishedWork.type, prevProps), prevState);\n\n {\n var didWarnSet = didWarnAboutUndefinedSnapshotBeforeUpdate;\n\n if (snapshot === undefined && !didWarnSet.has(finishedWork.type)) {\n didWarnSet.add(finishedWork.type);\n\n error('%s.getSnapshotBeforeUpdate(): A snapshot value (or null) ' + 'must be returned. You have returned undefined.', getComponentName(finishedWork.type));\n }\n }\n\n instance.__reactInternalSnapshotBeforeUpdate = snapshot;\n stopPhaseTimer();\n }\n }\n\n return;\n }\n\n case HostRoot:\n case HostComponent:\n case HostText:\n case HostPortal:\n case IncompleteClassComponent:\n // Nothing to do for these component types\n return;\n }\n\n {\n {\n throw Error( \"This unit of work tag should not have side-effects. This error is likely caused by a bug in React. Please file an issue.\" );\n }\n }\n}\n\nfunction commitHookEffectListUnmount(tag, finishedWork) {\n var updateQueue = finishedWork.updateQueue;\n var lastEffect = updateQueue !== null ? updateQueue.lastEffect : null;\n\n if (lastEffect !== null) {\n var firstEffect = lastEffect.next;\n var effect = firstEffect;\n\n do {\n if ((effect.tag & tag) === tag) {\n // Unmount\n var destroy = effect.destroy;\n effect.destroy = undefined;\n\n if (destroy !== undefined) {\n destroy();\n }\n }\n\n effect = effect.next;\n } while (effect !== firstEffect);\n }\n}\n\nfunction commitHookEffectListMount(tag, finishedWork) {\n var updateQueue = finishedWork.updateQueue;\n var lastEffect = updateQueue !== null ? updateQueue.lastEffect : null;\n\n if (lastEffect !== null) {\n var firstEffect = lastEffect.next;\n var effect = firstEffect;\n\n do {\n if ((effect.tag & tag) === tag) {\n // Mount\n var create = effect.create;\n effect.destroy = create();\n\n {\n var destroy = effect.destroy;\n\n if (destroy !== undefined && typeof destroy !== 'function') {\n var addendum = void 0;\n\n if (destroy === null) {\n addendum = ' You returned null. If your effect does not require clean ' + 'up, return undefined (or nothing).';\n } else if (typeof destroy.then === 'function') {\n addendum = '\\n\\nIt looks like you wrote useEffect(async () => ...) or returned a Promise. ' + 'Instead, write the async function inside your effect ' + 'and call it immediately:\\n\\n' + 'useEffect(() => {\\n' + ' async function fetchData() {\\n' + ' // You can await here\\n' + ' const response = await MyAPI.getData(someId);\\n' + ' // ...\\n' + ' }\\n' + ' fetchData();\\n' + \"}, [someId]); // Or [] if effect doesn't need props or state\\n\\n\" + 'Learn more about data fetching with Hooks: https://fb.me/react-hooks-data-fetching';\n } else {\n addendum = ' You returned: ' + destroy;\n }\n\n error('An effect function must not return anything besides a function, ' + 'which is used for clean-up.%s%s', addendum, getStackByFiberInDevAndProd(finishedWork));\n }\n }\n }\n\n effect = effect.next;\n } while (effect !== firstEffect);\n }\n}\n\nfunction commitPassiveHookEffects(finishedWork) {\n if ((finishedWork.effectTag & Passive) !== NoEffect) {\n switch (finishedWork.tag) {\n case FunctionComponent:\n case ForwardRef:\n case SimpleMemoComponent:\n case Block:\n {\n // TODO (#17945) We should call all passive destroy functions (for all fibers)\n // before calling any create functions. The current approach only serializes\n // these for a single fiber.\n commitHookEffectListUnmount(Passive$1 | HasEffect, finishedWork);\n commitHookEffectListMount(Passive$1 | HasEffect, finishedWork);\n break;\n }\n }\n }\n}\n\nfunction commitLifeCycles(finishedRoot, current, finishedWork, committedExpirationTime) {\n switch (finishedWork.tag) {\n case FunctionComponent:\n case ForwardRef:\n case SimpleMemoComponent:\n case Block:\n {\n // At this point layout effects have already been destroyed (during mutation phase).\n // This is done to prevent sibling component effects from interfering with each other,\n // e.g. a destroy function in one component should never override a ref set\n // by a create function in another component during the same commit.\n commitHookEffectListMount(Layout | HasEffect, finishedWork);\n\n return;\n }\n\n case ClassComponent:\n {\n var instance = finishedWork.stateNode;\n\n if (finishedWork.effectTag & Update) {\n if (current === null) {\n startPhaseTimer(finishedWork, 'componentDidMount'); // We could update instance props and state here,\n // but instead we rely on them being set during last render.\n // TODO: revisit this when we implement resuming.\n\n {\n if (finishedWork.type === finishedWork.elementType && !didWarnAboutReassigningProps) {\n if (instance.props !== finishedWork.memoizedProps) {\n error('Expected %s props to match memoized props before ' + 'componentDidMount. ' + 'This might either be because of a bug in React, or because ' + 'a component reassigns its own `this.props`. ' + 'Please file an issue.', getComponentName(finishedWork.type) || 'instance');\n }\n\n if (instance.state !== finishedWork.memoizedState) {\n error('Expected %s state to match memoized state before ' + 'componentDidMount. ' + 'This might either be because of a bug in React, or because ' + 'a component reassigns its own `this.props`. ' + 'Please file an issue.', getComponentName(finishedWork.type) || 'instance');\n }\n }\n }\n\n instance.componentDidMount();\n stopPhaseTimer();\n } else {\n var prevProps = finishedWork.elementType === finishedWork.type ? current.memoizedProps : resolveDefaultProps(finishedWork.type, current.memoizedProps);\n var prevState = current.memoizedState;\n startPhaseTimer(finishedWork, 'componentDidUpdate'); // We could update instance props and state here,\n // but instead we rely on them being set during last render.\n // TODO: revisit this when we implement resuming.\n\n {\n if (finishedWork.type === finishedWork.elementType && !didWarnAboutReassigningProps) {\n if (instance.props !== finishedWork.memoizedProps) {\n error('Expected %s props to match memoized props before ' + 'componentDidUpdate. ' + 'This might either be because of a bug in React, or because ' + 'a component reassigns its own `this.props`. ' + 'Please file an issue.', getComponentName(finishedWork.type) || 'instance');\n }\n\n if (instance.state !== finishedWork.memoizedState) {\n error('Expected %s state to match memoized state before ' + 'componentDidUpdate. ' + 'This might either be because of a bug in React, or because ' + 'a component reassigns its own `this.props`. ' + 'Please file an issue.', getComponentName(finishedWork.type) || 'instance');\n }\n }\n }\n\n instance.componentDidUpdate(prevProps, prevState, instance.__reactInternalSnapshotBeforeUpdate);\n stopPhaseTimer();\n }\n }\n\n var updateQueue = finishedWork.updateQueue;\n\n if (updateQueue !== null) {\n {\n if (finishedWork.type === finishedWork.elementType && !didWarnAboutReassigningProps) {\n if (instance.props !== finishedWork.memoizedProps) {\n error('Expected %s props to match memoized props before ' + 'processing the update queue. ' + 'This might either be because of a bug in React, or because ' + 'a component reassigns its own `this.props`. ' + 'Please file an issue.', getComponentName(finishedWork.type) || 'instance');\n }\n\n if (instance.state !== finishedWork.memoizedState) {\n error('Expected %s state to match memoized state before ' + 'processing the update queue. ' + 'This might either be because of a bug in React, or because ' + 'a component reassigns its own `this.props`. ' + 'Please file an issue.', getComponentName(finishedWork.type) || 'instance');\n }\n }\n } // We could update instance props and state here,\n // but instead we rely on them being set during last render.\n // TODO: revisit this when we implement resuming.\n\n\n commitUpdateQueue(finishedWork, updateQueue, instance);\n }\n\n return;\n }\n\n case HostRoot:\n {\n var _updateQueue = finishedWork.updateQueue;\n\n if (_updateQueue !== null) {\n var _instance = null;\n\n if (finishedWork.child !== null) {\n switch (finishedWork.child.tag) {\n case HostComponent:\n _instance = getPublicInstance(finishedWork.child.stateNode);\n break;\n\n case ClassComponent:\n _instance = finishedWork.child.stateNode;\n break;\n }\n }\n\n commitUpdateQueue(finishedWork, _updateQueue, _instance);\n }\n\n return;\n }\n\n case HostComponent:\n {\n var _instance2 = finishedWork.stateNode; // Renderers may schedule work to be done after host components are mounted\n // (eg DOM renderer may schedule auto-focus for inputs and form controls).\n // These effects should only be committed when components are first mounted,\n // aka when there is no current/alternate.\n\n if (current === null && finishedWork.effectTag & Update) {\n var type = finishedWork.type;\n var props = finishedWork.memoizedProps;\n commitMount(_instance2, type, props);\n }\n\n return;\n }\n\n case HostText:\n {\n // We have no life-cycles associated with text.\n return;\n }\n\n case HostPortal:\n {\n // We have no life-cycles associated with portals.\n return;\n }\n\n case Profiler:\n {\n {\n var onRender = finishedWork.memoizedProps.onRender;\n\n if (typeof onRender === 'function') {\n {\n onRender(finishedWork.memoizedProps.id, current === null ? 'mount' : 'update', finishedWork.actualDuration, finishedWork.treeBaseDuration, finishedWork.actualStartTime, getCommitTime(), finishedRoot.memoizedInteractions);\n }\n }\n }\n\n return;\n }\n\n case SuspenseComponent:\n {\n commitSuspenseHydrationCallbacks(finishedRoot, finishedWork);\n return;\n }\n\n case SuspenseListComponent:\n case IncompleteClassComponent:\n case FundamentalComponent:\n case ScopeComponent:\n return;\n }\n\n {\n {\n throw Error( \"This unit of work tag should not have side-effects. This error is likely caused by a bug in React. Please file an issue.\" );\n }\n }\n}\n\nfunction hideOrUnhideAllChildren(finishedWork, isHidden) {\n {\n // We only have the top Fiber that was inserted but we need to recurse down its\n // children to find all the terminal nodes.\n var node = finishedWork;\n\n while (true) {\n if (node.tag === HostComponent) {\n var instance = node.stateNode;\n\n if (isHidden) {\n hideInstance(instance);\n } else {\n unhideInstance(node.stateNode, node.memoizedProps);\n }\n } else if (node.tag === HostText) {\n var _instance3 = node.stateNode;\n\n if (isHidden) {\n hideTextInstance(_instance3);\n } else {\n unhideTextInstance(_instance3, node.memoizedProps);\n }\n } else if (node.tag === SuspenseComponent && node.memoizedState !== null && node.memoizedState.dehydrated === null) {\n // Found a nested Suspense component that timed out. Skip over the\n // primary child fragment, which should remain hidden.\n var fallbackChildFragment = node.child.sibling;\n fallbackChildFragment.return = node;\n node = fallbackChildFragment;\n continue;\n } else if (node.child !== null) {\n node.child.return = node;\n node = node.child;\n continue;\n }\n\n if (node === finishedWork) {\n return;\n }\n\n while (node.sibling === null) {\n if (node.return === null || node.return === finishedWork) {\n return;\n }\n\n node = node.return;\n }\n\n node.sibling.return = node.return;\n node = node.sibling;\n }\n }\n}\n\nfunction commitAttachRef(finishedWork) {\n var ref = finishedWork.ref;\n\n if (ref !== null) {\n var instance = finishedWork.stateNode;\n var instanceToUse;\n\n switch (finishedWork.tag) {\n case HostComponent:\n instanceToUse = getPublicInstance(instance);\n break;\n\n default:\n instanceToUse = instance;\n } // Moved outside to ensure DCE works with this flag\n\n if (typeof ref === 'function') {\n ref(instanceToUse);\n } else {\n {\n if (!ref.hasOwnProperty('current')) {\n error('Unexpected ref object provided for %s. ' + 'Use either a ref-setter function or React.createRef().%s', getComponentName(finishedWork.type), getStackByFiberInDevAndProd(finishedWork));\n }\n }\n\n ref.current = instanceToUse;\n }\n }\n}\n\nfunction commitDetachRef(current) {\n var currentRef = current.ref;\n\n if (currentRef !== null) {\n if (typeof currentRef === 'function') {\n currentRef(null);\n } else {\n currentRef.current = null;\n }\n }\n} // User-originating errors (lifecycles and refs) should not interrupt\n// deletion, so don't let them throw. Host-originating errors should\n// interrupt deletion, so it's okay\n\n\nfunction commitUnmount(finishedRoot, current, renderPriorityLevel) {\n onCommitUnmount(current);\n\n switch (current.tag) {\n case FunctionComponent:\n case ForwardRef:\n case MemoComponent:\n case SimpleMemoComponent:\n case Block:\n {\n var updateQueue = current.updateQueue;\n\n if (updateQueue !== null) {\n var lastEffect = updateQueue.lastEffect;\n\n if (lastEffect !== null) {\n var firstEffect = lastEffect.next;\n\n {\n // When the owner fiber is deleted, the destroy function of a passive\n // effect hook is called during the synchronous commit phase. This is\n // a concession to implementation complexity. Calling it in the\n // passive effect phase (like they usually are, when dependencies\n // change during an update) would require either traversing the\n // children of the deleted fiber again, or including unmount effects\n // as part of the fiber effect list.\n //\n // Because this is during the sync commit phase, we need to change\n // the priority.\n //\n // TODO: Reconsider this implementation trade off.\n var priorityLevel = renderPriorityLevel > NormalPriority ? NormalPriority : renderPriorityLevel;\n runWithPriority$1(priorityLevel, function () {\n var effect = firstEffect;\n\n do {\n var _destroy = effect.destroy;\n\n if (_destroy !== undefined) {\n safelyCallDestroy(current, _destroy);\n }\n\n effect = effect.next;\n } while (effect !== firstEffect);\n });\n }\n }\n }\n\n return;\n }\n\n case ClassComponent:\n {\n safelyDetachRef(current);\n var instance = current.stateNode;\n\n if (typeof instance.componentWillUnmount === 'function') {\n safelyCallComponentWillUnmount(current, instance);\n }\n\n return;\n }\n\n case HostComponent:\n {\n\n safelyDetachRef(current);\n return;\n }\n\n case HostPortal:\n {\n // TODO: this is recursive.\n // We are also not using this parent because\n // the portal will get pushed immediately.\n {\n unmountHostComponents(finishedRoot, current, renderPriorityLevel);\n }\n\n return;\n }\n\n case FundamentalComponent:\n {\n\n return;\n }\n\n case DehydratedFragment:\n {\n\n return;\n }\n\n case ScopeComponent:\n {\n\n return;\n }\n }\n}\n\nfunction commitNestedUnmounts(finishedRoot, root, renderPriorityLevel) {\n // While we're inside a removed host node we don't want to call\n // removeChild on the inner nodes because they're removed by the top\n // call anyway. We also want to call componentWillUnmount on all\n // composites before this host node is removed from the tree. Therefore\n // we do an inner loop while we're still inside the host node.\n var node = root;\n\n while (true) {\n commitUnmount(finishedRoot, node, renderPriorityLevel); // Visit children because they may contain more composite or host nodes.\n // Skip portals because commitUnmount() currently visits them recursively.\n\n if (node.child !== null && ( // If we use mutation we drill down into portals using commitUnmount above.\n // If we don't use mutation we drill down into portals here instead.\n node.tag !== HostPortal)) {\n node.child.return = node;\n node = node.child;\n continue;\n }\n\n if (node === root) {\n return;\n }\n\n while (node.sibling === null) {\n if (node.return === null || node.return === root) {\n return;\n }\n\n node = node.return;\n }\n\n node.sibling.return = node.return;\n node = node.sibling;\n }\n}\n\nfunction detachFiber(current) {\n var alternate = current.alternate; // Cut off the return pointers to disconnect it from the tree. Ideally, we\n // should clear the child pointer of the parent alternate to let this\n // get GC:ed but we don't know which for sure which parent is the current\n // one so we'll settle for GC:ing the subtree of this child. This child\n // itself will be GC:ed when the parent updates the next time.\n\n current.return = null;\n current.child = null;\n current.memoizedState = null;\n current.updateQueue = null;\n current.dependencies = null;\n current.alternate = null;\n current.firstEffect = null;\n current.lastEffect = null;\n current.pendingProps = null;\n current.memoizedProps = null;\n current.stateNode = null;\n\n if (alternate !== null) {\n detachFiber(alternate);\n }\n}\n\nfunction getHostParentFiber(fiber) {\n var parent = fiber.return;\n\n while (parent !== null) {\n if (isHostParent(parent)) {\n return parent;\n }\n\n parent = parent.return;\n }\n\n {\n {\n throw Error( \"Expected to find a host parent. This error is likely caused by a bug in React. Please file an issue.\" );\n }\n }\n}\n\nfunction isHostParent(fiber) {\n return fiber.tag === HostComponent || fiber.tag === HostRoot || fiber.tag === HostPortal;\n}\n\nfunction getHostSibling(fiber) {\n // We're going to search forward into the tree until we find a sibling host\n // node. Unfortunately, if multiple insertions are done in a row we have to\n // search past them. This leads to exponential search for the next sibling.\n // TODO: Find a more efficient way to do this.\n var node = fiber;\n\n siblings: while (true) {\n // If we didn't find anything, let's try the next sibling.\n while (node.sibling === null) {\n if (node.return === null || isHostParent(node.return)) {\n // If we pop out of the root or hit the parent the fiber we are the\n // last sibling.\n return null;\n }\n\n node = node.return;\n }\n\n node.sibling.return = node.return;\n node = node.sibling;\n\n while (node.tag !== HostComponent && node.tag !== HostText && node.tag !== DehydratedFragment) {\n // If it is not host node and, we might have a host node inside it.\n // Try to search down until we find one.\n if (node.effectTag & Placement) {\n // If we don't have a child, try the siblings instead.\n continue siblings;\n } // If we don't have a child, try the siblings instead.\n // We also skip portals because they are not part of this host tree.\n\n\n if (node.child === null || node.tag === HostPortal) {\n continue siblings;\n } else {\n node.child.return = node;\n node = node.child;\n }\n } // Check if this host node is stable or about to be placed.\n\n\n if (!(node.effectTag & Placement)) {\n // Found it!\n return node.stateNode;\n }\n }\n}\n\nfunction commitPlacement(finishedWork) {\n\n\n var parentFiber = getHostParentFiber(finishedWork); // Note: these two variables *must* always be updated together.\n\n var parent;\n var isContainer;\n var parentStateNode = parentFiber.stateNode;\n\n switch (parentFiber.tag) {\n case HostComponent:\n parent = parentStateNode;\n isContainer = false;\n break;\n\n case HostRoot:\n parent = parentStateNode.containerInfo;\n isContainer = true;\n break;\n\n case HostPortal:\n parent = parentStateNode.containerInfo;\n isContainer = true;\n break;\n\n case FundamentalComponent:\n\n // eslint-disable-next-line-no-fallthrough\n\n default:\n {\n {\n throw Error( \"Invalid host parent fiber. This error is likely caused by a bug in React. Please file an issue.\" );\n }\n }\n\n }\n\n if (parentFiber.effectTag & ContentReset) {\n // Reset the text content of the parent before doing any insertions\n resetTextContent(parent); // Clear ContentReset from the effect tag\n\n parentFiber.effectTag &= ~ContentReset;\n }\n\n var before = getHostSibling(finishedWork); // We only have the top Fiber that was inserted but we need to recurse down its\n // children to find all the terminal nodes.\n\n if (isContainer) {\n insertOrAppendPlacementNodeIntoContainer(finishedWork, before, parent);\n } else {\n insertOrAppendPlacementNode(finishedWork, before, parent);\n }\n}\n\nfunction insertOrAppendPlacementNodeIntoContainer(node, before, parent) {\n var tag = node.tag;\n var isHost = tag === HostComponent || tag === HostText;\n\n if (isHost || enableFundamentalAPI ) {\n var stateNode = isHost ? node.stateNode : node.stateNode.instance;\n\n if (before) {\n insertInContainerBefore(parent, stateNode, before);\n } else {\n appendChildToContainer(parent, stateNode);\n }\n } else if (tag === HostPortal) ; else {\n var child = node.child;\n\n if (child !== null) {\n insertOrAppendPlacementNodeIntoContainer(child, before, parent);\n var sibling = child.sibling;\n\n while (sibling !== null) {\n insertOrAppendPlacementNodeIntoContainer(sibling, before, parent);\n sibling = sibling.sibling;\n }\n }\n }\n}\n\nfunction insertOrAppendPlacementNode(node, before, parent) {\n var tag = node.tag;\n var isHost = tag === HostComponent || tag === HostText;\n\n if (isHost || enableFundamentalAPI ) {\n var stateNode = isHost ? node.stateNode : node.stateNode.instance;\n\n if (before) {\n insertBefore(parent, stateNode, before);\n } else {\n appendChild(parent, stateNode);\n }\n } else if (tag === HostPortal) ; else {\n var child = node.child;\n\n if (child !== null) {\n insertOrAppendPlacementNode(child, before, parent);\n var sibling = child.sibling;\n\n while (sibling !== null) {\n insertOrAppendPlacementNode(sibling, before, parent);\n sibling = sibling.sibling;\n }\n }\n }\n}\n\nfunction unmountHostComponents(finishedRoot, current, renderPriorityLevel) {\n // We only have the top Fiber that was deleted but we need to recurse down its\n // children to find all the terminal nodes.\n var node = current; // Each iteration, currentParent is populated with node's host parent if not\n // currentParentIsValid.\n\n var currentParentIsValid = false; // Note: these two variables *must* always be updated together.\n\n var currentParent;\n var currentParentIsContainer;\n\n while (true) {\n if (!currentParentIsValid) {\n var parent = node.return;\n\n findParent: while (true) {\n if (!(parent !== null)) {\n {\n throw Error( \"Expected to find a host parent. This error is likely caused by a bug in React. Please file an issue.\" );\n }\n }\n\n var parentStateNode = parent.stateNode;\n\n switch (parent.tag) {\n case HostComponent:\n currentParent = parentStateNode;\n currentParentIsContainer = false;\n break findParent;\n\n case HostRoot:\n currentParent = parentStateNode.containerInfo;\n currentParentIsContainer = true;\n break findParent;\n\n case HostPortal:\n currentParent = parentStateNode.containerInfo;\n currentParentIsContainer = true;\n break findParent;\n\n }\n\n parent = parent.return;\n }\n\n currentParentIsValid = true;\n }\n\n if (node.tag === HostComponent || node.tag === HostText) {\n commitNestedUnmounts(finishedRoot, node, renderPriorityLevel); // After all the children have unmounted, it is now safe to remove the\n // node from the tree.\n\n if (currentParentIsContainer) {\n removeChildFromContainer(currentParent, node.stateNode);\n } else {\n removeChild(currentParent, node.stateNode);\n } // Don't visit children because we already visited them.\n\n } else if (node.tag === HostPortal) {\n if (node.child !== null) {\n // When we go into a portal, it becomes the parent to remove from.\n // We will reassign it back when we pop the portal on the way up.\n currentParent = node.stateNode.containerInfo;\n currentParentIsContainer = true; // Visit children because portals might contain host components.\n\n node.child.return = node;\n node = node.child;\n continue;\n }\n } else {\n commitUnmount(finishedRoot, node, renderPriorityLevel); // Visit children because we may find more host components below.\n\n if (node.child !== null) {\n node.child.return = node;\n node = node.child;\n continue;\n }\n }\n\n if (node === current) {\n return;\n }\n\n while (node.sibling === null) {\n if (node.return === null || node.return === current) {\n return;\n }\n\n node = node.return;\n\n if (node.tag === HostPortal) {\n // When we go out of the portal, we need to restore the parent.\n // Since we don't keep a stack of them, we will search for it.\n currentParentIsValid = false;\n }\n }\n\n node.sibling.return = node.return;\n node = node.sibling;\n }\n}\n\nfunction commitDeletion(finishedRoot, current, renderPriorityLevel) {\n {\n // Recursively delete all host nodes from the parent.\n // Detach refs and call componentWillUnmount() on the whole subtree.\n unmountHostComponents(finishedRoot, current, renderPriorityLevel);\n }\n\n detachFiber(current);\n}\n\nfunction commitWork(current, finishedWork) {\n\n switch (finishedWork.tag) {\n case FunctionComponent:\n case ForwardRef:\n case MemoComponent:\n case SimpleMemoComponent:\n case Block:\n {\n // Layout effects are destroyed during the mutation phase so that all\n // destroy functions for all fibers are called before any create functions.\n // This prevents sibling component effects from interfering with each other,\n // e.g. a destroy function in one component should never override a ref set\n // by a create function in another component during the same commit.\n commitHookEffectListUnmount(Layout | HasEffect, finishedWork);\n return;\n }\n\n case ClassComponent:\n {\n return;\n }\n\n case HostComponent:\n {\n var instance = finishedWork.stateNode;\n\n if (instance != null) {\n // Commit the work prepared earlier.\n var newProps = finishedWork.memoizedProps; // For hydration we reuse the update path but we treat the oldProps\n // as the newProps. The updatePayload will contain the real change in\n // this case.\n\n var oldProps = current !== null ? current.memoizedProps : newProps;\n var type = finishedWork.type; // TODO: Type the updateQueue to be specific to host components.\n\n var updatePayload = finishedWork.updateQueue;\n finishedWork.updateQueue = null;\n\n if (updatePayload !== null) {\n commitUpdate(instance, updatePayload, type, oldProps, newProps);\n }\n }\n\n return;\n }\n\n case HostText:\n {\n if (!(finishedWork.stateNode !== null)) {\n {\n throw Error( \"This should have a text node initialized. This error is likely caused by a bug in React. Please file an issue.\" );\n }\n }\n\n var textInstance = finishedWork.stateNode;\n var newText = finishedWork.memoizedProps; // For hydration we reuse the update path but we treat the oldProps\n // as the newProps. The updatePayload will contain the real change in\n // this case.\n\n var oldText = current !== null ? current.memoizedProps : newText;\n commitTextUpdate(textInstance, oldText, newText);\n return;\n }\n\n case HostRoot:\n {\n {\n var _root = finishedWork.stateNode;\n\n if (_root.hydrate) {\n // We've just hydrated. No need to hydrate again.\n _root.hydrate = false;\n commitHydratedContainer(_root.containerInfo);\n }\n }\n\n return;\n }\n\n case Profiler:\n {\n return;\n }\n\n case SuspenseComponent:\n {\n commitSuspenseComponent(finishedWork);\n attachSuspenseRetryListeners(finishedWork);\n return;\n }\n\n case SuspenseListComponent:\n {\n attachSuspenseRetryListeners(finishedWork);\n return;\n }\n\n case IncompleteClassComponent:\n {\n return;\n }\n }\n\n {\n {\n throw Error( \"This unit of work tag should not have side-effects. This error is likely caused by a bug in React. Please file an issue.\" );\n }\n }\n}\n\nfunction commitSuspenseComponent(finishedWork) {\n var newState = finishedWork.memoizedState;\n var newDidTimeout;\n var primaryChildParent = finishedWork;\n\n if (newState === null) {\n newDidTimeout = false;\n } else {\n newDidTimeout = true;\n primaryChildParent = finishedWork.child;\n markCommitTimeOfFallback();\n }\n\n if ( primaryChildParent !== null) {\n hideOrUnhideAllChildren(primaryChildParent, newDidTimeout);\n }\n}\n\nfunction commitSuspenseHydrationCallbacks(finishedRoot, finishedWork) {\n\n var newState = finishedWork.memoizedState;\n\n if (newState === null) {\n var current = finishedWork.alternate;\n\n if (current !== null) {\n var prevState = current.memoizedState;\n\n if (prevState !== null) {\n var suspenseInstance = prevState.dehydrated;\n\n if (suspenseInstance !== null) {\n commitHydratedSuspenseInstance(suspenseInstance);\n }\n }\n }\n }\n}\n\nfunction attachSuspenseRetryListeners(finishedWork) {\n // If this boundary just timed out, then it will have a set of thenables.\n // For each thenable, attach a listener so that when it resolves, React\n // attempts to re-render the boundary in the primary (pre-timeout) state.\n var thenables = finishedWork.updateQueue;\n\n if (thenables !== null) {\n finishedWork.updateQueue = null;\n var retryCache = finishedWork.stateNode;\n\n if (retryCache === null) {\n retryCache = finishedWork.stateNode = new PossiblyWeakSet();\n }\n\n thenables.forEach(function (thenable) {\n // Memoize using the boundary fiber to prevent redundant listeners.\n var retry = resolveRetryThenable.bind(null, finishedWork, thenable);\n\n if (!retryCache.has(thenable)) {\n {\n if (thenable.__reactDoNotTraceInteractions !== true) {\n retry = tracing.unstable_wrap(retry);\n }\n }\n\n retryCache.add(thenable);\n thenable.then(retry, retry);\n }\n });\n }\n}\n\nfunction commitResetTextContent(current) {\n\n resetTextContent(current.stateNode);\n}\n\nvar PossiblyWeakMap$1 = typeof WeakMap === 'function' ? WeakMap : Map;\n\nfunction createRootErrorUpdate(fiber, errorInfo, expirationTime) {\n var update = createUpdate(expirationTime, null); // Unmount the root by rendering null.\n\n update.tag = CaptureUpdate; // Caution: React DevTools currently depends on this property\n // being called \"element\".\n\n update.payload = {\n element: null\n };\n var error = errorInfo.value;\n\n update.callback = function () {\n onUncaughtError(error);\n logError(fiber, errorInfo);\n };\n\n return update;\n}\n\nfunction createClassErrorUpdate(fiber, errorInfo, expirationTime) {\n var update = createUpdate(expirationTime, null);\n update.tag = CaptureUpdate;\n var getDerivedStateFromError = fiber.type.getDerivedStateFromError;\n\n if (typeof getDerivedStateFromError === 'function') {\n var error$1 = errorInfo.value;\n\n update.payload = function () {\n logError(fiber, errorInfo);\n return getDerivedStateFromError(error$1);\n };\n }\n\n var inst = fiber.stateNode;\n\n if (inst !== null && typeof inst.componentDidCatch === 'function') {\n update.callback = function callback() {\n {\n markFailedErrorBoundaryForHotReloading(fiber);\n }\n\n if (typeof getDerivedStateFromError !== 'function') {\n // To preserve the preexisting retry behavior of error boundaries,\n // we keep track of which ones already failed during this batch.\n // This gets reset before we yield back to the browser.\n // TODO: Warn in strict mode if getDerivedStateFromError is\n // not defined.\n markLegacyErrorBoundaryAsFailed(this); // Only log here if componentDidCatch is the only error boundary method defined\n\n logError(fiber, errorInfo);\n }\n\n var error$1 = errorInfo.value;\n var stack = errorInfo.stack;\n this.componentDidCatch(error$1, {\n componentStack: stack !== null ? stack : ''\n });\n\n {\n if (typeof getDerivedStateFromError !== 'function') {\n // If componentDidCatch is the only error boundary method defined,\n // then it needs to call setState to recover from errors.\n // If no state update is scheduled then the boundary will swallow the error.\n if (fiber.expirationTime !== Sync) {\n error('%s: Error boundaries should implement getDerivedStateFromError(). ' + 'In that method, return a state update to display an error message or fallback UI.', getComponentName(fiber.type) || 'Unknown');\n }\n }\n }\n };\n } else {\n update.callback = function () {\n markFailedErrorBoundaryForHotReloading(fiber);\n };\n }\n\n return update;\n}\n\nfunction attachPingListener(root, renderExpirationTime, thenable) {\n // Attach a listener to the promise to \"ping\" the root and retry. But\n // only if one does not already exist for the current render expiration\n // time (which acts like a \"thread ID\" here).\n var pingCache = root.pingCache;\n var threadIDs;\n\n if (pingCache === null) {\n pingCache = root.pingCache = new PossiblyWeakMap$1();\n threadIDs = new Set();\n pingCache.set(thenable, threadIDs);\n } else {\n threadIDs = pingCache.get(thenable);\n\n if (threadIDs === undefined) {\n threadIDs = new Set();\n pingCache.set(thenable, threadIDs);\n }\n }\n\n if (!threadIDs.has(renderExpirationTime)) {\n // Memoize using the thread ID to prevent redundant listeners.\n threadIDs.add(renderExpirationTime);\n var ping = pingSuspendedRoot.bind(null, root, thenable, renderExpirationTime);\n thenable.then(ping, ping);\n }\n}\n\nfunction throwException(root, returnFiber, sourceFiber, value, renderExpirationTime) {\n // The source fiber did not complete.\n sourceFiber.effectTag |= Incomplete; // Its effect list is no longer valid.\n\n sourceFiber.firstEffect = sourceFiber.lastEffect = null;\n\n if (value !== null && typeof value === 'object' && typeof value.then === 'function') {\n // This is a thenable.\n var thenable = value;\n\n if ((sourceFiber.mode & BlockingMode) === NoMode) {\n // Reset the memoizedState to what it was before we attempted\n // to render it.\n var currentSource = sourceFiber.alternate;\n\n if (currentSource) {\n sourceFiber.updateQueue = currentSource.updateQueue;\n sourceFiber.memoizedState = currentSource.memoizedState;\n sourceFiber.expirationTime = currentSource.expirationTime;\n } else {\n sourceFiber.updateQueue = null;\n sourceFiber.memoizedState = null;\n }\n }\n\n var hasInvisibleParentBoundary = hasSuspenseContext(suspenseStackCursor.current, InvisibleParentSuspenseContext); // Schedule the nearest Suspense to re-render the timed out view.\n\n var _workInProgress = returnFiber;\n\n do {\n if (_workInProgress.tag === SuspenseComponent && shouldCaptureSuspense(_workInProgress, hasInvisibleParentBoundary)) {\n // Found the nearest boundary.\n // Stash the promise on the boundary fiber. If the boundary times out, we'll\n // attach another listener to flip the boundary back to its normal state.\n var thenables = _workInProgress.updateQueue;\n\n if (thenables === null) {\n var updateQueue = new Set();\n updateQueue.add(thenable);\n _workInProgress.updateQueue = updateQueue;\n } else {\n thenables.add(thenable);\n } // If the boundary is outside of blocking mode, we should *not*\n // suspend the commit. Pretend as if the suspended component rendered\n // null and keep rendering. In the commit phase, we'll schedule a\n // subsequent synchronous update to re-render the Suspense.\n //\n // Note: It doesn't matter whether the component that suspended was\n // inside a blocking mode tree. If the Suspense is outside of it, we\n // should *not* suspend the commit.\n\n\n if ((_workInProgress.mode & BlockingMode) === NoMode) {\n _workInProgress.effectTag |= DidCapture; // We're going to commit this fiber even though it didn't complete.\n // But we shouldn't call any lifecycle methods or callbacks. Remove\n // all lifecycle effect tags.\n\n sourceFiber.effectTag &= ~(LifecycleEffectMask | Incomplete);\n\n if (sourceFiber.tag === ClassComponent) {\n var currentSourceFiber = sourceFiber.alternate;\n\n if (currentSourceFiber === null) {\n // This is a new mount. Change the tag so it's not mistaken for a\n // completed class component. For example, we should not call\n // componentWillUnmount if it is deleted.\n sourceFiber.tag = IncompleteClassComponent;\n } else {\n // When we try rendering again, we should not reuse the current fiber,\n // since it's known to be in an inconsistent state. Use a force update to\n // prevent a bail out.\n var update = createUpdate(Sync, null);\n update.tag = ForceUpdate;\n enqueueUpdate(sourceFiber, update);\n }\n } // The source fiber did not complete. Mark it with Sync priority to\n // indicate that it still has pending work.\n\n\n sourceFiber.expirationTime = Sync; // Exit without suspending.\n\n return;\n } // Confirmed that the boundary is in a concurrent mode tree. Continue\n // with the normal suspend path.\n //\n // After this we'll use a set of heuristics to determine whether this\n // render pass will run to completion or restart or \"suspend\" the commit.\n // The actual logic for this is spread out in different places.\n //\n // This first principle is that if we're going to suspend when we complete\n // a root, then we should also restart if we get an update or ping that\n // might unsuspend it, and vice versa. The only reason to suspend is\n // because you think you might want to restart before committing. However,\n // it doesn't make sense to restart only while in the period we're suspended.\n //\n // Restarting too aggressively is also not good because it starves out any\n // intermediate loading state. So we use heuristics to determine when.\n // Suspense Heuristics\n //\n // If nothing threw a Promise or all the same fallbacks are already showing,\n // then don't suspend/restart.\n //\n // If this is an initial render of a new tree of Suspense boundaries and\n // those trigger a fallback, then don't suspend/restart. We want to ensure\n // that we can show the initial loading state as quickly as possible.\n //\n // If we hit a \"Delayed\" case, such as when we'd switch from content back into\n // a fallback, then we should always suspend/restart. SuspenseConfig applies to\n // this case. If none is defined, JND is used instead.\n //\n // If we're already showing a fallback and it gets \"retried\", allowing us to show\n // another level, but there's still an inner boundary that would show a fallback,\n // then we suspend/restart for 500ms since the last time we showed a fallback\n // anywhere in the tree. This effectively throttles progressive loading into a\n // consistent train of commits. This also gives us an opportunity to restart to\n // get to the completed state slightly earlier.\n //\n // If there's ambiguity due to batching it's resolved in preference of:\n // 1) \"delayed\", 2) \"initial render\", 3) \"retry\".\n //\n // We want to ensure that a \"busy\" state doesn't get force committed. We want to\n // ensure that new initial loading states can commit as soon as possible.\n\n\n attachPingListener(root, renderExpirationTime, thenable);\n _workInProgress.effectTag |= ShouldCapture;\n _workInProgress.expirationTime = renderExpirationTime;\n return;\n } // This boundary already captured during this render. Continue to the next\n // boundary.\n\n\n _workInProgress = _workInProgress.return;\n } while (_workInProgress !== null); // No boundary was found. Fallthrough to error mode.\n // TODO: Use invariant so the message is stripped in prod?\n\n\n value = new Error((getComponentName(sourceFiber.type) || 'A React component') + ' suspended while rendering, but no fallback UI was specified.\\n' + '\\n' + 'Add a <Suspense fallback=...> component higher in the tree to ' + 'provide a loading indicator or placeholder to display.' + getStackByFiberInDevAndProd(sourceFiber));\n } // We didn't find a boundary that could handle this type of exception. Start\n // over and traverse parent path again, this time treating the exception\n // as an error.\n\n\n renderDidError();\n value = createCapturedValue(value, sourceFiber);\n var workInProgress = returnFiber;\n\n do {\n switch (workInProgress.tag) {\n case HostRoot:\n {\n var _errorInfo = value;\n workInProgress.effectTag |= ShouldCapture;\n workInProgress.expirationTime = renderExpirationTime;\n\n var _update = createRootErrorUpdate(workInProgress, _errorInfo, renderExpirationTime);\n\n enqueueCapturedUpdate(workInProgress, _update);\n return;\n }\n\n case ClassComponent:\n // Capture and retry\n var errorInfo = value;\n var ctor = workInProgress.type;\n var instance = workInProgress.stateNode;\n\n if ((workInProgress.effectTag & DidCapture) === NoEffect && (typeof ctor.getDerivedStateFromError === 'function' || instance !== null && typeof instance.componentDidCatch === 'function' && !isAlreadyFailedLegacyErrorBoundary(instance))) {\n workInProgress.effectTag |= ShouldCapture;\n workInProgress.expirationTime = renderExpirationTime; // Schedule the error boundary to re-render using updated state\n\n var _update2 = createClassErrorUpdate(workInProgress, errorInfo, renderExpirationTime);\n\n enqueueCapturedUpdate(workInProgress, _update2);\n return;\n }\n\n break;\n }\n\n workInProgress = workInProgress.return;\n } while (workInProgress !== null);\n}\n\nvar ceil = Math.ceil;\nvar ReactCurrentDispatcher$1 = ReactSharedInternals.ReactCurrentDispatcher,\n ReactCurrentOwner$2 = ReactSharedInternals.ReactCurrentOwner,\n IsSomeRendererActing = ReactSharedInternals.IsSomeRendererActing;\nvar NoContext =\n/* */\n0;\nvar BatchedContext =\n/* */\n1;\nvar EventContext =\n/* */\n2;\nvar DiscreteEventContext =\n/* */\n4;\nvar LegacyUnbatchedContext =\n/* */\n8;\nvar RenderContext =\n/* */\n16;\nvar CommitContext =\n/* */\n32;\nvar RootIncomplete = 0;\nvar RootFatalErrored = 1;\nvar RootErrored = 2;\nvar RootSuspended = 3;\nvar RootSuspendedWithDelay = 4;\nvar RootCompleted = 5;\n// Describes where we are in the React execution stack\nvar executionContext = NoContext; // The root we're working on\n\nvar workInProgressRoot = null; // The fiber we're working on\n\nvar workInProgress = null; // The expiration time we're rendering\n\nvar renderExpirationTime$1 = NoWork; // Whether to root completed, errored, suspended, etc.\n\nvar workInProgressRootExitStatus = RootIncomplete; // A fatal error, if one is thrown\n\nvar workInProgressRootFatalError = null; // Most recent event time among processed updates during this render.\n// This is conceptually a time stamp but expressed in terms of an ExpirationTime\n// because we deal mostly with expiration times in the hot path, so this avoids\n// the conversion happening in the hot path.\n\nvar workInProgressRootLatestProcessedExpirationTime = Sync;\nvar workInProgressRootLatestSuspenseTimeout = Sync;\nvar workInProgressRootCanSuspendUsingConfig = null; // The work left over by components that were visited during this render. Only\n// includes unprocessed updates, not work in bailed out children.\n\nvar workInProgressRootNextUnprocessedUpdateTime = NoWork; // If we're pinged while rendering we don't always restart immediately.\n// This flag determines if it might be worthwhile to restart if an opportunity\n// happens latere.\n\nvar workInProgressRootHasPendingPing = false; // The most recent time we committed a fallback. This lets us ensure a train\n// model where we don't commit new loading states in too quick succession.\n\nvar globalMostRecentFallbackTime = 0;\nvar FALLBACK_THROTTLE_MS = 500;\nvar nextEffect = null;\nvar hasUncaughtError = false;\nvar firstUncaughtError = null;\nvar legacyErrorBoundariesThatAlreadyFailed = null;\nvar rootDoesHavePassiveEffects = false;\nvar rootWithPendingPassiveEffects = null;\nvar pendingPassiveEffectsRenderPriority = NoPriority;\nvar pendingPassiveEffectsExpirationTime = NoWork;\nvar rootsWithPendingDiscreteUpdates = null; // Use these to prevent an infinite loop of nested updates\n\nvar NESTED_UPDATE_LIMIT = 50;\nvar nestedUpdateCount = 0;\nvar rootWithNestedUpdates = null;\nvar NESTED_PASSIVE_UPDATE_LIMIT = 50;\nvar nestedPassiveUpdateCount = 0;\nvar interruptedBy = null; // Marks the need to reschedule pending interactions at these expiration times\n// during the commit phase. This enables them to be traced across components\n// that spawn new work during render. E.g. hidden boundaries, suspended SSR\n// hydration or SuspenseList.\n\nvar spawnedWorkDuringRender = null; // Expiration times are computed by adding to the current time (the start\n// time). However, if two updates are scheduled within the same event, we\n// should treat their start times as simultaneous, even if the actual clock\n// time has advanced between the first and second call.\n// In other words, because expiration times determine how updates are batched,\n// we want all updates of like priority that occur within the same event to\n// receive the same expiration time. Otherwise we get tearing.\n\nvar currentEventTime = NoWork;\nfunction requestCurrentTimeForUpdate() {\n if ((executionContext & (RenderContext | CommitContext)) !== NoContext) {\n // We're inside React, so it's fine to read the actual time.\n return msToExpirationTime(now());\n } // We're not inside React, so we may be in the middle of a browser event.\n\n\n if (currentEventTime !== NoWork) {\n // Use the same start time for all updates until we enter React again.\n return currentEventTime;\n } // This is the first update since React yielded. Compute a new start time.\n\n\n currentEventTime = msToExpirationTime(now());\n return currentEventTime;\n}\nfunction getCurrentTime() {\n return msToExpirationTime(now());\n}\nfunction computeExpirationForFiber(currentTime, fiber, suspenseConfig) {\n var mode = fiber.mode;\n\n if ((mode & BlockingMode) === NoMode) {\n return Sync;\n }\n\n var priorityLevel = getCurrentPriorityLevel();\n\n if ((mode & ConcurrentMode) === NoMode) {\n return priorityLevel === ImmediatePriority ? Sync : Batched;\n }\n\n if ((executionContext & RenderContext) !== NoContext) {\n // Use whatever time we're already rendering\n // TODO: Should there be a way to opt out, like with `runWithPriority`?\n return renderExpirationTime$1;\n }\n\n var expirationTime;\n\n if (suspenseConfig !== null) {\n // Compute an expiration time based on the Suspense timeout.\n expirationTime = computeSuspenseExpiration(currentTime, suspenseConfig.timeoutMs | 0 || LOW_PRIORITY_EXPIRATION);\n } else {\n // Compute an expiration time based on the Scheduler priority.\n switch (priorityLevel) {\n case ImmediatePriority:\n expirationTime = Sync;\n break;\n\n case UserBlockingPriority$1:\n // TODO: Rename this to computeUserBlockingExpiration\n expirationTime = computeInteractiveExpiration(currentTime);\n break;\n\n case NormalPriority:\n case LowPriority:\n // TODO: Handle LowPriority\n // TODO: Rename this to... something better.\n expirationTime = computeAsyncExpiration(currentTime);\n break;\n\n case IdlePriority:\n expirationTime = Idle;\n break;\n\n default:\n {\n {\n throw Error( \"Expected a valid priority level\" );\n }\n }\n\n }\n } // If we're in the middle of rendering a tree, do not update at the same\n // expiration time that is already rendering.\n // TODO: We shouldn't have to do this if the update is on a different root.\n // Refactor computeExpirationForFiber + scheduleUpdate so we have access to\n // the root when we check for this condition.\n\n\n if (workInProgressRoot !== null && expirationTime === renderExpirationTime$1) {\n // This is a trick to move this update into a separate batch\n expirationTime -= 1;\n }\n\n return expirationTime;\n}\nfunction scheduleUpdateOnFiber(fiber, expirationTime) {\n checkForNestedUpdates();\n warnAboutRenderPhaseUpdatesInDEV(fiber);\n var root = markUpdateTimeFromFiberToRoot(fiber, expirationTime);\n\n if (root === null) {\n warnAboutUpdateOnUnmountedFiberInDEV(fiber);\n return;\n }\n\n checkForInterruption(fiber, expirationTime);\n recordScheduleUpdate(); // TODO: computeExpirationForFiber also reads the priority. Pass the\n // priority as an argument to that function and this one.\n\n var priorityLevel = getCurrentPriorityLevel();\n\n if (expirationTime === Sync) {\n if ( // Check if we're inside unbatchedUpdates\n (executionContext & LegacyUnbatchedContext) !== NoContext && // Check if we're not already rendering\n (executionContext & (RenderContext | CommitContext)) === NoContext) {\n // Register pending interactions on the root to avoid losing traced interaction data.\n schedulePendingInteractions(root, expirationTime); // This is a legacy edge case. The initial mount of a ReactDOM.render-ed\n // root inside of batchedUpdates should be synchronous, but layout updates\n // should be deferred until the end of the batch.\n\n performSyncWorkOnRoot(root);\n } else {\n ensureRootIsScheduled(root);\n schedulePendingInteractions(root, expirationTime);\n\n if (executionContext === NoContext) {\n // Flush the synchronous work now, unless we're already working or inside\n // a batch. This is intentionally inside scheduleUpdateOnFiber instead of\n // scheduleCallbackForFiber to preserve the ability to schedule a callback\n // without immediately flushing it. We only do this for user-initiated\n // updates, to preserve historical behavior of legacy mode.\n flushSyncCallbackQueue();\n }\n }\n } else {\n ensureRootIsScheduled(root);\n schedulePendingInteractions(root, expirationTime);\n }\n\n if ((executionContext & DiscreteEventContext) !== NoContext && ( // Only updates at user-blocking priority or greater are considered\n // discrete, even inside a discrete event.\n priorityLevel === UserBlockingPriority$1 || priorityLevel === ImmediatePriority)) {\n // This is the result of a discrete event. Track the lowest priority\n // discrete update per root so we can flush them early, if needed.\n if (rootsWithPendingDiscreteUpdates === null) {\n rootsWithPendingDiscreteUpdates = new Map([[root, expirationTime]]);\n } else {\n var lastDiscreteTime = rootsWithPendingDiscreteUpdates.get(root);\n\n if (lastDiscreteTime === undefined || lastDiscreteTime > expirationTime) {\n rootsWithPendingDiscreteUpdates.set(root, expirationTime);\n }\n }\n }\n}\nvar scheduleWork = scheduleUpdateOnFiber; // This is split into a separate function so we can mark a fiber with pending\n// work without treating it as a typical update that originates from an event;\n// e.g. retrying a Suspense boundary isn't an update, but it does schedule work\n// on a fiber.\n\nfunction markUpdateTimeFromFiberToRoot(fiber, expirationTime) {\n // Update the source fiber's expiration time\n if (fiber.expirationTime < expirationTime) {\n fiber.expirationTime = expirationTime;\n }\n\n var alternate = fiber.alternate;\n\n if (alternate !== null && alternate.expirationTime < expirationTime) {\n alternate.expirationTime = expirationTime;\n } // Walk the parent path to the root and update the child expiration time.\n\n\n var node = fiber.return;\n var root = null;\n\n if (node === null && fiber.tag === HostRoot) {\n root = fiber.stateNode;\n } else {\n while (node !== null) {\n alternate = node.alternate;\n\n if (node.childExpirationTime < expirationTime) {\n node.childExpirationTime = expirationTime;\n\n if (alternate !== null && alternate.childExpirationTime < expirationTime) {\n alternate.childExpirationTime = expirationTime;\n }\n } else if (alternate !== null && alternate.childExpirationTime < expirationTime) {\n alternate.childExpirationTime = expirationTime;\n }\n\n if (node.return === null && node.tag === HostRoot) {\n root = node.stateNode;\n break;\n }\n\n node = node.return;\n }\n }\n\n if (root !== null) {\n if (workInProgressRoot === root) {\n // Received an update to a tree that's in the middle of rendering. Mark\n // that's unprocessed work on this root.\n markUnprocessedUpdateTime(expirationTime);\n\n if (workInProgressRootExitStatus === RootSuspendedWithDelay) {\n // The root already suspended with a delay, which means this render\n // definitely won't finish. Since we have a new update, let's mark it as\n // suspended now, right before marking the incoming update. This has the\n // effect of interrupting the current render and switching to the update.\n // TODO: This happens to work when receiving an update during the render\n // phase, because of the trick inside computeExpirationForFiber to\n // subtract 1 from `renderExpirationTime` to move it into a\n // separate bucket. But we should probably model it with an exception,\n // using the same mechanism we use to force hydration of a subtree.\n // TODO: This does not account for low pri updates that were already\n // scheduled before the root started rendering. Need to track the next\n // pending expiration time (perhaps by backtracking the return path) and\n // then trigger a restart in the `renderDidSuspendDelayIfPossible` path.\n markRootSuspendedAtTime(root, renderExpirationTime$1);\n }\n } // Mark that the root has a pending update.\n\n\n markRootUpdatedAtTime(root, expirationTime);\n }\n\n return root;\n}\n\nfunction getNextRootExpirationTimeToWorkOn(root) {\n // Determines the next expiration time that the root should render, taking\n // into account levels that may be suspended, or levels that may have\n // received a ping.\n var lastExpiredTime = root.lastExpiredTime;\n\n if (lastExpiredTime !== NoWork) {\n return lastExpiredTime;\n } // \"Pending\" refers to any update that hasn't committed yet, including if it\n // suspended. The \"suspended\" range is therefore a subset.\n\n\n var firstPendingTime = root.firstPendingTime;\n\n if (!isRootSuspendedAtTime(root, firstPendingTime)) {\n // The highest priority pending time is not suspended. Let's work on that.\n return firstPendingTime;\n } // If the first pending time is suspended, check if there's a lower priority\n // pending level that we know about. Or check if we received a ping. Work\n // on whichever is higher priority.\n\n\n var lastPingedTime = root.lastPingedTime;\n var nextKnownPendingLevel = root.nextKnownPendingLevel;\n var nextLevel = lastPingedTime > nextKnownPendingLevel ? lastPingedTime : nextKnownPendingLevel;\n\n if ( nextLevel <= Idle && firstPendingTime !== nextLevel) {\n // Don't work on Idle/Never priority unless everything else is committed.\n return NoWork;\n }\n\n return nextLevel;\n} // Use this function to schedule a task for a root. There's only one task per\n// root; if a task was already scheduled, we'll check to make sure the\n// expiration time of the existing task is the same as the expiration time of\n// the next level that the root has work on. This function is called on every\n// update, and right before exiting a task.\n\n\nfunction ensureRootIsScheduled(root) {\n var lastExpiredTime = root.lastExpiredTime;\n\n if (lastExpiredTime !== NoWork) {\n // Special case: Expired work should flush synchronously.\n root.callbackExpirationTime = Sync;\n root.callbackPriority = ImmediatePriority;\n root.callbackNode = scheduleSyncCallback(performSyncWorkOnRoot.bind(null, root));\n return;\n }\n\n var expirationTime = getNextRootExpirationTimeToWorkOn(root);\n var existingCallbackNode = root.callbackNode;\n\n if (expirationTime === NoWork) {\n // There's nothing to work on.\n if (existingCallbackNode !== null) {\n root.callbackNode = null;\n root.callbackExpirationTime = NoWork;\n root.callbackPriority = NoPriority;\n }\n\n return;\n } // TODO: If this is an update, we already read the current time. Pass the\n // time as an argument.\n\n\n var currentTime = requestCurrentTimeForUpdate();\n var priorityLevel = inferPriorityFromExpirationTime(currentTime, expirationTime); // If there's an existing render task, confirm it has the correct priority and\n // expiration time. Otherwise, we'll cancel it and schedule a new one.\n\n if (existingCallbackNode !== null) {\n var existingCallbackPriority = root.callbackPriority;\n var existingCallbackExpirationTime = root.callbackExpirationTime;\n\n if ( // Callback must have the exact same expiration time.\n existingCallbackExpirationTime === expirationTime && // Callback must have greater or equal priority.\n existingCallbackPriority >= priorityLevel) {\n // Existing callback is sufficient.\n return;\n } // Need to schedule a new task.\n // TODO: Instead of scheduling a new task, we should be able to change the\n // priority of the existing one.\n\n\n cancelCallback(existingCallbackNode);\n }\n\n root.callbackExpirationTime = expirationTime;\n root.callbackPriority = priorityLevel;\n var callbackNode;\n\n if (expirationTime === Sync) {\n // Sync React callbacks are scheduled on a special internal queue\n callbackNode = scheduleSyncCallback(performSyncWorkOnRoot.bind(null, root));\n } else {\n callbackNode = scheduleCallback(priorityLevel, performConcurrentWorkOnRoot.bind(null, root), // Compute a task timeout based on the expiration time. This also affects\n // ordering because tasks are processed in timeout order.\n {\n timeout: expirationTimeToMs(expirationTime) - now()\n });\n }\n\n root.callbackNode = callbackNode;\n} // This is the entry point for every concurrent task, i.e. anything that\n// goes through Scheduler.\n\n\nfunction performConcurrentWorkOnRoot(root, didTimeout) {\n // Since we know we're in a React event, we can clear the current\n // event time. The next update will compute a new event time.\n currentEventTime = NoWork;\n\n if (didTimeout) {\n // The render task took too long to complete. Mark the current time as\n // expired to synchronously render all expired work in a single batch.\n var currentTime = requestCurrentTimeForUpdate();\n markRootExpiredAtTime(root, currentTime); // This will schedule a synchronous callback.\n\n ensureRootIsScheduled(root);\n return null;\n } // Determine the next expiration time to work on, using the fields stored\n // on the root.\n\n\n var expirationTime = getNextRootExpirationTimeToWorkOn(root);\n\n if (expirationTime !== NoWork) {\n var originalCallbackNode = root.callbackNode;\n\n if (!((executionContext & (RenderContext | CommitContext)) === NoContext)) {\n {\n throw Error( \"Should not already be working.\" );\n }\n }\n\n flushPassiveEffects(); // If the root or expiration time have changed, throw out the existing stack\n // and prepare a fresh one. Otherwise we'll continue where we left off.\n\n if (root !== workInProgressRoot || expirationTime !== renderExpirationTime$1) {\n prepareFreshStack(root, expirationTime);\n startWorkOnPendingInteractions(root, expirationTime);\n } // If we have a work-in-progress fiber, it means there's still work to do\n // in this root.\n\n\n if (workInProgress !== null) {\n var prevExecutionContext = executionContext;\n executionContext |= RenderContext;\n var prevDispatcher = pushDispatcher();\n var prevInteractions = pushInteractions(root);\n startWorkLoopTimer(workInProgress);\n\n do {\n try {\n workLoopConcurrent();\n break;\n } catch (thrownValue) {\n handleError(root, thrownValue);\n }\n } while (true);\n\n resetContextDependencies();\n executionContext = prevExecutionContext;\n popDispatcher(prevDispatcher);\n\n {\n popInteractions(prevInteractions);\n }\n\n if (workInProgressRootExitStatus === RootFatalErrored) {\n var fatalError = workInProgressRootFatalError;\n stopInterruptedWorkLoopTimer();\n prepareFreshStack(root, expirationTime);\n markRootSuspendedAtTime(root, expirationTime);\n ensureRootIsScheduled(root);\n throw fatalError;\n }\n\n if (workInProgress !== null) {\n // There's still work left over. Exit without committing.\n stopInterruptedWorkLoopTimer();\n } else {\n // We now have a consistent tree. The next step is either to commit it,\n // or, if something suspended, wait to commit it after a timeout.\n stopFinishedWorkLoopTimer();\n var finishedWork = root.finishedWork = root.current.alternate;\n root.finishedExpirationTime = expirationTime;\n finishConcurrentRender(root, finishedWork, workInProgressRootExitStatus, expirationTime);\n }\n\n ensureRootIsScheduled(root);\n\n if (root.callbackNode === originalCallbackNode) {\n // The task node scheduled for this root is the same one that's\n // currently executed. Need to return a continuation.\n return performConcurrentWorkOnRoot.bind(null, root);\n }\n }\n }\n\n return null;\n}\n\nfunction finishConcurrentRender(root, finishedWork, exitStatus, expirationTime) {\n // Set this to null to indicate there's no in-progress render.\n workInProgressRoot = null;\n\n switch (exitStatus) {\n case RootIncomplete:\n case RootFatalErrored:\n {\n {\n {\n throw Error( \"Root did not complete. This is a bug in React.\" );\n }\n }\n }\n // Flow knows about invariant, so it complains if I add a break\n // statement, but eslint doesn't know about invariant, so it complains\n // if I do. eslint-disable-next-line no-fallthrough\n\n case RootErrored:\n {\n // If this was an async render, the error may have happened due to\n // a mutation in a concurrent event. Try rendering one more time,\n // synchronously, to see if the error goes away. If there are\n // lower priority updates, let's include those, too, in case they\n // fix the inconsistency. Render at Idle to include all updates.\n // If it was Idle or Never or some not-yet-invented time, render\n // at that time.\n markRootExpiredAtTime(root, expirationTime > Idle ? Idle : expirationTime); // We assume that this second render pass will be synchronous\n // and therefore not hit this path again.\n\n break;\n }\n\n case RootSuspended:\n {\n markRootSuspendedAtTime(root, expirationTime);\n var lastSuspendedTime = root.lastSuspendedTime;\n\n if (expirationTime === lastSuspendedTime) {\n root.nextKnownPendingLevel = getRemainingExpirationTime(finishedWork);\n } // We have an acceptable loading state. We need to figure out if we\n // should immediately commit it or wait a bit.\n // If we have processed new updates during this render, we may now\n // have a new loading state ready. We want to ensure that we commit\n // that as soon as possible.\n\n\n var hasNotProcessedNewUpdates = workInProgressRootLatestProcessedExpirationTime === Sync;\n\n if (hasNotProcessedNewUpdates && // do not delay if we're inside an act() scope\n !( IsThisRendererActing.current)) {\n // If we have not processed any new updates during this pass, then\n // this is either a retry of an existing fallback state or a\n // hidden tree. Hidden trees shouldn't be batched with other work\n // and after that's fixed it can only be a retry. We're going to\n // throttle committing retries so that we don't show too many\n // loading states too quickly.\n var msUntilTimeout = globalMostRecentFallbackTime + FALLBACK_THROTTLE_MS - now(); // Don't bother with a very short suspense time.\n\n if (msUntilTimeout > 10) {\n if (workInProgressRootHasPendingPing) {\n var lastPingedTime = root.lastPingedTime;\n\n if (lastPingedTime === NoWork || lastPingedTime >= expirationTime) {\n // This render was pinged but we didn't get to restart\n // earlier so try restarting now instead.\n root.lastPingedTime = expirationTime;\n prepareFreshStack(root, expirationTime);\n break;\n }\n }\n\n var nextTime = getNextRootExpirationTimeToWorkOn(root);\n\n if (nextTime !== NoWork && nextTime !== expirationTime) {\n // There's additional work on this root.\n break;\n }\n\n if (lastSuspendedTime !== NoWork && lastSuspendedTime !== expirationTime) {\n // We should prefer to render the fallback of at the last\n // suspended level. Ping the last suspended level to try\n // rendering it again.\n root.lastPingedTime = lastSuspendedTime;\n break;\n } // The render is suspended, it hasn't timed out, and there's no\n // lower priority work to do. Instead of committing the fallback\n // immediately, wait for more data to arrive.\n\n\n root.timeoutHandle = scheduleTimeout(commitRoot.bind(null, root), msUntilTimeout);\n break;\n }\n } // The work expired. Commit immediately.\n\n\n commitRoot(root);\n break;\n }\n\n case RootSuspendedWithDelay:\n {\n markRootSuspendedAtTime(root, expirationTime);\n var _lastSuspendedTime = root.lastSuspendedTime;\n\n if (expirationTime === _lastSuspendedTime) {\n root.nextKnownPendingLevel = getRemainingExpirationTime(finishedWork);\n }\n\n if ( // do not delay if we're inside an act() scope\n !( IsThisRendererActing.current)) {\n // We're suspended in a state that should be avoided. We'll try to\n // avoid committing it for as long as the timeouts let us.\n if (workInProgressRootHasPendingPing) {\n var _lastPingedTime = root.lastPingedTime;\n\n if (_lastPingedTime === NoWork || _lastPingedTime >= expirationTime) {\n // This render was pinged but we didn't get to restart earlier\n // so try restarting now instead.\n root.lastPingedTime = expirationTime;\n prepareFreshStack(root, expirationTime);\n break;\n }\n }\n\n var _nextTime = getNextRootExpirationTimeToWorkOn(root);\n\n if (_nextTime !== NoWork && _nextTime !== expirationTime) {\n // There's additional work on this root.\n break;\n }\n\n if (_lastSuspendedTime !== NoWork && _lastSuspendedTime !== expirationTime) {\n // We should prefer to render the fallback of at the last\n // suspended level. Ping the last suspended level to try\n // rendering it again.\n root.lastPingedTime = _lastSuspendedTime;\n break;\n }\n\n var _msUntilTimeout;\n\n if (workInProgressRootLatestSuspenseTimeout !== Sync) {\n // We have processed a suspense config whose expiration time we\n // can use as the timeout.\n _msUntilTimeout = expirationTimeToMs(workInProgressRootLatestSuspenseTimeout) - now();\n } else if (workInProgressRootLatestProcessedExpirationTime === Sync) {\n // This should never normally happen because only new updates\n // cause delayed states, so we should have processed something.\n // However, this could also happen in an offscreen tree.\n _msUntilTimeout = 0;\n } else {\n // If we don't have a suspense config, we're going to use a\n // heuristic to determine how long we can suspend.\n var eventTimeMs = inferTimeFromExpirationTime(workInProgressRootLatestProcessedExpirationTime);\n var currentTimeMs = now();\n var timeUntilExpirationMs = expirationTimeToMs(expirationTime) - currentTimeMs;\n var timeElapsed = currentTimeMs - eventTimeMs;\n\n if (timeElapsed < 0) {\n // We get this wrong some time since we estimate the time.\n timeElapsed = 0;\n }\n\n _msUntilTimeout = jnd(timeElapsed) - timeElapsed; // Clamp the timeout to the expiration time. TODO: Once the\n // event time is exact instead of inferred from expiration time\n // we don't need this.\n\n if (timeUntilExpirationMs < _msUntilTimeout) {\n _msUntilTimeout = timeUntilExpirationMs;\n }\n } // Don't bother with a very short suspense time.\n\n\n if (_msUntilTimeout > 10) {\n // The render is suspended, it hasn't timed out, and there's no\n // lower priority work to do. Instead of committing the fallback\n // immediately, wait for more data to arrive.\n root.timeoutHandle = scheduleTimeout(commitRoot.bind(null, root), _msUntilTimeout);\n break;\n }\n } // The work expired. Commit immediately.\n\n\n commitRoot(root);\n break;\n }\n\n case RootCompleted:\n {\n // The work completed. Ready to commit.\n if ( // do not delay if we're inside an act() scope\n !( IsThisRendererActing.current) && workInProgressRootLatestProcessedExpirationTime !== Sync && workInProgressRootCanSuspendUsingConfig !== null) {\n // If we have exceeded the minimum loading delay, which probably\n // means we have shown a spinner already, we might have to suspend\n // a bit longer to ensure that the spinner is shown for\n // enough time.\n var _msUntilTimeout2 = computeMsUntilSuspenseLoadingDelay(workInProgressRootLatestProcessedExpirationTime, expirationTime, workInProgressRootCanSuspendUsingConfig);\n\n if (_msUntilTimeout2 > 10) {\n markRootSuspendedAtTime(root, expirationTime);\n root.timeoutHandle = scheduleTimeout(commitRoot.bind(null, root), _msUntilTimeout2);\n break;\n }\n }\n\n commitRoot(root);\n break;\n }\n\n default:\n {\n {\n {\n throw Error( \"Unknown root exit status.\" );\n }\n }\n }\n }\n} // This is the entry point for synchronous tasks that don't go\n// through Scheduler\n\n\nfunction performSyncWorkOnRoot(root) {\n // Check if there's expired work on this root. Otherwise, render at Sync.\n var lastExpiredTime = root.lastExpiredTime;\n var expirationTime = lastExpiredTime !== NoWork ? lastExpiredTime : Sync;\n\n if (!((executionContext & (RenderContext | CommitContext)) === NoContext)) {\n {\n throw Error( \"Should not already be working.\" );\n }\n }\n\n flushPassiveEffects(); // If the root or expiration time have changed, throw out the existing stack\n // and prepare a fresh one. Otherwise we'll continue where we left off.\n\n if (root !== workInProgressRoot || expirationTime !== renderExpirationTime$1) {\n prepareFreshStack(root, expirationTime);\n startWorkOnPendingInteractions(root, expirationTime);\n } // If we have a work-in-progress fiber, it means there's still work to do\n // in this root.\n\n\n if (workInProgress !== null) {\n var prevExecutionContext = executionContext;\n executionContext |= RenderContext;\n var prevDispatcher = pushDispatcher();\n var prevInteractions = pushInteractions(root);\n startWorkLoopTimer(workInProgress);\n\n do {\n try {\n workLoopSync();\n break;\n } catch (thrownValue) {\n handleError(root, thrownValue);\n }\n } while (true);\n\n resetContextDependencies();\n executionContext = prevExecutionContext;\n popDispatcher(prevDispatcher);\n\n {\n popInteractions(prevInteractions);\n }\n\n if (workInProgressRootExitStatus === RootFatalErrored) {\n var fatalError = workInProgressRootFatalError;\n stopInterruptedWorkLoopTimer();\n prepareFreshStack(root, expirationTime);\n markRootSuspendedAtTime(root, expirationTime);\n ensureRootIsScheduled(root);\n throw fatalError;\n }\n\n if (workInProgress !== null) {\n // This is a sync render, so we should have finished the whole tree.\n {\n {\n throw Error( \"Cannot commit an incomplete root. This error is likely caused by a bug in React. Please file an issue.\" );\n }\n }\n } else {\n // We now have a consistent tree. Because this is a sync render, we\n // will commit it even if something suspended.\n stopFinishedWorkLoopTimer();\n root.finishedWork = root.current.alternate;\n root.finishedExpirationTime = expirationTime;\n finishSyncRender(root);\n } // Before exiting, make sure there's a callback scheduled for the next\n // pending level.\n\n\n ensureRootIsScheduled(root);\n }\n\n return null;\n}\n\nfunction finishSyncRender(root) {\n // Set this to null to indicate there's no in-progress render.\n workInProgressRoot = null;\n commitRoot(root);\n}\nfunction flushDiscreteUpdates() {\n // TODO: Should be able to flush inside batchedUpdates, but not inside `act`.\n // However, `act` uses `batchedUpdates`, so there's no way to distinguish\n // those two cases. Need to fix this before exposing flushDiscreteUpdates\n // as a public API.\n if ((executionContext & (BatchedContext | RenderContext | CommitContext)) !== NoContext) {\n {\n if ((executionContext & RenderContext) !== NoContext) {\n error('unstable_flushDiscreteUpdates: Cannot flush updates when React is ' + 'already rendering.');\n }\n } // We're already rendering, so we can't synchronously flush pending work.\n // This is probably a nested event dispatch triggered by a lifecycle/effect,\n // like `el.focus()`. Exit.\n\n\n return;\n }\n\n flushPendingDiscreteUpdates(); // If the discrete updates scheduled passive effects, flush them now so that\n // they fire before the next serial event.\n\n flushPassiveEffects();\n}\nfunction syncUpdates(fn, a, b, c) {\n return runWithPriority$1(ImmediatePriority, fn.bind(null, a, b, c));\n}\n\nfunction flushPendingDiscreteUpdates() {\n if (rootsWithPendingDiscreteUpdates !== null) {\n // For each root with pending discrete updates, schedule a callback to\n // immediately flush them.\n var roots = rootsWithPendingDiscreteUpdates;\n rootsWithPendingDiscreteUpdates = null;\n roots.forEach(function (expirationTime, root) {\n markRootExpiredAtTime(root, expirationTime);\n ensureRootIsScheduled(root);\n }); // Now flush the immediate queue.\n\n flushSyncCallbackQueue();\n }\n}\n\nfunction batchedUpdates$1(fn, a) {\n var prevExecutionContext = executionContext;\n executionContext |= BatchedContext;\n\n try {\n return fn(a);\n } finally {\n executionContext = prevExecutionContext;\n\n if (executionContext === NoContext) {\n // Flush the immediate callbacks that were scheduled during this batch\n flushSyncCallbackQueue();\n }\n }\n}\nfunction batchedEventUpdates$1(fn, a) {\n var prevExecutionContext = executionContext;\n executionContext |= EventContext;\n\n try {\n return fn(a);\n } finally {\n executionContext = prevExecutionContext;\n\n if (executionContext === NoContext) {\n // Flush the immediate callbacks that were scheduled during this batch\n flushSyncCallbackQueue();\n }\n }\n}\nfunction discreteUpdates$1(fn, a, b, c, d) {\n var prevExecutionContext = executionContext;\n executionContext |= DiscreteEventContext;\n\n try {\n // Should this\n return runWithPriority$1(UserBlockingPriority$1, fn.bind(null, a, b, c, d));\n } finally {\n executionContext = prevExecutionContext;\n\n if (executionContext === NoContext) {\n // Flush the immediate callbacks that were scheduled during this batch\n flushSyncCallbackQueue();\n }\n }\n}\nfunction unbatchedUpdates(fn, a) {\n var prevExecutionContext = executionContext;\n executionContext &= ~BatchedContext;\n executionContext |= LegacyUnbatchedContext;\n\n try {\n return fn(a);\n } finally {\n executionContext = prevExecutionContext;\n\n if (executionContext === NoContext) {\n // Flush the immediate callbacks that were scheduled during this batch\n flushSyncCallbackQueue();\n }\n }\n}\nfunction flushSync(fn, a) {\n if ((executionContext & (RenderContext | CommitContext)) !== NoContext) {\n {\n {\n throw Error( \"flushSync was called from inside a lifecycle method. It cannot be called when React is already rendering.\" );\n }\n }\n }\n\n var prevExecutionContext = executionContext;\n executionContext |= BatchedContext;\n\n try {\n return runWithPriority$1(ImmediatePriority, fn.bind(null, a));\n } finally {\n executionContext = prevExecutionContext; // Flush the immediate callbacks that were scheduled during this batch.\n // Note that this will happen even if batchedUpdates is higher up\n // the stack.\n\n flushSyncCallbackQueue();\n }\n}\n\nfunction prepareFreshStack(root, expirationTime) {\n root.finishedWork = null;\n root.finishedExpirationTime = NoWork;\n var timeoutHandle = root.timeoutHandle;\n\n if (timeoutHandle !== noTimeout) {\n // The root previous suspended and scheduled a timeout to commit a fallback\n // state. Now that we have additional work, cancel the timeout.\n root.timeoutHandle = noTimeout; // $FlowFixMe Complains noTimeout is not a TimeoutID, despite the check above\n\n cancelTimeout(timeoutHandle);\n }\n\n if (workInProgress !== null) {\n var interruptedWork = workInProgress.return;\n\n while (interruptedWork !== null) {\n unwindInterruptedWork(interruptedWork);\n interruptedWork = interruptedWork.return;\n }\n }\n\n workInProgressRoot = root;\n workInProgress = createWorkInProgress(root.current, null);\n renderExpirationTime$1 = expirationTime;\n workInProgressRootExitStatus = RootIncomplete;\n workInProgressRootFatalError = null;\n workInProgressRootLatestProcessedExpirationTime = Sync;\n workInProgressRootLatestSuspenseTimeout = Sync;\n workInProgressRootCanSuspendUsingConfig = null;\n workInProgressRootNextUnprocessedUpdateTime = NoWork;\n workInProgressRootHasPendingPing = false;\n\n {\n spawnedWorkDuringRender = null;\n }\n\n {\n ReactStrictModeWarnings.discardPendingWarnings();\n }\n}\n\nfunction handleError(root, thrownValue) {\n do {\n try {\n // Reset module-level state that was set during the render phase.\n resetContextDependencies();\n resetHooksAfterThrow();\n resetCurrentFiber();\n\n if (workInProgress === null || workInProgress.return === null) {\n // Expected to be working on a non-root fiber. This is a fatal error\n // because there's no ancestor that can handle it; the root is\n // supposed to capture all errors that weren't caught by an error\n // boundary.\n workInProgressRootExitStatus = RootFatalErrored;\n workInProgressRootFatalError = thrownValue; // Set `workInProgress` to null. This represents advancing to the next\n // sibling, or the parent if there are no siblings. But since the root\n // has no siblings nor a parent, we set it to null. Usually this is\n // handled by `completeUnitOfWork` or `unwindWork`, but since we're\n // interntionally not calling those, we need set it here.\n // TODO: Consider calling `unwindWork` to pop the contexts.\n\n workInProgress = null;\n return null;\n }\n\n if (enableProfilerTimer && workInProgress.mode & ProfileMode) {\n // Record the time spent rendering before an error was thrown. This\n // avoids inaccurate Profiler durations in the case of a\n // suspended render.\n stopProfilerTimerIfRunningAndRecordDelta(workInProgress, true);\n }\n\n throwException(root, workInProgress.return, workInProgress, thrownValue, renderExpirationTime$1);\n workInProgress = completeUnitOfWork(workInProgress);\n } catch (yetAnotherThrownValue) {\n // Something in the return path also threw.\n thrownValue = yetAnotherThrownValue;\n continue;\n } // Return to the normal work loop.\n\n\n return;\n } while (true);\n}\n\nfunction pushDispatcher(root) {\n var prevDispatcher = ReactCurrentDispatcher$1.current;\n ReactCurrentDispatcher$1.current = ContextOnlyDispatcher;\n\n if (prevDispatcher === null) {\n // The React isomorphic package does not include a default dispatcher.\n // Instead the first renderer will lazily attach one, in order to give\n // nicer error messages.\n return ContextOnlyDispatcher;\n } else {\n return prevDispatcher;\n }\n}\n\nfunction popDispatcher(prevDispatcher) {\n ReactCurrentDispatcher$1.current = prevDispatcher;\n}\n\nfunction pushInteractions(root) {\n {\n var prevInteractions = tracing.__interactionsRef.current;\n tracing.__interactionsRef.current = root.memoizedInteractions;\n return prevInteractions;\n }\n}\n\nfunction popInteractions(prevInteractions) {\n {\n tracing.__interactionsRef.current = prevInteractions;\n }\n}\n\nfunction markCommitTimeOfFallback() {\n globalMostRecentFallbackTime = now();\n}\nfunction markRenderEventTimeAndConfig(expirationTime, suspenseConfig) {\n if (expirationTime < workInProgressRootLatestProcessedExpirationTime && expirationTime > Idle) {\n workInProgressRootLatestProcessedExpirationTime = expirationTime;\n }\n\n if (suspenseConfig !== null) {\n if (expirationTime < workInProgressRootLatestSuspenseTimeout && expirationTime > Idle) {\n workInProgressRootLatestSuspenseTimeout = expirationTime; // Most of the time we only have one config and getting wrong is not bad.\n\n workInProgressRootCanSuspendUsingConfig = suspenseConfig;\n }\n }\n}\nfunction markUnprocessedUpdateTime(expirationTime) {\n if (expirationTime > workInProgressRootNextUnprocessedUpdateTime) {\n workInProgressRootNextUnprocessedUpdateTime = expirationTime;\n }\n}\nfunction renderDidSuspend() {\n if (workInProgressRootExitStatus === RootIncomplete) {\n workInProgressRootExitStatus = RootSuspended;\n }\n}\nfunction renderDidSuspendDelayIfPossible() {\n if (workInProgressRootExitStatus === RootIncomplete || workInProgressRootExitStatus === RootSuspended) {\n workInProgressRootExitStatus = RootSuspendedWithDelay;\n } // Check if there's a lower priority update somewhere else in the tree.\n\n\n if (workInProgressRootNextUnprocessedUpdateTime !== NoWork && workInProgressRoot !== null) {\n // Mark the current render as suspended, and then mark that there's a\n // pending update.\n // TODO: This should immediately interrupt the current render, instead\n // of waiting until the next time we yield.\n markRootSuspendedAtTime(workInProgressRoot, renderExpirationTime$1);\n markRootUpdatedAtTime(workInProgressRoot, workInProgressRootNextUnprocessedUpdateTime);\n }\n}\nfunction renderDidError() {\n if (workInProgressRootExitStatus !== RootCompleted) {\n workInProgressRootExitStatus = RootErrored;\n }\n} // Called during render to determine if anything has suspended.\n// Returns false if we're not sure.\n\nfunction renderHasNotSuspendedYet() {\n // If something errored or completed, we can't really be sure,\n // so those are false.\n return workInProgressRootExitStatus === RootIncomplete;\n}\n\nfunction inferTimeFromExpirationTime(expirationTime) {\n // We don't know exactly when the update was scheduled, but we can infer an\n // approximate start time from the expiration time.\n var earliestExpirationTimeMs = expirationTimeToMs(expirationTime);\n return earliestExpirationTimeMs - LOW_PRIORITY_EXPIRATION;\n}\n\nfunction inferTimeFromExpirationTimeWithSuspenseConfig(expirationTime, suspenseConfig) {\n // We don't know exactly when the update was scheduled, but we can infer an\n // approximate start time from the expiration time by subtracting the timeout\n // that was added to the event time.\n var earliestExpirationTimeMs = expirationTimeToMs(expirationTime);\n return earliestExpirationTimeMs - (suspenseConfig.timeoutMs | 0 || LOW_PRIORITY_EXPIRATION);\n} // The work loop is an extremely hot path. Tell Closure not to inline it.\n\n/** @noinline */\n\n\nfunction workLoopSync() {\n // Already timed out, so perform work without checking if we need to yield.\n while (workInProgress !== null) {\n workInProgress = performUnitOfWork(workInProgress);\n }\n}\n/** @noinline */\n\n\nfunction workLoopConcurrent() {\n // Perform work until Scheduler asks us to yield\n while (workInProgress !== null && !shouldYield()) {\n workInProgress = performUnitOfWork(workInProgress);\n }\n}\n\nfunction performUnitOfWork(unitOfWork) {\n // The current, flushed, state of this fiber is the alternate. Ideally\n // nothing should rely on this, but relying on it here means that we don't\n // need an additional field on the work in progress.\n var current = unitOfWork.alternate;\n startWorkTimer(unitOfWork);\n setCurrentFiber(unitOfWork);\n var next;\n\n if ( (unitOfWork.mode & ProfileMode) !== NoMode) {\n startProfilerTimer(unitOfWork);\n next = beginWork$1(current, unitOfWork, renderExpirationTime$1);\n stopProfilerTimerIfRunningAndRecordDelta(unitOfWork, true);\n } else {\n next = beginWork$1(current, unitOfWork, renderExpirationTime$1);\n }\n\n resetCurrentFiber();\n unitOfWork.memoizedProps = unitOfWork.pendingProps;\n\n if (next === null) {\n // If this doesn't spawn new work, complete the current work.\n next = completeUnitOfWork(unitOfWork);\n }\n\n ReactCurrentOwner$2.current = null;\n return next;\n}\n\nfunction completeUnitOfWork(unitOfWork) {\n // Attempt to complete the current unit of work, then move to the next\n // sibling. If there are no more siblings, return to the parent fiber.\n workInProgress = unitOfWork;\n\n do {\n // The current, flushed, state of this fiber is the alternate. Ideally\n // nothing should rely on this, but relying on it here means that we don't\n // need an additional field on the work in progress.\n var current = workInProgress.alternate;\n var returnFiber = workInProgress.return; // Check if the work completed or if something threw.\n\n if ((workInProgress.effectTag & Incomplete) === NoEffect) {\n setCurrentFiber(workInProgress);\n var next = void 0;\n\n if ( (workInProgress.mode & ProfileMode) === NoMode) {\n next = completeWork(current, workInProgress, renderExpirationTime$1);\n } else {\n startProfilerTimer(workInProgress);\n next = completeWork(current, workInProgress, renderExpirationTime$1); // Update render duration assuming we didn't error.\n\n stopProfilerTimerIfRunningAndRecordDelta(workInProgress, false);\n }\n\n stopWorkTimer(workInProgress);\n resetCurrentFiber();\n resetChildExpirationTime(workInProgress);\n\n if (next !== null) {\n // Completing this fiber spawned new work. Work on that next.\n return next;\n }\n\n if (returnFiber !== null && // Do not append effects to parents if a sibling failed to complete\n (returnFiber.effectTag & Incomplete) === NoEffect) {\n // Append all the effects of the subtree and this fiber onto the effect\n // list of the parent. The completion order of the children affects the\n // side-effect order.\n if (returnFiber.firstEffect === null) {\n returnFiber.firstEffect = workInProgress.firstEffect;\n }\n\n if (workInProgress.lastEffect !== null) {\n if (returnFiber.lastEffect !== null) {\n returnFiber.lastEffect.nextEffect = workInProgress.firstEffect;\n }\n\n returnFiber.lastEffect = workInProgress.lastEffect;\n } // If this fiber had side-effects, we append it AFTER the children's\n // side-effects. We can perform certain side-effects earlier if needed,\n // by doing multiple passes over the effect list. We don't want to\n // schedule our own side-effect on our own list because if end up\n // reusing children we'll schedule this effect onto itself since we're\n // at the end.\n\n\n var effectTag = workInProgress.effectTag; // Skip both NoWork and PerformedWork tags when creating the effect\n // list. PerformedWork effect is read by React DevTools but shouldn't be\n // committed.\n\n if (effectTag > PerformedWork) {\n if (returnFiber.lastEffect !== null) {\n returnFiber.lastEffect.nextEffect = workInProgress;\n } else {\n returnFiber.firstEffect = workInProgress;\n }\n\n returnFiber.lastEffect = workInProgress;\n }\n }\n } else {\n // This fiber did not complete because something threw. Pop values off\n // the stack without entering the complete phase. If this is a boundary,\n // capture values if possible.\n var _next = unwindWork(workInProgress); // Because this fiber did not complete, don't reset its expiration time.\n\n\n if ( (workInProgress.mode & ProfileMode) !== NoMode) {\n // Record the render duration for the fiber that errored.\n stopProfilerTimerIfRunningAndRecordDelta(workInProgress, false); // Include the time spent working on failed children before continuing.\n\n var actualDuration = workInProgress.actualDuration;\n var child = workInProgress.child;\n\n while (child !== null) {\n actualDuration += child.actualDuration;\n child = child.sibling;\n }\n\n workInProgress.actualDuration = actualDuration;\n }\n\n if (_next !== null) {\n // If completing this work spawned new work, do that next. We'll come\n // back here again.\n // Since we're restarting, remove anything that is not a host effect\n // from the effect tag.\n // TODO: The name stopFailedWorkTimer is misleading because Suspense\n // also captures and restarts.\n stopFailedWorkTimer(workInProgress);\n _next.effectTag &= HostEffectMask;\n return _next;\n }\n\n stopWorkTimer(workInProgress);\n\n if (returnFiber !== null) {\n // Mark the parent fiber as incomplete and clear its effect list.\n returnFiber.firstEffect = returnFiber.lastEffect = null;\n returnFiber.effectTag |= Incomplete;\n }\n }\n\n var siblingFiber = workInProgress.sibling;\n\n if (siblingFiber !== null) {\n // If there is more work to do in this returnFiber, do that next.\n return siblingFiber;\n } // Otherwise, return to the parent\n\n\n workInProgress = returnFiber;\n } while (workInProgress !== null); // We've reached the root.\n\n\n if (workInProgressRootExitStatus === RootIncomplete) {\n workInProgressRootExitStatus = RootCompleted;\n }\n\n return null;\n}\n\nfunction getRemainingExpirationTime(fiber) {\n var updateExpirationTime = fiber.expirationTime;\n var childExpirationTime = fiber.childExpirationTime;\n return updateExpirationTime > childExpirationTime ? updateExpirationTime : childExpirationTime;\n}\n\nfunction resetChildExpirationTime(completedWork) {\n if (renderExpirationTime$1 !== Never && completedWork.childExpirationTime === Never) {\n // The children of this component are hidden. Don't bubble their\n // expiration times.\n return;\n }\n\n var newChildExpirationTime = NoWork; // Bubble up the earliest expiration time.\n\n if ( (completedWork.mode & ProfileMode) !== NoMode) {\n // In profiling mode, resetChildExpirationTime is also used to reset\n // profiler durations.\n var actualDuration = completedWork.actualDuration;\n var treeBaseDuration = completedWork.selfBaseDuration; // When a fiber is cloned, its actualDuration is reset to 0. This value will\n // only be updated if work is done on the fiber (i.e. it doesn't bailout).\n // When work is done, it should bubble to the parent's actualDuration. If\n // the fiber has not been cloned though, (meaning no work was done), then\n // this value will reflect the amount of time spent working on a previous\n // render. In that case it should not bubble. We determine whether it was\n // cloned by comparing the child pointer.\n\n var shouldBubbleActualDurations = completedWork.alternate === null || completedWork.child !== completedWork.alternate.child;\n var child = completedWork.child;\n\n while (child !== null) {\n var childUpdateExpirationTime = child.expirationTime;\n var childChildExpirationTime = child.childExpirationTime;\n\n if (childUpdateExpirationTime > newChildExpirationTime) {\n newChildExpirationTime = childUpdateExpirationTime;\n }\n\n if (childChildExpirationTime > newChildExpirationTime) {\n newChildExpirationTime = childChildExpirationTime;\n }\n\n if (shouldBubbleActualDurations) {\n actualDuration += child.actualDuration;\n }\n\n treeBaseDuration += child.treeBaseDuration;\n child = child.sibling;\n }\n\n completedWork.actualDuration = actualDuration;\n completedWork.treeBaseDuration = treeBaseDuration;\n } else {\n var _child = completedWork.child;\n\n while (_child !== null) {\n var _childUpdateExpirationTime = _child.expirationTime;\n var _childChildExpirationTime = _child.childExpirationTime;\n\n if (_childUpdateExpirationTime > newChildExpirationTime) {\n newChildExpirationTime = _childUpdateExpirationTime;\n }\n\n if (_childChildExpirationTime > newChildExpirationTime) {\n newChildExpirationTime = _childChildExpirationTime;\n }\n\n _child = _child.sibling;\n }\n }\n\n completedWork.childExpirationTime = newChildExpirationTime;\n}\n\nfunction commitRoot(root) {\n var renderPriorityLevel = getCurrentPriorityLevel();\n runWithPriority$1(ImmediatePriority, commitRootImpl.bind(null, root, renderPriorityLevel));\n return null;\n}\n\nfunction commitRootImpl(root, renderPriorityLevel) {\n do {\n // `flushPassiveEffects` will call `flushSyncUpdateQueue` at the end, which\n // means `flushPassiveEffects` will sometimes result in additional\n // passive effects. So we need to keep flushing in a loop until there are\n // no more pending effects.\n // TODO: Might be better if `flushPassiveEffects` did not automatically\n // flush synchronous work at the end, to avoid factoring hazards like this.\n flushPassiveEffects();\n } while (rootWithPendingPassiveEffects !== null);\n\n flushRenderPhaseStrictModeWarningsInDEV();\n\n if (!((executionContext & (RenderContext | CommitContext)) === NoContext)) {\n {\n throw Error( \"Should not already be working.\" );\n }\n }\n\n var finishedWork = root.finishedWork;\n var expirationTime = root.finishedExpirationTime;\n\n if (finishedWork === null) {\n return null;\n }\n\n root.finishedWork = null;\n root.finishedExpirationTime = NoWork;\n\n if (!(finishedWork !== root.current)) {\n {\n throw Error( \"Cannot commit the same tree as before. This error is likely caused by a bug in React. Please file an issue.\" );\n }\n } // commitRoot never returns a continuation; it always finishes synchronously.\n // So we can clear these now to allow a new callback to be scheduled.\n\n\n root.callbackNode = null;\n root.callbackExpirationTime = NoWork;\n root.callbackPriority = NoPriority;\n root.nextKnownPendingLevel = NoWork;\n startCommitTimer(); // Update the first and last pending times on this root. The new first\n // pending time is whatever is left on the root fiber.\n\n var remainingExpirationTimeBeforeCommit = getRemainingExpirationTime(finishedWork);\n markRootFinishedAtTime(root, expirationTime, remainingExpirationTimeBeforeCommit);\n\n if (root === workInProgressRoot) {\n // We can reset these now that they are finished.\n workInProgressRoot = null;\n workInProgress = null;\n renderExpirationTime$1 = NoWork;\n } // This indicates that the last root we worked on is not the same one that\n // we're committing now. This most commonly happens when a suspended root\n // times out.\n // Get the list of effects.\n\n\n var firstEffect;\n\n if (finishedWork.effectTag > PerformedWork) {\n // A fiber's effect list consists only of its children, not itself. So if\n // the root has an effect, we need to add it to the end of the list. The\n // resulting list is the set that would belong to the root's parent, if it\n // had one; that is, all the effects in the tree including the root.\n if (finishedWork.lastEffect !== null) {\n finishedWork.lastEffect.nextEffect = finishedWork;\n firstEffect = finishedWork.firstEffect;\n } else {\n firstEffect = finishedWork;\n }\n } else {\n // There is no effect on the root.\n firstEffect = finishedWork.firstEffect;\n }\n\n if (firstEffect !== null) {\n var prevExecutionContext = executionContext;\n executionContext |= CommitContext;\n var prevInteractions = pushInteractions(root); // Reset this to null before calling lifecycles\n\n ReactCurrentOwner$2.current = null; // The commit phase is broken into several sub-phases. We do a separate pass\n // of the effect list for each phase: all mutation effects come before all\n // layout effects, and so on.\n // The first phase a \"before mutation\" phase. We use this phase to read the\n // state of the host tree right before we mutate it. This is where\n // getSnapshotBeforeUpdate is called.\n\n startCommitSnapshotEffectsTimer();\n prepareForCommit(root.containerInfo);\n nextEffect = firstEffect;\n\n do {\n {\n invokeGuardedCallback(null, commitBeforeMutationEffects, null);\n\n if (hasCaughtError()) {\n if (!(nextEffect !== null)) {\n {\n throw Error( \"Should be working on an effect.\" );\n }\n }\n\n var error = clearCaughtError();\n captureCommitPhaseError(nextEffect, error);\n nextEffect = nextEffect.nextEffect;\n }\n }\n } while (nextEffect !== null);\n\n stopCommitSnapshotEffectsTimer();\n\n {\n // Mark the current commit time to be shared by all Profilers in this\n // batch. This enables them to be grouped later.\n recordCommitTime();\n } // The next phase is the mutation phase, where we mutate the host tree.\n\n\n startCommitHostEffectsTimer();\n nextEffect = firstEffect;\n\n do {\n {\n invokeGuardedCallback(null, commitMutationEffects, null, root, renderPriorityLevel);\n\n if (hasCaughtError()) {\n if (!(nextEffect !== null)) {\n {\n throw Error( \"Should be working on an effect.\" );\n }\n }\n\n var _error = clearCaughtError();\n\n captureCommitPhaseError(nextEffect, _error);\n nextEffect = nextEffect.nextEffect;\n }\n }\n } while (nextEffect !== null);\n\n stopCommitHostEffectsTimer();\n resetAfterCommit(root.containerInfo); // The work-in-progress tree is now the current tree. This must come after\n // the mutation phase, so that the previous tree is still current during\n // componentWillUnmount, but before the layout phase, so that the finished\n // work is current during componentDidMount/Update.\n\n root.current = finishedWork; // The next phase is the layout phase, where we call effects that read\n // the host tree after it's been mutated. The idiomatic use case for this is\n // layout, but class component lifecycles also fire here for legacy reasons.\n\n startCommitLifeCyclesTimer();\n nextEffect = firstEffect;\n\n do {\n {\n invokeGuardedCallback(null, commitLayoutEffects, null, root, expirationTime);\n\n if (hasCaughtError()) {\n if (!(nextEffect !== null)) {\n {\n throw Error( \"Should be working on an effect.\" );\n }\n }\n\n var _error2 = clearCaughtError();\n\n captureCommitPhaseError(nextEffect, _error2);\n nextEffect = nextEffect.nextEffect;\n }\n }\n } while (nextEffect !== null);\n\n stopCommitLifeCyclesTimer();\n nextEffect = null; // Tell Scheduler to yield at the end of the frame, so the browser has an\n // opportunity to paint.\n\n requestPaint();\n\n {\n popInteractions(prevInteractions);\n }\n\n executionContext = prevExecutionContext;\n } else {\n // No effects.\n root.current = finishedWork; // Measure these anyway so the flamegraph explicitly shows that there were\n // no effects.\n // TODO: Maybe there's a better way to report this.\n\n startCommitSnapshotEffectsTimer();\n stopCommitSnapshotEffectsTimer();\n\n {\n recordCommitTime();\n }\n\n startCommitHostEffectsTimer();\n stopCommitHostEffectsTimer();\n startCommitLifeCyclesTimer();\n stopCommitLifeCyclesTimer();\n }\n\n stopCommitTimer();\n var rootDidHavePassiveEffects = rootDoesHavePassiveEffects;\n\n if (rootDoesHavePassiveEffects) {\n // This commit has passive effects. Stash a reference to them. But don't\n // schedule a callback until after flushing layout work.\n rootDoesHavePassiveEffects = false;\n rootWithPendingPassiveEffects = root;\n pendingPassiveEffectsExpirationTime = expirationTime;\n pendingPassiveEffectsRenderPriority = renderPriorityLevel;\n } else {\n // We are done with the effect chain at this point so let's clear the\n // nextEffect pointers to assist with GC. If we have passive effects, we'll\n // clear this in flushPassiveEffects.\n nextEffect = firstEffect;\n\n while (nextEffect !== null) {\n var nextNextEffect = nextEffect.nextEffect;\n nextEffect.nextEffect = null;\n nextEffect = nextNextEffect;\n }\n } // Check if there's remaining work on this root\n\n\n var remainingExpirationTime = root.firstPendingTime;\n\n if (remainingExpirationTime !== NoWork) {\n {\n if (spawnedWorkDuringRender !== null) {\n var expirationTimes = spawnedWorkDuringRender;\n spawnedWorkDuringRender = null;\n\n for (var i = 0; i < expirationTimes.length; i++) {\n scheduleInteractions(root, expirationTimes[i], root.memoizedInteractions);\n }\n }\n\n schedulePendingInteractions(root, remainingExpirationTime);\n }\n } else {\n // If there's no remaining work, we can clear the set of already failed\n // error boundaries.\n legacyErrorBoundariesThatAlreadyFailed = null;\n }\n\n {\n if (!rootDidHavePassiveEffects) {\n // If there are no passive effects, then we can complete the pending interactions.\n // Otherwise, we'll wait until after the passive effects are flushed.\n // Wait to do this until after remaining work has been scheduled,\n // so that we don't prematurely signal complete for interactions when there's e.g. hidden work.\n finishPendingInteractions(root, expirationTime);\n }\n }\n\n if (remainingExpirationTime === Sync) {\n // Count the number of times the root synchronously re-renders without\n // finishing. If there are too many, it indicates an infinite update loop.\n if (root === rootWithNestedUpdates) {\n nestedUpdateCount++;\n } else {\n nestedUpdateCount = 0;\n rootWithNestedUpdates = root;\n }\n } else {\n nestedUpdateCount = 0;\n }\n\n onCommitRoot(finishedWork.stateNode, expirationTime); // Always call this before exiting `commitRoot`, to ensure that any\n // additional work on this root is scheduled.\n\n ensureRootIsScheduled(root);\n\n if (hasUncaughtError) {\n hasUncaughtError = false;\n var _error3 = firstUncaughtError;\n firstUncaughtError = null;\n throw _error3;\n }\n\n if ((executionContext & LegacyUnbatchedContext) !== NoContext) {\n // This is a legacy edge case. We just committed the initial mount of\n // a ReactDOM.render-ed root inside of batchedUpdates. The commit fired\n // synchronously, but layout updates should be deferred until the end\n // of the batch.\n return null;\n } // If layout work was scheduled, flush it now.\n\n\n flushSyncCallbackQueue();\n return null;\n}\n\nfunction commitBeforeMutationEffects() {\n while (nextEffect !== null) {\n var effectTag = nextEffect.effectTag;\n\n if ((effectTag & Snapshot) !== NoEffect) {\n setCurrentFiber(nextEffect);\n recordEffect();\n var current = nextEffect.alternate;\n commitBeforeMutationLifeCycles(current, nextEffect);\n resetCurrentFiber();\n }\n\n if ((effectTag & Passive) !== NoEffect) {\n // If there are passive effects, schedule a callback to flush at\n // the earliest opportunity.\n if (!rootDoesHavePassiveEffects) {\n rootDoesHavePassiveEffects = true;\n scheduleCallback(NormalPriority, function () {\n flushPassiveEffects();\n return null;\n });\n }\n }\n\n nextEffect = nextEffect.nextEffect;\n }\n}\n\nfunction commitMutationEffects(root, renderPriorityLevel) {\n // TODO: Should probably move the bulk of this function to commitWork.\n while (nextEffect !== null) {\n setCurrentFiber(nextEffect);\n var effectTag = nextEffect.effectTag;\n\n if (effectTag & ContentReset) {\n commitResetTextContent(nextEffect);\n }\n\n if (effectTag & Ref) {\n var current = nextEffect.alternate;\n\n if (current !== null) {\n commitDetachRef(current);\n }\n } // The following switch statement is only concerned about placement,\n // updates, and deletions. To avoid needing to add a case for every possible\n // bitmap value, we remove the secondary effects from the effect tag and\n // switch on that value.\n\n\n var primaryEffectTag = effectTag & (Placement | Update | Deletion | Hydrating);\n\n switch (primaryEffectTag) {\n case Placement:\n {\n commitPlacement(nextEffect); // Clear the \"placement\" from effect tag so that we know that this is\n // inserted, before any life-cycles like componentDidMount gets called.\n // TODO: findDOMNode doesn't rely on this any more but isMounted does\n // and isMounted is deprecated anyway so we should be able to kill this.\n\n nextEffect.effectTag &= ~Placement;\n break;\n }\n\n case PlacementAndUpdate:\n {\n // Placement\n commitPlacement(nextEffect); // Clear the \"placement\" from effect tag so that we know that this is\n // inserted, before any life-cycles like componentDidMount gets called.\n\n nextEffect.effectTag &= ~Placement; // Update\n\n var _current = nextEffect.alternate;\n commitWork(_current, nextEffect);\n break;\n }\n\n case Hydrating:\n {\n nextEffect.effectTag &= ~Hydrating;\n break;\n }\n\n case HydratingAndUpdate:\n {\n nextEffect.effectTag &= ~Hydrating; // Update\n\n var _current2 = nextEffect.alternate;\n commitWork(_current2, nextEffect);\n break;\n }\n\n case Update:\n {\n var _current3 = nextEffect.alternate;\n commitWork(_current3, nextEffect);\n break;\n }\n\n case Deletion:\n {\n commitDeletion(root, nextEffect, renderPriorityLevel);\n break;\n }\n } // TODO: Only record a mutation effect if primaryEffectTag is non-zero.\n\n\n recordEffect();\n resetCurrentFiber();\n nextEffect = nextEffect.nextEffect;\n }\n}\n\nfunction commitLayoutEffects(root, committedExpirationTime) {\n // TODO: Should probably move the bulk of this function to commitWork.\n while (nextEffect !== null) {\n setCurrentFiber(nextEffect);\n var effectTag = nextEffect.effectTag;\n\n if (effectTag & (Update | Callback)) {\n recordEffect();\n var current = nextEffect.alternate;\n commitLifeCycles(root, current, nextEffect);\n }\n\n if (effectTag & Ref) {\n recordEffect();\n commitAttachRef(nextEffect);\n }\n\n resetCurrentFiber();\n nextEffect = nextEffect.nextEffect;\n }\n}\n\nfunction flushPassiveEffects() {\n if (pendingPassiveEffectsRenderPriority !== NoPriority) {\n var priorityLevel = pendingPassiveEffectsRenderPriority > NormalPriority ? NormalPriority : pendingPassiveEffectsRenderPriority;\n pendingPassiveEffectsRenderPriority = NoPriority;\n return runWithPriority$1(priorityLevel, flushPassiveEffectsImpl);\n }\n}\n\nfunction flushPassiveEffectsImpl() {\n if (rootWithPendingPassiveEffects === null) {\n return false;\n }\n\n var root = rootWithPendingPassiveEffects;\n var expirationTime = pendingPassiveEffectsExpirationTime;\n rootWithPendingPassiveEffects = null;\n pendingPassiveEffectsExpirationTime = NoWork;\n\n if (!((executionContext & (RenderContext | CommitContext)) === NoContext)) {\n {\n throw Error( \"Cannot flush passive effects while already rendering.\" );\n }\n }\n\n var prevExecutionContext = executionContext;\n executionContext |= CommitContext;\n var prevInteractions = pushInteractions(root);\n\n {\n // Note: This currently assumes there are no passive effects on the root fiber\n // because the root is not part of its own effect list.\n // This could change in the future.\n var _effect2 = root.current.firstEffect;\n\n while (_effect2 !== null) {\n {\n setCurrentFiber(_effect2);\n invokeGuardedCallback(null, commitPassiveHookEffects, null, _effect2);\n\n if (hasCaughtError()) {\n if (!(_effect2 !== null)) {\n {\n throw Error( \"Should be working on an effect.\" );\n }\n }\n\n var _error5 = clearCaughtError();\n\n captureCommitPhaseError(_effect2, _error5);\n }\n\n resetCurrentFiber();\n }\n\n var nextNextEffect = _effect2.nextEffect; // Remove nextEffect pointer to assist GC\n\n _effect2.nextEffect = null;\n _effect2 = nextNextEffect;\n }\n }\n\n {\n popInteractions(prevInteractions);\n finishPendingInteractions(root, expirationTime);\n }\n\n executionContext = prevExecutionContext;\n flushSyncCallbackQueue(); // If additional passive effects were scheduled, increment a counter. If this\n // exceeds the limit, we'll fire a warning.\n\n nestedPassiveUpdateCount = rootWithPendingPassiveEffects === null ? 0 : nestedPassiveUpdateCount + 1;\n return true;\n}\n\nfunction isAlreadyFailedLegacyErrorBoundary(instance) {\n return legacyErrorBoundariesThatAlreadyFailed !== null && legacyErrorBoundariesThatAlreadyFailed.has(instance);\n}\nfunction markLegacyErrorBoundaryAsFailed(instance) {\n if (legacyErrorBoundariesThatAlreadyFailed === null) {\n legacyErrorBoundariesThatAlreadyFailed = new Set([instance]);\n } else {\n legacyErrorBoundariesThatAlreadyFailed.add(instance);\n }\n}\n\nfunction prepareToThrowUncaughtError(error) {\n if (!hasUncaughtError) {\n hasUncaughtError = true;\n firstUncaughtError = error;\n }\n}\n\nvar onUncaughtError = prepareToThrowUncaughtError;\n\nfunction captureCommitPhaseErrorOnRoot(rootFiber, sourceFiber, error) {\n var errorInfo = createCapturedValue(error, sourceFiber);\n var update = createRootErrorUpdate(rootFiber, errorInfo, Sync);\n enqueueUpdate(rootFiber, update);\n var root = markUpdateTimeFromFiberToRoot(rootFiber, Sync);\n\n if (root !== null) {\n ensureRootIsScheduled(root);\n schedulePendingInteractions(root, Sync);\n }\n}\n\nfunction captureCommitPhaseError(sourceFiber, error) {\n if (sourceFiber.tag === HostRoot) {\n // Error was thrown at the root. There is no parent, so the root\n // itself should capture it.\n captureCommitPhaseErrorOnRoot(sourceFiber, sourceFiber, error);\n return;\n }\n\n var fiber = sourceFiber.return;\n\n while (fiber !== null) {\n if (fiber.tag === HostRoot) {\n captureCommitPhaseErrorOnRoot(fiber, sourceFiber, error);\n return;\n } else if (fiber.tag === ClassComponent) {\n var ctor = fiber.type;\n var instance = fiber.stateNode;\n\n if (typeof ctor.getDerivedStateFromError === 'function' || typeof instance.componentDidCatch === 'function' && !isAlreadyFailedLegacyErrorBoundary(instance)) {\n var errorInfo = createCapturedValue(error, sourceFiber);\n var update = createClassErrorUpdate(fiber, errorInfo, // TODO: This is always sync\n Sync);\n enqueueUpdate(fiber, update);\n var root = markUpdateTimeFromFiberToRoot(fiber, Sync);\n\n if (root !== null) {\n ensureRootIsScheduled(root);\n schedulePendingInteractions(root, Sync);\n }\n\n return;\n }\n }\n\n fiber = fiber.return;\n }\n}\nfunction pingSuspendedRoot(root, thenable, suspendedTime) {\n var pingCache = root.pingCache;\n\n if (pingCache !== null) {\n // The thenable resolved, so we no longer need to memoize, because it will\n // never be thrown again.\n pingCache.delete(thenable);\n }\n\n if (workInProgressRoot === root && renderExpirationTime$1 === suspendedTime) {\n // Received a ping at the same priority level at which we're currently\n // rendering. We might want to restart this render. This should mirror\n // the logic of whether or not a root suspends once it completes.\n // TODO: If we're rendering sync either due to Sync, Batched or expired,\n // we should probably never restart.\n // If we're suspended with delay, we'll always suspend so we can always\n // restart. If we're suspended without any updates, it might be a retry.\n // If it's early in the retry we can restart. We can't know for sure\n // whether we'll eventually process an update during this render pass,\n // but it's somewhat unlikely that we get to a ping before that, since\n // getting to the root most update is usually very fast.\n if (workInProgressRootExitStatus === RootSuspendedWithDelay || workInProgressRootExitStatus === RootSuspended && workInProgressRootLatestProcessedExpirationTime === Sync && now() - globalMostRecentFallbackTime < FALLBACK_THROTTLE_MS) {\n // Restart from the root. Don't need to schedule a ping because\n // we're already working on this tree.\n prepareFreshStack(root, renderExpirationTime$1);\n } else {\n // Even though we can't restart right now, we might get an\n // opportunity later. So we mark this render as having a ping.\n workInProgressRootHasPendingPing = true;\n }\n\n return;\n }\n\n if (!isRootSuspendedAtTime(root, suspendedTime)) {\n // The root is no longer suspended at this time.\n return;\n }\n\n var lastPingedTime = root.lastPingedTime;\n\n if (lastPingedTime !== NoWork && lastPingedTime < suspendedTime) {\n // There's already a lower priority ping scheduled.\n return;\n } // Mark the time at which this ping was scheduled.\n\n\n root.lastPingedTime = suspendedTime;\n\n ensureRootIsScheduled(root);\n schedulePendingInteractions(root, suspendedTime);\n}\n\nfunction retryTimedOutBoundary(boundaryFiber, retryTime) {\n // The boundary fiber (a Suspense component or SuspenseList component)\n // previously was rendered in its fallback state. One of the promises that\n // suspended it has resolved, which means at least part of the tree was\n // likely unblocked. Try rendering again, at a new expiration time.\n if (retryTime === NoWork) {\n var suspenseConfig = null; // Retries don't carry over the already committed update.\n\n var currentTime = requestCurrentTimeForUpdate();\n retryTime = computeExpirationForFiber(currentTime, boundaryFiber, suspenseConfig);\n } // TODO: Special case idle priority?\n\n\n var root = markUpdateTimeFromFiberToRoot(boundaryFiber, retryTime);\n\n if (root !== null) {\n ensureRootIsScheduled(root);\n schedulePendingInteractions(root, retryTime);\n }\n}\nfunction resolveRetryThenable(boundaryFiber, thenable) {\n var retryTime = NoWork; // Default\n\n var retryCache;\n\n {\n retryCache = boundaryFiber.stateNode;\n }\n\n if (retryCache !== null) {\n // The thenable resolved, so we no longer need to memoize, because it will\n // never be thrown again.\n retryCache.delete(thenable);\n }\n\n retryTimedOutBoundary(boundaryFiber, retryTime);\n} // Computes the next Just Noticeable Difference (JND) boundary.\n// The theory is that a person can't tell the difference between small differences in time.\n// Therefore, if we wait a bit longer than necessary that won't translate to a noticeable\n// difference in the experience. However, waiting for longer might mean that we can avoid\n// showing an intermediate loading state. The longer we have already waited, the harder it\n// is to tell small differences in time. Therefore, the longer we've already waited,\n// the longer we can wait additionally. At some point we have to give up though.\n// We pick a train model where the next boundary commits at a consistent schedule.\n// These particular numbers are vague estimates. We expect to adjust them based on research.\n\nfunction jnd(timeElapsed) {\n return timeElapsed < 120 ? 120 : timeElapsed < 480 ? 480 : timeElapsed < 1080 ? 1080 : timeElapsed < 1920 ? 1920 : timeElapsed < 3000 ? 3000 : timeElapsed < 4320 ? 4320 : ceil(timeElapsed / 1960) * 1960;\n}\n\nfunction computeMsUntilSuspenseLoadingDelay(mostRecentEventTime, committedExpirationTime, suspenseConfig) {\n var busyMinDurationMs = suspenseConfig.busyMinDurationMs | 0;\n\n if (busyMinDurationMs <= 0) {\n return 0;\n }\n\n var busyDelayMs = suspenseConfig.busyDelayMs | 0; // Compute the time until this render pass would expire.\n\n var currentTimeMs = now();\n var eventTimeMs = inferTimeFromExpirationTimeWithSuspenseConfig(mostRecentEventTime, suspenseConfig);\n var timeElapsed = currentTimeMs - eventTimeMs;\n\n if (timeElapsed <= busyDelayMs) {\n // If we haven't yet waited longer than the initial delay, we don't\n // have to wait any additional time.\n return 0;\n }\n\n var msUntilTimeout = busyDelayMs + busyMinDurationMs - timeElapsed; // This is the value that is passed to `setTimeout`.\n\n return msUntilTimeout;\n}\n\nfunction checkForNestedUpdates() {\n if (nestedUpdateCount > NESTED_UPDATE_LIMIT) {\n nestedUpdateCount = 0;\n rootWithNestedUpdates = null;\n\n {\n {\n throw Error( \"Maximum update depth exceeded. This can happen when a component repeatedly calls setState inside componentWillUpdate or componentDidUpdate. React limits the number of nested updates to prevent infinite loops.\" );\n }\n }\n }\n\n {\n if (nestedPassiveUpdateCount > NESTED_PASSIVE_UPDATE_LIMIT) {\n nestedPassiveUpdateCount = 0;\n\n error('Maximum update depth exceeded. This can happen when a component ' + \"calls setState inside useEffect, but useEffect either doesn't \" + 'have a dependency array, or one of the dependencies changes on ' + 'every render.');\n }\n }\n}\n\nfunction flushRenderPhaseStrictModeWarningsInDEV() {\n {\n ReactStrictModeWarnings.flushLegacyContextWarning();\n\n {\n ReactStrictModeWarnings.flushPendingUnsafeLifecycleWarnings();\n }\n }\n}\n\nfunction stopFinishedWorkLoopTimer() {\n var didCompleteRoot = true;\n stopWorkLoopTimer(interruptedBy, didCompleteRoot);\n interruptedBy = null;\n}\n\nfunction stopInterruptedWorkLoopTimer() {\n // TODO: Track which fiber caused the interruption.\n var didCompleteRoot = false;\n stopWorkLoopTimer(interruptedBy, didCompleteRoot);\n interruptedBy = null;\n}\n\nfunction checkForInterruption(fiberThatReceivedUpdate, updateExpirationTime) {\n if ( workInProgressRoot !== null && updateExpirationTime > renderExpirationTime$1) {\n interruptedBy = fiberThatReceivedUpdate;\n }\n}\n\nvar didWarnStateUpdateForUnmountedComponent = null;\n\nfunction warnAboutUpdateOnUnmountedFiberInDEV(fiber) {\n {\n var tag = fiber.tag;\n\n if (tag !== HostRoot && tag !== ClassComponent && tag !== FunctionComponent && tag !== ForwardRef && tag !== MemoComponent && tag !== SimpleMemoComponent && tag !== Block) {\n // Only warn for user-defined components, not internal ones like Suspense.\n return;\n }\n // the problematic code almost always lies inside that component.\n\n\n var componentName = getComponentName(fiber.type) || 'ReactComponent';\n\n if (didWarnStateUpdateForUnmountedComponent !== null) {\n if (didWarnStateUpdateForUnmountedComponent.has(componentName)) {\n return;\n }\n\n didWarnStateUpdateForUnmountedComponent.add(componentName);\n } else {\n didWarnStateUpdateForUnmountedComponent = new Set([componentName]);\n }\n\n error(\"Can't perform a React state update on an unmounted component. This \" + 'is a no-op, but it indicates a memory leak in your application. To ' + 'fix, cancel all subscriptions and asynchronous tasks in %s.%s', tag === ClassComponent ? 'the componentWillUnmount method' : 'a useEffect cleanup function', getStackByFiberInDevAndProd(fiber));\n }\n}\n\nvar beginWork$1;\n\n{\n var dummyFiber = null;\n\n beginWork$1 = function (current, unitOfWork, expirationTime) {\n // If a component throws an error, we replay it again in a synchronously\n // dispatched event, so that the debugger will treat it as an uncaught\n // error See ReactErrorUtils for more information.\n // Before entering the begin phase, copy the work-in-progress onto a dummy\n // fiber. If beginWork throws, we'll use this to reset the state.\n var originalWorkInProgressCopy = assignFiberPropertiesInDEV(dummyFiber, unitOfWork);\n\n try {\n return beginWork(current, unitOfWork, expirationTime);\n } catch (originalError) {\n if (originalError !== null && typeof originalError === 'object' && typeof originalError.then === 'function') {\n // Don't replay promises. Treat everything else like an error.\n throw originalError;\n } // Keep this code in sync with handleError; any changes here must have\n // corresponding changes there.\n\n\n resetContextDependencies();\n resetHooksAfterThrow(); // Don't reset current debug fiber, since we're about to work on the\n // same fiber again.\n // Unwind the failed stack frame\n\n unwindInterruptedWork(unitOfWork); // Restore the original properties of the fiber.\n\n assignFiberPropertiesInDEV(unitOfWork, originalWorkInProgressCopy);\n\n if ( unitOfWork.mode & ProfileMode) {\n // Reset the profiler timer.\n startProfilerTimer(unitOfWork);\n } // Run beginWork again.\n\n\n invokeGuardedCallback(null, beginWork, null, current, unitOfWork, expirationTime);\n\n if (hasCaughtError()) {\n var replayError = clearCaughtError(); // `invokeGuardedCallback` sometimes sets an expando `_suppressLogging`.\n // Rethrow this error instead of the original one.\n\n throw replayError;\n } else {\n // This branch is reachable if the render phase is impure.\n throw originalError;\n }\n }\n };\n}\n\nvar didWarnAboutUpdateInRender = false;\nvar didWarnAboutUpdateInRenderForAnotherComponent;\n\n{\n didWarnAboutUpdateInRenderForAnotherComponent = new Set();\n}\n\nfunction warnAboutRenderPhaseUpdatesInDEV(fiber) {\n {\n if (isRendering && (executionContext & RenderContext) !== NoContext) {\n switch (fiber.tag) {\n case FunctionComponent:\n case ForwardRef:\n case SimpleMemoComponent:\n {\n var renderingComponentName = workInProgress && getComponentName(workInProgress.type) || 'Unknown'; // Dedupe by the rendering component because it's the one that needs to be fixed.\n\n var dedupeKey = renderingComponentName;\n\n if (!didWarnAboutUpdateInRenderForAnotherComponent.has(dedupeKey)) {\n didWarnAboutUpdateInRenderForAnotherComponent.add(dedupeKey);\n var setStateComponentName = getComponentName(fiber.type) || 'Unknown';\n\n error('Cannot update a component (`%s`) while rendering a ' + 'different component (`%s`). To locate the bad setState() call inside `%s`, ' + 'follow the stack trace as described in https://fb.me/setstate-in-render', setStateComponentName, renderingComponentName, renderingComponentName);\n }\n\n break;\n }\n\n case ClassComponent:\n {\n if (!didWarnAboutUpdateInRender) {\n error('Cannot update during an existing state transition (such as ' + 'within `render`). Render methods should be a pure ' + 'function of props and state.');\n\n didWarnAboutUpdateInRender = true;\n }\n\n break;\n }\n }\n }\n }\n} // a 'shared' variable that changes when act() opens/closes in tests.\n\n\nvar IsThisRendererActing = {\n current: false\n};\nfunction warnIfNotScopedWithMatchingAct(fiber) {\n {\n if ( IsSomeRendererActing.current === true && IsThisRendererActing.current !== true) {\n error(\"It looks like you're using the wrong act() around your test interactions.\\n\" + 'Be sure to use the matching version of act() corresponding to your renderer:\\n\\n' + '// for react-dom:\\n' + \"import {act} from 'react-dom/test-utils';\\n\" + '// ...\\n' + 'act(() => ...);\\n\\n' + '// for react-test-renderer:\\n' + \"import TestRenderer from 'react-test-renderer';\\n\" + 'const {act} = TestRenderer;\\n' + '// ...\\n' + 'act(() => ...);' + '%s', getStackByFiberInDevAndProd(fiber));\n }\n }\n}\nfunction warnIfNotCurrentlyActingEffectsInDEV(fiber) {\n {\n if ( (fiber.mode & StrictMode) !== NoMode && IsSomeRendererActing.current === false && IsThisRendererActing.current === false) {\n error('An update to %s ran an effect, but was not wrapped in act(...).\\n\\n' + 'When testing, code that causes React state updates should be ' + 'wrapped into act(...):\\n\\n' + 'act(() => {\\n' + ' /* fire events that update state */\\n' + '});\\n' + '/* assert on the output */\\n\\n' + \"This ensures that you're testing the behavior the user would see \" + 'in the browser.' + ' Learn more at https://fb.me/react-wrap-tests-with-act' + '%s', getComponentName(fiber.type), getStackByFiberInDevAndProd(fiber));\n }\n }\n}\n\nfunction warnIfNotCurrentlyActingUpdatesInDEV(fiber) {\n {\n if ( executionContext === NoContext && IsSomeRendererActing.current === false && IsThisRendererActing.current === false) {\n error('An update to %s inside a test was not wrapped in act(...).\\n\\n' + 'When testing, code that causes React state updates should be ' + 'wrapped into act(...):\\n\\n' + 'act(() => {\\n' + ' /* fire events that update state */\\n' + '});\\n' + '/* assert on the output */\\n\\n' + \"This ensures that you're testing the behavior the user would see \" + 'in the browser.' + ' Learn more at https://fb.me/react-wrap-tests-with-act' + '%s', getComponentName(fiber.type), getStackByFiberInDevAndProd(fiber));\n }\n }\n}\n\nvar warnIfNotCurrentlyActingUpdatesInDev = warnIfNotCurrentlyActingUpdatesInDEV; // In tests, we want to enforce a mocked scheduler.\n\nvar didWarnAboutUnmockedScheduler = false; // TODO Before we release concurrent mode, revisit this and decide whether a mocked\n// scheduler is the actual recommendation. The alternative could be a testing build,\n// a new lib, or whatever; we dunno just yet. This message is for early adopters\n// to get their tests right.\n\nfunction warnIfUnmockedScheduler(fiber) {\n {\n if (didWarnAboutUnmockedScheduler === false && Scheduler.unstable_flushAllWithoutAsserting === undefined) {\n if (fiber.mode & BlockingMode || fiber.mode & ConcurrentMode) {\n didWarnAboutUnmockedScheduler = true;\n\n error('In Concurrent or Sync modes, the \"scheduler\" module needs to be mocked ' + 'to guarantee consistent behaviour across tests and browsers. ' + 'For example, with jest: \\n' + \"jest.mock('scheduler', () => require('scheduler/unstable_mock'));\\n\\n\" + 'For more info, visit https://fb.me/react-mock-scheduler');\n }\n }\n }\n}\n\nfunction computeThreadID(root, expirationTime) {\n // Interaction threads are unique per root and expiration time.\n return expirationTime * 1000 + root.interactionThreadID;\n}\n\nfunction markSpawnedWork(expirationTime) {\n\n if (spawnedWorkDuringRender === null) {\n spawnedWorkDuringRender = [expirationTime];\n } else {\n spawnedWorkDuringRender.push(expirationTime);\n }\n}\n\nfunction scheduleInteractions(root, expirationTime, interactions) {\n\n if (interactions.size > 0) {\n var pendingInteractionMap = root.pendingInteractionMap;\n var pendingInteractions = pendingInteractionMap.get(expirationTime);\n\n if (pendingInteractions != null) {\n interactions.forEach(function (interaction) {\n if (!pendingInteractions.has(interaction)) {\n // Update the pending async work count for previously unscheduled interaction.\n interaction.__count++;\n }\n\n pendingInteractions.add(interaction);\n });\n } else {\n pendingInteractionMap.set(expirationTime, new Set(interactions)); // Update the pending async work count for the current interactions.\n\n interactions.forEach(function (interaction) {\n interaction.__count++;\n });\n }\n\n var subscriber = tracing.__subscriberRef.current;\n\n if (subscriber !== null) {\n var threadID = computeThreadID(root, expirationTime);\n subscriber.onWorkScheduled(interactions, threadID);\n }\n }\n}\n\nfunction schedulePendingInteractions(root, expirationTime) {\n\n scheduleInteractions(root, expirationTime, tracing.__interactionsRef.current);\n}\n\nfunction startWorkOnPendingInteractions(root, expirationTime) {\n // we can accurately attribute time spent working on it, And so that cascading\n // work triggered during the render phase will be associated with it.\n\n\n var interactions = new Set();\n root.pendingInteractionMap.forEach(function (scheduledInteractions, scheduledExpirationTime) {\n if (scheduledExpirationTime >= expirationTime) {\n scheduledInteractions.forEach(function (interaction) {\n return interactions.add(interaction);\n });\n }\n }); // Store the current set of interactions on the FiberRoot for a few reasons:\n // We can re-use it in hot functions like performConcurrentWorkOnRoot()\n // without having to recalculate it. We will also use it in commitWork() to\n // pass to any Profiler onRender() hooks. This also provides DevTools with a\n // way to access it when the onCommitRoot() hook is called.\n\n root.memoizedInteractions = interactions;\n\n if (interactions.size > 0) {\n var subscriber = tracing.__subscriberRef.current;\n\n if (subscriber !== null) {\n var threadID = computeThreadID(root, expirationTime);\n\n try {\n subscriber.onWorkStarted(interactions, threadID);\n } catch (error) {\n // If the subscriber throws, rethrow it in a separate task\n scheduleCallback(ImmediatePriority, function () {\n throw error;\n });\n }\n }\n }\n}\n\nfunction finishPendingInteractions(root, committedExpirationTime) {\n\n var earliestRemainingTimeAfterCommit = root.firstPendingTime;\n var subscriber;\n\n try {\n subscriber = tracing.__subscriberRef.current;\n\n if (subscriber !== null && root.memoizedInteractions.size > 0) {\n var threadID = computeThreadID(root, committedExpirationTime);\n subscriber.onWorkStopped(root.memoizedInteractions, threadID);\n }\n } catch (error) {\n // If the subscriber throws, rethrow it in a separate task\n scheduleCallback(ImmediatePriority, function () {\n throw error;\n });\n } finally {\n // Clear completed interactions from the pending Map.\n // Unless the render was suspended or cascading work was scheduled,\n // In which case– leave pending interactions until the subsequent render.\n var pendingInteractionMap = root.pendingInteractionMap;\n pendingInteractionMap.forEach(function (scheduledInteractions, scheduledExpirationTime) {\n // Only decrement the pending interaction count if we're done.\n // If there's still work at the current priority,\n // That indicates that we are waiting for suspense data.\n if (scheduledExpirationTime > earliestRemainingTimeAfterCommit) {\n pendingInteractionMap.delete(scheduledExpirationTime);\n scheduledInteractions.forEach(function (interaction) {\n interaction.__count--;\n\n if (subscriber !== null && interaction.__count === 0) {\n try {\n subscriber.onInteractionScheduledWorkCompleted(interaction);\n } catch (error) {\n // If the subscriber throws, rethrow it in a separate task\n scheduleCallback(ImmediatePriority, function () {\n throw error;\n });\n }\n }\n });\n }\n });\n }\n}\n\nvar onScheduleFiberRoot = null;\nvar onCommitFiberRoot = null;\nvar onCommitFiberUnmount = null;\nvar hasLoggedError = false;\nvar isDevToolsPresent = typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ !== 'undefined';\nfunction injectInternals(internals) {\n if (typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ === 'undefined') {\n // No DevTools\n return false;\n }\n\n var hook = __REACT_DEVTOOLS_GLOBAL_HOOK__;\n\n if (hook.isDisabled) {\n // This isn't a real property on the hook, but it can be set to opt out\n // of DevTools integration and associated warnings and logs.\n // https://github.com/facebook/react/issues/3877\n return true;\n }\n\n if (!hook.supportsFiber) {\n {\n error('The installed version of React DevTools is too old and will not work ' + 'with the current version of React. Please update React DevTools. ' + 'https://fb.me/react-devtools');\n } // DevTools exists, even though it doesn't support Fiber.\n\n\n return true;\n }\n\n try {\n var rendererID = hook.inject(internals); // We have successfully injected, so now it is safe to set up hooks.\n\n if (true) {\n // Only used by Fast Refresh\n if (typeof hook.onScheduleFiberRoot === 'function') {\n onScheduleFiberRoot = function (root, children) {\n try {\n hook.onScheduleFiberRoot(rendererID, root, children);\n } catch (err) {\n if ( true && !hasLoggedError) {\n hasLoggedError = true;\n\n error('React instrumentation encountered an error: %s', err);\n }\n }\n };\n }\n }\n\n onCommitFiberRoot = function (root, expirationTime) {\n try {\n var didError = (root.current.effectTag & DidCapture) === DidCapture;\n\n if (enableProfilerTimer) {\n var currentTime = getCurrentTime();\n var priorityLevel = inferPriorityFromExpirationTime(currentTime, expirationTime);\n hook.onCommitFiberRoot(rendererID, root, priorityLevel, didError);\n } else {\n hook.onCommitFiberRoot(rendererID, root, undefined, didError);\n }\n } catch (err) {\n if (true) {\n if (!hasLoggedError) {\n hasLoggedError = true;\n\n error('React instrumentation encountered an error: %s', err);\n }\n }\n }\n };\n\n onCommitFiberUnmount = function (fiber) {\n try {\n hook.onCommitFiberUnmount(rendererID, fiber);\n } catch (err) {\n if (true) {\n if (!hasLoggedError) {\n hasLoggedError = true;\n\n error('React instrumentation encountered an error: %s', err);\n }\n }\n }\n };\n } catch (err) {\n // Catch all errors because it is unsafe to throw during initialization.\n {\n error('React instrumentation encountered an error: %s.', err);\n }\n } // DevTools exists\n\n\n return true;\n}\nfunction onScheduleRoot(root, children) {\n if (typeof onScheduleFiberRoot === 'function') {\n onScheduleFiberRoot(root, children);\n }\n}\nfunction onCommitRoot(root, expirationTime) {\n if (typeof onCommitFiberRoot === 'function') {\n onCommitFiberRoot(root, expirationTime);\n }\n}\nfunction onCommitUnmount(fiber) {\n if (typeof onCommitFiberUnmount === 'function') {\n onCommitFiberUnmount(fiber);\n }\n}\n\nvar hasBadMapPolyfill;\n\n{\n hasBadMapPolyfill = false;\n\n try {\n var nonExtensibleObject = Object.preventExtensions({});\n var testMap = new Map([[nonExtensibleObject, null]]);\n var testSet = new Set([nonExtensibleObject]); // This is necessary for Rollup to not consider these unused.\n // https://github.com/rollup/rollup/issues/1771\n // TODO: we can remove these if Rollup fixes the bug.\n\n testMap.set(0, 0);\n testSet.add(0);\n } catch (e) {\n // TODO: Consider warning about bad polyfills\n hasBadMapPolyfill = true;\n }\n}\n\nvar debugCounter = 1;\n\nfunction FiberNode(tag, pendingProps, key, mode) {\n // Instance\n this.tag = tag;\n this.key = key;\n this.elementType = null;\n this.type = null;\n this.stateNode = null; // Fiber\n\n this.return = null;\n this.child = null;\n this.sibling = null;\n this.index = 0;\n this.ref = null;\n this.pendingProps = pendingProps;\n this.memoizedProps = null;\n this.updateQueue = null;\n this.memoizedState = null;\n this.dependencies = null;\n this.mode = mode; // Effects\n\n this.effectTag = NoEffect;\n this.nextEffect = null;\n this.firstEffect = null;\n this.lastEffect = null;\n this.expirationTime = NoWork;\n this.childExpirationTime = NoWork;\n this.alternate = null;\n\n {\n // Note: The following is done to avoid a v8 performance cliff.\n //\n // Initializing the fields below to smis and later updating them with\n // double values will cause Fibers to end up having separate shapes.\n // This behavior/bug has something to do with Object.preventExtension().\n // Fortunately this only impacts DEV builds.\n // Unfortunately it makes React unusably slow for some applications.\n // To work around this, initialize the fields below with doubles.\n //\n // Learn more about this here:\n // https://github.com/facebook/react/issues/14365\n // https://bugs.chromium.org/p/v8/issues/detail?id=8538\n this.actualDuration = Number.NaN;\n this.actualStartTime = Number.NaN;\n this.selfBaseDuration = Number.NaN;\n this.treeBaseDuration = Number.NaN; // It's okay to replace the initial doubles with smis after initialization.\n // This won't trigger the performance cliff mentioned above,\n // and it simplifies other profiler code (including DevTools).\n\n this.actualDuration = 0;\n this.actualStartTime = -1;\n this.selfBaseDuration = 0;\n this.treeBaseDuration = 0;\n } // This is normally DEV-only except www when it adds listeners.\n // TODO: remove the User Timing integration in favor of Root Events.\n\n\n {\n this._debugID = debugCounter++;\n this._debugIsCurrentlyTiming = false;\n }\n\n {\n this._debugSource = null;\n this._debugOwner = null;\n this._debugNeedsRemount = false;\n this._debugHookTypes = null;\n\n if (!hasBadMapPolyfill && typeof Object.preventExtensions === 'function') {\n Object.preventExtensions(this);\n }\n }\n} // This is a constructor function, rather than a POJO constructor, still\n// please ensure we do the following:\n// 1) Nobody should add any instance methods on this. Instance methods can be\n// more difficult to predict when they get optimized and they are almost\n// never inlined properly in static compilers.\n// 2) Nobody should rely on `instanceof Fiber` for type testing. We should\n// always know when it is a fiber.\n// 3) We might want to experiment with using numeric keys since they are easier\n// to optimize in a non-JIT environment.\n// 4) We can easily go from a constructor to a createFiber object literal if that\n// is faster.\n// 5) It should be easy to port this to a C struct and keep a C implementation\n// compatible.\n\n\nvar createFiber = function (tag, pendingProps, key, mode) {\n // $FlowFixMe: the shapes are exact here but Flow doesn't like constructors\n return new FiberNode(tag, pendingProps, key, mode);\n};\n\nfunction shouldConstruct(Component) {\n var prototype = Component.prototype;\n return !!(prototype && prototype.isReactComponent);\n}\n\nfunction isSimpleFunctionComponent(type) {\n return typeof type === 'function' && !shouldConstruct(type) && type.defaultProps === undefined;\n}\nfunction resolveLazyComponentTag(Component) {\n if (typeof Component === 'function') {\n return shouldConstruct(Component) ? ClassComponent : FunctionComponent;\n } else if (Component !== undefined && Component !== null) {\n var $$typeof = Component.$$typeof;\n\n if ($$typeof === REACT_FORWARD_REF_TYPE) {\n return ForwardRef;\n }\n\n if ($$typeof === REACT_MEMO_TYPE) {\n return MemoComponent;\n }\n }\n\n return IndeterminateComponent;\n} // This is used to create an alternate fiber to do work on.\n\nfunction createWorkInProgress(current, pendingProps) {\n var workInProgress = current.alternate;\n\n if (workInProgress === null) {\n // We use a double buffering pooling technique because we know that we'll\n // only ever need at most two versions of a tree. We pool the \"other\" unused\n // node that we're free to reuse. This is lazily created to avoid allocating\n // extra objects for things that are never updated. It also allow us to\n // reclaim the extra memory if needed.\n workInProgress = createFiber(current.tag, pendingProps, current.key, current.mode);\n workInProgress.elementType = current.elementType;\n workInProgress.type = current.type;\n workInProgress.stateNode = current.stateNode;\n\n {\n // DEV-only fields\n {\n workInProgress._debugID = current._debugID;\n }\n\n workInProgress._debugSource = current._debugSource;\n workInProgress._debugOwner = current._debugOwner;\n workInProgress._debugHookTypes = current._debugHookTypes;\n }\n\n workInProgress.alternate = current;\n current.alternate = workInProgress;\n } else {\n workInProgress.pendingProps = pendingProps; // We already have an alternate.\n // Reset the effect tag.\n\n workInProgress.effectTag = NoEffect; // The effect list is no longer valid.\n\n workInProgress.nextEffect = null;\n workInProgress.firstEffect = null;\n workInProgress.lastEffect = null;\n\n {\n // We intentionally reset, rather than copy, actualDuration & actualStartTime.\n // This prevents time from endlessly accumulating in new commits.\n // This has the downside of resetting values for different priority renders,\n // But works for yielding (the common case) and should support resuming.\n workInProgress.actualDuration = 0;\n workInProgress.actualStartTime = -1;\n }\n }\n\n workInProgress.childExpirationTime = current.childExpirationTime;\n workInProgress.expirationTime = current.expirationTime;\n workInProgress.child = current.child;\n workInProgress.memoizedProps = current.memoizedProps;\n workInProgress.memoizedState = current.memoizedState;\n workInProgress.updateQueue = current.updateQueue; // Clone the dependencies object. This is mutated during the render phase, so\n // it cannot be shared with the current fiber.\n\n var currentDependencies = current.dependencies;\n workInProgress.dependencies = currentDependencies === null ? null : {\n expirationTime: currentDependencies.expirationTime,\n firstContext: currentDependencies.firstContext,\n responders: currentDependencies.responders\n }; // These will be overridden during the parent's reconciliation\n\n workInProgress.sibling = current.sibling;\n workInProgress.index = current.index;\n workInProgress.ref = current.ref;\n\n {\n workInProgress.selfBaseDuration = current.selfBaseDuration;\n workInProgress.treeBaseDuration = current.treeBaseDuration;\n }\n\n {\n workInProgress._debugNeedsRemount = current._debugNeedsRemount;\n\n switch (workInProgress.tag) {\n case IndeterminateComponent:\n case FunctionComponent:\n case SimpleMemoComponent:\n workInProgress.type = resolveFunctionForHotReloading(current.type);\n break;\n\n case ClassComponent:\n workInProgress.type = resolveClassForHotReloading(current.type);\n break;\n\n case ForwardRef:\n workInProgress.type = resolveForwardRefForHotReloading(current.type);\n break;\n }\n }\n\n return workInProgress;\n} // Used to reuse a Fiber for a second pass.\n\nfunction resetWorkInProgress(workInProgress, renderExpirationTime) {\n // This resets the Fiber to what createFiber or createWorkInProgress would\n // have set the values to before during the first pass. Ideally this wouldn't\n // be necessary but unfortunately many code paths reads from the workInProgress\n // when they should be reading from current and writing to workInProgress.\n // We assume pendingProps, index, key, ref, return are still untouched to\n // avoid doing another reconciliation.\n // Reset the effect tag but keep any Placement tags, since that's something\n // that child fiber is setting, not the reconciliation.\n workInProgress.effectTag &= Placement; // The effect list is no longer valid.\n\n workInProgress.nextEffect = null;\n workInProgress.firstEffect = null;\n workInProgress.lastEffect = null;\n var current = workInProgress.alternate;\n\n if (current === null) {\n // Reset to createFiber's initial values.\n workInProgress.childExpirationTime = NoWork;\n workInProgress.expirationTime = renderExpirationTime;\n workInProgress.child = null;\n workInProgress.memoizedProps = null;\n workInProgress.memoizedState = null;\n workInProgress.updateQueue = null;\n workInProgress.dependencies = null;\n\n {\n // Note: We don't reset the actualTime counts. It's useful to accumulate\n // actual time across multiple render passes.\n workInProgress.selfBaseDuration = 0;\n workInProgress.treeBaseDuration = 0;\n }\n } else {\n // Reset to the cloned values that createWorkInProgress would've.\n workInProgress.childExpirationTime = current.childExpirationTime;\n workInProgress.expirationTime = current.expirationTime;\n workInProgress.child = current.child;\n workInProgress.memoizedProps = current.memoizedProps;\n workInProgress.memoizedState = current.memoizedState;\n workInProgress.updateQueue = current.updateQueue; // Clone the dependencies object. This is mutated during the render phase, so\n // it cannot be shared with the current fiber.\n\n var currentDependencies = current.dependencies;\n workInProgress.dependencies = currentDependencies === null ? null : {\n expirationTime: currentDependencies.expirationTime,\n firstContext: currentDependencies.firstContext,\n responders: currentDependencies.responders\n };\n\n {\n // Note: We don't reset the actualTime counts. It's useful to accumulate\n // actual time across multiple render passes.\n workInProgress.selfBaseDuration = current.selfBaseDuration;\n workInProgress.treeBaseDuration = current.treeBaseDuration;\n }\n }\n\n return workInProgress;\n}\nfunction createHostRootFiber(tag) {\n var mode;\n\n if (tag === ConcurrentRoot) {\n mode = ConcurrentMode | BlockingMode | StrictMode;\n } else if (tag === BlockingRoot) {\n mode = BlockingMode | StrictMode;\n } else {\n mode = NoMode;\n }\n\n if ( isDevToolsPresent) {\n // Always collect profile timings when DevTools are present.\n // This enables DevTools to start capturing timing at any point–\n // Without some nodes in the tree having empty base times.\n mode |= ProfileMode;\n }\n\n return createFiber(HostRoot, null, null, mode);\n}\nfunction createFiberFromTypeAndProps(type, // React$ElementType\nkey, pendingProps, owner, mode, expirationTime) {\n var fiber;\n var fiberTag = IndeterminateComponent; // The resolved type is set if we know what the final type will be. I.e. it's not lazy.\n\n var resolvedType = type;\n\n if (typeof type === 'function') {\n if (shouldConstruct(type)) {\n fiberTag = ClassComponent;\n\n {\n resolvedType = resolveClassForHotReloading(resolvedType);\n }\n } else {\n {\n resolvedType = resolveFunctionForHotReloading(resolvedType);\n }\n }\n } else if (typeof type === 'string') {\n fiberTag = HostComponent;\n } else {\n getTag: switch (type) {\n case REACT_FRAGMENT_TYPE:\n return createFiberFromFragment(pendingProps.children, mode, expirationTime, key);\n\n case REACT_CONCURRENT_MODE_TYPE:\n fiberTag = Mode;\n mode |= ConcurrentMode | BlockingMode | StrictMode;\n break;\n\n case REACT_STRICT_MODE_TYPE:\n fiberTag = Mode;\n mode |= StrictMode;\n break;\n\n case REACT_PROFILER_TYPE:\n return createFiberFromProfiler(pendingProps, mode, expirationTime, key);\n\n case REACT_SUSPENSE_TYPE:\n return createFiberFromSuspense(pendingProps, mode, expirationTime, key);\n\n case REACT_SUSPENSE_LIST_TYPE:\n return createFiberFromSuspenseList(pendingProps, mode, expirationTime, key);\n\n default:\n {\n if (typeof type === 'object' && type !== null) {\n switch (type.$$typeof) {\n case REACT_PROVIDER_TYPE:\n fiberTag = ContextProvider;\n break getTag;\n\n case REACT_CONTEXT_TYPE:\n // This is a consumer\n fiberTag = ContextConsumer;\n break getTag;\n\n case REACT_FORWARD_REF_TYPE:\n fiberTag = ForwardRef;\n\n {\n resolvedType = resolveForwardRefForHotReloading(resolvedType);\n }\n\n break getTag;\n\n case REACT_MEMO_TYPE:\n fiberTag = MemoComponent;\n break getTag;\n\n case REACT_LAZY_TYPE:\n fiberTag = LazyComponent;\n resolvedType = null;\n break getTag;\n\n case REACT_BLOCK_TYPE:\n fiberTag = Block;\n break getTag;\n\n }\n }\n\n var info = '';\n\n {\n if (type === undefined || typeof type === 'object' && type !== null && Object.keys(type).length === 0) {\n info += ' You likely forgot to export your component from the file ' + \"it's defined in, or you might have mixed up default and \" + 'named imports.';\n }\n\n var ownerName = owner ? getComponentName(owner.type) : null;\n\n if (ownerName) {\n info += '\\n\\nCheck the render method of `' + ownerName + '`.';\n }\n }\n\n {\n {\n throw Error( \"Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: \" + (type == null ? type : typeof type) + \".\" + info );\n }\n }\n }\n }\n }\n\n fiber = createFiber(fiberTag, pendingProps, key, mode);\n fiber.elementType = type;\n fiber.type = resolvedType;\n fiber.expirationTime = expirationTime;\n return fiber;\n}\nfunction createFiberFromElement(element, mode, expirationTime) {\n var owner = null;\n\n {\n owner = element._owner;\n }\n\n var type = element.type;\n var key = element.key;\n var pendingProps = element.props;\n var fiber = createFiberFromTypeAndProps(type, key, pendingProps, owner, mode, expirationTime);\n\n {\n fiber._debugSource = element._source;\n fiber._debugOwner = element._owner;\n }\n\n return fiber;\n}\nfunction createFiberFromFragment(elements, mode, expirationTime, key) {\n var fiber = createFiber(Fragment, elements, key, mode);\n fiber.expirationTime = expirationTime;\n return fiber;\n}\n\nfunction createFiberFromProfiler(pendingProps, mode, expirationTime, key) {\n {\n if (typeof pendingProps.id !== 'string' || typeof pendingProps.onRender !== 'function') {\n error('Profiler must specify an \"id\" string and \"onRender\" function as props');\n }\n }\n\n var fiber = createFiber(Profiler, pendingProps, key, mode | ProfileMode); // TODO: The Profiler fiber shouldn't have a type. It has a tag.\n\n fiber.elementType = REACT_PROFILER_TYPE;\n fiber.type = REACT_PROFILER_TYPE;\n fiber.expirationTime = expirationTime;\n return fiber;\n}\n\nfunction createFiberFromSuspense(pendingProps, mode, expirationTime, key) {\n var fiber = createFiber(SuspenseComponent, pendingProps, key, mode); // TODO: The SuspenseComponent fiber shouldn't have a type. It has a tag.\n // This needs to be fixed in getComponentName so that it relies on the tag\n // instead.\n\n fiber.type = REACT_SUSPENSE_TYPE;\n fiber.elementType = REACT_SUSPENSE_TYPE;\n fiber.expirationTime = expirationTime;\n return fiber;\n}\nfunction createFiberFromSuspenseList(pendingProps, mode, expirationTime, key) {\n var fiber = createFiber(SuspenseListComponent, pendingProps, key, mode);\n\n {\n // TODO: The SuspenseListComponent fiber shouldn't have a type. It has a tag.\n // This needs to be fixed in getComponentName so that it relies on the tag\n // instead.\n fiber.type = REACT_SUSPENSE_LIST_TYPE;\n }\n\n fiber.elementType = REACT_SUSPENSE_LIST_TYPE;\n fiber.expirationTime = expirationTime;\n return fiber;\n}\nfunction createFiberFromText(content, mode, expirationTime) {\n var fiber = createFiber(HostText, content, null, mode);\n fiber.expirationTime = expirationTime;\n return fiber;\n}\nfunction createFiberFromHostInstanceForDeletion() {\n var fiber = createFiber(HostComponent, null, null, NoMode); // TODO: These should not need a type.\n\n fiber.elementType = 'DELETED';\n fiber.type = 'DELETED';\n return fiber;\n}\nfunction createFiberFromPortal(portal, mode, expirationTime) {\n var pendingProps = portal.children !== null ? portal.children : [];\n var fiber = createFiber(HostPortal, pendingProps, portal.key, mode);\n fiber.expirationTime = expirationTime;\n fiber.stateNode = {\n containerInfo: portal.containerInfo,\n pendingChildren: null,\n // Used by persistent updates\n implementation: portal.implementation\n };\n return fiber;\n} // Used for stashing WIP properties to replay failed work in DEV.\n\nfunction assignFiberPropertiesInDEV(target, source) {\n if (target === null) {\n // This Fiber's initial properties will always be overwritten.\n // We only use a Fiber to ensure the same hidden class so DEV isn't slow.\n target = createFiber(IndeterminateComponent, null, null, NoMode);\n } // This is intentionally written as a list of all properties.\n // We tried to use Object.assign() instead but this is called in\n // the hottest path, and Object.assign() was too slow:\n // https://github.com/facebook/react/issues/12502\n // This code is DEV-only so size is not a concern.\n\n\n target.tag = source.tag;\n target.key = source.key;\n target.elementType = source.elementType;\n target.type = source.type;\n target.stateNode = source.stateNode;\n target.return = source.return;\n target.child = source.child;\n target.sibling = source.sibling;\n target.index = source.index;\n target.ref = source.ref;\n target.pendingProps = source.pendingProps;\n target.memoizedProps = source.memoizedProps;\n target.updateQueue = source.updateQueue;\n target.memoizedState = source.memoizedState;\n target.dependencies = source.dependencies;\n target.mode = source.mode;\n target.effectTag = source.effectTag;\n target.nextEffect = source.nextEffect;\n target.firstEffect = source.firstEffect;\n target.lastEffect = source.lastEffect;\n target.expirationTime = source.expirationTime;\n target.childExpirationTime = source.childExpirationTime;\n target.alternate = source.alternate;\n\n {\n target.actualDuration = source.actualDuration;\n target.actualStartTime = source.actualStartTime;\n target.selfBaseDuration = source.selfBaseDuration;\n target.treeBaseDuration = source.treeBaseDuration;\n }\n\n {\n target._debugID = source._debugID;\n }\n\n target._debugSource = source._debugSource;\n target._debugOwner = source._debugOwner;\n target._debugIsCurrentlyTiming = source._debugIsCurrentlyTiming;\n target._debugNeedsRemount = source._debugNeedsRemount;\n target._debugHookTypes = source._debugHookTypes;\n return target;\n}\n\nfunction FiberRootNode(containerInfo, tag, hydrate) {\n this.tag = tag;\n this.current = null;\n this.containerInfo = containerInfo;\n this.pendingChildren = null;\n this.pingCache = null;\n this.finishedExpirationTime = NoWork;\n this.finishedWork = null;\n this.timeoutHandle = noTimeout;\n this.context = null;\n this.pendingContext = null;\n this.hydrate = hydrate;\n this.callbackNode = null;\n this.callbackPriority = NoPriority;\n this.firstPendingTime = NoWork;\n this.firstSuspendedTime = NoWork;\n this.lastSuspendedTime = NoWork;\n this.nextKnownPendingLevel = NoWork;\n this.lastPingedTime = NoWork;\n this.lastExpiredTime = NoWork;\n\n {\n this.interactionThreadID = tracing.unstable_getThreadID();\n this.memoizedInteractions = new Set();\n this.pendingInteractionMap = new Map();\n }\n}\n\nfunction createFiberRoot(containerInfo, tag, hydrate, hydrationCallbacks) {\n var root = new FiberRootNode(containerInfo, tag, hydrate);\n // stateNode is any.\n\n\n var uninitializedFiber = createHostRootFiber(tag);\n root.current = uninitializedFiber;\n uninitializedFiber.stateNode = root;\n initializeUpdateQueue(uninitializedFiber);\n return root;\n}\nfunction isRootSuspendedAtTime(root, expirationTime) {\n var firstSuspendedTime = root.firstSuspendedTime;\n var lastSuspendedTime = root.lastSuspendedTime;\n return firstSuspendedTime !== NoWork && firstSuspendedTime >= expirationTime && lastSuspendedTime <= expirationTime;\n}\nfunction markRootSuspendedAtTime(root, expirationTime) {\n var firstSuspendedTime = root.firstSuspendedTime;\n var lastSuspendedTime = root.lastSuspendedTime;\n\n if (firstSuspendedTime < expirationTime) {\n root.firstSuspendedTime = expirationTime;\n }\n\n if (lastSuspendedTime > expirationTime || firstSuspendedTime === NoWork) {\n root.lastSuspendedTime = expirationTime;\n }\n\n if (expirationTime <= root.lastPingedTime) {\n root.lastPingedTime = NoWork;\n }\n\n if (expirationTime <= root.lastExpiredTime) {\n root.lastExpiredTime = NoWork;\n }\n}\nfunction markRootUpdatedAtTime(root, expirationTime) {\n // Update the range of pending times\n var firstPendingTime = root.firstPendingTime;\n\n if (expirationTime > firstPendingTime) {\n root.firstPendingTime = expirationTime;\n } // Update the range of suspended times. Treat everything lower priority or\n // equal to this update as unsuspended.\n\n\n var firstSuspendedTime = root.firstSuspendedTime;\n\n if (firstSuspendedTime !== NoWork) {\n if (expirationTime >= firstSuspendedTime) {\n // The entire suspended range is now unsuspended.\n root.firstSuspendedTime = root.lastSuspendedTime = root.nextKnownPendingLevel = NoWork;\n } else if (expirationTime >= root.lastSuspendedTime) {\n root.lastSuspendedTime = expirationTime + 1;\n } // This is a pending level. Check if it's higher priority than the next\n // known pending level.\n\n\n if (expirationTime > root.nextKnownPendingLevel) {\n root.nextKnownPendingLevel = expirationTime;\n }\n }\n}\nfunction markRootFinishedAtTime(root, finishedExpirationTime, remainingExpirationTime) {\n // Update the range of pending times\n root.firstPendingTime = remainingExpirationTime; // Update the range of suspended times. Treat everything higher priority or\n // equal to this update as unsuspended.\n\n if (finishedExpirationTime <= root.lastSuspendedTime) {\n // The entire suspended range is now unsuspended.\n root.firstSuspendedTime = root.lastSuspendedTime = root.nextKnownPendingLevel = NoWork;\n } else if (finishedExpirationTime <= root.firstSuspendedTime) {\n // Part of the suspended range is now unsuspended. Narrow the range to\n // include everything between the unsuspended time (non-inclusive) and the\n // last suspended time.\n root.firstSuspendedTime = finishedExpirationTime - 1;\n }\n\n if (finishedExpirationTime <= root.lastPingedTime) {\n // Clear the pinged time\n root.lastPingedTime = NoWork;\n }\n\n if (finishedExpirationTime <= root.lastExpiredTime) {\n // Clear the expired time\n root.lastExpiredTime = NoWork;\n }\n}\nfunction markRootExpiredAtTime(root, expirationTime) {\n var lastExpiredTime = root.lastExpiredTime;\n\n if (lastExpiredTime === NoWork || lastExpiredTime > expirationTime) {\n root.lastExpiredTime = expirationTime;\n }\n}\n\nvar didWarnAboutNestedUpdates;\nvar didWarnAboutFindNodeInStrictMode;\n\n{\n didWarnAboutNestedUpdates = false;\n didWarnAboutFindNodeInStrictMode = {};\n}\n\nfunction getContextForSubtree(parentComponent) {\n if (!parentComponent) {\n return emptyContextObject;\n }\n\n var fiber = get(parentComponent);\n var parentContext = findCurrentUnmaskedContext(fiber);\n\n if (fiber.tag === ClassComponent) {\n var Component = fiber.type;\n\n if (isContextProvider(Component)) {\n return processChildContext(fiber, Component, parentContext);\n }\n }\n\n return parentContext;\n}\n\nfunction findHostInstanceWithWarning(component, methodName) {\n {\n var fiber = get(component);\n\n if (fiber === undefined) {\n if (typeof component.render === 'function') {\n {\n {\n throw Error( \"Unable to find node on an unmounted component.\" );\n }\n }\n } else {\n {\n {\n throw Error( \"Argument appears to not be a ReactComponent. Keys: \" + Object.keys(component) );\n }\n }\n }\n }\n\n var hostFiber = findCurrentHostFiber(fiber);\n\n if (hostFiber === null) {\n return null;\n }\n\n if (hostFiber.mode & StrictMode) {\n var componentName = getComponentName(fiber.type) || 'Component';\n\n if (!didWarnAboutFindNodeInStrictMode[componentName]) {\n didWarnAboutFindNodeInStrictMode[componentName] = true;\n\n if (fiber.mode & StrictMode) {\n error('%s is deprecated in StrictMode. ' + '%s was passed an instance of %s which is inside StrictMode. ' + 'Instead, add a ref directly to the element you want to reference. ' + 'Learn more about using refs safely here: ' + 'https://fb.me/react-strict-mode-find-node%s', methodName, methodName, componentName, getStackByFiberInDevAndProd(hostFiber));\n } else {\n error('%s is deprecated in StrictMode. ' + '%s was passed an instance of %s which renders StrictMode children. ' + 'Instead, add a ref directly to the element you want to reference. ' + 'Learn more about using refs safely here: ' + 'https://fb.me/react-strict-mode-find-node%s', methodName, methodName, componentName, getStackByFiberInDevAndProd(hostFiber));\n }\n }\n }\n\n return hostFiber.stateNode;\n }\n}\n\nfunction createContainer(containerInfo, tag, hydrate, hydrationCallbacks) {\n return createFiberRoot(containerInfo, tag, hydrate);\n}\nfunction updateContainer(element, container, parentComponent, callback) {\n {\n onScheduleRoot(container, element);\n }\n\n var current$1 = container.current;\n var currentTime = requestCurrentTimeForUpdate();\n\n {\n // $FlowExpectedError - jest isn't a global, and isn't recognized outside of tests\n if ('undefined' !== typeof jest) {\n warnIfUnmockedScheduler(current$1);\n warnIfNotScopedWithMatchingAct(current$1);\n }\n }\n\n var suspenseConfig = requestCurrentSuspenseConfig();\n var expirationTime = computeExpirationForFiber(currentTime, current$1, suspenseConfig);\n var context = getContextForSubtree(parentComponent);\n\n if (container.context === null) {\n container.context = context;\n } else {\n container.pendingContext = context;\n }\n\n {\n if (isRendering && current !== null && !didWarnAboutNestedUpdates) {\n didWarnAboutNestedUpdates = true;\n\n error('Render methods should be a pure function of props and state; ' + 'triggering nested component updates from render is not allowed. ' + 'If necessary, trigger nested updates in componentDidUpdate.\\n\\n' + 'Check the render method of %s.', getComponentName(current.type) || 'Unknown');\n }\n }\n\n var update = createUpdate(expirationTime, suspenseConfig); // Caution: React DevTools currently depends on this property\n // being called \"element\".\n\n update.payload = {\n element: element\n };\n callback = callback === undefined ? null : callback;\n\n if (callback !== null) {\n {\n if (typeof callback !== 'function') {\n error('render(...): Expected the last optional `callback` argument to be a ' + 'function. Instead received: %s.', callback);\n }\n }\n\n update.callback = callback;\n }\n\n enqueueUpdate(current$1, update);\n scheduleWork(current$1, expirationTime);\n return expirationTime;\n}\nfunction getPublicRootInstance(container) {\n var containerFiber = container.current;\n\n if (!containerFiber.child) {\n return null;\n }\n\n switch (containerFiber.child.tag) {\n case HostComponent:\n return getPublicInstance(containerFiber.child.stateNode);\n\n default:\n return containerFiber.child.stateNode;\n }\n}\n\nfunction markRetryTimeImpl(fiber, retryTime) {\n var suspenseState = fiber.memoizedState;\n\n if (suspenseState !== null && suspenseState.dehydrated !== null) {\n if (suspenseState.retryTime < retryTime) {\n suspenseState.retryTime = retryTime;\n }\n }\n} // Increases the priority of thennables when they resolve within this boundary.\n\n\nfunction markRetryTimeIfNotHydrated(fiber, retryTime) {\n markRetryTimeImpl(fiber, retryTime);\n var alternate = fiber.alternate;\n\n if (alternate) {\n markRetryTimeImpl(alternate, retryTime);\n }\n}\n\nfunction attemptUserBlockingHydration$1(fiber) {\n if (fiber.tag !== SuspenseComponent) {\n // We ignore HostRoots here because we can't increase\n // their priority and they should not suspend on I/O,\n // since you have to wrap anything that might suspend in\n // Suspense.\n return;\n }\n\n var expTime = computeInteractiveExpiration(requestCurrentTimeForUpdate());\n scheduleWork(fiber, expTime);\n markRetryTimeIfNotHydrated(fiber, expTime);\n}\nfunction attemptContinuousHydration$1(fiber) {\n if (fiber.tag !== SuspenseComponent) {\n // We ignore HostRoots here because we can't increase\n // their priority and they should not suspend on I/O,\n // since you have to wrap anything that might suspend in\n // Suspense.\n return;\n }\n\n scheduleWork(fiber, ContinuousHydration);\n markRetryTimeIfNotHydrated(fiber, ContinuousHydration);\n}\nfunction attemptHydrationAtCurrentPriority$1(fiber) {\n if (fiber.tag !== SuspenseComponent) {\n // We ignore HostRoots here because we can't increase\n // their priority other than synchronously flush it.\n return;\n }\n\n var currentTime = requestCurrentTimeForUpdate();\n var expTime = computeExpirationForFiber(currentTime, fiber, null);\n scheduleWork(fiber, expTime);\n markRetryTimeIfNotHydrated(fiber, expTime);\n}\nfunction findHostInstanceWithNoPortals(fiber) {\n var hostFiber = findCurrentHostFiberWithNoPortals(fiber);\n\n if (hostFiber === null) {\n return null;\n }\n\n if (hostFiber.tag === FundamentalComponent) {\n return hostFiber.stateNode.instance;\n }\n\n return hostFiber.stateNode;\n}\n\nvar shouldSuspendImpl = function (fiber) {\n return false;\n};\n\nfunction shouldSuspend(fiber) {\n return shouldSuspendImpl(fiber);\n}\nvar overrideHookState = null;\nvar overrideProps = null;\nvar scheduleUpdate = null;\nvar setSuspenseHandler = null;\n\n{\n var copyWithSetImpl = function (obj, path, idx, value) {\n if (idx >= path.length) {\n return value;\n }\n\n var key = path[idx];\n var updated = Array.isArray(obj) ? obj.slice() : _assign({}, obj); // $FlowFixMe number or string is fine here\n\n updated[key] = copyWithSetImpl(obj[key], path, idx + 1, value);\n return updated;\n };\n\n var copyWithSet = function (obj, path, value) {\n return copyWithSetImpl(obj, path, 0, value);\n }; // Support DevTools editable values for useState and useReducer.\n\n\n overrideHookState = function (fiber, id, path, value) {\n // For now, the \"id\" of stateful hooks is just the stateful hook index.\n // This may change in the future with e.g. nested hooks.\n var currentHook = fiber.memoizedState;\n\n while (currentHook !== null && id > 0) {\n currentHook = currentHook.next;\n id--;\n }\n\n if (currentHook !== null) {\n var newState = copyWithSet(currentHook.memoizedState, path, value);\n currentHook.memoizedState = newState;\n currentHook.baseState = newState; // We aren't actually adding an update to the queue,\n // because there is no update we can add for useReducer hooks that won't trigger an error.\n // (There's no appropriate action type for DevTools overrides.)\n // As a result though, React will see the scheduled update as a noop and bailout.\n // Shallow cloning props works as a workaround for now to bypass the bailout check.\n\n fiber.memoizedProps = _assign({}, fiber.memoizedProps);\n scheduleWork(fiber, Sync);\n }\n }; // Support DevTools props for function components, forwardRef, memo, host components, etc.\n\n\n overrideProps = function (fiber, path, value) {\n fiber.pendingProps = copyWithSet(fiber.memoizedProps, path, value);\n\n if (fiber.alternate) {\n fiber.alternate.pendingProps = fiber.pendingProps;\n }\n\n scheduleWork(fiber, Sync);\n };\n\n scheduleUpdate = function (fiber) {\n scheduleWork(fiber, Sync);\n };\n\n setSuspenseHandler = function (newShouldSuspendImpl) {\n shouldSuspendImpl = newShouldSuspendImpl;\n };\n}\n\nfunction injectIntoDevTools(devToolsConfig) {\n var findFiberByHostInstance = devToolsConfig.findFiberByHostInstance;\n var ReactCurrentDispatcher = ReactSharedInternals.ReactCurrentDispatcher;\n return injectInternals(_assign({}, devToolsConfig, {\n overrideHookState: overrideHookState,\n overrideProps: overrideProps,\n setSuspenseHandler: setSuspenseHandler,\n scheduleUpdate: scheduleUpdate,\n currentDispatcherRef: ReactCurrentDispatcher,\n findHostInstanceByFiber: function (fiber) {\n var hostFiber = findCurrentHostFiber(fiber);\n\n if (hostFiber === null) {\n return null;\n }\n\n return hostFiber.stateNode;\n },\n findFiberByHostInstance: function (instance) {\n if (!findFiberByHostInstance) {\n // Might not be implemented by the renderer.\n return null;\n }\n\n return findFiberByHostInstance(instance);\n },\n // React Refresh\n findHostInstancesForRefresh: findHostInstancesForRefresh ,\n scheduleRefresh: scheduleRefresh ,\n scheduleRoot: scheduleRoot ,\n setRefreshHandler: setRefreshHandler ,\n // Enables DevTools to append owner stacks to error messages in DEV mode.\n getCurrentFiber: function () {\n return current;\n } \n }));\n}\nvar IsSomeRendererActing$1 = ReactSharedInternals.IsSomeRendererActing;\n\nfunction ReactDOMRoot(container, options) {\n this._internalRoot = createRootImpl(container, ConcurrentRoot, options);\n}\n\nfunction ReactDOMBlockingRoot(container, tag, options) {\n this._internalRoot = createRootImpl(container, tag, options);\n}\n\nReactDOMRoot.prototype.render = ReactDOMBlockingRoot.prototype.render = function (children) {\n var root = this._internalRoot;\n\n {\n if (typeof arguments[1] === 'function') {\n error('render(...): does not support the second callback argument. ' + 'To execute a side effect after rendering, declare it in a component body with useEffect().');\n }\n\n var container = root.containerInfo;\n\n if (container.nodeType !== COMMENT_NODE) {\n var hostInstance = findHostInstanceWithNoPortals(root.current);\n\n if (hostInstance) {\n if (hostInstance.parentNode !== container) {\n error('render(...): It looks like the React-rendered content of the ' + 'root container was removed without using React. This is not ' + 'supported and will cause errors. Instead, call ' + \"root.unmount() to empty a root's container.\");\n }\n }\n }\n }\n\n updateContainer(children, root, null, null);\n};\n\nReactDOMRoot.prototype.unmount = ReactDOMBlockingRoot.prototype.unmount = function () {\n {\n if (typeof arguments[0] === 'function') {\n error('unmount(...): does not support a callback argument. ' + 'To execute a side effect after rendering, declare it in a component body with useEffect().');\n }\n }\n\n var root = this._internalRoot;\n var container = root.containerInfo;\n updateContainer(null, root, null, function () {\n unmarkContainerAsRoot(container);\n });\n};\n\nfunction createRootImpl(container, tag, options) {\n // Tag is either LegacyRoot or Concurrent Root\n var hydrate = options != null && options.hydrate === true;\n var hydrationCallbacks = options != null && options.hydrationOptions || null;\n var root = createContainer(container, tag, hydrate);\n markContainerAsRoot(root.current, container);\n\n if (hydrate && tag !== LegacyRoot) {\n var doc = container.nodeType === DOCUMENT_NODE ? container : container.ownerDocument;\n eagerlyTrapReplayableEvents(container, doc);\n }\n\n return root;\n}\nfunction createLegacyRoot(container, options) {\n return new ReactDOMBlockingRoot(container, LegacyRoot, options);\n}\nfunction isValidContainer(node) {\n return !!(node && (node.nodeType === ELEMENT_NODE || node.nodeType === DOCUMENT_NODE || node.nodeType === DOCUMENT_FRAGMENT_NODE || node.nodeType === COMMENT_NODE && node.nodeValue === ' react-mount-point-unstable '));\n}\n\nvar ReactCurrentOwner$3 = ReactSharedInternals.ReactCurrentOwner;\nvar topLevelUpdateWarnings;\nvar warnedAboutHydrateAPI = false;\n\n{\n topLevelUpdateWarnings = function (container) {\n if (container._reactRootContainer && container.nodeType !== COMMENT_NODE) {\n var hostInstance = findHostInstanceWithNoPortals(container._reactRootContainer._internalRoot.current);\n\n if (hostInstance) {\n if (hostInstance.parentNode !== container) {\n error('render(...): It looks like the React-rendered content of this ' + 'container was removed without using React. This is not ' + 'supported and will cause errors. Instead, call ' + 'ReactDOM.unmountComponentAtNode to empty a container.');\n }\n }\n }\n\n var isRootRenderedBySomeReact = !!container._reactRootContainer;\n var rootEl = getReactRootElementInContainer(container);\n var hasNonRootReactChild = !!(rootEl && getInstanceFromNode$1(rootEl));\n\n if (hasNonRootReactChild && !isRootRenderedBySomeReact) {\n error('render(...): Replacing React-rendered children with a new root ' + 'component. If you intended to update the children of this node, ' + 'you should instead have the existing children update their state ' + 'and render the new components instead of calling ReactDOM.render.');\n }\n\n if (container.nodeType === ELEMENT_NODE && container.tagName && container.tagName.toUpperCase() === 'BODY') {\n error('render(): Rendering components directly into document.body is ' + 'discouraged, since its children are often manipulated by third-party ' + 'scripts and browser extensions. This may lead to subtle ' + 'reconciliation issues. Try rendering into a container element created ' + 'for your app.');\n }\n };\n}\n\nfunction getReactRootElementInContainer(container) {\n if (!container) {\n return null;\n }\n\n if (container.nodeType === DOCUMENT_NODE) {\n return container.documentElement;\n } else {\n return container.firstChild;\n }\n}\n\nfunction shouldHydrateDueToLegacyHeuristic(container) {\n var rootElement = getReactRootElementInContainer(container);\n return !!(rootElement && rootElement.nodeType === ELEMENT_NODE && rootElement.hasAttribute(ROOT_ATTRIBUTE_NAME));\n}\n\nfunction legacyCreateRootFromDOMContainer(container, forceHydrate) {\n var shouldHydrate = forceHydrate || shouldHydrateDueToLegacyHeuristic(container); // First clear any existing content.\n\n if (!shouldHydrate) {\n var warned = false;\n var rootSibling;\n\n while (rootSibling = container.lastChild) {\n {\n if (!warned && rootSibling.nodeType === ELEMENT_NODE && rootSibling.hasAttribute(ROOT_ATTRIBUTE_NAME)) {\n warned = true;\n\n error('render(): Target node has markup rendered by React, but there ' + 'are unrelated nodes as well. This is most commonly caused by ' + 'white-space inserted around server-rendered markup.');\n }\n }\n\n container.removeChild(rootSibling);\n }\n }\n\n {\n if (shouldHydrate && !forceHydrate && !warnedAboutHydrateAPI) {\n warnedAboutHydrateAPI = true;\n\n warn('render(): Calling ReactDOM.render() to hydrate server-rendered markup ' + 'will stop working in React v17. Replace the ReactDOM.render() call ' + 'with ReactDOM.hydrate() if you want React to attach to the server HTML.');\n }\n }\n\n return createLegacyRoot(container, shouldHydrate ? {\n hydrate: true\n } : undefined);\n}\n\nfunction warnOnInvalidCallback$1(callback, callerName) {\n {\n if (callback !== null && typeof callback !== 'function') {\n error('%s(...): Expected the last optional `callback` argument to be a ' + 'function. Instead received: %s.', callerName, callback);\n }\n }\n}\n\nfunction legacyRenderSubtreeIntoContainer(parentComponent, children, container, forceHydrate, callback) {\n {\n topLevelUpdateWarnings(container);\n warnOnInvalidCallback$1(callback === undefined ? null : callback, 'render');\n } // TODO: Without `any` type, Flow says \"Property cannot be accessed on any\n // member of intersection type.\" Whyyyyyy.\n\n\n var root = container._reactRootContainer;\n var fiberRoot;\n\n if (!root) {\n // Initial mount\n root = container._reactRootContainer = legacyCreateRootFromDOMContainer(container, forceHydrate);\n fiberRoot = root._internalRoot;\n\n if (typeof callback === 'function') {\n var originalCallback = callback;\n\n callback = function () {\n var instance = getPublicRootInstance(fiberRoot);\n originalCallback.call(instance);\n };\n } // Initial mount should not be batched.\n\n\n unbatchedUpdates(function () {\n updateContainer(children, fiberRoot, parentComponent, callback);\n });\n } else {\n fiberRoot = root._internalRoot;\n\n if (typeof callback === 'function') {\n var _originalCallback = callback;\n\n callback = function () {\n var instance = getPublicRootInstance(fiberRoot);\n\n _originalCallback.call(instance);\n };\n } // Update\n\n\n updateContainer(children, fiberRoot, parentComponent, callback);\n }\n\n return getPublicRootInstance(fiberRoot);\n}\n\nfunction findDOMNode(componentOrElement) {\n {\n var owner = ReactCurrentOwner$3.current;\n\n if (owner !== null && owner.stateNode !== null) {\n var warnedAboutRefsInRender = owner.stateNode._warnedAboutRefsInRender;\n\n if (!warnedAboutRefsInRender) {\n error('%s is accessing findDOMNode inside its render(). ' + 'render() should be a pure function of props and state. It should ' + 'never access something that requires stale data from the previous ' + 'render, such as refs. Move this logic to componentDidMount and ' + 'componentDidUpdate instead.', getComponentName(owner.type) || 'A component');\n }\n\n owner.stateNode._warnedAboutRefsInRender = true;\n }\n }\n\n if (componentOrElement == null) {\n return null;\n }\n\n if (componentOrElement.nodeType === ELEMENT_NODE) {\n return componentOrElement;\n }\n\n {\n return findHostInstanceWithWarning(componentOrElement, 'findDOMNode');\n }\n}\nfunction hydrate(element, container, callback) {\n if (!isValidContainer(container)) {\n {\n throw Error( \"Target container is not a DOM element.\" );\n }\n }\n\n {\n var isModernRoot = isContainerMarkedAsRoot(container) && container._reactRootContainer === undefined;\n\n if (isModernRoot) {\n error('You are calling ReactDOM.hydrate() on a container that was previously ' + 'passed to ReactDOM.createRoot(). This is not supported. ' + 'Did you mean to call createRoot(container, {hydrate: true}).render(element)?');\n }\n } // TODO: throw or warn if we couldn't hydrate?\n\n\n return legacyRenderSubtreeIntoContainer(null, element, container, true, callback);\n}\nfunction render(element, container, callback) {\n if (!isValidContainer(container)) {\n {\n throw Error( \"Target container is not a DOM element.\" );\n }\n }\n\n {\n var isModernRoot = isContainerMarkedAsRoot(container) && container._reactRootContainer === undefined;\n\n if (isModernRoot) {\n error('You are calling ReactDOM.render() on a container that was previously ' + 'passed to ReactDOM.createRoot(). This is not supported. ' + 'Did you mean to call root.render(element)?');\n }\n }\n\n return legacyRenderSubtreeIntoContainer(null, element, container, false, callback);\n}\nfunction unstable_renderSubtreeIntoContainer(parentComponent, element, containerNode, callback) {\n if (!isValidContainer(containerNode)) {\n {\n throw Error( \"Target container is not a DOM element.\" );\n }\n }\n\n if (!(parentComponent != null && has(parentComponent))) {\n {\n throw Error( \"parentComponent must be a valid React Component\" );\n }\n }\n\n return legacyRenderSubtreeIntoContainer(parentComponent, element, containerNode, false, callback);\n}\nfunction unmountComponentAtNode(container) {\n if (!isValidContainer(container)) {\n {\n throw Error( \"unmountComponentAtNode(...): Target container is not a DOM element.\" );\n }\n }\n\n {\n var isModernRoot = isContainerMarkedAsRoot(container) && container._reactRootContainer === undefined;\n\n if (isModernRoot) {\n error('You are calling ReactDOM.unmountComponentAtNode() on a container that was previously ' + 'passed to ReactDOM.createRoot(). This is not supported. Did you mean to call root.unmount()?');\n }\n }\n\n if (container._reactRootContainer) {\n {\n var rootEl = getReactRootElementInContainer(container);\n var renderedByDifferentReact = rootEl && !getInstanceFromNode$1(rootEl);\n\n if (renderedByDifferentReact) {\n error(\"unmountComponentAtNode(): The node you're attempting to unmount \" + 'was rendered by another copy of React.');\n }\n } // Unmount should not be batched.\n\n\n unbatchedUpdates(function () {\n legacyRenderSubtreeIntoContainer(null, null, container, false, function () {\n // $FlowFixMe This should probably use `delete container._reactRootContainer`\n container._reactRootContainer = null;\n unmarkContainerAsRoot(container);\n });\n }); // If you call unmountComponentAtNode twice in quick succession, you'll\n // get `true` twice. That's probably fine?\n\n return true;\n } else {\n {\n var _rootEl = getReactRootElementInContainer(container);\n\n var hasNonRootReactChild = !!(_rootEl && getInstanceFromNode$1(_rootEl)); // Check if the container itself is a React root node.\n\n var isContainerReactRoot = container.nodeType === ELEMENT_NODE && isValidContainer(container.parentNode) && !!container.parentNode._reactRootContainer;\n\n if (hasNonRootReactChild) {\n error(\"unmountComponentAtNode(): The node you're attempting to unmount \" + 'was rendered by React and is not a top-level container. %s', isContainerReactRoot ? 'You may have accidentally passed in a React root node instead ' + 'of its container.' : 'Instead, have the parent component update its state and ' + 'rerender in order to remove this component.');\n }\n }\n\n return false;\n }\n}\n\nfunction createPortal(children, containerInfo, // TODO: figure out the API for cross-renderer implementation.\nimplementation) {\n var key = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : null;\n return {\n // This tag allow us to uniquely identify this as a React Portal\n $$typeof: REACT_PORTAL_TYPE,\n key: key == null ? null : '' + key,\n children: children,\n containerInfo: containerInfo,\n implementation: implementation\n };\n}\n\nvar ReactVersion = '16.13.1';\n\nsetAttemptUserBlockingHydration(attemptUserBlockingHydration$1);\nsetAttemptContinuousHydration(attemptContinuousHydration$1);\nsetAttemptHydrationAtCurrentPriority(attemptHydrationAtCurrentPriority$1);\nvar didWarnAboutUnstableCreatePortal = false;\n\n{\n if (typeof Map !== 'function' || // $FlowIssue Flow incorrectly thinks Map has no prototype\n Map.prototype == null || typeof Map.prototype.forEach !== 'function' || typeof Set !== 'function' || // $FlowIssue Flow incorrectly thinks Set has no prototype\n Set.prototype == null || typeof Set.prototype.clear !== 'function' || typeof Set.prototype.forEach !== 'function') {\n error('React depends on Map and Set built-in types. Make sure that you load a ' + 'polyfill in older browsers. https://fb.me/react-polyfills');\n }\n}\n\nsetRestoreImplementation(restoreControlledState$3);\nsetBatchingImplementation(batchedUpdates$1, discreteUpdates$1, flushDiscreteUpdates, batchedEventUpdates$1);\n\nfunction createPortal$1(children, container) {\n var key = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null;\n\n if (!isValidContainer(container)) {\n {\n throw Error( \"Target container is not a DOM element.\" );\n }\n } // TODO: pass ReactDOM portal implementation as third argument\n // $FlowFixMe The Flow type is opaque but there's no way to actually create it.\n\n\n return createPortal(children, container, null, key);\n}\n\nfunction renderSubtreeIntoContainer(parentComponent, element, containerNode, callback) {\n\n return unstable_renderSubtreeIntoContainer(parentComponent, element, containerNode, callback);\n}\n\nfunction unstable_createPortal(children, container) {\n var key = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null;\n\n {\n if (!didWarnAboutUnstableCreatePortal) {\n didWarnAboutUnstableCreatePortal = true;\n\n warn('The ReactDOM.unstable_createPortal() alias has been deprecated, ' + 'and will be removed in React 17+. Update your code to use ' + 'ReactDOM.createPortal() instead. It has the exact same API, ' + 'but without the \"unstable_\" prefix.');\n }\n }\n\n return createPortal$1(children, container, key);\n}\n\nvar Internals = {\n // Keep in sync with ReactDOMUnstableNativeDependencies.js\n // ReactTestUtils.js, and ReactTestUtilsAct.js. This is an array for better minification.\n Events: [getInstanceFromNode$1, getNodeFromInstance$1, getFiberCurrentPropsFromNode$1, injectEventPluginsByName, eventNameDispatchConfigs, accumulateTwoPhaseDispatches, accumulateDirectDispatches, enqueueStateRestore, restoreStateIfNeeded, dispatchEvent, runEventsInBatch, flushPassiveEffects, IsThisRendererActing]\n};\nvar foundDevTools = injectIntoDevTools({\n findFiberByHostInstance: getClosestInstanceFromNode,\n bundleType: 1 ,\n version: ReactVersion,\n rendererPackageName: 'react-dom'\n});\n\n{\n if (!foundDevTools && canUseDOM && window.top === window.self) {\n // If we're in Chrome or Firefox, provide a download link if not installed.\n if (navigator.userAgent.indexOf('Chrome') > -1 && navigator.userAgent.indexOf('Edge') === -1 || navigator.userAgent.indexOf('Firefox') > -1) {\n var protocol = window.location.protocol; // Don't warn in exotic cases like chrome-extension://.\n\n if (/^(https?|file):$/.test(protocol)) {\n // eslint-disable-next-line react-internal/no-production-logging\n console.info('%cDownload the React DevTools ' + 'for a better development experience: ' + 'https://fb.me/react-devtools' + (protocol === 'file:' ? '\\nYou might need to use a local HTTP server (instead of file://): ' + 'https://fb.me/react-devtools-faq' : ''), 'font-weight:bold');\n }\n }\n }\n}\n\nexports.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED = Internals;\nexports.createPortal = createPortal$1;\nexports.findDOMNode = findDOMNode;\nexports.flushSync = flushSync;\nexports.hydrate = hydrate;\nexports.render = render;\nexports.unmountComponentAtNode = unmountComponentAtNode;\nexports.unstable_batchedUpdates = batchedUpdates$1;\nexports.unstable_createPortal = unstable_createPortal;\nexports.unstable_renderSubtreeIntoContainer = renderSubtreeIntoContainer;\nexports.version = ReactVersion;\n })();\n}\n\n\n//# sourceURL=webpack:///./node_modules/react-dom/cjs/react-dom.development.js?");
/***/ }),
/***/ "./node_modules/react-dom/index.js":
/*!*****************************************!*\
!*** ./node_modules/react-dom/index.js ***!
\*****************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
eval("\n\nfunction checkDCE() {\n /* global __REACT_DEVTOOLS_GLOBAL_HOOK__ */\n if (\n typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ === 'undefined' ||\n typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE !== 'function'\n ) {\n return;\n }\n if (true) {\n // This branch is unreachable because this function is only called\n // in production, but the condition is true only in development.\n // Therefore if the branch is still here, dead code elimination wasn't\n // properly applied.\n // Don't change the message. React DevTools relies on it. Also make sure\n // this message doesn't occur elsewhere in this function, or it will cause\n // a false positive.\n throw new Error('^_^');\n }\n try {\n // Verify that the code above has been dead code eliminated (DCE'd).\n __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(checkDCE);\n } catch (err) {\n // DevTools shouldn't crash React, no matter what.\n // We should still report in case we break this code.\n console.error(err);\n }\n}\n\nif (false) {} else {\n module.exports = __webpack_require__(/*! ./cjs/react-dom.development.js */ \"./node_modules/react-dom/cjs/react-dom.development.js\");\n}\n\n\n//# sourceURL=webpack:///./node_modules/react-dom/index.js?");
/***/ }),
/***/ "./node_modules/react-is/cjs/react-is.development.js":
/*!***********************************************************!*\
!*** ./node_modules/react-is/cjs/react-is.development.js ***!
\***********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
eval("/** @license React v16.13.1\n * react-is.development.js\n *\n * Copyright (c) Facebook, Inc. and its affiliates.\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\n\n\n\nif (true) {\n (function() {\n'use strict';\n\n// The Symbol used to tag the ReactElement-like types. If there is no native Symbol\n// nor polyfill, then a plain number is used for performance.\nvar hasSymbol = typeof Symbol === 'function' && Symbol.for;\nvar REACT_ELEMENT_TYPE = hasSymbol ? Symbol.for('react.element') : 0xeac7;\nvar REACT_PORTAL_TYPE = hasSymbol ? Symbol.for('react.portal') : 0xeaca;\nvar REACT_FRAGMENT_TYPE = hasSymbol ? Symbol.for('react.fragment') : 0xeacb;\nvar REACT_STRICT_MODE_TYPE = hasSymbol ? Symbol.for('react.strict_mode') : 0xeacc;\nvar REACT_PROFILER_TYPE = hasSymbol ? Symbol.for('react.profiler') : 0xead2;\nvar REACT_PROVIDER_TYPE = hasSymbol ? Symbol.for('react.provider') : 0xeacd;\nvar REACT_CONTEXT_TYPE = hasSymbol ? Symbol.for('react.context') : 0xeace; // TODO: We don't use AsyncMode or ConcurrentMode anymore. They were temporary\n// (unstable) APIs that have been removed. Can we remove the symbols?\n\nvar REACT_ASYNC_MODE_TYPE = hasSymbol ? Symbol.for('react.async_mode') : 0xeacf;\nvar REACT_CONCURRENT_MODE_TYPE = hasSymbol ? Symbol.for('react.concurrent_mode') : 0xeacf;\nvar REACT_FORWARD_REF_TYPE = hasSymbol ? Symbol.for('react.forward_ref') : 0xead0;\nvar REACT_SUSPENSE_TYPE = hasSymbol ? Symbol.for('react.suspense') : 0xead1;\nvar REACT_SUSPENSE_LIST_TYPE = hasSymbol ? Symbol.for('react.suspense_list') : 0xead8;\nvar REACT_MEMO_TYPE = hasSymbol ? Symbol.for('react.memo') : 0xead3;\nvar REACT_LAZY_TYPE = hasSymbol ? Symbol.for('react.lazy') : 0xead4;\nvar REACT_BLOCK_TYPE = hasSymbol ? Symbol.for('react.block') : 0xead9;\nvar REACT_FUNDAMENTAL_TYPE = hasSymbol ? Symbol.for('react.fundamental') : 0xead5;\nvar REACT_RESPONDER_TYPE = hasSymbol ? Symbol.for('react.responder') : 0xead6;\nvar REACT_SCOPE_TYPE = hasSymbol ? Symbol.for('react.scope') : 0xead7;\n\nfunction isValidElementType(type) {\n return typeof type === 'string' || typeof type === 'function' || // Note: its typeof might be other than 'symbol' or 'number' if it's a polyfill.\n type === REACT_FRAGMENT_TYPE || type === REACT_CONCURRENT_MODE_TYPE || type === REACT_PROFILER_TYPE || type === REACT_STRICT_MODE_TYPE || type === REACT_SUSPENSE_TYPE || type === REACT_SUSPENSE_LIST_TYPE || typeof type === 'object' && type !== null && (type.$$typeof === REACT_LAZY_TYPE || type.$$typeof === REACT_MEMO_TYPE || type.$$typeof === REACT_PROVIDER_TYPE || type.$$typeof === REACT_CONTEXT_TYPE || type.$$typeof === REACT_FORWARD_REF_TYPE || type.$$typeof === REACT_FUNDAMENTAL_TYPE || type.$$typeof === REACT_RESPONDER_TYPE || type.$$typeof === REACT_SCOPE_TYPE || type.$$typeof === REACT_BLOCK_TYPE);\n}\n\nfunction typeOf(object) {\n if (typeof object === 'object' && object !== null) {\n var $$typeof = object.$$typeof;\n\n switch ($$typeof) {\n case REACT_ELEMENT_TYPE:\n var type = object.type;\n\n switch (type) {\n case REACT_ASYNC_MODE_TYPE:\n case REACT_CONCURRENT_MODE_TYPE:\n case REACT_FRAGMENT_TYPE:\n case REACT_PROFILER_TYPE:\n case REACT_STRICT_MODE_TYPE:\n case REACT_SUSPENSE_TYPE:\n return type;\n\n default:\n var $$typeofType = type && type.$$typeof;\n\n switch ($$typeofType) {\n case REACT_CONTEXT_TYPE:\n case REACT_FORWARD_REF_TYPE:\n case REACT_LAZY_TYPE:\n case REACT_MEMO_TYPE:\n case REACT_PROVIDER_TYPE:\n return $$typeofType;\n\n default:\n return $$typeof;\n }\n\n }\n\n case REACT_PORTAL_TYPE:\n return $$typeof;\n }\n }\n\n return undefined;\n} // AsyncMode is deprecated along with isAsyncMode\n\nvar AsyncMode = REACT_ASYNC_MODE_TYPE;\nvar ConcurrentMode = REACT_CONCURRENT_MODE_TYPE;\nvar ContextConsumer = REACT_CONTEXT_TYPE;\nvar ContextProvider = REACT_PROVIDER_TYPE;\nvar Element = REACT_ELEMENT_TYPE;\nvar ForwardRef = REACT_FORWARD_REF_TYPE;\nvar Fragment = REACT_FRAGMENT_TYPE;\nvar Lazy = REACT_LAZY_TYPE;\nvar Memo = REACT_MEMO_TYPE;\nvar Portal = REACT_PORTAL_TYPE;\nvar Profiler = REACT_PROFILER_TYPE;\nvar StrictMode = REACT_STRICT_MODE_TYPE;\nvar Suspense = REACT_SUSPENSE_TYPE;\nvar hasWarnedAboutDeprecatedIsAsyncMode = false; // AsyncMode should be deprecated\n\nfunction isAsyncMode(object) {\n {\n if (!hasWarnedAboutDeprecatedIsAsyncMode) {\n hasWarnedAboutDeprecatedIsAsyncMode = true; // Using console['warn'] to evade Babel and ESLint\n\n console['warn']('The ReactIs.isAsyncMode() alias has been deprecated, ' + 'and will be removed in React 17+. Update your code to use ' + 'ReactIs.isConcurrentMode() instead. It has the exact same API.');\n }\n }\n\n return isConcurrentMode(object) || typeOf(object) === REACT_ASYNC_MODE_TYPE;\n}\nfunction isConcurrentMode(object) {\n return typeOf(object) === REACT_CONCURRENT_MODE_TYPE;\n}\nfunction isContextConsumer(object) {\n return typeOf(object) === REACT_CONTEXT_TYPE;\n}\nfunction isContextProvider(object) {\n return typeOf(object) === REACT_PROVIDER_TYPE;\n}\nfunction isElement(object) {\n return typeof object === 'object' && object !== null && object.$$typeof === REACT_ELEMENT_TYPE;\n}\nfunction isForwardRef(object) {\n return typeOf(object) === REACT_FORWARD_REF_TYPE;\n}\nfunction isFragment(object) {\n return typeOf(object) === REACT_FRAGMENT_TYPE;\n}\nfunction isLazy(object) {\n return typeOf(object) === REACT_LAZY_TYPE;\n}\nfunction isMemo(object) {\n return typeOf(object) === REACT_MEMO_TYPE;\n}\nfunction isPortal(object) {\n return typeOf(object) === REACT_PORTAL_TYPE;\n}\nfunction isProfiler(object) {\n return typeOf(object) === REACT_PROFILER_TYPE;\n}\nfunction isStrictMode(object) {\n return typeOf(object) === REACT_STRICT_MODE_TYPE;\n}\nfunction isSuspense(object) {\n return typeOf(object) === REACT_SUSPENSE_TYPE;\n}\n\nexports.AsyncMode = AsyncMode;\nexports.ConcurrentMode = ConcurrentMode;\nexports.ContextConsumer = ContextConsumer;\nexports.ContextProvider = ContextProvider;\nexports.Element = Element;\nexports.ForwardRef = ForwardRef;\nexports.Fragment = Fragment;\nexports.Lazy = Lazy;\nexports.Memo = Memo;\nexports.Portal = Portal;\nexports.Profiler = Profiler;\nexports.StrictMode = StrictMode;\nexports.Suspense = Suspense;\nexports.isAsyncMode = isAsyncMode;\nexports.isConcurrentMode = isConcurrentMode;\nexports.isContextConsumer = isContextConsumer;\nexports.isContextProvider = isContextProvider;\nexports.isElement = isElement;\nexports.isForwardRef = isForwardRef;\nexports.isFragment = isFragment;\nexports.isLazy = isLazy;\nexports.isMemo = isMemo;\nexports.isPortal = isPortal;\nexports.isProfiler = isProfiler;\nexports.isStrictMode = isStrictMode;\nexports.isSuspense = isSuspense;\nexports.isValidElementType = isValidElementType;\nexports.typeOf = typeOf;\n })();\n}\n\n\n//# sourceURL=webpack:///./node_modules/react-is/cjs/react-is.development.js?");
/***/ }),
/***/ "./node_modules/react-is/index.js":
/*!****************************************!*\
!*** ./node_modules/react-is/index.js ***!
\****************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
eval("\n\nif (false) {} else {\n module.exports = __webpack_require__(/*! ./cjs/react-is.development.js */ \"./node_modules/react-is/cjs/react-is.development.js\");\n}\n\n\n//# sourceURL=webpack:///./node_modules/react-is/index.js?");
/***/ }),
/***/ "./node_modules/react-router-dom/esm/react-router-dom.js":
/*!***************************************************************!*\
!*** ./node_modules/react-router-dom/esm/react-router-dom.js ***!
\***************************************************************/
/*! exports provided: MemoryRouter, Prompt, Redirect, Route, Router, StaticRouter, Switch, __RouterContext, generatePath, matchPath, useHistory, useLocation, useParams, useRouteMatch, withRouter, BrowserRouter, HashRouter, Link, NavLink */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"BrowserRouter\", function() { return BrowserRouter; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"HashRouter\", function() { return HashRouter; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"Link\", function() { return Link; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"NavLink\", function() { return NavLink; });\n/* harmony import */ var react_router__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! react-router */ \"./node_modules/react-router/esm/react-router.js\");\n/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, \"MemoryRouter\", function() { return react_router__WEBPACK_IMPORTED_MODULE_0__[\"MemoryRouter\"]; });\n\n/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, \"Prompt\", function() { return react_router__WEBPACK_IMPORTED_MODULE_0__[\"Prompt\"]; });\n\n/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, \"Redirect\", function() { return react_router__WEBPACK_IMPORTED_MODULE_0__[\"Redirect\"]; });\n\n/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, \"Route\", function() { return react_router__WEBPACK_IMPORTED_MODULE_0__[\"Route\"]; });\n\n/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, \"Router\", function() { return react_router__WEBPACK_IMPORTED_MODULE_0__[\"Router\"]; });\n\n/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, \"StaticRouter\", function() { return react_router__WEBPACK_IMPORTED_MODULE_0__[\"StaticRouter\"]; });\n\n/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, \"Switch\", function() { return react_router__WEBPACK_IMPORTED_MODULE_0__[\"Switch\"]; });\n\n/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, \"__RouterContext\", function() { return react_router__WEBPACK_IMPORTED_MODULE_0__[\"__RouterContext\"]; });\n\n/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, \"generatePath\", function() { return react_router__WEBPACK_IMPORTED_MODULE_0__[\"generatePath\"]; });\n\n/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, \"matchPath\", function() { return react_router__WEBPACK_IMPORTED_MODULE_0__[\"matchPath\"]; });\n\n/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, \"useHistory\", function() { return react_router__WEBPACK_IMPORTED_MODULE_0__[\"useHistory\"]; });\n\n/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, \"useLocation\", function() { return react_router__WEBPACK_IMPORTED_MODULE_0__[\"useLocation\"]; });\n\n/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, \"useParams\", function() { return react_router__WEBPACK_IMPORTED_MODULE_0__[\"useParams\"]; });\n\n/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, \"useRouteMatch\", function() { return react_router__WEBPACK_IMPORTED_MODULE_0__[\"useRouteMatch\"]; });\n\n/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, \"withRouter\", function() { return react_router__WEBPACK_IMPORTED_MODULE_0__[\"withRouter\"]; });\n\n/* harmony import */ var _babel_runtime_helpers_esm_inheritsLoose__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @babel/runtime/helpers/esm/inheritsLoose */ \"./node_modules/@babel/runtime/helpers/esm/inheritsLoose.js\");\n/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! react */ \"./node_modules/react/index.js\");\n/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_2__);\n/* harmony import */ var history__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! history */ \"./node_modules/history/esm/history.js\");\n/* harmony import */ var prop_types__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! prop-types */ \"./node_modules/prop-types/index.js\");\n/* harmony import */ var prop_types__WEBPACK_IMPORTED_MODULE_4___default = /*#__PURE__*/__webpack_require__.n(prop_types__WEBPACK_IMPORTED_MODULE_4__);\n/* harmony import */ var tiny_warning__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! tiny-warning */ \"./node_modules/tiny-warning/dist/tiny-warning.esm.js\");\n/* harmony import */ var _babel_runtime_helpers_esm_extends__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! @babel/runtime/helpers/esm/extends */ \"./node_modules/@babel/runtime/helpers/esm/extends.js\");\n/* harmony import */ var _babel_runtime_helpers_esm_objectWithoutPropertiesLoose__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! @babel/runtime/helpers/esm/objectWithoutPropertiesLoose */ \"./node_modules/@babel/runtime/helpers/esm/objectWithoutPropertiesLoose.js\");\n/* harmony import */ var tiny_invariant__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! tiny-invariant */ \"./node_modules/tiny-invariant/dist/tiny-invariant.esm.js\");\n\n\n\n\n\n\n\n\n\n\n\n/**\n * The public API for a <Router> that uses HTML5 history.\n */\n\nvar BrowserRouter =\n/*#__PURE__*/\nfunction (_React$Component) {\n Object(_babel_runtime_helpers_esm_inheritsLoose__WEBPACK_IMPORTED_MODULE_1__[\"default\"])(BrowserRouter, _React$Component);\n\n function BrowserRouter() {\n var _this;\n\n for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {\n args[_key] = arguments[_key];\n }\n\n _this = _React$Component.call.apply(_React$Component, [this].concat(args)) || this;\n _this.history = Object(history__WEBPACK_IMPORTED_MODULE_3__[\"createBrowserHistory\"])(_this.props);\n return _this;\n }\n\n var _proto = BrowserRouter.prototype;\n\n _proto.render = function render() {\n return react__WEBPACK_IMPORTED_MODULE_2___default.a.createElement(react_router__WEBPACK_IMPORTED_MODULE_0__[\"Router\"], {\n history: this.history,\n children: this.props.children\n });\n };\n\n return BrowserRouter;\n}(react__WEBPACK_IMPORTED_MODULE_2___default.a.Component);\n\nif (true) {\n BrowserRouter.propTypes = {\n basename: prop_types__WEBPACK_IMPORTED_MODULE_4___default.a.string,\n children: prop_types__WEBPACK_IMPORTED_MODULE_4___default.a.node,\n forceRefresh: prop_types__WEBPACK_IMPORTED_MODULE_4___default.a.bool,\n getUserConfirmation: prop_types__WEBPACK_IMPORTED_MODULE_4___default.a.func,\n keyLength: prop_types__WEBPACK_IMPORTED_MODULE_4___default.a.number\n };\n\n BrowserRouter.prototype.componentDidMount = function () {\n true ? Object(tiny_warning__WEBPACK_IMPORTED_MODULE_5__[\"default\"])(!this.props.history, \"<BrowserRouter> ignores the history prop. To use a custom history, \" + \"use `import { Router }` instead of `import { BrowserRouter as Router }`.\") : undefined;\n };\n}\n\n/**\n * The public API for a <Router> that uses window.location.hash.\n */\n\nvar HashRouter =\n/*#__PURE__*/\nfunction (_React$Component) {\n Object(_babel_runtime_helpers_esm_inheritsLoose__WEBPACK_IMPORTED_MODULE_1__[\"default\"])(HashRouter, _React$Component);\n\n function HashRouter() {\n var _this;\n\n for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {\n args[_key] = arguments[_key];\n }\n\n _this = _React$Component.call.apply(_React$Component, [this].concat(args)) || this;\n _this.history = Object(history__WEBPACK_IMPORTED_MODULE_3__[\"createHashHistory\"])(_this.props);\n return _this;\n }\n\n var _proto = HashRouter.prototype;\n\n _proto.render = function render() {\n return react__WEBPACK_IMPORTED_MODULE_2___default.a.createElement(react_router__WEBPACK_IMPORTED_MODULE_0__[\"Router\"], {\n history: this.history,\n children: this.props.children\n });\n };\n\n return HashRouter;\n}(react__WEBPACK_IMPORTED_MODULE_2___default.a.Component);\n\nif (true) {\n HashRouter.propTypes = {\n basename: prop_types__WEBPACK_IMPORTED_MODULE_4___default.a.string,\n children: prop_types__WEBPACK_IMPORTED_MODULE_4___default.a.node,\n getUserConfirmation: prop_types__WEBPACK_IMPORTED_MODULE_4___default.a.func,\n hashType: prop_types__WEBPACK_IMPORTED_MODULE_4___default.a.oneOf([\"hashbang\", \"noslash\", \"slash\"])\n };\n\n HashRouter.prototype.componentDidMount = function () {\n true ? Object(tiny_warning__WEBPACK_IMPORTED_MODULE_5__[\"default\"])(!this.props.history, \"<HashRouter> ignores the history prop. To use a custom history, \" + \"use `import { Router }` instead of `import { HashRouter as Router }`.\") : undefined;\n };\n}\n\nvar resolveToLocation = function resolveToLocation(to, currentLocation) {\n return typeof to === \"function\" ? to(currentLocation) : to;\n};\nvar normalizeToLocation = function normalizeToLocation(to, currentLocation) {\n return typeof to === \"string\" ? Object(history__WEBPACK_IMPORTED_MODULE_3__[\"createLocation\"])(to, null, null, currentLocation) : to;\n};\n\nvar forwardRefShim = function forwardRefShim(C) {\n return C;\n};\n\nvar forwardRef = react__WEBPACK_IMPORTED_MODULE_2___default.a.forwardRef;\n\nif (typeof forwardRef === \"undefined\") {\n forwardRef = forwardRefShim;\n}\n\nfunction isModifiedEvent(event) {\n return !!(event.metaKey || event.altKey || event.ctrlKey || event.shiftKey);\n}\n\nvar LinkAnchor = forwardRef(function (_ref, forwardedRef) {\n var innerRef = _ref.innerRef,\n navigate = _ref.navigate,\n _onClick = _ref.onClick,\n rest = Object(_babel_runtime_helpers_esm_objectWithoutPropertiesLoose__WEBPACK_IMPORTED_MODULE_7__[\"default\"])(_ref, [\"innerRef\", \"navigate\", \"onClick\"]);\n\n var target = rest.target;\n\n var props = Object(_babel_runtime_helpers_esm_extends__WEBPACK_IMPORTED_MODULE_6__[\"default\"])({}, rest, {\n onClick: function onClick(event) {\n try {\n if (_onClick) _onClick(event);\n } catch (ex) {\n event.preventDefault();\n throw ex;\n }\n\n if (!event.defaultPrevented && // onClick prevented default\n event.button === 0 && ( // ignore everything but left clicks\n !target || target === \"_self\") && // let browser handle \"target=_blank\" etc.\n !isModifiedEvent(event) // ignore clicks with modifier keys\n ) {\n event.preventDefault();\n navigate();\n }\n }\n }); // React 15 compat\n\n\n if (forwardRefShim !== forwardRef) {\n props.ref = forwardedRef || innerRef;\n } else {\n props.ref = innerRef;\n }\n\n return react__WEBPACK_IMPORTED_MODULE_2___default.a.createElement(\"a\", props);\n});\n\nif (true) {\n LinkAnchor.displayName = \"LinkAnchor\";\n}\n/**\n * The public API for rendering a history-aware <a>.\n */\n\n\nvar Link = forwardRef(function (_ref2, forwardedRef) {\n var _ref2$component = _ref2.component,\n component = _ref2$component === void 0 ? LinkAnchor : _ref2$component,\n replace = _ref2.replace,\n to = _ref2.to,\n innerRef = _ref2.innerRef,\n rest = Object(_babel_runtime_helpers_esm_objectWithoutPropertiesLoose__WEBPACK_IMPORTED_MODULE_7__[\"default\"])(_ref2, [\"component\", \"replace\", \"to\", \"innerRef\"]);\n\n return react__WEBPACK_IMPORTED_MODULE_2___default.a.createElement(react_router__WEBPACK_IMPORTED_MODULE_0__[\"__RouterContext\"].Consumer, null, function (context) {\n !context ? true ? Object(tiny_invariant__WEBPACK_IMPORTED_MODULE_8__[\"default\"])(false, \"You should not use <Link> outside a <Router>\") : undefined : void 0;\n var history = context.history;\n var location = normalizeToLocation(resolveToLocation(to, context.location), context.location);\n var href = location ? history.createHref(location) : \"\";\n\n var props = Object(_babel_runtime_helpers_esm_extends__WEBPACK_IMPORTED_MODULE_6__[\"default\"])({}, rest, {\n href: href,\n navigate: function navigate() {\n var location = resolveToLocation(to, context.location);\n var method = replace ? history.replace : history.push;\n method(location);\n }\n }); // React 15 compat\n\n\n if (forwardRefShim !== forwardRef) {\n props.ref = forwardedRef || innerRef;\n } else {\n props.innerRef = innerRef;\n }\n\n return react__WEBPACK_IMPORTED_MODULE_2___default.a.createElement(component, props);\n });\n});\n\nif (true) {\n var toType = prop_types__WEBPACK_IMPORTED_MODULE_4___default.a.oneOfType([prop_types__WEBPACK_IMPORTED_MODULE_4___default.a.string, prop_types__WEBPACK_IMPORTED_MODULE_4___default.a.object, prop_types__WEBPACK_IMPORTED_MODULE_4___default.a.func]);\n var refType = prop_types__WEBPACK_IMPORTED_MODULE_4___default.a.oneOfType([prop_types__WEBPACK_IMPORTED_MODULE_4___default.a.string, prop_types__WEBPACK_IMPORTED_MODULE_4___default.a.func, prop_types__WEBPACK_IMPORTED_MODULE_4___default.a.shape({\n current: prop_types__WEBPACK_IMPORTED_MODULE_4___default.a.any\n })]);\n Link.displayName = \"Link\";\n Link.propTypes = {\n innerRef: refType,\n onClick: prop_types__WEBPACK_IMPORTED_MODULE_4___default.a.func,\n replace: prop_types__WEBPACK_IMPORTED_MODULE_4___default.a.bool,\n target: prop_types__WEBPACK_IMPORTED_MODULE_4___default.a.string,\n to: toType.isRequired\n };\n}\n\nvar forwardRefShim$1 = function forwardRefShim(C) {\n return C;\n};\n\nvar forwardRef$1 = react__WEBPACK_IMPORTED_MODULE_2___default.a.forwardRef;\n\nif (typeof forwardRef$1 === \"undefined\") {\n forwardRef$1 = forwardRefShim$1;\n}\n\nfunction joinClassnames() {\n for (var _len = arguments.length, classnames = new Array(_len), _key = 0; _key < _len; _key++) {\n classnames[_key] = arguments[_key];\n }\n\n return classnames.filter(function (i) {\n return i;\n }).join(\" \");\n}\n/**\n * A <Link> wrapper that knows if it's \"active\" or not.\n */\n\n\nvar NavLink = forwardRef$1(function (_ref, forwardedRef) {\n var _ref$ariaCurrent = _ref[\"aria-current\"],\n ariaCurrent = _ref$ariaCurrent === void 0 ? \"page\" : _ref$ariaCurrent,\n _ref$activeClassName = _ref.activeClassName,\n activeClassName = _ref$activeClassName === void 0 ? \"active\" : _ref$activeClassName,\n activeStyle = _ref.activeStyle,\n classNameProp = _ref.className,\n exact = _ref.exact,\n isActiveProp = _ref.isActive,\n locationProp = _ref.location,\n strict = _ref.strict,\n styleProp = _ref.style,\n to = _ref.to,\n innerRef = _ref.innerRef,\n rest = Object(_babel_runtime_helpers_esm_objectWithoutPropertiesLoose__WEBPACK_IMPORTED_MODULE_7__[\"default\"])(_ref, [\"aria-current\", \"activeClassName\", \"activeStyle\", \"className\", \"exact\", \"isActive\", \"location\", \"strict\", \"style\", \"to\", \"innerRef\"]);\n\n return react__WEBPACK_IMPORTED_MODULE_2___default.a.createElement(react_router__WEBPACK_IMPORTED_MODULE_0__[\"__RouterContext\"].Consumer, null, function (context) {\n !context ? true ? Object(tiny_invariant__WEBPACK_IMPORTED_MODULE_8__[\"default\"])(false, \"You should not use <NavLink> outside a <Router>\") : undefined : void 0;\n var currentLocation = locationProp || context.location;\n var toLocation = normalizeToLocation(resolveToLocation(to, currentLocation), currentLocation);\n var path = toLocation.pathname; // Regex taken from: https://github.com/pillarjs/path-to-regexp/blob/master/index.js#L202\n\n var escapedPath = path && path.replace(/([.+*?=^!:${}()[\\]|/\\\\])/g, \"\\\\$1\");\n var match = escapedPath ? Object(react_router__WEBPACK_IMPORTED_MODULE_0__[\"matchPath\"])(currentLocation.pathname, {\n path: escapedPath,\n exact: exact,\n strict: strict\n }) : null;\n var isActive = !!(isActiveProp ? isActiveProp(match, currentLocation) : match);\n var className = isActive ? joinClassnames(classNameProp, activeClassName) : classNameProp;\n var style = isActive ? Object(_babel_runtime_helpers_esm_extends__WEBPACK_IMPORTED_MODULE_6__[\"default\"])({}, styleProp, {}, activeStyle) : styleProp;\n\n var props = Object(_babel_runtime_helpers_esm_extends__WEBPACK_IMPORTED_MODULE_6__[\"default\"])({\n \"aria-current\": isActive && ariaCurrent || null,\n className: className,\n style: style,\n to: toLocation\n }, rest); // React 15 compat\n\n\n if (forwardRefShim$1 !== forwardRef$1) {\n props.ref = forwardedRef || innerRef;\n } else {\n props.innerRef = innerRef;\n }\n\n return react__WEBPACK_IMPORTED_MODULE_2___default.a.createElement(Link, props);\n });\n});\n\nif (true) {\n NavLink.displayName = \"NavLink\";\n var ariaCurrentType = prop_types__WEBPACK_IMPORTED_MODULE_4___default.a.oneOf([\"page\", \"step\", \"location\", \"date\", \"time\", \"true\"]);\n NavLink.propTypes = Object(_babel_runtime_helpers_esm_extends__WEBPACK_IMPORTED_MODULE_6__[\"default\"])({}, Link.propTypes, {\n \"aria-current\": ariaCurrentType,\n activeClassName: prop_types__WEBPACK_IMPORTED_MODULE_4___default.a.string,\n activeStyle: prop_types__WEBPACK_IMPORTED_MODULE_4___default.a.object,\n className: prop_types__WEBPACK_IMPORTED_MODULE_4___default.a.string,\n exact: prop_types__WEBPACK_IMPORTED_MODULE_4___default.a.bool,\n isActive: prop_types__WEBPACK_IMPORTED_MODULE_4___default.a.func,\n location: prop_types__WEBPACK_IMPORTED_MODULE_4___default.a.object,\n strict: prop_types__WEBPACK_IMPORTED_MODULE_4___default.a.bool,\n style: prop_types__WEBPACK_IMPORTED_MODULE_4___default.a.object\n });\n}\n\n\n//# sourceMappingURL=react-router-dom.js.map\n\n\n//# sourceURL=webpack:///./node_modules/react-router-dom/esm/react-router-dom.js?");
/***/ }),
/***/ "./node_modules/react-router/esm/react-router.js":
/*!*******************************************************!*\
!*** ./node_modules/react-router/esm/react-router.js ***!
\*******************************************************/
/*! exports provided: MemoryRouter, Prompt, Redirect, Route, Router, StaticRouter, Switch, __RouterContext, generatePath, matchPath, useHistory, useLocation, useParams, useRouteMatch, withRouter */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"MemoryRouter\", function() { return MemoryRouter; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"Prompt\", function() { return Prompt; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"Redirect\", function() { return Redirect; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"Route\", function() { return Route; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"Router\", function() { return Router; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"StaticRouter\", function() { return StaticRouter; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"Switch\", function() { return Switch; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"__RouterContext\", function() { return context; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"generatePath\", function() { return generatePath; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"matchPath\", function() { return matchPath; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"useHistory\", function() { return useHistory; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"useLocation\", function() { return useLocation; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"useParams\", function() { return useParams; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"useRouteMatch\", function() { return useRouteMatch; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"withRouter\", function() { return withRouter; });\n/* harmony import */ var _babel_runtime_helpers_esm_inheritsLoose__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @babel/runtime/helpers/esm/inheritsLoose */ \"./node_modules/@babel/runtime/helpers/esm/inheritsLoose.js\");\n/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! react */ \"./node_modules/react/index.js\");\n/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_1__);\n/* harmony import */ var prop_types__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! prop-types */ \"./node_modules/prop-types/index.js\");\n/* harmony import */ var prop_types__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(prop_types__WEBPACK_IMPORTED_MODULE_2__);\n/* harmony import */ var history__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! history */ \"./node_modules/history/esm/history.js\");\n/* harmony import */ var tiny_warning__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! tiny-warning */ \"./node_modules/tiny-warning/dist/tiny-warning.esm.js\");\n/* harmony import */ var mini_create_react_context__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! mini-create-react-context */ \"./node_modules/mini-create-react-context/dist/esm/index.js\");\n/* harmony import */ var tiny_invariant__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! tiny-invariant */ \"./node_modules/tiny-invariant/dist/tiny-invariant.esm.js\");\n/* harmony import */ var _babel_runtime_helpers_esm_extends__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! @babel/runtime/helpers/esm/extends */ \"./node_modules/@babel/runtime/helpers/esm/extends.js\");\n/* harmony import */ var path_to_regexp__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! path-to-regexp */ \"./node_modules/react-router/node_modules/path-to-regexp/index.js\");\n/* harmony import */ var path_to_regexp__WEBPACK_IMPORTED_MODULE_8___default = /*#__PURE__*/__webpack_require__.n(path_to_regexp__WEBPACK_IMPORTED_MODULE_8__);\n/* harmony import */ var react_is__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! react-is */ \"./node_modules/react-is/index.js\");\n/* harmony import */ var react_is__WEBPACK_IMPORTED_MODULE_9___default = /*#__PURE__*/__webpack_require__.n(react_is__WEBPACK_IMPORTED_MODULE_9__);\n/* harmony import */ var _babel_runtime_helpers_esm_objectWithoutPropertiesLoose__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! @babel/runtime/helpers/esm/objectWithoutPropertiesLoose */ \"./node_modules/@babel/runtime/helpers/esm/objectWithoutPropertiesLoose.js\");\n/* harmony import */ var hoist_non_react_statics__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! hoist-non-react-statics */ \"./node_modules/hoist-non-react-statics/dist/hoist-non-react-statics.cjs.js\");\n/* harmony import */ var hoist_non_react_statics__WEBPACK_IMPORTED_MODULE_11___default = /*#__PURE__*/__webpack_require__.n(hoist_non_react_statics__WEBPACK_IMPORTED_MODULE_11__);\n\n\n\n\n\n\n\n\n\n\n\n\n\n// TODO: Replace with React.createContext once we can assume React 16+\n\nvar createNamedContext = function createNamedContext(name) {\n var context = Object(mini_create_react_context__WEBPACK_IMPORTED_MODULE_5__[\"default\"])();\n context.displayName = name;\n return context;\n};\n\nvar context =\n/*#__PURE__*/\ncreateNamedContext(\"Router\");\n\n/**\n * The public API for putting history on context.\n */\n\nvar Router =\n/*#__PURE__*/\nfunction (_React$Component) {\n Object(_babel_runtime_helpers_esm_inheritsLoose__WEBPACK_IMPORTED_MODULE_0__[\"default\"])(Router, _React$Component);\n\n Router.computeRootMatch = function computeRootMatch(pathname) {\n return {\n path: \"/\",\n url: \"/\",\n params: {},\n isExact: pathname === \"/\"\n };\n };\n\n function Router(props) {\n var _this;\n\n _this = _React$Component.call(this, props) || this;\n _this.state = {\n location: props.history.location\n }; // This is a bit of a hack. We have to start listening for location\n // changes here in the constructor in case there are any <Redirect>s\n // on the initial render. If there are, they will replace/push when\n // they mount and since cDM fires in children before parents, we may\n // get a new location before the <Router> is mounted.\n\n _this._isMounted = false;\n _this._pendingLocation = null;\n\n if (!props.staticContext) {\n _this.unlisten = props.history.listen(function (location) {\n if (_this._isMounted) {\n _this.setState({\n location: location\n });\n } else {\n _this._pendingLocation = location;\n }\n });\n }\n\n return _this;\n }\n\n var _proto = Router.prototype;\n\n _proto.componentDidMount = function componentDidMount() {\n this._isMounted = true;\n\n if (this._pendingLocation) {\n this.setState({\n location: this._pendingLocation\n });\n }\n };\n\n _proto.componentWillUnmount = function componentWillUnmount() {\n if (this.unlisten) this.unlisten();\n };\n\n _proto.render = function render() {\n return react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(context.Provider, {\n children: this.props.children || null,\n value: {\n history: this.props.history,\n location: this.state.location,\n match: Router.computeRootMatch(this.state.location.pathname),\n staticContext: this.props.staticContext\n }\n });\n };\n\n return Router;\n}(react__WEBPACK_IMPORTED_MODULE_1___default.a.Component);\n\nif (true) {\n Router.propTypes = {\n children: prop_types__WEBPACK_IMPORTED_MODULE_2___default.a.node,\n history: prop_types__WEBPACK_IMPORTED_MODULE_2___default.a.object.isRequired,\n staticContext: prop_types__WEBPACK_IMPORTED_MODULE_2___default.a.object\n };\n\n Router.prototype.componentDidUpdate = function (prevProps) {\n true ? Object(tiny_warning__WEBPACK_IMPORTED_MODULE_4__[\"default\"])(prevProps.history === this.props.history, \"You cannot change <Router history>\") : undefined;\n };\n}\n\n/**\n * The public API for a <Router> that stores location in memory.\n */\n\nvar MemoryRouter =\n/*#__PURE__*/\nfunction (_React$Component) {\n Object(_babel_runtime_helpers_esm_inheritsLoose__WEBPACK_IMPORTED_MODULE_0__[\"default\"])(MemoryRouter, _React$Component);\n\n function MemoryRouter() {\n var _this;\n\n for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {\n args[_key] = arguments[_key];\n }\n\n _this = _React$Component.call.apply(_React$Component, [this].concat(args)) || this;\n _this.history = Object(history__WEBPACK_IMPORTED_MODULE_3__[\"createMemoryHistory\"])(_this.props);\n return _this;\n }\n\n var _proto = MemoryRouter.prototype;\n\n _proto.render = function render() {\n return react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(Router, {\n history: this.history,\n children: this.props.children\n });\n };\n\n return MemoryRouter;\n}(react__WEBPACK_IMPORTED_MODULE_1___default.a.Component);\n\nif (true) {\n MemoryRouter.propTypes = {\n initialEntries: prop_types__WEBPACK_IMPORTED_MODULE_2___default.a.array,\n initialIndex: prop_types__WEBPACK_IMPORTED_MODULE_2___default.a.number,\n getUserConfirmation: prop_types__WEBPACK_IMPORTED_MODULE_2___default.a.func,\n keyLength: prop_types__WEBPACK_IMPORTED_MODULE_2___default.a.number,\n children: prop_types__WEBPACK_IMPORTED_MODULE_2___default.a.node\n };\n\n MemoryRouter.prototype.componentDidMount = function () {\n true ? Object(tiny_warning__WEBPACK_IMPORTED_MODULE_4__[\"default\"])(!this.props.history, \"<MemoryRouter> ignores the history prop. To use a custom history, \" + \"use `import { Router }` instead of `import { MemoryRouter as Router }`.\") : undefined;\n };\n}\n\nvar Lifecycle =\n/*#__PURE__*/\nfunction (_React$Component) {\n Object(_babel_runtime_helpers_esm_inheritsLoose__WEBPACK_IMPORTED_MODULE_0__[\"default\"])(Lifecycle, _React$Component);\n\n function Lifecycle() {\n return _React$Component.apply(this, arguments) || this;\n }\n\n var _proto = Lifecycle.prototype;\n\n _proto.componentDidMount = function componentDidMount() {\n if (this.props.onMount) this.props.onMount.call(this, this);\n };\n\n _proto.componentDidUpdate = function componentDidUpdate(prevProps) {\n if (this.props.onUpdate) this.props.onUpdate.call(this, this, prevProps);\n };\n\n _proto.componentWillUnmount = function componentWillUnmount() {\n if (this.props.onUnmount) this.props.onUnmount.call(this, this);\n };\n\n _proto.render = function render() {\n return null;\n };\n\n return Lifecycle;\n}(react__WEBPACK_IMPORTED_MODULE_1___default.a.Component);\n\n/**\n * The public API for prompting the user before navigating away from a screen.\n */\n\nfunction Prompt(_ref) {\n var message = _ref.message,\n _ref$when = _ref.when,\n when = _ref$when === void 0 ? true : _ref$when;\n return react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(context.Consumer, null, function (context) {\n !context ? true ? Object(tiny_invariant__WEBPACK_IMPORTED_MODULE_6__[\"default\"])(false, \"You should not use <Prompt> outside a <Router>\") : undefined : void 0;\n if (!when || context.staticContext) return null;\n var method = context.history.block;\n return react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(Lifecycle, {\n onMount: function onMount(self) {\n self.release = method(message);\n },\n onUpdate: function onUpdate(self, prevProps) {\n if (prevProps.message !== message) {\n self.release();\n self.release = method(message);\n }\n },\n onUnmount: function onUnmount(self) {\n self.release();\n },\n message: message\n });\n });\n}\n\nif (true) {\n var messageType = prop_types__WEBPACK_IMPORTED_MODULE_2___default.a.oneOfType([prop_types__WEBPACK_IMPORTED_MODULE_2___default.a.func, prop_types__WEBPACK_IMPORTED_MODULE_2___default.a.string]);\n Prompt.propTypes = {\n when: prop_types__WEBPACK_IMPORTED_MODULE_2___default.a.bool,\n message: messageType.isRequired\n };\n}\n\nvar cache = {};\nvar cacheLimit = 10000;\nvar cacheCount = 0;\n\nfunction compilePath(path) {\n if (cache[path]) return cache[path];\n var generator = path_to_regexp__WEBPACK_IMPORTED_MODULE_8___default.a.compile(path);\n\n if (cacheCount < cacheLimit) {\n cache[path] = generator;\n cacheCount++;\n }\n\n return generator;\n}\n/**\n * Public API for generating a URL pathname from a path and parameters.\n */\n\n\nfunction generatePath(path, params) {\n if (path === void 0) {\n path = \"/\";\n }\n\n if (params === void 0) {\n params = {};\n }\n\n return path === \"/\" ? path : compilePath(path)(params, {\n pretty: true\n });\n}\n\n/**\n * The public API for navigating programmatically with a component.\n */\n\nfunction Redirect(_ref) {\n var computedMatch = _ref.computedMatch,\n to = _ref.to,\n _ref$push = _ref.push,\n push = _ref$push === void 0 ? false : _ref$push;\n return react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(context.Consumer, null, function (context) {\n !context ? true ? Object(tiny_invariant__WEBPACK_IMPORTED_MODULE_6__[\"default\"])(false, \"You should not use <Redirect> outside a <Router>\") : undefined : void 0;\n var history = context.history,\n staticContext = context.staticContext;\n var method = push ? history.push : history.replace;\n var location = Object(history__WEBPACK_IMPORTED_MODULE_3__[\"createLocation\"])(computedMatch ? typeof to === \"string\" ? generatePath(to, computedMatch.params) : Object(_babel_runtime_helpers_esm_extends__WEBPACK_IMPORTED_MODULE_7__[\"default\"])({}, to, {\n pathname: generatePath(to.pathname, computedMatch.params)\n }) : to); // When rendering in a static context,\n // set the new location immediately.\n\n if (staticContext) {\n method(location);\n return null;\n }\n\n return react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(Lifecycle, {\n onMount: function onMount() {\n method(location);\n },\n onUpdate: function onUpdate(self, prevProps) {\n var prevLocation = Object(history__WEBPACK_IMPORTED_MODULE_3__[\"createLocation\"])(prevProps.to);\n\n if (!Object(history__WEBPACK_IMPORTED_MODULE_3__[\"locationsAreEqual\"])(prevLocation, Object(_babel_runtime_helpers_esm_extends__WEBPACK_IMPORTED_MODULE_7__[\"default\"])({}, location, {\n key: prevLocation.key\n }))) {\n method(location);\n }\n },\n to: to\n });\n });\n}\n\nif (true) {\n Redirect.propTypes = {\n push: prop_types__WEBPACK_IMPORTED_MODULE_2___default.a.bool,\n from: prop_types__WEBPACK_IMPORTED_MODULE_2___default.a.string,\n to: prop_types__WEBPACK_IMPORTED_MODULE_2___default.a.oneOfType([prop_types__WEBPACK_IMPORTED_MODULE_2___default.a.string, prop_types__WEBPACK_IMPORTED_MODULE_2___default.a.object]).isRequired\n };\n}\n\nvar cache$1 = {};\nvar cacheLimit$1 = 10000;\nvar cacheCount$1 = 0;\n\nfunction compilePath$1(path, options) {\n var cacheKey = \"\" + options.end + options.strict + options.sensitive;\n var pathCache = cache$1[cacheKey] || (cache$1[cacheKey] = {});\n if (pathCache[path]) return pathCache[path];\n var keys = [];\n var regexp = path_to_regexp__WEBPACK_IMPORTED_MODULE_8___default()(path, keys, options);\n var result = {\n regexp: regexp,\n keys: keys\n };\n\n if (cacheCount$1 < cacheLimit$1) {\n pathCache[path] = result;\n cacheCount$1++;\n }\n\n return result;\n}\n/**\n * Public API for matching a URL pathname to a path.\n */\n\n\nfunction matchPath(pathname, options) {\n if (options === void 0) {\n options = {};\n }\n\n if (typeof options === \"string\" || Array.isArray(options)) {\n options = {\n path: options\n };\n }\n\n var _options = options,\n path = _options.path,\n _options$exact = _options.exact,\n exact = _options$exact === void 0 ? false : _options$exact,\n _options$strict = _options.strict,\n strict = _options$strict === void 0 ? false : _options$strict,\n _options$sensitive = _options.sensitive,\n sensitive = _options$sensitive === void 0 ? false : _options$sensitive;\n var paths = [].concat(path);\n return paths.reduce(function (matched, path) {\n if (!path && path !== \"\") return null;\n if (matched) return matched;\n\n var _compilePath = compilePath$1(path, {\n end: exact,\n strict: strict,\n sensitive: sensitive\n }),\n regexp = _compilePath.regexp,\n keys = _compilePath.keys;\n\n var match = regexp.exec(pathname);\n if (!match) return null;\n var url = match[0],\n values = match.slice(1);\n var isExact = pathname === url;\n if (exact && !isExact) return null;\n return {\n path: path,\n // the path used to match\n url: path === \"/\" && url === \"\" ? \"/\" : url,\n // the matched portion of the URL\n isExact: isExact,\n // whether or not we matched exactly\n params: keys.reduce(function (memo, key, index) {\n memo[key.name] = values[index];\n return memo;\n }, {})\n };\n }, null);\n}\n\nfunction isEmptyChildren(children) {\n return react__WEBPACK_IMPORTED_MODULE_1___default.a.Children.count(children) === 0;\n}\n\nfunction evalChildrenDev(children, props, path) {\n var value = children(props);\n true ? Object(tiny_warning__WEBPACK_IMPORTED_MODULE_4__[\"default\"])(value !== undefined, \"You returned `undefined` from the `children` function of \" + (\"<Route\" + (path ? \" path=\\\"\" + path + \"\\\"\" : \"\") + \">, but you \") + \"should have returned a React element or `null`\") : undefined;\n return value || null;\n}\n/**\n * The public API for matching a single path and rendering.\n */\n\n\nvar Route =\n/*#__PURE__*/\nfunction (_React$Component) {\n Object(_babel_runtime_helpers_esm_inheritsLoose__WEBPACK_IMPORTED_MODULE_0__[\"default\"])(Route, _React$Component);\n\n function Route() {\n return _React$Component.apply(this, arguments) || this;\n }\n\n var _proto = Route.prototype;\n\n _proto.render = function render() {\n var _this = this;\n\n return react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(context.Consumer, null, function (context$1) {\n !context$1 ? true ? Object(tiny_invariant__WEBPACK_IMPORTED_MODULE_6__[\"default\"])(false, \"You should not use <Route> outside a <Router>\") : undefined : void 0;\n var location = _this.props.location || context$1.location;\n var match = _this.props.computedMatch ? _this.props.computedMatch // <Switch> already computed the match for us\n : _this.props.path ? matchPath(location.pathname, _this.props) : context$1.match;\n\n var props = Object(_babel_runtime_helpers_esm_extends__WEBPACK_IMPORTED_MODULE_7__[\"default\"])({}, context$1, {\n location: location,\n match: match\n });\n\n var _this$props = _this.props,\n children = _this$props.children,\n component = _this$props.component,\n render = _this$props.render; // Preact uses an empty array as children by\n // default, so use null if that's the case.\n\n if (Array.isArray(children) && children.length === 0) {\n children = null;\n }\n\n return react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(context.Provider, {\n value: props\n }, props.match ? children ? typeof children === \"function\" ? true ? evalChildrenDev(children, props, _this.props.path) : undefined : children : component ? react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(component, props) : render ? render(props) : null : typeof children === \"function\" ? true ? evalChildrenDev(children, props, _this.props.path) : undefined : null);\n });\n };\n\n return Route;\n}(react__WEBPACK_IMPORTED_MODULE_1___default.a.Component);\n\nif (true) {\n Route.propTypes = {\n children: prop_types__WEBPACK_IMPORTED_MODULE_2___default.a.oneOfType([prop_types__WEBPACK_IMPORTED_MODULE_2___default.a.func, prop_types__WEBPACK_IMPORTED_MODULE_2___default.a.node]),\n component: function component(props, propName) {\n if (props[propName] && !Object(react_is__WEBPACK_IMPORTED_MODULE_9__[\"isValidElementType\"])(props[propName])) {\n return new Error(\"Invalid prop 'component' supplied to 'Route': the prop is not a valid React component\");\n }\n },\n exact: prop_types__WEBPACK_IMPORTED_MODULE_2___default.a.bool,\n location: prop_types__WEBPACK_IMPORTED_MODULE_2___default.a.object,\n path: prop_types__WEBPACK_IMPORTED_MODULE_2___default.a.oneOfType([prop_types__WEBPACK_IMPORTED_MODULE_2___default.a.string, prop_types__WEBPACK_IMPORTED_MODULE_2___default.a.arrayOf(prop_types__WEBPACK_IMPORTED_MODULE_2___default.a.string)]),\n render: prop_types__WEBPACK_IMPORTED_MODULE_2___default.a.func,\n sensitive: prop_types__WEBPACK_IMPORTED_MODULE_2___default.a.bool,\n strict: prop_types__WEBPACK_IMPORTED_MODULE_2___default.a.bool\n };\n\n Route.prototype.componentDidMount = function () {\n true ? Object(tiny_warning__WEBPACK_IMPORTED_MODULE_4__[\"default\"])(!(this.props.children && !isEmptyChildren(this.props.children) && this.props.component), \"You should not use <Route component> and <Route children> in the same route; <Route component> will be ignored\") : undefined;\n true ? Object(tiny_warning__WEBPACK_IMPORTED_MODULE_4__[\"default\"])(!(this.props.children && !isEmptyChildren(this.props.children) && this.props.render), \"You should not use <Route render> and <Route children> in the same route; <Route render> will be ignored\") : undefined;\n true ? Object(tiny_warning__WEBPACK_IMPORTED_MODULE_4__[\"default\"])(!(this.props.component && this.props.render), \"You should not use <Route component> and <Route render> in the same route; <Route render> will be ignored\") : undefined;\n };\n\n Route.prototype.componentDidUpdate = function (prevProps) {\n true ? Object(tiny_warning__WEBPACK_IMPORTED_MODULE_4__[\"default\"])(!(this.props.location && !prevProps.location), '<Route> elements should not change from uncontrolled to controlled (or vice versa). You initially used no \"location\" prop and then provided one on a subsequent render.') : undefined;\n true ? Object(tiny_warning__WEBPACK_IMPORTED_MODULE_4__[\"default\"])(!(!this.props.location && prevProps.location), '<Route> elements should not change from controlled to uncontrolled (or vice versa). You provided a \"location\" prop initially but omitted it on a subsequent render.') : undefined;\n };\n}\n\nfunction addLeadingSlash(path) {\n return path.charAt(0) === \"/\" ? path : \"/\" + path;\n}\n\nfunction addBasename(basename, location) {\n if (!basename) return location;\n return Object(_babel_runtime_helpers_esm_extends__WEBPACK_IMPORTED_MODULE_7__[\"default\"])({}, location, {\n pathname: addLeadingSlash(basename) + location.pathname\n });\n}\n\nfunction stripBasename(basename, location) {\n if (!basename) return location;\n var base = addLeadingSlash(basename);\n if (location.pathname.indexOf(base) !== 0) return location;\n return Object(_babel_runtime_helpers_esm_extends__WEBPACK_IMPORTED_MODULE_7__[\"default\"])({}, location, {\n pathname: location.pathname.substr(base.length)\n });\n}\n\nfunction createURL(location) {\n return typeof location === \"string\" ? location : Object(history__WEBPACK_IMPORTED_MODULE_3__[\"createPath\"])(location);\n}\n\nfunction staticHandler(methodName) {\n return function () {\n true ? Object(tiny_invariant__WEBPACK_IMPORTED_MODULE_6__[\"default\"])(false, \"You cannot %s with <StaticRouter>\", methodName) : undefined ;\n };\n}\n\nfunction noop() {}\n/**\n * The public top-level API for a \"static\" <Router>, so-called because it\n * can't actually change the current location. Instead, it just records\n * location changes in a context object. Useful mainly in testing and\n * server-rendering scenarios.\n */\n\n\nvar StaticRouter =\n/*#__PURE__*/\nfunction (_React$Component) {\n Object(_babel_runtime_helpers_esm_inheritsLoose__WEBPACK_IMPORTED_MODULE_0__[\"default\"])(StaticRouter, _React$Component);\n\n function StaticRouter() {\n var _this;\n\n for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {\n args[_key] = arguments[_key];\n }\n\n _this = _React$Component.call.apply(_React$Component, [this].concat(args)) || this;\n\n _this.handlePush = function (location) {\n return _this.navigateTo(location, \"PUSH\");\n };\n\n _this.handleReplace = function (location) {\n return _this.navigateTo(location, \"REPLACE\");\n };\n\n _this.handleListen = function () {\n return noop;\n };\n\n _this.handleBlock = function () {\n return noop;\n };\n\n return _this;\n }\n\n var _proto = StaticRouter.prototype;\n\n _proto.navigateTo = function navigateTo(location, action) {\n var _this$props = this.props,\n _this$props$basename = _this$props.basename,\n basename = _this$props$basename === void 0 ? \"\" : _this$props$basename,\n _this$props$context = _this$props.context,\n context = _this$props$context === void 0 ? {} : _this$props$context;\n context.action = action;\n context.location = addBasename(basename, Object(history__WEBPACK_IMPORTED_MODULE_3__[\"createLocation\"])(location));\n context.url = createURL(context.location);\n };\n\n _proto.render = function render() {\n var _this$props2 = this.props,\n _this$props2$basename = _this$props2.basename,\n basename = _this$props2$basename === void 0 ? \"\" : _this$props2$basename,\n _this$props2$context = _this$props2.context,\n context = _this$props2$context === void 0 ? {} : _this$props2$context,\n _this$props2$location = _this$props2.location,\n location = _this$props2$location === void 0 ? \"/\" : _this$props2$location,\n rest = Object(_babel_runtime_helpers_esm_objectWithoutPropertiesLoose__WEBPACK_IMPORTED_MODULE_10__[\"default\"])(_this$props2, [\"basename\", \"context\", \"location\"]);\n\n var history = {\n createHref: function createHref(path) {\n return addLeadingSlash(basename + createURL(path));\n },\n action: \"POP\",\n location: stripBasename(basename, Object(history__WEBPACK_IMPORTED_MODULE_3__[\"createLocation\"])(location)),\n push: this.handlePush,\n replace: this.handleReplace,\n go: staticHandler(\"go\"),\n goBack: staticHandler(\"goBack\"),\n goForward: staticHandler(\"goForward\"),\n listen: this.handleListen,\n block: this.handleBlock\n };\n return react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(Router, Object(_babel_runtime_helpers_esm_extends__WEBPACK_IMPORTED_MODULE_7__[\"default\"])({}, rest, {\n history: history,\n staticContext: context\n }));\n };\n\n return StaticRouter;\n}(react__WEBPACK_IMPORTED_MODULE_1___default.a.Component);\n\nif (true) {\n StaticRouter.propTypes = {\n basename: prop_types__WEBPACK_IMPORTED_MODULE_2___default.a.string,\n context: prop_types__WEBPACK_IMPORTED_MODULE_2___default.a.object,\n location: prop_types__WEBPACK_IMPORTED_MODULE_2___default.a.oneOfType([prop_types__WEBPACK_IMPORTED_MODULE_2___default.a.string, prop_types__WEBPACK_IMPORTED_MODULE_2___default.a.object])\n };\n\n StaticRouter.prototype.componentDidMount = function () {\n true ? Object(tiny_warning__WEBPACK_IMPORTED_MODULE_4__[\"default\"])(!this.props.history, \"<StaticRouter> ignores the history prop. To use a custom history, \" + \"use `import { Router }` instead of `import { StaticRouter as Router }`.\") : undefined;\n };\n}\n\n/**\n * The public API for rendering the first <Route> that matches.\n */\n\nvar Switch =\n/*#__PURE__*/\nfunction (_React$Component) {\n Object(_babel_runtime_helpers_esm_inheritsLoose__WEBPACK_IMPORTED_MODULE_0__[\"default\"])(Switch, _React$Component);\n\n function Switch() {\n return _React$Component.apply(this, arguments) || this;\n }\n\n var _proto = Switch.prototype;\n\n _proto.render = function render() {\n var _this = this;\n\n return react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(context.Consumer, null, function (context) {\n !context ? true ? Object(tiny_invariant__WEBPACK_IMPORTED_MODULE_6__[\"default\"])(false, \"You should not use <Switch> outside a <Router>\") : undefined : void 0;\n var location = _this.props.location || context.location;\n var element, match; // We use React.Children.forEach instead of React.Children.toArray().find()\n // here because toArray adds keys to all child elements and we do not want\n // to trigger an unmount/remount for two <Route>s that render the same\n // component at different URLs.\n\n react__WEBPACK_IMPORTED_MODULE_1___default.a.Children.forEach(_this.props.children, function (child) {\n if (match == null && react__WEBPACK_IMPORTED_MODULE_1___default.a.isValidElement(child)) {\n element = child;\n var path = child.props.path || child.props.from;\n match = path ? matchPath(location.pathname, Object(_babel_runtime_helpers_esm_extends__WEBPACK_IMPORTED_MODULE_7__[\"default\"])({}, child.props, {\n path: path\n })) : context.match;\n }\n });\n return match ? react__WEBPACK_IMPORTED_MODULE_1___default.a.cloneElement(element, {\n location: location,\n computedMatch: match\n }) : null;\n });\n };\n\n return Switch;\n}(react__WEBPACK_IMPORTED_MODULE_1___default.a.Component);\n\nif (true) {\n Switch.propTypes = {\n children: prop_types__WEBPACK_IMPORTED_MODULE_2___default.a.node,\n location: prop_types__WEBPACK_IMPORTED_MODULE_2___default.a.object\n };\n\n Switch.prototype.componentDidUpdate = function (prevProps) {\n true ? Object(tiny_warning__WEBPACK_IMPORTED_MODULE_4__[\"default\"])(!(this.props.location && !prevProps.location), '<Switch> elements should not change from uncontrolled to controlled (or vice versa). You initially used no \"location\" prop and then provided one on a subsequent render.') : undefined;\n true ? Object(tiny_warning__WEBPACK_IMPORTED_MODULE_4__[\"default\"])(!(!this.props.location && prevProps.location), '<Switch> elements should not change from controlled to uncontrolled (or vice versa). You provided a \"location\" prop initially but omitted it on a subsequent render.') : undefined;\n };\n}\n\n/**\n * A public higher-order component to access the imperative API\n */\n\nfunction withRouter(Component) {\n var displayName = \"withRouter(\" + (Component.displayName || Component.name) + \")\";\n\n var C = function C(props) {\n var wrappedComponentRef = props.wrappedComponentRef,\n remainingProps = Object(_babel_runtime_helpers_esm_objectWithoutPropertiesLoose__WEBPACK_IMPORTED_MODULE_10__[\"default\"])(props, [\"wrappedComponentRef\"]);\n\n return react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(context.Consumer, null, function (context) {\n !context ? true ? Object(tiny_invariant__WEBPACK_IMPORTED_MODULE_6__[\"default\"])(false, \"You should not use <\" + displayName + \" /> outside a <Router>\") : undefined : void 0;\n return react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(Component, Object(_babel_runtime_helpers_esm_extends__WEBPACK_IMPORTED_MODULE_7__[\"default\"])({}, remainingProps, context, {\n ref: wrappedComponentRef\n }));\n });\n };\n\n C.displayName = displayName;\n C.WrappedComponent = Component;\n\n if (true) {\n C.propTypes = {\n wrappedComponentRef: prop_types__WEBPACK_IMPORTED_MODULE_2___default.a.oneOfType([prop_types__WEBPACK_IMPORTED_MODULE_2___default.a.string, prop_types__WEBPACK_IMPORTED_MODULE_2___default.a.func, prop_types__WEBPACK_IMPORTED_MODULE_2___default.a.object])\n };\n }\n\n return hoist_non_react_statics__WEBPACK_IMPORTED_MODULE_11___default()(C, Component);\n}\n\nvar useContext = react__WEBPACK_IMPORTED_MODULE_1___default.a.useContext;\nfunction useHistory() {\n if (true) {\n !(typeof useContext === \"function\") ? true ? Object(tiny_invariant__WEBPACK_IMPORTED_MODULE_6__[\"default\"])(false, \"You must use React >= 16.8 in order to use useHistory()\") : undefined : void 0;\n }\n\n return useContext(context).history;\n}\nfunction useLocation() {\n if (true) {\n !(typeof useContext === \"function\") ? true ? Object(tiny_invariant__WEBPACK_IMPORTED_MODULE_6__[\"default\"])(false, \"You must use React >= 16.8 in order to use useLocation()\") : undefined : void 0;\n }\n\n return useContext(context).location;\n}\nfunction useParams() {\n if (true) {\n !(typeof useContext === \"function\") ? true ? Object(tiny_invariant__WEBPACK_IMPORTED_MODULE_6__[\"default\"])(false, \"You must use React >= 16.8 in order to use useParams()\") : undefined : void 0;\n }\n\n var match = useContext(context).match;\n return match ? match.params : {};\n}\nfunction useRouteMatch(path) {\n if (true) {\n !(typeof useContext === \"function\") ? true ? Object(tiny_invariant__WEBPACK_IMPORTED_MODULE_6__[\"default\"])(false, \"You must use React >= 16.8 in order to use useRouteMatch()\") : undefined : void 0;\n }\n\n return path ? matchPath(useLocation().pathname, path) : useContext(context).match;\n}\n\nif (true) {\n if (typeof window !== \"undefined\") {\n var global = window;\n var key = \"__react_router_build__\";\n var buildNames = {\n cjs: \"CommonJS\",\n esm: \"ES modules\",\n umd: \"UMD\"\n };\n\n if (global[key] && global[key] !== \"esm\") {\n var initialBuildName = buildNames[global[key]];\n var secondaryBuildName = buildNames[\"esm\"]; // TODO: Add link to article that explains in detail how to avoid\n // loading 2 different builds.\n\n throw new Error(\"You are loading the \" + secondaryBuildName + \" build of React Router \" + (\"on a page that is already running the \" + initialBuildName + \" \") + \"build, so things won't work right.\");\n }\n\n global[key] = \"esm\";\n }\n}\n\n\n//# sourceMappingURL=react-router.js.map\n\n\n//# sourceURL=webpack:///./node_modules/react-router/esm/react-router.js?");
/***/ }),
/***/ "./node_modules/react-router/node_modules/isarray/index.js":
/*!*****************************************************************!*\
!*** ./node_modules/react-router/node_modules/isarray/index.js ***!
\*****************************************************************/
/*! no static exports found */
/***/ (function(module, exports) {
eval("module.exports = Array.isArray || function (arr) {\n return Object.prototype.toString.call(arr) == '[object Array]';\n};\n\n\n//# sourceURL=webpack:///./node_modules/react-router/node_modules/isarray/index.js?");
/***/ }),
/***/ "./node_modules/react-router/node_modules/path-to-regexp/index.js":
/*!************************************************************************!*\
!*** ./node_modules/react-router/node_modules/path-to-regexp/index.js ***!
\************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
eval("var isarray = __webpack_require__(/*! isarray */ \"./node_modules/react-router/node_modules/isarray/index.js\")\n\n/**\n * Expose `pathToRegexp`.\n */\nmodule.exports = pathToRegexp\nmodule.exports.parse = parse\nmodule.exports.compile = compile\nmodule.exports.tokensToFunction = tokensToFunction\nmodule.exports.tokensToRegExp = tokensToRegExp\n\n/**\n * The main path matching regexp utility.\n *\n * @type {RegExp}\n */\nvar PATH_REGEXP = new RegExp([\n // Match escaped characters that would otherwise appear in future matches.\n // This allows the user to escape special characters that won't transform.\n '(\\\\\\\\.)',\n // Match Express-style parameters and un-named parameters with a prefix\n // and optional suffixes. Matches appear as:\n //\n // \"/:test(\\\\d+)?\" => [\"/\", \"test\", \"\\d+\", undefined, \"?\", undefined]\n // \"/route(\\\\d+)\" => [undefined, undefined, undefined, \"\\d+\", undefined, undefined]\n // \"/*\" => [\"/\", undefined, undefined, undefined, undefined, \"*\"]\n '([\\\\/.])?(?:(?:\\\\:(\\\\w+)(?:\\\\(((?:\\\\\\\\.|[^\\\\\\\\()])+)\\\\))?|\\\\(((?:\\\\\\\\.|[^\\\\\\\\()])+)\\\\))([+*?])?|(\\\\*))'\n].join('|'), 'g')\n\n/**\n * Parse a string for the raw tokens.\n *\n * @param {string} str\n * @param {Object=} options\n * @return {!Array}\n */\nfunction parse (str, options) {\n var tokens = []\n var key = 0\n var index = 0\n var path = ''\n var defaultDelimiter = options && options.delimiter || '/'\n var res\n\n while ((res = PATH_REGEXP.exec(str)) != null) {\n var m = res[0]\n var escaped = res[1]\n var offset = res.index\n path += str.slice(index, offset)\n index = offset + m.length\n\n // Ignore already escaped sequences.\n if (escaped) {\n path += escaped[1]\n continue\n }\n\n var next = str[index]\n var prefix = res[2]\n var name = res[3]\n var capture = res[4]\n var group = res[5]\n var modifier = res[6]\n var asterisk = res[7]\n\n // Push the current path onto the tokens.\n if (path) {\n tokens.push(path)\n path = ''\n }\n\n var partial = prefix != null && next != null && next !== prefix\n var repeat = modifier === '+' || modifier === '*'\n var optional = modifier === '?' || modifier === '*'\n var delimiter = res[2] || defaultDelimiter\n var pattern = capture || group\n\n tokens.push({\n name: name || key++,\n prefix: prefix || '',\n delimiter: delimiter,\n optional: optional,\n repeat: repeat,\n partial: partial,\n asterisk: !!asterisk,\n pattern: pattern ? escapeGroup(pattern) : (asterisk ? '.*' : '[^' + escapeString(delimiter) + ']+?')\n })\n }\n\n // Match any characters still remaining.\n if (index < str.length) {\n path += str.substr(index)\n }\n\n // If the path exists, push it onto the end.\n if (path) {\n tokens.push(path)\n }\n\n return tokens\n}\n\n/**\n * Compile a string to a template function for the path.\n *\n * @param {string} str\n * @param {Object=} options\n * @return {!function(Object=, Object=)}\n */\nfunction compile (str, options) {\n return tokensToFunction(parse(str, options), options)\n}\n\n/**\n * Prettier encoding of URI path segments.\n *\n * @param {string}\n * @return {string}\n */\nfunction encodeURIComponentPretty (str) {\n return encodeURI(str).replace(/[\\/?#]/g, function (c) {\n return '%' + c.charCodeAt(0).toString(16).toUpperCase()\n })\n}\n\n/**\n * Encode the asterisk parameter. Similar to `pretty`, but allows slashes.\n *\n * @param {string}\n * @return {string}\n */\nfunction encodeAsterisk (str) {\n return encodeURI(str).replace(/[?#]/g, function (c) {\n return '%' + c.charCodeAt(0).toString(16).toUpperCase()\n })\n}\n\n/**\n * Expose a method for transforming tokens into the path function.\n */\nfunction tokensToFunction (tokens, options) {\n // Compile all the tokens into regexps.\n var matches = new Array(tokens.length)\n\n // Compile all the patterns before compilation.\n for (var i = 0; i < tokens.length; i++) {\n if (typeof tokens[i] === 'object') {\n matches[i] = new RegExp('^(?:' + tokens[i].pattern + ')$', flags(options))\n }\n }\n\n return function (obj, opts) {\n var path = ''\n var data = obj || {}\n var options = opts || {}\n var encode = options.pretty ? encodeURIComponentPretty : encodeURIComponent\n\n for (var i = 0; i < tokens.length; i++) {\n var token = tokens[i]\n\n if (typeof token === 'string') {\n path += token\n\n continue\n }\n\n var value = data[token.name]\n var segment\n\n if (value == null) {\n if (token.optional) {\n // Prepend partial segment prefixes.\n if (token.partial) {\n path += token.prefix\n }\n\n continue\n } else {\n throw new TypeError('Expected \"' + token.name + '\" to be defined')\n }\n }\n\n if (isarray(value)) {\n if (!token.repeat) {\n throw new TypeError('Expected \"' + token.name + '\" to not repeat, but received `' + JSON.stringify(value) + '`')\n }\n\n if (value.length === 0) {\n if (token.optional) {\n continue\n } else {\n throw new TypeError('Expected \"' + token.name + '\" to not be empty')\n }\n }\n\n for (var j = 0; j < value.length; j++) {\n segment = encode(value[j])\n\n if (!matches[i].test(segment)) {\n throw new TypeError('Expected all \"' + token.name + '\" to match \"' + token.pattern + '\", but received `' + JSON.stringify(segment) + '`')\n }\n\n path += (j === 0 ? token.prefix : token.delimiter) + segment\n }\n\n continue\n }\n\n segment = token.asterisk ? encodeAsterisk(value) : encode(value)\n\n if (!matches[i].test(segment)) {\n throw new TypeError('Expected \"' + token.name + '\" to match \"' + token.pattern + '\", but received \"' + segment + '\"')\n }\n\n path += token.prefix + segment\n }\n\n return path\n }\n}\n\n/**\n * Escape a regular expression string.\n *\n * @param {string} str\n * @return {string}\n */\nfunction escapeString (str) {\n return str.replace(/([.+*?=^!:${}()[\\]|\\/\\\\])/g, '\\\\$1')\n}\n\n/**\n * Escape the capturing group by escaping special characters and meaning.\n *\n * @param {string} group\n * @return {string}\n */\nfunction escapeGroup (group) {\n return group.replace(/([=!:$\\/()])/g, '\\\\$1')\n}\n\n/**\n * Attach the keys as a property of the regexp.\n *\n * @param {!RegExp} re\n * @param {Array} keys\n * @return {!RegExp}\n */\nfunction attachKeys (re, keys) {\n re.keys = keys\n return re\n}\n\n/**\n * Get the flags for a regexp from the options.\n *\n * @param {Object} options\n * @return {string}\n */\nfunction flags (options) {\n return options && options.sensitive ? '' : 'i'\n}\n\n/**\n * Pull out keys from a regexp.\n *\n * @param {!RegExp} path\n * @param {!Array} keys\n * @return {!RegExp}\n */\nfunction regexpToRegexp (path, keys) {\n // Use a negative lookahead to match only capturing groups.\n var groups = path.source.match(/\\((?!\\?)/g)\n\n if (groups) {\n for (var i = 0; i < groups.length; i++) {\n keys.push({\n name: i,\n prefix: null,\n delimiter: null,\n optional: false,\n repeat: false,\n partial: false,\n asterisk: false,\n pattern: null\n })\n }\n }\n\n return attachKeys(path, keys)\n}\n\n/**\n * Transform an array into a regexp.\n *\n * @param {!Array} path\n * @param {Array} keys\n * @param {!Object} options\n * @return {!RegExp}\n */\nfunction arrayToRegexp (path, keys, options) {\n var parts = []\n\n for (var i = 0; i < path.length; i++) {\n parts.push(pathToRegexp(path[i], keys, options).source)\n }\n\n var regexp = new RegExp('(?:' + parts.join('|') + ')', flags(options))\n\n return attachKeys(regexp, keys)\n}\n\n/**\n * Create a path regexp from string input.\n *\n * @param {string} path\n * @param {!Array} keys\n * @param {!Object} options\n * @return {!RegExp}\n */\nfunction stringToRegexp (path, keys, options) {\n return tokensToRegExp(parse(path, options), keys, options)\n}\n\n/**\n * Expose a function for taking tokens and returning a RegExp.\n *\n * @param {!Array} tokens\n * @param {(Array|Object)=} keys\n * @param {Object=} options\n * @return {!RegExp}\n */\nfunction tokensToRegExp (tokens, keys, options) {\n if (!isarray(keys)) {\n options = /** @type {!Object} */ (keys || options)\n keys = []\n }\n\n options = options || {}\n\n var strict = options.strict\n var end = options.end !== false\n var route = ''\n\n // Iterate over the tokens and create our regexp string.\n for (var i = 0; i < tokens.length; i++) {\n var token = tokens[i]\n\n if (typeof token === 'string') {\n route += escapeString(token)\n } else {\n var prefix = escapeString(token.prefix)\n var capture = '(?:' + token.pattern + ')'\n\n keys.push(token)\n\n if (token.repeat) {\n capture += '(?:' + prefix + capture + ')*'\n }\n\n if (token.optional) {\n if (!token.partial) {\n capture = '(?:' + prefix + '(' + capture + '))?'\n } else {\n capture = prefix + '(' + capture + ')?'\n }\n } else {\n capture = prefix + '(' + capture + ')'\n }\n\n route += capture\n }\n }\n\n var delimiter = escapeString(options.delimiter || '/')\n var endsWithDelimiter = route.slice(-delimiter.length) === delimiter\n\n // In non-strict mode we allow a slash at the end of match. If the path to\n // match already ends with a slash, we remove it for consistency. The slash\n // is valid at the end of a path match, not in the middle. This is important\n // in non-ending mode, where \"/test/\" shouldn't match \"/test//route\".\n if (!strict) {\n route = (endsWithDelimiter ? route.slice(0, -delimiter.length) : route) + '(?:' + delimiter + '(?=$))?'\n }\n\n if (end) {\n route += '$'\n } else {\n // In non-ending mode, we need the capturing groups to match as much as\n // possible by using a positive lookahead to the end or next path segment.\n route += strict && endsWithDelimiter ? '' : '(?=' + delimiter + '|$)'\n }\n\n return attachKeys(new RegExp('^' + route, flags(options)), keys)\n}\n\n/**\n * Normalize the given path string, returning a regular expression.\n *\n * An empty array can be passed in for the keys, which will hold the\n * placeholder key descriptions. For example, using `/user/:id`, `keys` will\n * contain `[{ name: 'id', delimiter: '/', optional: false, repeat: false }]`.\n *\n * @param {(string|RegExp|Array)} path\n * @param {(Array|Object)=} keys\n * @param {Object=} options\n * @return {!RegExp}\n */\nfunction pathToRegexp (path, keys, options) {\n if (!isarray(keys)) {\n options = /** @type {!Object} */ (keys || options)\n keys = []\n }\n\n options = options || {}\n\n if (path instanceof RegExp) {\n return regexpToRegexp(path, /** @type {!Array} */ (keys))\n }\n\n if (isarray(path)) {\n return arrayToRegexp(/** @type {!Array} */ (path), /** @type {!Array} */ (keys), options)\n }\n\n return stringToRegexp(/** @type {string} */ (path), /** @type {!Array} */ (keys), options)\n}\n\n\n//# sourceURL=webpack:///./node_modules/react-router/node_modules/path-to-regexp/index.js?");
/***/ }),
/***/ "./node_modules/react-validation/build/button.js":
/*!*******************************************************!*\
!*** ./node_modules/react-validation/build/button.js ***!
\*******************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
eval("!function(e,t){ true?module.exports=t(__webpack_require__(/*! react */ \"./node_modules/react/index.js\"),__webpack_require__(/*! prop-types */ \"./node_modules/prop-types/index.js\")):undefined}(this,function(e,t){return function(e){function t(n){if(r[n])return r[n].exports;var o=r[n]={i:n,l:!1,exports:{}};return e[n].call(o.exports,o,o.exports,t),o.l=!0,o.exports}var r={};return t.m=e,t.c=r,t.d=function(e,r,n){t.o(e,r)||Object.defineProperty(e,r,{configurable:!1,enumerable:!0,get:n})},t.n=function(e){var r=e&&e.__esModule?function(){return e.default}:function(){return e};return t.d(r,\"a\",r),r},t.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},t.p=\"/\",t(t.s=15)}({0:function(t,r){t.exports=e},1:function(e,r){e.exports=t},15:function(e,t,r){\"use strict\";function n(e,t){var r={};for(var n in e)t.indexOf(n)>=0||Object.prototype.hasOwnProperty.call(e,n)&&(r[n]=e[n]);return r}Object.defineProperty(t,\"__esModule\",{value:!0});var o=r(0),u=r.n(o),a=r(1),c=r.n(a),i=r(9),s=function(e){var t=e.hasErrors,r=n(e,[\"hasErrors\"]);return u.a.createElement(\"button\",Object.assign({},r,{disabled:t}))};s.contextTypes={hasErrors:c.a.bool},t.default=Object(i.a)(s)},9:function(e,t,r){\"use strict\";function n(e,t){if(!(e instanceof t))throw new TypeError(\"Cannot call a class as a function\")}function o(e,t){if(!e)throw new ReferenceError(\"this hasn't been initialised - super() hasn't been called\");return!t||\"object\"!==typeof t&&\"function\"!==typeof t?e:t}function u(e,t){if(\"function\"!==typeof t&&null!==t)throw new TypeError(\"Super expression must either be null or a function, not \"+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}function a(e){var t,r;return r=t=function(t){function r(){return n(this,r),o(this,(r.__proto__||Object.getPrototypeOf(r)).apply(this,arguments))}return u(r,t),f(r,[{key:\"shouldComponentUpdate\",value:function(e,t,r){return r._errors!==this.context._errors}},{key:\"render\",value:function(){var t=!!Object.keys(this.context._errors).length;return i.a.createElement(e,Object.assign({},this.props,{hasErrors:t}))}}]),r}(c.Component),t.contextTypes={_errors:p.a.arrayOf(p.a.oneOfType([p.a.object,p.a.string]))},t.displayName=\"Button(\"+e.name+\")\",r}t.a=a;var c=r(0),i=r.n(c),s=r(1),p=r.n(s),f=function(){function e(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,\"value\"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}}return function(t,r,n){return r&&e(t.prototype,r),n&&e(t,n),t}}()}})});\n//# sourceMappingURL=button.js.map\n\n//# sourceURL=webpack:///./node_modules/react-validation/build/button.js?");
/***/ }),
/***/ "./node_modules/react-validation/build/form.js":
/*!*****************************************************!*\
!*** ./node_modules/react-validation/build/form.js ***!
\*****************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
eval("!function(e,t){ true?module.exports=t(__webpack_require__(/*! react */ \"./node_modules/react/index.js\"),__webpack_require__(/*! prop-types */ \"./node_modules/prop-types/index.js\"),__webpack_require__(/*! lodash.omit */ \"./node_modules/lodash.omit/index.js\")):undefined}(this,function(e,t,r){return function(e){function t(n){if(r[n])return r[n].exports;var a=r[n]={i:n,l:!1,exports:{}};return e[n].call(a.exports,a,a.exports,t),a.l=!0,a.exports}var r={};return t.m=e,t.c=r,t.d=function(e,r,n){t.o(e,r)||Object.defineProperty(e,r,{configurable:!1,enumerable:!0,get:n})},t.n=function(e){var r=e&&e.__esModule?function(){return e.default}:function(){return e};return t.d(r,\"a\",r),r},t.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},t.p=\"/\",t(t.s=11)}([function(t,r){t.exports=e},function(e,r){e.exports=t},,,,,,function(e,t,r){\"use strict\";function n(e,t){var r={};for(var n in e)t.indexOf(n)>=0||Object.prototype.hasOwnProperty.call(e,n)&&(r[n]=e[n]);return r}function a(e,t,r){return t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function i(e){if(Array.isArray(e)){for(var t=0,r=Array(e.length);t<e.length;t++)r[t]=e[t];return r}return Array.from(e)}function o(e,t){if(!(e instanceof t))throw new TypeError(\"Cannot call a class as a function\")}function s(e,t){if(!e)throw new ReferenceError(\"this hasn't been initialised - super() hasn't been called\");return!t||\"object\"!==typeof t&&\"function\"!==typeof t?e:t}function u(e,t){if(\"function\"!==typeof t&&null!==t)throw new TypeError(\"Super expression must either be null or a function, not \"+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}function c(e){var t,r,c;return r=t=function(t){function r(e,t){o(this,r);var n=s(this,(r.__proto__||Object.getPrototypeOf(r)).call(this,e,t));return c.call(n),n.state={byName:{},byId:{}},n}return u(r,t),h(r,[{key:\"getChildContext\",value:function(){var e=this;return{_register:this._register,_unregister:this._unregister,_setProps:this._setProps,_handleChange:this._handleChange,_handleBlur:this._handleBlur,_getProps:this._getProps,_errors:Object.keys(this.state.byId).filter(function(t){return e.state.byId[t].error})}}},{key:\"render\",value:function(){return l.a.createElement(e,Object.assign({},this.props,{validate:this.validate,validateAll:this.validateAll,getValues:this.getValues,showError:this.showError,hideError:this.hideError}))}}]),r}(f.PureComponent),t.displayName=\"Form(\"+e.name+\")\",t.propTypes={},t.childContextTypes={_register:b.a.func.isRequired,_unregister:b.a.func.isRequired,_setProps:b.a.func.isRequired,_handleChange:b.a.func.isRequired,_handleBlur:b.a.func.isRequired,_getProps:b.a.func.isRequired,_errors:b.a.array},c=function(){var e=this;this._register=function(t,r){e.setState(function(e){return{byName:Object.assign({},e.byName,a({},t.props.name,[].concat(i(e.byName[t.props.name]||[]),[r]))),byId:Object.assign({},e.byId,a({},r,Object.assign({},t.props,{isCheckable:g(t),value:t.props.value||\"\"},g(t)?{checked:!!t.props.checked}:{})))}},e._setErrors)},this._unregister=function(t,r){var n=[].concat(i(e.state.byName[t.props.name]));n.splice(n.indexOf(r),1);var o=n.length?Object.assign({},e.state.byName,a({},t.props.name,n)):y()(e.state.byName,t.props.name);e.setState({byName:o,byId:y()(e.state.byId,r)})},this._getProps=function(t){if(e.state.byId[t]){var r=e.state.byId[t];r.validations,r.isCheckable;return n(r,[\"validations\",\"isCheckable\"])}},this._setProps=function(t,r){e.setState(function(e){return{byId:Object.assign({},e.byId,a({},r,Object.assign({},e.byId[r],t)))}},e._setErrors)},this._handleChange=function(t,r){var n=e.state.byId[r].isCheckable;e.setState({byId:Object.assign({},e.state.byId,n?Object.assign({},e.state.byName[e.state.byId[r].name].reduce(function(t,r){return t[r]=Object.assign({},e.state.byId[r],{checked:!1}),t},{})):{},a({},r,Object.assign({},e.state.byId[r],{isChanged:!0,value:t.target.value},n&&{checked:t.target.checked})))},e._setErrors)},this._handleBlur=function(t,r){e.setState({byId:Object.assign({},e.state.byId,a({},r,Object.assign({},e.state.byId[r],{isUsed:!0,value:t.target.value})))},e._setErrors)},this._setErrors=function(){e.setState(function(e){return{byId:Object.keys(e.byId).reduce(function(t,r){var n=e.byId[r].validations,a=e.byId[r],i=Object.keys(e.byName).reduce(function(t,r){return t[r]=e.byName[r].map(function(t){return e.byId[t]}),t},{}),o=a.value;t[r]=Object.assign({},e.byId[r]);var s=!0,u=!1,c=void 0;try{for(var f,l=n[Symbol.iterator]();!(s=(f=l.next()).done);s=!0){var d=f.value,b=d(o,a,i);if(b){t[r].error=b;break}delete t[r].error}}catch(e){u=!0,c=e}finally{try{!s&&l.return&&l.return()}finally{if(u)throw c}}return t},{})}})},this.getValues=function(){return Object.keys(e.state.byName).reduce(function(t,r){return e.state.byName[r].length>1?t[r]=e.state.byName[r].map(function(t){return e.state.byId[t].value}):t[r]=e.state.byId[e.state.byName[r][0]].value,t},{})},this.validate=function(t){e.setState(function(e){return{byId:Object.assign({},e.byId,e.byName[t].reduce(function(t,r){return t[r]=Object.assign({},e.byId[r],{isChanged:!0,isUsed:!0}),t},{}))}},e._setErrors)},this.validateAll=function(){e.setState(function(e){return{byId:Object.assign({},e.byId,Object.keys(e.byName).reduce(function(t,r){return e.byName[r].reduce(function(r,n){return t[n]=Object.assign({},e.byId[n],{isChanged:!0,isUsed:!0}),r},{}),t},{}))}},e._setErrors)},this.showError=function(t,r){t&&setTimeout(function(){e.setState({byId:Object.assign({},e.state.byId,a({},t.id,Object.assign({},e.state.byId[t.id],{isChanged:!0,isUsed:!0,error:r})))})},0)},this.hideError=function(t){e.setState(function(e){return{byId:Object.assign({},e.byId,a({},t.id,Object.assign({},y()(e.byId[t.id],\"error\"),{isChanged:!1,isUsed:!1})))}})}},r}t.a=c;var f=r(0),l=r.n(f),d=r(1),b=r.n(d),p=r(8),y=r.n(p),h=function(){function e(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,\"value\"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}}return function(t,r,n){return r&&e(t.prototype,r),n&&e(t,n),t}}(),g=function(e){return\"radio\"===e.props.type||\"checkbox\"===e.props.type}},function(e,t){e.exports=r},,,function(e,t,r){\"use strict\";function n(e,t){var r={};for(var n in e)t.indexOf(n)>=0||Object.prototype.hasOwnProperty.call(e,n)&&(r[n]=e[n]);return r}function a(e,t){if(!(e instanceof t))throw new TypeError(\"Cannot call a class as a function\")}function i(e,t){if(!e)throw new ReferenceError(\"this hasn't been initialised - super() hasn't been called\");return!t||\"object\"!==typeof t&&\"function\"!==typeof t?e:t}function o(e,t){if(\"function\"!==typeof t&&null!==t)throw new TypeError(\"Super expression must either be null or a function, not \"+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}Object.defineProperty(t,\"__esModule\",{value:!0});var s=r(0),u=r.n(s),c=r(1),f=r.n(c),l=r(7),d=function(){function e(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,\"value\"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}}return function(t,r,n){return r&&e(t.prototype,r),n&&e(t,n),t}}(),b=function(e){function t(){return a(this,t),i(this,(t.__proto__||Object.getPrototypeOf(t)).apply(this,arguments))}return o(t,e),d(t,[{key:\"render\",value:function(){var e=this.props,t=(e.getValues,e.validate,e.validateAll,e.showError,e.hideError,n(e,[\"getValues\",\"validate\",\"validateAll\",\"showError\",\"hideError\"]));return u.a.createElement(\"form\",t)}}]),t}(s.Component);b.propTypes={getValues:f.a.func.isRequired,validate:f.a.func.isRequired,validateAll:f.a.func.isRequired,showError:f.a.func.isRequired,hideError:f.a.func.isRequired},t.default=Object(l.a)(b)}])});\n//# sourceMappingURL=form.js.map\n\n//# sourceURL=webpack:///./node_modules/react-validation/build/form.js?");
/***/ }),
/***/ "./node_modules/react-validation/build/input.js":
/*!******************************************************!*\
!*** ./node_modules/react-validation/build/input.js ***!
\******************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
eval("!function(e,t){ true?module.exports=t(__webpack_require__(/*! react */ \"./node_modules/react/index.js\"),__webpack_require__(/*! prop-types */ \"./node_modules/prop-types/index.js\"),__webpack_require__(/*! uuid/v4 */ \"./node_modules/uuid/v4.js\")):undefined}(this,function(e,t,n){return function(e){function t(r){if(n[r])return n[r].exports;var o=n[r]={i:r,l:!1,exports:{}};return e[r].call(o.exports,o,o.exports,t),o.l=!0,o.exports}var n={};return t.m=e,t.c=n,t.d=function(e,n,r){t.o(e,n)||Object.defineProperty(e,n,{configurable:!1,enumerable:!0,get:r})},t.n=function(e){var n=e&&e.__esModule?function(){return e.default}:function(){return e};return t.d(n,\"a\",n),n},t.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},t.p=\"/\",t(t.s=12)}([function(t,n){t.exports=e},function(e,n){e.exports=t},function(e,t,n){\"use strict\";function r(e,t){if(!(e instanceof t))throw new TypeError(\"Cannot call a class as a function\")}function o(e,t){if(!e)throw new ReferenceError(\"this hasn't been initialised - super() hasn't been called\");return!t||\"object\"!==typeof t&&\"function\"!==typeof t?e:t}function i(e,t){if(\"function\"!==typeof t&&null!==t)throw new TypeError(\"Super expression must either be null or a function, not \"+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}function u(e){var t,n;return n=t=function(t){function n(){return r(this,n),o(this,(n.__proto__||Object.getPrototypeOf(n)).apply(this,arguments))}return i(n,t),f(n,[{key:\"render\",value:function(){var t=this.context._getProps(this.id);return t?c.a.createElement(e,Object.assign({},t,{onChange:this.handleChange,onBlur:this.handleBlur})):null}}]),n}(s.a),t.displayName=\"Control(\"+e.name+\")\",n}t.a=u;var a=n(0),c=n.n(a),s=n(3),f=function(){function e(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,\"value\"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}return function(t,n,r){return n&&e(t.prototype,n),r&&e(t,r),t}}()},function(e,t,n){\"use strict\";function r(e,t){var n={};for(var r in e)t.indexOf(r)>=0||Object.prototype.hasOwnProperty.call(e,r)&&(n[r]=e[r]);return n}function o(e,t){if(!(e instanceof t))throw new TypeError(\"Cannot call a class as a function\")}function i(e,t){if(!e)throw new ReferenceError(\"this hasn't been initialised - super() hasn't been called\");return!t||\"object\"!==typeof t&&\"function\"!==typeof t?e:t}function u(e,t){if(\"function\"!==typeof t&&null!==t)throw new TypeError(\"Super expression must either be null or a function, not \"+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}var a=n(0),c=(n.n(a),n(1)),s=n.n(c),f=n(4),p=n.n(f),l=n(5),d=n.n(l),h=n(6),y=n.n(h),v=function(){function e(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,\"value\"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}return function(t,n,r){return n&&e(t.prototype,n),r&&e(t,r),t}}(),b=function(e){function t(){var e,n,r,u;o(this,t);for(var a=arguments.length,c=Array(a),s=0;s<a;s++)c[s]=arguments[s];return n=r=i(this,(e=t.__proto__||Object.getPrototypeOf(t)).call.apply(e,[this].concat(c))),r.id=y()(),r.handleChange=function(e){e.persist(),r.context._handleChange(e,r.id),r.props.onChange&&r.props.onChange(e)},r.handleBlur=function(e){e.persist(),r.context._handleBlur(e,r.id),r.props.onBlur&&r.props.onBlur(e)},u=n,i(r,u)}return u(t,e),v(t,[{key:\"componentDidMount\",value:function(){this.context._register(this,this.id)}},{key:\"componentWillUnmount\",value:function(){this.context._unregister(this,this.id)}},{key:\"componentWillReceiveProps\",value:function(e){var t=e.validations,n=r(e,[\"validations\"]),o=this.props,i=o.validations,u=r(o,[\"validations\"]);d()(u,n)&&p()(i,t)||this.context._setProps(n,this.id)}},{key:\"shouldComponentUpdate\",value:function(e,t,n){return n!==this.context}},{key:\"render\",value:function(){return null}}]),t}(a.Component);b.contextTypes={_register:s.a.func.isRequired,_unregister:s.a.func.isRequired,_setProps:s.a.func.isRequired,_handleChange:s.a.func.isRequired,_handleBlur:s.a.func.isRequired,_getProps:s.a.func.isRequired},b.propTypes={validations:s.a.arrayOf(s.a.func),onChange:s.a.func,onBlur:s.a.func},b.defaultProps={validations:[]},t.a=b},function(e,t){e.exports=function(e,t){if(e===t)return!0;var n=e.length;if(t.length!==n)return!1;for(var r=0;r<n;r++)if(e[r]!==t[r])return!1;return!0}},function(e,t){e.exports=function(e,t){if(e===t)return!0;var n=Object.keys(e),r=Object.keys(t),o=n.length;if(r.length!==o)return!1;for(var i=0;i<o;i++){var u=n[i];if(e[u]!==t[u])return!1}return!0}},function(e,t){e.exports=n},,,,,,function(e,t,n){\"use strict\";function r(e,t){var n={};for(var r in e)t.indexOf(r)>=0||Object.prototype.hasOwnProperty.call(e,r)&&(n[r]=e[r]);return n}Object.defineProperty(t,\"__esModule\",{value:!0});var o=n(0),i=n.n(o),u=n(1),a=n.n(u),c=n(2),s=function(e){var t=e.error,n=e.isChanged,o=e.isUsed,u=r(e,[\"error\",\"isChanged\",\"isUsed\"]);return i.a.createElement(\"div\",null,i.a.createElement(\"input\",Object.assign({},u,n&&o&&t?{className:\"is-invalid-input \"+u.className}:{className:u.className})),n&&o&&t)};s.propTypes={error:a.a.oneOfType([a.a.node,a.a.string])},t.default=Object(c.a)(s)}])});\n//# sourceMappingURL=input.js.map\n\n//# sourceURL=webpack:///./node_modules/react-validation/build/input.js?");
/***/ }),
/***/ "./node_modules/react/cjs/react.development.js":
/*!*****************************************************!*\
!*** ./node_modules/react/cjs/react.development.js ***!
\*****************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
eval("/** @license React v16.13.1\n * react.development.js\n *\n * Copyright (c) Facebook, Inc. and its affiliates.\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\n\n\n\nif (true) {\n (function() {\n'use strict';\n\nvar _assign = __webpack_require__(/*! object-assign */ \"./node_modules/object-assign/index.js\");\nvar checkPropTypes = __webpack_require__(/*! prop-types/checkPropTypes */ \"./node_modules/prop-types/checkPropTypes.js\");\n\nvar ReactVersion = '16.13.1';\n\n// The Symbol used to tag the ReactElement-like types. If there is no native Symbol\n// nor polyfill, then a plain number is used for performance.\nvar hasSymbol = typeof Symbol === 'function' && Symbol.for;\nvar REACT_ELEMENT_TYPE = hasSymbol ? Symbol.for('react.element') : 0xeac7;\nvar REACT_PORTAL_TYPE = hasSymbol ? Symbol.for('react.portal') : 0xeaca;\nvar REACT_FRAGMENT_TYPE = hasSymbol ? Symbol.for('react.fragment') : 0xeacb;\nvar REACT_STRICT_MODE_TYPE = hasSymbol ? Symbol.for('react.strict_mode') : 0xeacc;\nvar REACT_PROFILER_TYPE = hasSymbol ? Symbol.for('react.profiler') : 0xead2;\nvar REACT_PROVIDER_TYPE = hasSymbol ? Symbol.for('react.provider') : 0xeacd;\nvar REACT_CONTEXT_TYPE = hasSymbol ? Symbol.for('react.context') : 0xeace; // TODO: We don't use AsyncMode or ConcurrentMode anymore. They were temporary\nvar REACT_CONCURRENT_MODE_TYPE = hasSymbol ? Symbol.for('react.concurrent_mode') : 0xeacf;\nvar REACT_FORWARD_REF_TYPE = hasSymbol ? Symbol.for('react.forward_ref') : 0xead0;\nvar REACT_SUSPENSE_TYPE = hasSymbol ? Symbol.for('react.suspense') : 0xead1;\nvar REACT_SUSPENSE_LIST_TYPE = hasSymbol ? Symbol.for('react.suspense_list') : 0xead8;\nvar REACT_MEMO_TYPE = hasSymbol ? Symbol.for('react.memo') : 0xead3;\nvar REACT_LAZY_TYPE = hasSymbol ? Symbol.for('react.lazy') : 0xead4;\nvar REACT_BLOCK_TYPE = hasSymbol ? Symbol.for('react.block') : 0xead9;\nvar REACT_FUNDAMENTAL_TYPE = hasSymbol ? Symbol.for('react.fundamental') : 0xead5;\nvar REACT_RESPONDER_TYPE = hasSymbol ? Symbol.for('react.responder') : 0xead6;\nvar REACT_SCOPE_TYPE = hasSymbol ? Symbol.for('react.scope') : 0xead7;\nvar MAYBE_ITERATOR_SYMBOL = typeof Symbol === 'function' && Symbol.iterator;\nvar FAUX_ITERATOR_SYMBOL = '@@iterator';\nfunction getIteratorFn(maybeIterable) {\n if (maybeIterable === null || typeof maybeIterable !== 'object') {\n return null;\n }\n\n var maybeIterator = MAYBE_ITERATOR_SYMBOL && maybeIterable[MAYBE_ITERATOR_SYMBOL] || maybeIterable[FAUX_ITERATOR_SYMBOL];\n\n if (typeof maybeIterator === 'function') {\n return maybeIterator;\n }\n\n return null;\n}\n\n/**\n * Keeps track of the current dispatcher.\n */\nvar ReactCurrentDispatcher = {\n /**\n * @internal\n * @type {ReactComponent}\n */\n current: null\n};\n\n/**\n * Keeps track of the current batch's configuration such as how long an update\n * should suspend for if it needs to.\n */\nvar ReactCurrentBatchConfig = {\n suspense: null\n};\n\n/**\n * Keeps track of the current owner.\n *\n * The current owner is the component who should own any components that are\n * currently being constructed.\n */\nvar ReactCurrentOwner = {\n /**\n * @internal\n * @type {ReactComponent}\n */\n current: null\n};\n\nvar BEFORE_SLASH_RE = /^(.*)[\\\\\\/]/;\nfunction describeComponentFrame (name, source, ownerName) {\n var sourceInfo = '';\n\n if (source) {\n var path = source.fileName;\n var fileName = path.replace(BEFORE_SLASH_RE, '');\n\n {\n // In DEV, include code for a common special case:\n // prefer \"folder/index.js\" instead of just \"index.js\".\n if (/^index\\./.test(fileName)) {\n var match = path.match(BEFORE_SLASH_RE);\n\n if (match) {\n var pathBeforeSlash = match[1];\n\n if (pathBeforeSlash) {\n var folderName = pathBeforeSlash.replace(BEFORE_SLASH_RE, '');\n fileName = folderName + '/' + fileName;\n }\n }\n }\n }\n\n sourceInfo = ' (at ' + fileName + ':' + source.lineNumber + ')';\n } else if (ownerName) {\n sourceInfo = ' (created by ' + ownerName + ')';\n }\n\n return '\\n in ' + (name || 'Unknown') + sourceInfo;\n}\n\nvar Resolved = 1;\nfunction refineResolvedLazyComponent(lazyComponent) {\n return lazyComponent._status === Resolved ? lazyComponent._result : null;\n}\n\nfunction getWrappedName(outerType, innerType, wrapperName) {\n var functionName = innerType.displayName || innerType.name || '';\n return outerType.displayName || (functionName !== '' ? wrapperName + \"(\" + functionName + \")\" : wrapperName);\n}\n\nfunction getComponentName(type) {\n if (type == null) {\n // Host root, text node or just invalid type.\n return null;\n }\n\n {\n if (typeof type.tag === 'number') {\n error('Received an unexpected object in getComponentName(). ' + 'This is likely a bug in React. Please file an issue.');\n }\n }\n\n if (typeof type === 'function') {\n return type.displayName || type.name || null;\n }\n\n if (typeof type === 'string') {\n return type;\n }\n\n switch (type) {\n case REACT_FRAGMENT_TYPE:\n return 'Fragment';\n\n case REACT_PORTAL_TYPE:\n return 'Portal';\n\n case REACT_PROFILER_TYPE:\n return \"Profiler\";\n\n case REACT_STRICT_MODE_TYPE:\n return 'StrictMode';\n\n case REACT_SUSPENSE_TYPE:\n return 'Suspense';\n\n case REACT_SUSPENSE_LIST_TYPE:\n return 'SuspenseList';\n }\n\n if (typeof type === 'object') {\n switch (type.$$typeof) {\n case REACT_CONTEXT_TYPE:\n return 'Context.Consumer';\n\n case REACT_PROVIDER_TYPE:\n return 'Context.Provider';\n\n case REACT_FORWARD_REF_TYPE:\n return getWrappedName(type, type.render, 'ForwardRef');\n\n case REACT_MEMO_TYPE:\n return getComponentName(type.type);\n\n case REACT_BLOCK_TYPE:\n return getComponentName(type.render);\n\n case REACT_LAZY_TYPE:\n {\n var thenable = type;\n var resolvedThenable = refineResolvedLazyComponent(thenable);\n\n if (resolvedThenable) {\n return getComponentName(resolvedThenable);\n }\n\n break;\n }\n }\n }\n\n return null;\n}\n\nvar ReactDebugCurrentFrame = {};\nvar currentlyValidatingElement = null;\nfunction setCurrentlyValidatingElement(element) {\n {\n currentlyValidatingElement = element;\n }\n}\n\n{\n // Stack implementation injected by the current renderer.\n ReactDebugCurrentFrame.getCurrentStack = null;\n\n ReactDebugCurrentFrame.getStackAddendum = function () {\n var stack = ''; // Add an extra top frame while an element is being validated\n\n if (currentlyValidatingElement) {\n var name = getComponentName(currentlyValidatingElement.type);\n var owner = currentlyValidatingElement._owner;\n stack += describeComponentFrame(name, currentlyValidatingElement._source, owner && getComponentName(owner.type));\n } // Delegate to the injected renderer-specific implementation\n\n\n var impl = ReactDebugCurrentFrame.getCurrentStack;\n\n if (impl) {\n stack += impl() || '';\n }\n\n return stack;\n };\n}\n\n/**\n * Used by act() to track whether you're inside an act() scope.\n */\nvar IsSomeRendererActing = {\n current: false\n};\n\nvar ReactSharedInternals = {\n ReactCurrentDispatcher: ReactCurrentDispatcher,\n ReactCurrentBatchConfig: ReactCurrentBatchConfig,\n ReactCurrentOwner: ReactCurrentOwner,\n IsSomeRendererActing: IsSomeRendererActing,\n // Used by renderers to avoid bundling object-assign twice in UMD bundles:\n assign: _assign\n};\n\n{\n _assign(ReactSharedInternals, {\n // These should not be included in production.\n ReactDebugCurrentFrame: ReactDebugCurrentFrame,\n // Shim for React DOM 16.0.0 which still destructured (but not used) this.\n // TODO: remove in React 17.0.\n ReactComponentTreeHook: {}\n });\n}\n\n// by calls to these methods by a Babel plugin.\n//\n// In PROD (or in packages without access to React internals),\n// they are left as they are instead.\n\nfunction warn(format) {\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 printWarning('warn', format, args);\n }\n}\nfunction error(format) {\n {\n for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {\n args[_key2 - 1] = arguments[_key2];\n }\n\n printWarning('error', format, args);\n }\n}\n\nfunction printWarning(level, format, args) {\n // When changing this logic, you might want to also\n // update consoleWithStackDev.www.js as well.\n {\n var hasExistingStack = args.length > 0 && typeof args[args.length - 1] === 'string' && args[args.length - 1].indexOf('\\n in') === 0;\n\n if (!hasExistingStack) {\n var ReactDebugCurrentFrame = ReactSharedInternals.ReactDebugCurrentFrame;\n var stack = ReactDebugCurrentFrame.getStackAddendum();\n\n if (stack !== '') {\n format += '%s';\n args = args.concat([stack]);\n }\n }\n\n var argsWithFormat = args.map(function (item) {\n return '' + item;\n }); // Careful: RN currently depends on this prefix\n\n argsWithFormat.unshift('Warning: ' + format); // We intentionally don't use spread (or .apply) directly because it\n // breaks IE9: https://github.com/facebook/react/issues/13610\n // eslint-disable-next-line react-internal/no-production-logging\n\n Function.prototype.apply.call(console[level], console, argsWithFormat);\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 var argIndex = 0;\n var message = 'Warning: ' + format.replace(/%s/g, function () {\n return args[argIndex++];\n });\n throw new Error(message);\n } catch (x) {}\n }\n}\n\nvar didWarnStateUpdateForUnmountedComponent = {};\n\nfunction warnNoop(publicInstance, callerName) {\n {\n var _constructor = publicInstance.constructor;\n var componentName = _constructor && (_constructor.displayName || _constructor.name) || 'ReactClass';\n var warningKey = componentName + \".\" + callerName;\n\n if (didWarnStateUpdateForUnmountedComponent[warningKey]) {\n return;\n }\n\n error(\"Can't call %s on a component that is not yet mounted. \" + 'This is a no-op, but it might indicate a bug in your application. ' + 'Instead, assign to `this.state` directly or define a `state = {};` ' + 'class property with the desired state in the %s component.', callerName, componentName);\n\n didWarnStateUpdateForUnmountedComponent[warningKey] = true;\n }\n}\n/**\n * This is the abstract API for an update queue.\n */\n\n\nvar ReactNoopUpdateQueue = {\n /**\n * Checks whether or not this composite component is mounted.\n * @param {ReactClass} publicInstance The instance we want to test.\n * @return {boolean} True if mounted, false otherwise.\n * @protected\n * @final\n */\n isMounted: function (publicInstance) {\n return false;\n },\n\n /**\n * Forces an update. This should only be invoked when it is known with\n * certainty that we are **not** in a DOM transaction.\n *\n * You may want to call this when you know that some deeper aspect of the\n * component's state has changed but `setState` was not called.\n *\n * This will not invoke `shouldComponentUpdate`, but it will invoke\n * `componentWillUpdate` and `componentDidUpdate`.\n *\n * @param {ReactClass} publicInstance The instance that should rerender.\n * @param {?function} callback Called after component is updated.\n * @param {?string} callerName name of the calling function in the public API.\n * @internal\n */\n enqueueForceUpdate: function (publicInstance, callback, callerName) {\n warnNoop(publicInstance, 'forceUpdate');\n },\n\n /**\n * Replaces all of the state. Always use this or `setState` to mutate state.\n * You should treat `this.state` as immutable.\n *\n * There is no guarantee that `this.state` will be immediately updated, so\n * accessing `this.state` after calling this method may return the old value.\n *\n * @param {ReactClass} publicInstance The instance that should rerender.\n * @param {object} completeState Next state.\n * @param {?function} callback Called after component is updated.\n * @param {?string} callerName name of the calling function in the public API.\n * @internal\n */\n enqueueReplaceState: function (publicInstance, completeState, callback, callerName) {\n warnNoop(publicInstance, 'replaceState');\n },\n\n /**\n * Sets a subset of the state. This only exists because _pendingState is\n * internal. This provides a merging strategy that is not available to deep\n * properties which is confusing. TODO: Expose pendingState or don't use it\n * during the merge.\n *\n * @param {ReactClass} publicInstance The instance that should rerender.\n * @param {object} partialState Next partial state to be merged with state.\n * @param {?function} callback Called after component is updated.\n * @param {?string} Name of the calling function in the public API.\n * @internal\n */\n enqueueSetState: function (publicInstance, partialState, callback, callerName) {\n warnNoop(publicInstance, 'setState');\n }\n};\n\nvar emptyObject = {};\n\n{\n Object.freeze(emptyObject);\n}\n/**\n * Base class helpers for the updating state of a component.\n */\n\n\nfunction Component(props, context, updater) {\n this.props = props;\n this.context = context; // If a component has string refs, we will assign a different object later.\n\n this.refs = emptyObject; // We initialize the default updater but the real one gets injected by the\n // renderer.\n\n this.updater = updater || ReactNoopUpdateQueue;\n}\n\nComponent.prototype.isReactComponent = {};\n/**\n * Sets a subset of the state. Always use this to mutate\n * state. You should treat `this.state` as immutable.\n *\n * There is no guarantee that `this.state` will be immediately updated, so\n * accessing `this.state` after calling this method may return the old value.\n *\n * There is no guarantee that calls to `setState` will run synchronously,\n * as they may eventually be batched together. You can provide an optional\n * callback that will be executed when the call to setState is actually\n * completed.\n *\n * When a function is provided to setState, it will be called at some point in\n * the future (not synchronously). It will be called with the up to date\n * component arguments (state, props, context). These values can be different\n * from this.* because your function may be called after receiveProps but before\n * shouldComponentUpdate, and this new state, props, and context will not yet be\n * assigned to this.\n *\n * @param {object|function} partialState Next partial state or function to\n * produce next partial state to be merged with current state.\n * @param {?function} callback Called after state is updated.\n * @final\n * @protected\n */\n\nComponent.prototype.setState = function (partialState, callback) {\n if (!(typeof partialState === 'object' || typeof partialState === 'function' || partialState == null)) {\n {\n throw Error( \"setState(...): takes an object of state variables to update or a function which returns an object of state variables.\" );\n }\n }\n\n this.updater.enqueueSetState(this, partialState, callback, 'setState');\n};\n/**\n * Forces an update. This should only be invoked when it is known with\n * certainty that we are **not** in a DOM transaction.\n *\n * You may want to call this when you know that some deeper aspect of the\n * component's state has changed but `setState` was not called.\n *\n * This will not invoke `shouldComponentUpdate`, but it will invoke\n * `componentWillUpdate` and `componentDidUpdate`.\n *\n * @param {?function} callback Called after update is complete.\n * @final\n * @protected\n */\n\n\nComponent.prototype.forceUpdate = function (callback) {\n this.updater.enqueueForceUpdate(this, callback, 'forceUpdate');\n};\n/**\n * Deprecated APIs. These APIs used to exist on classic React classes but since\n * we would like to deprecate them, we're not going to move them over to this\n * modern base class. Instead, we define a getter that warns if it's accessed.\n */\n\n\n{\n var deprecatedAPIs = {\n isMounted: ['isMounted', 'Instead, make sure to clean up subscriptions and pending requests in ' + 'componentWillUnmount to prevent memory leaks.'],\n replaceState: ['replaceState', 'Refactor your code to use setState instead (see ' + 'https://github.com/facebook/react/issues/3236).']\n };\n\n var defineDeprecationWarning = function (methodName, info) {\n Object.defineProperty(Component.prototype, methodName, {\n get: function () {\n warn('%s(...) is deprecated in plain JavaScript React classes. %s', info[0], info[1]);\n\n return undefined;\n }\n });\n };\n\n for (var fnName in deprecatedAPIs) {\n if (deprecatedAPIs.hasOwnProperty(fnName)) {\n defineDeprecationWarning(fnName, deprecatedAPIs[fnName]);\n }\n }\n}\n\nfunction ComponentDummy() {}\n\nComponentDummy.prototype = Component.prototype;\n/**\n * Convenience component with default shallow equality check for sCU.\n */\n\nfunction PureComponent(props, context, updater) {\n this.props = props;\n this.context = context; // If a component has string refs, we will assign a different object later.\n\n this.refs = emptyObject;\n this.updater = updater || ReactNoopUpdateQueue;\n}\n\nvar pureComponentPrototype = PureComponent.prototype = new ComponentDummy();\npureComponentPrototype.constructor = PureComponent; // Avoid an extra prototype jump for these methods.\n\n_assign(pureComponentPrototype, Component.prototype);\n\npureComponentPrototype.isPureReactComponent = true;\n\n// an immutable object with a single mutable value\nfunction createRef() {\n var refObject = {\n current: null\n };\n\n {\n Object.seal(refObject);\n }\n\n return refObject;\n}\n\nvar hasOwnProperty = Object.prototype.hasOwnProperty;\nvar RESERVED_PROPS = {\n key: true,\n ref: true,\n __self: true,\n __source: true\n};\nvar specialPropKeyWarningShown, specialPropRefWarningShown, didWarnAboutStringRefs;\n\n{\n didWarnAboutStringRefs = {};\n}\n\nfunction hasValidRef(config) {\n {\n if (hasOwnProperty.call(config, 'ref')) {\n var getter = Object.getOwnPropertyDescriptor(config, 'ref').get;\n\n if (getter && getter.isReactWarning) {\n return false;\n }\n }\n }\n\n return config.ref !== undefined;\n}\n\nfunction hasValidKey(config) {\n {\n if (hasOwnProperty.call(config, 'key')) {\n var getter = Object.getOwnPropertyDescriptor(config, 'key').get;\n\n if (getter && getter.isReactWarning) {\n return false;\n }\n }\n }\n\n return config.key !== undefined;\n}\n\nfunction defineKeyPropWarningGetter(props, displayName) {\n var warnAboutAccessingKey = function () {\n {\n if (!specialPropKeyWarningShown) {\n specialPropKeyWarningShown = true;\n\n error('%s: `key` is not a prop. Trying to access it will result ' + 'in `undefined` being returned. If you need to access the same ' + 'value within the child component, you should pass it as a different ' + 'prop. (https://fb.me/react-special-props)', displayName);\n }\n }\n };\n\n warnAboutAccessingKey.isReactWarning = true;\n Object.defineProperty(props, 'key', {\n get: warnAboutAccessingKey,\n configurable: true\n });\n}\n\nfunction defineRefPropWarningGetter(props, displayName) {\n var warnAboutAccessingRef = function () {\n {\n if (!specialPropRefWarningShown) {\n specialPropRefWarningShown = true;\n\n error('%s: `ref` is not a prop. Trying to access it will result ' + 'in `undefined` being returned. If you need to access the same ' + 'value within the child component, you should pass it as a different ' + 'prop. (https://fb.me/react-special-props)', displayName);\n }\n }\n };\n\n warnAboutAccessingRef.isReactWarning = true;\n Object.defineProperty(props, 'ref', {\n get: warnAboutAccessingRef,\n configurable: true\n });\n}\n\nfunction warnIfStringRefCannotBeAutoConverted(config) {\n {\n if (typeof config.ref === 'string' && ReactCurrentOwner.current && config.__self && ReactCurrentOwner.current.stateNode !== config.__self) {\n var componentName = getComponentName(ReactCurrentOwner.current.type);\n\n if (!didWarnAboutStringRefs[componentName]) {\n error('Component \"%s\" contains the string ref \"%s\". ' + 'Support for string refs will be removed in a future major release. ' + 'This case cannot be automatically converted to an arrow function. ' + 'We ask you to manually fix this case by using useRef() or createRef() instead. ' + 'Learn more about using refs safely here: ' + 'https://fb.me/react-strict-mode-string-ref', getComponentName(ReactCurrentOwner.current.type), config.ref);\n\n didWarnAboutStringRefs[componentName] = true;\n }\n }\n }\n}\n/**\n * Factory method to create a new React element. This no longer adheres to\n * the class pattern, so do not use new to call it. Also, instanceof check\n * will not work. Instead test $$typeof field against Symbol.for('react.element') to check\n * if something is a React Element.\n *\n * @param {*} type\n * @param {*} props\n * @param {*} key\n * @param {string|object} ref\n * @param {*} owner\n * @param {*} self A *temporary* helper to detect places where `this` is\n * different from the `owner` when React.createElement is called, so that we\n * can warn. We want to get rid of owner and replace string `ref`s with arrow\n * functions, and as long as `this` and owner are the same, there will be no\n * change in behavior.\n * @param {*} source An annotation object (added by a transpiler or otherwise)\n * indicating filename, line number, and/or other information.\n * @internal\n */\n\n\nvar ReactElement = function (type, key, ref, self, source, owner, props) {\n var element = {\n // This tag allows us to uniquely identify this as a React Element\n $$typeof: REACT_ELEMENT_TYPE,\n // Built-in properties that belong on the element\n type: type,\n key: key,\n ref: ref,\n props: props,\n // Record the component responsible for creating this element.\n _owner: owner\n };\n\n {\n // The validation flag is currently mutative. We put it on\n // an external backing store so that we can freeze the whole object.\n // This can be replaced with a WeakMap once they are implemented in\n // commonly used development environments.\n element._store = {}; // To make comparing ReactElements easier for testing purposes, we make\n // the validation flag non-enumerable (where possible, which should\n // include every environment we run tests in), so the test framework\n // ignores it.\n\n Object.defineProperty(element._store, 'validated', {\n configurable: false,\n enumerable: false,\n writable: true,\n value: false\n }); // self and source are DEV only properties.\n\n Object.defineProperty(element, '_self', {\n configurable: false,\n enumerable: false,\n writable: false,\n value: self\n }); // Two elements created in two different places should be considered\n // equal for testing purposes and therefore we hide it from enumeration.\n\n Object.defineProperty(element, '_source', {\n configurable: false,\n enumerable: false,\n writable: false,\n value: source\n });\n\n if (Object.freeze) {\n Object.freeze(element.props);\n Object.freeze(element);\n }\n }\n\n return element;\n};\n/**\n * Create and return a new ReactElement of the given type.\n * See https://reactjs.org/docs/react-api.html#createelement\n */\n\nfunction createElement(type, config, children) {\n var propName; // Reserved names are extracted\n\n var props = {};\n var key = null;\n var ref = null;\n var self = null;\n var source = null;\n\n if (config != null) {\n if (hasValidRef(config)) {\n ref = config.ref;\n\n {\n warnIfStringRefCannotBeAutoConverted(config);\n }\n }\n\n if (hasValidKey(config)) {\n key = '' + config.key;\n }\n\n self = config.__self === undefined ? null : config.__self;\n source = config.__source === undefined ? null : config.__source; // Remaining properties are added to a new props object\n\n for (propName in config) {\n if (hasOwnProperty.call(config, propName) && !RESERVED_PROPS.hasOwnProperty(propName)) {\n props[propName] = config[propName];\n }\n }\n } // Children can be more than one argument, and those are transferred onto\n // the newly allocated props object.\n\n\n var childrenLength = arguments.length - 2;\n\n if (childrenLength === 1) {\n props.children = children;\n } else if (childrenLength > 1) {\n var childArray = Array(childrenLength);\n\n for (var i = 0; i < childrenLength; i++) {\n childArray[i] = arguments[i + 2];\n }\n\n {\n if (Object.freeze) {\n Object.freeze(childArray);\n }\n }\n\n props.children = childArray;\n } // Resolve default props\n\n\n if (type && type.defaultProps) {\n var defaultProps = type.defaultProps;\n\n for (propName in defaultProps) {\n if (props[propName] === undefined) {\n props[propName] = defaultProps[propName];\n }\n }\n }\n\n {\n if (key || ref) {\n var displayName = typeof type === 'function' ? type.displayName || type.name || 'Unknown' : type;\n\n if (key) {\n defineKeyPropWarningGetter(props, displayName);\n }\n\n if (ref) {\n defineRefPropWarningGetter(props, displayName);\n }\n }\n }\n\n return ReactElement(type, key, ref, self, source, ReactCurrentOwner.current, props);\n}\nfunction cloneAndReplaceKey(oldElement, newKey) {\n var newElement = ReactElement(oldElement.type, newKey, oldElement.ref, oldElement._self, oldElement._source, oldElement._owner, oldElement.props);\n return newElement;\n}\n/**\n * Clone and return a new ReactElement using element as the starting point.\n * See https://reactjs.org/docs/react-api.html#cloneelement\n */\n\nfunction cloneElement(element, config, children) {\n if (!!(element === null || element === undefined)) {\n {\n throw Error( \"React.cloneElement(...): The argument must be a React element, but you passed \" + element + \".\" );\n }\n }\n\n var propName; // Original props are copied\n\n var props = _assign({}, element.props); // Reserved names are extracted\n\n\n var key = element.key;\n var ref = element.ref; // Self is preserved since the owner is preserved.\n\n var self = element._self; // Source is preserved since cloneElement is unlikely to be targeted by a\n // transpiler, and the original source is probably a better indicator of the\n // true owner.\n\n var source = element._source; // Owner will be preserved, unless ref is overridden\n\n var owner = element._owner;\n\n if (config != null) {\n if (hasValidRef(config)) {\n // Silently steal the ref from the parent.\n ref = config.ref;\n owner = ReactCurrentOwner.current;\n }\n\n if (hasValidKey(config)) {\n key = '' + config.key;\n } // Remaining properties override existing props\n\n\n var defaultProps;\n\n if (element.type && element.type.defaultProps) {\n defaultProps = element.type.defaultProps;\n }\n\n for (propName in config) {\n if (hasOwnProperty.call(config, propName) && !RESERVED_PROPS.hasOwnProperty(propName)) {\n if (config[propName] === undefined && defaultProps !== undefined) {\n // Resolve default props\n props[propName] = defaultProps[propName];\n } else {\n props[propName] = config[propName];\n }\n }\n }\n } // Children can be more than one argument, and those are transferred onto\n // the newly allocated props object.\n\n\n var childrenLength = arguments.length - 2;\n\n if (childrenLength === 1) {\n props.children = children;\n } else if (childrenLength > 1) {\n var childArray = Array(childrenLength);\n\n for (var i = 0; i < childrenLength; i++) {\n childArray[i] = arguments[i + 2];\n }\n\n props.children = childArray;\n }\n\n return ReactElement(element.type, key, ref, self, source, owner, props);\n}\n/**\n * Verifies the object is a ReactElement.\n * See https://reactjs.org/docs/react-api.html#isvalidelement\n * @param {?object} object\n * @return {boolean} True if `object` is a ReactElement.\n * @final\n */\n\nfunction isValidElement(object) {\n return typeof object === 'object' && object !== null && object.$$typeof === REACT_ELEMENT_TYPE;\n}\n\nvar SEPARATOR = '.';\nvar SUBSEPARATOR = ':';\n/**\n * Escape and wrap key so it is safe to use as a reactid\n *\n * @param {string} key to be escaped.\n * @return {string} the escaped key.\n */\n\nfunction escape(key) {\n var escapeRegex = /[=:]/g;\n var escaperLookup = {\n '=': '=0',\n ':': '=2'\n };\n var escapedString = ('' + key).replace(escapeRegex, function (match) {\n return escaperLookup[match];\n });\n return '$' + escapedString;\n}\n/**\n * TODO: Test that a single child and an array with one item have the same key\n * pattern.\n */\n\n\nvar didWarnAboutMaps = false;\nvar userProvidedKeyEscapeRegex = /\\/+/g;\n\nfunction escapeUserProvidedKey(text) {\n return ('' + text).replace(userProvidedKeyEscapeRegex, '$&/');\n}\n\nvar POOL_SIZE = 10;\nvar traverseContextPool = [];\n\nfunction getPooledTraverseContext(mapResult, keyPrefix, mapFunction, mapContext) {\n if (traverseContextPool.length) {\n var traverseContext = traverseContextPool.pop();\n traverseContext.result = mapResult;\n traverseContext.keyPrefix = keyPrefix;\n traverseContext.func = mapFunction;\n traverseContext.context = mapContext;\n traverseContext.count = 0;\n return traverseContext;\n } else {\n return {\n result: mapResult,\n keyPrefix: keyPrefix,\n func: mapFunction,\n context: mapContext,\n count: 0\n };\n }\n}\n\nfunction releaseTraverseContext(traverseContext) {\n traverseContext.result = null;\n traverseContext.keyPrefix = null;\n traverseContext.func = null;\n traverseContext.context = null;\n traverseContext.count = 0;\n\n if (traverseContextPool.length < POOL_SIZE) {\n traverseContextPool.push(traverseContext);\n }\n}\n/**\n * @param {?*} children Children tree container.\n * @param {!string} nameSoFar Name of the key path so far.\n * @param {!function} callback Callback to invoke with each child found.\n * @param {?*} traverseContext Used to pass information throughout the traversal\n * process.\n * @return {!number} The number of children in this subtree.\n */\n\n\nfunction traverseAllChildrenImpl(children, nameSoFar, callback, traverseContext) {\n var type = typeof children;\n\n if (type === 'undefined' || type === 'boolean') {\n // All of the above are perceived as null.\n children = null;\n }\n\n var invokeCallback = false;\n\n if (children === null) {\n invokeCallback = true;\n } else {\n switch (type) {\n case 'string':\n case 'number':\n invokeCallback = true;\n break;\n\n case 'object':\n switch (children.$$typeof) {\n case REACT_ELEMENT_TYPE:\n case REACT_PORTAL_TYPE:\n invokeCallback = true;\n }\n\n }\n }\n\n if (invokeCallback) {\n callback(traverseContext, children, // If it's the only child, treat the name as if it was wrapped in an array\n // so that it's consistent if the number of children grows.\n nameSoFar === '' ? SEPARATOR + getComponentKey(children, 0) : nameSoFar);\n return 1;\n }\n\n var child;\n var nextName;\n var subtreeCount = 0; // Count of children found in the current subtree.\n\n var nextNamePrefix = nameSoFar === '' ? SEPARATOR : nameSoFar + SUBSEPARATOR;\n\n if (Array.isArray(children)) {\n for (var i = 0; i < children.length; i++) {\n child = children[i];\n nextName = nextNamePrefix + getComponentKey(child, i);\n subtreeCount += traverseAllChildrenImpl(child, nextName, callback, traverseContext);\n }\n } else {\n var iteratorFn = getIteratorFn(children);\n\n if (typeof iteratorFn === 'function') {\n\n {\n // Warn about using Maps as children\n if (iteratorFn === children.entries) {\n if (!didWarnAboutMaps) {\n warn('Using Maps as children is deprecated and will be removed in ' + 'a future major release. Consider converting children to ' + 'an array of keyed ReactElements instead.');\n }\n\n didWarnAboutMaps = true;\n }\n }\n\n var iterator = iteratorFn.call(children);\n var step;\n var ii = 0;\n\n while (!(step = iterator.next()).done) {\n child = step.value;\n nextName = nextNamePrefix + getComponentKey(child, ii++);\n subtreeCount += traverseAllChildrenImpl(child, nextName, callback, traverseContext);\n }\n } else if (type === 'object') {\n var addendum = '';\n\n {\n addendum = ' If you meant to render a collection of children, use an array ' + 'instead.' + ReactDebugCurrentFrame.getStackAddendum();\n }\n\n var childrenString = '' + children;\n\n {\n {\n throw Error( \"Objects are not valid as a React child (found: \" + (childrenString === '[object Object]' ? 'object with keys {' + Object.keys(children).join(', ') + '}' : childrenString) + \").\" + addendum );\n }\n }\n }\n }\n\n return subtreeCount;\n}\n/**\n * Traverses children that are typically specified as `props.children`, but\n * might also be specified through attributes:\n *\n * - `traverseAllChildren(this.props.children, ...)`\n * - `traverseAllChildren(this.props.leftPanelChildren, ...)`\n *\n * The `traverseContext` is an optional argument that is passed through the\n * entire traversal. It can be used to store accumulations or anything else that\n * the callback might find relevant.\n *\n * @param {?*} children Children tree object.\n * @param {!function} callback To invoke upon traversing each child.\n * @param {?*} traverseContext Context for traversal.\n * @return {!number} The number of children in this subtree.\n */\n\n\nfunction traverseAllChildren(children, callback, traverseContext) {\n if (children == null) {\n return 0;\n }\n\n return traverseAllChildrenImpl(children, '', callback, traverseContext);\n}\n/**\n * Generate a key string that identifies a component within a set.\n *\n * @param {*} component A component that could contain a manual key.\n * @param {number} index Index that is used if a manual key is not provided.\n * @return {string}\n */\n\n\nfunction getComponentKey(component, index) {\n // Do some typechecking here since we call this blindly. We want to ensure\n // that we don't block potential future ES APIs.\n if (typeof component === 'object' && component !== null && component.key != null) {\n // Explicit key\n return escape(component.key);\n } // Implicit key determined by the index in the set\n\n\n return index.toString(36);\n}\n\nfunction forEachSingleChild(bookKeeping, child, name) {\n var func = bookKeeping.func,\n context = bookKeeping.context;\n func.call(context, child, bookKeeping.count++);\n}\n/**\n * Iterates through children that are typically specified as `props.children`.\n *\n * See https://reactjs.org/docs/react-api.html#reactchildrenforeach\n *\n * The provided forEachFunc(child, index) will be called for each\n * leaf child.\n *\n * @param {?*} children Children tree container.\n * @param {function(*, int)} forEachFunc\n * @param {*} forEachContext Context for forEachContext.\n */\n\n\nfunction forEachChildren(children, forEachFunc, forEachContext) {\n if (children == null) {\n return children;\n }\n\n var traverseContext = getPooledTraverseContext(null, null, forEachFunc, forEachContext);\n traverseAllChildren(children, forEachSingleChild, traverseContext);\n releaseTraverseContext(traverseContext);\n}\n\nfunction mapSingleChildIntoContext(bookKeeping, child, childKey) {\n var result = bookKeeping.result,\n keyPrefix = bookKeeping.keyPrefix,\n func = bookKeeping.func,\n context = bookKeeping.context;\n var mappedChild = func.call(context, child, bookKeeping.count++);\n\n if (Array.isArray(mappedChild)) {\n mapIntoWithKeyPrefixInternal(mappedChild, result, childKey, function (c) {\n return c;\n });\n } else if (mappedChild != null) {\n if (isValidElement(mappedChild)) {\n mappedChild = cloneAndReplaceKey(mappedChild, // Keep both the (mapped) and old keys if they differ, just as\n // traverseAllChildren used to do for objects as children\n keyPrefix + (mappedChild.key && (!child || child.key !== mappedChild.key) ? escapeUserProvidedKey(mappedChild.key) + '/' : '') + childKey);\n }\n\n result.push(mappedChild);\n }\n}\n\nfunction mapIntoWithKeyPrefixInternal(children, array, prefix, func, context) {\n var escapedPrefix = '';\n\n if (prefix != null) {\n escapedPrefix = escapeUserProvidedKey(prefix) + '/';\n }\n\n var traverseContext = getPooledTraverseContext(array, escapedPrefix, func, context);\n traverseAllChildren(children, mapSingleChildIntoContext, traverseContext);\n releaseTraverseContext(traverseContext);\n}\n/**\n * Maps children that are typically specified as `props.children`.\n *\n * See https://reactjs.org/docs/react-api.html#reactchildrenmap\n *\n * The provided mapFunction(child, key, index) will be called for each\n * leaf child.\n *\n * @param {?*} children Children tree container.\n * @param {function(*, int)} func The map function.\n * @param {*} context Context for mapFunction.\n * @return {object} Object containing the ordered map of results.\n */\n\n\nfunction mapChildren(children, func, context) {\n if (children == null) {\n return children;\n }\n\n var result = [];\n mapIntoWithKeyPrefixInternal(children, result, null, func, context);\n return result;\n}\n/**\n * Count the number of children that are typically specified as\n * `props.children`.\n *\n * See https://reactjs.org/docs/react-api.html#reactchildrencount\n *\n * @param {?*} children Children tree container.\n * @return {number} The number of children.\n */\n\n\nfunction countChildren(children) {\n return traverseAllChildren(children, function () {\n return null;\n }, null);\n}\n/**\n * Flatten a children object (typically specified as `props.children`) and\n * return an array with appropriately re-keyed children.\n *\n * See https://reactjs.org/docs/react-api.html#reactchildrentoarray\n */\n\n\nfunction toArray(children) {\n var result = [];\n mapIntoWithKeyPrefixInternal(children, result, null, function (child) {\n return child;\n });\n return result;\n}\n/**\n * Returns the first child in a collection of children and verifies that there\n * is only one child in the collection.\n *\n * See https://reactjs.org/docs/react-api.html#reactchildrenonly\n *\n * The current implementation of this function assumes that a single child gets\n * passed without a wrapper, but the purpose of this helper function is to\n * abstract away the particular structure of children.\n *\n * @param {?object} children Child collection structure.\n * @return {ReactElement} The first and only `ReactElement` contained in the\n * structure.\n */\n\n\nfunction onlyChild(children) {\n if (!isValidElement(children)) {\n {\n throw Error( \"React.Children.only expected to receive a single React element child.\" );\n }\n }\n\n return children;\n}\n\nfunction createContext(defaultValue, calculateChangedBits) {\n if (calculateChangedBits === undefined) {\n calculateChangedBits = null;\n } else {\n {\n if (calculateChangedBits !== null && typeof calculateChangedBits !== 'function') {\n error('createContext: Expected the optional second argument to be a ' + 'function. Instead received: %s', calculateChangedBits);\n }\n }\n }\n\n var context = {\n $$typeof: REACT_CONTEXT_TYPE,\n _calculateChangedBits: calculateChangedBits,\n // As a workaround to support multiple concurrent renderers, we categorize\n // some renderers as primary and others as secondary. We only expect\n // there to be two concurrent renderers at most: React Native (primary) and\n // Fabric (secondary); React DOM (primary) and React ART (secondary).\n // Secondary renderers store their context values on separate fields.\n _currentValue: defaultValue,\n _currentValue2: defaultValue,\n // Used to track how many concurrent renderers this context currently\n // supports within in a single renderer. Such as parallel server rendering.\n _threadCount: 0,\n // These are circular\n Provider: null,\n Consumer: null\n };\n context.Provider = {\n $$typeof: REACT_PROVIDER_TYPE,\n _context: context\n };\n var hasWarnedAboutUsingNestedContextConsumers = false;\n var hasWarnedAboutUsingConsumerProvider = false;\n\n {\n // A separate object, but proxies back to the original context object for\n // backwards compatibility. It has a different $$typeof, so we can properly\n // warn for the incorrect usage of Context as a Consumer.\n var Consumer = {\n $$typeof: REACT_CONTEXT_TYPE,\n _context: context,\n _calculateChangedBits: context._calculateChangedBits\n }; // $FlowFixMe: Flow complains about not setting a value, which is intentional here\n\n Object.defineProperties(Consumer, {\n Provider: {\n get: function () {\n if (!hasWarnedAboutUsingConsumerProvider) {\n hasWarnedAboutUsingConsumerProvider = true;\n\n error('Rendering <Context.Consumer.Provider> is not supported and will be removed in ' + 'a future major release. Did you mean to render <Context.Provider> instead?');\n }\n\n return context.Provider;\n },\n set: function (_Provider) {\n context.Provider = _Provider;\n }\n },\n _currentValue: {\n get: function () {\n return context._currentValue;\n },\n set: function (_currentValue) {\n context._currentValue = _currentValue;\n }\n },\n _currentValue2: {\n get: function () {\n return context._currentValue2;\n },\n set: function (_currentValue2) {\n context._currentValue2 = _currentValue2;\n }\n },\n _threadCount: {\n get: function () {\n return context._threadCount;\n },\n set: function (_threadCount) {\n context._threadCount = _threadCount;\n }\n },\n Consumer: {\n get: function () {\n if (!hasWarnedAboutUsingNestedContextConsumers) {\n hasWarnedAboutUsingNestedContextConsumers = true;\n\n error('Rendering <Context.Consumer.Consumer> is not supported and will be removed in ' + 'a future major release. Did you mean to render <Context.Consumer> instead?');\n }\n\n return context.Consumer;\n }\n }\n }); // $FlowFixMe: Flow complains about missing properties because it doesn't understand defineProperty\n\n context.Consumer = Consumer;\n }\n\n {\n context._currentRenderer = null;\n context._currentRenderer2 = null;\n }\n\n return context;\n}\n\nfunction lazy(ctor) {\n var lazyType = {\n $$typeof: REACT_LAZY_TYPE,\n _ctor: ctor,\n // React uses these fields to store the result.\n _status: -1,\n _result: null\n };\n\n {\n // In production, this would just set it on the object.\n var defaultProps;\n var propTypes;\n Object.defineProperties(lazyType, {\n defaultProps: {\n configurable: true,\n get: function () {\n return defaultProps;\n },\n set: function (newDefaultProps) {\n error('React.lazy(...): It is not supported to assign `defaultProps` to ' + 'a lazy component import. Either specify them where the component ' + 'is defined, or create a wrapping component around it.');\n\n defaultProps = newDefaultProps; // Match production behavior more closely:\n\n Object.defineProperty(lazyType, 'defaultProps', {\n enumerable: true\n });\n }\n },\n propTypes: {\n configurable: true,\n get: function () {\n return propTypes;\n },\n set: function (newPropTypes) {\n error('React.lazy(...): It is not supported to assign `propTypes` to ' + 'a lazy component import. Either specify them where the component ' + 'is defined, or create a wrapping component around it.');\n\n propTypes = newPropTypes; // Match production behavior more closely:\n\n Object.defineProperty(lazyType, 'propTypes', {\n enumerable: true\n });\n }\n }\n });\n }\n\n return lazyType;\n}\n\nfunction forwardRef(render) {\n {\n if (render != null && render.$$typeof === REACT_MEMO_TYPE) {\n error('forwardRef requires a render function but received a `memo` ' + 'component. Instead of forwardRef(memo(...)), use ' + 'memo(forwardRef(...)).');\n } else if (typeof render !== 'function') {\n error('forwardRef requires a render function but was given %s.', render === null ? 'null' : typeof render);\n } else {\n if (render.length !== 0 && render.length !== 2) {\n error('forwardRef render functions accept exactly two parameters: props and ref. %s', render.length === 1 ? 'Did you forget to use the ref parameter?' : 'Any additional parameter will be undefined.');\n }\n }\n\n if (render != null) {\n if (render.defaultProps != null || render.propTypes != null) {\n error('forwardRef render functions do not support propTypes or defaultProps. ' + 'Did you accidentally pass a React component?');\n }\n }\n }\n\n return {\n $$typeof: REACT_FORWARD_REF_TYPE,\n render: render\n };\n}\n\nfunction isValidElementType(type) {\n return typeof type === 'string' || typeof type === 'function' || // Note: its typeof might be other than 'symbol' or 'number' if it's a polyfill.\n type === REACT_FRAGMENT_TYPE || type === REACT_CONCURRENT_MODE_TYPE || type === REACT_PROFILER_TYPE || type === REACT_STRICT_MODE_TYPE || type === REACT_SUSPENSE_TYPE || type === REACT_SUSPENSE_LIST_TYPE || typeof type === 'object' && type !== null && (type.$$typeof === REACT_LAZY_TYPE || type.$$typeof === REACT_MEMO_TYPE || type.$$typeof === REACT_PROVIDER_TYPE || type.$$typeof === REACT_CONTEXT_TYPE || type.$$typeof === REACT_FORWARD_REF_TYPE || type.$$typeof === REACT_FUNDAMENTAL_TYPE || type.$$typeof === REACT_RESPONDER_TYPE || type.$$typeof === REACT_SCOPE_TYPE || type.$$typeof === REACT_BLOCK_TYPE);\n}\n\nfunction memo(type, compare) {\n {\n if (!isValidElementType(type)) {\n error('memo: The first argument must be a component. Instead ' + 'received: %s', type === null ? 'null' : typeof type);\n }\n }\n\n return {\n $$typeof: REACT_MEMO_TYPE,\n type: type,\n compare: compare === undefined ? null : compare\n };\n}\n\nfunction resolveDispatcher() {\n var dispatcher = ReactCurrentDispatcher.current;\n\n if (!(dispatcher !== null)) {\n {\n throw Error( \"Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:\\n1. You might have mismatching versions of React and the renderer (such as React DOM)\\n2. You might be breaking the Rules of Hooks\\n3. You might have more than one copy of React in the same app\\nSee https://fb.me/react-invalid-hook-call for tips about how to debug and fix this problem.\" );\n }\n }\n\n return dispatcher;\n}\n\nfunction useContext(Context, unstable_observedBits) {\n var dispatcher = resolveDispatcher();\n\n {\n if (unstable_observedBits !== undefined) {\n error('useContext() second argument is reserved for future ' + 'use in React. Passing it is not supported. ' + 'You passed: %s.%s', unstable_observedBits, typeof unstable_observedBits === 'number' && Array.isArray(arguments[2]) ? '\\n\\nDid you call array.map(useContext)? ' + 'Calling Hooks inside a loop is not supported. ' + 'Learn more at https://fb.me/rules-of-hooks' : '');\n } // TODO: add a more generic warning for invalid values.\n\n\n if (Context._context !== undefined) {\n var realContext = Context._context; // Don't deduplicate because this legitimately causes bugs\n // and nobody should be using this in existing code.\n\n if (realContext.Consumer === Context) {\n error('Calling useContext(Context.Consumer) is not supported, may cause bugs, and will be ' + 'removed in a future major release. Did you mean to call useContext(Context) instead?');\n } else if (realContext.Provider === Context) {\n error('Calling useContext(Context.Provider) is not supported. ' + 'Did you mean to call useContext(Context) instead?');\n }\n }\n }\n\n return dispatcher.useContext(Context, unstable_observedBits);\n}\nfunction useState(initialState) {\n var dispatcher = resolveDispatcher();\n return dispatcher.useState(initialState);\n}\nfunction useReducer(reducer, initialArg, init) {\n var dispatcher = resolveDispatcher();\n return dispatcher.useReducer(reducer, initialArg, init);\n}\nfunction useRef(initialValue) {\n var dispatcher = resolveDispatcher();\n return dispatcher.useRef(initialValue);\n}\nfunction useEffect(create, deps) {\n var dispatcher = resolveDispatcher();\n return dispatcher.useEffect(create, deps);\n}\nfunction useLayoutEffect(create, deps) {\n var dispatcher = resolveDispatcher();\n return dispatcher.useLayoutEffect(create, deps);\n}\nfunction useCallback(callback, deps) {\n var dispatcher = resolveDispatcher();\n return dispatcher.useCallback(callback, deps);\n}\nfunction useMemo(create, deps) {\n var dispatcher = resolveDispatcher();\n return dispatcher.useMemo(create, deps);\n}\nfunction useImperativeHandle(ref, create, deps) {\n var dispatcher = resolveDispatcher();\n return dispatcher.useImperativeHandle(ref, create, deps);\n}\nfunction useDebugValue(value, formatterFn) {\n {\n var dispatcher = resolveDispatcher();\n return dispatcher.useDebugValue(value, formatterFn);\n }\n}\n\nvar propTypesMisspellWarningShown;\n\n{\n propTypesMisspellWarningShown = false;\n}\n\nfunction getDeclarationErrorAddendum() {\n if (ReactCurrentOwner.current) {\n var name = getComponentName(ReactCurrentOwner.current.type);\n\n if (name) {\n return '\\n\\nCheck the render method of `' + name + '`.';\n }\n }\n\n return '';\n}\n\nfunction getSourceInfoErrorAddendum(source) {\n if (source !== undefined) {\n var fileName = source.fileName.replace(/^.*[\\\\\\/]/, '');\n var lineNumber = source.lineNumber;\n return '\\n\\nCheck your code at ' + fileName + ':' + lineNumber + '.';\n }\n\n return '';\n}\n\nfunction getSourceInfoErrorAddendumForProps(elementProps) {\n if (elementProps !== null && elementProps !== undefined) {\n return getSourceInfoErrorAddendum(elementProps.__source);\n }\n\n return '';\n}\n/**\n * Warn if there's no key explicitly set on dynamic arrays of children or\n * object keys are not valid. This allows us to keep track of children between\n * updates.\n */\n\n\nvar ownerHasKeyUseWarning = {};\n\nfunction getCurrentComponentErrorInfo(parentType) {\n var info = getDeclarationErrorAddendum();\n\n if (!info) {\n var parentName = typeof parentType === 'string' ? parentType : parentType.displayName || parentType.name;\n\n if (parentName) {\n info = \"\\n\\nCheck the top-level render call using <\" + parentName + \">.\";\n }\n }\n\n return info;\n}\n/**\n * Warn if the element doesn't have an explicit key assigned to it.\n * This element is in an array. The array could grow and shrink or be\n * reordered. All children that haven't already been validated are required to\n * have a \"key\" property assigned to it. Error statuses are cached so a warning\n * will only be shown once.\n *\n * @internal\n * @param {ReactElement} element Element that requires a key.\n * @param {*} parentType element's parent's type.\n */\n\n\nfunction validateExplicitKey(element, parentType) {\n if (!element._store || element._store.validated || element.key != null) {\n return;\n }\n\n element._store.validated = true;\n var currentComponentErrorInfo = getCurrentComponentErrorInfo(parentType);\n\n if (ownerHasKeyUseWarning[currentComponentErrorInfo]) {\n return;\n }\n\n ownerHasKeyUseWarning[currentComponentErrorInfo] = true; // Usually the current owner is the offender, but if it accepts children as a\n // property, it may be the creator of the child that's responsible for\n // assigning it a key.\n\n var childOwner = '';\n\n if (element && element._owner && element._owner !== ReactCurrentOwner.current) {\n // Give the component that originally created this child.\n childOwner = \" It was passed a child from \" + getComponentName(element._owner.type) + \".\";\n }\n\n setCurrentlyValidatingElement(element);\n\n {\n error('Each child in a list should have a unique \"key\" prop.' + '%s%s See https://fb.me/react-warning-keys for more information.', currentComponentErrorInfo, childOwner);\n }\n\n setCurrentlyValidatingElement(null);\n}\n/**\n * Ensure that every element either is passed in a static location, in an\n * array with an explicit keys property defined, or in an object literal\n * with valid key property.\n *\n * @internal\n * @param {ReactNode} node Statically passed child of any type.\n * @param {*} parentType node's parent's type.\n */\n\n\nfunction validateChildKeys(node, parentType) {\n if (typeof node !== 'object') {\n return;\n }\n\n if (Array.isArray(node)) {\n for (var i = 0; i < node.length; i++) {\n var child = node[i];\n\n if (isValidElement(child)) {\n validateExplicitKey(child, parentType);\n }\n }\n } else if (isValidElement(node)) {\n // This element was passed in a valid location.\n if (node._store) {\n node._store.validated = true;\n }\n } else if (node) {\n var iteratorFn = getIteratorFn(node);\n\n if (typeof iteratorFn === 'function') {\n // Entry iterators used to provide implicit keys,\n // but now we print a separate warning for them later.\n if (iteratorFn !== node.entries) {\n var iterator = iteratorFn.call(node);\n var step;\n\n while (!(step = iterator.next()).done) {\n if (isValidElement(step.value)) {\n validateExplicitKey(step.value, parentType);\n }\n }\n }\n }\n }\n}\n/**\n * Given an element, validate that its props follow the propTypes definition,\n * provided by the type.\n *\n * @param {ReactElement} element\n */\n\n\nfunction validatePropTypes(element) {\n {\n var type = element.type;\n\n if (type === null || type === undefined || typeof type === 'string') {\n return;\n }\n\n var name = getComponentName(type);\n var propTypes;\n\n if (typeof type === 'function') {\n propTypes = type.propTypes;\n } else if (typeof type === 'object' && (type.$$typeof === REACT_FORWARD_REF_TYPE || // Note: Memo only checks outer props here.\n // Inner props are checked in the reconciler.\n type.$$typeof === REACT_MEMO_TYPE)) {\n propTypes = type.propTypes;\n } else {\n return;\n }\n\n if (propTypes) {\n setCurrentlyValidatingElement(element);\n checkPropTypes(propTypes, element.props, 'prop', name, ReactDebugCurrentFrame.getStackAddendum);\n setCurrentlyValidatingElement(null);\n } else if (type.PropTypes !== undefined && !propTypesMisspellWarningShown) {\n propTypesMisspellWarningShown = true;\n\n error('Component %s declared `PropTypes` instead of `propTypes`. Did you misspell the property assignment?', name || 'Unknown');\n }\n\n if (typeof type.getDefaultProps === 'function' && !type.getDefaultProps.isReactClassApproved) {\n error('getDefaultProps is only used on classic React.createClass ' + 'definitions. Use a static property named `defaultProps` instead.');\n }\n }\n}\n/**\n * Given a fragment, validate that it can only be provided with fragment props\n * @param {ReactElement} fragment\n */\n\n\nfunction validateFragmentProps(fragment) {\n {\n setCurrentlyValidatingElement(fragment);\n var keys = Object.keys(fragment.props);\n\n for (var i = 0; i < keys.length; i++) {\n var key = keys[i];\n\n if (key !== 'children' && key !== 'key') {\n error('Invalid prop `%s` supplied to `React.Fragment`. ' + 'React.Fragment can only have `key` and `children` props.', key);\n\n break;\n }\n }\n\n if (fragment.ref !== null) {\n error('Invalid attribute `ref` supplied to `React.Fragment`.');\n }\n\n setCurrentlyValidatingElement(null);\n }\n}\nfunction createElementWithValidation(type, props, children) {\n var validType = isValidElementType(type); // We warn in this case but don't throw. We expect the element creation to\n // succeed and there will likely be errors in render.\n\n if (!validType) {\n var info = '';\n\n if (type === undefined || typeof type === 'object' && type !== null && Object.keys(type).length === 0) {\n info += ' You likely forgot to export your component from the file ' + \"it's defined in, or you might have mixed up default and named imports.\";\n }\n\n var sourceInfo = getSourceInfoErrorAddendumForProps(props);\n\n if (sourceInfo) {\n info += sourceInfo;\n } else {\n info += getDeclarationErrorAddendum();\n }\n\n var typeString;\n\n if (type === null) {\n typeString = 'null';\n } else if (Array.isArray(type)) {\n typeString = 'array';\n } else if (type !== undefined && type.$$typeof === REACT_ELEMENT_TYPE) {\n typeString = \"<\" + (getComponentName(type.type) || 'Unknown') + \" />\";\n info = ' Did you accidentally export a JSX literal instead of a component?';\n } else {\n typeString = typeof type;\n }\n\n {\n error('React.createElement: type is invalid -- expected a string (for ' + 'built-in components) or a class/function (for composite ' + 'components) but got: %s.%s', typeString, info);\n }\n }\n\n var element = createElement.apply(this, arguments); // The result can be nullish if a mock or a custom function is used.\n // TODO: Drop this when these are no longer allowed as the type argument.\n\n if (element == null) {\n return element;\n } // Skip key warning if the type isn't valid since our key validation logic\n // doesn't expect a non-string/function type and can throw confusing errors.\n // We don't want exception behavior to differ between dev and prod.\n // (Rendering will throw with a helpful message and as soon as the type is\n // fixed, the key warnings will appear.)\n\n\n if (validType) {\n for (var i = 2; i < arguments.length; i++) {\n validateChildKeys(arguments[i], type);\n }\n }\n\n if (type === REACT_FRAGMENT_TYPE) {\n validateFragmentProps(element);\n } else {\n validatePropTypes(element);\n }\n\n return element;\n}\nvar didWarnAboutDeprecatedCreateFactory = false;\nfunction createFactoryWithValidation(type) {\n var validatedFactory = createElementWithValidation.bind(null, type);\n validatedFactory.type = type;\n\n {\n if (!didWarnAboutDeprecatedCreateFactory) {\n didWarnAboutDeprecatedCreateFactory = true;\n\n warn('React.createFactory() is deprecated and will be removed in ' + 'a future major release. Consider using JSX ' + 'or use React.createElement() directly instead.');\n } // Legacy hook: remove it\n\n\n Object.defineProperty(validatedFactory, 'type', {\n enumerable: false,\n get: function () {\n warn('Factory.type is deprecated. Access the class directly ' + 'before passing it to createFactory.');\n\n Object.defineProperty(this, 'type', {\n value: type\n });\n return type;\n }\n });\n }\n\n return validatedFactory;\n}\nfunction cloneElementWithValidation(element, props, children) {\n var newElement = cloneElement.apply(this, arguments);\n\n for (var i = 2; i < arguments.length; i++) {\n validateChildKeys(arguments[i], newElement.type);\n }\n\n validatePropTypes(newElement);\n return newElement;\n}\n\n{\n\n try {\n var frozenObject = Object.freeze({});\n var testMap = new Map([[frozenObject, null]]);\n var testSet = new Set([frozenObject]); // This is necessary for Rollup to not consider these unused.\n // https://github.com/rollup/rollup/issues/1771\n // TODO: we can remove these if Rollup fixes the bug.\n\n testMap.set(0, 0);\n testSet.add(0);\n } catch (e) {\n }\n}\n\nvar createElement$1 = createElementWithValidation ;\nvar cloneElement$1 = cloneElementWithValidation ;\nvar createFactory = createFactoryWithValidation ;\nvar Children = {\n map: mapChildren,\n forEach: forEachChildren,\n count: countChildren,\n toArray: toArray,\n only: onlyChild\n};\n\nexports.Children = Children;\nexports.Component = Component;\nexports.Fragment = REACT_FRAGMENT_TYPE;\nexports.Profiler = REACT_PROFILER_TYPE;\nexports.PureComponent = PureComponent;\nexports.StrictMode = REACT_STRICT_MODE_TYPE;\nexports.Suspense = REACT_SUSPENSE_TYPE;\nexports.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED = ReactSharedInternals;\nexports.cloneElement = cloneElement$1;\nexports.createContext = createContext;\nexports.createElement = createElement$1;\nexports.createFactory = createFactory;\nexports.createRef = createRef;\nexports.forwardRef = forwardRef;\nexports.isValidElement = isValidElement;\nexports.lazy = lazy;\nexports.memo = memo;\nexports.useCallback = useCallback;\nexports.useContext = useContext;\nexports.useDebugValue = useDebugValue;\nexports.useEffect = useEffect;\nexports.useImperativeHandle = useImperativeHandle;\nexports.useLayoutEffect = useLayoutEffect;\nexports.useMemo = useMemo;\nexports.useReducer = useReducer;\nexports.useRef = useRef;\nexports.useState = useState;\nexports.version = ReactVersion;\n })();\n}\n\n\n//# sourceURL=webpack:///./node_modules/react/cjs/react.development.js?");
/***/ }),
/***/ "./node_modules/react/index.js":
/*!*************************************!*\
!*** ./node_modules/react/index.js ***!
\*************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
eval("\n\nif (false) {} else {\n module.exports = __webpack_require__(/*! ./cjs/react.development.js */ \"./node_modules/react/cjs/react.development.js\");\n}\n\n\n//# sourceURL=webpack:///./node_modules/react/index.js?");
/***/ }),
/***/ "./node_modules/resolve-pathname/esm/resolve-pathname.js":
/*!***************************************************************!*\
!*** ./node_modules/resolve-pathname/esm/resolve-pathname.js ***!
\***************************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
eval("__webpack_require__.r(__webpack_exports__);\nfunction isAbsolute(pathname) {\n return pathname.charAt(0) === '/';\n}\n\n// About 1.5x faster than the two-arg version of Array#splice()\nfunction spliceOne(list, index) {\n for (var i = index, k = i + 1, n = list.length; k < n; i += 1, k += 1) {\n list[i] = list[k];\n }\n\n list.pop();\n}\n\n// This implementation is based heavily on node's url.parse\nfunction resolvePathname(to, from) {\n if (from === undefined) from = '';\n\n var toParts = (to && to.split('/')) || [];\n var fromParts = (from && from.split('/')) || [];\n\n var isToAbs = to && isAbsolute(to);\n var isFromAbs = from && isAbsolute(from);\n var mustEndAbs = isToAbs || isFromAbs;\n\n if (to && isAbsolute(to)) {\n // to is absolute\n fromParts = toParts;\n } else if (toParts.length) {\n // to is relative, drop the filename\n fromParts.pop();\n fromParts = fromParts.concat(toParts);\n }\n\n if (!fromParts.length) return '/';\n\n var hasTrailingSlash;\n if (fromParts.length) {\n var last = fromParts[fromParts.length - 1];\n hasTrailingSlash = last === '.' || last === '..' || last === '';\n } else {\n hasTrailingSlash = false;\n }\n\n var up = 0;\n for (var i = fromParts.length; i >= 0; i--) {\n var part = fromParts[i];\n\n if (part === '.') {\n spliceOne(fromParts, i);\n } else if (part === '..') {\n spliceOne(fromParts, i);\n up++;\n } else if (up) {\n spliceOne(fromParts, i);\n up--;\n }\n }\n\n if (!mustEndAbs) for (; up--; up) fromParts.unshift('..');\n\n if (\n mustEndAbs &&\n fromParts[0] !== '' &&\n (!fromParts[0] || !isAbsolute(fromParts[0]))\n )\n fromParts.unshift('');\n\n var result = fromParts.join('/');\n\n if (hasTrailingSlash && result.substr(-1) !== '/') result += '/';\n\n return result;\n}\n\n/* harmony default export */ __webpack_exports__[\"default\"] = (resolvePathname);\n\n\n//# sourceURL=webpack:///./node_modules/resolve-pathname/esm/resolve-pathname.js?");
/***/ }),
/***/ "./node_modules/scheduler/cjs/scheduler-tracing.development.js":
/*!*********************************************************************!*\
!*** ./node_modules/scheduler/cjs/scheduler-tracing.development.js ***!
\*********************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
eval("/** @license React v0.19.1\n * scheduler-tracing.development.js\n *\n * Copyright (c) Facebook, Inc. and its affiliates.\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\n\n\n\nif (true) {\n (function() {\n'use strict';\n\nvar DEFAULT_THREAD_ID = 0; // Counters used to generate unique IDs.\n\nvar interactionIDCounter = 0;\nvar threadIDCounter = 0; // Set of currently traced interactions.\n// Interactions \"stack\"–\n// Meaning that newly traced interactions are appended to the previously active set.\n// When an interaction goes out of scope, the previous set (if any) is restored.\n\nexports.__interactionsRef = null; // Listener(s) to notify when interactions begin and end.\n\nexports.__subscriberRef = null;\n\n{\n exports.__interactionsRef = {\n current: new Set()\n };\n exports.__subscriberRef = {\n current: null\n };\n}\nfunction unstable_clear(callback) {\n\n var prevInteractions = exports.__interactionsRef.current;\n exports.__interactionsRef.current = new Set();\n\n try {\n return callback();\n } finally {\n exports.__interactionsRef.current = prevInteractions;\n }\n}\nfunction unstable_getCurrent() {\n {\n return exports.__interactionsRef.current;\n }\n}\nfunction unstable_getThreadID() {\n return ++threadIDCounter;\n}\nfunction unstable_trace(name, timestamp, callback) {\n var threadID = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : DEFAULT_THREAD_ID;\n\n var interaction = {\n __count: 1,\n id: interactionIDCounter++,\n name: name,\n timestamp: timestamp\n };\n var prevInteractions = exports.__interactionsRef.current; // Traced interactions should stack/accumulate.\n // To do that, clone the current interactions.\n // The previous set will be restored upon completion.\n\n var interactions = new Set(prevInteractions);\n interactions.add(interaction);\n exports.__interactionsRef.current = interactions;\n var subscriber = exports.__subscriberRef.current;\n var returnValue;\n\n try {\n if (subscriber !== null) {\n subscriber.onInteractionTraced(interaction);\n }\n } finally {\n try {\n if (subscriber !== null) {\n subscriber.onWorkStarted(interactions, threadID);\n }\n } finally {\n try {\n returnValue = callback();\n } finally {\n exports.__interactionsRef.current = prevInteractions;\n\n try {\n if (subscriber !== null) {\n subscriber.onWorkStopped(interactions, threadID);\n }\n } finally {\n interaction.__count--; // If no async work was scheduled for this interaction,\n // Notify subscribers that it's completed.\n\n if (subscriber !== null && interaction.__count === 0) {\n subscriber.onInteractionScheduledWorkCompleted(interaction);\n }\n }\n }\n }\n }\n\n return returnValue;\n}\nfunction unstable_wrap(callback) {\n var threadID = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : DEFAULT_THREAD_ID;\n\n var wrappedInteractions = exports.__interactionsRef.current;\n var subscriber = exports.__subscriberRef.current;\n\n if (subscriber !== null) {\n subscriber.onWorkScheduled(wrappedInteractions, threadID);\n } // Update the pending async work count for the current interactions.\n // Update after calling subscribers in case of error.\n\n\n wrappedInteractions.forEach(function (interaction) {\n interaction.__count++;\n });\n var hasRun = false;\n\n function wrapped() {\n var prevInteractions = exports.__interactionsRef.current;\n exports.__interactionsRef.current = wrappedInteractions;\n subscriber = exports.__subscriberRef.current;\n\n try {\n var returnValue;\n\n try {\n if (subscriber !== null) {\n subscriber.onWorkStarted(wrappedInteractions, threadID);\n }\n } finally {\n try {\n returnValue = callback.apply(undefined, arguments);\n } finally {\n exports.__interactionsRef.current = prevInteractions;\n\n if (subscriber !== null) {\n subscriber.onWorkStopped(wrappedInteractions, threadID);\n }\n }\n }\n\n return returnValue;\n } finally {\n if (!hasRun) {\n // We only expect a wrapped function to be executed once,\n // But in the event that it's executed more than once–\n // Only decrement the outstanding interaction counts once.\n hasRun = true; // Update pending async counts for all wrapped interactions.\n // If this was the last scheduled async work for any of them,\n // Mark them as completed.\n\n wrappedInteractions.forEach(function (interaction) {\n interaction.__count--;\n\n if (subscriber !== null && interaction.__count === 0) {\n subscriber.onInteractionScheduledWorkCompleted(interaction);\n }\n });\n }\n }\n }\n\n wrapped.cancel = function cancel() {\n subscriber = exports.__subscriberRef.current;\n\n try {\n if (subscriber !== null) {\n subscriber.onWorkCanceled(wrappedInteractions, threadID);\n }\n } finally {\n // Update pending async counts for all wrapped interactions.\n // If this was the last scheduled async work for any of them,\n // Mark them as completed.\n wrappedInteractions.forEach(function (interaction) {\n interaction.__count--;\n\n if (subscriber && interaction.__count === 0) {\n subscriber.onInteractionScheduledWorkCompleted(interaction);\n }\n });\n }\n };\n\n return wrapped;\n}\n\nvar subscribers = null;\n\n{\n subscribers = new Set();\n}\n\nfunction unstable_subscribe(subscriber) {\n {\n subscribers.add(subscriber);\n\n if (subscribers.size === 1) {\n exports.__subscriberRef.current = {\n onInteractionScheduledWorkCompleted: onInteractionScheduledWorkCompleted,\n onInteractionTraced: onInteractionTraced,\n onWorkCanceled: onWorkCanceled,\n onWorkScheduled: onWorkScheduled,\n onWorkStarted: onWorkStarted,\n onWorkStopped: onWorkStopped\n };\n }\n }\n}\nfunction unstable_unsubscribe(subscriber) {\n {\n subscribers.delete(subscriber);\n\n if (subscribers.size === 0) {\n exports.__subscriberRef.current = null;\n }\n }\n}\n\nfunction onInteractionTraced(interaction) {\n var didCatchError = false;\n var caughtError = null;\n subscribers.forEach(function (subscriber) {\n try {\n subscriber.onInteractionTraced(interaction);\n } catch (error) {\n if (!didCatchError) {\n didCatchError = true;\n caughtError = error;\n }\n }\n });\n\n if (didCatchError) {\n throw caughtError;\n }\n}\n\nfunction onInteractionScheduledWorkCompleted(interaction) {\n var didCatchError = false;\n var caughtError = null;\n subscribers.forEach(function (subscriber) {\n try {\n subscriber.onInteractionScheduledWorkCompleted(interaction);\n } catch (error) {\n if (!didCatchError) {\n didCatchError = true;\n caughtError = error;\n }\n }\n });\n\n if (didCatchError) {\n throw caughtError;\n }\n}\n\nfunction onWorkScheduled(interactions, threadID) {\n var didCatchError = false;\n var caughtError = null;\n subscribers.forEach(function (subscriber) {\n try {\n subscriber.onWorkScheduled(interactions, threadID);\n } catch (error) {\n if (!didCatchError) {\n didCatchError = true;\n caughtError = error;\n }\n }\n });\n\n if (didCatchError) {\n throw caughtError;\n }\n}\n\nfunction onWorkStarted(interactions, threadID) {\n var didCatchError = false;\n var caughtError = null;\n subscribers.forEach(function (subscriber) {\n try {\n subscriber.onWorkStarted(interactions, threadID);\n } catch (error) {\n if (!didCatchError) {\n didCatchError = true;\n caughtError = error;\n }\n }\n });\n\n if (didCatchError) {\n throw caughtError;\n }\n}\n\nfunction onWorkStopped(interactions, threadID) {\n var didCatchError = false;\n var caughtError = null;\n subscribers.forEach(function (subscriber) {\n try {\n subscriber.onWorkStopped(interactions, threadID);\n } catch (error) {\n if (!didCatchError) {\n didCatchError = true;\n caughtError = error;\n }\n }\n });\n\n if (didCatchError) {\n throw caughtError;\n }\n}\n\nfunction onWorkCanceled(interactions, threadID) {\n var didCatchError = false;\n var caughtError = null;\n subscribers.forEach(function (subscriber) {\n try {\n subscriber.onWorkCanceled(interactions, threadID);\n } catch (error) {\n if (!didCatchError) {\n didCatchError = true;\n caughtError = error;\n }\n }\n });\n\n if (didCatchError) {\n throw caughtError;\n }\n}\n\nexports.unstable_clear = unstable_clear;\nexports.unstable_getCurrent = unstable_getCurrent;\nexports.unstable_getThreadID = unstable_getThreadID;\nexports.unstable_subscribe = unstable_subscribe;\nexports.unstable_trace = unstable_trace;\nexports.unstable_unsubscribe = unstable_unsubscribe;\nexports.unstable_wrap = unstable_wrap;\n })();\n}\n\n\n//# sourceURL=webpack:///./node_modules/scheduler/cjs/scheduler-tracing.development.js?");
/***/ }),
/***/ "./node_modules/scheduler/cjs/scheduler.development.js":
/*!*************************************************************!*\
!*** ./node_modules/scheduler/cjs/scheduler.development.js ***!
\*************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
eval("/** @license React v0.19.1\n * scheduler.development.js\n *\n * Copyright (c) Facebook, Inc. and its affiliates.\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\n\n\n\nif (true) {\n (function() {\n'use strict';\n\nvar enableSchedulerDebugging = false;\nvar enableProfiling = true;\n\nvar requestHostCallback;\nvar requestHostTimeout;\nvar cancelHostTimeout;\nvar shouldYieldToHost;\nvar requestPaint;\n\nif ( // If Scheduler runs in a non-DOM environment, it falls back to a naive\n// implementation using setTimeout.\ntypeof window === 'undefined' || // Check if MessageChannel is supported, too.\ntypeof MessageChannel !== 'function') {\n // If this accidentally gets imported in a non-browser environment, e.g. JavaScriptCore,\n // fallback to a naive implementation.\n var _callback = null;\n var _timeoutID = null;\n\n var _flushCallback = function () {\n if (_callback !== null) {\n try {\n var currentTime = exports.unstable_now();\n var hasRemainingTime = true;\n\n _callback(hasRemainingTime, currentTime);\n\n _callback = null;\n } catch (e) {\n setTimeout(_flushCallback, 0);\n throw e;\n }\n }\n };\n\n var initialTime = Date.now();\n\n exports.unstable_now = function () {\n return Date.now() - initialTime;\n };\n\n requestHostCallback = function (cb) {\n if (_callback !== null) {\n // Protect against re-entrancy.\n setTimeout(requestHostCallback, 0, cb);\n } else {\n _callback = cb;\n setTimeout(_flushCallback, 0);\n }\n };\n\n requestHostTimeout = function (cb, ms) {\n _timeoutID = setTimeout(cb, ms);\n };\n\n cancelHostTimeout = function () {\n clearTimeout(_timeoutID);\n };\n\n shouldYieldToHost = function () {\n return false;\n };\n\n requestPaint = exports.unstable_forceFrameRate = function () {};\n} else {\n // Capture local references to native APIs, in case a polyfill overrides them.\n var performance = window.performance;\n var _Date = window.Date;\n var _setTimeout = window.setTimeout;\n var _clearTimeout = window.clearTimeout;\n\n if (typeof console !== 'undefined') {\n // TODO: Scheduler no longer requires these methods to be polyfilled. But\n // maybe we want to continue warning if they don't exist, to preserve the\n // option to rely on it in the future?\n var requestAnimationFrame = window.requestAnimationFrame;\n var cancelAnimationFrame = window.cancelAnimationFrame; // TODO: Remove fb.me link\n\n if (typeof requestAnimationFrame !== 'function') {\n // Using console['error'] to evade Babel and ESLint\n console['error'](\"This browser doesn't support requestAnimationFrame. \" + 'Make sure that you load a ' + 'polyfill in older browsers. https://fb.me/react-polyfills');\n }\n\n if (typeof cancelAnimationFrame !== 'function') {\n // Using console['error'] to evade Babel and ESLint\n console['error'](\"This browser doesn't support cancelAnimationFrame. \" + 'Make sure that you load a ' + 'polyfill in older browsers. https://fb.me/react-polyfills');\n }\n }\n\n if (typeof performance === 'object' && typeof performance.now === 'function') {\n exports.unstable_now = function () {\n return performance.now();\n };\n } else {\n var _initialTime = _Date.now();\n\n exports.unstable_now = function () {\n return _Date.now() - _initialTime;\n };\n }\n\n var isMessageLoopRunning = false;\n var scheduledHostCallback = null;\n var taskTimeoutID = -1; // Scheduler periodically yields in case there is other work on the main\n // thread, like user events. By default, it yields multiple times per frame.\n // It does not attempt to align with frame boundaries, since most tasks don't\n // need to be frame aligned; for those that do, use requestAnimationFrame.\n\n var yieldInterval = 5;\n var deadline = 0; // TODO: Make this configurable\n\n {\n // `isInputPending` is not available. Since we have no way of knowing if\n // there's pending input, always yield at the end of the frame.\n shouldYieldToHost = function () {\n return exports.unstable_now() >= deadline;\n }; // Since we yield every frame regardless, `requestPaint` has no effect.\n\n\n requestPaint = function () {};\n }\n\n exports.unstable_forceFrameRate = function (fps) {\n if (fps < 0 || fps > 125) {\n // Using console['error'] to evade Babel and ESLint\n console['error']('forceFrameRate takes a positive int between 0 and 125, ' + 'forcing framerates higher than 125 fps is not unsupported');\n return;\n }\n\n if (fps > 0) {\n yieldInterval = Math.floor(1000 / fps);\n } else {\n // reset the framerate\n yieldInterval = 5;\n }\n };\n\n var performWorkUntilDeadline = function () {\n if (scheduledHostCallback !== null) {\n var currentTime = exports.unstable_now(); // Yield after `yieldInterval` ms, regardless of where we are in the vsync\n // cycle. This means there's always time remaining at the beginning of\n // the message event.\n\n deadline = currentTime + yieldInterval;\n var hasTimeRemaining = true;\n\n try {\n var hasMoreWork = scheduledHostCallback(hasTimeRemaining, currentTime);\n\n if (!hasMoreWork) {\n isMessageLoopRunning = false;\n scheduledHostCallback = null;\n } else {\n // If there's more work, schedule the next message event at the end\n // of the preceding one.\n port.postMessage(null);\n }\n } catch (error) {\n // If a scheduler task throws, exit the current browser task so the\n // error can be observed.\n port.postMessage(null);\n throw error;\n }\n } else {\n isMessageLoopRunning = false;\n } // Yielding to the browser will give it a chance to paint, so we can\n };\n\n var channel = new MessageChannel();\n var port = channel.port2;\n channel.port1.onmessage = performWorkUntilDeadline;\n\n requestHostCallback = function (callback) {\n scheduledHostCallback = callback;\n\n if (!isMessageLoopRunning) {\n isMessageLoopRunning = true;\n port.postMessage(null);\n }\n };\n\n requestHostTimeout = function (callback, ms) {\n taskTimeoutID = _setTimeout(function () {\n callback(exports.unstable_now());\n }, ms);\n };\n\n cancelHostTimeout = function () {\n _clearTimeout(taskTimeoutID);\n\n taskTimeoutID = -1;\n };\n}\n\nfunction push(heap, node) {\n var index = heap.length;\n heap.push(node);\n siftUp(heap, node, index);\n}\nfunction peek(heap) {\n var first = heap[0];\n return first === undefined ? null : first;\n}\nfunction pop(heap) {\n var first = heap[0];\n\n if (first !== undefined) {\n var last = heap.pop();\n\n if (last !== first) {\n heap[0] = last;\n siftDown(heap, last, 0);\n }\n\n return first;\n } else {\n return null;\n }\n}\n\nfunction siftUp(heap, node, i) {\n var index = i;\n\n while (true) {\n var parentIndex = index - 1 >>> 1;\n var parent = heap[parentIndex];\n\n if (parent !== undefined && compare(parent, node) > 0) {\n // The parent is larger. Swap positions.\n heap[parentIndex] = node;\n heap[index] = parent;\n index = parentIndex;\n } else {\n // The parent is smaller. Exit.\n return;\n }\n }\n}\n\nfunction siftDown(heap, node, i) {\n var index = i;\n var length = heap.length;\n\n while (index < length) {\n var leftIndex = (index + 1) * 2 - 1;\n var left = heap[leftIndex];\n var rightIndex = leftIndex + 1;\n var right = heap[rightIndex]; // If the left or right node is smaller, swap with the smaller of those.\n\n if (left !== undefined && compare(left, node) < 0) {\n if (right !== undefined && compare(right, left) < 0) {\n heap[index] = right;\n heap[rightIndex] = node;\n index = rightIndex;\n } else {\n heap[index] = left;\n heap[leftIndex] = node;\n index = leftIndex;\n }\n } else if (right !== undefined && compare(right, node) < 0) {\n heap[index] = right;\n heap[rightIndex] = node;\n index = rightIndex;\n } else {\n // Neither child is smaller. Exit.\n return;\n }\n }\n}\n\nfunction compare(a, b) {\n // Compare sort index first, then task id.\n var diff = a.sortIndex - b.sortIndex;\n return diff !== 0 ? diff : a.id - b.id;\n}\n\n// TODO: Use symbols?\nvar NoPriority = 0;\nvar ImmediatePriority = 1;\nvar UserBlockingPriority = 2;\nvar NormalPriority = 3;\nvar LowPriority = 4;\nvar IdlePriority = 5;\n\nvar runIdCounter = 0;\nvar mainThreadIdCounter = 0;\nvar profilingStateSize = 4;\nvar sharedProfilingBuffer = // $FlowFixMe Flow doesn't know about SharedArrayBuffer\ntypeof SharedArrayBuffer === 'function' ? new SharedArrayBuffer(profilingStateSize * Int32Array.BYTES_PER_ELEMENT) : // $FlowFixMe Flow doesn't know about ArrayBuffer\ntypeof ArrayBuffer === 'function' ? new ArrayBuffer(profilingStateSize * Int32Array.BYTES_PER_ELEMENT) : null // Don't crash the init path on IE9\n;\nvar profilingState = sharedProfilingBuffer !== null ? new Int32Array(sharedProfilingBuffer) : []; // We can't read this but it helps save bytes for null checks\n\nvar PRIORITY = 0;\nvar CURRENT_TASK_ID = 1;\nvar CURRENT_RUN_ID = 2;\nvar QUEUE_SIZE = 3;\n\n{\n profilingState[PRIORITY] = NoPriority; // This is maintained with a counter, because the size of the priority queue\n // array might include canceled tasks.\n\n profilingState[QUEUE_SIZE] = 0;\n profilingState[CURRENT_TASK_ID] = 0;\n} // Bytes per element is 4\n\n\nvar INITIAL_EVENT_LOG_SIZE = 131072;\nvar MAX_EVENT_LOG_SIZE = 524288; // Equivalent to 2 megabytes\n\nvar eventLogSize = 0;\nvar eventLogBuffer = null;\nvar eventLog = null;\nvar eventLogIndex = 0;\nvar TaskStartEvent = 1;\nvar TaskCompleteEvent = 2;\nvar TaskErrorEvent = 3;\nvar TaskCancelEvent = 4;\nvar TaskRunEvent = 5;\nvar TaskYieldEvent = 6;\nvar SchedulerSuspendEvent = 7;\nvar SchedulerResumeEvent = 8;\n\nfunction logEvent(entries) {\n if (eventLog !== null) {\n var offset = eventLogIndex;\n eventLogIndex += entries.length;\n\n if (eventLogIndex + 1 > eventLogSize) {\n eventLogSize *= 2;\n\n if (eventLogSize > MAX_EVENT_LOG_SIZE) {\n // Using console['error'] to evade Babel and ESLint\n console['error'](\"Scheduler Profiling: Event log exceeded maximum size. Don't \" + 'forget to call `stopLoggingProfilingEvents()`.');\n stopLoggingProfilingEvents();\n return;\n }\n\n var newEventLog = new Int32Array(eventLogSize * 4);\n newEventLog.set(eventLog);\n eventLogBuffer = newEventLog.buffer;\n eventLog = newEventLog;\n }\n\n eventLog.set(entries, offset);\n }\n}\n\nfunction startLoggingProfilingEvents() {\n eventLogSize = INITIAL_EVENT_LOG_SIZE;\n eventLogBuffer = new ArrayBuffer(eventLogSize * 4);\n eventLog = new Int32Array(eventLogBuffer);\n eventLogIndex = 0;\n}\nfunction stopLoggingProfilingEvents() {\n var buffer = eventLogBuffer;\n eventLogSize = 0;\n eventLogBuffer = null;\n eventLog = null;\n eventLogIndex = 0;\n return buffer;\n}\nfunction markTaskStart(task, ms) {\n {\n profilingState[QUEUE_SIZE]++;\n\n if (eventLog !== null) {\n // performance.now returns a float, representing milliseconds. When the\n // event is logged, it's coerced to an int. Convert to microseconds to\n // maintain extra degrees of precision.\n logEvent([TaskStartEvent, ms * 1000, task.id, task.priorityLevel]);\n }\n }\n}\nfunction markTaskCompleted(task, ms) {\n {\n profilingState[PRIORITY] = NoPriority;\n profilingState[CURRENT_TASK_ID] = 0;\n profilingState[QUEUE_SIZE]--;\n\n if (eventLog !== null) {\n logEvent([TaskCompleteEvent, ms * 1000, task.id]);\n }\n }\n}\nfunction markTaskCanceled(task, ms) {\n {\n profilingState[QUEUE_SIZE]--;\n\n if (eventLog !== null) {\n logEvent([TaskCancelEvent, ms * 1000, task.id]);\n }\n }\n}\nfunction markTaskErrored(task, ms) {\n {\n profilingState[PRIORITY] = NoPriority;\n profilingState[CURRENT_TASK_ID] = 0;\n profilingState[QUEUE_SIZE]--;\n\n if (eventLog !== null) {\n logEvent([TaskErrorEvent, ms * 1000, task.id]);\n }\n }\n}\nfunction markTaskRun(task, ms) {\n {\n runIdCounter++;\n profilingState[PRIORITY] = task.priorityLevel;\n profilingState[CURRENT_TASK_ID] = task.id;\n profilingState[CURRENT_RUN_ID] = runIdCounter;\n\n if (eventLog !== null) {\n logEvent([TaskRunEvent, ms * 1000, task.id, runIdCounter]);\n }\n }\n}\nfunction markTaskYield(task, ms) {\n {\n profilingState[PRIORITY] = NoPriority;\n profilingState[CURRENT_TASK_ID] = 0;\n profilingState[CURRENT_RUN_ID] = 0;\n\n if (eventLog !== null) {\n logEvent([TaskYieldEvent, ms * 1000, task.id, runIdCounter]);\n }\n }\n}\nfunction markSchedulerSuspended(ms) {\n {\n mainThreadIdCounter++;\n\n if (eventLog !== null) {\n logEvent([SchedulerSuspendEvent, ms * 1000, mainThreadIdCounter]);\n }\n }\n}\nfunction markSchedulerUnsuspended(ms) {\n {\n if (eventLog !== null) {\n logEvent([SchedulerResumeEvent, ms * 1000, mainThreadIdCounter]);\n }\n }\n}\n\n/* eslint-disable no-var */\n// Math.pow(2, 30) - 1\n// 0b111111111111111111111111111111\n\nvar maxSigned31BitInt = 1073741823; // Times out immediately\n\nvar IMMEDIATE_PRIORITY_TIMEOUT = -1; // Eventually times out\n\nvar USER_BLOCKING_PRIORITY = 250;\nvar NORMAL_PRIORITY_TIMEOUT = 5000;\nvar LOW_PRIORITY_TIMEOUT = 10000; // Never times out\n\nvar IDLE_PRIORITY = maxSigned31BitInt; // Tasks are stored on a min heap\n\nvar taskQueue = [];\nvar timerQueue = []; // Incrementing id counter. Used to maintain insertion order.\n\nvar taskIdCounter = 1; // Pausing the scheduler is useful for debugging.\nvar currentTask = null;\nvar currentPriorityLevel = NormalPriority; // This is set while performing work, to prevent re-entrancy.\n\nvar isPerformingWork = false;\nvar isHostCallbackScheduled = false;\nvar isHostTimeoutScheduled = false;\n\nfunction advanceTimers(currentTime) {\n // Check for tasks that are no longer delayed and add them to the queue.\n var timer = peek(timerQueue);\n\n while (timer !== null) {\n if (timer.callback === null) {\n // Timer was cancelled.\n pop(timerQueue);\n } else if (timer.startTime <= currentTime) {\n // Timer fired. Transfer to the task queue.\n pop(timerQueue);\n timer.sortIndex = timer.expirationTime;\n push(taskQueue, timer);\n\n {\n markTaskStart(timer, currentTime);\n timer.isQueued = true;\n }\n } else {\n // Remaining timers are pending.\n return;\n }\n\n timer = peek(timerQueue);\n }\n}\n\nfunction handleTimeout(currentTime) {\n isHostTimeoutScheduled = false;\n advanceTimers(currentTime);\n\n if (!isHostCallbackScheduled) {\n if (peek(taskQueue) !== null) {\n isHostCallbackScheduled = true;\n requestHostCallback(flushWork);\n } else {\n var firstTimer = peek(timerQueue);\n\n if (firstTimer !== null) {\n requestHostTimeout(handleTimeout, firstTimer.startTime - currentTime);\n }\n }\n }\n}\n\nfunction flushWork(hasTimeRemaining, initialTime) {\n {\n markSchedulerUnsuspended(initialTime);\n } // We'll need a host callback the next time work is scheduled.\n\n\n isHostCallbackScheduled = false;\n\n if (isHostTimeoutScheduled) {\n // We scheduled a timeout but it's no longer needed. Cancel it.\n isHostTimeoutScheduled = false;\n cancelHostTimeout();\n }\n\n isPerformingWork = true;\n var previousPriorityLevel = currentPriorityLevel;\n\n try {\n if (enableProfiling) {\n try {\n return workLoop(hasTimeRemaining, initialTime);\n } catch (error) {\n if (currentTask !== null) {\n var currentTime = exports.unstable_now();\n markTaskErrored(currentTask, currentTime);\n currentTask.isQueued = false;\n }\n\n throw error;\n }\n } else {\n // No catch in prod codepath.\n return workLoop(hasTimeRemaining, initialTime);\n }\n } finally {\n currentTask = null;\n currentPriorityLevel = previousPriorityLevel;\n isPerformingWork = false;\n\n {\n var _currentTime = exports.unstable_now();\n\n markSchedulerSuspended(_currentTime);\n }\n }\n}\n\nfunction workLoop(hasTimeRemaining, initialTime) {\n var currentTime = initialTime;\n advanceTimers(currentTime);\n currentTask = peek(taskQueue);\n\n while (currentTask !== null && !(enableSchedulerDebugging )) {\n if (currentTask.expirationTime > currentTime && (!hasTimeRemaining || shouldYieldToHost())) {\n // This currentTask hasn't expired, and we've reached the deadline.\n break;\n }\n\n var callback = currentTask.callback;\n\n if (callback !== null) {\n currentTask.callback = null;\n currentPriorityLevel = currentTask.priorityLevel;\n var didUserCallbackTimeout = currentTask.expirationTime <= currentTime;\n markTaskRun(currentTask, currentTime);\n var continuationCallback = callback(didUserCallbackTimeout);\n currentTime = exports.unstable_now();\n\n if (typeof continuationCallback === 'function') {\n currentTask.callback = continuationCallback;\n markTaskYield(currentTask, currentTime);\n } else {\n {\n markTaskCompleted(currentTask, currentTime);\n currentTask.isQueued = false;\n }\n\n if (currentTask === peek(taskQueue)) {\n pop(taskQueue);\n }\n }\n\n advanceTimers(currentTime);\n } else {\n pop(taskQueue);\n }\n\n currentTask = peek(taskQueue);\n } // Return whether there's additional work\n\n\n if (currentTask !== null) {\n return true;\n } else {\n var firstTimer = peek(timerQueue);\n\n if (firstTimer !== null) {\n requestHostTimeout(handleTimeout, firstTimer.startTime - currentTime);\n }\n\n return false;\n }\n}\n\nfunction unstable_runWithPriority(priorityLevel, eventHandler) {\n switch (priorityLevel) {\n case ImmediatePriority:\n case UserBlockingPriority:\n case NormalPriority:\n case LowPriority:\n case IdlePriority:\n break;\n\n default:\n priorityLevel = NormalPriority;\n }\n\n var previousPriorityLevel = currentPriorityLevel;\n currentPriorityLevel = priorityLevel;\n\n try {\n return eventHandler();\n } finally {\n currentPriorityLevel = previousPriorityLevel;\n }\n}\n\nfunction unstable_next(eventHandler) {\n var priorityLevel;\n\n switch (currentPriorityLevel) {\n case ImmediatePriority:\n case UserBlockingPriority:\n case NormalPriority:\n // Shift down to normal priority\n priorityLevel = NormalPriority;\n break;\n\n default:\n // Anything lower than normal priority should remain at the current level.\n priorityLevel = currentPriorityLevel;\n break;\n }\n\n var previousPriorityLevel = currentPriorityLevel;\n currentPriorityLevel = priorityLevel;\n\n try {\n return eventHandler();\n } finally {\n currentPriorityLevel = previousPriorityLevel;\n }\n}\n\nfunction unstable_wrapCallback(callback) {\n var parentPriorityLevel = currentPriorityLevel;\n return function () {\n // This is a fork of runWithPriority, inlined for performance.\n var previousPriorityLevel = currentPriorityLevel;\n currentPriorityLevel = parentPriorityLevel;\n\n try {\n return callback.apply(this, arguments);\n } finally {\n currentPriorityLevel = previousPriorityLevel;\n }\n };\n}\n\nfunction timeoutForPriorityLevel(priorityLevel) {\n switch (priorityLevel) {\n case ImmediatePriority:\n return IMMEDIATE_PRIORITY_TIMEOUT;\n\n case UserBlockingPriority:\n return USER_BLOCKING_PRIORITY;\n\n case IdlePriority:\n return IDLE_PRIORITY;\n\n case LowPriority:\n return LOW_PRIORITY_TIMEOUT;\n\n case NormalPriority:\n default:\n return NORMAL_PRIORITY_TIMEOUT;\n }\n}\n\nfunction unstable_scheduleCallback(priorityLevel, callback, options) {\n var currentTime = exports.unstable_now();\n var startTime;\n var timeout;\n\n if (typeof options === 'object' && options !== null) {\n var delay = options.delay;\n\n if (typeof delay === 'number' && delay > 0) {\n startTime = currentTime + delay;\n } else {\n startTime = currentTime;\n }\n\n timeout = typeof options.timeout === 'number' ? options.timeout : timeoutForPriorityLevel(priorityLevel);\n } else {\n timeout = timeoutForPriorityLevel(priorityLevel);\n startTime = currentTime;\n }\n\n var expirationTime = startTime + timeout;\n var newTask = {\n id: taskIdCounter++,\n callback: callback,\n priorityLevel: priorityLevel,\n startTime: startTime,\n expirationTime: expirationTime,\n sortIndex: -1\n };\n\n {\n newTask.isQueued = false;\n }\n\n if (startTime > currentTime) {\n // This is a delayed task.\n newTask.sortIndex = startTime;\n push(timerQueue, newTask);\n\n if (peek(taskQueue) === null && newTask === peek(timerQueue)) {\n // All tasks are delayed, and this is the task with the earliest delay.\n if (isHostTimeoutScheduled) {\n // Cancel an existing timeout.\n cancelHostTimeout();\n } else {\n isHostTimeoutScheduled = true;\n } // Schedule a timeout.\n\n\n requestHostTimeout(handleTimeout, startTime - currentTime);\n }\n } else {\n newTask.sortIndex = expirationTime;\n push(taskQueue, newTask);\n\n {\n markTaskStart(newTask, currentTime);\n newTask.isQueued = true;\n } // Schedule a host callback, if needed. If we're already performing work,\n // wait until the next time we yield.\n\n\n if (!isHostCallbackScheduled && !isPerformingWork) {\n isHostCallbackScheduled = true;\n requestHostCallback(flushWork);\n }\n }\n\n return newTask;\n}\n\nfunction unstable_pauseExecution() {\n}\n\nfunction unstable_continueExecution() {\n\n if (!isHostCallbackScheduled && !isPerformingWork) {\n isHostCallbackScheduled = true;\n requestHostCallback(flushWork);\n }\n}\n\nfunction unstable_getFirstCallbackNode() {\n return peek(taskQueue);\n}\n\nfunction unstable_cancelCallback(task) {\n {\n if (task.isQueued) {\n var currentTime = exports.unstable_now();\n markTaskCanceled(task, currentTime);\n task.isQueued = false;\n }\n } // Null out the callback to indicate the task has been canceled. (Can't\n // remove from the queue because you can't remove arbitrary nodes from an\n // array based heap, only the first one.)\n\n\n task.callback = null;\n}\n\nfunction unstable_getCurrentPriorityLevel() {\n return currentPriorityLevel;\n}\n\nfunction unstable_shouldYield() {\n var currentTime = exports.unstable_now();\n advanceTimers(currentTime);\n var firstTask = peek(taskQueue);\n return firstTask !== currentTask && currentTask !== null && firstTask !== null && firstTask.callback !== null && firstTask.startTime <= currentTime && firstTask.expirationTime < currentTask.expirationTime || shouldYieldToHost();\n}\n\nvar unstable_requestPaint = requestPaint;\nvar unstable_Profiling = {\n startLoggingProfilingEvents: startLoggingProfilingEvents,\n stopLoggingProfilingEvents: stopLoggingProfilingEvents,\n sharedProfilingBuffer: sharedProfilingBuffer\n} ;\n\nexports.unstable_IdlePriority = IdlePriority;\nexports.unstable_ImmediatePriority = ImmediatePriority;\nexports.unstable_LowPriority = LowPriority;\nexports.unstable_NormalPriority = NormalPriority;\nexports.unstable_Profiling = unstable_Profiling;\nexports.unstable_UserBlockingPriority = UserBlockingPriority;\nexports.unstable_cancelCallback = unstable_cancelCallback;\nexports.unstable_continueExecution = unstable_continueExecution;\nexports.unstable_getCurrentPriorityLevel = unstable_getCurrentPriorityLevel;\nexports.unstable_getFirstCallbackNode = unstable_getFirstCallbackNode;\nexports.unstable_next = unstable_next;\nexports.unstable_pauseExecution = unstable_pauseExecution;\nexports.unstable_requestPaint = unstable_requestPaint;\nexports.unstable_runWithPriority = unstable_runWithPriority;\nexports.unstable_scheduleCallback = unstable_scheduleCallback;\nexports.unstable_shouldYield = unstable_shouldYield;\nexports.unstable_wrapCallback = unstable_wrapCallback;\n })();\n}\n\n\n//# sourceURL=webpack:///./node_modules/scheduler/cjs/scheduler.development.js?");
/***/ }),
/***/ "./node_modules/scheduler/index.js":
/*!*****************************************!*\
!*** ./node_modules/scheduler/index.js ***!
\*****************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
eval("\n\nif (false) {} else {\n module.exports = __webpack_require__(/*! ./cjs/scheduler.development.js */ \"./node_modules/scheduler/cjs/scheduler.development.js\");\n}\n\n\n//# sourceURL=webpack:///./node_modules/scheduler/index.js?");
/***/ }),
/***/ "./node_modules/scheduler/tracing.js":
/*!*******************************************!*\
!*** ./node_modules/scheduler/tracing.js ***!
\*******************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
eval("\n\nif (false) {} else {\n module.exports = __webpack_require__(/*! ./cjs/scheduler-tracing.development.js */ \"./node_modules/scheduler/cjs/scheduler-tracing.development.js\");\n}\n\n\n//# sourceURL=webpack:///./node_modules/scheduler/tracing.js?");
/***/ }),
/***/ "./node_modules/style-loader/dist/runtime/injectStylesIntoStyleTag.js":
/*!****************************************************************************!*\
!*** ./node_modules/style-loader/dist/runtime/injectStylesIntoStyleTag.js ***!
\****************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
eval("\n\nvar isOldIE = function isOldIE() {\n var memo;\n return function memorize() {\n if (typeof memo === 'undefined') {\n // Test for IE <= 9 as proposed by Browserhacks\n // @see http://browserhacks.com/#hack-e71d8692f65334173fee715c222cb805\n // Tests for existence of standard globals is to allow style-loader\n // to operate correctly into non-standard environments\n // @see https://github.com/webpack-contrib/style-loader/issues/177\n memo = Boolean(window && document && document.all && !window.atob);\n }\n\n return memo;\n };\n}();\n\nvar getTarget = function getTarget() {\n var memo = {};\n return function memorize(target) {\n if (typeof memo[target] === 'undefined') {\n var styleTarget = document.querySelector(target); // Special case to return head of iframe instead of iframe itself\n\n if (window.HTMLIFrameElement && styleTarget instanceof window.HTMLIFrameElement) {\n try {\n // This will throw an exception if access to iframe is blocked\n // due to cross-origin restrictions\n styleTarget = styleTarget.contentDocument.head;\n } catch (e) {\n // istanbul ignore next\n styleTarget = null;\n }\n }\n\n memo[target] = styleTarget;\n }\n\n return memo[target];\n };\n}();\n\nvar stylesInDom = [];\n\nfunction getIndexByIdentifier(identifier) {\n var result = -1;\n\n for (var i = 0; i < stylesInDom.length; i++) {\n if (stylesInDom[i].identifier === identifier) {\n result = i;\n break;\n }\n }\n\n return result;\n}\n\nfunction modulesToDom(list, options) {\n var idCountMap = {};\n var identifiers = [];\n\n for (var i = 0; i < list.length; i++) {\n var item = list[i];\n var id = options.base ? item[0] + options.base : item[0];\n var count = idCountMap[id] || 0;\n var identifier = \"\".concat(id, \" \").concat(count);\n idCountMap[id] = count + 1;\n var index = getIndexByIdentifier(identifier);\n var obj = {\n css: item[1],\n media: item[2],\n sourceMap: item[3]\n };\n\n if (index !== -1) {\n stylesInDom[index].references++;\n stylesInDom[index].updater(obj);\n } else {\n stylesInDom.push({\n identifier: identifier,\n updater: addStyle(obj, options),\n references: 1\n });\n }\n\n identifiers.push(identifier);\n }\n\n return identifiers;\n}\n\nfunction insertStyleElement(options) {\n var style = document.createElement('style');\n var attributes = options.attributes || {};\n\n if (typeof attributes.nonce === 'undefined') {\n var nonce = true ? __webpack_require__.nc : undefined;\n\n if (nonce) {\n attributes.nonce = nonce;\n }\n }\n\n Object.keys(attributes).forEach(function (key) {\n style.setAttribute(key, attributes[key]);\n });\n\n if (typeof options.insert === 'function') {\n options.insert(style);\n } else {\n var target = getTarget(options.insert || 'head');\n\n if (!target) {\n throw new Error(\"Couldn't find a style target. This probably means that the value for the 'insert' parameter is invalid.\");\n }\n\n target.appendChild(style);\n }\n\n return style;\n}\n\nfunction removeStyleElement(style) {\n // istanbul ignore if\n if (style.parentNode === null) {\n return false;\n }\n\n style.parentNode.removeChild(style);\n}\n/* istanbul ignore next */\n\n\nvar replaceText = function replaceText() {\n var textStore = [];\n return function replace(index, replacement) {\n textStore[index] = replacement;\n return textStore.filter(Boolean).join('\\n');\n };\n}();\n\nfunction applyToSingletonTag(style, index, remove, obj) {\n var css = remove ? '' : obj.media ? \"@media \".concat(obj.media, \" {\").concat(obj.css, \"}\") : obj.css; // For old IE\n\n /* istanbul ignore if */\n\n if (style.styleSheet) {\n style.styleSheet.cssText = replaceText(index, css);\n } else {\n var cssNode = document.createTextNode(css);\n var childNodes = style.childNodes;\n\n if (childNodes[index]) {\n style.removeChild(childNodes[index]);\n }\n\n if (childNodes.length) {\n style.insertBefore(cssNode, childNodes[index]);\n } else {\n style.appendChild(cssNode);\n }\n }\n}\n\nfunction applyToTag(style, options, obj) {\n var css = obj.css;\n var media = obj.media;\n var sourceMap = obj.sourceMap;\n\n if (media) {\n style.setAttribute('media', media);\n } else {\n style.removeAttribute('media');\n }\n\n if (sourceMap && btoa) {\n css += \"\\n/*# sourceMappingURL=data:application/json;base64,\".concat(btoa(unescape(encodeURIComponent(JSON.stringify(sourceMap)))), \" */\");\n } // For old IE\n\n /* istanbul ignore if */\n\n\n if (style.styleSheet) {\n style.styleSheet.cssText = css;\n } else {\n while (style.firstChild) {\n style.removeChild(style.firstChild);\n }\n\n style.appendChild(document.createTextNode(css));\n }\n}\n\nvar singleton = null;\nvar singletonCounter = 0;\n\nfunction addStyle(obj, options) {\n var style;\n var update;\n var remove;\n\n if (options.singleton) {\n var styleIndex = singletonCounter++;\n style = singleton || (singleton = insertStyleElement(options));\n update = applyToSingletonTag.bind(null, style, styleIndex, false);\n remove = applyToSingletonTag.bind(null, style, styleIndex, true);\n } else {\n style = insertStyleElement(options);\n update = applyToTag.bind(null, style, options);\n\n remove = function remove() {\n removeStyleElement(style);\n };\n }\n\n update(obj);\n return function updateStyle(newObj) {\n if (newObj) {\n if (newObj.css === obj.css && newObj.media === obj.media && newObj.sourceMap === obj.sourceMap) {\n return;\n }\n\n update(obj = newObj);\n } else {\n remove();\n }\n };\n}\n\nmodule.exports = function (list, options) {\n options = options || {}; // Force single-tag solution on IE6-9, which has a hard limit on the # of <style>\n // tags it will allow on a page\n\n if (!options.singleton && typeof options.singleton !== 'boolean') {\n options.singleton = isOldIE();\n }\n\n list = list || [];\n var lastIdentifiers = modulesToDom(list, options);\n return function update(newList) {\n newList = newList || [];\n\n if (Object.prototype.toString.call(newList) !== '[object Array]') {\n return;\n }\n\n for (var i = 0; i < lastIdentifiers.length; i++) {\n var identifier = lastIdentifiers[i];\n var index = getIndexByIdentifier(identifier);\n stylesInDom[index].references--;\n }\n\n var newLastIdentifiers = modulesToDom(newList, options);\n\n for (var _i = 0; _i < lastIdentifiers.length; _i++) {\n var _identifier = lastIdentifiers[_i];\n\n var _index = getIndexByIdentifier(_identifier);\n\n if (stylesInDom[_index].references === 0) {\n stylesInDom[_index].updater();\n\n stylesInDom.splice(_index, 1);\n }\n }\n\n lastIdentifiers = newLastIdentifiers;\n };\n};\n\n//# sourceURL=webpack:///./node_modules/style-loader/dist/runtime/injectStylesIntoStyleTag.js?");
/***/ }),
/***/ "./node_modules/tiny-invariant/dist/tiny-invariant.esm.js":
/*!****************************************************************!*\
!*** ./node_modules/tiny-invariant/dist/tiny-invariant.esm.js ***!
\****************************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
eval("__webpack_require__.r(__webpack_exports__);\nvar isProduction = \"development\" === 'production';\nvar prefix = 'Invariant failed';\nfunction invariant(condition, message) {\n if (condition) {\n return;\n }\n if (isProduction) {\n throw new Error(prefix);\n }\n throw new Error(prefix + \": \" + (message || ''));\n}\n\n/* harmony default export */ __webpack_exports__[\"default\"] = (invariant);\n\n\n//# sourceURL=webpack:///./node_modules/tiny-invariant/dist/tiny-invariant.esm.js?");
/***/ }),
/***/ "./node_modules/tiny-warning/dist/tiny-warning.esm.js":
/*!************************************************************!*\
!*** ./node_modules/tiny-warning/dist/tiny-warning.esm.js ***!
\************************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
eval("__webpack_require__.r(__webpack_exports__);\nvar isProduction = \"development\" === '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\n/* harmony default export */ __webpack_exports__[\"default\"] = (warning);\n\n\n//# sourceURL=webpack:///./node_modules/tiny-warning/dist/tiny-warning.esm.js?");
/***/ }),
/***/ "./node_modules/uuid/lib/bytesToUuid.js":
/*!**********************************************!*\
!*** ./node_modules/uuid/lib/bytesToUuid.js ***!
\**********************************************/
/*! no static exports found */
/***/ (function(module, exports) {
eval("/**\n * Convert array of 16 byte values to UUID string format of the form:\n * XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX\n */\nvar byteToHex = [];\nfor (var i = 0; i < 256; ++i) {\n byteToHex[i] = (i + 0x100).toString(16).substr(1);\n}\n\nfunction bytesToUuid(buf, offset) {\n var i = offset || 0;\n var bth = byteToHex;\n // join used to fix memory issue caused by concatenation: https://bugs.chromium.org/p/v8/issues/detail?id=3175#c4\n return ([\n bth[buf[i++]], bth[buf[i++]],\n bth[buf[i++]], bth[buf[i++]], '-',\n bth[buf[i++]], bth[buf[i++]], '-',\n bth[buf[i++]], bth[buf[i++]], '-',\n bth[buf[i++]], bth[buf[i++]], '-',\n bth[buf[i++]], bth[buf[i++]],\n bth[buf[i++]], bth[buf[i++]],\n bth[buf[i++]], bth[buf[i++]]\n ]).join('');\n}\n\nmodule.exports = bytesToUuid;\n\n\n//# sourceURL=webpack:///./node_modules/uuid/lib/bytesToUuid.js?");
/***/ }),
/***/ "./node_modules/uuid/lib/rng-browser.js":
/*!**********************************************!*\
!*** ./node_modules/uuid/lib/rng-browser.js ***!
\**********************************************/
/*! no static exports found */
/***/ (function(module, exports) {
eval("// Unique ID creation requires a high quality random # generator. In the\n// browser this is a little complicated due to unknown quality of Math.random()\n// and inconsistent support for the `crypto` API. We do the best we can via\n// feature-detection\n\n// getRandomValues needs to be invoked in a context where \"this\" is a Crypto\n// implementation. Also, find the complete implementation of crypto on IE11.\nvar getRandomValues = (typeof(crypto) != 'undefined' && crypto.getRandomValues && crypto.getRandomValues.bind(crypto)) ||\n (typeof(msCrypto) != 'undefined' && typeof window.msCrypto.getRandomValues == 'function' && msCrypto.getRandomValues.bind(msCrypto));\n\nif (getRandomValues) {\n // WHATWG crypto RNG - http://wiki.whatwg.org/wiki/Crypto\n var rnds8 = new Uint8Array(16); // eslint-disable-line no-undef\n\n module.exports = function whatwgRNG() {\n getRandomValues(rnds8);\n return rnds8;\n };\n} else {\n // Math.random()-based (RNG)\n //\n // If all else fails, use Math.random(). It's fast, but is of unspecified\n // quality.\n var rnds = new Array(16);\n\n module.exports = function mathRNG() {\n for (var i = 0, r; i < 16; i++) {\n if ((i & 0x03) === 0) r = Math.random() * 0x100000000;\n rnds[i] = r >>> ((i & 0x03) << 3) & 0xff;\n }\n\n return rnds;\n };\n}\n\n\n//# sourceURL=webpack:///./node_modules/uuid/lib/rng-browser.js?");
/***/ }),
/***/ "./node_modules/uuid/v4.js":
/*!*********************************!*\
!*** ./node_modules/uuid/v4.js ***!
\*********************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
eval("var rng = __webpack_require__(/*! ./lib/rng */ \"./node_modules/uuid/lib/rng-browser.js\");\nvar bytesToUuid = __webpack_require__(/*! ./lib/bytesToUuid */ \"./node_modules/uuid/lib/bytesToUuid.js\");\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\n\n//# sourceURL=webpack:///./node_modules/uuid/v4.js?");
/***/ }),
/***/ "./node_modules/validator/index.js":
/*!*****************************************!*\
!*** ./node_modules/validator/index.js ***!
\*****************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
eval("\n\nfunction _typeof(obj) { \"@babel/helpers - typeof\"; if (typeof Symbol === \"function\" && typeof Symbol.iterator === \"symbol\") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === \"function\" && obj.constructor === Symbol && obj !== Symbol.prototype ? \"symbol\" : typeof obj; }; } return _typeof(obj); }\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = void 0;\n\nvar _toDate = _interopRequireDefault(__webpack_require__(/*! ./lib/toDate */ \"./node_modules/validator/lib/toDate.js\"));\n\nvar _toFloat = _interopRequireDefault(__webpack_require__(/*! ./lib/toFloat */ \"./node_modules/validator/lib/toFloat.js\"));\n\nvar _toInt = _interopRequireDefault(__webpack_require__(/*! ./lib/toInt */ \"./node_modules/validator/lib/toInt.js\"));\n\nvar _toBoolean = _interopRequireDefault(__webpack_require__(/*! ./lib/toBoolean */ \"./node_modules/validator/lib/toBoolean.js\"));\n\nvar _equals = _interopRequireDefault(__webpack_require__(/*! ./lib/equals */ \"./node_modules/validator/lib/equals.js\"));\n\nvar _contains = _interopRequireDefault(__webpack_require__(/*! ./lib/contains */ \"./node_modules/validator/lib/contains.js\"));\n\nvar _matches = _interopRequireDefault(__webpack_require__(/*! ./lib/matches */ \"./node_modules/validator/lib/matches.js\"));\n\nvar _isEmail = _interopRequireDefault(__webpack_require__(/*! ./lib/isEmail */ \"./node_modules/validator/lib/isEmail.js\"));\n\nvar _isURL = _interopRequireDefault(__webpack_require__(/*! ./lib/isURL */ \"./node_modules/validator/lib/isURL.js\"));\n\nvar _isMACAddress = _interopRequireDefault(__webpack_require__(/*! ./lib/isMACAddress */ \"./node_modules/validator/lib/isMACAddress.js\"));\n\nvar _isIP = _interopRequireDefault(__webpack_require__(/*! ./lib/isIP */ \"./node_modules/validator/lib/isIP.js\"));\n\nvar _isIPRange = _interopRequireDefault(__webpack_require__(/*! ./lib/isIPRange */ \"./node_modules/validator/lib/isIPRange.js\"));\n\nvar _isFQDN = _interopRequireDefault(__webpack_require__(/*! ./lib/isFQDN */ \"./node_modules/validator/lib/isFQDN.js\"));\n\nvar _isBoolean = _interopRequireDefault(__webpack_require__(/*! ./lib/isBoolean */ \"./node_modules/validator/lib/isBoolean.js\"));\n\nvar _isLocale = _interopRequireDefault(__webpack_require__(/*! ./lib/isLocale */ \"./node_modules/validator/lib/isLocale.js\"));\n\nvar _isAlpha = _interopRequireWildcard(__webpack_require__(/*! ./lib/isAlpha */ \"./node_modules/validator/lib/isAlpha.js\"));\n\nvar _isAlphanumeric = _interopRequireWildcard(__webpack_require__(/*! ./lib/isAlphanumeric */ \"./node_modules/validator/lib/isAlphanumeric.js\"));\n\nvar _isNumeric = _interopRequireDefault(__webpack_require__(/*! ./lib/isNumeric */ \"./node_modules/validator/lib/isNumeric.js\"));\n\nvar _isPassportNumber = _interopRequireDefault(__webpack_require__(/*! ./lib/isPassportNumber */ \"./node_modules/validator/lib/isPassportNumber.js\"));\n\nvar _isPort = _interopRequireDefault(__webpack_require__(/*! ./lib/isPort */ \"./node_modules/validator/lib/isPort.js\"));\n\nvar _isLowercase = _interopRequireDefault(__webpack_require__(/*! ./lib/isLowercase */ \"./node_modules/validator/lib/isLowercase.js\"));\n\nvar _isUppercase = _interopRequireDefault(__webpack_require__(/*! ./lib/isUppercase */ \"./node_modules/validator/lib/isUppercase.js\"));\n\nvar _isAscii = _interopRequireDefault(__webpack_require__(/*! ./lib/isAscii */ \"./node_modules/validator/lib/isAscii.js\"));\n\nvar _isFullWidth = _interopRequireDefault(__webpack_require__(/*! ./lib/isFullWidth */ \"./node_modules/validator/lib/isFullWidth.js\"));\n\nvar _isHalfWidth = _interopRequireDefault(__webpack_require__(/*! ./lib/isHalfWidth */ \"./node_modules/validator/lib/isHalfWidth.js\"));\n\nvar _isVariableWidth = _interopRequireDefault(__webpack_require__(/*! ./lib/isVariableWidth */ \"./node_modules/validator/lib/isVariableWidth.js\"));\n\nvar _isMultibyte = _interopRequireDefault(__webpack_require__(/*! ./lib/isMultibyte */ \"./node_modules/validator/lib/isMultibyte.js\"));\n\nvar _isSemVer = _interopRequireDefault(__webpack_require__(/*! ./lib/isSemVer */ \"./node_modules/validator/lib/isSemVer.js\"));\n\nvar _isSurrogatePair = _interopRequireDefault(__webpack_require__(/*! ./lib/isSurrogatePair */ \"./node_modules/validator/lib/isSurrogatePair.js\"));\n\nvar _isInt = _interopRequireDefault(__webpack_require__(/*! ./lib/isInt */ \"./node_modules/validator/lib/isInt.js\"));\n\nvar _isFloat = _interopRequireWildcard(__webpack_require__(/*! ./lib/isFloat */ \"./node_modules/validator/lib/isFloat.js\"));\n\nvar _isDecimal = _interopRequireDefault(__webpack_require__(/*! ./lib/isDecimal */ \"./node_modules/validator/lib/isDecimal.js\"));\n\nvar _isHexadecimal = _interopRequireDefault(__webpack_require__(/*! ./lib/isHexadecimal */ \"./node_modules/validator/lib/isHexadecimal.js\"));\n\nvar _isOctal = _interopRequireDefault(__webpack_require__(/*! ./lib/isOctal */ \"./node_modules/validator/lib/isOctal.js\"));\n\nvar _isDivisibleBy = _interopRequireDefault(__webpack_require__(/*! ./lib/isDivisibleBy */ \"./node_modules/validator/lib/isDivisibleBy.js\"));\n\nvar _isHexColor = _interopRequireDefault(__webpack_require__(/*! ./lib/isHexColor */ \"./node_modules/validator/lib/isHexColor.js\"));\n\nvar _isRgbColor = _interopRequireDefault(__webpack_require__(/*! ./lib/isRgbColor */ \"./node_modules/validator/lib/isRgbColor.js\"));\n\nvar _isHSL = _interopRequireDefault(__webpack_require__(/*! ./lib/isHSL */ \"./node_modules/validator/lib/isHSL.js\"));\n\nvar _isISRC = _interopRequireDefault(__webpack_require__(/*! ./lib/isISRC */ \"./node_modules/validator/lib/isISRC.js\"));\n\nvar _isIBAN = _interopRequireDefault(__webpack_require__(/*! ./lib/isIBAN */ \"./node_modules/validator/lib/isIBAN.js\"));\n\nvar _isBIC = _interopRequireDefault(__webpack_require__(/*! ./lib/isBIC */ \"./node_modules/validator/lib/isBIC.js\"));\n\nvar _isMD = _interopRequireDefault(__webpack_require__(/*! ./lib/isMD5 */ \"./node_modules/validator/lib/isMD5.js\"));\n\nvar _isHash = _interopRequireDefault(__webpack_require__(/*! ./lib/isHash */ \"./node_modules/validator/lib/isHash.js\"));\n\nvar _isJWT = _interopRequireDefault(__webpack_require__(/*! ./lib/isJWT */ \"./node_modules/validator/lib/isJWT.js\"));\n\nvar _isJSON = _interopRequireDefault(__webpack_require__(/*! ./lib/isJSON */ \"./node_modules/validator/lib/isJSON.js\"));\n\nvar _isEmpty = _interopRequireDefault(__webpack_require__(/*! ./lib/isEmpty */ \"./node_modules/validator/lib/isEmpty.js\"));\n\nvar _isLength = _interopRequireDefault(__webpack_require__(/*! ./lib/isLength */ \"./node_modules/validator/lib/isLength.js\"));\n\nvar _isByteLength = _interopRequireDefault(__webpack_require__(/*! ./lib/isByteLength */ \"./node_modules/validator/lib/isByteLength.js\"));\n\nvar _isUUID = _interopRequireDefault(__webpack_require__(/*! ./lib/isUUID */ \"./node_modules/validator/lib/isUUID.js\"));\n\nvar _isMongoId = _interopRequireDefault(__webpack_require__(/*! ./lib/isMongoId */ \"./node_modules/validator/lib/isMongoId.js\"));\n\nvar _isAfter = _interopRequireDefault(__webpack_require__(/*! ./lib/isAfter */ \"./node_modules/validator/lib/isAfter.js\"));\n\nvar _isBefore = _interopRequireDefault(__webpack_require__(/*! ./lib/isBefore */ \"./node_modules/validator/lib/isBefore.js\"));\n\nvar _isIn = _interopRequireDefault(__webpack_require__(/*! ./lib/isIn */ \"./node_modules/validator/lib/isIn.js\"));\n\nvar _isCreditCard = _interopRequireDefault(__webpack_require__(/*! ./lib/isCreditCard */ \"./node_modules/validator/lib/isCreditCard.js\"));\n\nvar _isIdentityCard = _interopRequireDefault(__webpack_require__(/*! ./lib/isIdentityCard */ \"./node_modules/validator/lib/isIdentityCard.js\"));\n\nvar _isEAN = _interopRequireDefault(__webpack_require__(/*! ./lib/isEAN */ \"./node_modules/validator/lib/isEAN.js\"));\n\nvar _isISIN = _interopRequireDefault(__webpack_require__(/*! ./lib/isISIN */ \"./node_modules/validator/lib/isISIN.js\"));\n\nvar _isISBN = _interopRequireDefault(__webpack_require__(/*! ./lib/isISBN */ \"./node_modules/validator/lib/isISBN.js\"));\n\nvar _isISSN = _interopRequireDefault(__webpack_require__(/*! ./lib/isISSN */ \"./node_modules/validator/lib/isISSN.js\"));\n\nvar _isMobilePhone = _interopRequireWildcard(__webpack_require__(/*! ./lib/isMobilePhone */ \"./node_modules/validator/lib/isMobilePhone.js\"));\n\nvar _isEthereumAddress = _interopRequireDefault(__webpack_require__(/*! ./lib/isEthereumAddress */ \"./node_modules/validator/lib/isEthereumAddress.js\"));\n\nvar _isCurrency = _interopRequireDefault(__webpack_require__(/*! ./lib/isCurrency */ \"./node_modules/validator/lib/isCurrency.js\"));\n\nvar _isBtcAddress = _interopRequireDefault(__webpack_require__(/*! ./lib/isBtcAddress */ \"./node_modules/validator/lib/isBtcAddress.js\"));\n\nvar _isISO = _interopRequireDefault(__webpack_require__(/*! ./lib/isISO8601 */ \"./node_modules/validator/lib/isISO8601.js\"));\n\nvar _isRFC = _interopRequireDefault(__webpack_require__(/*! ./lib/isRFC3339 */ \"./node_modules/validator/lib/isRFC3339.js\"));\n\nvar _isISO31661Alpha = _interopRequireDefault(__webpack_require__(/*! ./lib/isISO31661Alpha2 */ \"./node_modules/validator/lib/isISO31661Alpha2.js\"));\n\nvar _isISO31661Alpha2 = _interopRequireDefault(__webpack_require__(/*! ./lib/isISO31661Alpha3 */ \"./node_modules/validator/lib/isISO31661Alpha3.js\"));\n\nvar _isBase = _interopRequireDefault(__webpack_require__(/*! ./lib/isBase32 */ \"./node_modules/validator/lib/isBase32.js\"));\n\nvar _isBase2 = _interopRequireDefault(__webpack_require__(/*! ./lib/isBase64 */ \"./node_modules/validator/lib/isBase64.js\"));\n\nvar _isDataURI = _interopRequireDefault(__webpack_require__(/*! ./lib/isDataURI */ \"./node_modules/validator/lib/isDataURI.js\"));\n\nvar _isMagnetURI = _interopRequireDefault(__webpack_require__(/*! ./lib/isMagnetURI */ \"./node_modules/validator/lib/isMagnetURI.js\"));\n\nvar _isMimeType = _interopRequireDefault(__webpack_require__(/*! ./lib/isMimeType */ \"./node_modules/validator/lib/isMimeType.js\"));\n\nvar _isLatLong = _interopRequireDefault(__webpack_require__(/*! ./lib/isLatLong */ \"./node_modules/validator/lib/isLatLong.js\"));\n\nvar _isPostalCode = _interopRequireWildcard(__webpack_require__(/*! ./lib/isPostalCode */ \"./node_modules/validator/lib/isPostalCode.js\"));\n\nvar _ltrim = _interopRequireDefault(__webpack_require__(/*! ./lib/ltrim */ \"./node_modules/validator/lib/ltrim.js\"));\n\nvar _rtrim = _interopRequireDefault(__webpack_require__(/*! ./lib/rtrim */ \"./node_modules/validator/lib/rtrim.js\"));\n\nvar _trim = _interopRequireDefault(__webpack_require__(/*! ./lib/trim */ \"./node_modules/validator/lib/trim.js\"));\n\nvar _escape = _interopRequireDefault(__webpack_require__(/*! ./lib/escape */ \"./node_modules/validator/lib/escape.js\"));\n\nvar _unescape = _interopRequireDefault(__webpack_require__(/*! ./lib/unescape */ \"./node_modules/validator/lib/unescape.js\"));\n\nvar _stripLow = _interopRequireDefault(__webpack_require__(/*! ./lib/stripLow */ \"./node_modules/validator/lib/stripLow.js\"));\n\nvar _whitelist = _interopRequireDefault(__webpack_require__(/*! ./lib/whitelist */ \"./node_modules/validator/lib/whitelist.js\"));\n\nvar _blacklist = _interopRequireDefault(__webpack_require__(/*! ./lib/blacklist */ \"./node_modules/validator/lib/blacklist.js\"));\n\nvar _isWhitelisted = _interopRequireDefault(__webpack_require__(/*! ./lib/isWhitelisted */ \"./node_modules/validator/lib/isWhitelisted.js\"));\n\nvar _normalizeEmail = _interopRequireDefault(__webpack_require__(/*! ./lib/normalizeEmail */ \"./node_modules/validator/lib/normalizeEmail.js\"));\n\nvar _isSlug = _interopRequireDefault(__webpack_require__(/*! ./lib/isSlug */ \"./node_modules/validator/lib/isSlug.js\"));\n\nfunction _getRequireWildcardCache() { if (typeof WeakMap !== \"function\") return null; var cache = new WeakMap(); _getRequireWildcardCache = function _getRequireWildcardCache() { return cache; }; return cache; }\n\nfunction _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || _typeof(obj) !== \"object\" && typeof obj !== \"function\") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\nvar version = '13.0.0';\nvar validator = {\n version: version,\n toDate: _toDate.default,\n toFloat: _toFloat.default,\n toInt: _toInt.default,\n toBoolean: _toBoolean.default,\n equals: _equals.default,\n contains: _contains.default,\n matches: _matches.default,\n isEmail: _isEmail.default,\n isURL: _isURL.default,\n isMACAddress: _isMACAddress.default,\n isIP: _isIP.default,\n isIPRange: _isIPRange.default,\n isFQDN: _isFQDN.default,\n isBoolean: _isBoolean.default,\n isIBAN: _isIBAN.default,\n isBIC: _isBIC.default,\n isAlpha: _isAlpha.default,\n isAlphaLocales: _isAlpha.locales,\n isAlphanumeric: _isAlphanumeric.default,\n isAlphanumericLocales: _isAlphanumeric.locales,\n isNumeric: _isNumeric.default,\n isPassportNumber: _isPassportNumber.default,\n isPort: _isPort.default,\n isLowercase: _isLowercase.default,\n isUppercase: _isUppercase.default,\n isAscii: _isAscii.default,\n isFullWidth: _isFullWidth.default,\n isHalfWidth: _isHalfWidth.default,\n isVariableWidth: _isVariableWidth.default,\n isMultibyte: _isMultibyte.default,\n isSemVer: _isSemVer.default,\n isSurrogatePair: _isSurrogatePair.default,\n isInt: _isInt.default,\n isFloat: _isFloat.default,\n isFloatLocales: _isFloat.locales,\n isDecimal: _isDecimal.default,\n isHexadecimal: _isHexadecimal.default,\n isOctal: _isOctal.default,\n isDivisibleBy: _isDivisibleBy.default,\n isHexColor: _isHexColor.default,\n isRgbColor: _isRgbColor.default,\n isHSL: _isHSL.default,\n isISRC: _isISRC.default,\n isMD5: _isMD.default,\n isHash: _isHash.default,\n isJWT: _isJWT.default,\n isJSON: _isJSON.default,\n isEmpty: _isEmpty.default,\n isLength: _isLength.default,\n isLocale: _isLocale.default,\n isByteLength: _isByteLength.default,\n isUUID: _isUUID.default,\n isMongoId: _isMongoId.default,\n isAfter: _isAfter.default,\n isBefore: _isBefore.default,\n isIn: _isIn.default,\n isCreditCard: _isCreditCard.default,\n isIdentityCard: _isIdentityCard.default,\n isEAN: _isEAN.default,\n isISIN: _isISIN.default,\n isISBN: _isISBN.default,\n isISSN: _isISSN.default,\n isMobilePhone: _isMobilePhone.default,\n isMobilePhoneLocales: _isMobilePhone.locales,\n isPostalCode: _isPostalCode.default,\n isPostalCodeLocales: _isPostalCode.locales,\n isEthereumAddress: _isEthereumAddress.default,\n isCurrency: _isCurrency.default,\n isBtcAddress: _isBtcAddress.default,\n isISO8601: _isISO.default,\n isRFC3339: _isRFC.default,\n isISO31661Alpha2: _isISO31661Alpha.default,\n isISO31661Alpha3: _isISO31661Alpha2.default,\n isBase32: _isBase.default,\n isBase64: _isBase2.default,\n isDataURI: _isDataURI.default,\n isMagnetURI: _isMagnetURI.default,\n isMimeType: _isMimeType.default,\n isLatLong: _isLatLong.default,\n ltrim: _ltrim.default,\n rtrim: _rtrim.default,\n trim: _trim.default,\n escape: _escape.default,\n unescape: _unescape.default,\n stripLow: _stripLow.default,\n whitelist: _whitelist.default,\n blacklist: _blacklist.default,\n isWhitelisted: _isWhitelisted.default,\n normalizeEmail: _normalizeEmail.default,\n toString: toString,\n isSlug: _isSlug.default\n};\nvar _default = validator;\nexports.default = _default;\nmodule.exports = exports.default;\nmodule.exports.default = exports.default;\n\n//# sourceURL=webpack:///./node_modules/validator/index.js?");
/***/ }),
/***/ "./node_modules/validator/lib/alpha.js":
/*!*********************************************!*\
!*** ./node_modules/validator/lib/alpha.js ***!
\*********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
eval("\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.commaDecimal = exports.dotDecimal = exports.arabicLocales = exports.englishLocales = exports.decimal = exports.alphanumeric = exports.alpha = void 0;\nvar alpha = {\n 'en-US': /^[A-Z]+$/i,\n 'bg-BG': /^[А-Я]+$/i,\n 'cs-CZ': /^[A-ZÁČĎÉĚÍŇÓŘŠŤÚŮÝŽ]+$/i,\n 'da-DK': /^[A-ZÆØÅ]+$/i,\n 'de-DE': /^[A-ZÄÖÜß]+$/i,\n 'el-GR': /^[Α-ώ]+$/i,\n 'es-ES': /^[A-ZÁÉÍÑÓÚÜ]+$/i,\n 'fr-FR': /^[A-ZÀÂÆÇÉÈÊËÏÎÔŒÙÛÜŸ]+$/i,\n 'it-IT': /^[A-ZÀÉÈÌÎÓÒÙ]+$/i,\n 'nb-NO': /^[A-ZÆØÅ]+$/i,\n 'nl-NL': /^[A-ZÁÉËÏÓÖÜÚ]+$/i,\n 'nn-NO': /^[A-ZÆØÅ]+$/i,\n 'hu-HU': /^[A-ZÁÉÍÓÖŐÚÜŰ]+$/i,\n 'pl-PL': /^[A-ZĄĆĘŚŁŃÓŻŹ]+$/i,\n 'pt-PT': /^[A-ZÃÁÀÂÄÇÉÊËÍÏÕÓÔÖÚÜ]+$/i,\n 'ru-RU': /^[А-ЯЁ]+$/i,\n 'sl-SI': /^[A-ZČĆĐŠŽ]+$/i,\n 'sk-SK': /^[A-ZÁČĎÉÍŇÓŠŤÚÝŽĹŔĽÄÔ]+$/i,\n 'sr-RS@latin': /^[A-ZČĆŽŠĐ]+$/i,\n 'sr-RS': /^[А-ЯЂЈЉЊЋЏ]+$/i,\n 'sv-SE': /^[A-ZÅÄÖ]+$/i,\n 'tr-TR': /^[A-ZÇĞİıÖŞÜ]+$/i,\n 'uk-UA': /^[А-ЩЬЮЯЄIЇҐі]+$/i,\n 'ku-IQ': /^[ئابپتجچحخدرڕزژسشعغفڤقکگلڵمنوۆھەیێيطؤثآإأكضصةظذ]+$/i,\n ar: /^[ءآأؤإئابةتثجحخدذرزسشصضطظعغفقكلمنهوىيًٌٍَُِّْٰ]+$/,\n he: /^[א-ת]+$/,\n 'fa-IR': /^['آابپتثجچهخدذرزژسشصضطظعغفقکگلمنوهی']+$/i\n};\nexports.alpha = alpha;\nvar alphanumeric = {\n 'en-US': /^[0-9A-Z]+$/i,\n 'bg-BG': /^[0-9А-Я]+$/i,\n 'cs-CZ': /^[0-9A-ZÁČĎÉĚÍŇÓŘŠŤÚŮÝŽ]+$/i,\n 'da-DK': /^[0-9A-ZÆØÅ]+$/i,\n 'de-DE': /^[0-9A-ZÄÖÜß]+$/i,\n 'el-GR': /^[0-9Α-ω]+$/i,\n 'es-ES': /^[0-9A-ZÁÉÍÑÓÚÜ]+$/i,\n 'fr-FR': /^[0-9A-ZÀÂÆÇÉÈÊËÏÎÔŒÙÛÜŸ]+$/i,\n 'it-IT': /^[0-9A-ZÀÉÈÌÎÓÒÙ]+$/i,\n 'hu-HU': /^[0-9A-ZÁÉÍÓÖŐÚÜŰ]+$/i,\n 'nb-NO': /^[0-9A-ZÆØÅ]+$/i,\n 'nl-NL': /^[0-9A-ZÁÉËÏÓÖÜÚ]+$/i,\n 'nn-NO': /^[0-9A-ZÆØÅ]+$/i,\n 'pl-PL': /^[0-9A-ZĄĆĘŚŁŃÓŻŹ]+$/i,\n 'pt-PT': /^[0-9A-ZÃÁÀÂÄÇÉÊËÍÏÕÓÔÖÚÜ]+$/i,\n 'ru-RU': /^[0-9А-ЯЁ]+$/i,\n 'sl-SI': /^[0-9A-ZČĆĐŠŽ]+$/i,\n 'sk-SK': /^[0-9A-ZÁČĎÉÍŇÓŠŤÚÝŽĹŔĽÄÔ]+$/i,\n 'sr-RS@latin': /^[0-9A-ZČĆŽŠĐ]+$/i,\n 'sr-RS': /^[0-9А-ЯЂЈЉЊЋЏ]+$/i,\n 'sv-SE': /^[0-9A-ZÅÄÖ]+$/i,\n 'tr-TR': /^[0-9A-ZÇĞİıÖŞÜ]+$/i,\n 'uk-UA': /^[0-9А-ЩЬЮЯЄIЇҐі]+$/i,\n 'ku-IQ': /^[٠١٢٣٤٥٦٧٨٩0-9ئابپتجچحخدرڕزژسشعغفڤقکگلڵمنوۆھەیێيطؤثآإأكضصةظذ]+$/i,\n ar: /^[٠١٢٣٤٥٦٧٨٩0-9ءآأؤإئابةتثجحخدذرزسشصضطظعغفقكلمنهوىيًٌٍَُِّْٰ]+$/,\n he: /^[0-9א-ת]+$/,\n 'fa-IR': /^['0-9آابپتثجچهخدذرزژسشصضطظعغفقکگلمنوهی۱۲۳۴۵۶۷۸۹۰']+$/i\n};\nexports.alphanumeric = alphanumeric;\nvar decimal = {\n 'en-US': '.',\n ar: '٫'\n};\nexports.decimal = decimal;\nvar englishLocales = ['AU', 'GB', 'HK', 'IN', 'NZ', 'ZA', 'ZM'];\nexports.englishLocales = englishLocales;\n\nfor (var locale, i = 0; i < englishLocales.length; i++) {\n locale = \"en-\".concat(englishLocales[i]);\n alpha[locale] = alpha['en-US'];\n alphanumeric[locale] = alphanumeric['en-US'];\n decimal[locale] = decimal['en-US'];\n} // Source: http://www.localeplanet.com/java/\n\n\nvar arabicLocales = ['AE', 'BH', 'DZ', 'EG', 'IQ', 'JO', 'KW', 'LB', 'LY', 'MA', 'QM', 'QA', 'SA', 'SD', 'SY', 'TN', 'YE'];\nexports.arabicLocales = arabicLocales;\n\nfor (var _locale, _i = 0; _i < arabicLocales.length; _i++) {\n _locale = \"ar-\".concat(arabicLocales[_i]);\n alpha[_locale] = alpha.ar;\n alphanumeric[_locale] = alphanumeric.ar;\n decimal[_locale] = decimal.ar;\n} // Source: https://en.wikipedia.org/wiki/Decimal_mark\n\n\nvar dotDecimal = ['ar-EG', 'ar-LB', 'ar-LY'];\nexports.dotDecimal = dotDecimal;\nvar commaDecimal = ['bg-BG', 'cs-CZ', 'da-DK', 'de-DE', 'el-GR', 'en-ZM', 'es-ES', 'fr-FR', 'it-IT', 'ku-IQ', 'hu-HU', 'nb-NO', 'nn-NO', 'nl-NL', 'pl-PL', 'pt-PT', 'ru-RU', 'sl-SI', 'sr-RS@latin', 'sr-RS', 'sv-SE', 'tr-TR', 'uk-UA'];\nexports.commaDecimal = commaDecimal;\n\nfor (var _i2 = 0; _i2 < dotDecimal.length; _i2++) {\n decimal[dotDecimal[_i2]] = decimal['en-US'];\n}\n\nfor (var _i3 = 0; _i3 < commaDecimal.length; _i3++) {\n decimal[commaDecimal[_i3]] = ',';\n}\n\nalpha['pt-BR'] = alpha['pt-PT'];\nalphanumeric['pt-BR'] = alphanumeric['pt-PT'];\ndecimal['pt-BR'] = decimal['pt-PT']; // see #862\n\nalpha['pl-Pl'] = alpha['pl-PL'];\nalphanumeric['pl-Pl'] = alphanumeric['pl-PL'];\ndecimal['pl-Pl'] = decimal['pl-PL'];\n\n//# sourceURL=webpack:///./node_modules/validator/lib/alpha.js?");
/***/ }),
/***/ "./node_modules/validator/lib/blacklist.js":
/*!*************************************************!*\
!*** ./node_modules/validator/lib/blacklist.js ***!
\*************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
eval("\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = blacklist;\n\nvar _assertString = _interopRequireDefault(__webpack_require__(/*! ./util/assertString */ \"./node_modules/validator/lib/util/assertString.js\"));\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\nfunction blacklist(str, chars) {\n (0, _assertString.default)(str);\n return str.replace(new RegExp(\"[\".concat(chars, \"]+\"), 'g'), '');\n}\n\nmodule.exports = exports.default;\nmodule.exports.default = exports.default;\n\n//# sourceURL=webpack:///./node_modules/validator/lib/blacklist.js?");
/***/ }),
/***/ "./node_modules/validator/lib/contains.js":
/*!************************************************!*\
!*** ./node_modules/validator/lib/contains.js ***!
\************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
eval("\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = contains;\n\nvar _assertString = _interopRequireDefault(__webpack_require__(/*! ./util/assertString */ \"./node_modules/validator/lib/util/assertString.js\"));\n\nvar _toString = _interopRequireDefault(__webpack_require__(/*! ./util/toString */ \"./node_modules/validator/lib/util/toString.js\"));\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\nfunction contains(str, elem) {\n (0, _assertString.default)(str);\n return str.indexOf((0, _toString.default)(elem)) >= 0;\n}\n\nmodule.exports = exports.default;\nmodule.exports.default = exports.default;\n\n//# sourceURL=webpack:///./node_modules/validator/lib/contains.js?");
/***/ }),
/***/ "./node_modules/validator/lib/equals.js":
/*!**********************************************!*\
!*** ./node_modules/validator/lib/equals.js ***!
\**********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
eval("\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = equals;\n\nvar _assertString = _interopRequireDefault(__webpack_require__(/*! ./util/assertString */ \"./node_modules/validator/lib/util/assertString.js\"));\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\nfunction equals(str, comparison) {\n (0, _assertString.default)(str);\n return str === comparison;\n}\n\nmodule.exports = exports.default;\nmodule.exports.default = exports.default;\n\n//# sourceURL=webpack:///./node_modules/validator/lib/equals.js?");
/***/ }),
/***/ "./node_modules/validator/lib/escape.js":
/*!**********************************************!*\
!*** ./node_modules/validator/lib/escape.js ***!
\**********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
eval("\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = escape;\n\nvar _assertString = _interopRequireDefault(__webpack_require__(/*! ./util/assertString */ \"./node_modules/validator/lib/util/assertString.js\"));\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\nfunction escape(str) {\n (0, _assertString.default)(str);\n return str.replace(/&/g, '&').replace(/\"/g, '"').replace(/'/g, ''').replace(/</g, '<').replace(/>/g, '>').replace(/\\//g, '/').replace(/\\\\/g, '\').replace(/`/g, '`');\n}\n\nmodule.exports = exports.default;\nmodule.exports.default = exports.default;\n\n//# sourceURL=webpack:///./node_modules/validator/lib/escape.js?");
/***/ }),
/***/ "./node_modules/validator/lib/isAfter.js":
/*!***********************************************!*\
!*** ./node_modules/validator/lib/isAfter.js ***!
\***********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
eval("\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = isAfter;\n\nvar _assertString = _interopRequireDefault(__webpack_require__(/*! ./util/assertString */ \"./node_modules/validator/lib/util/assertString.js\"));\n\nvar _toDate = _interopRequireDefault(__webpack_require__(/*! ./toDate */ \"./node_modules/validator/lib/toDate.js\"));\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\nfunction isAfter(str) {\n var date = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : String(new Date());\n (0, _assertString.default)(str);\n var comparison = (0, _toDate.default)(date);\n var original = (0, _toDate.default)(str);\n return !!(original && comparison && original > comparison);\n}\n\nmodule.exports = exports.default;\nmodule.exports.default = exports.default;\n\n//# sourceURL=webpack:///./node_modules/validator/lib/isAfter.js?");
/***/ }),
/***/ "./node_modules/validator/lib/isAlpha.js":
/*!***********************************************!*\
!*** ./node_modules/validator/lib/isAlpha.js ***!
\***********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
eval("\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = isAlpha;\nexports.locales = void 0;\n\nvar _assertString = _interopRequireDefault(__webpack_require__(/*! ./util/assertString */ \"./node_modules/validator/lib/util/assertString.js\"));\n\nvar _alpha = __webpack_require__(/*! ./alpha */ \"./node_modules/validator/lib/alpha.js\");\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\nfunction isAlpha(str) {\n var locale = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'en-US';\n (0, _assertString.default)(str);\n\n if (locale in _alpha.alpha) {\n return _alpha.alpha[locale].test(str);\n }\n\n throw new Error(\"Invalid locale '\".concat(locale, \"'\"));\n}\n\nvar locales = Object.keys(_alpha.alpha);\nexports.locales = locales;\n\n//# sourceURL=webpack:///./node_modules/validator/lib/isAlpha.js?");
/***/ }),
/***/ "./node_modules/validator/lib/isAlphanumeric.js":
/*!******************************************************!*\
!*** ./node_modules/validator/lib/isAlphanumeric.js ***!
\******************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
eval("\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = isAlphanumeric;\nexports.locales = void 0;\n\nvar _assertString = _interopRequireDefault(__webpack_require__(/*! ./util/assertString */ \"./node_modules/validator/lib/util/assertString.js\"));\n\nvar _alpha = __webpack_require__(/*! ./alpha */ \"./node_modules/validator/lib/alpha.js\");\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\nfunction isAlphanumeric(str) {\n var locale = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'en-US';\n (0, _assertString.default)(str);\n\n if (locale in _alpha.alphanumeric) {\n return _alpha.alphanumeric[locale].test(str);\n }\n\n throw new Error(\"Invalid locale '\".concat(locale, \"'\"));\n}\n\nvar locales = Object.keys(_alpha.alphanumeric);\nexports.locales = locales;\n\n//# sourceURL=webpack:///./node_modules/validator/lib/isAlphanumeric.js?");
/***/ }),
/***/ "./node_modules/validator/lib/isAscii.js":
/*!***********************************************!*\
!*** ./node_modules/validator/lib/isAscii.js ***!
\***********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
eval("\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = isAscii;\n\nvar _assertString = _interopRequireDefault(__webpack_require__(/*! ./util/assertString */ \"./node_modules/validator/lib/util/assertString.js\"));\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\n/* eslint-disable no-control-regex */\nvar ascii = /^[\\x00-\\x7F]+$/;\n/* eslint-enable no-control-regex */\n\nfunction isAscii(str) {\n (0, _assertString.default)(str);\n return ascii.test(str);\n}\n\nmodule.exports = exports.default;\nmodule.exports.default = exports.default;\n\n//# sourceURL=webpack:///./node_modules/validator/lib/isAscii.js?");
/***/ }),
/***/ "./node_modules/validator/lib/isBIC.js":
/*!*********************************************!*\
!*** ./node_modules/validator/lib/isBIC.js ***!
\*********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
eval("\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = isBIC;\n\nvar _assertString = _interopRequireDefault(__webpack_require__(/*! ./util/assertString */ \"./node_modules/validator/lib/util/assertString.js\"));\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\nvar isBICReg = /^[A-z]{4}[A-z]{2}\\w{2}(\\w{3})?$/;\n\nfunction isBIC(str) {\n (0, _assertString.default)(str);\n return isBICReg.test(str);\n}\n\nmodule.exports = exports.default;\nmodule.exports.default = exports.default;\n\n//# sourceURL=webpack:///./node_modules/validator/lib/isBIC.js?");
/***/ }),
/***/ "./node_modules/validator/lib/isBase32.js":
/*!************************************************!*\
!*** ./node_modules/validator/lib/isBase32.js ***!
\************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
eval("\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = isBase32;\n\nvar _assertString = _interopRequireDefault(__webpack_require__(/*! ./util/assertString */ \"./node_modules/validator/lib/util/assertString.js\"));\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\nvar base32 = /^[A-Z2-7]+=*$/;\n\nfunction isBase32(str) {\n (0, _assertString.default)(str);\n var len = str.length;\n\n if (len > 0 && len % 8 === 0 && base32.test(str)) {\n return true;\n }\n\n return false;\n}\n\nmodule.exports = exports.default;\nmodule.exports.default = exports.default;\n\n//# sourceURL=webpack:///./node_modules/validator/lib/isBase32.js?");
/***/ }),
/***/ "./node_modules/validator/lib/isBase64.js":
/*!************************************************!*\
!*** ./node_modules/validator/lib/isBase64.js ***!
\************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
eval("\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = isBase64;\n\nvar _assertString = _interopRequireDefault(__webpack_require__(/*! ./util/assertString */ \"./node_modules/validator/lib/util/assertString.js\"));\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\nvar notBase64 = /[^A-Z0-9+\\/=]/i;\n\nfunction isBase64(str) {\n (0, _assertString.default)(str);\n var len = str.length;\n\n if (!len || len % 4 !== 0 || notBase64.test(str)) {\n return false;\n }\n\n var firstPaddingChar = str.indexOf('=');\n return firstPaddingChar === -1 || firstPaddingChar === len - 1 || firstPaddingChar === len - 2 && str[len - 1] === '=';\n}\n\nmodule.exports = exports.default;\nmodule.exports.default = exports.default;\n\n//# sourceURL=webpack:///./node_modules/validator/lib/isBase64.js?");
/***/ }),
/***/ "./node_modules/validator/lib/isBefore.js":
/*!************************************************!*\
!*** ./node_modules/validator/lib/isBefore.js ***!
\************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
eval("\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = isBefore;\n\nvar _assertString = _interopRequireDefault(__webpack_require__(/*! ./util/assertString */ \"./node_modules/validator/lib/util/assertString.js\"));\n\nvar _toDate = _interopRequireDefault(__webpack_require__(/*! ./toDate */ \"./node_modules/validator/lib/toDate.js\"));\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\nfunction isBefore(str) {\n var date = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : String(new Date());\n (0, _assertString.default)(str);\n var comparison = (0, _toDate.default)(date);\n var original = (0, _toDate.default)(str);\n return !!(original && comparison && original < comparison);\n}\n\nmodule.exports = exports.default;\nmodule.exports.default = exports.default;\n\n//# sourceURL=webpack:///./node_modules/validator/lib/isBefore.js?");
/***/ }),
/***/ "./node_modules/validator/lib/isBoolean.js":
/*!*************************************************!*\
!*** ./node_modules/validator/lib/isBoolean.js ***!
\*************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
eval("\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = isBoolean;\n\nvar _assertString = _interopRequireDefault(__webpack_require__(/*! ./util/assertString */ \"./node_modules/validator/lib/util/assertString.js\"));\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\nfunction isBoolean(str) {\n (0, _assertString.default)(str);\n return ['true', 'false', '1', '0'].indexOf(str) >= 0;\n}\n\nmodule.exports = exports.default;\nmodule.exports.default = exports.default;\n\n//# sourceURL=webpack:///./node_modules/validator/lib/isBoolean.js?");
/***/ }),
/***/ "./node_modules/validator/lib/isBtcAddress.js":
/*!****************************************************!*\
!*** ./node_modules/validator/lib/isBtcAddress.js ***!
\****************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
eval("\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = isBtcAddress;\n\nvar _assertString = _interopRequireDefault(__webpack_require__(/*! ./util/assertString */ \"./node_modules/validator/lib/util/assertString.js\"));\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\n// supports Bech32 addresses\nvar btc = /^(bc1|[13])[a-zA-HJ-NP-Z0-9]{25,39}$/;\n\nfunction isBtcAddress(str) {\n (0, _assertString.default)(str);\n return btc.test(str);\n}\n\nmodule.exports = exports.default;\nmodule.exports.default = exports.default;\n\n//# sourceURL=webpack:///./node_modules/validator/lib/isBtcAddress.js?");
/***/ }),
/***/ "./node_modules/validator/lib/isByteLength.js":
/*!****************************************************!*\
!*** ./node_modules/validator/lib/isByteLength.js ***!
\****************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
eval("\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = isByteLength;\n\nvar _assertString = _interopRequireDefault(__webpack_require__(/*! ./util/assertString */ \"./node_modules/validator/lib/util/assertString.js\"));\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\nfunction _typeof(obj) { \"@babel/helpers - typeof\"; if (typeof Symbol === \"function\" && typeof Symbol.iterator === \"symbol\") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === \"function\" && obj.constructor === Symbol && obj !== Symbol.prototype ? \"symbol\" : typeof obj; }; } return _typeof(obj); }\n\n/* eslint-disable prefer-rest-params */\nfunction isByteLength(str, options) {\n (0, _assertString.default)(str);\n var min;\n var max;\n\n if (_typeof(options) === 'object') {\n min = options.min || 0;\n max = options.max;\n } else {\n // backwards compatibility: isByteLength(str, min [, max])\n min = arguments[1];\n max = arguments[2];\n }\n\n var len = encodeURI(str).split(/%..|./).length - 1;\n return len >= min && (typeof max === 'undefined' || len <= max);\n}\n\nmodule.exports = exports.default;\nmodule.exports.default = exports.default;\n\n//# sourceURL=webpack:///./node_modules/validator/lib/isByteLength.js?");
/***/ }),
/***/ "./node_modules/validator/lib/isCreditCard.js":
/*!****************************************************!*\
!*** ./node_modules/validator/lib/isCreditCard.js ***!
\****************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
eval("\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = isCreditCard;\n\nvar _assertString = _interopRequireDefault(__webpack_require__(/*! ./util/assertString */ \"./node_modules/validator/lib/util/assertString.js\"));\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\n/* eslint-disable max-len */\nvar creditCard = /^(?:4[0-9]{12}(?:[0-9]{3})?|5[1-5][0-9]{14}|(222[1-9]|22[3-9][0-9]|2[3-6][0-9]{2}|27[01][0-9]|2720)[0-9]{12}|6(?:011|5[0-9][0-9])[0-9]{12}|3[47][0-9]{13}|3(?:0[0-5]|[68][0-9])[0-9]{11}|(?:2131|1800|35\\d{3})\\d{11}|6[27][0-9]{14})$/;\n/* eslint-enable max-len */\n\nfunction isCreditCard(str) {\n (0, _assertString.default)(str);\n var sanitized = str.replace(/[- ]+/g, '');\n\n if (!creditCard.test(sanitized)) {\n return false;\n }\n\n var sum = 0;\n var digit;\n var tmpNum;\n var shouldDouble;\n\n for (var i = sanitized.length - 1; i >= 0; i--) {\n digit = sanitized.substring(i, i + 1);\n tmpNum = parseInt(digit, 10);\n\n if (shouldDouble) {\n tmpNum *= 2;\n\n if (tmpNum >= 10) {\n sum += tmpNum % 10 + 1;\n } else {\n sum += tmpNum;\n }\n } else {\n sum += tmpNum;\n }\n\n shouldDouble = !shouldDouble;\n }\n\n return !!(sum % 10 === 0 ? sanitized : false);\n}\n\nmodule.exports = exports.default;\nmodule.exports.default = exports.default;\n\n//# sourceURL=webpack:///./node_modules/validator/lib/isCreditCard.js?");
/***/ }),
/***/ "./node_modules/validator/lib/isCurrency.js":
/*!**************************************************!*\
!*** ./node_modules/validator/lib/isCurrency.js ***!
\**************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
eval("\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = isCurrency;\n\nvar _merge = _interopRequireDefault(__webpack_require__(/*! ./util/merge */ \"./node_modules/validator/lib/util/merge.js\"));\n\nvar _assertString = _interopRequireDefault(__webpack_require__(/*! ./util/assertString */ \"./node_modules/validator/lib/util/assertString.js\"));\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\nfunction currencyRegex(options) {\n var decimal_digits = \"\\\\d{\".concat(options.digits_after_decimal[0], \"}\");\n options.digits_after_decimal.forEach(function (digit, index) {\n if (index !== 0) decimal_digits = \"\".concat(decimal_digits, \"|\\\\d{\").concat(digit, \"}\");\n });\n var symbol = \"(\\\\\".concat(options.symbol.replace(/\\./g, '\\\\.'), \")\").concat(options.require_symbol ? '' : '?'),\n negative = '-?',\n whole_dollar_amount_without_sep = '[1-9]\\\\d*',\n whole_dollar_amount_with_sep = \"[1-9]\\\\d{0,2}(\\\\\".concat(options.thousands_separator, \"\\\\d{3})*\"),\n valid_whole_dollar_amounts = ['0', whole_dollar_amount_without_sep, whole_dollar_amount_with_sep],\n whole_dollar_amount = \"(\".concat(valid_whole_dollar_amounts.join('|'), \")?\"),\n decimal_amount = \"(\\\\\".concat(options.decimal_separator, \"(\").concat(decimal_digits, \"))\").concat(options.require_decimal ? '' : '?');\n var pattern = whole_dollar_amount + (options.allow_decimal || options.require_decimal ? decimal_amount : ''); // default is negative sign before symbol, but there are two other options (besides parens)\n\n if (options.allow_negatives && !options.parens_for_negatives) {\n if (options.negative_sign_after_digits) {\n pattern += negative;\n } else if (options.negative_sign_before_digits) {\n pattern = negative + pattern;\n }\n } // South African Rand, for example, uses R 123 (space) and R-123 (no space)\n\n\n if (options.allow_negative_sign_placeholder) {\n pattern = \"( (?!\\\\-))?\".concat(pattern);\n } else if (options.allow_space_after_symbol) {\n pattern = \" ?\".concat(pattern);\n } else if (options.allow_space_after_digits) {\n pattern += '( (?!$))?';\n }\n\n if (options.symbol_after_digits) {\n pattern += symbol;\n } else {\n pattern = symbol + pattern;\n }\n\n if (options.allow_negatives) {\n if (options.parens_for_negatives) {\n pattern = \"(\\\\(\".concat(pattern, \"\\\\)|\").concat(pattern, \")\");\n } else if (!(options.negative_sign_before_digits || options.negative_sign_after_digits)) {\n pattern = negative + pattern;\n }\n } // ensure there's a dollar and/or decimal amount, and that\n // it doesn't start with a space or a negative sign followed by a space\n\n\n return new RegExp(\"^(?!-? )(?=.*\\\\d)\".concat(pattern, \"$\"));\n}\n\nvar default_currency_options = {\n symbol: '$',\n require_symbol: false,\n allow_space_after_symbol: false,\n symbol_after_digits: false,\n allow_negatives: true,\n parens_for_negatives: false,\n negative_sign_before_digits: false,\n negative_sign_after_digits: false,\n allow_negative_sign_placeholder: false,\n thousands_separator: ',',\n decimal_separator: '.',\n allow_decimal: true,\n require_decimal: false,\n digits_after_decimal: [2],\n allow_space_after_digits: false\n};\n\nfunction isCurrency(str, options) {\n (0, _assertString.default)(str);\n options = (0, _merge.default)(options, default_currency_options);\n return currencyRegex(options).test(str);\n}\n\nmodule.exports = exports.default;\nmodule.exports.default = exports.default;\n\n//# sourceURL=webpack:///./node_modules/validator/lib/isCurrency.js?");
/***/ }),
/***/ "./node_modules/validator/lib/isDataURI.js":
/*!*************************************************!*\
!*** ./node_modules/validator/lib/isDataURI.js ***!
\*************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
eval("\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = isDataURI;\n\nvar _assertString = _interopRequireDefault(__webpack_require__(/*! ./util/assertString */ \"./node_modules/validator/lib/util/assertString.js\"));\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\nvar validMediaType = /^[a-z]+\\/[a-z0-9\\-\\+]+$/i;\nvar validAttribute = /^[a-z\\-]+=[a-z0-9\\-]+$/i;\nvar validData = /^[a-z0-9!\\$&'\\(\\)\\*\\+,;=\\-\\._~:@\\/\\?%\\s]*$/i;\n\nfunction isDataURI(str) {\n (0, _assertString.default)(str);\n var data = str.split(',');\n\n if (data.length < 2) {\n return false;\n }\n\n var attributes = data.shift().trim().split(';');\n var schemeAndMediaType = attributes.shift();\n\n if (schemeAndMediaType.substr(0, 5) !== 'data:') {\n return false;\n }\n\n var mediaType = schemeAndMediaType.substr(5);\n\n if (mediaType !== '' && !validMediaType.test(mediaType)) {\n return false;\n }\n\n for (var i = 0; i < attributes.length; i++) {\n if (i === attributes.length - 1 && attributes[i].toLowerCase() === 'base64') {// ok\n } else if (!validAttribute.test(attributes[i])) {\n return false;\n }\n }\n\n for (var _i = 0; _i < data.length; _i++) {\n if (!validData.test(data[_i])) {\n return false;\n }\n }\n\n return true;\n}\n\nmodule.exports = exports.default;\nmodule.exports.default = exports.default;\n\n//# sourceURL=webpack:///./node_modules/validator/lib/isDataURI.js?");
/***/ }),
/***/ "./node_modules/validator/lib/isDecimal.js":
/*!*************************************************!*\
!*** ./node_modules/validator/lib/isDecimal.js ***!
\*************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
eval("\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = isDecimal;\n\nvar _merge = _interopRequireDefault(__webpack_require__(/*! ./util/merge */ \"./node_modules/validator/lib/util/merge.js\"));\n\nvar _assertString = _interopRequireDefault(__webpack_require__(/*! ./util/assertString */ \"./node_modules/validator/lib/util/assertString.js\"));\n\nvar _includes = _interopRequireDefault(__webpack_require__(/*! ./util/includes */ \"./node_modules/validator/lib/util/includes.js\"));\n\nvar _alpha = __webpack_require__(/*! ./alpha */ \"./node_modules/validator/lib/alpha.js\");\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\nfunction decimalRegExp(options) {\n var regExp = new RegExp(\"^[-+]?([0-9]+)?(\\\\\".concat(_alpha.decimal[options.locale], \"[0-9]{\").concat(options.decimal_digits, \"})\").concat(options.force_decimal ? '' : '?', \"$\"));\n return regExp;\n}\n\nvar default_decimal_options = {\n force_decimal: false,\n decimal_digits: '1,',\n locale: 'en-US'\n};\nvar blacklist = ['', '-', '+'];\n\nfunction isDecimal(str, options) {\n (0, _assertString.default)(str);\n options = (0, _merge.default)(options, default_decimal_options);\n\n if (options.locale in _alpha.decimal) {\n return !(0, _includes.default)(blacklist, str.replace(/ /g, '')) && decimalRegExp(options).test(str);\n }\n\n throw new Error(\"Invalid locale '\".concat(options.locale, \"'\"));\n}\n\nmodule.exports = exports.default;\nmodule.exports.default = exports.default;\n\n//# sourceURL=webpack:///./node_modules/validator/lib/isDecimal.js?");
/***/ }),
/***/ "./node_modules/validator/lib/isDivisibleBy.js":
/*!*****************************************************!*\
!*** ./node_modules/validator/lib/isDivisibleBy.js ***!
\*****************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
eval("\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = isDivisibleBy;\n\nvar _assertString = _interopRequireDefault(__webpack_require__(/*! ./util/assertString */ \"./node_modules/validator/lib/util/assertString.js\"));\n\nvar _toFloat = _interopRequireDefault(__webpack_require__(/*! ./toFloat */ \"./node_modules/validator/lib/toFloat.js\"));\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\nfunction isDivisibleBy(str, num) {\n (0, _assertString.default)(str);\n return (0, _toFloat.default)(str) % parseInt(num, 10) === 0;\n}\n\nmodule.exports = exports.default;\nmodule.exports.default = exports.default;\n\n//# sourceURL=webpack:///./node_modules/validator/lib/isDivisibleBy.js?");
/***/ }),
/***/ "./node_modules/validator/lib/isEAN.js":
/*!*********************************************!*\
!*** ./node_modules/validator/lib/isEAN.js ***!
\*********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
eval("\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = isEAN;\n\nvar _assertString = _interopRequireDefault(__webpack_require__(/*! ./util/assertString */ \"./node_modules/validator/lib/util/assertString.js\"));\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\n/**\n * The most commonly used EAN standard is\n * the thirteen-digit EAN-13, while the\n * less commonly used 8-digit EAN-8 barcode was\n * introduced for use on small packages.\n * EAN consists of:\n * GS1 prefix, manufacturer code, product code and check digit\n * Reference: https://en.wikipedia.org/wiki/International_Article_Number\n */\n\n/**\n * Define EAN Lenghts; 8 for EAN-8; 13 for EAN-13\n * and Regular Expression for valid EANs (EAN-8, EAN-13),\n * with exact numberic matching of 8 or 13 digits [0-9]\n */\nvar LENGTH_EAN_8 = 8;\nvar validEanRegex = /^(\\d{8}|\\d{13})$/;\n/**\n * Get position weight given:\n * EAN length and digit index/position\n *\n * @param {number} length\n * @param {number} index\n * @return {number}\n */\n\nfunction getPositionWeightThroughLengthAndIndex(length, index) {\n if (length === LENGTH_EAN_8) {\n return index % 2 === 0 ? 3 : 1;\n }\n\n return index % 2 === 0 ? 1 : 3;\n}\n/**\n * Calculate EAN Check Digit\n * Reference: https://en.wikipedia.org/wiki/International_Article_Number#Calculation_of_checksum_digit\n *\n * @param {string} ean\n * @return {number}\n */\n\n\nfunction calculateCheckDigit(ean) {\n var checksum = ean.slice(0, -1).split('').map(function (char, index) {\n return Number(char) * getPositionWeightThroughLengthAndIndex(ean.length, index);\n }).reduce(function (acc, partialSum) {\n return acc + partialSum;\n }, 0);\n var remainder = 10 - checksum % 10;\n return remainder < 10 ? remainder : 0;\n}\n/**\n * Check if string is valid EAN:\n * Matches EAN-8/EAN-13 regex\n * Has valid check digit.\n *\n * @param {string} str\n * @return {boolean}\n */\n\n\nfunction isEAN(str) {\n (0, _assertString.default)(str);\n var actualCheckDigit = Number(str.slice(-1));\n return validEanRegex.test(str) && actualCheckDigit === calculateCheckDigit(str);\n}\n\nmodule.exports = exports.default;\nmodule.exports.default = exports.default;\n\n//# sourceURL=webpack:///./node_modules/validator/lib/isEAN.js?");
/***/ }),
/***/ "./node_modules/validator/lib/isEmail.js":
/*!***********************************************!*\
!*** ./node_modules/validator/lib/isEmail.js ***!
\***********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
eval("\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = isEmail;\n\nvar _assertString = _interopRequireDefault(__webpack_require__(/*! ./util/assertString */ \"./node_modules/validator/lib/util/assertString.js\"));\n\nvar _merge = _interopRequireDefault(__webpack_require__(/*! ./util/merge */ \"./node_modules/validator/lib/util/merge.js\"));\n\nvar _isByteLength = _interopRequireDefault(__webpack_require__(/*! ./isByteLength */ \"./node_modules/validator/lib/isByteLength.js\"));\n\nvar _isFQDN = _interopRequireDefault(__webpack_require__(/*! ./isFQDN */ \"./node_modules/validator/lib/isFQDN.js\"));\n\nvar _isIP = _interopRequireDefault(__webpack_require__(/*! ./isIP */ \"./node_modules/validator/lib/isIP.js\"));\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\nfunction _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _nonIterableRest(); }\n\nfunction _nonIterableRest() { throw new TypeError(\"Invalid attempt to destructure non-iterable instance\"); }\n\nfunction _iterableToArrayLimit(arr, i) { if (!(Symbol.iterator in Object(arr) || Object.prototype.toString.call(arr) === \"[object Arguments]\")) { return; } var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i[\"return\"] != null) _i[\"return\"](); } finally { if (_d) throw _e; } } return _arr; }\n\nfunction _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }\n\nvar default_email_options = {\n allow_display_name: false,\n require_display_name: false,\n allow_utf8_local_part: true,\n require_tld: true\n};\n/* eslint-disable max-len */\n\n/* eslint-disable no-control-regex */\n\nvar splitNameAddress = /^([^\\x00-\\x1F\\x7F-\\x9F\\cX]+)<(.+)>$/i;\nvar emailUserPart = /^[a-z\\d!#\\$%&'\\*\\+\\-\\/=\\?\\^_`{\\|}~]+$/i;\nvar gmailUserPart = /^[a-z\\d]+$/;\nvar quotedEmailUser = /^([\\s\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x7f\\x21\\x23-\\x5b\\x5d-\\x7e]|(\\\\[\\x01-\\x09\\x0b\\x0c\\x0d-\\x7f]))*$/i;\nvar emailUserUtf8Part = /^[a-z\\d!#\\$%&'\\*\\+\\-\\/=\\?\\^_`{\\|}~\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF]+$/i;\nvar quotedEmailUserUtf8 = /^([\\s\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x7f\\x21\\x23-\\x5b\\x5d-\\x7e\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF]|(\\\\[\\x01-\\x09\\x0b\\x0c\\x0d-\\x7f\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF]))*$/i;\nvar defaultMaxEmailLength = 254;\n/* eslint-enable max-len */\n\n/* eslint-enable no-control-regex */\n\n/**\n * Validate display name according to the RFC2822: https://tools.ietf.org/html/rfc2822#appendix-A.1.2\n * @param {String} display_name\n */\n\nfunction validateDisplayName(display_name) {\n var trim_quotes = display_name.match(/^\"(.+)\"$/i);\n var display_name_without_quotes = trim_quotes ? trim_quotes[1] : display_name; // display name with only spaces is not valid\n\n if (!display_name_without_quotes.trim()) {\n return false;\n } // check whether display name contains illegal character\n\n\n var contains_illegal = /[\\.\";<>]/.test(display_name_without_quotes);\n\n if (contains_illegal) {\n // if contains illegal characters,\n // must to be enclosed in double-quotes, otherwise it's not a valid display name\n if (!trim_quotes) {\n return false;\n } // the quotes in display name must start with character symbol \\\n\n\n var all_start_with_back_slash = display_name_without_quotes.split('\"').length === display_name_without_quotes.split('\\\\\"').length;\n\n if (!all_start_with_back_slash) {\n return false;\n }\n }\n\n return true;\n}\n\nfunction isEmail(str, options) {\n (0, _assertString.default)(str);\n options = (0, _merge.default)(options, default_email_options);\n\n if (options.require_display_name || options.allow_display_name) {\n var display_email = str.match(splitNameAddress);\n\n if (display_email) {\n var display_name;\n\n var _display_email = _slicedToArray(display_email, 3);\n\n display_name = _display_email[1];\n str = _display_email[2];\n\n // sometimes need to trim the last space to get the display name\n // because there may be a space between display name and email address\n // eg. myname <[email protected]>\n // the display name is `myname` instead of `myname `, so need to trim the last space\n if (display_name.endsWith(' ')) {\n display_name = display_name.substr(0, display_name.length - 1);\n }\n\n if (!validateDisplayName(display_name)) {\n return false;\n }\n } else if (options.require_display_name) {\n return false;\n }\n }\n\n if (!options.ignore_max_length && str.length > defaultMaxEmailLength) {\n return false;\n }\n\n var parts = str.split('@');\n var domain = parts.pop();\n var user = parts.join('@');\n var lower_domain = domain.toLowerCase();\n\n if (options.domain_specific_validation && (lower_domain === 'gmail.com' || lower_domain === 'googlemail.com')) {\n /*\n Previously we removed dots for gmail addresses before validating.\n This was removed because it allows `[email protected]`\n to be reported as valid, but it is not.\n Gmail only normalizes single dots, removing them from here is pointless,\n should be done in normalizeEmail\n */\n user = user.toLowerCase(); // Removing sub-address from username before gmail validation\n\n var username = user.split('+')[0]; // Dots are not included in gmail length restriction\n\n if (!(0, _isByteLength.default)(username.replace('.', ''), {\n min: 6,\n max: 30\n })) {\n return false;\n }\n\n var _user_parts = username.split('.');\n\n for (var i = 0; i < _user_parts.length; i++) {\n if (!gmailUserPart.test(_user_parts[i])) {\n return false;\n }\n }\n }\n\n if (!(0, _isByteLength.default)(user, {\n max: 64\n }) || !(0, _isByteLength.default)(domain, {\n max: 254\n })) {\n return false;\n }\n\n if (!(0, _isFQDN.default)(domain, {\n require_tld: options.require_tld\n })) {\n if (!options.allow_ip_domain) {\n return false;\n }\n\n if (!(0, _isIP.default)(domain)) {\n if (!domain.startsWith('[') || !domain.endsWith(']')) {\n return false;\n }\n\n var noBracketdomain = domain.substr(1, domain.length - 2);\n\n if (noBracketdomain.length === 0 || !(0, _isIP.default)(noBracketdomain)) {\n return false;\n }\n }\n }\n\n if (user[0] === '\"') {\n user = user.slice(1, user.length - 1);\n return options.allow_utf8_local_part ? quotedEmailUserUtf8.test(user) : quotedEmailUser.test(user);\n }\n\n var pattern = options.allow_utf8_local_part ? emailUserUtf8Part : emailUserPart;\n var user_parts = user.split('.');\n\n for (var _i2 = 0; _i2 < user_parts.length; _i2++) {\n if (!pattern.test(user_parts[_i2])) {\n return false;\n }\n }\n\n return true;\n}\n\nmodule.exports = exports.default;\nmodule.exports.default = exports.default;\n\n//# sourceURL=webpack:///./node_modules/validator/lib/isEmail.js?");
/***/ }),
/***/ "./node_modules/validator/lib/isEmpty.js":
/*!***********************************************!*\
!*** ./node_modules/validator/lib/isEmpty.js ***!
\***********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
eval("\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = isEmpty;\n\nvar _assertString = _interopRequireDefault(__webpack_require__(/*! ./util/assertString */ \"./node_modules/validator/lib/util/assertString.js\"));\n\nvar _merge = _interopRequireDefault(__webpack_require__(/*! ./util/merge */ \"./node_modules/validator/lib/util/merge.js\"));\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\nvar default_is_empty_options = {\n ignore_whitespace: false\n};\n\nfunction isEmpty(str, options) {\n (0, _assertString.default)(str);\n options = (0, _merge.default)(options, default_is_empty_options);\n return (options.ignore_whitespace ? str.trim().length : str.length) === 0;\n}\n\nmodule.exports = exports.default;\nmodule.exports.default = exports.default;\n\n//# sourceURL=webpack:///./node_modules/validator/lib/isEmpty.js?");
/***/ }),
/***/ "./node_modules/validator/lib/isEthereumAddress.js":
/*!*********************************************************!*\
!*** ./node_modules/validator/lib/isEthereumAddress.js ***!
\*********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
eval("\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = isEthereumAddress;\n\nvar _assertString = _interopRequireDefault(__webpack_require__(/*! ./util/assertString */ \"./node_modules/validator/lib/util/assertString.js\"));\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\nvar eth = /^(0x)[0-9a-f]{40}$/i;\n\nfunction isEthereumAddress(str) {\n (0, _assertString.default)(str);\n return eth.test(str);\n}\n\nmodule.exports = exports.default;\nmodule.exports.default = exports.default;\n\n//# sourceURL=webpack:///./node_modules/validator/lib/isEthereumAddress.js?");
/***/ }),
/***/ "./node_modules/validator/lib/isFQDN.js":
/*!**********************************************!*\
!*** ./node_modules/validator/lib/isFQDN.js ***!
\**********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
eval("\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = isFQDN;\n\nvar _assertString = _interopRequireDefault(__webpack_require__(/*! ./util/assertString */ \"./node_modules/validator/lib/util/assertString.js\"));\n\nvar _merge = _interopRequireDefault(__webpack_require__(/*! ./util/merge */ \"./node_modules/validator/lib/util/merge.js\"));\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\nvar default_fqdn_options = {\n require_tld: true,\n allow_underscores: false,\n allow_trailing_dot: false\n};\n\nfunction isFQDN(str, options) {\n (0, _assertString.default)(str);\n options = (0, _merge.default)(options, default_fqdn_options);\n /* Remove the optional trailing dot before checking validity */\n\n if (options.allow_trailing_dot && str[str.length - 1] === '.') {\n str = str.substring(0, str.length - 1);\n }\n\n var parts = str.split('.');\n\n for (var i = 0; i < parts.length; i++) {\n if (parts[i].length > 63) {\n return false;\n }\n }\n\n if (options.require_tld) {\n var tld = parts.pop();\n\n if (!parts.length || !/^([a-z\\u00a1-\\uffff]{2,}|xn[a-z0-9-]{2,})$/i.test(tld)) {\n return false;\n } // disallow spaces\n\n\n if (/[\\s\\u2002-\\u200B\\u202F\\u205F\\u3000\\uFEFF\\uDB40\\uDC20]/.test(tld)) {\n return false;\n }\n }\n\n for (var part, _i = 0; _i < parts.length; _i++) {\n part = parts[_i];\n\n if (options.allow_underscores) {\n part = part.replace(/_/g, '');\n }\n\n if (!/^[a-z\\u00a1-\\uffff0-9-]+$/i.test(part)) {\n return false;\n } // disallow full-width chars\n\n\n if (/[\\uff01-\\uff5e]/.test(part)) {\n return false;\n }\n\n if (part[0] === '-' || part[part.length - 1] === '-') {\n return false;\n }\n }\n\n return true;\n}\n\nmodule.exports = exports.default;\nmodule.exports.default = exports.default;\n\n//# sourceURL=webpack:///./node_modules/validator/lib/isFQDN.js?");
/***/ }),
/***/ "./node_modules/validator/lib/isFloat.js":
/*!***********************************************!*\
!*** ./node_modules/validator/lib/isFloat.js ***!
\***********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
eval("\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = isFloat;\nexports.locales = void 0;\n\nvar _assertString = _interopRequireDefault(__webpack_require__(/*! ./util/assertString */ \"./node_modules/validator/lib/util/assertString.js\"));\n\nvar _alpha = __webpack_require__(/*! ./alpha */ \"./node_modules/validator/lib/alpha.js\");\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\nfunction isFloat(str, options) {\n (0, _assertString.default)(str);\n options = options || {};\n var float = new RegExp(\"^(?:[-+])?(?:[0-9]+)?(?:\\\\\".concat(options.locale ? _alpha.decimal[options.locale] : '.', \"[0-9]*)?(?:[eE][\\\\+\\\\-]?(?:[0-9]+))?$\"));\n\n if (str === '' || str === '.' || str === '-' || str === '+') {\n return false;\n }\n\n var value = parseFloat(str.replace(',', '.'));\n return float.test(str) && (!options.hasOwnProperty('min') || value >= options.min) && (!options.hasOwnProperty('max') || value <= options.max) && (!options.hasOwnProperty('lt') || value < options.lt) && (!options.hasOwnProperty('gt') || value > options.gt);\n}\n\nvar locales = Object.keys(_alpha.decimal);\nexports.locales = locales;\n\n//# sourceURL=webpack:///./node_modules/validator/lib/isFloat.js?");
/***/ }),
/***/ "./node_modules/validator/lib/isFullWidth.js":
/*!***************************************************!*\
!*** ./node_modules/validator/lib/isFullWidth.js ***!
\***************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
eval("\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = isFullWidth;\nexports.fullWidth = void 0;\n\nvar _assertString = _interopRequireDefault(__webpack_require__(/*! ./util/assertString */ \"./node_modules/validator/lib/util/assertString.js\"));\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\nvar fullWidth = /[^\\u0020-\\u007E\\uFF61-\\uFF9F\\uFFA0-\\uFFDC\\uFFE8-\\uFFEE0-9a-zA-Z]/;\nexports.fullWidth = fullWidth;\n\nfunction isFullWidth(str) {\n (0, _assertString.default)(str);\n return fullWidth.test(str);\n}\n\n//# sourceURL=webpack:///./node_modules/validator/lib/isFullWidth.js?");
/***/ }),
/***/ "./node_modules/validator/lib/isHSL.js":
/*!*********************************************!*\
!*** ./node_modules/validator/lib/isHSL.js ***!
\*********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
eval("\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = isHSL;\n\nvar _assertString = _interopRequireDefault(__webpack_require__(/*! ./util/assertString */ \"./node_modules/validator/lib/util/assertString.js\"));\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\nvar hslcomma = /^(hsl)a?\\(\\s*((\\+|\\-)?([0-9]+(\\.[0-9]+)?(e(\\+|\\-)?[0-9]+)?|\\.[0-9]+(e(\\+|\\-)?[0-9]+)?))(deg|grad|rad|turn|\\s*)(\\s*,\\s*(\\+|\\-)?([0-9]+(\\.[0-9]+)?(e(\\+|\\-)?[0-9]+)?|\\.[0-9]+(e(\\+|\\-)?[0-9]+)?)%){2}\\s*(,\\s*((\\+|\\-)?([0-9]+(\\.[0-9]+)?(e(\\+|\\-)?[0-9]+)?|\\.[0-9]+(e(\\+|\\-)?[0-9]+)?)%?)\\s*)?\\)$/i;\nvar hslspace = /^(hsl)a?\\(\\s*((\\+|\\-)?([0-9]+(\\.[0-9]+)?(e(\\+|\\-)?[0-9]+)?|\\.[0-9]+(e(\\+|\\-)?[0-9]+)?))(deg|grad|rad|turn|\\s)(\\s*(\\+|\\-)?([0-9]+(\\.[0-9]+)?(e(\\+|\\-)?[0-9]+)?|\\.[0-9]+(e(\\+|\\-)?[0-9]+)?)%){2}\\s*(\\/\\s*((\\+|\\-)?([0-9]+(\\.[0-9]+)?(e(\\+|\\-)?[0-9]+)?|\\.[0-9]+(e(\\+|\\-)?[0-9]+)?)%?)\\s*)?\\)$/i;\n\nfunction isHSL(str) {\n (0, _assertString.default)(str);\n return hslcomma.test(str) || hslspace.test(str);\n}\n\nmodule.exports = exports.default;\nmodule.exports.default = exports.default;\n\n//# sourceURL=webpack:///./node_modules/validator/lib/isHSL.js?");
/***/ }),
/***/ "./node_modules/validator/lib/isHalfWidth.js":
/*!***************************************************!*\
!*** ./node_modules/validator/lib/isHalfWidth.js ***!
\***************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
eval("\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = isHalfWidth;\nexports.halfWidth = void 0;\n\nvar _assertString = _interopRequireDefault(__webpack_require__(/*! ./util/assertString */ \"./node_modules/validator/lib/util/assertString.js\"));\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\nvar halfWidth = /[\\u0020-\\u007E\\uFF61-\\uFF9F\\uFFA0-\\uFFDC\\uFFE8-\\uFFEE0-9a-zA-Z]/;\nexports.halfWidth = halfWidth;\n\nfunction isHalfWidth(str) {\n (0, _assertString.default)(str);\n return halfWidth.test(str);\n}\n\n//# sourceURL=webpack:///./node_modules/validator/lib/isHalfWidth.js?");
/***/ }),
/***/ "./node_modules/validator/lib/isHash.js":
/*!**********************************************!*\
!*** ./node_modules/validator/lib/isHash.js ***!
\**********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
eval("\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = isHash;\n\nvar _assertString = _interopRequireDefault(__webpack_require__(/*! ./util/assertString */ \"./node_modules/validator/lib/util/assertString.js\"));\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\nvar lengths = {\n md5: 32,\n md4: 32,\n sha1: 40,\n sha256: 64,\n sha384: 96,\n sha512: 128,\n ripemd128: 32,\n ripemd160: 40,\n tiger128: 32,\n tiger160: 40,\n tiger192: 48,\n crc32: 8,\n crc32b: 8\n};\n\nfunction isHash(str, algorithm) {\n (0, _assertString.default)(str);\n var hash = new RegExp(\"^[a-fA-F0-9]{\".concat(lengths[algorithm], \"}$\"));\n return hash.test(str);\n}\n\nmodule.exports = exports.default;\nmodule.exports.default = exports.default;\n\n//# sourceURL=webpack:///./node_modules/validator/lib/isHash.js?");
/***/ }),
/***/ "./node_modules/validator/lib/isHexColor.js":
/*!**************************************************!*\
!*** ./node_modules/validator/lib/isHexColor.js ***!
\**************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
eval("\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = isHexColor;\n\nvar _assertString = _interopRequireDefault(__webpack_require__(/*! ./util/assertString */ \"./node_modules/validator/lib/util/assertString.js\"));\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\nvar hexcolor = /^#?([0-9A-F]{3}|[0-9A-F]{4}|[0-9A-F]{6}|[0-9A-F]{8})$/i;\n\nfunction isHexColor(str) {\n (0, _assertString.default)(str);\n return hexcolor.test(str);\n}\n\nmodule.exports = exports.default;\nmodule.exports.default = exports.default;\n\n//# sourceURL=webpack:///./node_modules/validator/lib/isHexColor.js?");
/***/ }),
/***/ "./node_modules/validator/lib/isHexadecimal.js":
/*!*****************************************************!*\
!*** ./node_modules/validator/lib/isHexadecimal.js ***!
\*****************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
eval("\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = isHexadecimal;\n\nvar _assertString = _interopRequireDefault(__webpack_require__(/*! ./util/assertString */ \"./node_modules/validator/lib/util/assertString.js\"));\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\nvar hexadecimal = /^(0x|0h)?[0-9A-F]+$/i;\n\nfunction isHexadecimal(str) {\n (0, _assertString.default)(str);\n return hexadecimal.test(str);\n}\n\nmodule.exports = exports.default;\nmodule.exports.default = exports.default;\n\n//# sourceURL=webpack:///./node_modules/validator/lib/isHexadecimal.js?");
/***/ }),
/***/ "./node_modules/validator/lib/isIBAN.js":
/*!**********************************************!*\
!*** ./node_modules/validator/lib/isIBAN.js ***!
\**********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
eval("\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = isIBAN;\n\nvar _assertString = _interopRequireDefault(__webpack_require__(/*! ./util/assertString */ \"./node_modules/validator/lib/util/assertString.js\"));\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\n/**\n * List of country codes with\n * corresponding IBAN regular expression\n * Reference: https://en.wikipedia.org/wiki/International_Bank_Account_Number\n */\nvar ibanRegexThroughCountryCode = {\n AD: /^(AD[0-9]{2})\\d{8}[A-Z0-9]{12}$/,\n AE: /^(AE[0-9]{2})\\d{3}\\d{16}$/,\n AL: /^(AL[0-9]{2})\\d{8}[A-Z0-9]{16}$/,\n AT: /^(AT[0-9]{2})\\d{16}$/,\n AZ: /^(AZ[0-9]{2})[A-Z0-9]{4}\\d{20}$/,\n BA: /^(BA[0-9]{2})\\d{16}$/,\n BE: /^(BE[0-9]{2})\\d{12}$/,\n BG: /^(BG[0-9]{2})[A-Z]{4}\\d{6}[A-Z0-9]{8}$/,\n BH: /^(BH[0-9]{2})[A-Z]{4}[A-Z0-9]{14}$/,\n BR: /^(BR[0-9]{2})\\d{23}[A-Z]{1}[A-Z0-9]{1}$/,\n BY: /^(BY[0-9]{2})[A-Z0-9]{4}\\d{20}$/,\n CH: /^(CH[0-9]{2})\\d{5}[A-Z0-9]{12}$/,\n CR: /^(CR[0-9]{2})\\d{18}$/,\n CY: /^(CY[0-9]{2})\\d{8}[A-Z0-9]{16}$/,\n CZ: /^(CZ[0-9]{2})\\d{20}$/,\n DE: /^(DE[0-9]{2})\\d{18}$/,\n DK: /^(DK[0-9]{2})\\d{14}$/,\n DO: /^(DO[0-9]{2})[A-Z]{4}\\d{20}$/,\n EE: /^(EE[0-9]{2})\\d{16}$/,\n ES: /^(ES[0-9]{2})\\d{20}$/,\n FI: /^(FI[0-9]{2})\\d{14}$/,\n FO: /^(FO[0-9]{2})\\d{14}$/,\n FR: /^(FR[0-9]{2})\\d{10}[A-Z0-9]{11}\\d{2}$/,\n GB: /^(GB[0-9]{2})[A-Z]{4}\\d{14}$/,\n GE: /^(GE[0-9]{2})[A-Z0-9]{2}\\d{16}$/,\n GI: /^(GI[0-9]{2})[A-Z]{4}[A-Z0-9]{15}$/,\n GL: /^(GL[0-9]{2})\\d{14}$/,\n GR: /^(GR[0-9]{2})\\d{7}[A-Z0-9]{16}$/,\n GT: /^(GT[0-9]{2})[A-Z0-9]{4}[A-Z0-9]{20}$/,\n HR: /^(HR[0-9]{2})\\d{17}$/,\n HU: /^(HU[0-9]{2})\\d{24}$/,\n IE: /^(IE[0-9]{2})[A-Z0-9]{4}\\d{14}$/,\n IL: /^(IL[0-9]{2})\\d{19}$/,\n IQ: /^(IQ[0-9]{2})[A-Z]{4}\\d{15}$/,\n IS: /^(IS[0-9]{2})\\d{22}$/,\n IT: /^(IT[0-9]{2})[A-Z]{1}\\d{10}[A-Z0-9]{12}$/,\n JO: /^(JO[0-9]{2})[A-Z]{4}\\d{22}$/,\n KW: /^(KW[0-9]{2})[A-Z]{4}[A-Z0-9]{22}$/,\n KZ: /^(KZ[0-9]{2})\\d{3}[A-Z0-9]{13}$/,\n LB: /^(LB[0-9]{2})\\d{4}[A-Z0-9]{20}$/,\n LC: /^(LC[0-9]{2})[A-Z]{4}[A-Z0-9]{24}$/,\n LI: /^(LI[0-9]{2})\\d{5}[A-Z0-9]{12}$/,\n LT: /^(LT[0-9]{2})\\d{16}$/,\n LU: /^(LU[0-9]{2})\\d{3}[A-Z0-9]{13}$/,\n LV: /^(LV[0-9]{2})[A-Z]{4}[A-Z0-9]{13}$/,\n MC: /^(MC[0-9]{2})\\d{10}[A-Z0-9]{11}\\d{2}$/,\n MD: /^(MD[0-9]{2})[A-Z0-9]{20}$/,\n ME: /^(ME[0-9]{2})\\d{18}$/,\n MK: /^(MK[0-9]{2})\\d{3}[A-Z0-9]{10}\\d{2}$/,\n MR: /^(MR[0-9]{2})\\d{23}$/,\n MT: /^(MT[0-9]{2})[A-Z]{4}\\d{5}[A-Z0-9]{18}$/,\n MU: /^(MU[0-9]{2})[A-Z]{4}\\d{19}[A-Z]{3}$/,\n NL: /^(NL[0-9]{2})[A-Z]{4}\\d{10}$/,\n NO: /^(NO[0-9]{2})\\d{11}$/,\n PK: /^(PK[0-9]{2})[A-Z0-9]{4}\\d{16}$/,\n PL: /^(PL[0-9]{2})\\d{24}$/,\n PS: /^(PS[0-9]{2})[A-Z0-9]{4}\\d{21}$/,\n PT: /^(PT[0-9]{2})\\d{21}$/,\n QA: /^(QA[0-9]{2})[A-Z]{4}[A-Z0-9]{21}$/,\n RO: /^(RO[0-9]{2})[A-Z]{4}[A-Z0-9]{16}$/,\n RS: /^(RS[0-9]{2})\\d{18}$/,\n SA: /^(SA[0-9]{2})\\d{2}[A-Z0-9]{18}$/,\n SC: /^(SC[0-9]{2})[A-Z]{4}\\d{20}[A-Z]{3}$/,\n SE: /^(SE[0-9]{2})\\d{20}$/,\n SI: /^(SI[0-9]{2})\\d{15}$/,\n SK: /^(SK[0-9]{2})\\d{20}$/,\n SM: /^(SM[0-9]{2})[A-Z]{1}\\d{10}[A-Z0-9]{12}$/,\n TL: /^(TL[0-9]{2})\\d{19}$/,\n TN: /^(TN[0-9]{2})\\d{20}$/,\n TR: /^(TR[0-9]{2})\\d{5}[A-Z0-9]{17}$/,\n UA: /^(UA[0-9]{2})\\d{6}[A-Z0-9]{19}$/,\n VA: /^(VA[0-9]{2})\\d{18}$/,\n VG: /^(VG[0-9]{2})[A-Z0-9]{4}\\d{16}$/,\n XK: /^(XK[0-9]{2})\\d{16}$/\n};\n/**\n * Check whether string has correct universal IBAN format\n * The IBAN consists of up to 34 alphanumeric characters, as follows:\n * Country Code using ISO 3166-1 alpha-2, two letters\n * check digits, two digits and\n * Basic Bank Account Number (BBAN), up to 30 alphanumeric characters.\n * NOTE: Permitted IBAN characters are: digits [0-9] and the 26 latin alphabetic [A-Z]\n *\n * @param {string} str - string under validation\n * @return {boolean}\n */\n\nfunction hasValidIbanFormat(str) {\n // Strip white spaces and hyphens\n var strippedStr = str.replace(/[\\s\\-]+/gi, '').toUpperCase();\n var isoCountryCode = strippedStr.slice(0, 2).toUpperCase();\n return isoCountryCode in ibanRegexThroughCountryCode && ibanRegexThroughCountryCode[isoCountryCode].test(strippedStr);\n}\n/**\n * Check whether string has valid IBAN Checksum\n * by performing basic mod-97 operation and\n * the remainder should equal 1\n * -- Start by rearranging the IBAN by moving the four initial characters to the end of the string\n * -- Replace each letter in the string with two digits, A -> 10, B = 11, Z = 35\n * -- Interpret the string as a decimal integer and\n * -- compute the remainder on division by 97 (mod 97)\n * Reference: https://en.wikipedia.org/wiki/International_Bank_Account_Number\n *\n * @param {string} str\n * @return {boolean}\n */\n\n\nfunction hasValidIbanChecksum(str) {\n var strippedStr = str.replace(/[^A-Z0-9]+/gi, '').toUpperCase(); // Keep only digits and A-Z latin alphabetic\n\n var rearranged = strippedStr.slice(4) + strippedStr.slice(0, 4);\n var alphaCapsReplacedWithDigits = rearranged.replace(/[A-Z]/g, function (char) {\n return char.charCodeAt(0) - 55;\n });\n var remainder = alphaCapsReplacedWithDigits.match(/\\d{1,7}/g).reduce(function (acc, value) {\n return Number(acc + value) % 97;\n }, '');\n return remainder === 1;\n}\n\nfunction isIBAN(str) {\n (0, _assertString.default)(str);\n return hasValidIbanFormat(str) && hasValidIbanChecksum(str);\n}\n\nmodule.exports = exports.default;\nmodule.exports.default = exports.default;\n\n//# sourceURL=webpack:///./node_modules/validator/lib/isIBAN.js?");
/***/ }),
/***/ "./node_modules/validator/lib/isIP.js":
/*!********************************************!*\
!*** ./node_modules/validator/lib/isIP.js ***!
\********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
eval("\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = isIP;\n\nvar _assertString = _interopRequireDefault(__webpack_require__(/*! ./util/assertString */ \"./node_modules/validator/lib/util/assertString.js\"));\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\n/**\n11.3. Examples\n\n The following addresses\n\n fe80::1234 (on the 1st link of the node)\n ff02::5678 (on the 5th link of the node)\n ff08::9abc (on the 10th organization of the node)\n\n would be represented as follows:\n\n fe80::1234%1\n ff02::5678%5\n ff08::9abc%10\n\n (Here we assume a natural translation from a zone index to the\n <zone_id> part, where the Nth zone of any scope is translated into\n \"N\".)\n\n If we use interface names as <zone_id>, those addresses could also be\n represented as follows:\n\n fe80::1234%ne0\n ff02::5678%pvc1.3\n ff08::9abc%interface10\n\n where the interface \"ne0\" belongs to the 1st link, \"pvc1.3\" belongs\n to the 5th link, and \"interface10\" belongs to the 10th organization.\n * * */\nvar ipv4Maybe = /^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$/;\nvar ipv6Block = /^[0-9A-F]{1,4}$/i;\n\nfunction isIP(str) {\n var version = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : '';\n (0, _assertString.default)(str);\n version = String(version);\n\n if (!version) {\n return isIP(str, 4) || isIP(str, 6);\n } else if (version === '4') {\n if (!ipv4Maybe.test(str)) {\n return false;\n }\n\n var parts = str.split('.').sort(function (a, b) {\n return a - b;\n });\n return parts[3] <= 255;\n } else if (version === '6') {\n var addressAndZone = [str]; // ipv6 addresses could have scoped architecture\n // according to https://tools.ietf.org/html/rfc4007#section-11\n\n if (str.includes('%')) {\n addressAndZone = str.split('%');\n\n if (addressAndZone.length !== 2) {\n // it must be just two parts\n return false;\n }\n\n if (!addressAndZone[0].includes(':')) {\n // the first part must be the address\n return false;\n }\n\n if (addressAndZone[1] === '') {\n // the second part must not be empty\n return false;\n }\n }\n\n var blocks = addressAndZone[0].split(':');\n var foundOmissionBlock = false; // marker to indicate ::\n // At least some OS accept the last 32 bits of an IPv6 address\n // (i.e. 2 of the blocks) in IPv4 notation, and RFC 3493 says\n // that '::ffff:a.b.c.d' is valid for IPv4-mapped IPv6 addresses,\n // and '::a.b.c.d' is deprecated, but also valid.\n\n var foundIPv4TransitionBlock = isIP(blocks[blocks.length - 1], 4);\n var expectedNumberOfBlocks = foundIPv4TransitionBlock ? 7 : 8;\n\n if (blocks.length > expectedNumberOfBlocks) {\n return false;\n } // initial or final ::\n\n\n if (str === '::') {\n return true;\n } else if (str.substr(0, 2) === '::') {\n blocks.shift();\n blocks.shift();\n foundOmissionBlock = true;\n } else if (str.substr(str.length - 2) === '::') {\n blocks.pop();\n blocks.pop();\n foundOmissionBlock = true;\n }\n\n for (var i = 0; i < blocks.length; ++i) {\n // test for a :: which can not be at the string start/end\n // since those cases have been handled above\n if (blocks[i] === '' && i > 0 && i < blocks.length - 1) {\n if (foundOmissionBlock) {\n return false; // multiple :: in address\n }\n\n foundOmissionBlock = true;\n } else if (foundIPv4TransitionBlock && i === blocks.length - 1) {// it has been checked before that the last\n // block is a valid IPv4 address\n } else if (!ipv6Block.test(blocks[i])) {\n return false;\n }\n }\n\n if (foundOmissionBlock) {\n return blocks.length >= 1;\n }\n\n return blocks.length === expectedNumberOfBlocks;\n }\n\n return false;\n}\n\nmodule.exports = exports.default;\nmodule.exports.default = exports.default;\n\n//# sourceURL=webpack:///./node_modules/validator/lib/isIP.js?");
/***/ }),
/***/ "./node_modules/validator/lib/isIPRange.js":
/*!*************************************************!*\
!*** ./node_modules/validator/lib/isIPRange.js ***!
\*************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
eval("\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = isIPRange;\n\nvar _assertString = _interopRequireDefault(__webpack_require__(/*! ./util/assertString */ \"./node_modules/validator/lib/util/assertString.js\"));\n\nvar _isIP = _interopRequireDefault(__webpack_require__(/*! ./isIP */ \"./node_modules/validator/lib/isIP.js\"));\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\nvar subnetMaybe = /^\\d{1,2}$/;\n\nfunction isIPRange(str) {\n (0, _assertString.default)(str);\n var parts = str.split('/'); // parts[0] -> ip, parts[1] -> subnet\n\n if (parts.length !== 2) {\n return false;\n }\n\n if (!subnetMaybe.test(parts[1])) {\n return false;\n } // Disallow preceding 0 i.e. 01, 02, ...\n\n\n if (parts[1].length > 1 && parts[1].startsWith('0')) {\n return false;\n }\n\n return (0, _isIP.default)(parts[0], 4) && parts[1] <= 32 && parts[1] >= 0;\n}\n\nmodule.exports = exports.default;\nmodule.exports.default = exports.default;\n\n//# sourceURL=webpack:///./node_modules/validator/lib/isIPRange.js?");
/***/ }),
/***/ "./node_modules/validator/lib/isISBN.js":
/*!**********************************************!*\
!*** ./node_modules/validator/lib/isISBN.js ***!
\**********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
eval("\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = isISBN;\n\nvar _assertString = _interopRequireDefault(__webpack_require__(/*! ./util/assertString */ \"./node_modules/validator/lib/util/assertString.js\"));\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\nvar isbn10Maybe = /^(?:[0-9]{9}X|[0-9]{10})$/;\nvar isbn13Maybe = /^(?:[0-9]{13})$/;\nvar factor = [1, 3];\n\nfunction isISBN(str) {\n var version = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : '';\n (0, _assertString.default)(str);\n version = String(version);\n\n if (!version) {\n return isISBN(str, 10) || isISBN(str, 13);\n }\n\n var sanitized = str.replace(/[\\s-]+/g, '');\n var checksum = 0;\n var i;\n\n if (version === '10') {\n if (!isbn10Maybe.test(sanitized)) {\n return false;\n }\n\n for (i = 0; i < 9; i++) {\n checksum += (i + 1) * sanitized.charAt(i);\n }\n\n if (sanitized.charAt(9) === 'X') {\n checksum += 10 * 10;\n } else {\n checksum += 10 * sanitized.charAt(9);\n }\n\n if (checksum % 11 === 0) {\n return !!sanitized;\n }\n } else if (version === '13') {\n if (!isbn13Maybe.test(sanitized)) {\n return false;\n }\n\n for (i = 0; i < 12; i++) {\n checksum += factor[i % 2] * sanitized.charAt(i);\n }\n\n if (sanitized.charAt(12) - (10 - checksum % 10) % 10 === 0) {\n return !!sanitized;\n }\n }\n\n return false;\n}\n\nmodule.exports = exports.default;\nmodule.exports.default = exports.default;\n\n//# sourceURL=webpack:///./node_modules/validator/lib/isISBN.js?");
/***/ }),
/***/ "./node_modules/validator/lib/isISIN.js":
/*!**********************************************!*\
!*** ./node_modules/validator/lib/isISIN.js ***!
\**********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
eval("\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = isISIN;\n\nvar _assertString = _interopRequireDefault(__webpack_require__(/*! ./util/assertString */ \"./node_modules/validator/lib/util/assertString.js\"));\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\nvar isin = /^[A-Z]{2}[0-9A-Z]{9}[0-9]$/;\n\nfunction isISIN(str) {\n (0, _assertString.default)(str);\n\n if (!isin.test(str)) {\n return false;\n }\n\n var checksumStr = str.replace(/[A-Z]/g, function (character) {\n return parseInt(character, 36);\n });\n var sum = 0;\n var digit;\n var tmpNum;\n var shouldDouble = true;\n\n for (var i = checksumStr.length - 2; i >= 0; i--) {\n digit = checksumStr.substring(i, i + 1);\n tmpNum = parseInt(digit, 10);\n\n if (shouldDouble) {\n tmpNum *= 2;\n\n if (tmpNum >= 10) {\n sum += tmpNum + 1;\n } else {\n sum += tmpNum;\n }\n } else {\n sum += tmpNum;\n }\n\n shouldDouble = !shouldDouble;\n }\n\n return parseInt(str.substr(str.length - 1), 10) === (10000 - sum) % 10;\n}\n\nmodule.exports = exports.default;\nmodule.exports.default = exports.default;\n\n//# sourceURL=webpack:///./node_modules/validator/lib/isISIN.js?");
/***/ }),
/***/ "./node_modules/validator/lib/isISO31661Alpha2.js":
/*!********************************************************!*\
!*** ./node_modules/validator/lib/isISO31661Alpha2.js ***!
\********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
eval("\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = isISO31661Alpha2;\n\nvar _assertString = _interopRequireDefault(__webpack_require__(/*! ./util/assertString */ \"./node_modules/validator/lib/util/assertString.js\"));\n\nvar _includes = _interopRequireDefault(__webpack_require__(/*! ./util/includes */ \"./node_modules/validator/lib/util/includes.js\"));\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\n// from https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2\nvar validISO31661Alpha2CountriesCodes = ['AD', 'AE', 'AF', 'AG', 'AI', 'AL', 'AM', 'AO', 'AQ', 'AR', 'AS', 'AT', 'AU', 'AW', 'AX', 'AZ', 'BA', 'BB', 'BD', 'BE', 'BF', 'BG', 'BH', 'BI', 'BJ', 'BL', 'BM', 'BN', 'BO', 'BQ', 'BR', 'BS', 'BT', 'BV', 'BW', 'BY', 'BZ', 'CA', 'CC', 'CD', 'CF', 'CG', 'CH', 'CI', 'CK', 'CL', 'CM', 'CN', 'CO', 'CR', 'CU', 'CV', 'CW', 'CX', 'CY', 'CZ', 'DE', 'DJ', 'DK', 'DM', 'DO', 'DZ', 'EC', 'EE', 'EG', 'EH', 'ER', 'ES', 'ET', 'FI', 'FJ', 'FK', 'FM', 'FO', 'FR', 'GA', 'GB', 'GD', 'GE', 'GF', 'GG', 'GH', 'GI', 'GL', 'GM', 'GN', 'GP', 'GQ', 'GR', 'GS', 'GT', 'GU', 'GW', 'GY', 'HK', 'HM', 'HN', 'HR', 'HT', 'HU', 'ID', 'IE', 'IL', 'IM', 'IN', 'IO', 'IQ', 'IR', 'IS', 'IT', 'JE', 'JM', 'JO', 'JP', 'KE', 'KG', 'KH', 'KI', 'KM', 'KN', 'KP', 'KR', 'KW', 'KY', 'KZ', 'LA', 'LB', 'LC', 'LI', 'LK', 'LR', 'LS', 'LT', 'LU', 'LV', 'LY', 'MA', 'MC', 'MD', 'ME', 'MF', 'MG', 'MH', 'MK', 'ML', 'MM', 'MN', 'MO', 'MP', 'MQ', 'MR', 'MS', 'MT', 'MU', 'MV', 'MW', 'MX', 'MY', 'MZ', 'NA', 'NC', 'NE', 'NF', 'NG', 'NI', 'NL', 'NO', 'NP', 'NR', 'NU', 'NZ', 'OM', 'PA', 'PE', 'PF', 'PG', 'PH', 'PK', 'PL', 'PM', 'PN', 'PR', 'PS', 'PT', 'PW', 'PY', 'QA', 'RE', 'RO', 'RS', 'RU', 'RW', 'SA', 'SB', 'SC', 'SD', 'SE', 'SG', 'SH', 'SI', 'SJ', 'SK', 'SL', 'SM', 'SN', 'SO', 'SR', 'SS', 'ST', 'SV', 'SX', 'SY', 'SZ', 'TC', 'TD', 'TF', 'TG', 'TH', 'TJ', 'TK', 'TL', 'TM', 'TN', 'TO', 'TR', 'TT', 'TV', 'TW', 'TZ', 'UA', 'UG', 'UM', 'US', 'UY', 'UZ', 'VA', 'VC', 'VE', 'VG', 'VI', 'VN', 'VU', 'WF', 'WS', 'YE', 'YT', 'ZA', 'ZM', 'ZW'];\n\nfunction isISO31661Alpha2(str) {\n (0, _assertString.default)(str);\n return (0, _includes.default)(validISO31661Alpha2CountriesCodes, str.toUpperCase());\n}\n\nmodule.exports = exports.default;\nmodule.exports.default = exports.default;\n\n//# sourceURL=webpack:///./node_modules/validator/lib/isISO31661Alpha2.js?");
/***/ }),
/***/ "./node_modules/validator/lib/isISO31661Alpha3.js":
/*!********************************************************!*\
!*** ./node_modules/validator/lib/isISO31661Alpha3.js ***!
\********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
eval("\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = isISO31661Alpha3;\n\nvar _assertString = _interopRequireDefault(__webpack_require__(/*! ./util/assertString */ \"./node_modules/validator/lib/util/assertString.js\"));\n\nvar _includes = _interopRequireDefault(__webpack_require__(/*! ./util/includes */ \"./node_modules/validator/lib/util/includes.js\"));\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\n// from https://en.wikipedia.org/wiki/ISO_3166-1_alpha-3\nvar validISO31661Alpha3CountriesCodes = ['AFG', 'ALA', 'ALB', 'DZA', 'ASM', 'AND', 'AGO', 'AIA', 'ATA', 'ATG', 'ARG', 'ARM', 'ABW', 'AUS', 'AUT', 'AZE', 'BHS', 'BHR', 'BGD', 'BRB', 'BLR', 'BEL', 'BLZ', 'BEN', 'BMU', 'BTN', 'BOL', 'BES', 'BIH', 'BWA', 'BVT', 'BRA', 'IOT', 'BRN', 'BGR', 'BFA', 'BDI', 'KHM', 'CMR', 'CAN', 'CPV', 'CYM', 'CAF', 'TCD', 'CHL', 'CHN', 'CXR', 'CCK', 'COL', 'COM', 'COG', 'COD', 'COK', 'CRI', 'CIV', 'HRV', 'CUB', 'CUW', 'CYP', 'CZE', 'DNK', 'DJI', 'DMA', 'DOM', 'ECU', 'EGY', 'SLV', 'GNQ', 'ERI', 'EST', 'ETH', 'FLK', 'FRO', 'FJI', 'FIN', 'FRA', 'GUF', 'PYF', 'ATF', 'GAB', 'GMB', 'GEO', 'DEU', 'GHA', 'GIB', 'GRC', 'GRL', 'GRD', 'GLP', 'GUM', 'GTM', 'GGY', 'GIN', 'GNB', 'GUY', 'HTI', 'HMD', 'VAT', 'HND', 'HKG', 'HUN', 'ISL', 'IND', 'IDN', 'IRN', 'IRQ', 'IRL', 'IMN', 'ISR', 'ITA', 'JAM', 'JPN', 'JEY', 'JOR', 'KAZ', 'KEN', 'KIR', 'PRK', 'KOR', 'KWT', 'KGZ', 'LAO', 'LVA', 'LBN', 'LSO', 'LBR', 'LBY', 'LIE', 'LTU', 'LUX', 'MAC', 'MKD', 'MDG', 'MWI', 'MYS', 'MDV', 'MLI', 'MLT', 'MHL', 'MTQ', 'MRT', 'MUS', 'MYT', 'MEX', 'FSM', 'MDA', 'MCO', 'MNG', 'MNE', 'MSR', 'MAR', 'MOZ', 'MMR', 'NAM', 'NRU', 'NPL', 'NLD', 'NCL', 'NZL', 'NIC', 'NER', 'NGA', 'NIU', 'NFK', 'MNP', 'NOR', 'OMN', 'PAK', 'PLW', 'PSE', 'PAN', 'PNG', 'PRY', 'PER', 'PHL', 'PCN', 'POL', 'PRT', 'PRI', 'QAT', 'REU', 'ROU', 'RUS', 'RWA', 'BLM', 'SHN', 'KNA', 'LCA', 'MAF', 'SPM', 'VCT', 'WSM', 'SMR', 'STP', 'SAU', 'SEN', 'SRB', 'SYC', 'SLE', 'SGP', 'SXM', 'SVK', 'SVN', 'SLB', 'SOM', 'ZAF', 'SGS', 'SSD', 'ESP', 'LKA', 'SDN', 'SUR', 'SJM', 'SWZ', 'SWE', 'CHE', 'SYR', 'TWN', 'TJK', 'TZA', 'THA', 'TLS', 'TGO', 'TKL', 'TON', 'TTO', 'TUN', 'TUR', 'TKM', 'TCA', 'TUV', 'UGA', 'UKR', 'ARE', 'GBR', 'USA', 'UMI', 'URY', 'UZB', 'VUT', 'VEN', 'VNM', 'VGB', 'VIR', 'WLF', 'ESH', 'YEM', 'ZMB', 'ZWE'];\n\nfunction isISO31661Alpha3(str) {\n (0, _assertString.default)(str);\n return (0, _includes.default)(validISO31661Alpha3CountriesCodes, str.toUpperCase());\n}\n\nmodule.exports = exports.default;\nmodule.exports.default = exports.default;\n\n//# sourceURL=webpack:///./node_modules/validator/lib/isISO31661Alpha3.js?");
/***/ }),
/***/ "./node_modules/validator/lib/isISO8601.js":
/*!*************************************************!*\
!*** ./node_modules/validator/lib/isISO8601.js ***!
\*************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
eval("\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = isISO8601;\n\nvar _assertString = _interopRequireDefault(__webpack_require__(/*! ./util/assertString */ \"./node_modules/validator/lib/util/assertString.js\"));\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\n/* eslint-disable max-len */\n// from http://goo.gl/0ejHHW\nvar iso8601 = /^([\\+-]?\\d{4}(?!\\d{2}\\b))((-?)((0[1-9]|1[0-2])(\\3([12]\\d|0[1-9]|3[01]))?|W([0-4]\\d|5[0-3])(-?[1-7])?|(00[1-9]|0[1-9]\\d|[12]\\d{2}|3([0-5]\\d|6[1-6])))([T\\s]((([01]\\d|2[0-3])((:?)[0-5]\\d)?|24:?00)([\\.,]\\d+(?!:))?)?(\\17[0-5]\\d([\\.,]\\d+)?)?([zZ]|([\\+-])([01]\\d|2[0-3]):?([0-5]\\d)?)?)?)?$/;\n/* eslint-enable max-len */\n\nvar isValidDate = function isValidDate(str) {\n // str must have passed the ISO8601 check\n // this check is meant to catch invalid dates\n // like 2009-02-31\n // first check for ordinal dates\n var ordinalMatch = str.match(/^(\\d{4})-?(\\d{3})([ T]{1}\\.*|$)/);\n\n if (ordinalMatch) {\n var oYear = Number(ordinalMatch[1]);\n var oDay = Number(ordinalMatch[2]); // if is leap year\n\n if (oYear % 4 === 0 && oYear % 100 !== 0 || oYear % 400 === 0) return oDay <= 366;\n return oDay <= 365;\n }\n\n var match = str.match(/(\\d{4})-?(\\d{0,2})-?(\\d*)/).map(Number);\n var year = match[1];\n var month = match[2];\n var day = match[3];\n var monthString = month ? \"0\".concat(month).slice(-2) : month;\n var dayString = day ? \"0\".concat(day).slice(-2) : day; // create a date object and compare\n\n var d = new Date(\"\".concat(year, \"-\").concat(monthString || '01', \"-\").concat(dayString || '01'));\n\n if (month && day) {\n return d.getUTCFullYear() === year && d.getUTCMonth() + 1 === month && d.getUTCDate() === day;\n }\n\n return true;\n};\n\nfunction isISO8601(str, options) {\n (0, _assertString.default)(str);\n var check = iso8601.test(str);\n if (!options) return check;\n if (check && options.strict) return isValidDate(str);\n return check;\n}\n\nmodule.exports = exports.default;\nmodule.exports.default = exports.default;\n\n//# sourceURL=webpack:///./node_modules/validator/lib/isISO8601.js?");
/***/ }),
/***/ "./node_modules/validator/lib/isISRC.js":
/*!**********************************************!*\
!*** ./node_modules/validator/lib/isISRC.js ***!
\**********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
eval("\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = isISRC;\n\nvar _assertString = _interopRequireDefault(__webpack_require__(/*! ./util/assertString */ \"./node_modules/validator/lib/util/assertString.js\"));\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\n// see http://isrc.ifpi.org/en/isrc-standard/code-syntax\nvar isrc = /^[A-Z]{2}[0-9A-Z]{3}\\d{2}\\d{5}$/;\n\nfunction isISRC(str) {\n (0, _assertString.default)(str);\n return isrc.test(str);\n}\n\nmodule.exports = exports.default;\nmodule.exports.default = exports.default;\n\n//# sourceURL=webpack:///./node_modules/validator/lib/isISRC.js?");
/***/ }),
/***/ "./node_modules/validator/lib/isISSN.js":
/*!**********************************************!*\
!*** ./node_modules/validator/lib/isISSN.js ***!
\**********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
eval("\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = isISSN;\n\nvar _assertString = _interopRequireDefault(__webpack_require__(/*! ./util/assertString */ \"./node_modules/validator/lib/util/assertString.js\"));\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\nvar issn = '^\\\\d{4}-?\\\\d{3}[\\\\dX]$';\n\nfunction isISSN(str) {\n var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};\n (0, _assertString.default)(str);\n var testIssn = issn;\n testIssn = options.require_hyphen ? testIssn.replace('?', '') : testIssn;\n testIssn = options.case_sensitive ? new RegExp(testIssn) : new RegExp(testIssn, 'i');\n\n if (!testIssn.test(str)) {\n return false;\n }\n\n var digits = str.replace('-', '').toUpperCase();\n var checksum = 0;\n\n for (var i = 0; i < digits.length; i++) {\n var digit = digits[i];\n checksum += (digit === 'X' ? 10 : +digit) * (8 - i);\n }\n\n return checksum % 11 === 0;\n}\n\nmodule.exports = exports.default;\nmodule.exports.default = exports.default;\n\n//# sourceURL=webpack:///./node_modules/validator/lib/isISSN.js?");
/***/ }),
/***/ "./node_modules/validator/lib/isIdentityCard.js":
/*!******************************************************!*\
!*** ./node_modules/validator/lib/isIdentityCard.js ***!
\******************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
eval("\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = isIdentityCard;\n\nvar _assertString = _interopRequireDefault(__webpack_require__(/*! ./util/assertString */ \"./node_modules/validator/lib/util/assertString.js\"));\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\nvar validators = {\n ES: function ES(str) {\n (0, _assertString.default)(str);\n var DNI = /^[0-9X-Z][0-9]{7}[TRWAGMYFPDXBNJZSQVHLCKE]$/;\n var charsValue = {\n X: 0,\n Y: 1,\n Z: 2\n };\n var controlDigits = ['T', 'R', 'W', 'A', 'G', 'M', 'Y', 'F', 'P', 'D', 'X', 'B', 'N', 'J', 'Z', 'S', 'Q', 'V', 'H', 'L', 'C', 'K', 'E']; // sanitize user input\n\n var sanitized = str.trim().toUpperCase(); // validate the data structure\n\n if (!DNI.test(sanitized)) {\n return false;\n } // validate the control digit\n\n\n var number = sanitized.slice(0, -1).replace(/[X,Y,Z]/g, function (char) {\n return charsValue[char];\n });\n return sanitized.endsWith(controlDigits[number % 23]);\n },\n 'he-IL': function heIL(str) {\n var DNI = /^\\d{9}$/; // sanitize user input\n\n var sanitized = str.trim(); // validate the data structure\n\n if (!DNI.test(sanitized)) {\n return false;\n }\n\n var id = sanitized;\n var sum = 0,\n incNum;\n\n for (var i = 0; i < id.length; i++) {\n incNum = Number(id[i]) * (i % 2 + 1); // Multiply number by 1 or 2\n\n sum += incNum > 9 ? incNum - 9 : incNum; // Sum the digits up and add to total\n }\n\n return sum % 10 === 0;\n },\n 'zh-TW': function zhTW(str) {\n var ALPHABET_CODES = {\n A: 10,\n B: 11,\n C: 12,\n D: 13,\n E: 14,\n F: 15,\n G: 16,\n H: 17,\n I: 34,\n J: 18,\n K: 19,\n L: 20,\n M: 21,\n N: 22,\n O: 35,\n P: 23,\n Q: 24,\n R: 25,\n S: 26,\n T: 27,\n U: 28,\n V: 29,\n W: 32,\n X: 30,\n Y: 31,\n Z: 33\n };\n var sanitized = str.trim().toUpperCase();\n if (!/^[A-Z][0-9]{9}$/.test(sanitized)) return false;\n return Array.from(sanitized).reduce(function (sum, number, index) {\n if (index === 0) {\n var code = ALPHABET_CODES[number];\n return code % 10 * 9 + Math.floor(code / 10);\n }\n\n if (index === 9) {\n return (10 - sum % 10 - Number(number)) % 10 === 0;\n }\n\n return sum + Number(number) * (9 - index);\n }, 0);\n }\n};\n\nfunction isIdentityCard(str, locale) {\n (0, _assertString.default)(str);\n\n if (locale in validators) {\n return validators[locale](str);\n } else if (locale === 'any') {\n for (var key in validators) {\n // https://github.com/gotwarlost/istanbul/blob/master/ignoring-code-for-coverage.md#ignoring-code-for-coverage-purposes\n // istanbul ignore else\n if (validators.hasOwnProperty(key)) {\n var validator = validators[key];\n\n if (validator(str)) {\n return true;\n }\n }\n }\n\n return false;\n }\n\n throw new Error(\"Invalid locale '\".concat(locale, \"'\"));\n}\n\nmodule.exports = exports.default;\nmodule.exports.default = exports.default;\n\n//# sourceURL=webpack:///./node_modules/validator/lib/isIdentityCard.js?");
/***/ }),
/***/ "./node_modules/validator/lib/isIn.js":
/*!********************************************!*\
!*** ./node_modules/validator/lib/isIn.js ***!
\********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
eval("\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = isIn;\n\nvar _assertString = _interopRequireDefault(__webpack_require__(/*! ./util/assertString */ \"./node_modules/validator/lib/util/assertString.js\"));\n\nvar _toString = _interopRequireDefault(__webpack_require__(/*! ./util/toString */ \"./node_modules/validator/lib/util/toString.js\"));\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\nfunction _typeof(obj) { \"@babel/helpers - typeof\"; if (typeof Symbol === \"function\" && typeof Symbol.iterator === \"symbol\") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === \"function\" && obj.constructor === Symbol && obj !== Symbol.prototype ? \"symbol\" : typeof obj; }; } return _typeof(obj); }\n\nfunction isIn(str, options) {\n (0, _assertString.default)(str);\n var i;\n\n if (Object.prototype.toString.call(options) === '[object Array]') {\n var array = [];\n\n for (i in options) {\n // https://github.com/gotwarlost/istanbul/blob/master/ignoring-code-for-coverage.md#ignoring-code-for-coverage-purposes\n // istanbul ignore else\n if ({}.hasOwnProperty.call(options, i)) {\n array[i] = (0, _toString.default)(options[i]);\n }\n }\n\n return array.indexOf(str) >= 0;\n } else if (_typeof(options) === 'object') {\n return options.hasOwnProperty(str);\n } else if (options && typeof options.indexOf === 'function') {\n return options.indexOf(str) >= 0;\n }\n\n return false;\n}\n\nmodule.exports = exports.default;\nmodule.exports.default = exports.default;\n\n//# sourceURL=webpack:///./node_modules/validator/lib/isIn.js?");
/***/ }),
/***/ "./node_modules/validator/lib/isInt.js":
/*!*********************************************!*\
!*** ./node_modules/validator/lib/isInt.js ***!
\*********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
eval("\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = isInt;\n\nvar _assertString = _interopRequireDefault(__webpack_require__(/*! ./util/assertString */ \"./node_modules/validator/lib/util/assertString.js\"));\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\nvar int = /^(?:[-+]?(?:0|[1-9][0-9]*))$/;\nvar intLeadingZeroes = /^[-+]?[0-9]+$/;\n\nfunction isInt(str, options) {\n (0, _assertString.default)(str);\n options = options || {}; // Get the regex to use for testing, based on whether\n // leading zeroes are allowed or not.\n\n var regex = options.hasOwnProperty('allow_leading_zeroes') && !options.allow_leading_zeroes ? int : intLeadingZeroes; // Check min/max/lt/gt\n\n var minCheckPassed = !options.hasOwnProperty('min') || str >= options.min;\n var maxCheckPassed = !options.hasOwnProperty('max') || str <= options.max;\n var ltCheckPassed = !options.hasOwnProperty('lt') || str < options.lt;\n var gtCheckPassed = !options.hasOwnProperty('gt') || str > options.gt;\n return regex.test(str) && minCheckPassed && maxCheckPassed && ltCheckPassed && gtCheckPassed;\n}\n\nmodule.exports = exports.default;\nmodule.exports.default = exports.default;\n\n//# sourceURL=webpack:///./node_modules/validator/lib/isInt.js?");
/***/ }),
/***/ "./node_modules/validator/lib/isJSON.js":
/*!**********************************************!*\
!*** ./node_modules/validator/lib/isJSON.js ***!
\**********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
eval("\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = isJSON;\n\nvar _assertString = _interopRequireDefault(__webpack_require__(/*! ./util/assertString */ \"./node_modules/validator/lib/util/assertString.js\"));\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\nfunction _typeof(obj) { \"@babel/helpers - typeof\"; if (typeof Symbol === \"function\" && typeof Symbol.iterator === \"symbol\") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === \"function\" && obj.constructor === Symbol && obj !== Symbol.prototype ? \"symbol\" : typeof obj; }; } return _typeof(obj); }\n\nfunction isJSON(str) {\n (0, _assertString.default)(str);\n\n try {\n var obj = JSON.parse(str);\n return !!obj && _typeof(obj) === 'object';\n } catch (e) {\n /* ignore */\n }\n\n return false;\n}\n\nmodule.exports = exports.default;\nmodule.exports.default = exports.default;\n\n//# sourceURL=webpack:///./node_modules/validator/lib/isJSON.js?");
/***/ }),
/***/ "./node_modules/validator/lib/isJWT.js":
/*!*********************************************!*\
!*** ./node_modules/validator/lib/isJWT.js ***!
\*********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
eval("\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = isJWT;\n\nvar _assertString = _interopRequireDefault(__webpack_require__(/*! ./util/assertString */ \"./node_modules/validator/lib/util/assertString.js\"));\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\nvar jwt = /^([A-Za-z0-9\\-_~+\\/]+[=]{0,2})\\.([A-Za-z0-9\\-_~+\\/]+[=]{0,2})(?:\\.([A-Za-z0-9\\-_~+\\/]+[=]{0,2}))?$/;\n\nfunction isJWT(str) {\n (0, _assertString.default)(str);\n return jwt.test(str);\n}\n\nmodule.exports = exports.default;\nmodule.exports.default = exports.default;\n\n//# sourceURL=webpack:///./node_modules/validator/lib/isJWT.js?");
/***/ }),
/***/ "./node_modules/validator/lib/isLatLong.js":
/*!*************************************************!*\
!*** ./node_modules/validator/lib/isLatLong.js ***!
\*************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
eval("\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = _default;\n\nvar _assertString = _interopRequireDefault(__webpack_require__(/*! ./util/assertString */ \"./node_modules/validator/lib/util/assertString.js\"));\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\nvar lat = /^\\(?[+-]?(90(\\.0+)?|[1-8]?\\d(\\.\\d+)?)$/;\nvar long = /^\\s?[+-]?(180(\\.0+)?|1[0-7]\\d(\\.\\d+)?|\\d{1,2}(\\.\\d+)?)\\)?$/;\n\nfunction _default(str) {\n (0, _assertString.default)(str);\n if (!str.includes(',')) return false;\n var pair = str.split(',');\n if (pair[0].startsWith('(') && !pair[1].endsWith(')') || pair[1].endsWith(')') && !pair[0].startsWith('(')) return false;\n return lat.test(pair[0]) && long.test(pair[1]);\n}\n\nmodule.exports = exports.default;\nmodule.exports.default = exports.default;\n\n//# sourceURL=webpack:///./node_modules/validator/lib/isLatLong.js?");
/***/ }),
/***/ "./node_modules/validator/lib/isLength.js":
/*!************************************************!*\
!*** ./node_modules/validator/lib/isLength.js ***!
\************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
eval("\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = isLength;\n\nvar _assertString = _interopRequireDefault(__webpack_require__(/*! ./util/assertString */ \"./node_modules/validator/lib/util/assertString.js\"));\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\nfunction _typeof(obj) { \"@babel/helpers - typeof\"; if (typeof Symbol === \"function\" && typeof Symbol.iterator === \"symbol\") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === \"function\" && obj.constructor === Symbol && obj !== Symbol.prototype ? \"symbol\" : typeof obj; }; } return _typeof(obj); }\n\n/* eslint-disable prefer-rest-params */\nfunction isLength(str, options) {\n (0, _assertString.default)(str);\n var min;\n var max;\n\n if (_typeof(options) === 'object') {\n min = options.min || 0;\n max = options.max;\n } else {\n // backwards compatibility: isLength(str, min [, max])\n min = arguments[1] || 0;\n max = arguments[2];\n }\n\n var surrogatePairs = str.match(/[\\uD800-\\uDBFF][\\uDC00-\\uDFFF]/g) || [];\n var len = str.length - surrogatePairs.length;\n return len >= min && (typeof max === 'undefined' || len <= max);\n}\n\nmodule.exports = exports.default;\nmodule.exports.default = exports.default;\n\n//# sourceURL=webpack:///./node_modules/validator/lib/isLength.js?");
/***/ }),
/***/ "./node_modules/validator/lib/isLocale.js":
/*!************************************************!*\
!*** ./node_modules/validator/lib/isLocale.js ***!
\************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
eval("\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = isLocale;\n\nvar _assertString = _interopRequireDefault(__webpack_require__(/*! ./util/assertString */ \"./node_modules/validator/lib/util/assertString.js\"));\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\nvar localeReg = /^[A-z]{2,4}([_-]([A-z]{4}|[\\d]{3}))?([_-]([A-z]{2}|[\\d]{3}))?$/;\n\nfunction isLocale(str) {\n (0, _assertString.default)(str);\n\n if (str === 'en_US_POSIX' || str === 'ca_ES_VALENCIA') {\n return true;\n }\n\n return localeReg.test(str);\n}\n\nmodule.exports = exports.default;\nmodule.exports.default = exports.default;\n\n//# sourceURL=webpack:///./node_modules/validator/lib/isLocale.js?");
/***/ }),
/***/ "./node_modules/validator/lib/isLowercase.js":
/*!***************************************************!*\
!*** ./node_modules/validator/lib/isLowercase.js ***!
\***************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
eval("\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = isLowercase;\n\nvar _assertString = _interopRequireDefault(__webpack_require__(/*! ./util/assertString */ \"./node_modules/validator/lib/util/assertString.js\"));\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\nfunction isLowercase(str) {\n (0, _assertString.default)(str);\n return str === str.toLowerCase();\n}\n\nmodule.exports = exports.default;\nmodule.exports.default = exports.default;\n\n//# sourceURL=webpack:///./node_modules/validator/lib/isLowercase.js?");
/***/ }),
/***/ "./node_modules/validator/lib/isMACAddress.js":
/*!****************************************************!*\
!*** ./node_modules/validator/lib/isMACAddress.js ***!
\****************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
eval("\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = isMACAddress;\n\nvar _assertString = _interopRequireDefault(__webpack_require__(/*! ./util/assertString */ \"./node_modules/validator/lib/util/assertString.js\"));\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\nvar macAddress = /^([0-9a-fA-F][0-9a-fA-F]:){5}([0-9a-fA-F][0-9a-fA-F])$/;\nvar macAddressNoColons = /^([0-9a-fA-F]){12}$/;\nvar macAddressWithHyphen = /^([0-9a-fA-F][0-9a-fA-F]-){5}([0-9a-fA-F][0-9a-fA-F])$/;\nvar macAddressWithSpaces = /^([0-9a-fA-F][0-9a-fA-F]\\s){5}([0-9a-fA-F][0-9a-fA-F])$/;\nvar macAddressWithDots = /^([0-9a-fA-F]{4}).([0-9a-fA-F]{4}).([0-9a-fA-F]{4})$/;\n\nfunction isMACAddress(str, options) {\n (0, _assertString.default)(str);\n\n if (options && options.no_colons) {\n return macAddressNoColons.test(str);\n }\n\n return macAddress.test(str) || macAddressWithHyphen.test(str) || macAddressWithSpaces.test(str) || macAddressWithDots.test(str);\n}\n\nmodule.exports = exports.default;\nmodule.exports.default = exports.default;\n\n//# sourceURL=webpack:///./node_modules/validator/lib/isMACAddress.js?");
/***/ }),
/***/ "./node_modules/validator/lib/isMD5.js":
/*!*********************************************!*\
!*** ./node_modules/validator/lib/isMD5.js ***!
\*********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
eval("\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = isMD5;\n\nvar _assertString = _interopRequireDefault(__webpack_require__(/*! ./util/assertString */ \"./node_modules/validator/lib/util/assertString.js\"));\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\nvar md5 = /^[a-f0-9]{32}$/;\n\nfunction isMD5(str) {\n (0, _assertString.default)(str);\n return md5.test(str);\n}\n\nmodule.exports = exports.default;\nmodule.exports.default = exports.default;\n\n//# sourceURL=webpack:///./node_modules/validator/lib/isMD5.js?");
/***/ }),
/***/ "./node_modules/validator/lib/isMagnetURI.js":
/*!***************************************************!*\
!*** ./node_modules/validator/lib/isMagnetURI.js ***!
\***************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
eval("\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = isMagnetURI;\n\nvar _assertString = _interopRequireDefault(__webpack_require__(/*! ./util/assertString */ \"./node_modules/validator/lib/util/assertString.js\"));\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\nvar magnetURI = /^magnet:\\?xt=urn:[a-z0-9]+:[a-z0-9]{32,40}&dn=.+&tr=.+$/i;\n\nfunction isMagnetURI(url) {\n (0, _assertString.default)(url);\n return magnetURI.test(url.trim());\n}\n\nmodule.exports = exports.default;\nmodule.exports.default = exports.default;\n\n//# sourceURL=webpack:///./node_modules/validator/lib/isMagnetURI.js?");
/***/ }),
/***/ "./node_modules/validator/lib/isMimeType.js":
/*!**************************************************!*\
!*** ./node_modules/validator/lib/isMimeType.js ***!
\**************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
eval("\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = isMimeType;\n\nvar _assertString = _interopRequireDefault(__webpack_require__(/*! ./util/assertString */ \"./node_modules/validator/lib/util/assertString.js\"));\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\n/*\n Checks if the provided string matches to a correct Media type format (MIME type)\n\n This function only checks is the string format follows the\n etablished rules by the according RFC specifications.\n This function supports 'charset' in textual media types\n (https://tools.ietf.org/html/rfc6657).\n\n This function does not check against all the media types listed\n by the IANA (https://www.iana.org/assignments/media-types/media-types.xhtml)\n because of lightness purposes : it would require to include\n all these MIME types in this librairy, which would weigh it\n significantly. This kind of effort maybe is not worth for the use that\n this function has in this entire librairy.\n\n More informations in the RFC specifications :\n - https://tools.ietf.org/html/rfc2045\n - https://tools.ietf.org/html/rfc2046\n - https://tools.ietf.org/html/rfc7231#section-3.1.1.1\n - https://tools.ietf.org/html/rfc7231#section-3.1.1.5\n*/\n// Match simple MIME types\n// NB :\n// Subtype length must not exceed 100 characters.\n// This rule does not comply to the RFC specs (what is the max length ?).\nvar mimeTypeSimple = /^(application|audio|font|image|message|model|multipart|text|video)\\/[a-zA-Z0-9\\.\\-\\+]{1,100}$/i; // eslint-disable-line max-len\n// Handle \"charset\" in \"text/*\"\n\nvar mimeTypeText = /^text\\/[a-zA-Z0-9\\.\\-\\+]{1,100};\\s?charset=(\"[a-zA-Z0-9\\.\\-\\+\\s]{0,70}\"|[a-zA-Z0-9\\.\\-\\+]{0,70})(\\s?\\([a-zA-Z0-9\\.\\-\\+\\s]{1,20}\\))?$/i; // eslint-disable-line max-len\n// Handle \"boundary\" in \"multipart/*\"\n\nvar mimeTypeMultipart = /^multipart\\/[a-zA-Z0-9\\.\\-\\+]{1,100}(;\\s?(boundary|charset)=(\"[a-zA-Z0-9\\.\\-\\+\\s]{0,70}\"|[a-zA-Z0-9\\.\\-\\+]{0,70})(\\s?\\([a-zA-Z0-9\\.\\-\\+\\s]{1,20}\\))?){0,2}$/i; // eslint-disable-line max-len\n\nfunction isMimeType(str) {\n (0, _assertString.default)(str);\n return mimeTypeSimple.test(str) || mimeTypeText.test(str) || mimeTypeMultipart.test(str);\n}\n\nmodule.exports = exports.default;\nmodule.exports.default = exports.default;\n\n//# sourceURL=webpack:///./node_modules/validator/lib/isMimeType.js?");
/***/ }),
/***/ "./node_modules/validator/lib/isMobilePhone.js":
/*!*****************************************************!*\
!*** ./node_modules/validator/lib/isMobilePhone.js ***!
\*****************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
eval("\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = isMobilePhone;\nexports.locales = void 0;\n\nvar _assertString = _interopRequireDefault(__webpack_require__(/*! ./util/assertString */ \"./node_modules/validator/lib/util/assertString.js\"));\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\n/* eslint-disable max-len */\nvar phones = {\n 'am-AM': /^(\\+?374|0)((10|[9|7][0-9])\\d{6}$|[2-4]\\d{7}$)/,\n 'ar-AE': /^((\\+?971)|0)?5[024568]\\d{7}$/,\n 'ar-BH': /^(\\+?973)?(3|6)\\d{7}$/,\n 'ar-DZ': /^(\\+?213|0)(5|6|7)\\d{8}$/,\n 'ar-EG': /^((\\+?20)|0)?1[0125]\\d{8}$/,\n 'ar-IQ': /^(\\+?964|0)?7[0-9]\\d{8}$/,\n 'ar-JO': /^(\\+?962|0)?7[789]\\d{7}$/,\n 'ar-KW': /^(\\+?965)[569]\\d{7}$/,\n 'ar-SA': /^(!?(\\+?966)|0)?5\\d{8}$/,\n 'ar-SY': /^(!?(\\+?963)|0)?9\\d{8}$/,\n 'ar-TN': /^(\\+?216)?[2459]\\d{7}$/,\n 'be-BY': /^(\\+?375)?(24|25|29|33|44)\\d{7}$/,\n 'bg-BG': /^(\\+?359|0)?8[789]\\d{7}$/,\n 'bn-BD': /^(\\+?880|0)1[13456789][0-9]{8}$/,\n 'cs-CZ': /^(\\+?420)? ?[1-9][0-9]{2} ?[0-9]{3} ?[0-9]{3}$/,\n 'da-DK': /^(\\+?45)?\\s?\\d{2}\\s?\\d{2}\\s?\\d{2}\\s?\\d{2}$/,\n 'de-DE': /^(\\+49)?0?1(5[0-25-9]\\d|6([23]|0\\d?)|7([0-57-9]|6\\d))\\d{7}$/,\n 'de-AT': /^(\\+43|0)\\d{1,4}\\d{3,12}$/,\n 'el-GR': /^(\\+?30|0)?(69\\d{8})$/,\n 'en-AU': /^(\\+?61|0)4\\d{8}$/,\n 'en-GB': /^(\\+?44|0)7\\d{9}$/,\n 'en-GG': /^(\\+?44|0)1481\\d{6}$/,\n 'en-GH': /^(\\+233|0)(20|50|24|54|27|57|26|56|23|28)\\d{7}$/,\n 'en-HK': /^(\\+?852[-\\s]?)?[456789]\\d{3}[-\\s]?\\d{4}$/,\n 'en-MO': /^(\\+?853[-\\s]?)?[6]\\d{3}[-\\s]?\\d{4}$/,\n 'en-IE': /^(\\+?353|0)8[356789]\\d{7}$/,\n 'en-IN': /^(\\+?91|0)?[6789]\\d{9}$/,\n 'en-KE': /^(\\+?254|0)(7|1)\\d{8}$/,\n 'en-MT': /^(\\+?356|0)?(99|79|77|21|27|22|25)[0-9]{6}$/,\n 'en-MU': /^(\\+?230|0)?\\d{8}$/,\n 'en-NG': /^(\\+?234|0)?[789]\\d{9}$/,\n 'en-NZ': /^(\\+?64|0)[28]\\d{7,9}$/,\n 'en-PK': /^((\\+92)|(0092))-{0,1}\\d{3}-{0,1}\\d{7}$|^\\d{11}$|^\\d{4}-\\d{7}$/,\n 'en-RW': /^(\\+?250|0)?[7]\\d{8}$/,\n 'en-SG': /^(\\+65)?[89]\\d{7}$/,\n 'en-TZ': /^(\\+?255|0)?[67]\\d{8}$/,\n 'en-UG': /^(\\+?256|0)?[7]\\d{8}$/,\n 'en-US': /^((\\+1|1)?( |-)?)?(\\([2-9][0-9]{2}\\)|[2-9][0-9]{2})( |-)?([2-9][0-9]{2}( |-)?[0-9]{4})$/,\n 'en-ZA': /^(\\+?27|0)\\d{9}$/,\n 'en-ZM': /^(\\+?26)?09[567]\\d{7}$/,\n 'es-CL': /^(\\+?56|0)[2-9]\\d{1}\\d{7}$/,\n 'es-EC': /^(\\+?593|0)([2-7]|9[2-9])\\d{7}$/,\n 'es-ES': /^(\\+?34)?(6\\d{1}|7[1234])\\d{7}$/,\n 'es-MX': /^(\\+?52)?(1|01)?\\d{10,11}$/,\n 'es-PA': /^(\\+?507)\\d{7,8}$/,\n 'es-PY': /^(\\+?595|0)9[9876]\\d{7}$/,\n 'es-UY': /^(\\+598|0)9[1-9][\\d]{6}$/,\n 'et-EE': /^(\\+?372)?\\s?(5|8[1-4])\\s?([0-9]\\s?){6,7}$/,\n 'fa-IR': /^(\\+?98[\\-\\s]?|0)9[0-39]\\d[\\-\\s]?\\d{3}[\\-\\s]?\\d{4}$/,\n 'fi-FI': /^(\\+?358|0)\\s?(4(0|1|2|4|5|6)?|50)\\s?(\\d\\s?){4,8}\\d$/,\n 'fj-FJ': /^(\\+?679)?\\s?\\d{3}\\s?\\d{4}$/,\n 'fo-FO': /^(\\+?298)?\\s?\\d{2}\\s?\\d{2}\\s?\\d{2}$/,\n 'fr-FR': /^(\\+?33|0)[67]\\d{8}$/,\n 'fr-GF': /^(\\+?594|0|00594)[67]\\d{8}$/,\n 'fr-GP': /^(\\+?590|0|00590)[67]\\d{8}$/,\n 'fr-MQ': /^(\\+?596|0|00596)[67]\\d{8}$/,\n 'fr-RE': /^(\\+?262|0|00262)[67]\\d{8}$/,\n 'he-IL': /^(\\+972|0)([23489]|5[012345689]|77)[1-9]\\d{6}$/,\n 'hu-HU': /^(\\+?36)(20|30|70)\\d{7}$/,\n 'id-ID': /^(\\+?62|0)8(1[123456789]|2[1238]|3[1238]|5[12356789]|7[78]|9[56789]|8[123456789])([\\s?|\\d]{5,11})$/,\n 'it-IT': /^(\\+?39)?\\s?3\\d{2} ?\\d{6,7}$/,\n 'ja-JP': /^(\\+81[ \\-]?(\\(0\\))?|0)[6789]0[ \\-]?\\d{4}[ \\-]?\\d{4}$/,\n 'kk-KZ': /^(\\+?7|8)?7\\d{9}$/,\n 'kl-GL': /^(\\+?299)?\\s?\\d{2}\\s?\\d{2}\\s?\\d{2}$/,\n 'ko-KR': /^((\\+?82)[ \\-]?)?0?1([0|1|6|7|8|9]{1})[ \\-]?\\d{3,4}[ \\-]?\\d{4}$/,\n 'lt-LT': /^(\\+370|8)\\d{8}$/,\n 'ms-MY': /^(\\+?6?01){1}(([0145]{1}(\\-|\\s)?\\d{7,8})|([236789]{1}(\\s|\\-)?\\d{7}))$/,\n 'nb-NO': /^(\\+?47)?[49]\\d{7}$/,\n 'ne-NP': /^(\\+?977)?9[78]\\d{8}$/,\n 'nl-BE': /^(\\+?32|0)4?\\d{8}$/,\n 'nl-NL': /^(\\+?31|0)6?\\d{8}$/,\n 'nn-NO': /^(\\+?47)?[49]\\d{7}$/,\n 'pl-PL': /^(\\+?48)? ?[5-8]\\d ?\\d{3} ?\\d{2} ?\\d{2}$/,\n 'pt-BR': /(?=^(\\+?5{2}\\-?|0)[1-9]{2}\\-?\\d{4}\\-?\\d{4}$)(^(\\+?5{2}\\-?|0)[1-9]{2}\\-?[6-9]{1}\\d{3}\\-?\\d{4}$)|(^(\\+?5{2}\\-?|0)[1-9]{2}\\-?9[6-9]{1}\\d{3}\\-?\\d{4}$)/,\n 'pt-PT': /^(\\+?351)?9[1236]\\d{7}$/,\n 'ro-RO': /^(\\+?4?0)\\s?7\\d{2}(\\/|\\s|\\.|\\-)?\\d{3}(\\s|\\.|\\-)?\\d{3}$/,\n 'ru-RU': /^(\\+?7|8)?9\\d{9}$/,\n 'sl-SI': /^(\\+386\\s?|0)(\\d{1}\\s?\\d{3}\\s?\\d{2}\\s?\\d{2}|\\d{2}\\s?\\d{3}\\s?\\d{3})$/,\n 'sk-SK': /^(\\+?421)? ?[1-9][0-9]{2} ?[0-9]{3} ?[0-9]{3}$/,\n 'sr-RS': /^(\\+3816|06)[- \\d]{5,9}$/,\n 'sv-SE': /^(\\+?46|0)[\\s\\-]?7[\\s\\-]?[02369]([\\s\\-]?\\d){7}$/,\n 'th-TH': /^(\\+66|66|0)\\d{9}$/,\n 'tr-TR': /^(\\+?90|0)?5\\d{9}$/,\n 'uk-UA': /^(\\+?38|8)?0\\d{9}$/,\n 'vi-VN': /^(\\+?84|0)((3([2-9]))|(5([2689]))|(7([0|6-9]))|(8([1-6|89]))|(9([0-9])))([0-9]{7})$/,\n 'zh-CN': /^((\\+|00)86)?1([358][0-9]|4[579]|6[67]|7[01235678]|9[189])[0-9]{8}$/,\n 'zh-TW': /^(\\+?886\\-?|0)?9\\d{8}$/\n};\n/* eslint-enable max-len */\n// aliases\n\nphones['en-CA'] = phones['en-US'];\nphones['fr-BE'] = phones['nl-BE'];\nphones['zh-HK'] = phones['en-HK'];\nphones['zh-MO'] = phones['en-MO'];\n\nfunction isMobilePhone(str, locale, options) {\n (0, _assertString.default)(str);\n\n if (options && options.strictMode && !str.startsWith('+')) {\n return false;\n }\n\n if (Array.isArray(locale)) {\n return locale.some(function (key) {\n // https://github.com/gotwarlost/istanbul/blob/master/ignoring-code-for-coverage.md#ignoring-code-for-coverage-purposes\n // istanbul ignore else\n if (phones.hasOwnProperty(key)) {\n var phone = phones[key];\n\n if (phone.test(str)) {\n return true;\n }\n }\n\n return false;\n });\n } else if (locale in phones) {\n return phones[locale].test(str); // alias falsey locale as 'any'\n } else if (!locale || locale === 'any') {\n for (var key in phones) {\n // istanbul ignore else\n if (phones.hasOwnProperty(key)) {\n var phone = phones[key];\n\n if (phone.test(str)) {\n return true;\n }\n }\n }\n\n return false;\n }\n\n throw new Error(\"Invalid locale '\".concat(locale, \"'\"));\n}\n\nvar locales = Object.keys(phones);\nexports.locales = locales;\n\n//# sourceURL=webpack:///./node_modules/validator/lib/isMobilePhone.js?");
/***/ }),
/***/ "./node_modules/validator/lib/isMongoId.js":
/*!*************************************************!*\
!*** ./node_modules/validator/lib/isMongoId.js ***!
\*************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
eval("\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = isMongoId;\n\nvar _assertString = _interopRequireDefault(__webpack_require__(/*! ./util/assertString */ \"./node_modules/validator/lib/util/assertString.js\"));\n\nvar _isHexadecimal = _interopRequireDefault(__webpack_require__(/*! ./isHexadecimal */ \"./node_modules/validator/lib/isHexadecimal.js\"));\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\nfunction isMongoId(str) {\n (0, _assertString.default)(str);\n return (0, _isHexadecimal.default)(str) && str.length === 24;\n}\n\nmodule.exports = exports.default;\nmodule.exports.default = exports.default;\n\n//# sourceURL=webpack:///./node_modules/validator/lib/isMongoId.js?");
/***/ }),
/***/ "./node_modules/validator/lib/isMultibyte.js":
/*!***************************************************!*\
!*** ./node_modules/validator/lib/isMultibyte.js ***!
\***************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
eval("\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = isMultibyte;\n\nvar _assertString = _interopRequireDefault(__webpack_require__(/*! ./util/assertString */ \"./node_modules/validator/lib/util/assertString.js\"));\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\n/* eslint-disable no-control-regex */\nvar multibyte = /[^\\x00-\\x7F]/;\n/* eslint-enable no-control-regex */\n\nfunction isMultibyte(str) {\n (0, _assertString.default)(str);\n return multibyte.test(str);\n}\n\nmodule.exports = exports.default;\nmodule.exports.default = exports.default;\n\n//# sourceURL=webpack:///./node_modules/validator/lib/isMultibyte.js?");
/***/ }),
/***/ "./node_modules/validator/lib/isNumeric.js":
/*!*************************************************!*\
!*** ./node_modules/validator/lib/isNumeric.js ***!
\*************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
eval("\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = isNumeric;\n\nvar _assertString = _interopRequireDefault(__webpack_require__(/*! ./util/assertString */ \"./node_modules/validator/lib/util/assertString.js\"));\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\nvar numeric = /^[+-]?([0-9]*[.])?[0-9]+$/;\nvar numericNoSymbols = /^[0-9]+$/;\n\nfunction isNumeric(str, options) {\n (0, _assertString.default)(str);\n\n if (options && options.no_symbols) {\n return numericNoSymbols.test(str);\n }\n\n return numeric.test(str);\n}\n\nmodule.exports = exports.default;\nmodule.exports.default = exports.default;\n\n//# sourceURL=webpack:///./node_modules/validator/lib/isNumeric.js?");
/***/ }),
/***/ "./node_modules/validator/lib/isOctal.js":
/*!***********************************************!*\
!*** ./node_modules/validator/lib/isOctal.js ***!
\***********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
eval("\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = isOctal;\n\nvar _assertString = _interopRequireDefault(__webpack_require__(/*! ./util/assertString */ \"./node_modules/validator/lib/util/assertString.js\"));\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\nvar octal = /^(0o)?[0-7]+$/i;\n\nfunction isOctal(str) {\n (0, _assertString.default)(str);\n return octal.test(str);\n}\n\nmodule.exports = exports.default;\nmodule.exports.default = exports.default;\n\n//# sourceURL=webpack:///./node_modules/validator/lib/isOctal.js?");
/***/ }),
/***/ "./node_modules/validator/lib/isPassportNumber.js":
/*!********************************************************!*\
!*** ./node_modules/validator/lib/isPassportNumber.js ***!
\********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
eval("\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = isPassportNumber;\n\n/**\n * Reference:\n * https://en.wikipedia.org/ -- Wikipedia\n * https://docs.microsoft.com/en-us/microsoft-365/compliance/eu-passport-number -- EU Passport Number\n * https://countrycode.org/ -- Country Codes\n */\nvar passportRegexByCountryCode = {\n AM: /^[A-Z]{2}\\d{7}$/,\n // ARMENIA\n AR: /^[A-Z]{3}\\d{6}$/,\n // ARGENTINA\n AT: /^[A-Z]\\d{7}$/,\n // AUSTRIA\n AU: /^[A-Z]\\d{7}$/,\n // AUSTRALIA\n BE: /^[A-Z]{2}\\d{6}$/,\n // BELGIUM\n BG: /^\\d{9}$/,\n // BULGARIA\n CA: /^[A-Z]{2}\\d{6}$/,\n // CANADA\n CH: /^[A-Z]\\d{7}$/,\n // SWITZERLAND\n CN: /^[GE]\\d{8}$/,\n // CHINA [G=Ordinary, E=Electronic] followed by 8-digits\n CY: /^[A-Z](\\d{6}|\\d{8})$/,\n // CYPRUS\n CZ: /^\\d{8}$/,\n // CZECH REPUBLIC\n DE: /^[CFGHJKLMNPRTVWXYZ0-9]{9}$/,\n // GERMANY\n DK: /^\\d{9}$/,\n // DENMARK\n DZ: /^\\d{9}$/,\n // ALGERIA\n EE: /^([A-Z]\\d{7}|[A-Z]{2}\\d{7})$/,\n // ESTONIA (K followed by 7-digits), e-passports have 2 UPPERCASE followed by 7 digits\n ES: /^[A-Z0-9]{2}([A-Z0-9]?)\\d{6}$/,\n // SPAIN\n FI: /^[A-Z]{2}\\d{7}$/,\n // FINLAND\n FR: /^\\d{2}[A-Z]{2}\\d{5}$/,\n // FRANCE\n GB: /^\\d{9}$/,\n // UNITED KINGDOM\n GR: /^[A-Z]{2}\\d{7}$/,\n // GREECE\n HR: /^\\d{9}$/,\n // CROATIA\n HU: /^[A-Z]{2}(\\d{6}|\\d{7})$/,\n // HUNGARY\n IE: /^[A-Z0-9]{2}\\d{7}$/,\n // IRELAND\n IS: /^(A)\\d{7}$/,\n // ICELAND\n IT: /^[A-Z0-9]{2}\\d{7}$/,\n // ITALY\n JP: /^[A-Z]{2}\\d{7}$/,\n // JAPAN\n KR: /^[MS]\\d{8}$/,\n // SOUTH KOREA, REPUBLIC OF KOREA, [S=PS Passports, M=PM Passports]\n LT: /^[A-Z0-9]{8}$/,\n // LITHUANIA\n LU: /^[A-Z0-9]{8}$/,\n // LUXEMBURG\n LV: /^[A-Z0-9]{2}\\d{7}$/,\n // LATVIA\n MT: /^\\d{7}$/,\n // MALTA\n NL: /^[A-Z]{2}[A-Z0-9]{6}\\d$/,\n // NETHERLANDS\n PO: /^[A-Z]{2}\\d{7}$/,\n // POLAND\n PT: /^[A-Z]\\d{6}$/,\n // PORTUGAL\n RO: /^\\d{8,9}$/,\n // ROMANIA\n SE: /^\\d{8}$/,\n // SWEDEN\n SL: /^(P)[A-Z]\\d{7}$/,\n // SLOVANIA\n SK: /^[0-9A-Z]\\d{7}$/,\n // SLOVAKIA\n TR: /^[A-Z]\\d{8}$/,\n // TURKEY\n UA: /^[A-Z]{2}\\d{6}$/,\n // UKRAINE\n US: /^\\d{9}$/ // UNITED STATES\n\n};\n/**\n * Check if str is a valid passport number\n * relative to provided ISO Country Code.\n *\n * @param {string} str\n * @param {string} countryCode\n * @return {boolean}\n */\n\nfunction isPassportNumber(str, countryCode) {\n /** Remove All Whitespaces, Convert to UPPERCASE */\n var normalizedStr = str.replace(/\\s/g, '').toUpperCase();\n return countryCode.toUpperCase() in passportRegexByCountryCode && passportRegexByCountryCode[countryCode].test(normalizedStr);\n}\n\nmodule.exports = exports.default;\nmodule.exports.default = exports.default;\n\n//# sourceURL=webpack:///./node_modules/validator/lib/isPassportNumber.js?");
/***/ }),
/***/ "./node_modules/validator/lib/isPort.js":
/*!**********************************************!*\
!*** ./node_modules/validator/lib/isPort.js ***!
\**********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
eval("\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = isPort;\n\nvar _isInt = _interopRequireDefault(__webpack_require__(/*! ./isInt */ \"./node_modules/validator/lib/isInt.js\"));\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\nfunction isPort(str) {\n return (0, _isInt.default)(str, {\n min: 0,\n max: 65535\n });\n}\n\nmodule.exports = exports.default;\nmodule.exports.default = exports.default;\n\n//# sourceURL=webpack:///./node_modules/validator/lib/isPort.js?");
/***/ }),
/***/ "./node_modules/validator/lib/isPostalCode.js":
/*!****************************************************!*\
!*** ./node_modules/validator/lib/isPostalCode.js ***!
\****************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
eval("\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = _default;\nexports.locales = void 0;\n\nvar _assertString = _interopRequireDefault(__webpack_require__(/*! ./util/assertString */ \"./node_modules/validator/lib/util/assertString.js\"));\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\n// common patterns\nvar threeDigit = /^\\d{3}$/;\nvar fourDigit = /^\\d{4}$/;\nvar fiveDigit = /^\\d{5}$/;\nvar sixDigit = /^\\d{6}$/;\nvar patterns = {\n AD: /^AD\\d{3}$/,\n AT: fourDigit,\n AU: fourDigit,\n BE: fourDigit,\n BG: fourDigit,\n BR: /^\\d{5}-\\d{3}$/,\n CA: /^[ABCEGHJKLMNPRSTVXY]\\d[ABCEGHJ-NPRSTV-Z][\\s\\-]?\\d[ABCEGHJ-NPRSTV-Z]\\d$/i,\n CH: fourDigit,\n CZ: /^\\d{3}\\s?\\d{2}$/,\n DE: fiveDigit,\n DK: fourDigit,\n DZ: fiveDigit,\n EE: fiveDigit,\n ES: fiveDigit,\n FI: fiveDigit,\n FR: /^\\d{2}\\s?\\d{3}$/,\n GB: /^(gir\\s?0aa|[a-z]{1,2}\\d[\\da-z]?\\s?(\\d[a-z]{2})?)$/i,\n GR: /^\\d{3}\\s?\\d{2}$/,\n HR: /^([1-5]\\d{4}$)/,\n HU: fourDigit,\n ID: fiveDigit,\n IE: /^(?!.*(?:o))[A-z]\\d[\\dw]\\s\\w{4}$/i,\n IL: fiveDigit,\n IN: /^((?!10|29|35|54|55|65|66|86|87|88|89)[1-9][0-9]{5})$/,\n IS: threeDigit,\n IT: fiveDigit,\n JP: /^\\d{3}\\-\\d{4}$/,\n KE: fiveDigit,\n LI: /^(948[5-9]|949[0-7])$/,\n LT: /^LT\\-\\d{5}$/,\n LU: fourDigit,\n LV: /^LV\\-\\d{4}$/,\n MX: fiveDigit,\n MT: /^[A-Za-z]{3}\\s{0,1}\\d{4}$/,\n NL: /^\\d{4}\\s?[a-z]{2}$/i,\n NO: fourDigit,\n NZ: fourDigit,\n PL: /^\\d{2}\\-\\d{3}$/,\n PR: /^00[679]\\d{2}([ -]\\d{4})?$/,\n PT: /^\\d{4}\\-\\d{3}?$/,\n RO: sixDigit,\n RU: sixDigit,\n SA: fiveDigit,\n SE: /^[1-9]\\d{2}\\s?\\d{2}$/,\n SI: fourDigit,\n SK: /^\\d{3}\\s?\\d{2}$/,\n TN: fourDigit,\n TW: /^\\d{3}(\\d{2})?$/,\n UA: fiveDigit,\n US: /^\\d{5}(-\\d{4})?$/,\n ZA: fourDigit,\n ZM: fiveDigit\n};\nvar locales = Object.keys(patterns);\nexports.locales = locales;\n\nfunction _default(str, locale) {\n (0, _assertString.default)(str);\n\n if (locale in patterns) {\n return patterns[locale].test(str);\n } else if (locale === 'any') {\n for (var key in patterns) {\n // https://github.com/gotwarlost/istanbul/blob/master/ignoring-code-for-coverage.md#ignoring-code-for-coverage-purposes\n // istanbul ignore else\n if (patterns.hasOwnProperty(key)) {\n var pattern = patterns[key];\n\n if (pattern.test(str)) {\n return true;\n }\n }\n }\n\n return false;\n }\n\n throw new Error(\"Invalid locale '\".concat(locale, \"'\"));\n}\n\n//# sourceURL=webpack:///./node_modules/validator/lib/isPostalCode.js?");
/***/ }),
/***/ "./node_modules/validator/lib/isRFC3339.js":
/*!*************************************************!*\
!*** ./node_modules/validator/lib/isRFC3339.js ***!
\*************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
eval("\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = isRFC3339;\n\nvar _assertString = _interopRequireDefault(__webpack_require__(/*! ./util/assertString */ \"./node_modules/validator/lib/util/assertString.js\"));\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\n/* Based on https://tools.ietf.org/html/rfc3339#section-5.6 */\nvar dateFullYear = /[0-9]{4}/;\nvar dateMonth = /(0[1-9]|1[0-2])/;\nvar dateMDay = /([12]\\d|0[1-9]|3[01])/;\nvar timeHour = /([01][0-9]|2[0-3])/;\nvar timeMinute = /[0-5][0-9]/;\nvar timeSecond = /([0-5][0-9]|60)/;\nvar timeSecFrac = /(\\.[0-9]+)?/;\nvar timeNumOffset = new RegExp(\"[-+]\".concat(timeHour.source, \":\").concat(timeMinute.source));\nvar timeOffset = new RegExp(\"([zZ]|\".concat(timeNumOffset.source, \")\"));\nvar partialTime = new RegExp(\"\".concat(timeHour.source, \":\").concat(timeMinute.source, \":\").concat(timeSecond.source).concat(timeSecFrac.source));\nvar fullDate = new RegExp(\"\".concat(dateFullYear.source, \"-\").concat(dateMonth.source, \"-\").concat(dateMDay.source));\nvar fullTime = new RegExp(\"\".concat(partialTime.source).concat(timeOffset.source));\nvar rfc3339 = new RegExp(\"\".concat(fullDate.source, \"[ tT]\").concat(fullTime.source));\n\nfunction isRFC3339(str) {\n (0, _assertString.default)(str);\n return rfc3339.test(str);\n}\n\nmodule.exports = exports.default;\nmodule.exports.default = exports.default;\n\n//# sourceURL=webpack:///./node_modules/validator/lib/isRFC3339.js?");
/***/ }),
/***/ "./node_modules/validator/lib/isRgbColor.js":
/*!**************************************************!*\
!*** ./node_modules/validator/lib/isRgbColor.js ***!
\**************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
eval("\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = isRgbColor;\n\nvar _assertString = _interopRequireDefault(__webpack_require__(/*! ./util/assertString */ \"./node_modules/validator/lib/util/assertString.js\"));\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\nvar rgbColor = /^rgb\\((([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5]),){2}([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\\)$/;\nvar rgbaColor = /^rgba\\((([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5]),){3}(0?\\.\\d|1(\\.0)?|0(\\.0)?)\\)$/;\nvar rgbColorPercent = /^rgb\\((([0-9]%|[1-9][0-9]%|100%),){2}([0-9]%|[1-9][0-9]%|100%)\\)/;\nvar rgbaColorPercent = /^rgba\\((([0-9]%|[1-9][0-9]%|100%),){3}(0?\\.\\d|1(\\.0)?|0(\\.0)?)\\)/;\n\nfunction isRgbColor(str) {\n var includePercentValues = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;\n (0, _assertString.default)(str);\n\n if (!includePercentValues) {\n return rgbColor.test(str) || rgbaColor.test(str);\n }\n\n return rgbColor.test(str) || rgbaColor.test(str) || rgbColorPercent.test(str) || rgbaColorPercent.test(str);\n}\n\nmodule.exports = exports.default;\nmodule.exports.default = exports.default;\n\n//# sourceURL=webpack:///./node_modules/validator/lib/isRgbColor.js?");
/***/ }),
/***/ "./node_modules/validator/lib/isSemVer.js":
/*!************************************************!*\
!*** ./node_modules/validator/lib/isSemVer.js ***!
\************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
eval("\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = isSemVer;\n\nvar _assertString = _interopRequireDefault(__webpack_require__(/*! ./util/assertString */ \"./node_modules/validator/lib/util/assertString.js\"));\n\nvar _multilineRegex = _interopRequireDefault(__webpack_require__(/*! ./util/multilineRegex */ \"./node_modules/validator/lib/util/multilineRegex.js\"));\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\n/**\n * Regular Expression to match\n * semantic versioning (SemVer)\n * built from multi-line, multi-parts regexp\n * Reference: https://semver.org/\n */\nvar semanticVersioningRegex = (0, _multilineRegex.default)(['^(0|[1-9]\\\\d*)\\\\.(0|[1-9]\\\\d*)\\\\.(0|[1-9]\\\\d*)', '(?:-((?:0|[1-9]\\\\d*|\\\\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\\\\.(?:0|[1-9]\\\\d*|\\\\d*[a-zA-Z-][0-9a-zA-Z-]*))*))', '?(?:\\\\+([0-9a-zA-Z-]+(?:\\\\.[0-9a-zA-Z-]+)*))?$']);\n\nfunction isSemVer(str) {\n (0, _assertString.default)(str);\n return semanticVersioningRegex.test(str);\n}\n\nmodule.exports = exports.default;\nmodule.exports.default = exports.default;\n\n//# sourceURL=webpack:///./node_modules/validator/lib/isSemVer.js?");
/***/ }),
/***/ "./node_modules/validator/lib/isSlug.js":
/*!**********************************************!*\
!*** ./node_modules/validator/lib/isSlug.js ***!
\**********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
eval("\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = isSlug;\n\nvar _assertString = _interopRequireDefault(__webpack_require__(/*! ./util/assertString */ \"./node_modules/validator/lib/util/assertString.js\"));\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\nvar charsetRegex = /^[^-_](?!.*?[-_]{2,})([a-z0-9\\\\-]{1,}).*[^-_]$/;\n\nfunction isSlug(str) {\n (0, _assertString.default)(str);\n return charsetRegex.test(str);\n}\n\nmodule.exports = exports.default;\nmodule.exports.default = exports.default;\n\n//# sourceURL=webpack:///./node_modules/validator/lib/isSlug.js?");
/***/ }),
/***/ "./node_modules/validator/lib/isSurrogatePair.js":
/*!*******************************************************!*\
!*** ./node_modules/validator/lib/isSurrogatePair.js ***!
\*******************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
eval("\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = isSurrogatePair;\n\nvar _assertString = _interopRequireDefault(__webpack_require__(/*! ./util/assertString */ \"./node_modules/validator/lib/util/assertString.js\"));\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\nvar surrogatePair = /[\\uD800-\\uDBFF][\\uDC00-\\uDFFF]/;\n\nfunction isSurrogatePair(str) {\n (0, _assertString.default)(str);\n return surrogatePair.test(str);\n}\n\nmodule.exports = exports.default;\nmodule.exports.default = exports.default;\n\n//# sourceURL=webpack:///./node_modules/validator/lib/isSurrogatePair.js?");
/***/ }),
/***/ "./node_modules/validator/lib/isURL.js":
/*!*********************************************!*\
!*** ./node_modules/validator/lib/isURL.js ***!
\*********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
eval("\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = isURL;\n\nvar _assertString = _interopRequireDefault(__webpack_require__(/*! ./util/assertString */ \"./node_modules/validator/lib/util/assertString.js\"));\n\nvar _isFQDN = _interopRequireDefault(__webpack_require__(/*! ./isFQDN */ \"./node_modules/validator/lib/isFQDN.js\"));\n\nvar _isIP = _interopRequireDefault(__webpack_require__(/*! ./isIP */ \"./node_modules/validator/lib/isIP.js\"));\n\nvar _merge = _interopRequireDefault(__webpack_require__(/*! ./util/merge */ \"./node_modules/validator/lib/util/merge.js\"));\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\n/*\noptions for isURL method\n\nrequire_protocol - if set as true isURL will return false if protocol is not present in the URL\nrequire_valid_protocol - isURL will check if the URL's protocol is present in the protocols option\nprotocols - valid protocols can be modified with this option\nrequire_host - if set as false isURL will not check if host is present in the URL\nallow_protocol_relative_urls - if set as true protocol relative URLs will be allowed\n\n*/\nvar default_url_options = {\n protocols: ['http', 'https', 'ftp'],\n require_tld: true,\n require_protocol: false,\n require_host: true,\n require_valid_protocol: true,\n allow_underscores: false,\n allow_trailing_dot: false,\n allow_protocol_relative_urls: false\n};\nvar wrapped_ipv6 = /^\\[([^\\]]+)\\](?::([0-9]+))?$/;\n\nfunction isRegExp(obj) {\n return Object.prototype.toString.call(obj) === '[object RegExp]';\n}\n\nfunction checkHost(host, matches) {\n for (var i = 0; i < matches.length; i++) {\n var match = matches[i];\n\n if (host === match || isRegExp(match) && match.test(host)) {\n return true;\n }\n }\n\n return false;\n}\n\nfunction isURL(url, options) {\n (0, _assertString.default)(url);\n\n if (!url || url.length >= 2083 || /[\\s<>]/.test(url)) {\n return false;\n }\n\n if (url.indexOf('mailto:') === 0) {\n return false;\n }\n\n options = (0, _merge.default)(options, default_url_options);\n var protocol, auth, host, hostname, port, port_str, split, ipv6;\n split = url.split('#');\n url = split.shift();\n split = url.split('?');\n url = split.shift();\n split = url.split('://');\n\n if (split.length > 1) {\n protocol = split.shift().toLowerCase();\n\n if (options.require_valid_protocol && options.protocols.indexOf(protocol) === -1) {\n return false;\n }\n } else if (options.require_protocol) {\n return false;\n } else if (url.substr(0, 2) === '//') {\n if (!options.allow_protocol_relative_urls) {\n return false;\n }\n\n split[0] = url.substr(2);\n }\n\n url = split.join('://');\n\n if (url === '') {\n return false;\n }\n\n split = url.split('/');\n url = split.shift();\n\n if (url === '' && !options.require_host) {\n return true;\n }\n\n split = url.split('@');\n\n if (split.length > 1) {\n if (options.disallow_auth) {\n return false;\n }\n\n auth = split.shift();\n\n if (auth.indexOf(':') >= 0 && auth.split(':').length > 2) {\n return false;\n }\n }\n\n hostname = split.join('@');\n port_str = null;\n ipv6 = null;\n var ipv6_match = hostname.match(wrapped_ipv6);\n\n if (ipv6_match) {\n host = '';\n ipv6 = ipv6_match[1];\n port_str = ipv6_match[2] || null;\n } else {\n split = hostname.split(':');\n host = split.shift();\n\n if (split.length) {\n port_str = split.join(':');\n }\n }\n\n if (port_str !== null) {\n port = parseInt(port_str, 10);\n\n if (!/^[0-9]+$/.test(port_str) || port <= 0 || port > 65535) {\n return false;\n }\n }\n\n if (!(0, _isIP.default)(host) && !(0, _isFQDN.default)(host, options) && (!ipv6 || !(0, _isIP.default)(ipv6, 6))) {\n return false;\n }\n\n host = host || ipv6;\n\n if (options.host_whitelist && !checkHost(host, options.host_whitelist)) {\n return false;\n }\n\n if (options.host_blacklist && checkHost(host, options.host_blacklist)) {\n return false;\n }\n\n return true;\n}\n\nmodule.exports = exports.default;\nmodule.exports.default = exports.default;\n\n//# sourceURL=webpack:///./node_modules/validator/lib/isURL.js?");
/***/ }),
/***/ "./node_modules/validator/lib/isUUID.js":
/*!**********************************************!*\
!*** ./node_modules/validator/lib/isUUID.js ***!
\**********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
eval("\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = isUUID;\n\nvar _assertString = _interopRequireDefault(__webpack_require__(/*! ./util/assertString */ \"./node_modules/validator/lib/util/assertString.js\"));\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\nvar uuid = {\n 3: /^[0-9A-F]{8}-[0-9A-F]{4}-3[0-9A-F]{3}-[0-9A-F]{4}-[0-9A-F]{12}$/i,\n 4: /^[0-9A-F]{8}-[0-9A-F]{4}-4[0-9A-F]{3}-[89AB][0-9A-F]{3}-[0-9A-F]{12}$/i,\n 5: /^[0-9A-F]{8}-[0-9A-F]{4}-5[0-9A-F]{3}-[89AB][0-9A-F]{3}-[0-9A-F]{12}$/i,\n all: /^[0-9A-F]{8}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{12}$/i\n};\n\nfunction isUUID(str) {\n var version = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'all';\n (0, _assertString.default)(str);\n var pattern = uuid[version];\n return pattern && pattern.test(str);\n}\n\nmodule.exports = exports.default;\nmodule.exports.default = exports.default;\n\n//# sourceURL=webpack:///./node_modules/validator/lib/isUUID.js?");
/***/ }),
/***/ "./node_modules/validator/lib/isUppercase.js":
/*!***************************************************!*\
!*** ./node_modules/validator/lib/isUppercase.js ***!
\***************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
eval("\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = isUppercase;\n\nvar _assertString = _interopRequireDefault(__webpack_require__(/*! ./util/assertString */ \"./node_modules/validator/lib/util/assertString.js\"));\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\nfunction isUppercase(str) {\n (0, _assertString.default)(str);\n return str === str.toUpperCase();\n}\n\nmodule.exports = exports.default;\nmodule.exports.default = exports.default;\n\n//# sourceURL=webpack:///./node_modules/validator/lib/isUppercase.js?");
/***/ }),
/***/ "./node_modules/validator/lib/isVariableWidth.js":
/*!*******************************************************!*\
!*** ./node_modules/validator/lib/isVariableWidth.js ***!
\*******************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
eval("\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = isVariableWidth;\n\nvar _assertString = _interopRequireDefault(__webpack_require__(/*! ./util/assertString */ \"./node_modules/validator/lib/util/assertString.js\"));\n\nvar _isFullWidth = __webpack_require__(/*! ./isFullWidth */ \"./node_modules/validator/lib/isFullWidth.js\");\n\nvar _isHalfWidth = __webpack_require__(/*! ./isHalfWidth */ \"./node_modules/validator/lib/isHalfWidth.js\");\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\nfunction isVariableWidth(str) {\n (0, _assertString.default)(str);\n return _isFullWidth.fullWidth.test(str) && _isHalfWidth.halfWidth.test(str);\n}\n\nmodule.exports = exports.default;\nmodule.exports.default = exports.default;\n\n//# sourceURL=webpack:///./node_modules/validator/lib/isVariableWidth.js?");
/***/ }),
/***/ "./node_modules/validator/lib/isWhitelisted.js":
/*!*****************************************************!*\
!*** ./node_modules/validator/lib/isWhitelisted.js ***!
\*****************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
eval("\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = isWhitelisted;\n\nvar _assertString = _interopRequireDefault(__webpack_require__(/*! ./util/assertString */ \"./node_modules/validator/lib/util/assertString.js\"));\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\nfunction isWhitelisted(str, chars) {\n (0, _assertString.default)(str);\n\n for (var i = str.length - 1; i >= 0; i--) {\n if (chars.indexOf(str[i]) === -1) {\n return false;\n }\n }\n\n return true;\n}\n\nmodule.exports = exports.default;\nmodule.exports.default = exports.default;\n\n//# sourceURL=webpack:///./node_modules/validator/lib/isWhitelisted.js?");
/***/ }),
/***/ "./node_modules/validator/lib/ltrim.js":
/*!*********************************************!*\
!*** ./node_modules/validator/lib/ltrim.js ***!
\*********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
eval("\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = ltrim;\n\nvar _assertString = _interopRequireDefault(__webpack_require__(/*! ./util/assertString */ \"./node_modules/validator/lib/util/assertString.js\"));\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\nfunction ltrim(str, chars) {\n (0, _assertString.default)(str); // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions#Escaping\n\n var pattern = chars ? new RegExp(\"^[\".concat(chars.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&'), \"]+\"), 'g') : /^\\s+/g;\n return str.replace(pattern, '');\n}\n\nmodule.exports = exports.default;\nmodule.exports.default = exports.default;\n\n//# sourceURL=webpack:///./node_modules/validator/lib/ltrim.js?");
/***/ }),
/***/ "./node_modules/validator/lib/matches.js":
/*!***********************************************!*\
!*** ./node_modules/validator/lib/matches.js ***!
\***********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
eval("\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = matches;\n\nvar _assertString = _interopRequireDefault(__webpack_require__(/*! ./util/assertString */ \"./node_modules/validator/lib/util/assertString.js\"));\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\nfunction matches(str, pattern, modifiers) {\n (0, _assertString.default)(str);\n\n if (Object.prototype.toString.call(pattern) !== '[object RegExp]') {\n pattern = new RegExp(pattern, modifiers);\n }\n\n return pattern.test(str);\n}\n\nmodule.exports = exports.default;\nmodule.exports.default = exports.default;\n\n//# sourceURL=webpack:///./node_modules/validator/lib/matches.js?");
/***/ }),
/***/ "./node_modules/validator/lib/normalizeEmail.js":
/*!******************************************************!*\
!*** ./node_modules/validator/lib/normalizeEmail.js ***!
\******************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
eval("\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = normalizeEmail;\n\nvar _merge = _interopRequireDefault(__webpack_require__(/*! ./util/merge */ \"./node_modules/validator/lib/util/merge.js\"));\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\nvar default_normalize_email_options = {\n // The following options apply to all email addresses\n // Lowercases the local part of the email address.\n // Please note this may violate RFC 5321 as per http://stackoverflow.com/a/9808332/192024).\n // The domain is always lowercased, as per RFC 1035\n all_lowercase: true,\n // The following conversions are specific to GMail\n // Lowercases the local part of the GMail address (known to be case-insensitive)\n gmail_lowercase: true,\n // Removes dots from the local part of the email address, as that's ignored by GMail\n gmail_remove_dots: true,\n // Removes the subaddress (e.g. \"+foo\") from the email address\n gmail_remove_subaddress: true,\n // Conversts the googlemail.com domain to gmail.com\n gmail_convert_googlemaildotcom: true,\n // The following conversions are specific to Outlook.com / Windows Live / Hotmail\n // Lowercases the local part of the Outlook.com address (known to be case-insensitive)\n outlookdotcom_lowercase: true,\n // Removes the subaddress (e.g. \"+foo\") from the email address\n outlookdotcom_remove_subaddress: true,\n // The following conversions are specific to Yahoo\n // Lowercases the local part of the Yahoo address (known to be case-insensitive)\n yahoo_lowercase: true,\n // Removes the subaddress (e.g. \"-foo\") from the email address\n yahoo_remove_subaddress: true,\n // The following conversions are specific to Yandex\n // Lowercases the local part of the Yandex address (known to be case-insensitive)\n yandex_lowercase: true,\n // The following conversions are specific to iCloud\n // Lowercases the local part of the iCloud address (known to be case-insensitive)\n icloud_lowercase: true,\n // Removes the subaddress (e.g. \"+foo\") from the email address\n icloud_remove_subaddress: true\n}; // List of domains used by iCloud\n\nvar icloud_domains = ['icloud.com', 'me.com']; // List of domains used by Outlook.com and its predecessors\n// This list is likely incomplete.\n// Partial reference:\n// https://blogs.office.com/2013/04/17/outlook-com-gets-two-step-verification-sign-in-by-alias-and-new-international-domains/\n\nvar outlookdotcom_domains = ['hotmail.at', 'hotmail.be', 'hotmail.ca', 'hotmail.cl', 'hotmail.co.il', 'hotmail.co.nz', 'hotmail.co.th', 'hotmail.co.uk', 'hotmail.com', 'hotmail.com.ar', 'hotmail.com.au', 'hotmail.com.br', 'hotmail.com.gr', 'hotmail.com.mx', 'hotmail.com.pe', 'hotmail.com.tr', 'hotmail.com.vn', 'hotmail.cz', 'hotmail.de', 'hotmail.dk', 'hotmail.es', 'hotmail.fr', 'hotmail.hu', 'hotmail.id', 'hotmail.ie', 'hotmail.in', 'hotmail.it', 'hotmail.jp', 'hotmail.kr', 'hotmail.lv', 'hotmail.my', 'hotmail.ph', 'hotmail.pt', 'hotmail.sa', 'hotmail.sg', 'hotmail.sk', 'live.be', 'live.co.uk', 'live.com', 'live.com.ar', 'live.com.mx', 'live.de', 'live.es', 'live.eu', 'live.fr', 'live.it', 'live.nl', 'msn.com', 'outlook.at', 'outlook.be', 'outlook.cl', 'outlook.co.il', 'outlook.co.nz', 'outlook.co.th', 'outlook.com', 'outlook.com.ar', 'outlook.com.au', 'outlook.com.br', 'outlook.com.gr', 'outlook.com.pe', 'outlook.com.tr', 'outlook.com.vn', 'outlook.cz', 'outlook.de', 'outlook.dk', 'outlook.es', 'outlook.fr', 'outlook.hu', 'outlook.id', 'outlook.ie', 'outlook.in', 'outlook.it', 'outlook.jp', 'outlook.kr', 'outlook.lv', 'outlook.my', 'outlook.ph', 'outlook.pt', 'outlook.sa', 'outlook.sg', 'outlook.sk', 'passport.com']; // List of domains used by Yahoo Mail\n// This list is likely incomplete\n\nvar yahoo_domains = ['rocketmail.com', 'yahoo.ca', 'yahoo.co.uk', 'yahoo.com', 'yahoo.de', 'yahoo.fr', 'yahoo.in', 'yahoo.it', 'ymail.com']; // List of domains used by yandex.ru\n\nvar yandex_domains = ['yandex.ru', 'yandex.ua', 'yandex.kz', 'yandex.com', 'yandex.by', 'ya.ru']; // replace single dots, but not multiple consecutive dots\n\nfunction dotsReplacer(match) {\n if (match.length > 1) {\n return match;\n }\n\n return '';\n}\n\nfunction normalizeEmail(email, options) {\n options = (0, _merge.default)(options, default_normalize_email_options);\n var raw_parts = email.split('@');\n var domain = raw_parts.pop();\n var user = raw_parts.join('@');\n var parts = [user, domain]; // The domain is always lowercased, as it's case-insensitive per RFC 1035\n\n parts[1] = parts[1].toLowerCase();\n\n if (parts[1] === 'gmail.com' || parts[1] === 'googlemail.com') {\n // Address is GMail\n if (options.gmail_remove_subaddress) {\n parts[0] = parts[0].split('+')[0];\n }\n\n if (options.gmail_remove_dots) {\n // this does not replace consecutive dots like [email protected]\n parts[0] = parts[0].replace(/\\.+/g, dotsReplacer);\n }\n\n if (!parts[0].length) {\n return false;\n }\n\n if (options.all_lowercase || options.gmail_lowercase) {\n parts[0] = parts[0].toLowerCase();\n }\n\n parts[1] = options.gmail_convert_googlemaildotcom ? 'gmail.com' : parts[1];\n } else if (icloud_domains.indexOf(parts[1]) >= 0) {\n // Address is iCloud\n if (options.icloud_remove_subaddress) {\n parts[0] = parts[0].split('+')[0];\n }\n\n if (!parts[0].length) {\n return false;\n }\n\n if (options.all_lowercase || options.icloud_lowercase) {\n parts[0] = parts[0].toLowerCase();\n }\n } else if (outlookdotcom_domains.indexOf(parts[1]) >= 0) {\n // Address is Outlook.com\n if (options.outlookdotcom_remove_subaddress) {\n parts[0] = parts[0].split('+')[0];\n }\n\n if (!parts[0].length) {\n return false;\n }\n\n if (options.all_lowercase || options.outlookdotcom_lowercase) {\n parts[0] = parts[0].toLowerCase();\n }\n } else if (yahoo_domains.indexOf(parts[1]) >= 0) {\n // Address is Yahoo\n if (options.yahoo_remove_subaddress) {\n var components = parts[0].split('-');\n parts[0] = components.length > 1 ? components.slice(0, -1).join('-') : components[0];\n }\n\n if (!parts[0].length) {\n return false;\n }\n\n if (options.all_lowercase || options.yahoo_lowercase) {\n parts[0] = parts[0].toLowerCase();\n }\n } else if (yandex_domains.indexOf(parts[1]) >= 0) {\n if (options.all_lowercase || options.yandex_lowercase) {\n parts[0] = parts[0].toLowerCase();\n }\n\n parts[1] = 'yandex.ru'; // all yandex domains are equal, 1st preffered\n } else if (options.all_lowercase) {\n // Any other address\n parts[0] = parts[0].toLowerCase();\n }\n\n return parts.join('@');\n}\n\nmodule.exports = exports.default;\nmodule.exports.default = exports.default;\n\n//# sourceURL=webpack:///./node_modules/validator/lib/normalizeEmail.js?");
/***/ }),
/***/ "./node_modules/validator/lib/rtrim.js":
/*!*********************************************!*\
!*** ./node_modules/validator/lib/rtrim.js ***!
\*********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
eval("\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = rtrim;\n\nvar _assertString = _interopRequireDefault(__webpack_require__(/*! ./util/assertString */ \"./node_modules/validator/lib/util/assertString.js\"));\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\nfunction rtrim(str, chars) {\n (0, _assertString.default)(str); // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions#Escaping\n\n var pattern = chars ? new RegExp(\"[\".concat(chars.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&'), \"]+$\"), 'g') : /\\s+$/g;\n return str.replace(pattern, '');\n}\n\nmodule.exports = exports.default;\nmodule.exports.default = exports.default;\n\n//# sourceURL=webpack:///./node_modules/validator/lib/rtrim.js?");
/***/ }),
/***/ "./node_modules/validator/lib/stripLow.js":
/*!************************************************!*\
!*** ./node_modules/validator/lib/stripLow.js ***!
\************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
eval("\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = stripLow;\n\nvar _assertString = _interopRequireDefault(__webpack_require__(/*! ./util/assertString */ \"./node_modules/validator/lib/util/assertString.js\"));\n\nvar _blacklist = _interopRequireDefault(__webpack_require__(/*! ./blacklist */ \"./node_modules/validator/lib/blacklist.js\"));\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\nfunction stripLow(str, keep_new_lines) {\n (0, _assertString.default)(str);\n var chars = keep_new_lines ? '\\\\x00-\\\\x09\\\\x0B\\\\x0C\\\\x0E-\\\\x1F\\\\x7F' : '\\\\x00-\\\\x1F\\\\x7F';\n return (0, _blacklist.default)(str, chars);\n}\n\nmodule.exports = exports.default;\nmodule.exports.default = exports.default;\n\n//# sourceURL=webpack:///./node_modules/validator/lib/stripLow.js?");
/***/ }),
/***/ "./node_modules/validator/lib/toBoolean.js":
/*!*************************************************!*\
!*** ./node_modules/validator/lib/toBoolean.js ***!
\*************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
eval("\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = toBoolean;\n\nvar _assertString = _interopRequireDefault(__webpack_require__(/*! ./util/assertString */ \"./node_modules/validator/lib/util/assertString.js\"));\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\nfunction toBoolean(str, strict) {\n (0, _assertString.default)(str);\n\n if (strict) {\n return str === '1' || /^true$/i.test(str);\n }\n\n return str !== '0' && !/^false$/i.test(str) && str !== '';\n}\n\nmodule.exports = exports.default;\nmodule.exports.default = exports.default;\n\n//# sourceURL=webpack:///./node_modules/validator/lib/toBoolean.js?");
/***/ }),
/***/ "./node_modules/validator/lib/toDate.js":
/*!**********************************************!*\
!*** ./node_modules/validator/lib/toDate.js ***!
\**********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
eval("\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = toDate;\n\nvar _assertString = _interopRequireDefault(__webpack_require__(/*! ./util/assertString */ \"./node_modules/validator/lib/util/assertString.js\"));\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\nfunction toDate(date) {\n (0, _assertString.default)(date);\n date = Date.parse(date);\n return !isNaN(date) ? new Date(date) : null;\n}\n\nmodule.exports = exports.default;\nmodule.exports.default = exports.default;\n\n//# sourceURL=webpack:///./node_modules/validator/lib/toDate.js?");
/***/ }),
/***/ "./node_modules/validator/lib/toFloat.js":
/*!***********************************************!*\
!*** ./node_modules/validator/lib/toFloat.js ***!
\***********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
eval("\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = toFloat;\n\nvar _isFloat = _interopRequireDefault(__webpack_require__(/*! ./isFloat */ \"./node_modules/validator/lib/isFloat.js\"));\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\nfunction toFloat(str) {\n if (!(0, _isFloat.default)(str)) return NaN;\n return parseFloat(str);\n}\n\nmodule.exports = exports.default;\nmodule.exports.default = exports.default;\n\n//# sourceURL=webpack:///./node_modules/validator/lib/toFloat.js?");
/***/ }),
/***/ "./node_modules/validator/lib/toInt.js":
/*!*********************************************!*\
!*** ./node_modules/validator/lib/toInt.js ***!
\*********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
eval("\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = toInt;\n\nvar _assertString = _interopRequireDefault(__webpack_require__(/*! ./util/assertString */ \"./node_modules/validator/lib/util/assertString.js\"));\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\nfunction toInt(str, radix) {\n (0, _assertString.default)(str);\n return parseInt(str, radix || 10);\n}\n\nmodule.exports = exports.default;\nmodule.exports.default = exports.default;\n\n//# sourceURL=webpack:///./node_modules/validator/lib/toInt.js?");
/***/ }),
/***/ "./node_modules/validator/lib/trim.js":
/*!********************************************!*\
!*** ./node_modules/validator/lib/trim.js ***!
\********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
eval("\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = trim;\n\nvar _rtrim = _interopRequireDefault(__webpack_require__(/*! ./rtrim */ \"./node_modules/validator/lib/rtrim.js\"));\n\nvar _ltrim = _interopRequireDefault(__webpack_require__(/*! ./ltrim */ \"./node_modules/validator/lib/ltrim.js\"));\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\nfunction trim(str, chars) {\n return (0, _rtrim.default)((0, _ltrim.default)(str, chars), chars);\n}\n\nmodule.exports = exports.default;\nmodule.exports.default = exports.default;\n\n//# sourceURL=webpack:///./node_modules/validator/lib/trim.js?");
/***/ }),
/***/ "./node_modules/validator/lib/unescape.js":
/*!************************************************!*\
!*** ./node_modules/validator/lib/unescape.js ***!
\************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
eval("\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = unescape;\n\nvar _assertString = _interopRequireDefault(__webpack_require__(/*! ./util/assertString */ \"./node_modules/validator/lib/util/assertString.js\"));\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\nfunction unescape(str) {\n (0, _assertString.default)(str);\n return str.replace(/&/g, '&').replace(/"/g, '\"').replace(/'/g, \"'\").replace(/</g, '<').replace(/>/g, '>').replace(///g, '/').replace(/\/g, '\\\\').replace(/`/g, '`');\n}\n\nmodule.exports = exports.default;\nmodule.exports.default = exports.default;\n\n//# sourceURL=webpack:///./node_modules/validator/lib/unescape.js?");
/***/ }),
/***/ "./node_modules/validator/lib/util/assertString.js":
/*!*********************************************************!*\
!*** ./node_modules/validator/lib/util/assertString.js ***!
\*********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
eval("\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = assertString;\n\nfunction _typeof(obj) { \"@babel/helpers - typeof\"; if (typeof Symbol === \"function\" && typeof Symbol.iterator === \"symbol\") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === \"function\" && obj.constructor === Symbol && obj !== Symbol.prototype ? \"symbol\" : typeof obj; }; } return _typeof(obj); }\n\nfunction assertString(input) {\n var isString = typeof input === 'string' || input instanceof String;\n\n if (!isString) {\n var invalidType;\n\n if (input === null) {\n invalidType = 'null';\n } else {\n invalidType = _typeof(input);\n\n if (invalidType === 'object' && input.constructor && input.constructor.hasOwnProperty('name')) {\n invalidType = input.constructor.name;\n } else {\n invalidType = \"a \".concat(invalidType);\n }\n }\n\n throw new TypeError(\"Expected string but received \".concat(invalidType, \".\"));\n }\n}\n\nmodule.exports = exports.default;\nmodule.exports.default = exports.default;\n\n//# sourceURL=webpack:///./node_modules/validator/lib/util/assertString.js?");
/***/ }),
/***/ "./node_modules/validator/lib/util/includes.js":
/*!*****************************************************!*\
!*** ./node_modules/validator/lib/util/includes.js ***!
\*****************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
eval("\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = void 0;\n\nvar includes = function includes(arr, val) {\n return arr.some(function (arrVal) {\n return val === arrVal;\n });\n};\n\nvar _default = includes;\nexports.default = _default;\nmodule.exports = exports.default;\nmodule.exports.default = exports.default;\n\n//# sourceURL=webpack:///./node_modules/validator/lib/util/includes.js?");
/***/ }),
/***/ "./node_modules/validator/lib/util/merge.js":
/*!**************************************************!*\
!*** ./node_modules/validator/lib/util/merge.js ***!
\**************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
eval("\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = merge;\n\nfunction merge() {\n var obj = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};\n var defaults = arguments.length > 1 ? arguments[1] : undefined;\n\n for (var key in defaults) {\n if (typeof obj[key] === 'undefined') {\n obj[key] = defaults[key];\n }\n }\n\n return obj;\n}\n\nmodule.exports = exports.default;\nmodule.exports.default = exports.default;\n\n//# sourceURL=webpack:///./node_modules/validator/lib/util/merge.js?");
/***/ }),
/***/ "./node_modules/validator/lib/util/multilineRegex.js":
/*!***********************************************************!*\
!*** ./node_modules/validator/lib/util/multilineRegex.js ***!
\***********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
eval("\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = multilineRegexp;\n\n/**\n * Build RegExp object from an array\n * of multiple/multi-line regexp parts\n *\n * @param {string[]} parts\n * @param {string} flags\n * @return {object} - RegExp object\n */\nfunction multilineRegexp(parts) {\n var flags = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : '';\n var regexpAsStringLiteral = parts.join('');\n return new RegExp(regexpAsStringLiteral, flags);\n}\n\nmodule.exports = exports.default;\nmodule.exports.default = exports.default;\n\n//# sourceURL=webpack:///./node_modules/validator/lib/util/multilineRegex.js?");
/***/ }),
/***/ "./node_modules/validator/lib/util/toString.js":
/*!*****************************************************!*\
!*** ./node_modules/validator/lib/util/toString.js ***!
\*****************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
eval("\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = toString;\n\nfunction _typeof(obj) { \"@babel/helpers - typeof\"; if (typeof Symbol === \"function\" && typeof Symbol.iterator === \"symbol\") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === \"function\" && obj.constructor === Symbol && obj !== Symbol.prototype ? \"symbol\" : typeof obj; }; } return _typeof(obj); }\n\nfunction toString(input) {\n if (_typeof(input) === 'object' && input !== null) {\n if (typeof input.toString === 'function') {\n input = input.toString();\n } else {\n input = '[object Object]';\n }\n } else if (input === null || typeof input === 'undefined' || isNaN(input) && !input.length) {\n input = '';\n }\n\n return String(input);\n}\n\nmodule.exports = exports.default;\nmodule.exports.default = exports.default;\n\n//# sourceURL=webpack:///./node_modules/validator/lib/util/toString.js?");
/***/ }),
/***/ "./node_modules/validator/lib/whitelist.js":
/*!*************************************************!*\
!*** ./node_modules/validator/lib/whitelist.js ***!
\*************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
eval("\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = whitelist;\n\nvar _assertString = _interopRequireDefault(__webpack_require__(/*! ./util/assertString */ \"./node_modules/validator/lib/util/assertString.js\"));\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\nfunction whitelist(str, chars) {\n (0, _assertString.default)(str);\n return str.replace(new RegExp(\"[^\".concat(chars, \"]+\"), 'g'), '');\n}\n\nmodule.exports = exports.default;\nmodule.exports.default = exports.default;\n\n//# sourceURL=webpack:///./node_modules/validator/lib/whitelist.js?");
/***/ }),
/***/ "./node_modules/value-equal/esm/value-equal.js":
/*!*****************************************************!*\
!*** ./node_modules/value-equal/esm/value-equal.js ***!
\*****************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
eval("__webpack_require__.r(__webpack_exports__);\nfunction valueOf(obj) {\n return obj.valueOf ? obj.valueOf() : Object.prototype.valueOf.call(obj);\n}\n\nfunction valueEqual(a, b) {\n // Test for strict equality first.\n if (a === b) return true;\n\n // Otherwise, if either of them == null they are not equal.\n if (a == null || b == null) return false;\n\n if (Array.isArray(a)) {\n return (\n Array.isArray(b) &&\n a.length === b.length &&\n a.every(function(item, index) {\n return valueEqual(item, b[index]);\n })\n );\n }\n\n if (typeof a === 'object' || typeof b === 'object') {\n var aValue = valueOf(a);\n var bValue = valueOf(b);\n\n if (aValue !== a || bValue !== b) return valueEqual(aValue, bValue);\n\n return Object.keys(Object.assign({}, a, b)).every(function(key) {\n return valueEqual(a[key], b[key]);\n });\n }\n\n return false;\n}\n\n/* harmony default export */ __webpack_exports__[\"default\"] = (valueEqual);\n\n\n//# sourceURL=webpack:///./node_modules/value-equal/esm/value-equal.js?");
/***/ }),
/***/ "./node_modules/webpack/buildin/global.js":
/*!***********************************!*\
!*** (webpack)/buildin/global.js ***!
\***********************************/
/*! no static exports found */
/***/ (function(module, exports) {
eval("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\n\n//# sourceURL=webpack:///(webpack)/buildin/global.js?");
/***/ }),
/***/ "./src/App.css":
/*!*********************!*\
!*** ./src/App.css ***!
\*********************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
eval("var api = __webpack_require__(/*! ../node_modules/style-loader/dist/runtime/injectStylesIntoStyleTag.js */ \"./node_modules/style-loader/dist/runtime/injectStylesIntoStyleTag.js\");\n var content = __webpack_require__(/*! !../node_modules/css-loader/dist/cjs.js!./App.css */ \"./node_modules/css-loader/dist/cjs.js!./src/App.css\");\n\n content = content.__esModule ? content.default : content;\n\n if (typeof content === 'string') {\n content = [[module.i, content, '']];\n }\n\nvar options = {};\n\noptions.insert = \"head\";\noptions.singleton = false;\n\nvar update = api(content, options);\n\n\n\nmodule.exports = content.locals || {};\n\n//# sourceURL=webpack:///./src/App.css?");
/***/ }),
/***/ "./src/App.js":
/*!********************!*\
!*** ./src/App.js ***!
\********************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
eval("__webpack_require__.r(__webpack_exports__);\n/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! react */ \"./node_modules/react/index.js\");\n/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);\n/* harmony import */ var react_router_dom__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! react-router-dom */ \"./node_modules/react-router-dom/esm/react-router-dom.js\");\n/* harmony import */ var bootstrap_dist_css_bootstrap_min_css__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! bootstrap/dist/css/bootstrap.min.css */ \"./node_modules/bootstrap/dist/css/bootstrap.min.css\");\n/* harmony import */ var bootstrap_dist_css_bootstrap_min_css__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(bootstrap_dist_css_bootstrap_min_css__WEBPACK_IMPORTED_MODULE_2__);\n/* harmony import */ var _App_css__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./App.css */ \"./src/App.css\");\n/* harmony import */ var _App_css__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(_App_css__WEBPACK_IMPORTED_MODULE_3__);\n/* harmony import */ var _services_auth_service__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./services/auth-service */ \"./src/services/auth-service.js\");\n/* harmony import */ var _components_login_component__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./components/login.component */ \"./src/components/login.component.js\");\n/* harmony import */ var _components_register_component__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./components/register.component */ \"./src/components/register.component.js\");\n/* harmony import */ var _components_home_component__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./components/home.component */ \"./src/components/home.component.js\");\n/* harmony import */ var _components_profile_component__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./components/profile.component */ \"./src/components/profile.component.js\");\n/* harmony import */ var _components_board_user_component__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ./components/board-user.component */ \"./src/components/board-user.component.js\");\nfunction _typeof(obj) { \"@babel/helpers - typeof\"; if (typeof Symbol === \"function\" && typeof Symbol.iterator === \"symbol\") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === \"function\" && obj.constructor === Symbol && obj !== Symbol.prototype ? \"symbol\" : typeof obj; }; } return _typeof(obj); }\n\nfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(\"Cannot call a class as a function\"); } }\n\nfunction _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if (\"value\" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }\n\nfunction _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }\n\nfunction _inherits(subClass, superClass) { if (typeof superClass !== \"function\" && superClass !== null) { throw new TypeError(\"Super expression must either be null or a function\"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); }\n\nfunction _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }\n\nfunction _createSuper(Derived) { return function () { var Super = _getPrototypeOf(Derived), result; if (_isNativeReflectConstruct()) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }\n\nfunction _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === \"object\" || typeof call === \"function\")) { return call; } return _assertThisInitialized(self); }\n\nfunction _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError(\"this hasn't been initialised - super() hasn't been called\"); } return self; }\n\nfunction _isNativeReflectConstruct() { if (typeof Reflect === \"undefined\" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === \"function\") return true; try { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } }\n\nfunction _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }\n\n\n\n\n\n\n\n\n\n\n\n\nvar App = /*#__PURE__*/function (_Component) {\n _inherits(App, _Component);\n\n var _super = _createSuper(App);\n\n function App(props) {\n var _this;\n\n _classCallCheck(this, App);\n\n _this = _super.call(this, props);\n _this.logOut = _this.logOut.bind(_assertThisInitialized(_this));\n _this.state = {\n showModeratorBoard: false,\n showAdminBoard: false,\n currentUser: undefined\n };\n return _this;\n }\n\n _createClass(App, [{\n key: \"componentDidMount\",\n value: function componentDidMount() {\n var user = _services_auth_service__WEBPACK_IMPORTED_MODULE_4__[\"default\"].getCurrentUser();\n\n if (user) {\n this.setState({\n currentUser: _services_auth_service__WEBPACK_IMPORTED_MODULE_4__[\"default\"].getCurrentUser() // showModeratorBoard: user.roles.includes(\"ROLE_MODERATOR\"),\n // showAdminBoard: user.roles.includes(\"ROLE_ADMIN\")\n\n });\n }\n }\n }, {\n key: \"logOut\",\n value: function logOut() {\n _services_auth_service__WEBPACK_IMPORTED_MODULE_4__[\"default\"].logout();\n }\n }, {\n key: \"render\",\n value: function render() {\n var _this$state = this.state,\n currentUser = _this$state.currentUser,\n showModeratorBoard = _this$state.showModeratorBoard,\n showAdminBoard = _this$state.showAdminBoard;\n return /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(react_router_dom__WEBPACK_IMPORTED_MODULE_1__[\"BrowserRouter\"], null, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(\"div\", null, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(\"nav\", {\n className: \"navbar navbar-expand navbar-dark bg-dark\"\n }, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(react_router_dom__WEBPACK_IMPORTED_MODULE_1__[\"Link\"], {\n to: \"/\",\n className: \"navbar-brand\"\n }, \"VideoService\"), /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(\"div\", {\n className: \"navbar-nav mr-auto\"\n }, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(\"li\", {\n className: \"nav-item\"\n }, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(react_router_dom__WEBPACK_IMPORTED_MODULE_1__[\"Link\"], {\n to: \"/home\",\n className: \"nav-link\"\n }, \"Home\")), showModeratorBoard && /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(\"li\", {\n className: \"nav-item\"\n }, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(react_router_dom__WEBPACK_IMPORTED_MODULE_1__[\"Link\"], {\n to: \"/mod\",\n className: \"nav-link\"\n }, \"Moderator Board\")), showAdminBoard && /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(\"li\", {\n className: \"nav-item\"\n }, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(react_router_dom__WEBPACK_IMPORTED_MODULE_1__[\"Link\"], {\n to: \"/admin\",\n className: \"nav-link\"\n }, \"Admin Board\")), currentUser && /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(\"li\", {\n className: \"nav-item\"\n }, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(react_router_dom__WEBPACK_IMPORTED_MODULE_1__[\"Link\"], {\n to: \"/user\",\n className: \"nav-link\"\n }, \"User\"))), currentUser ? /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(\"div\", {\n className: \"navbar-nav ml-auto\"\n }, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(\"li\", {\n className: \"nav-item\"\n }, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(react_router_dom__WEBPACK_IMPORTED_MODULE_1__[\"Link\"], {\n to: \"/profile\",\n className: \"nav-link\"\n }, currentUser.username)), /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(\"li\", {\n className: \"nav-item\"\n }, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(\"a\", {\n href: \"/\",\n className: \"nav-link\",\n onClick: this.logOut\n }, \"LogOut\"))) : /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(\"div\", {\n className: \"navbar-nav ml-auto\"\n }, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(\"li\", {\n className: \"nav-item\"\n }, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(react_router_dom__WEBPACK_IMPORTED_MODULE_1__[\"Link\"], {\n to: \"/login\",\n className: \"nav-link\"\n }, \"Login\")), /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(\"li\", {\n className: \"nav-item\"\n }, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(react_router_dom__WEBPACK_IMPORTED_MODULE_1__[\"Link\"], {\n to: \"/register\",\n className: \"nav-link\"\n }, \"Sign Up\")))), /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(\"div\", {\n className: \"container mt-3\"\n }, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(react_router_dom__WEBPACK_IMPORTED_MODULE_1__[\"Switch\"], null, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(react_router_dom__WEBPACK_IMPORTED_MODULE_1__[\"Route\"], {\n exact: true,\n path: [\"/\", \"/home\"],\n component: _components_home_component__WEBPACK_IMPORTED_MODULE_7__[\"default\"]\n }), /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(react_router_dom__WEBPACK_IMPORTED_MODULE_1__[\"Route\"], {\n exact: true,\n path: \"/login\",\n component: _components_login_component__WEBPACK_IMPORTED_MODULE_5__[\"default\"]\n }), /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(react_router_dom__WEBPACK_IMPORTED_MODULE_1__[\"Route\"], {\n exact: true,\n path: \"/register\",\n component: _components_register_component__WEBPACK_IMPORTED_MODULE_6__[\"default\"]\n }), /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(react_router_dom__WEBPACK_IMPORTED_MODULE_1__[\"Route\"], {\n exact: true,\n path: \"/profile\",\n component: _components_profile_component__WEBPACK_IMPORTED_MODULE_8__[\"default\"]\n }), /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(react_router_dom__WEBPACK_IMPORTED_MODULE_1__[\"Route\"], {\n path: \"/user\",\n component: _components_board_user_component__WEBPACK_IMPORTED_MODULE_9__[\"default\"]\n })))));\n }\n }]);\n\n return App;\n}(react__WEBPACK_IMPORTED_MODULE_0__[\"Component\"]);\n\n/* harmony default export */ __webpack_exports__[\"default\"] = (App);\n\n//# sourceURL=webpack:///./src/App.js?");
/***/ }),
/***/ "./src/components/board-user.component.js":
/*!************************************************!*\
!*** ./src/components/board-user.component.js ***!
\************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"default\", function() { return BoardUser; });\n/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! react */ \"./node_modules/react/index.js\");\n/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);\n/* harmony import */ var _services_user_service__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../services/user-service */ \"./src/services/user-service.js\");\nfunction _typeof(obj) { \"@babel/helpers - typeof\"; if (typeof Symbol === \"function\" && typeof Symbol.iterator === \"symbol\") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === \"function\" && obj.constructor === Symbol && obj !== Symbol.prototype ? \"symbol\" : typeof obj; }; } return _typeof(obj); }\n\nfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(\"Cannot call a class as a function\"); } }\n\nfunction _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if (\"value\" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }\n\nfunction _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }\n\nfunction _inherits(subClass, superClass) { if (typeof superClass !== \"function\" && superClass !== null) { throw new TypeError(\"Super expression must either be null or a function\"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); }\n\nfunction _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }\n\nfunction _createSuper(Derived) { return function () { var Super = _getPrototypeOf(Derived), result; if (_isNativeReflectConstruct()) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }\n\nfunction _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === \"object\" || typeof call === \"function\")) { return call; } return _assertThisInitialized(self); }\n\nfunction _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError(\"this hasn't been initialised - super() hasn't been called\"); } return self; }\n\nfunction _isNativeReflectConstruct() { if (typeof Reflect === \"undefined\" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === \"function\") return true; try { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } }\n\nfunction _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }\n\n\n\n\nvar BoardUser = /*#__PURE__*/function (_Component) {\n _inherits(BoardUser, _Component);\n\n var _super = _createSuper(BoardUser);\n\n function BoardUser(props) {\n var _this;\n\n _classCallCheck(this, BoardUser);\n\n _this = _super.call(this, props);\n _this.state = {\n content: \"\"\n };\n return _this;\n }\n\n _createClass(BoardUser, [{\n key: \"componentDidMount\",\n value: function componentDidMount() {\n var _this2 = this;\n\n _services_user_service__WEBPACK_IMPORTED_MODULE_1__[\"default\"].getUserBoard().then(function (response) {\n _this2.setState({\n content: response.data\n });\n }, function (error) {\n _this2.setState({\n content: error.response && error.response.data && error.response.data.message || error.message || error.toString()\n });\n });\n }\n }, {\n key: \"render\",\n value: function render() {\n return /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(\"div\", {\n className: \"container\"\n }, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(\"header\", {\n className: \"jumbotron\"\n }, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(\"h3\", null, this.state.content)));\n }\n }]);\n\n return BoardUser;\n}(react__WEBPACK_IMPORTED_MODULE_0__[\"Component\"]);\n\n\n\n//# sourceURL=webpack:///./src/components/board-user.component.js?");
/***/ }),
/***/ "./src/components/home.component.js":
/*!******************************************!*\
!*** ./src/components/home.component.js ***!
\******************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"default\", function() { return Home; });\n/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! react */ \"./node_modules/react/index.js\");\n/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);\n/* harmony import */ var _services_user_service__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../services/user-service */ \"./src/services/user-service.js\");\nfunction _typeof(obj) { \"@babel/helpers - typeof\"; if (typeof Symbol === \"function\" && typeof Symbol.iterator === \"symbol\") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === \"function\" && obj.constructor === Symbol && obj !== Symbol.prototype ? \"symbol\" : typeof obj; }; } return _typeof(obj); }\n\nfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(\"Cannot call a class as a function\"); } }\n\nfunction _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if (\"value\" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }\n\nfunction _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }\n\nfunction _inherits(subClass, superClass) { if (typeof superClass !== \"function\" && superClass !== null) { throw new TypeError(\"Super expression must either be null or a function\"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); }\n\nfunction _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }\n\nfunction _createSuper(Derived) { return function () { var Super = _getPrototypeOf(Derived), result; if (_isNativeReflectConstruct()) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }\n\nfunction _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === \"object\" || typeof call === \"function\")) { return call; } return _assertThisInitialized(self); }\n\nfunction _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError(\"this hasn't been initialised - super() hasn't been called\"); } return self; }\n\nfunction _isNativeReflectConstruct() { if (typeof Reflect === \"undefined\" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === \"function\") return true; try { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } }\n\nfunction _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }\n\n\n\n\nvar Home = /*#__PURE__*/function (_Component) {\n _inherits(Home, _Component);\n\n var _super = _createSuper(Home);\n\n function Home(props) {\n var _this;\n\n _classCallCheck(this, Home);\n\n _this = _super.call(this, props);\n _this.state = {\n content: \"\"\n };\n return _this;\n }\n\n _createClass(Home, [{\n key: \"componentDidMount\",\n value: function componentDidMount() {\n var _this2 = this;\n\n _services_user_service__WEBPACK_IMPORTED_MODULE_1__[\"default\"].getPublicContent().then(function (response) {\n _this2.setState({\n content: response.data\n });\n }, function (error) {\n _this2.setState({\n content: error.response && error.response.data || error.message || error.toString()\n });\n });\n }\n }, {\n key: \"render\",\n value: function render() {\n return /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(\"div\", {\n className: \"container\"\n }, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(\"header\", {\n className: \"jumbotron\"\n }, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(\"h3\", null, this.state.content)));\n }\n }]);\n\n return Home;\n}(react__WEBPACK_IMPORTED_MODULE_0__[\"Component\"]);\n\n\n\n//# sourceURL=webpack:///./src/components/home.component.js?");
/***/ }),
/***/ "./src/components/login.component.js":
/*!*******************************************!*\
!*** ./src/components/login.component.js ***!
\*******************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"default\", function() { return Login; });\n/* harmony import */ var react_validation_build_form__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! react-validation/build/form */ \"./node_modules/react-validation/build/form.js\");\n/* harmony import */ var react_validation_build_form__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react_validation_build_form__WEBPACK_IMPORTED_MODULE_0__);\n/* harmony import */ var react_validation_build_input__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! react-validation/build/input */ \"./node_modules/react-validation/build/input.js\");\n/* harmony import */ var react_validation_build_input__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(react_validation_build_input__WEBPACK_IMPORTED_MODULE_1__);\n/* harmony import */ var react_validation_build_button__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! react-validation/build/button */ \"./node_modules/react-validation/build/button.js\");\n/* harmony import */ var react_validation_build_button__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(react_validation_build_button__WEBPACK_IMPORTED_MODULE_2__);\n/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! react */ \"./node_modules/react/index.js\");\n/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_3__);\n/* harmony import */ var _services_auth_service__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../services/auth-service */ \"./src/services/auth-service.js\");\n/* harmony import */ var react_router_dom__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! react-router-dom */ \"./node_modules/react-router-dom/esm/react-router-dom.js\");\n/* harmony import */ var validator__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! validator */ \"./node_modules/validator/index.js\");\n/* harmony import */ var validator__WEBPACK_IMPORTED_MODULE_6___default = /*#__PURE__*/__webpack_require__.n(validator__WEBPACK_IMPORTED_MODULE_6__);\nfunction _typeof(obj) { \"@babel/helpers - typeof\"; if (typeof Symbol === \"function\" && typeof Symbol.iterator === \"symbol\") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === \"function\" && obj.constructor === Symbol && obj !== Symbol.prototype ? \"symbol\" : typeof obj; }; } return _typeof(obj); }\n\nfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(\"Cannot call a class as a function\"); } }\n\nfunction _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if (\"value\" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }\n\nfunction _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }\n\nfunction _inherits(subClass, superClass) { if (typeof superClass !== \"function\" && superClass !== null) { throw new TypeError(\"Super expression must either be null or a function\"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); }\n\nfunction _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }\n\nfunction _createSuper(Derived) { return function () { var Super = _getPrototypeOf(Derived), result; if (_isNativeReflectConstruct()) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }\n\nfunction _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === \"object\" || typeof call === \"function\")) { return call; } return _assertThisInitialized(self); }\n\nfunction _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError(\"this hasn't been initialised - super() hasn't been called\"); } return self; }\n\nfunction _isNativeReflectConstruct() { if (typeof Reflect === \"undefined\" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === \"function\") return true; try { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } }\n\nfunction _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }\n\n\n\n\n\n\n\n\n\nvar required = function required(value) {\n if (!value) {\n return /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement(\"div\", {\n className: \"alert alert-danger\",\n role: \"alert\"\n }, \"This field is required!\");\n }\n};\n\nvar Login = /*#__PURE__*/function (_Component) {\n _inherits(Login, _Component);\n\n var _super = _createSuper(Login);\n\n function Login(props) {\n var _this;\n\n _classCallCheck(this, Login);\n\n _this = _super.call(this, props);\n _this.handleLogin = _this.handleLogin.bind(_assertThisInitialized(_this));\n _this.onChangeUsername = _this.onChangeUsername.bind(_assertThisInitialized(_this));\n _this.onChangePassword = _this.onChangePassword.bind(_assertThisInitialized(_this));\n _this.state = {\n username: \"\",\n password: \"\",\n loading: false,\n message: \"\"\n };\n return _this;\n }\n\n _createClass(Login, [{\n key: \"onChangeUsername\",\n value: function onChangeUsername(e) {\n this.setState({\n username: e.target.value\n });\n }\n }, {\n key: \"onChangePassword\",\n value: function onChangePassword(e) {\n this.setState({\n password: e.target.value\n });\n }\n }, {\n key: \"handleLogin\",\n value: function handleLogin(e) {\n var _this2 = this;\n\n e.preventDefault();\n this.setState({\n message: \"\",\n loading: true\n });\n this.form.validateAll();\n\n if (this.checkBtn.context._errors.length === 0) {\n _services_auth_service__WEBPACK_IMPORTED_MODULE_4__[\"default\"].login(this.state.username, this.state.password).then(function () {\n _this2.props.history.push(\"/\");\n\n window.location.reload();\n }, function (error) {\n var resMessage = error.response && error.response.data && error.response.data.message || error.message || error.toString();\n\n _this2.setState({\n loading: false,\n message: resMessage\n });\n });\n } else {\n this.setState({\n loading: false\n });\n }\n }\n }, {\n key: \"render\",\n value: function render() {\n var _this3 = this;\n\n return /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement(\"div\", {\n className: \"col-md-12\"\n }, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement(\"div\", {\n className: \"card card-container\"\n }, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement(\"img\", {\n src: \"//ssl.gstatic.com/accounts/ui/avatar_2x.png\",\n alt: \"profile-img\",\n className: \"profile-img-card\"\n }), /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement(react_validation_build_form__WEBPACK_IMPORTED_MODULE_0___default.a, {\n onSubmit: this.handleLogin,\n ref: function ref(c) {\n _this3.form = c;\n }\n }, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement(\"div\", {\n className: \"form-group\"\n }, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement(\"label\", {\n htmlFor: \"username\"\n }, \"Username\"), /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement(react_validation_build_input__WEBPACK_IMPORTED_MODULE_1___default.a, {\n type: \"text\",\n className: \"form-control\",\n name: \"username\",\n value: this.state.username,\n onChange: this.onChangeUsername,\n validations: [required]\n })), /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement(\"div\", {\n className: \"form-group\"\n }, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement(\"label\", {\n htmlFor: \"password\"\n }, \"Password\"), /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement(react_validation_build_input__WEBPACK_IMPORTED_MODULE_1___default.a, {\n type: \"password\",\n className: \"form-control\",\n name: \"password\",\n value: this.state.password,\n onChange: this.onChangePassword,\n validations: [required]\n })), /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement(\"div\", {\n className: \"form-group\"\n }, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement(\"button\", {\n className: \"btn btn-primary btn-block\",\n disabled: this.state.loading\n }, this.state.loading && /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement(\"span\", {\n className: \"spinner-border spinner-border-sm\"\n }), /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement(\"span\", null, \"Login\"))), this.state.message && /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement(\"div\", {\n className: \"form-group\"\n }, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement(\"div\", {\n className: \"alert alert-danger\",\n role: \"alert\"\n }, this.state.message)), /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement(react_validation_build_button__WEBPACK_IMPORTED_MODULE_2___default.a, {\n style: {\n display: \"none\"\n },\n ref: function ref(c) {\n _this3.checkBtn = c;\n }\n }))));\n }\n }]);\n\n return Login;\n}(react__WEBPACK_IMPORTED_MODULE_3__[\"Component\"]);\n\n\n\n//# sourceURL=webpack:///./src/components/login.component.js?");
/***/ }),
/***/ "./src/components/profile.component.js":
/*!*********************************************!*\
!*** ./src/components/profile.component.js ***!
\*********************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"default\", function() { return Profile; });\n/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! react */ \"./node_modules/react/index.js\");\n/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);\n/* harmony import */ var _services_auth_service__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../services/auth-service */ \"./src/services/auth-service.js\");\nfunction _typeof(obj) { \"@babel/helpers - typeof\"; if (typeof Symbol === \"function\" && typeof Symbol.iterator === \"symbol\") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === \"function\" && obj.constructor === Symbol && obj !== Symbol.prototype ? \"symbol\" : typeof obj; }; } return _typeof(obj); }\n\nfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(\"Cannot call a class as a function\"); } }\n\nfunction _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if (\"value\" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }\n\nfunction _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }\n\nfunction _inherits(subClass, superClass) { if (typeof superClass !== \"function\" && superClass !== null) { throw new TypeError(\"Super expression must either be null or a function\"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); }\n\nfunction _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }\n\nfunction _createSuper(Derived) { return function () { var Super = _getPrototypeOf(Derived), result; if (_isNativeReflectConstruct()) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }\n\nfunction _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === \"object\" || typeof call === \"function\")) { return call; } return _assertThisInitialized(self); }\n\nfunction _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError(\"this hasn't been initialised - super() hasn't been called\"); } return self; }\n\nfunction _isNativeReflectConstruct() { if (typeof Reflect === \"undefined\" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === \"function\") return true; try { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } }\n\nfunction _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }\n\n\n\n\nvar Profile = /*#__PURE__*/function (_Component) {\n _inherits(Profile, _Component);\n\n var _super = _createSuper(Profile);\n\n function Profile(props) {\n var _this;\n\n _classCallCheck(this, Profile);\n\n _this = _super.call(this, props);\n _this.state = {\n currentUser: _services_auth_service__WEBPACK_IMPORTED_MODULE_1__[\"default\"].getCurrentUser()\n };\n return _this;\n }\n\n _createClass(Profile, [{\n key: \"render\",\n value: function render() {\n var currentUser = this.state.currentUser;\n return /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(\"div\", {\n className: \"container\"\n }, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(\"header\", {\n className: \"jumbotron\"\n }, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(\"h3\", null, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(\"strong\", null, currentUser.username), \" Profile\")), /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(\"p\", null, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(\"strong\", null, \"Token:\"), \" \", currentUser.accessToken.substring(0, 20), \" ...\", \" \", currentUser.accessToken.substr(currentUser.accessToken.length - 20)), /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(\"p\", null, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(\"strong\", null, \"Id:\"), \" \", currentUser.id), /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(\"p\", null, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(\"strong\", null, \"Email:\"), \" \", currentUser.email), /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(\"strong\", null, \"Authorities:\"), /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(\"ul\", null, currentUser.roles && currentUser.roles.map(function (role, index) {\n return /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(\"li\", {\n key: index\n }, role);\n })));\n }\n }]);\n\n return Profile;\n}(react__WEBPACK_IMPORTED_MODULE_0__[\"Component\"]);\n\n\n\n//# sourceURL=webpack:///./src/components/profile.component.js?");
/***/ }),
/***/ "./src/components/register.component.js":
/*!**********************************************!*\
!*** ./src/components/register.component.js ***!
\**********************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"default\", function() { return Register; });\n/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! react */ \"./node_modules/react/index.js\");\n/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);\n/* harmony import */ var react_validation_build_form__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! react-validation/build/form */ \"./node_modules/react-validation/build/form.js\");\n/* harmony import */ var react_validation_build_form__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(react_validation_build_form__WEBPACK_IMPORTED_MODULE_1__);\n/* harmony import */ var react_validation_build_input__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! react-validation/build/input */ \"./node_modules/react-validation/build/input.js\");\n/* harmony import */ var react_validation_build_input__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(react_validation_build_input__WEBPACK_IMPORTED_MODULE_2__);\n/* harmony import */ var react_validation_build_button__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! react-validation/build/button */ \"./node_modules/react-validation/build/button.js\");\n/* harmony import */ var react_validation_build_button__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(react_validation_build_button__WEBPACK_IMPORTED_MODULE_3__);\n/* harmony import */ var validator__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! validator */ \"./node_modules/validator/index.js\");\n/* harmony import */ var validator__WEBPACK_IMPORTED_MODULE_4___default = /*#__PURE__*/__webpack_require__.n(validator__WEBPACK_IMPORTED_MODULE_4__);\n/* harmony import */ var _services_auth_service__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../services/auth-service */ \"./src/services/auth-service.js\");\nfunction _typeof(obj) { \"@babel/helpers - typeof\"; if (typeof Symbol === \"function\" && typeof Symbol.iterator === \"symbol\") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === \"function\" && obj.constructor === Symbol && obj !== Symbol.prototype ? \"symbol\" : typeof obj; }; } return _typeof(obj); }\n\nfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(\"Cannot call a class as a function\"); } }\n\nfunction _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if (\"value\" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }\n\nfunction _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }\n\nfunction _inherits(subClass, superClass) { if (typeof superClass !== \"function\" && superClass !== null) { throw new TypeError(\"Super expression must either be null or a function\"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); }\n\nfunction _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }\n\nfunction _createSuper(Derived) { return function () { var Super = _getPrototypeOf(Derived), result; if (_isNativeReflectConstruct()) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }\n\nfunction _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === \"object\" || typeof call === \"function\")) { return call; } return _assertThisInitialized(self); }\n\nfunction _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError(\"this hasn't been initialised - super() hasn't been called\"); } return self; }\n\nfunction _isNativeReflectConstruct() { if (typeof Reflect === \"undefined\" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === \"function\") return true; try { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } }\n\nfunction _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }\n\n\n\n\n\n\n\n\nvar required = function required(value) {\n if (!value) {\n return /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(\"div\", {\n className: \"alert alert-danger\",\n role: \"alert\"\n }, \"This field is required!\");\n }\n};\n\nvar email = function email(value) {\n if (!Object(validator__WEBPACK_IMPORTED_MODULE_4__[\"isEmail\"])(value)) {\n return /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(\"div\", {\n className: \"alert alert-danger\",\n role: \"alert\"\n }, \"This is not a valid email.\");\n }\n};\n\nvar vusername = function vusername(value) {\n if (value.length < 3 || value.length > 20) {\n return /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(\"div\", {\n className: \"alert alert-danger\",\n role: \"alert\"\n }, \"The username must be between 3 and 20 characters.\");\n }\n};\n\nvar vpassword = function vpassword(value) {\n if (value.length < 6 || value.length > 40) {\n return /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(\"div\", {\n className: \"alert alert-danger\",\n role: \"alert\"\n }, \"The password must be between 6 and 40 characters.\");\n }\n};\n\nvar Register = /*#__PURE__*/function (_Component) {\n _inherits(Register, _Component);\n\n var _super = _createSuper(Register);\n\n function Register(props) {\n var _this;\n\n _classCallCheck(this, Register);\n\n _this = _super.call(this, props);\n _this.handleRegister = _this.handleRegister.bind(_assertThisInitialized(_this));\n _this.onChangeUsername = _this.onChangeUsername.bind(_assertThisInitialized(_this));\n _this.onChangeEmail = _this.onChangeEmail.bind(_assertThisInitialized(_this));\n _this.onChangePassword = _this.onChangePassword.bind(_assertThisInitialized(_this));\n _this.state = {\n username: \"\",\n email: \"\",\n password: \"\",\n successful: false,\n message: \"\"\n };\n return _this;\n }\n\n _createClass(Register, [{\n key: \"onChangeUsername\",\n value: function onChangeUsername(e) {\n this.setState({\n username: e.target.value\n });\n }\n }, {\n key: \"onChangeEmail\",\n value: function onChangeEmail(e) {\n this.setState({\n email: e.target.value\n });\n }\n }, {\n key: \"onChangePassword\",\n value: function onChangePassword(e) {\n this.setState({\n password: e.target.value\n });\n }\n }, {\n key: \"handleRegister\",\n value: function handleRegister(e) {\n var _this2 = this;\n\n e.preventDefault();\n this.setState({\n message: \"\",\n successful: false\n });\n this.form.validateAll();\n\n if (this.checkBtn.context._errors.length === 0) {\n _services_auth_service__WEBPACK_IMPORTED_MODULE_5__[\"default\"].register(this.state.username, this.state.email, this.state.password).then(function (response) {\n _this2.setState({\n message: response.data.message,\n successful: true\n });\n }, function (error) {\n var resMessage = error.response && error.response.data && error.response.data.message || error.message || error.toString();\n\n _this2.setState({\n successful: false,\n message: resMessage\n });\n });\n }\n }\n }, {\n key: \"render\",\n value: function render() {\n var _this3 = this;\n\n return /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(\"div\", {\n className: \"col-md-12\"\n }, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(\"div\", {\n className: \"card card-container\"\n }, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(\"img\", {\n src: \"//ssl.gstatic.com/accounts/ui/avatar_2x.png\",\n alt: \"profile-img\",\n className: \"profile-img-card\"\n }), /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(react_validation_build_form__WEBPACK_IMPORTED_MODULE_1___default.a, {\n onSubmit: this.handleRegister,\n ref: function ref(c) {\n _this3.form = c;\n }\n }, !this.state.successful && /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(\"div\", null, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(\"div\", {\n className: \"form-group\"\n }, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(\"label\", {\n htmlFor: \"username\"\n }, \"Username\"), /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(react_validation_build_input__WEBPACK_IMPORTED_MODULE_2___default.a, {\n type: \"text\",\n className: \"form-control\",\n name: \"username\",\n value: this.state.username,\n onChange: this.onChangeUsername,\n validations: [required, vusername]\n })), /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(\"div\", {\n className: \"form-group\"\n }, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(\"label\", {\n htmlFor: \"email\"\n }, \"Email\"), /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(react_validation_build_input__WEBPACK_IMPORTED_MODULE_2___default.a, {\n type: \"text\",\n className: \"form-control\",\n name: \"email\",\n value: this.state.email,\n onChange: this.onChangeEmail,\n validations: [required, email]\n })), /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(\"div\", {\n className: \"form-group\"\n }, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(\"label\", {\n htmlFor: \"password\"\n }, \"Password\"), /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(react_validation_build_input__WEBPACK_IMPORTED_MODULE_2___default.a, {\n type: \"password\",\n className: \"form-control\",\n name: \"password\",\n value: this.state.password,\n onChange: this.onChangePassword,\n validations: [required, vpassword]\n })), /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(\"div\", {\n className: \"form-group\"\n }, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(\"button\", {\n className: \"btn btn-primary btn-block\"\n }, \"Sign Up\"))), this.state.message && /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(\"div\", {\n className: \"form-group\"\n }, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(\"div\", {\n className: this.state.successful ? \"alert alert-success\" : \"alert alert-danger\",\n role: \"alert\"\n }, this.state.message)), /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(react_validation_build_button__WEBPACK_IMPORTED_MODULE_3___default.a, {\n style: {\n display: \"none\"\n },\n ref: function ref(c) {\n _this3.checkBtn = c;\n }\n }))));\n }\n }]);\n\n return Register;\n}(react__WEBPACK_IMPORTED_MODULE_0__[\"Component\"]);\n\n\n\n//# sourceURL=webpack:///./src/components/register.component.js?");
/***/ }),
/***/ "./src/index.js":
/*!**********************!*\
!*** ./src/index.js ***!
\**********************/
/*! no exports provided */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
eval("__webpack_require__.r(__webpack_exports__);\n/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! react */ \"./node_modules/react/index.js\");\n/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);\n/* harmony import */ var react_dom__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! react-dom */ \"./node_modules/react-dom/index.js\");\n/* harmony import */ var react_dom__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(react_dom__WEBPACK_IMPORTED_MODULE_1__);\n/* harmony import */ var react_router_dom__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! react-router-dom */ \"./node_modules/react-router-dom/esm/react-router-dom.js\");\n/* harmony import */ var _App__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./App */ \"./src/App.js\");\n\n\n // import MyInfo from \"./components/MyInfo\"\n//import App from './components/learning/LearningApp';\n\n\nreact_dom__WEBPACK_IMPORTED_MODULE_1___default.a.render( /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(react_router_dom__WEBPACK_IMPORTED_MODULE_2__[\"BrowserRouter\"], null, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(_App__WEBPACK_IMPORTED_MODULE_3__[\"default\"], null)), document.getElementById('root'));\n\n//# sourceURL=webpack:///./src/index.js?");
/***/ }),
/***/ "./src/services/auth-header.js":
/*!*************************************!*\
!*** ./src/services/auth-header.js ***!
\*************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"default\", function() { return authHeader; });\nfunction authHeader() {\n var user = JSON.parse(localStorage.getItem('user'));\n\n if (user && user.accessToken) {\n return {\n Authorization: 'Bearer ' + user.accessToken\n }; // for Spring Boot back-end\n // return { 'x-access-token': user.accessToken }; // for Node.js Express back-end\n } else {\n return {};\n }\n}\n\n//# sourceURL=webpack:///./src/services/auth-header.js?");
/***/ }),
/***/ "./src/services/auth-service.js":
/*!**************************************!*\
!*** ./src/services/auth-service.js ***!
\**************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
eval("__webpack_require__.r(__webpack_exports__);\n/* harmony import */ var axios__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! axios */ \"./node_modules/axios/index.js\");\n/* harmony import */ var axios__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(axios__WEBPACK_IMPORTED_MODULE_0__);\nfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(\"Cannot call a class as a function\"); } }\n\nfunction _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if (\"value\" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }\n\nfunction _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }\n\n\nvar API_URL = \"https://springboot-apis.herokuapp.com/api/auth/\";\n\nvar AuthService = /*#__PURE__*/function () {\n function AuthService() {\n _classCallCheck(this, AuthService);\n }\n\n _createClass(AuthService, [{\n key: \"login\",\n value: function login(username, password) {\n return axios__WEBPACK_IMPORTED_MODULE_0___default.a.post(API_URL + \"signin\", {\n username: username,\n password: password\n }).then(function (response) {\n if (response.data.accessToken) {\n localStorage.setItem(\"user\", JSON.stringify(response.data));\n }\n\n return response.data;\n });\n }\n }, {\n key: \"logout\",\n value: function logout() {\n localStorage.removeItem(\"user\");\n }\n }, {\n key: \"register\",\n value: function register(username, email, password) {\n return axios__WEBPACK_IMPORTED_MODULE_0___default.a.post(API_URL + \"signup\", {\n username: username,\n //email,\n password: password\n });\n }\n }, {\n key: \"getCurrentUser\",\n value: function getCurrentUser() {\n return JSON.parse(localStorage.getItem('user'));\n }\n }]);\n\n return AuthService;\n}();\n\n/* harmony default export */ __webpack_exports__[\"default\"] = (new AuthService());\n\n//# sourceURL=webpack:///./src/services/auth-service.js?");
/***/ }),
/***/ "./src/services/user-service.js":
/*!**************************************!*\
!*** ./src/services/user-service.js ***!
\**************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
eval("__webpack_require__.r(__webpack_exports__);\n/* harmony import */ var axios__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! axios */ \"./node_modules/axios/index.js\");\n/* harmony import */ var axios__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(axios__WEBPACK_IMPORTED_MODULE_0__);\n/* harmony import */ var _auth_header__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./auth-header */ \"./src/services/auth-header.js\");\nfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(\"Cannot call a class as a function\"); } }\n\nfunction _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if (\"value\" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }\n\nfunction _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }\n\n\n\nvar API_URL = 'https://springboot-apis.herokuapp.com/users/';\n\nvar UserService = /*#__PURE__*/function () {\n function UserService() {\n _classCallCheck(this, UserService);\n }\n\n _createClass(UserService, [{\n key: \"getPublicContent\",\n value: function getPublicContent() {\n return axios__WEBPACK_IMPORTED_MODULE_0___default.a.get(API_URL + 'all');\n }\n }, {\n key: \"getUserBoard\",\n value: function getUserBoard() {\n return axios__WEBPACK_IMPORTED_MODULE_0___default.a.get(API_URL + 'user', {\n headers: Object(_auth_header__WEBPACK_IMPORTED_MODULE_1__[\"default\"])()\n });\n }\n }, {\n key: \"getUserDetails\",\n value: function getUserDetails(userId) {\n return axios__WEBPACK_IMPORTED_MODULE_0___default.a.get(API_URL + userId, {\n headers: Object(_auth_header__WEBPACK_IMPORTED_MODULE_1__[\"default\"])()\n });\n }\n }, {\n key: \"getModeratorBoard\",\n value: function getModeratorBoard() {\n return axios__WEBPACK_IMPORTED_MODULE_0___default.a.get(API_URL + 'mod', {\n headers: Object(_auth_header__WEBPACK_IMPORTED_MODULE_1__[\"default\"])()\n });\n }\n }, {\n key: \"getAdminBoard\",\n value: function getAdminBoard() {\n return axios__WEBPACK_IMPORTED_MODULE_0___default.a.get(API_URL + 'admin', {\n headers: Object(_auth_header__WEBPACK_IMPORTED_MODULE_1__[\"default\"])()\n });\n }\n }]);\n\n return UserService;\n}();\n\n/* harmony default export */ __webpack_exports__[\"default\"] = (new UserService());\n\n//# sourceURL=webpack:///./src/services/user-service.js?");
/***/ })
/******/ }); | new build with video player
| bundle.js | new build with video player | <ide><path>undle.js
<ide> /***/ (function(module, __webpack_exports__, __webpack_require__) {
<ide>
<ide> "use strict";
<del>eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"default\", function() { return Home; });\n/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! react */ \"./node_modules/react/index.js\");\n/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);\n/* harmony import */ var _services_user_service__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../services/user-service */ \"./src/services/user-service.js\");\nfunction _typeof(obj) { \"@babel/helpers - typeof\"; if (typeof Symbol === \"function\" && typeof Symbol.iterator === \"symbol\") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === \"function\" && obj.constructor === Symbol && obj !== Symbol.prototype ? \"symbol\" : typeof obj; }; } return _typeof(obj); }\n\nfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(\"Cannot call a class as a function\"); } }\n\nfunction _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if (\"value\" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }\n\nfunction _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }\n\nfunction _inherits(subClass, superClass) { if (typeof superClass !== \"function\" && superClass !== null) { throw new TypeError(\"Super expression must either be null or a function\"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); }\n\nfunction _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }\n\nfunction _createSuper(Derived) { return function () { var Super = _getPrototypeOf(Derived), result; if (_isNativeReflectConstruct()) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }\n\nfunction _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === \"object\" || typeof call === \"function\")) { return call; } return _assertThisInitialized(self); }\n\nfunction _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError(\"this hasn't been initialised - super() hasn't been called\"); } return self; }\n\nfunction _isNativeReflectConstruct() { if (typeof Reflect === \"undefined\" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === \"function\") return true; try { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } }\n\nfunction _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }\n\n\n\n\nvar Home = /*#__PURE__*/function (_Component) {\n _inherits(Home, _Component);\n\n var _super = _createSuper(Home);\n\n function Home(props) {\n var _this;\n\n _classCallCheck(this, Home);\n\n _this = _super.call(this, props);\n _this.state = {\n content: \"\"\n };\n return _this;\n }\n\n _createClass(Home, [{\n key: \"componentDidMount\",\n value: function componentDidMount() {\n var _this2 = this;\n\n _services_user_service__WEBPACK_IMPORTED_MODULE_1__[\"default\"].getPublicContent().then(function (response) {\n _this2.setState({\n content: response.data\n });\n }, function (error) {\n _this2.setState({\n content: error.response && error.response.data || error.message || error.toString()\n });\n });\n }\n }, {\n key: \"render\",\n value: function render() {\n return /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(\"div\", {\n className: \"container\"\n }, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(\"header\", {\n className: \"jumbotron\"\n }, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(\"h3\", null, this.state.content)));\n }\n }]);\n\n return Home;\n}(react__WEBPACK_IMPORTED_MODULE_0__[\"Component\"]);\n\n\n\n//# sourceURL=webpack:///./src/components/home.component.js?");
<add>eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"default\", function() { return Home; });\n/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! react */ \"./node_modules/react/index.js\");\n/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);\n/* harmony import */ var _config_config__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../config/config */ \"./src/config/config.js\");\n/* harmony import */ var _services_user_service__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../services/user-service */ \"./src/services/user-service.js\");\n/* harmony import */ var _services_auth_service__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../services/auth-service */ \"./src/services/auth-service.js\");\nfunction _typeof(obj) { \"@babel/helpers - typeof\"; if (typeof Symbol === \"function\" && typeof Symbol.iterator === \"symbol\") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === \"function\" && obj.constructor === Symbol && obj !== Symbol.prototype ? \"symbol\" : typeof obj; }; } return _typeof(obj); }\n\nfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(\"Cannot call a class as a function\"); } }\n\nfunction _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if (\"value\" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }\n\nfunction _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }\n\nfunction _inherits(subClass, superClass) { if (typeof superClass !== \"function\" && superClass !== null) { throw new TypeError(\"Super expression must either be null or a function\"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); }\n\nfunction _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }\n\nfunction _createSuper(Derived) { return function () { var Super = _getPrototypeOf(Derived), result; if (_isNativeReflectConstruct()) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }\n\nfunction _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === \"object\" || typeof call === \"function\")) { return call; } return _assertThisInitialized(self); }\n\nfunction _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError(\"this hasn't been initialised - super() hasn't been called\"); } return self; }\n\nfunction _isNativeReflectConstruct() { if (typeof Reflect === \"undefined\" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === \"function\") return true; try { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } }\n\nfunction _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }\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\n\n\n\n\n\nvar Home = /*#__PURE__*/function (_Component) {\n _inherits(Home, _Component);\n\n var _super = _createSuper(Home);\n\n function Home(props) {\n var _this;\n\n _classCallCheck(this, Home);\n\n _this = _super.call(this, props);\n\n _defineProperty(_assertThisInitialized(_this), \"videoSecond\", 0);\n\n _this.state = {\n content: \"\",\n currentUser: undefined\n };\n _this.videoTimeHandler = _this.videoTimeHandler.bind(_assertThisInitialized(_this));\n return _this;\n }\n\n _createClass(Home, [{\n key: \"componentDidMount\",\n value: function componentDidMount() {\n var _this2 = this;\n\n _services_user_service__WEBPACK_IMPORTED_MODULE_2__[\"default\"].getPublicContent().then(function (response) {\n _this2.setState({\n content: response.data\n });\n }, function (error) {\n _this2.setState({\n content: error.response && error.response.data || error.message || error.toString()\n });\n });\n var user = _services_auth_service__WEBPACK_IMPORTED_MODULE_3__[\"default\"].getCurrentUser();\n\n if (user) {\n this.setState({\n currentUser: _services_auth_service__WEBPACK_IMPORTED_MODULE_3__[\"default\"].getCurrentUser() // showModeratorBoard: user.roles.includes(\"ROLE_MODERATOR\"),\n // showAdminBoard: user.roles.includes(\"ROLE_ADMIN\")\n\n });\n }\n }\n }, {\n key: \"videoTimeHandler\",\n value: function videoTimeHandler(event) {\n //console.log(event.target.currentTime)\n var minutes = Math.floor(event.target.currentTime / 60);\n var seconds = Math.floor(event.target.currentTime - minutes * 60);\n\n if (this.videoSecond === 20) {\n this.videoSecond = 0; // call api to save this in database\n\n _services_user_service__WEBPACK_IMPORTED_MODULE_2__[\"default\"].updateStatus(\"01-01_Trailer\", this.state.currentUser.id, minutes + \":\" + seconds).then(function (response) {\n console.log(\"response:\" + response);\n }, function (error) {\n console.log(\"error:\" + error);\n });\n console.log(minutes + \":\" + seconds);\n }\n\n this.videoSecond = this.videoSecond + 1; // setTimeout(function(){\n // console.log('your audio is started just now');\n // }, 1000)\n }\n }, {\n key: \"render\",\n value: function render() {\n return /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(\"div\", {\n className: \"container\"\n }, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(\"header\", {\n className: \"jumbotron\"\n }, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(\"h3\", null, this.state.content), this.state.currentUser ? /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(\"video\", {\n width: \"320\",\n height: \"240\",\n autoPlay: \"autoplay\",\n onTimeUpdate: this.videoTimeHandler,\n controls: true\n }, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(\"source\", {\n src: _config_config__WEBPACK_IMPORTED_MODULE_1__[\"default\"].backendHost + \"/videos/01-01_Trailer?access_token=\" + this.state.currentUser.accessToken,\n type: \"video/mp4\"\n })) : /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(\"p\", null)));\n }\n }]);\n\n return Home;\n}(react__WEBPACK_IMPORTED_MODULE_0__[\"Component\"]);\n\n\n\n//# sourceURL=webpack:///./src/components/home.component.js?");
<ide>
<ide> /***/ }),
<ide>
<ide>
<ide> /***/ }),
<ide>
<add>/***/ "./src/config/config.js":
<add>/*!******************************!*\
<add> !*** ./src/config/config.js ***!
<add> \******************************/
<add>/*! exports provided: default */
<add>/***/ (function(module, __webpack_exports__, __webpack_require__) {
<add>
<add>"use strict";
<add>eval("__webpack_require__.r(__webpack_exports__);\nvar host = window.location.hostname === 'localhost' ? 'http://localhost:8081' : \"https://springboot-apis.herokuapp.com\";\nvar config = {\n backendHost: host\n};\n/* harmony default export */ __webpack_exports__[\"default\"] = (config);\n\n//# sourceURL=webpack:///./src/config/config.js?");
<add>
<add>/***/ }),
<add>
<ide> /***/ "./src/index.js":
<ide> /*!**********************!*\
<ide> !*** ./src/index.js ***!
<ide> /***/ (function(module, __webpack_exports__, __webpack_require__) {
<ide>
<ide> "use strict";
<del>eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"default\", function() { return authHeader; });\nfunction authHeader() {\n var user = JSON.parse(localStorage.getItem('user'));\n\n if (user && user.accessToken) {\n return {\n Authorization: 'Bearer ' + user.accessToken\n }; // for Spring Boot back-end\n // return { 'x-access-token': user.accessToken }; // for Node.js Express back-end\n } else {\n return {};\n }\n}\n\n//# sourceURL=webpack:///./src/services/auth-header.js?");
<add>eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"default\", function() { return authHeader; });\nfunction authHeader() {\n var user = JSON.parse(localStorage.getItem('user'));\n\n if (user && user.accessToken) {\n return {\n Authorization: 'Bearer ' + user.accessToken,\n \"Access-Control-Allow-Origin\": \"*\"\n };\n } else {\n return {};\n }\n}\n\n//# sourceURL=webpack:///./src/services/auth-header.js?");
<ide>
<ide> /***/ }),
<ide>
<ide> /***/ (function(module, __webpack_exports__, __webpack_require__) {
<ide>
<ide> "use strict";
<del>eval("__webpack_require__.r(__webpack_exports__);\n/* harmony import */ var axios__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! axios */ \"./node_modules/axios/index.js\");\n/* harmony import */ var axios__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(axios__WEBPACK_IMPORTED_MODULE_0__);\nfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(\"Cannot call a class as a function\"); } }\n\nfunction _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if (\"value\" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }\n\nfunction _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }\n\n\nvar API_URL = \"https://springboot-apis.herokuapp.com/api/auth/\";\n\nvar AuthService = /*#__PURE__*/function () {\n function AuthService() {\n _classCallCheck(this, AuthService);\n }\n\n _createClass(AuthService, [{\n key: \"login\",\n value: function login(username, password) {\n return axios__WEBPACK_IMPORTED_MODULE_0___default.a.post(API_URL + \"signin\", {\n username: username,\n password: password\n }).then(function (response) {\n if (response.data.accessToken) {\n localStorage.setItem(\"user\", JSON.stringify(response.data));\n }\n\n return response.data;\n });\n }\n }, {\n key: \"logout\",\n value: function logout() {\n localStorage.removeItem(\"user\");\n }\n }, {\n key: \"register\",\n value: function register(username, email, password) {\n return axios__WEBPACK_IMPORTED_MODULE_0___default.a.post(API_URL + \"signup\", {\n username: username,\n //email,\n password: password\n });\n }\n }, {\n key: \"getCurrentUser\",\n value: function getCurrentUser() {\n return JSON.parse(localStorage.getItem('user'));\n }\n }]);\n\n return AuthService;\n}();\n\n/* harmony default export */ __webpack_exports__[\"default\"] = (new AuthService());\n\n//# sourceURL=webpack:///./src/services/auth-service.js?");
<add>eval("__webpack_require__.r(__webpack_exports__);\n/* harmony import */ var axios__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! axios */ \"./node_modules/axios/index.js\");\n/* harmony import */ var axios__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(axios__WEBPACK_IMPORTED_MODULE_0__);\n/* harmony import */ var _config_config__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../config/config */ \"./src/config/config.js\");\nfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(\"Cannot call a class as a function\"); } }\n\nfunction _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if (\"value\" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }\n\nfunction _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }\n\n\n\nvar API_URL = _config_config__WEBPACK_IMPORTED_MODULE_1__[\"default\"].backendHost + \"/api/auth/\";\n\nvar AuthService = /*#__PURE__*/function () {\n function AuthService() {\n _classCallCheck(this, AuthService);\n }\n\n _createClass(AuthService, [{\n key: \"login\",\n value: function login(username, password) {\n return axios__WEBPACK_IMPORTED_MODULE_0___default.a.post(API_URL + \"signin\", {\n username: username,\n password: password\n }).then(function (response) {\n if (response.data.accessToken) {\n localStorage.setItem(\"user\", JSON.stringify(response.data));\n }\n\n return response.data;\n });\n }\n }, {\n key: \"logout\",\n value: function logout() {\n localStorage.removeItem(\"user\");\n }\n }, {\n key: \"register\",\n value: function register(username, email, password) {\n return axios__WEBPACK_IMPORTED_MODULE_0___default.a.post(API_URL + \"signup\", {\n username: username,\n email: email,\n password: password\n });\n }\n }, {\n key: \"getCurrentUser\",\n value: function getCurrentUser() {\n return JSON.parse(localStorage.getItem('user'));\n }\n }]);\n\n return AuthService;\n}();\n\n/* harmony default export */ __webpack_exports__[\"default\"] = (new AuthService());\n\n//# sourceURL=webpack:///./src/services/auth-service.js?");
<ide>
<ide> /***/ }),
<ide>
<ide> /***/ (function(module, __webpack_exports__, __webpack_require__) {
<ide>
<ide> "use strict";
<del>eval("__webpack_require__.r(__webpack_exports__);\n/* harmony import */ var axios__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! axios */ \"./node_modules/axios/index.js\");\n/* harmony import */ var axios__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(axios__WEBPACK_IMPORTED_MODULE_0__);\n/* harmony import */ var _auth_header__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./auth-header */ \"./src/services/auth-header.js\");\nfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(\"Cannot call a class as a function\"); } }\n\nfunction _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if (\"value\" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }\n\nfunction _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }\n\n\n\nvar API_URL = 'https://springboot-apis.herokuapp.com/users/';\n\nvar UserService = /*#__PURE__*/function () {\n function UserService() {\n _classCallCheck(this, UserService);\n }\n\n _createClass(UserService, [{\n key: \"getPublicContent\",\n value: function getPublicContent() {\n return axios__WEBPACK_IMPORTED_MODULE_0___default.a.get(API_URL + 'all');\n }\n }, {\n key: \"getUserBoard\",\n value: function getUserBoard() {\n return axios__WEBPACK_IMPORTED_MODULE_0___default.a.get(API_URL + 'user', {\n headers: Object(_auth_header__WEBPACK_IMPORTED_MODULE_1__[\"default\"])()\n });\n }\n }, {\n key: \"getUserDetails\",\n value: function getUserDetails(userId) {\n return axios__WEBPACK_IMPORTED_MODULE_0___default.a.get(API_URL + userId, {\n headers: Object(_auth_header__WEBPACK_IMPORTED_MODULE_1__[\"default\"])()\n });\n }\n }, {\n key: \"getModeratorBoard\",\n value: function getModeratorBoard() {\n return axios__WEBPACK_IMPORTED_MODULE_0___default.a.get(API_URL + 'mod', {\n headers: Object(_auth_header__WEBPACK_IMPORTED_MODULE_1__[\"default\"])()\n });\n }\n }, {\n key: \"getAdminBoard\",\n value: function getAdminBoard() {\n return axios__WEBPACK_IMPORTED_MODULE_0___default.a.get(API_URL + 'admin', {\n headers: Object(_auth_header__WEBPACK_IMPORTED_MODULE_1__[\"default\"])()\n });\n }\n }]);\n\n return UserService;\n}();\n\n/* harmony default export */ __webpack_exports__[\"default\"] = (new UserService());\n\n//# sourceURL=webpack:///./src/services/user-service.js?");
<add>eval("__webpack_require__.r(__webpack_exports__);\n/* harmony import */ var axios__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! axios */ \"./node_modules/axios/index.js\");\n/* harmony import */ var axios__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(axios__WEBPACK_IMPORTED_MODULE_0__);\n/* harmony import */ var _auth_header__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./auth-header */ \"./src/services/auth-header.js\");\n/* harmony import */ var _config_config__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../config/config */ \"./src/config/config.js\");\nfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(\"Cannot call a class as a function\"); } }\n\nfunction _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if (\"value\" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }\n\nfunction _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }\n\n\n\n\nvar API_URL = _config_config__WEBPACK_IMPORTED_MODULE_2__[\"default\"].backendHost + '/users/';\n\nvar UserService = /*#__PURE__*/function () {\n function UserService() {\n _classCallCheck(this, UserService);\n }\n\n _createClass(UserService, [{\n key: \"getPublicContent\",\n value: function getPublicContent() {\n return axios__WEBPACK_IMPORTED_MODULE_0___default.a.get(API_URL + 'all');\n }\n }, {\n key: \"getUserBoard\",\n value: function getUserBoard() {\n return axios__WEBPACK_IMPORTED_MODULE_0___default.a.get(API_URL + 'user', {\n headers: Object(_auth_header__WEBPACK_IMPORTED_MODULE_1__[\"default\"])()\n });\n }\n }, {\n key: \"getUserDetails\",\n value: function getUserDetails(userId) {\n return axios__WEBPACK_IMPORTED_MODULE_0___default.a.get(API_URL + userId, {\n headers: Object(_auth_header__WEBPACK_IMPORTED_MODULE_1__[\"default\"])()\n });\n }\n }, {\n key: \"getModeratorBoard\",\n value: function getModeratorBoard() {\n return axios__WEBPACK_IMPORTED_MODULE_0___default.a.get(API_URL + 'mod', {\n headers: Object(_auth_header__WEBPACK_IMPORTED_MODULE_1__[\"default\"])()\n });\n }\n }, {\n key: \"getAdminBoard\",\n value: function getAdminBoard() {\n return axios__WEBPACK_IMPORTED_MODULE_0___default.a.get(API_URL + 'admin', {\n headers: Object(_auth_header__WEBPACK_IMPORTED_MODULE_1__[\"default\"])()\n });\n }\n }, {\n key: \"updateStatus\",\n value: function updateStatus(videoName, userId, duration) {\n return axios__WEBPACK_IMPORTED_MODULE_0___default.a.patch(API_URL + \"video_status\", {\n videoName: videoName,\n userId: userId,\n duration: duration\n }, {\n headers: Object(_auth_header__WEBPACK_IMPORTED_MODULE_1__[\"default\"])()\n });\n }\n }]);\n\n return UserService;\n}();\n\n/* harmony default export */ __webpack_exports__[\"default\"] = (new UserService());\n\n//# sourceURL=webpack:///./src/services/user-service.js?");
<ide>
<ide> /***/ })
<ide> |
|
JavaScript | mit | 4e617a576c29577d44702360fda82d01a96da822 | 0 | larsthorup/pluto | /*global define*/
define([
'jquery',
'backbone',
'lodash'
], function ($, Backbone,_) {
'use strict';
var CardView = Backbone.View.extend({
initialize: function() {
var $el = $('#card', this.options.document);
this.setElement($el[0]);
},
render: function() {
// ToDo: how to cache the template?
var template = _.template($('#card-template', this.options.document).html());
// ToDo: why toJSON??
this.$el.html(template(this.model.toJSON()));
return this;
}
});
return CardView;
});
| src/app/views/card.js | /*global define*/
define([
'backbone',
'lodash'
], function (Backbone,_) {
'use strict';
var CardView = Backbone.View.extend({
initialize: function() {
var $el = $('#card', this.options.document);
this.setElement($el[0]);
},
render: function() {
// ToDo: how to cache the template?
var template = _.template($('#card-template', this.options.document).html());
// ToDo: why toJSON??
this.$el.html(template(this.model.toJSON()));
return this;
}
});
return CardView;
});
| fix dependency bug
| src/app/views/card.js | fix dependency bug | <ide><path>rc/app/views/card.js
<ide> /*global define*/
<ide> define([
<add> 'jquery',
<ide> 'backbone',
<ide> 'lodash'
<del>], function (Backbone,_) {
<add>], function ($, Backbone,_) {
<ide> 'use strict';
<ide> var CardView = Backbone.View.extend({
<ide> initialize: function() { |
|
Java | apache-2.0 | b24bd39cf3f0481130b86032ecb8427270cb77e1 | 0 | flipkart-incubator/flux,flipkart-incubator/flux,flipkart-incubator/flux,flipkart-incubator/flux | /*
* Copyright 2012-2016, the original author or authors.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.flipkart.flux.impl.task;
import com.flipkart.flux.api.EventData;
import com.flipkart.flux.api.core.FluxError;
import com.flipkart.flux.client.registry.Executable;
import com.flipkart.flux.registry.TaskExecutableImpl;
import javafx.util.Pair;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.lang.reflect.Method;
/**
* A task that can be executed locally within the same JVM
* @author yogesh.nachnani
* @author shyam.akirala
*/
public class LocalJvmTask extends AbstractTask {
private final Executable toInvoke;
private static final Logger logger = LoggerFactory.getLogger(LocalJvmTask.class);
public LocalJvmTask(Executable toInvoke) {
this.toInvoke = toInvoke;
}
@Override
public String getName() {
return this.toInvoke.getName();
}
@Override
public String getTaskGroupName() {
/* TODO - pull from deployment unit */
return "flux";
}
@Override
public int getExecutionConcurrency() {
/* TODO - pull from deployment unit/ client definition */
return 10;
}
@Override
public int getExecutionTimeout() {
return (int)toInvoke.getTimeout(); // TODO - fix this. Let all timeouts be in int
}
@Override
public Pair<Object, FluxError> execute(EventData[] events) {
Object[] parameters = new Object[events.length];
Class<?>[] parameterTypes = toInvoke.getParameterTypes();
try {
ClassLoader classLoader = ((TaskExecutableImpl)toInvoke).getDeploymentUnitClassLoader();
Object objectMapperInstance = ((TaskExecutableImpl)toInvoke).getObjectMapperInstance();
Class objectMapper = objectMapperInstance.getClass();
for (int i = 0 ; i < parameterTypes.length; i++) {
if(Class.forName(events[i].getType(), true, classLoader).equals(parameterTypes[i])) {
parameters[i] = objectMapper.getMethod("readValue", String.class, Class.class).invoke(objectMapperInstance, events[i].getData(), Class.forName(events[i].getType(), true, classLoader));
} else {
logger.warn("Parameter type {} did not match with event: {}",parameterTypes[i], events[i]);
throw new RuntimeException("Parameter type "+ parameterTypes[i] + " did not match with event: " + events[i]);
}
}
Method writeValueAsString = objectMapper.getMethod("writeValueAsString", Object.class);
SerializedEvent serializedEvent = null;
try {
//set current thread contextClassLoader to Deployment Unit classloader
Thread.currentThread().setContextClassLoader(((TaskExecutableImpl) toInvoke).getDeploymentUnitClassLoader());
final Object returnObject = toInvoke.execute(parameters);
if (returnObject != null) {
serializedEvent = new SerializedEvent(returnObject.getClass().getCanonicalName(), (String) writeValueAsString.invoke(objectMapperInstance, returnObject));
}
} finally {
//reset the current thread contextClassLoader to Flux app class loader
Thread.currentThread().setContextClassLoader(this.getClass().getClassLoader());
}
return new Pair<>(serializedEvent, null);
} catch (Exception e) {
logger.error("Bad things happened while trying to execute {}",toInvoke,e);
return new Pair<>(null,new FluxError(FluxError.ErrorType.runtime,e.getMessage(),e));
}
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
LocalJvmTask that = (LocalJvmTask) o;
return toInvoke.equals(that.toInvoke);
}
@Override
public int hashCode() {
return toInvoke.hashCode();
}
}
| task/src/main/java/com/flipkart/flux/impl/task/LocalJvmTask.java | /*
* Copyright 2012-2016, the original author or authors.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.flipkart.flux.impl.task;
import com.flipkart.flux.api.EventData;
import com.flipkart.flux.api.core.FluxError;
import com.flipkart.flux.client.registry.Executable;
import com.flipkart.flux.registry.TaskExecutableImpl;
import javafx.util.Pair;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.lang.reflect.Method;
/**
* A task that can be executed locally within the same JVM
* @author yogesh.nachnani
* @author shyam.akirala
*/
public class LocalJvmTask extends AbstractTask {
private final Executable toInvoke;
private static final Logger logger = LoggerFactory.getLogger(LocalJvmTask.class);
public LocalJvmTask(Executable toInvoke) {
this.toInvoke = toInvoke;
}
@Override
public String getName() {
return this.toInvoke.getName();
}
@Override
public String getTaskGroupName() {
/* TODO - pull from deployment unit */
return "flux";
}
@Override
public int getExecutionConcurrency() {
/* TODO - pull from deployment unit/ client definition */
return 10;
}
@Override
public int getExecutionTimeout() {
return (int)toInvoke.getTimeout(); // TODO - fix this. Let all timeouts be in int
}
@Override
public Pair<Object, FluxError> execute(EventData[] events) {
Object[] parameters = new Object[events.length];
Class<?>[] parameterTypes = toInvoke.getParameterTypes();
try {
ClassLoader classLoader = ((TaskExecutableImpl)toInvoke).getDeploymentUnitClassLoader();
Object objectMapperInstance = ((TaskExecutableImpl)toInvoke).getObjectMapperInstance();
Class objectMapper = objectMapperInstance.getClass();
for (int i = 0 ; i < parameterTypes.length; i++) {
if(Class.forName(events[i].getType(), true, classLoader).equals(parameterTypes[i])) {
parameters[i] = objectMapper.getMethod("readValue", String.class, Class.class).invoke(objectMapperInstance, events[i].getData(), Class.forName(events[i].getType(), true, classLoader));
} else {
logger.warn("Parameter type {} did not match with event type {}",parameterTypes[i], events[i]);
throw new RuntimeException("Could not find a parameter of type " + parameterTypes[i]);
}
}
Method writeValueAsString = objectMapper.getMethod("writeValueAsString", Object.class);
SerializedEvent serializedEvent = null;
try {
//set current thread contextClassLoader to Deployment Unit classloader
Thread.currentThread().setContextClassLoader(((TaskExecutableImpl) toInvoke).getDeploymentUnitClassLoader());
final Object returnObject = toInvoke.execute(parameters);
if (returnObject != null) {
serializedEvent = new SerializedEvent(returnObject.getClass().getCanonicalName(), (String) writeValueAsString.invoke(objectMapperInstance, returnObject));
}
} finally {
//reset the current thread contextClassLoader to Flux app class loader
Thread.currentThread().setContextClassLoader(this.getClass().getClassLoader());
}
return new Pair<>(serializedEvent, null);
} catch (Exception e) {
logger.error("Bad things happened while trying to execute {}",toInvoke,e);
return new Pair<>(null,new FluxError(FluxError.ErrorType.runtime,e.getMessage(),e));
}
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
LocalJvmTask that = (LocalJvmTask) o;
return toInvoke.equals(that.toInvoke);
}
@Override
public int hashCode() {
return toInvoke.hashCode();
}
}
| Changed error message
| task/src/main/java/com/flipkart/flux/impl/task/LocalJvmTask.java | Changed error message | <ide><path>ask/src/main/java/com/flipkart/flux/impl/task/LocalJvmTask.java
<ide> if(Class.forName(events[i].getType(), true, classLoader).equals(parameterTypes[i])) {
<ide> parameters[i] = objectMapper.getMethod("readValue", String.class, Class.class).invoke(objectMapperInstance, events[i].getData(), Class.forName(events[i].getType(), true, classLoader));
<ide> } else {
<del> logger.warn("Parameter type {} did not match with event type {}",parameterTypes[i], events[i]);
<del> throw new RuntimeException("Could not find a parameter of type " + parameterTypes[i]);
<add> logger.warn("Parameter type {} did not match with event: {}",parameterTypes[i], events[i]);
<add> throw new RuntimeException("Parameter type "+ parameterTypes[i] + " did not match with event: " + events[i]);
<ide> }
<ide> }
<ide> |
|
Java | apache-2.0 | c995f8f9c27a2a47cb1ca00cae8855324b4cb010 | 0 | nectec-wisru/marlo | /*
* Copyright (c) 2017 NECTEC
* National Electronics and Computer Technology Center, Thailand
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package th.or.nectec.marlo.model;
import android.os.Parcel;
import android.os.Parcelable;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import com.google.android.gms.maps.model.PolygonOptions;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
public class Polygon implements Parcelable {
public static final Parcelable.Creator<Polygon> CREATOR = new Parcelable.Creator<Polygon>() {
@Override
public Polygon createFromParcel(Parcel source) {
return new Polygon(source);
}
@Override
public Polygon[] newArray(int size) {
return new Polygon[size];
}
};
private final List<Coordinate> boundary;
private final List<Polygon> holes;
public Polygon() {
boundary = new ArrayList<>();
holes = new ArrayList<>();
}
public Polygon(Polygon polygon) {
boundary = new ArrayList<>(Coordinate.clones(polygon.getBoundary()));
holes = new ArrayList<>();
for (Polygon hole : polygon.getAllHoles()) {
holes.add(new Polygon(hole));
}
}
public Polygon(List<Coordinate> boundary) {
this(boundary, new ArrayList<Polygon>());
}
public Polygon(List<Coordinate> boundary, List<Polygon> holes) {
this.boundary = boundary;
this.holes = holes;
}
private Polygon(Parcel in) {
this.boundary = in.createTypedArrayList(Coordinate.CREATOR);
int holesCount = in.readInt();
this.holes = new ArrayList<>();
for (int hole = 0; hole < holesCount; hole++) {
this.holes.add((Polygon) in.readValue(Polygon.class.getClassLoader()));
}
}
/**
* @param geojson String of GeoJson as Polygon Geometry object or coordinate
* @return Object create from GeoJson
*/
public static Polygon fromGeoJson(@NonNull String geojson) {
try {
JSONTokener tokener = new JSONTokener(geojson);
Object json = tokener.nextValue();
if (json instanceof JSONObject) {
return fromGeoJson((JSONObject) json);
} else if (json instanceof JSONArray) {
return fromGeoJson((JSONArray) json);
} else {
throw new RuntimeException("Not support json");
}
} catch (JSONException e) {
throw new RuntimeException(e);
}
}
/**
* @param polygon JsonObject as Geometry format of GeoJson spec.
* @return Object create from GeoJson
*/
public static Polygon fromGeoJson(@NonNull JSONObject polygon) {
try {
return fromGeoJson(polygon.getJSONArray("coordinates"));
} catch (JSONException error) {
throw new RuntimeException(error);
}
}
/**
* @param coordinates JsonArray of coordinates field in GeoJson's polygon geometry
* @return object from GeoJson
*/
public static Polygon fromGeoJson(@NonNull JSONArray coordinates) {
try {
Polygon returnObj = new Polygon();
for (int boundaryIndex = 0; boundaryIndex < coordinates.length(); boundaryIndex++) {
Polygon polygon = boundaryIndex == 0 ? returnObj : new Polygon();
JSONArray boundary = coordinates.getJSONArray(boundaryIndex);
for (int coordIndex = 0; coordIndex < boundary.length(); coordIndex++) {
polygon.add(Coordinate.fromGeoJson(boundary.get(coordIndex).toString()));
}
if (boundaryIndex != 0) returnObj.addHoles(polygon);
}
return returnObj;
} catch (JSONException error) {
throw new RuntimeException(error);
}
}
/**
* @param geojson String of GeoJson as MultiPolygon Geometry object or coordinates
* @return object from GeoJson
*/
public static List<Polygon> fromGeoJsonMultiPolygon(@NonNull String geojson) {
try {
JSONTokener tokener = new JSONTokener(geojson);
Object json = tokener.nextValue();
if (json instanceof JSONObject) {
return fromGeoJsonMultiPolygon((JSONObject) json);
} else if (json instanceof JSONArray) {
return fromGeoJsonMultiPolygon((JSONArray) json);
} else {
throw new RuntimeException("Input not support type");
}
} catch (JSONException error) {
throw new RuntimeException(error);
}
}
/**
* @param geometry String of GeoJson as MultiPolygon Geometry object or coordinates
* @return object from GeoJson
*/
public static List<Polygon> fromGeoJsonMultiPolygon(@NonNull JSONObject geometry) {
try {
return fromGeoJsonMultiPolygon(geometry.getJSONArray("coordinates"));
} catch (JSONException error) {
throw new RuntimeException("Not found coordinates filed", error);
}
}
/**
* @param coordinates GeoJson array of MultiPolygon
* @return object from coordinates
*/
public static List<Polygon> fromGeoJsonMultiPolygon(@NonNull JSONArray coordinates) {
try {
List<Polygon> polygons = new ArrayList<>();
for (int polygonIndex = 0; polygonIndex < coordinates.length(); polygonIndex++) {
polygons.add(Polygon.fromGeoJson(coordinates.getJSONArray(polygonIndex)));
}
return polygons;
} catch (JSONException error) {
throw new RuntimeException(error);
}
}
@NonNull
public static JSONObject toGeoJson(List<Polygon> multiPolygon) {
try {
JSONObject geoJson = new JSONObject();
geoJson.put("type", "MultiPolygon");
JSONArray coordinate = new JSONArray();
for (Polygon polygon : multiPolygon) {
coordinate.put(polygon.toGeoJsonCoordinates());
}
geoJson.put("coordinates", coordinate);
return geoJson;
} catch (JSONException error) {
throw new RuntimeException(error);
}
}
/**
* @param coord
* @return
*/
public boolean isCoordinateExist(Coordinate coord) {
for (Coordinate point : boundary) {
if (point.equals(coord))
return true;
for (Polygon hole : holes) {
if (hole.isCoordinateExist(coord))
return true;
}
}
return false;
}
public List<Coordinate> getBoundary() {
return boundary;
}
public List<Polygon> getAllHoles() {
return new ArrayList<>(holes);
}
/**
* @return JsonObject in GeoJson's geometry format
*/
public JSONObject toGeoJson() {
try {
JSONObject geoJson = new JSONObject();
geoJson.put("type", "Polygon");
JSONArray coordinate = toGeoJsonCoordinates();
geoJson.put("coordinates", coordinate);
return geoJson;
} catch (JSONException error) {
throw new RuntimeException(error);
}
}
public PolygonOptions toPolygonOptions() {
return toPolygonOptions(new PolygonOptions());
}
public PolygonOptions toPolygonOptions(PolygonOptions options) {
options.addAll(Coordinate.toLatLngs(boundary));
for (Polygon hold : holes) {
options.addHole(Coordinate.toLatLngs(hold.boundary));
}
return options;
}
@NonNull
private JSONArray toGeoJsonCoordinates() {
JSONArray coordinate = new JSONArray();
coordinate.put(boundaryToJson());
for (Polygon hole : holes) {
if (hole.isEmpty() || !hole.isValid())
continue;
coordinate.put(hole.boundaryToJson());
}
return coordinate;
}
@NonNull
private JSONArray boundaryToJson() {
JSONArray jsonBoundary = new JSONArray();
for (Coordinate point : boundary) {
jsonBoundary.put(point.toGeoJson());
}
if (!boundary.get(0).equals(boundary.get(boundary.size() - 1)))
jsonBoundary.put(boundary.get(0).toGeoJson());
return jsonBoundary;
}
public void add(Coordinate coordinate) {
if (boundary.size() > 0 && boundary.get(0).equals(coordinate))
return; //ignore close position
boundary.add(coordinate);
}
public void add(double lat, double lng) {
add(new Coordinate(lat, lng));
}
public void addHoles(Polygon coordinates) {
holes.add(coordinates);
}
public Polygon getHole(int holeIndex) {
return holes.get(holeIndex);
}
public boolean isValid() {
return boundary.size() >= 3;
}
public boolean isEmpty() {
return boundary.size() == 0;
}
public int getHolesCount() {
return holes.size();
}
public Polygon getLastHole() {
return holes.get(holes.size() - 1);
}
public boolean haveHole() {
return getHolesCount() > 0;
}
@Nullable
public Coordinate getLastCoordinate() {
if (haveHole()) {
Coordinate coord;
if ((coord = getLastHole().getLastCoordinate()) != null)
return coord;
}
if (!isEmpty()) {
Coordinate peek = boundary.get(boundary.size() - 1);
return new Coordinate(peek.getLatitude(), peek.getLongitude());
} else {
return null;
}
}
public Coordinate pop() {
if (!boundary.isEmpty()) {
return boundary.remove(boundary.size() - 1);
}
return null;
}
public void removeHole(Polygon hole) {
holes.remove(hole);
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Polygon polygon = (Polygon) o;
return Objects.equals(boundary, polygon.boundary)
&& Objects.equals(holes, polygon.holes);
}
@Override
public int hashCode() {
return Objects.hash(boundary, holes);
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeTypedList(this.boundary);
dest.writeInt(this.holes.size());
for (Polygon hole : this.holes) {
dest.writeValue(hole);
}
}
public boolean replace(Coordinate oldCoord, Coordinate newCoord) {
int coordPosition = boundary.indexOf(oldCoord);
if (coordPosition > -1) {
boundary.set(coordPosition, newCoord);
return true;
}
for (Polygon hole : holes) {
if (hole.replace(oldCoord, newCoord))
return true;
}
return false;
}
}
| marlo/src/main/java/th/or/nectec/marlo/model/Polygon.java | /*
* Copyright (c) 2017 NECTEC
* National Electronics and Computer Technology Center, Thailand
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package th.or.nectec.marlo.model;
import android.os.Parcel;
import android.os.Parcelable;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import com.google.android.gms.maps.model.PolygonOptions;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
public class Polygon implements Parcelable {
public static final Parcelable.Creator<Polygon> CREATOR = new Parcelable.Creator<Polygon>() {
@Override
public Polygon createFromParcel(Parcel source) {
return new Polygon(source);
}
@Override
public Polygon[] newArray(int size) {
return new Polygon[size];
}
};
private final List<Coordinate> boundary;
private final List<Polygon> holes;
public Polygon() {
boundary = new ArrayList<>();
holes = new ArrayList<>();
}
public Polygon(Polygon polygon) {
boundary = new ArrayList<>(Coordinate.clones(polygon.getBoundary()));
holes = new ArrayList<>();
for (Polygon hole : polygon.getAllHoles()) {
holes.add(new Polygon(hole));
}
}
public Polygon(List<Coordinate> boundary) {
this(boundary, new ArrayList<Polygon>());
}
public Polygon(List<Coordinate> boundary, List<Polygon> holes) {
this.boundary = boundary;
this.holes = holes;
}
private Polygon(Parcel in) {
this.boundary = in.createTypedArrayList(Coordinate.CREATOR);
int holesCount = in.readInt();
this.holes = new ArrayList<>();
for (int hole = 0; hole < holesCount; hole++) {
this.holes.add((Polygon) in.readValue(Polygon.class.getClassLoader()));
}
}
/**
* @param geojson String of GeoJson as Polygon Geometry object or coordinate
* @return Object create from GeoJson
*/
public static Polygon fromGeoJson(@NonNull String geojson) {
try {
JSONTokener tokener = new JSONTokener(geojson);
Object json = tokener.nextValue();
if (json instanceof JSONObject) {
return fromGeoJson((JSONObject) json);
} else if (json instanceof JSONArray) {
return fromGeoJson((JSONArray) json);
} else {
throw new RuntimeException("Not support json");
}
} catch (JSONException e) {
throw new RuntimeException(e);
}
}
/**
* @param polygon JsonObject as Geometry format of GeoJson spec.
* @return Object create from GeoJson
*/
public static Polygon fromGeoJson(@NonNull JSONObject polygon) {
try {
return fromGeoJson(polygon.getJSONArray("coordinates"));
} catch (JSONException error) {
throw new RuntimeException(error);
}
}
/**
* @param coordinates JsonArray of coordinates field in GeoJson's polygon geometry
* @return object from GeoJson
*/
public static Polygon fromGeoJson(@NonNull JSONArray coordinates) {
try {
Polygon returnObj = new Polygon();
for (int boundaryIndex = 0; boundaryIndex < coordinates.length(); boundaryIndex++) {
Polygon polygon = boundaryIndex == 0 ? returnObj : new Polygon();
JSONArray boundary = coordinates.getJSONArray(boundaryIndex);
for (int coordIndex = 0; coordIndex < boundary.length(); coordIndex++) {
polygon.add(Coordinate.fromGeoJson(boundary.get(coordIndex).toString()));
}
if (boundaryIndex != 0) returnObj.addHoles(polygon);
}
return returnObj;
} catch (JSONException error) {
throw new RuntimeException(error);
}
}
/**
* @param geojson String of GeoJson as MultiPolygon Geometry object or coordinates
* @return object from GeoJson
*/
public static List<Polygon> fromGeoJsonMultiPolygon(@NonNull String geojson) {
try {
JSONTokener tokener = new JSONTokener(geojson);
Object json = tokener.nextValue();
if (json instanceof JSONObject) {
return fromGeoJsonMultiPolygon((JSONObject) json);
} else if (json instanceof JSONArray) {
return fromGeoJsonMultiPolygon((JSONArray) json);
} else {
throw new RuntimeException("Input not support type");
}
} catch (JSONException error) {
throw new RuntimeException(error);
}
}
/**
* @param geometry String of GeoJson as MultiPolygon Geometry object or coordinates
* @return object from GeoJson
*/
public static List<Polygon> fromGeoJsonMultiPolygon(@NonNull JSONObject geometry) {
try {
return fromGeoJsonMultiPolygon(geometry.getJSONArray("coordinates"));
} catch (JSONException error) {
throw new RuntimeException("Not found coordinates filed", error);
}
}
/**
* @param coordinates GeoJson array of MultiPolygon
* @return object from coordinates
*/
public static List<Polygon> fromGeoJsonMultiPolygon(@NonNull JSONArray coordinates) {
try {
List<Polygon> polygons = new ArrayList<>();
for (int polygonIndex = 0; polygonIndex < coordinates.length(); polygonIndex++) {
polygons.add(Polygon.fromGeoJson(coordinates.getJSONArray(polygonIndex)));
}
return polygons;
} catch (JSONException error) {
throw new RuntimeException(error);
}
}
@NonNull
public static JSONObject toGeoJson(List<Polygon> multiPolygon) {
try {
JSONObject geoJson = new JSONObject();
geoJson.put("type", "MultiPolygon");
JSONArray coordinate = new JSONArray();
for (Polygon polygon : multiPolygon) {
coordinate.put(polygon.toGeoJsonCoordinates());
}
geoJson.put("coordinates", coordinate);
return geoJson;
} catch (JSONException error) {
throw new RuntimeException(error);
}
}
/**
* @param coord
* @return
*/
public boolean isCoordinateExist(Coordinate coord) {
for (Coordinate point : boundary) {
if (point.equals(coord))
return true;
for (Polygon hole : holes) {
if (hole.isCoordinateExist(coord))
return true;
}
}
return false;
}
public List<Coordinate> getBoundary() {
return boundary;
}
public List<Polygon> getAllHoles() {
return new ArrayList<>(holes);
}
/**
* @return JsonObject in GeoJson's geometry format
*/
public JSONObject toGeoJson() {
try {
JSONObject geoJson = new JSONObject();
geoJson.put("type", "Polygon");
JSONArray coordinate = toGeoJsonCoordinates();
geoJson.put("coordinates", coordinate);
return geoJson;
} catch (JSONException error) {
throw new RuntimeException(error);
}
}
public PolygonOptions toPolygonOptions() {
return toPolygonOptions(new PolygonOptions());
}
public PolygonOptions toPolygonOptions(PolygonOptions options) {
options.addAll(Coordinate.toLatLngs(boundary));
for (Polygon hold : holes) {
options.addHole(Coordinate.toLatLngs(hold.boundary));
}
return options;
}
@NonNull
private JSONArray toGeoJsonCoordinates() {
JSONArray coordinate = new JSONArray();
coordinate.put(boundaryToJson());
for (Polygon hole : holes) {
coordinate.put(hole.boundaryToJson());
}
return coordinate;
}
@NonNull
private JSONArray boundaryToJson() {
JSONArray jsonBoundary = new JSONArray();
for (Coordinate point : boundary) {
jsonBoundary.put(point.toGeoJson());
}
if (!boundary.get(0).equals(boundary.get(boundary.size() - 1)))
jsonBoundary.put(boundary.get(0).toGeoJson());
return jsonBoundary;
}
public void add(Coordinate coordinate) {
if (boundary.size() > 0 && boundary.get(0).equals(coordinate))
return; //ignore close position
boundary.add(coordinate);
}
public void add(double lat, double lng) {
add(new Coordinate(lat, lng));
}
public void addHoles(Polygon coordinates) {
holes.add(coordinates);
}
public Polygon getHole(int holeIndex) {
return holes.get(holeIndex);
}
public boolean isValid() {
return boundary.size() >= 3;
}
public boolean isEmpty() {
return boundary.size() == 0;
}
public int getHolesCount() {
return holes.size();
}
public Polygon getLastHole() {
return holes.get(holes.size() - 1);
}
public boolean haveHole() {
return getHolesCount() > 0;
}
@Nullable
public Coordinate getLastCoordinate() {
if (haveHole()) {
Coordinate coord;
if ((coord = getLastHole().getLastCoordinate()) != null)
return coord;
}
if (!isEmpty()) {
Coordinate peek = boundary.get(boundary.size() - 1);
return new Coordinate(peek.getLatitude(), peek.getLongitude());
} else {
return null;
}
}
public Coordinate pop() {
if (!boundary.isEmpty()) {
return boundary.remove(boundary.size() - 1);
}
return null;
}
public void removeHole(Polygon hole) {
holes.remove(hole);
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Polygon polygon = (Polygon) o;
return Objects.equals(boundary, polygon.boundary)
&& Objects.equals(holes, polygon.holes);
}
@Override
public int hashCode() {
return Objects.hash(boundary, holes);
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeTypedList(this.boundary);
dest.writeInt(this.holes.size());
for (Polygon hole : this.holes) {
dest.writeValue(hole);
}
}
public boolean replace(Coordinate oldCoord, Coordinate newCoord) {
int coordPosition = boundary.indexOf(oldCoord);
if (coordPosition > -1) {
boundary.set(coordPosition, newCoord);
return true;
}
for (Polygon hole : holes) {
if (hole.replace(oldCoord, newCoord))
return true;
}
return false;
}
}
| not parse empty hole or invalid hole to geojson this prevent exception on runtime but can be cause of data error if not carefully check polygon
| marlo/src/main/java/th/or/nectec/marlo/model/Polygon.java | not parse empty hole or invalid hole to geojson this prevent exception on runtime but can be cause of data error if not carefully check polygon | <ide><path>arlo/src/main/java/th/or/nectec/marlo/model/Polygon.java
<ide> JSONArray coordinate = new JSONArray();
<ide> coordinate.put(boundaryToJson());
<ide> for (Polygon hole : holes) {
<add> if (hole.isEmpty() || !hole.isValid())
<add> continue;
<ide> coordinate.put(hole.boundaryToJson());
<ide> }
<ide> return coordinate; |
|
JavaScript | apache-2.0 | c3b9fc241fc31c1227380efe71e0a20b517793c2 | 0 | cafjs/caf_iot | /*!
Copyright 2013 Hewlett-Packard Development Company, L.P.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
"use strict";
/**
* A container component that assembles and manages one IoT device.
*
* The state of a IoT device and its plugins is managed transactionally using a
* 2PC (Two-Phase Commit) protocol. See caf_components/gen_transactional for
* details.
*
* @name caf_iot/iot_main
* @namespace
* @augments caf_components/gen_transactional
*/
var assert = require('assert');
var caf_comp = require('caf_components');
var myUtils = caf_comp.myUtils;
var genTransactional = caf_comp.gen_transactional;
var async = caf_comp.async;
var PULSE_CRON_NAME = 'pulseCron';
/**
* Factory method to create an IoT device.
*
*
* @see caf_components/supervisor
*/
exports.newInstance = function($, spec, cb) {
try {
var that = genTransactional.constructor($, spec);
assert.equal(typeof spec.env.myId, 'string',
"'spec.env.myId' not a string");
// become the root component of the children context
that.$._ = that;
that.$.loader = $._.$.loader;
console.log('New IoT main');
/**
* Run-time type information.
*
* @type {boolean}
* @name iot_main#__ca_isIoTMain__
*/
that.__ca_isIoTMain__ = true;
/**
* Returns this application name, e.g., 'root-helloworld'
*
* @return {string} A name for this app.
*
* @name iot_main#__ca_getAppName__
* @function
*/
that.__ca_getAppName__ = function() {
return $._.__ca_getAppName__();
};
/**
* Returns the CA name, e.g., 'foo-device1'.
*
* @return {string} The CA name.
*
* @name iot_main#__ca_getName__
* @function
*/
that.__ca_getName__ = function() {
return spec.env.myId;
};
var super__ca_checkup__ = myUtils.superior(that, '__ca_checkup__');
var queue = async.queue(super__ca_checkup__, 1); // serialize
that.__ca_checkup__ = function(data, cb0) {
queue.push(data, cb0);
};
var super__ca_shutdown__ = myUtils.superior(that, '__ca_shutdown__');
that.__ca_shutdown__ = function(data, cb) {
console.log('IOT: shutdown');
super__ca_shutdown__(data, cb);
};
async.series([
function(cb0) {
// force initialization of lazy components.
that.__ca_checkup__(null, cb0);
},
that.__ca_init__,
function(cb0) {
that.$.queue.process('__ca_pulse__', [], cb0);
}
], function(err) {
if (err) {
cb(err);
} else {
that.$.cron.__iot_addCron__(PULSE_CRON_NAME, '__ca_pulse__', [],
spec.env.interval);
cb(err, that);
}
});
} catch (err) {
cb(err);
}
};
| lib/iot_main.js | /*!
Copyright 2013 Hewlett-Packard Development Company, L.P.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
"use strict";
/**
* A container component that assembles and manages one IoT device.
*
* The state of a IoT device and its plugins is managed transactionally using a
* 2PC (Two-Phase Commit) protocol. See caf_components/gen_transactional for
* details.
*
* @name caf_iot/iot_main
* @namespace
* @augments caf_components/gen_transactional
*/
var assert = require('assert');
var caf_comp = require('caf_components');
var myUtils = caf_comp.myUtils;
var genTransactional = caf_comp.gen_transactional;
var async = caf_comp.async;
var PULSE_CRON_NAME = 'pulseCron';
/**
* Factory method to create an IoT device.
*
*
* @see caf_components/supervisor
*/
exports.newInstance = function($, spec, cb) {
try {
var that = genTransactional.constructor($, spec);
assert.equal(typeof spec.env.myId, 'string',
"'spec.env.myId' not a string");
// become the root component of the children context
that.$._ = that;
that.$.loader = $._.$.loader;
console.log('New IoT main');
/**
* Run-time type information.
*
* @type {boolean}
* @name iot_main#__ca_isIoTMain__
*/
that.__ca_isIoTMain__ = true;
/**
* Returns this application name, e.g., 'root-helloworld'
*
* @return {string} A name for this app.
*
* @name iot_main#__ca_getAppName__
* @function
*/
that.__ca_getAppName__ = function() {
return $._.__ca_getAppName__();
};
/**
* Returns this application fully qualified name, e.g.,
* 'root-helloworld.cafjs.com'
*
* @return {string} A fully qualified name for this app.
*
* @name iot_main#__ca_getAppFullName__
* @function
*/
that.__ca_getName__ = function() {
return spec.env.myId;
};
var super__ca_checkup__ = myUtils.superior(that, '__ca_checkup__');
var queue = async.queue(super__ca_checkup__, 1); // serialize
that.__ca_checkup__ = function(data, cb0) {
queue.push(data, cb0);
};
var super__ca_shutdown__ = myUtils.superior(that, '__ca_shutdown__');
that.__ca_shutdown__ = function(data, cb) {
console.log('IOT: shutdown');
super__ca_shutdown__(data, cb);
};
async.series([
function(cb0) {
// force initialization of lazy components.
that.__ca_checkup__(null, cb0);
},
that.__ca_init__,
function(cb0) {
that.$.queue.process('__ca_pulse__', [], cb0);
}
], function(err) {
if (err) {
cb(err);
} else {
that.$.cron.__iot_addCron__(PULSE_CRON_NAME, '__ca_pulse__', [],
spec.env.interval);
cb(err, that);
}
});
} catch (err) {
cb(err);
}
};
| Fix comment
| lib/iot_main.js | Fix comment | <ide><path>ib/iot_main.js
<ide> };
<ide>
<ide> /**
<del> * Returns this application fully qualified name, e.g.,
<del> * 'root-helloworld.cafjs.com'
<add> * Returns the CA name, e.g., 'foo-device1'.
<ide> *
<del> * @return {string} A fully qualified name for this app.
<add> * @return {string} The CA name.
<ide> *
<del> * @name iot_main#__ca_getAppFullName__
<add> * @name iot_main#__ca_getName__
<ide> * @function
<ide> */
<ide> that.__ca_getName__ = function() { |
|
Java | agpl-3.0 | 8c83842c9350ff2a4931e4abe1f03b50e63f2848 | 0 | WASP-System/central,WASP-System/central,WASP-System/central,WASP-System/central,WASP-System/central,WASP-System/central | package edu.yu.einstein.wasp.controller;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import org.apache.commons.lang.StringUtils;
import org.codehaus.jackson.map.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.support.SessionStatus;
import edu.yu.einstein.wasp.model.AcctGrant;
import edu.yu.einstein.wasp.model.Department;
import edu.yu.einstein.wasp.model.Job;
import edu.yu.einstein.wasp.model.Lab;
import edu.yu.einstein.wasp.model.LabMeta;
import edu.yu.einstein.wasp.model.LabPending;
import edu.yu.einstein.wasp.model.LabPendingMeta;
import edu.yu.einstein.wasp.model.LabUser;
import edu.yu.einstein.wasp.model.MetaBase;
import edu.yu.einstein.wasp.model.MetaHelper;
import edu.yu.einstein.wasp.exception.MetadataException;
import edu.yu.einstein.wasp.model.Project;
import edu.yu.einstein.wasp.model.Role;
import edu.yu.einstein.wasp.model.Sample;
import edu.yu.einstein.wasp.model.SampleLab;
import edu.yu.einstein.wasp.model.User;
import edu.yu.einstein.wasp.model.UserMeta;
import edu.yu.einstein.wasp.model.UserPending;
import edu.yu.einstein.wasp.model.UserPendingMeta;
import edu.yu.einstein.wasp.service.AuthenticationService;
import edu.yu.einstein.wasp.service.DepartmentService;
import edu.yu.einstein.wasp.service.EmailService;
import edu.yu.einstein.wasp.service.LabMetaService;
import edu.yu.einstein.wasp.service.LabPendingMetaService;
import edu.yu.einstein.wasp.service.LabPendingService;
import edu.yu.einstein.wasp.service.LabService;
import edu.yu.einstein.wasp.service.LabUserService;
import edu.yu.einstein.wasp.service.MessageService;
import edu.yu.einstein.wasp.service.PasswordService;
import edu.yu.einstein.wasp.service.RoleService;
import edu.yu.einstein.wasp.service.UserMetaService;
import edu.yu.einstein.wasp.service.UserPendingMetaService;
import edu.yu.einstein.wasp.service.UserPendingService;
import edu.yu.einstein.wasp.taglib.JQFieldTag;
@Controller
@Transactional
@RequestMapping("/lab")
public class LabController extends WaspController {
@Autowired
private LabService labService;
@Autowired
private LabUserService labUserService;
@Autowired
private RoleService roleService;
@Autowired
private LabMetaService labMetaService;
@Autowired
private DepartmentService deptService;
@Autowired
private UserMetaService userMetaService;
@Autowired
private UserPendingService userPendingService;
@Autowired
private UserPendingMetaService userPendingMetaService;
@Autowired
private LabPendingService labPendingService;
@Autowired
private LabPendingMetaService labPendingMetaService;
@Autowired
private EmailService emailService;
@Autowired
private MessageService messageService;
@Autowired
private AuthenticationService authenticationService;
@Autowired
private PasswordService passwordService;
/**
* get a @{link MetaHelper} instance for working with LabMeta metadata
*
* @return
*/
private final MetaHelper getMetaHelper() {
return new MetaHelper("lab", LabMeta.class, request.getSession());
}
/**
* get a @{link MetaHelper} instance for working with labPending metadata
*
* @return
*/
private final MetaHelper getLabPendingMetaHelper() {
return new MetaHelper("labPending", LabPendingMeta.class,request.getSession());
}
/**
* Return list of labs in JGrid
*
* @param m
* @return
*/
@RequestMapping("/list")
@PreAuthorize("hasRole('god')")
public String list(ModelMap m) {
m.addAttribute("_metaList", getMetaHelper().getMasterList(MetaBase.class));
m.addAttribute(JQFieldTag.AREA_ATTR, getMetaHelper().getArea());
prepareSelectListData(m);
return "lab/list";
}
/**
* Returns list of labs
*
* @param response
* @return
*/
@RequestMapping(value = "/listJSON", method = RequestMethod.GET)
public String getListJSON(HttpServletResponse response) {
// result
Map<String, Object> jqgrid = new HashMap<String, Object>();
List<Lab> labList;
if (request.getParameter("_search") == null || StringUtils.isEmpty(request.getParameter("searchString"))) {
labList = this.labService.findAll();
} else {
Map<String, String> m = new HashMap<String, String>();
m.put(request.getParameter("searchField"), request.getParameter("searchString"));
labList = this.labService.findByMap(m);
if ("ne".equals(request.getParameter("searchOper"))) {
List<Lab> allLabs = new ArrayList<Lab>(this.labService.findAll());
for (Iterator<Lab> it = labList.iterator(); it.hasNext();) {
Lab excludeLab = it.next();
allLabs.remove(excludeLab);
}
labList = allLabs;
}
}
ObjectMapper mapper = new ObjectMapper();
try {
// String labs = mapper.writeValueAsString(labList);
int pageId = Integer.parseInt(request.getParameter("page")); // index of page
int pageRowNum = Integer.parseInt(request.getParameter("rows")); // number of rows in one page
int rowNum = labList.size(); // total number of rows
int pageNum = (rowNum + pageRowNum - 1) / pageRowNum; // total number of pages
jqgrid.put("page", pageId + "");
jqgrid.put("records", rowNum + "");
jqgrid.put("total", pageNum + "");
Map<String, String> userData = new HashMap<String, String>();
userData.put("page", "1");
userData.put("selId", StringUtils.isEmpty(request.getParameter("selId")) ? "" : request.getParameter("selId"));
jqgrid.put("userdata", userData);
List<Map> rows = new ArrayList<Map>();
Map<Integer, String> allDepts = new TreeMap<Integer, String>();
for (Department dept : (List<Department>) deptService.findAll()) {
allDepts.put(dept.getDepartmentId(), dept.getName());
}
Map<Integer, String> allUsers = new TreeMap<Integer, String>();
for (User user : (List<User>) userService.findAll()) {
allUsers.put(user.getUserId(), user.getFirstName() + " " + user.getLastName());
}
int frId = pageRowNum * (pageId - 1);
int toId = pageRowNum * pageId;
toId = toId <= rowNum ? toId : rowNum;
List<Lab> labPage = labList.subList(frId, toId);
for (Lab lab : labPage) {
Map cell = new HashMap();
cell.put("id", lab.getLabId());
List<LabMeta> labMeta = getMetaHelper().syncWithMaster(
lab.getLabMeta());
List<String> cellList = new ArrayList<String>(
Arrays.asList(new String[] {
lab.getName(),
"<a href=/wasp/user/list.do?selId="
+ lab.getPrimaryUserId() + ">"
+ allUsers.get(lab.getPrimaryUserId())
+ "</a>",
allDepts.get(lab.getDepartmentId()),
lab.getIsActive() == 1 ? "yes" : "no" }));
for (LabMeta meta : labMeta) {
cellList.add(meta.getV());
}
int l = cellList.size();
cell.put("cell", cellList);
rows.add(cell);
}
jqgrid.put("rows", rows);
return outputJSON(jqgrid, response);
} catch (Throwable e) {
throw new IllegalStateException("Can't marshall to JSON " + labList, e);
}
}
@RequestMapping(value = "/subgridJSON.do", method = RequestMethod.GET)
public String subgridJSON(@RequestParam("id") Integer labId, ModelMap m, HttpServletResponse response) {
Map<String, Object> jqgrid = new HashMap<String, Object>();
Lab labDb = this.labService.getById(labId);
List<LabUser> users = labDb.getLabUser();
List<Project> projects = labDb.getProject();
List<Sample> samples = labDb.getSample();
List<AcctGrant> accGrants = labDb.getAcctGrant();
List<SampleLab> sampleLabs = labDb.getSampleLab();
List<Job> jobs = labDb.getJob();
// get max lenth of the previous 4 lists
int max = Math.max(Math.max(users.size(), projects.size()), Math.max(samples.size(), accGrants.size()));
max = Math.max(max, Math.max(sampleLabs.size(), jobs.size()));
if (max == 0) {
LabUser lUser = new LabUser();
lUser.setUser(new User());
users.add(lUser);
projects.add(new Project());
samples.add(new Sample());
accGrants.add(new AcctGrant());
SampleLab sampleLab = new SampleLab();
sampleLab.setLab(new Lab());
sampleLabs.add(sampleLab);
jobs.add(new Job());
max = 1;
}
String[][] mtrx = new String[max][6];
ObjectMapper mapper = new ObjectMapper();
String text;
try {
// String labs = mapper.writeValueAsString(labList);
jqgrid.put("page", "1");
jqgrid.put("records", max + "");
jqgrid.put("total", max + "");
int i = 0;
int j = 0;
for (LabUser user : users) {
text = user.getUserId() == 0 ? "No Users"
: "<a href=/wasp/user/list.do?selId="
+ user.getUserId() + ">"
+ user.getUser().getFirstName() + " "
+ user.getUser().getLastName() + "</a>";
mtrx[j][i] = text;
j++;
}
i++;
j = 0;
for (Project project : projects) {
text = project.getProjectId() == 0 ? "No Projects" : project.getName();
mtrx[j][i] = text;
j++;
}
i++;
j = 0;
for (Sample sample : samples) {
text = sample.getSampleId() == 0 ? "No Samples" : sample.getName();
mtrx[j][i] = text;
j++;
}
i++;
j = 0;
for (AcctGrant acc : accGrants) {
text = acc.getGrantId() == 0 ? "No Acc Grants" : acc.getName();
mtrx[j][i] = text;
j++;
}
i++;
j = 0;
for (SampleLab sampleLab : sampleLabs) {
text = sampleLab.getLab().getLabId() == 0 ? "No Sample Labs" : sampleLab.getLab().getName();
mtrx[j][i] = text;
j++;
}
i++;
j = 0;
for (Job job : jobs) {
text = job.getJobId() == 0 ? "No Jobs" : job.getName();
mtrx[j][i] = text;
j++;
}
List<Map> rows = new ArrayList<Map>();
for (j = 0; j < max; j++) {
Map cell = new HashMap();
rows.add(cell);
cell.put("id", j + "");
List<String> cellList = Arrays.asList(mtrx[j]);
cell.put("cell", cellList);
}
jqgrid.put("rows", rows);
return outputJSON(jqgrid, response);
} catch (Throwable e) {
throw new IllegalStateException("Can't marshall to JSON " + labDb,e);
}
}
@RequestMapping(value = "/detail_rw/updateJSON.do", method = RequestMethod.POST)
public String updateDetailJSON(@RequestParam("id") Integer labId,
Lab labForm, ModelMap m, HttpServletResponse response) {
List<LabMeta> labMetaList = getMetaHelper().getFromJsonForm(request, LabMeta.class);
labForm.setLabMeta(labMetaList);
if (labId == 0) {
labForm.setLastUpdTs(new Date());
labForm.setIsActive(1);
Lab labDb = this.labService.save(labForm);
labId = labDb.getLabId();
} else {
Lab labDb = this.labService.getById(labId);
labDb.setName(labForm.getName());
labDb.setIsActive(labForm.getIsActive());
labDb.setDepartmentId(labForm.getDepartmentId());
labDb.setPrimaryUserId(labForm.getPrimaryUserId());
this.labService.merge(labDb);
}
for (LabMeta meta : labMetaList) {
meta.setLabId(labId);
}
labMetaService.updateByLabId(labId, labMetaList);
// MimeMessageHelper a;
try {
response.getWriter().println(messageService.getMessage("lab.updated_success.label"));
return null;
} catch (Throwable e) {
throw new IllegalStateException("Cant output success message ", e);
}
}
@RequestMapping(value = "/pending/detail_rw/updateJSON.do", method = RequestMethod.POST)
public String updatePendingDetailJSON(
@RequestParam("id") Integer labPendingId, LabPending labPendingForm, ModelMap m, HttpServletResponse response) {
List<LabPendingMeta> labPendingMetaList = getLabPendingMetaHelper().getFromJsonForm(request, LabPendingMeta.class);
labPendingForm.setLabPendingMeta(labPendingMetaList);
if (labPendingId == 0) {
labPendingForm.setLastUpdTs(new Date());
// labPendingForm.setIsActive(1);
LabPending labPendingDb = this.labPendingService.save(labPendingForm);
labPendingId = labPendingDb.getLabPendingId();
} else {
LabPending labPendingDb = this.labPendingService.getById(labPendingId);
labPendingDb.setName(labPendingForm.getName());
// labPendingDb.setIsActive(labPendingForm.getIsActive());
labPendingDb.setDepartmentId(labPendingForm.getDepartmentId());
labPendingDb.setPrimaryUserId(labPendingForm.getPrimaryUserId());
this.labPendingService.merge(labPendingDb);
}
for (LabPendingMeta meta : labPendingMetaList) {
meta.setLabpendingId(labPendingId);
}
labPendingMetaService.updateByLabpendingId(labPendingId, labPendingMetaList);
// MimeMessageHelper a;
try {
response.getWriter().println(messageService.getMessage("labPending.updated_success.label"));
return null;
} catch (Throwable e) {
throw new IllegalStateException("Cant output success message ", e);
}
}
@RequestMapping(value = "/detail_rw/{deptId}/{labId}.do", method = RequestMethod.GET)
@PreAuthorize("hasRole('god') or hasRole('sa') or hasRole('ga') or hasRole('da-' + #deptId) or hasRole('lu-' + #labId)")
public String detailRW(@PathVariable("deptId") Integer deptId, @PathVariable("labId") Integer labId, ModelMap m) {
return detail(labId, m, true);
}
@RequestMapping(value = "/detail_ro/{deptId}/{labId}.do", method = RequestMethod.GET)
@PreAuthorize("hasRole('god') or hasRole('sa') or hasRole('ga') or hasRole('da-' + #deptId) or hasRole('lu-' + #labId)")
public String detailRO(@PathVariable("deptId") Integer deptId, @PathVariable("labId") Integer labId, ModelMap m) {
return detail(labId, m, false);
}
private String detail(Integer labId, ModelMap m, boolean isRW) {
Lab lab = this.labService.getById(labId);
lab.setLabMeta(getMetaHelper().syncWithMaster(lab.getLabMeta()));
List<LabUser> labUserList = lab.getLabUser();
labUserList.size();
List<Job> jobList = lab.getJob();
jobList.size();
m.addAttribute("lab", lab);
prepareSelectListData(m);
if (isRW) {
return "lab/detail_rw";
} else {
m.addAttribute("puserFullName", getPiFullNameFromLabId(labId));
return "lab/detail_ro";
}
}
@RequestMapping(value = "/pending/detail_rw/{deptId}/{labPendingId}.do", method = RequestMethod.GET)
@PreAuthorize("hasRole('god') or hasRole('sa') or hasRole('ga') or hasRole('da-' + #deptId)")
public String pendingDetailRW(@PathVariable("deptId") Integer deptId,
@PathVariable("labPendingId") Integer labPendingId, ModelMap m) {
return pendingDetail(labPendingId, m, true);
}
@RequestMapping(value = "/pending/detail_ro/{deptId}/{labPendingId}.do", method = RequestMethod.GET)
@PreAuthorize("hasRole('god') or hasRole('sa') or hasRole('ga') or hasRole('da-' + #deptId)")
public String pendingDetailRO(@PathVariable("deptId") Integer deptId,
@PathVariable("labPendingId") Integer labPendingId, ModelMap m) {
LabPending labPending = this.labPendingService.getLabPendingByLabPendingId(labPendingId);
if (labPending.getLabPendingId() == 0) {// labpendingId doesn't exist
waspMessage("labPending.labpendingid_notexist.error");
return "redirect:/dashboard.do";
}
if (deptId != labPending.getDepartmentId()) {
waspMessage("labPending.departmentid_mismatch.error");
return "redirect:/dashboard.do";
} else if (!labPending.getStatus().equalsIgnoreCase("PENDING")) {
waspMessage("labPending.status_mismatch.error");
return "redirect:/dashboard.do";
} else {
return pendingDetail(labPendingId, m, false);
}
}
private String getPiFullNameFromLabPendingId(int labPendingId) {
LabPending labPending = this.labPendingService.getById(labPendingId);
String puserFullName = "";
if (labPending.getUserpendingId() != null) {
// this PI is currently a pending user.
UserPending userPending = userPendingService.getUserPendingByUserPendingId(labPending.getUserpendingId());
puserFullName = userPending.getFirstName() + " " + userPending.getLastName();
} else if (labPending.getPrimaryUserId() != null){
// the referenced PI of this lab exists in the user table already
User user = userService.getUserByUserId(labPending.getPrimaryUserId());
puserFullName = user.getFirstName() + " " + user.getLastName();
} else {
// shouldn't get here
}
return puserFullName;
}
private String getPiFullNameFromLabId(int labId) {
Lab lab = this.labService.getById(labId);
String puserFullName = "";
User user = userService.getUserByUserId(lab.getPrimaryUserId());
puserFullName = user.getFirstName() + " " + user.getLastName();
return puserFullName;
}
private String pendingDetail(Integer labPendingId, ModelMap m, boolean isRW) {
LabPending labPending = this.labPendingService.getById(labPendingId);
labPending.setLabPendingMeta(getLabPendingMetaHelper().syncWithMaster(
labPending.getLabPendingMeta()));
// List<LabUser> labUserList = labPending.getLabUser();
// labUserList.size();
// List<Job> jobList = labPending.getJob();
// jobList.size();
m.addAttribute("puserFullName", getPiFullNameFromLabPendingId(labPendingId));
m.addAttribute("labPending", labPending);
prepareSelectListData(m);
return isRW ? "lab/pending/detail_rw" : "lab/pending/detail_ro";
}
@RequestMapping(value = "/create/form.do", method = RequestMethod.GET)
@PreAuthorize("hasRole('god')")
public String showEmptyForm(ModelMap m) {
Lab lab = new Lab();
lab.setLabMeta(getMetaHelper().getMasterList(LabMeta.class));
m.addAttribute("lab", lab);
prepareSelectListData(m);
return "lab/detail_rw";
}
@RequestMapping(value = "/create/form.do", method = RequestMethod.POST)
@PreAuthorize("hasRole('god')")
public String create(@Valid Lab labForm, BindingResult result,
SessionStatus status, ModelMap m) {
// read properties from form
List<LabMeta> labMetaList = getMetaHelper().getFromRequest(request, LabMeta.class);
getMetaHelper().validate(labMetaList, result);
labForm.setLabMeta(labMetaList);
if (result.hasErrors()) {
waspMessage("lab.created.error");
return "lab/detail_rw";
}
labForm.setLastUpdTs(new Date());
Lab labDb = this.labService.save(labForm);
for (LabMeta um : labMetaList) {
um.setLabId(labDb.getLabId());
}
labMetaService.updateByLabId(labDb.getLabId(), labMetaList);
status.setComplete();
waspMessage("lab.created_success.label");
return "redirect:/lab/detail_rw/" + labDb.getLabId() + ".do";
}
@RequestMapping(value = "/detail_rw/{deptId}/{labId}.do", method = RequestMethod.POST)
@PreAuthorize("hasRole('god') or hasRole('da-' + #deptId) or hasRole('lm-' + #labId)")
public String updateDetail(@PathVariable("deptId") Integer deptId,
@PathVariable("labId") Integer labId, @Valid Lab labForm,
BindingResult result, SessionStatus status, ModelMap m) {
// return read only version of page if cancel button pressed
String submitValue = (String) request.getParameter("submit");
if ( submitValue.equals(messageService.getMessage("labDetail.cancel.label")) ){
return "redirect:/lab/detail_ro/" + deptId + "/" + labId + ".do";
}
List<LabMeta> labMetaList = getMetaHelper().getFromRequest(request, LabMeta.class);
for (LabMeta meta : labMetaList) {
meta.setLabId(labId);
}
labForm.setLabMeta(labMetaList);
getMetaHelper().validate(labMetaList, result);
if (result.hasErrors()) {
prepareSelectListData(m);
waspMessage("lab.updated.error");
return "lab/detail_rw";
}
Lab labDb = this.labService.getById(labId);
labDb.setName(labForm.getName());
labDb.setDepartmentId(labForm.getDepartmentId());
labDb.setPrimaryUserId(labForm.getPrimaryUserId());
labDb.setLastUpdTs(new Date());
this.labService.merge(labDb);
labMetaService.updateByLabId(labId, labMetaList);
status.setComplete();
waspMessage("lab.updated_success.label");
// return "redirect:" + labId + ".do";
return "redirect:/lab/detail_ro/"
+ Integer.toString(labDb.getDepartmentId()) + "/" + labId
+ ".do";
}
@RequestMapping(value = "/pending/detail_rw/{deptId}/{labPendingId}.do", method = RequestMethod.POST)
@PreAuthorize("hasRole('god') or hasRole('da-' + #deptId) or hasRole('lm-' + #labPendingId)")
public String updatePendingDetail(@PathVariable("deptId") Integer deptId,
@PathVariable("labPendingId") Integer labPendingId,
@Valid LabPending labPendingForm, BindingResult result,
SessionStatus status, ModelMap m) {
// return read only version of page if cancel button pressed
String submitValue = (String) request.getParameter("submit");
if ( submitValue.equals(messageService.getMessage("labPending.cancel.label")) ){
return "redirect:/lab/pending/detail_ro/" + deptId + "/" + labPendingId + ".do";
}
List<LabPendingMeta> labPendingMetaList = getLabPendingMetaHelper().getFromRequest(request, LabPendingMeta.class);
for (LabPendingMeta meta : labPendingMetaList) {
meta.setLabpendingId(labPendingId);
}
labPendingForm.setLabPendingMeta(labPendingMetaList);
getLabPendingMetaHelper().validate(labPendingMetaList, result);
if (result.hasErrors()) {
waspMessage("labPending.updated.error");
prepareSelectListData(m);
m.addAttribute("puserFullName", getPiFullNameFromLabPendingId(labPendingId));
return "lab/pending/detail_rw";
}
LabPending labPendingDb = this.labPendingService.getById(labPendingId);
labPendingDb.setName(labPendingForm.getName());
labPendingDb.setDepartmentId(labPendingForm.getDepartmentId());
labPendingDb.setPrimaryUserId(labPendingForm.getPrimaryUserId());
labPendingDb.setLastUpdTs(new Date());
this.labPendingService.merge(labPendingDb);
labPendingMetaService.updateByLabpendingId(labPendingId, labPendingMetaList);
status.setComplete();
waspMessage("labPending.updated_success.label");
// return "redirect:" + labId + ".do";
return "redirect:/lab/pending/detail_ro/"
+ Integer.toString(labPendingDb.getDepartmentId()) + "/"
+ labPendingId + ".do";
}
@RequestMapping(value = "/user_manager/{labId}.do", method = RequestMethod.GET)
@PreAuthorize("hasRole('god') or hasRole('lu-' + #labId)")
public String userManager(@PathVariable("labId") Integer labId, ModelMap m) {
Lab lab = this.labService.getById(labId);
List<LabUser> labUsers = new ArrayList();
for (LabUser lu: (List<LabUser>) lab.getLabUser()){
if (!lu.getRole().getRoleName().equals("lp")){
labUsers.add(lu);
}
}
m.addAttribute("labuser", labUsers);
// add pending users applying to lab
pendingUserList(labId, m);
return "lab/user_manager";
}
@RequestMapping(value = "/user_list/{labId}.do", method = RequestMethod.GET)
@PreAuthorize("hasRole('god') or hasRole('lu-' + #labId)")
public String userList(@PathVariable("labId") Integer labId, ModelMap m) {
Lab lab = this.labService.getById(labId);
List<User> labManagers = new ArrayList();
List<User> labMembers= new ArrayList();
User pi = new User();
for(LabUser labUser : (List<LabUser>) lab.getLabUser() ){
User currentUser = userService.getUserByUserId(labUser.getUserId());
if (currentUser.getUserId() == lab.getPrimaryUserId()){
pi = currentUser;
} else if (labUser.getRole().getRoleName().equals("lm")){
labManagers.add(currentUser);
} else {
labMembers.add(currentUser);
}
}
m.addAttribute("lab", lab);
m.addAttribute("pi", pi);
m.addAttribute("labManagers", labManagers);
m.addAttribute("labMembers", labMembers);
return "lab/user_list";
}
@RequestMapping(value = "/pendinguser/list/{labId}.do", method = RequestMethod.GET)
@PreAuthorize("hasRole('god') or hasRole('lu-' + #labId)")
public String pendingUserList(@PathVariable("labId") Integer labId, ModelMap m) {
Lab lab = this.labService.getById(labId);
Map userPendingQueryMap = new HashMap();
userPendingQueryMap.put("labId", labId);
userPendingQueryMap.put("status", "PENDING");
List<UserPending> userPending = userPendingService.findByMap(userPendingQueryMap);
Map labUserPendingQueryMap = new HashMap();
labUserPendingQueryMap.put("labId", labId);
labUserPendingQueryMap.put("roleId", roleService.getRoleByRoleName("lp").getRoleId());
List<LabUser> labUserPending = labUserService.findByMap(labUserPendingQueryMap);
m.addAttribute("lab", lab);
m.addAttribute("userpending", userPending);
m.addAttribute("labuserpending", labUserPending);
return "lab/pendinguser/list";
}
@RequestMapping(value = "/user/role/{labId}/{userId}/{roleName}.do", method = RequestMethod.GET)
@PreAuthorize("hasRole('god') or hasRole('lm-' + #labId)")
public String userDetail(@PathVariable("labId") Integer labId,
@PathVariable("userId") Integer userId,
@PathVariable("roleName") String roleName, ModelMap m) {
// TODO CHECK VALID LABUSER
LabUser labUser = labUserService.getLabUserByLabIdUserId(labId, userId);
if (roleName.equals("xx")) {
// TODO CONFIRM ROLE WAS "LP"
labUserService.remove(labUser);
waspMessage("hello.error");
return "redirect:/lab/user_manager/" + labId + ".do";
}
// TODO CHECK VALID ROLE NAME
Role role = roleService.getRoleByRoleName(roleName);
// TODO CHECK VALID ROLE FLOW
labUser.setRoleId(role.getRoleId());
labUserService.merge(labUser);
// TODO ADD MESSAGE
// if i am the user, reauth
User me = authenticationService.getAuthenticatedUser();
if (me.getUserId() == userId) {
doReauth();
}
waspMessage("hello.error");
return "redirect:/lab/user_manager/" + labId + ".do";
}
/**
* Creates a new Lab from a LabPending object. If principal investigator is
* pending, her {@link User} account is generated first.
*
* @param labPending
* @return {@link Lab} the created lab
* @throws MetadataException
*/
public Lab createLabFromLabPending(LabPending labPending) throws MetadataException {
Lab lab = new Lab();
User user;
if (labPending.getUserpendingId() != null) {
// this PI is currently a pending user. Make them a full user before
// creating lab
UserPending userPending = userPendingService.getUserPendingByUserPendingId(labPending.getUserpendingId());
user = createUserFromUserPending(userPending);
} else if (labPending.getPrimaryUserId() != null) {
// the referenced PI of this lab exists in the user table already so
// get their record
user = userService.getUserByUserId(labPending.getPrimaryUserId());
} else {
// shouldn't get here
return lab; // return empty lab
}
lab.setPrimaryUserId(user.getUserId());
lab.setName(labPending.getName());
lab.setDepartmentId(labPending.getDepartmentId());
lab.setIsActive(1);
Lab labDb = labService.save(lab);
// copies meta data from labPendingMeta to labMeta.
MetaHelper labMetaHelper = new MetaHelper("lab", LabMeta.class, request.getSession());
labMetaHelper.getMasterList(LabMeta.class);
MetaHelper labPendingMetaHelper = new MetaHelper("labPending", LabPendingMeta.class, request.getSession());
List<LabPendingMeta> labPendingMetaList = labPendingMetaHelper.syncWithMaster(labPending.getLabPendingMeta());
for (LabPendingMeta lpm : labPendingMetaList) {
// get name from prefix by removing area
String name = lpm.getK().replaceAll("^.*?\\.", "");
try {
labMetaHelper.setMetaValueByName(name, lpm.getV());
} catch (MetadataException e) {
// no match for 'name' in labMeta
logger.debug("No match for labPendingMeta property with name '" + name + "' in labMeta properties");
}
}
for (LabMeta labMeta : (List<LabMeta>) labMetaHelper.getMetaList()) {
labMeta.setLabId(labDb.getLabId());
labMetaService.save(labMeta);
}
// set pi role
Role role = roleService.getRoleByRoleName("pi");
LabUser labUser = new LabUser();
labUser.setUserId(user.getUserId());
labUser.setLabId(lab.getLabId());
labUser.setRoleId(role.getRoleId());
labUserService.save(labUser);
// set status to 'CREATED' for any other pending labs of the same name
// (user may have attempted to apply for their
// lab account more than once)
Map pendingLabQueryMap = new HashMap();
pendingLabQueryMap.put("primaryUserId", user.getUserId());
pendingLabQueryMap.put("name", labDb.getName());
for (LabPending lp : (List<LabPending>) labPendingService.findByMap(pendingLabQueryMap)) {
lp.setStatus("CREATED");
labPendingService.save(lp);
}
// if i am the p.i. reauth
User me = authenticationService.getAuthenticatedUser();
if (me.getUserId() == user.getUserId()) {
doReauth();
}
return labDb;
}
/**
* Creates and returns a new {@link User} object from the supplied
* {@link UserPending} object.
*
* @param userPending
* the pending user
* @return {@link User} the created user
* @throws MetadataException
*/
public User createUserFromUserPending(UserPending userPending) throws MetadataException {
boolean isPiPending = (userPending.getLabId() == null) ? true : false;
User user = new User();
user.setFirstName(userPending.getFirstName());
user.setLastName(userPending.getLastName());
user.setEmail(userPending.getEmail());
user.setPassword(userPending.getPassword());
user.setLocale(userPending.getLocale());
user.setIsActive(1);
user.setLogin(userPending.getLogin());
User userDb = userService.save(user);
int userId = userDb.getUserId();
/*
* List<UserPendingMeta> userPendingMetaList =
* userPendingMetaService.getUserPendingMetaByUserPendingId
* (userPending.getUserPendingId()); copies meta data
*/
MetaHelper userMetaHelper = new MetaHelper("user", UserMeta.class, request.getSession());
userMetaHelper.getMasterList(UserMeta.class);
MetaHelper userPendingMetaHelper = new MetaHelper("userPending",
UserPendingMeta.class, request.getSession());
if (isPiPending)
userPendingMetaHelper.setArea("piPending");
List<UserPendingMeta> userPendingMetaList = userPendingMetaHelper.syncWithMaster(userPending.getUserPendingMeta());
for (UserPendingMeta upm : userPendingMetaList) {
// convert prefix
String name = upm.getK().replaceAll("^.*?\\.", "");
try {
userMetaHelper.setMetaValueByName(name, upm.getV());
} catch (MetadataException e) {
// no match for 'name' in userMeta data
logger.debug("No match for userPendingMeta property with name '" + name + "' in userMeta properties");
}
}
// if this user is not a PI, copy address information from the PI's User
// data.
if (!isPiPending) {
/*
* not a PI application request create a metahelper object to work
* with metadata for PI.
*/
String piUserLogin = userPendingMetaHelper.getMetaByName("primaryuserid").getV();
MetaHelper piMetaHelper = new MetaHelper("user", UserMeta.class, request.getSession());
piMetaHelper.syncWithMaster(userService.getUserByLogin(piUserLogin).getUserMeta()); // get PI meta from database and sync with
// current properties
try {
userMetaHelper.setMetaValueByName("institution", piMetaHelper.getMetaByName("institution").getV());
userMetaHelper.setMetaValueByName("departmentId", piMetaHelper.getMetaByName("departmentId").getV());
userMetaHelper.setMetaValueByName("state", piMetaHelper.getMetaByName("state").getV());
userMetaHelper.setMetaValueByName("city", piMetaHelper.getMetaByName("city").getV());
userMetaHelper.setMetaValueByName("country", piMetaHelper.getMetaByName("country").getV());
userMetaHelper.setMetaValueByName("zip", piMetaHelper.getMetaByName("zip").getV());
} catch (MetadataException e) {
// should never get here because of sync
throw new MetadataException("Metadata user / pi meta name mismatch", e);
}
}
for (UserMeta userMeta : (List<UserMeta>) userMetaHelper.getMetaList()) {
userMeta.setUserId(userId);
userMetaService.save(userMeta);
}
// userDb doesn't have associated metadata so add it
userDb.setUserMeta((List<UserMeta>) userMetaHelper.getMetaList());
/*
* Set status of any other applications from user with the same email
* address to 'CREATED' If the new user is also pending in other labs
* but not yet confirmed by the PI of each of those labs, add the user
* to that lab (via entry into the labUser table) and set their status
* as 'lp' (lab-pending).
*/
Map userPendingQueryMap = new HashMap();
userPendingQueryMap.put("email", userPending.getEmail());
userPendingQueryMap.put("status", "PENDING");
List<UserPending> userPendingList = userPendingService.findByMap(userPendingQueryMap);
userPendingQueryMap.put("status", "WAIT_EMAIL");
userPendingList.addAll(userPendingService.findByMap(userPendingQueryMap));
Role roleLabPending = roleService.getRoleByRoleName("lp");
for (UserPending userPendingCurrent : userPendingList) {
userPendingCurrent.setStatus("CREATED");
userPendingService.save(userPendingCurrent);
if (userPendingCurrent.getLabId() != null) {
// not a PI application request
LabUser labUserCurrent = labUserService.getLabUserByLabIdUserId(userPendingCurrent.getLabId(), userDb.getUserId());
if (labUserCurrent.getLabUserId() > 0) {
// already registered as a user of the requested lab
continue;
}
// add user to requested lab with lab-pending role
labUserCurrent.setUserId(userId);
labUserCurrent.setLabId(userPendingCurrent.getLabId());
labUserCurrent.setRoleId(roleLabPending.getRoleId());
labUserService.save(labUserCurrent);
}
/*
* iterate through list of pending labs. If this user was previously
* registered as 'userPending' in a lab, remove reference to her
* userPendingId and insert reference to her new userId instead
*/
Map labPendingQueryMap = new HashMap();
labPendingQueryMap.put("userpendingId", userPendingCurrent.getUserPendingId());
List<LabPending> labPendingList = labPendingService.findByMap(labPendingQueryMap);
for (LabPending labPending : labPendingList) {
labPending.setUserpendingId((Integer) null);
labPending.setPrimaryUserId(userId);
labPendingService.save(labPending);
}
}
return userDb;
}
/**
* Request-mapped function that allows a principal investigator or lab
* manager to accept or reject an application from a pending lab user (already
* an active WASP user) to join their lab.
* @param labId
* @param labUserId
* @param action
* @param m
* @return
*/
@RequestMapping(value = "/labuserpending/{action}/{labId}/{labUserId}.do", method = RequestMethod.GET)
@PreAuthorize("hasRole('god') or hasRole('lm-' + #labId)")
public String labUserPendingDetail(@PathVariable("labId") Integer labId,
@PathVariable("labUserId") Integer labUserId,
@PathVariable("action") String action, ModelMap m){
if (!(action.equals("approve") || action.equals("reject"))) {
waspMessage("userPending.action.error");
return "redirect:/dashboard.do";
}
LabUser labUserPending = labUserService.getLabUserByLabUserId(labUserId);
if (labUserPending.getLabId() != labId){
waspMessage("labuser.labUserNotFoundInLab.error");
return "redirect:/dashboard.do";
}
if (labUserPending.getRoleId() != roleService.getRoleByRoleName("lp").getRoleId() ) {
waspMessage("userPending.status_not_pending.error");
return "redirect:/dashboard.do";
}
if ("approve".equals(action)) {
// add user to lab (labUser table) with role 'lu' (lab-user) and
// email pending user notification of acceptance
Role roleLabUser = roleService.getRoleByRoleName("lu");
// createUserFromUserPending, should have made this.
labUserPending.setRoleId(roleLabUser.getRoleId());
labUserService.save(labUserPending);
emailService.sendPendingLabUserNotifyAccepted(labUserPending.getUser(), labUserPending.getLab());
waspMessage("userPending.approved.label");
} else {
labUserService.remove(labUserPending);
// email pending user notification of rejection
emailService.sendPendingLabUserNotifyRejected(labUserPending.getUser(), labUserPending.getLab());
waspMessage("userPending.rejected.label");
}
String referer = request.getHeader("Referer");
return "redirect:"+ referer;
}
/**
* Request-mapped function that allows a principal investigator or lab
* manager to accept or reject an application from a pending user (not yet
* an active WASP user) to join their lab.
*
* @param labId
* @param userPendingId
* @param action
* @param m
* @return view
* @throws MetadataException
*/
@RequestMapping(value = "/userpending/{action}/{labId}/{userPendingId}.do", method = RequestMethod.GET)
@PreAuthorize("hasRole('god') or hasRole('lm-' + #labId)")
public String userPendingDetail(@PathVariable("labId") Integer labId,
@PathVariable("userPendingId") Integer userPendingId,
@PathVariable("action") String action, ModelMap m)
throws MetadataException {
if (!(action.equals("approve") || action.equals("reject"))) {
waspMessage("userPending.action.error");
return "redirect:/dashboard.do";
}
UserPending userPending = userPendingService.getUserPendingByUserPendingId(userPendingId);
if (! userPending.getStatus().equals("PENDING") ) {
waspMessage("userPending.status_not_pending.error");
return "redirect:/dashboard.do";
}
if (userPending.getLabId().intValue() != labId.intValue()) {
waspMessage("userPending.labid_mismatch.error");
return "redirect:/dashboard.do";
}
User user;
if ("approve".equals(action)) {
// add user to lab (labUser table) with role 'lu' (lab-user) and
// email pending user notification of acceptance
user = createUserFromUserPending(userPending);
Role roleLabUser = roleService.getRoleByRoleName("lu");
// createUserFromUserPending, should have made this.
LabUser labUser = labUserService.getLabUserByLabIdUserId(labId, user.getUserId());
labUser.setRoleId(roleLabUser.getRoleId());
labUserService.merge(labUser);
emailService.sendPendingUserNotifyAccepted(user, labService.getLabByLabId(labId));
waspMessage("userPending.approved.label");
} else {
// email pending user notification of rejection
emailService.sendPendingUserNotifyRejected(userPending, labService.getLabByLabId(labId));
waspMessage("userPending.rejected.label");
}
userPending.setStatus(action);
userPendingService.save(userPending);
String referer = request.getHeader("Referer");
return "redirect:"+ referer;
}
/**
* Request-mapped function that allows a department administrator to accept
* or reject an application for a new lab within their department.
*
* @param departmentId
* @param labPendingId
* @param action
* @param m
* @return
* @throws MetadataException
*/
@RequestMapping(value = "/pending/{action}/{deptId}/{labPendingId}.do", method = RequestMethod.GET)
@PreAuthorize("hasRole('god') or hasRole('da-' + #deptId) or hasRole('ga-*')")
public String labPendingDetail(@PathVariable("deptId") Integer deptId,
@PathVariable("labPendingId") Integer labPendingId,
@PathVariable("action") String action, ModelMap m)
throws MetadataException {
if (!(action.equals("approve") || action.equals("reject"))) {
waspMessage("labPending.action.error");
//return "redirect:/department/detail/" + deptId + ".do";
return "redirect:/department/dapendingtasklist.do";
}
LabPending labPending = labPendingService.getLabPendingByLabPendingId(labPendingId);
if (! labPending.getStatus().equals("PENDING") ) {
waspMessage("labPending.status_not_pending.error");
//return "redirect:/department/detail/" + deptId + ".do";
return "redirect:/department/dapendingtasklist.do";
}
if (labPending.getDepartmentId() != deptId) {
waspMessage("labPending.departmentid_mismatch.error");
//return "redirect:/department/detail/" + deptId + ".do";
return "redirect:/department/dapendingtasklist.do";
}
if ("approve".equals(action)) {
Lab lab = createLabFromLabPending(labPending);
if (lab.getLabId() == 0){
waspMessage("labPending.could_not_create_lab.error");
//return "redirect:/department/detail/" + deptId + ".do";
return "redirect:/department/dapendingtasklist.do";
}
emailService.sendPendingLabNotifyAccepted(lab);
waspMessage("labPending.approved.label");
} else {
if (labPending.getUserpendingId() != null) {
// this PI is currently a pending user. Reject their pending
// user application too
UserPending userPending = userPendingService.getUserPendingByUserPendingId(labPending.getUserpendingId());
userPending.setStatus(action);
userPendingService.save(userPending);
waspMessage("labPending.rejected.label");
} else if (labPending.getPrimaryUserId() == null){
waspMessage("labPending.could_not_create_lab.error");
//return "redirect:/department/detail/" + deptId + ".do";
return "redirect:/department/dapendingtasklist.do";
}
emailService.sendPendingLabNotifyRejected(labPending);
}
labPending.setStatus(action);
labPendingService.save(labPending);
//return "redirect:/department/detail/" + deptId + ".do";
return "redirect:/department/dapendingtasklist.do";
}
/**
* Handles request to create new laboratory by GET.
* Pre-populates as much of the form as possible given current user information.
* @param m model
* @return view
* @throws MetadataException
*/
@RequestMapping(value = "/newrequest", method = RequestMethod.GET)
public String showRequestForm(ModelMap m) throws MetadataException {
MetaHelper labPendingMetaHelper = new MetaHelper("labPending", LabPendingMeta.class, request.getSession());
labPendingMetaHelper.getMasterList(LabPendingMeta.class);
MetaHelper userMetaHelper = new MetaHelper("user", UserMeta.class, request.getSession());
// Pre-populate some metadata from user's current information
User me = authenticationService.getAuthenticatedUser();
userMetaHelper.syncWithMaster(me.getUserMeta()); // get user meta from database and sync with current properties
LabPending labPending = new LabPending();
try {
String departmentId = userMetaHelper.getMetaByName("departmentId").getV();
if (departmentId != null && !departmentId.isEmpty()){
labPendingMetaHelper.setMetaValueByName("billing_departmentId",departmentId);
labPending.setDepartmentId(Integer.valueOf(departmentId));
String internalExternal = (deptService.findById( Integer.valueOf(departmentId) ).getIsInternal() == 1) ? "internal" : "external";
labPendingMetaHelper.setMetaValueByName("internal_external_lab", internalExternal);
}
labPendingMetaHelper.setMetaValueByName("billing_institution", userMetaHelper.getMetaByName("institution").getV());
labPendingMetaHelper.setMetaValueByName("billing_state", userMetaHelper.getMetaByName("state").getV());
labPendingMetaHelper.setMetaValueByName("billing_city", userMetaHelper.getMetaByName("city").getV());
labPendingMetaHelper.setMetaValueByName("billing_country", userMetaHelper.getMetaByName("country").getV());
labPendingMetaHelper.setMetaValueByName("billing_zip", userMetaHelper.getMetaByName("zip").getV());
labPendingMetaHelper.setMetaValueByName("billing_contact", me.getFirstName() + " " + me.getLastName());
} catch (MetadataException e) {
// report meta problem
logger.warn("Meta data mismatch when pre-populating labMeta data from userMeta (" + e.getMessage() + ")");
}
labPending.setLabPendingMeta( (List<LabPendingMeta>) labPendingMetaHelper.getMetaList());
m.addAttribute("labPending", labPending);
prepareSelectListData(m);
return "lab/newrequest";
}
/**
* Handles request to create new laboratory by POST.
* Validates LabPending form.
* @param labPendingForm
* @param result
* @param status
* @param m model
* @return view
*/
@RequestMapping(value = "/newrequest", method = RequestMethod.POST)
public String createNewLabPending(@Valid LabPending labPendingForm, BindingResult result, SessionStatus status, ModelMap m) {
MetaHelper pendingMetaHelper = new MetaHelper("labPending",LabPendingMeta.class, request.getSession());
List<LabPendingMeta> labPendingMetaList = pendingMetaHelper.getFromRequest(request, LabPendingMeta.class);
pendingMetaHelper.validate(labPendingMetaList, result);
User me = authenticationService.getAuthenticatedUser();
labPendingForm.setPrimaryUserId(me.getUserId());
labPendingForm.setStatus("PENDING");
if (result.hasErrors()) {
labPendingForm.setLabPendingMeta(labPendingMetaList);
prepareSelectListData(m);
waspMessage("user.created.error");
return "lab/newrequest";
}
LabPending labPendingDb = labPendingService.save(labPendingForm);
for (LabPendingMeta lpm : labPendingMetaList) {
lpm.setLabpendingId(labPendingDb.getLabPendingId());
labPendingMetaService.save(lpm);
}
status.setComplete();
emailService.sendPendingPrincipalConfirmRequest(labPendingDb);
waspMessage("labuser.request_success.label");
return "redirect:/dashboard.do";
}
/**
* Handles request to join an existing lab by logged in user.
* @param primaryUserLogin The login name of the PI of the lab which the user wishes to join
* @param m model
* @return view
*/
@RequestMapping(value = "/request.do", method = RequestMethod.POST)
public String requestAccess(
@RequestParam("primaryUserLogin") String primaryUserLogin,
ModelMap m) {
// check existence of primaryUser/lab
if (primaryUserLogin == null || primaryUserLogin.isEmpty()){
waspMessage("labuser.request_primaryuser.error");
return "redirect:/lab/newrequest.do";
}
User primaryUser = userService.getUserByLogin(primaryUserLogin);
if (primaryUser.getUserId() == 0) {
waspMessage("labuser.request_primaryuser.error");
return "redirect:/lab/newrequest.do";
}
Lab lab = labService.getLabByPrimaryUserId(primaryUser.getUserId());
if (lab.getLabId() == 0) {
waspMessage("labuser.request_primaryuser.error");
return "redirect:/lab/newrequest.do";
}
// check role of lab user
User me = authenticationService.getAuthenticatedUser();
LabUser labUser = labUserService.getLabUserByLabIdUserId(lab.getLabId(), me.getUserId());
if (labUser.getLabUserId() != 0) {
ArrayList<String> alreadyPendingRoles = new ArrayList();
alreadyPendingRoles.add("lp");
if (alreadyPendingRoles.contains(labUser.getRole().getRoleName())) {
waspMessage("labuser.request_alreadypending.error");
return "redirect:/lab/newrequest.do";
}
ArrayList<String> alreadyAccessRoles = new ArrayList();
alreadyAccessRoles.add("pi");
alreadyAccessRoles.add("lm");
alreadyAccessRoles.add("lu");
if (alreadyAccessRoles.contains(labUser.getRole().getRoleName())) {
waspMessage("labuser.request_alreadyaccess.error");
return "redirect:/lab/newrequest.do";
}
}
Role role = roleService.getRoleByRoleName("lp");
labUser.setLabId(lab.getLabId());
labUser.setUserId(me.getUserId());
labUser.setRoleId(role.getRoleId());
labUserService.save(labUser);
labUserService.refresh(labUser);
emailService.sendPendingLabUserConfirmRequest(labUser);
waspMessage("labuser.request_success.label");
return "redirect:/dashboard.do";
}
protected void prepareSelectListData(ModelMap m) {
Map userQueryMap = new HashMap();
userQueryMap.put("isActive", 1);
m.addAttribute("pusers", userService.findByMap(userQueryMap));
super.prepareSelectListData(m);
m.addAttribute("departments", deptService.findAll());
}
}
| src/main/java/edu/yu/einstein/wasp/controller/LabController.java | package edu.yu.einstein.wasp.controller;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import org.apache.commons.lang.StringUtils;
import org.codehaus.jackson.map.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.support.SessionStatus;
import edu.yu.einstein.wasp.model.AcctGrant;
import edu.yu.einstein.wasp.model.Department;
import edu.yu.einstein.wasp.model.Job;
import edu.yu.einstein.wasp.model.Lab;
import edu.yu.einstein.wasp.model.LabMeta;
import edu.yu.einstein.wasp.model.LabPending;
import edu.yu.einstein.wasp.model.LabPendingMeta;
import edu.yu.einstein.wasp.model.LabUser;
import edu.yu.einstein.wasp.model.MetaBase;
import edu.yu.einstein.wasp.model.MetaHelper;
import edu.yu.einstein.wasp.exception.MetadataException;
import edu.yu.einstein.wasp.model.Project;
import edu.yu.einstein.wasp.model.Role;
import edu.yu.einstein.wasp.model.Sample;
import edu.yu.einstein.wasp.model.SampleLab;
import edu.yu.einstein.wasp.model.User;
import edu.yu.einstein.wasp.model.UserMeta;
import edu.yu.einstein.wasp.model.UserPending;
import edu.yu.einstein.wasp.model.UserPendingMeta;
import edu.yu.einstein.wasp.service.AuthenticationService;
import edu.yu.einstein.wasp.service.DepartmentService;
import edu.yu.einstein.wasp.service.EmailService;
import edu.yu.einstein.wasp.service.LabMetaService;
import edu.yu.einstein.wasp.service.LabPendingMetaService;
import edu.yu.einstein.wasp.service.LabPendingService;
import edu.yu.einstein.wasp.service.LabService;
import edu.yu.einstein.wasp.service.LabUserService;
import edu.yu.einstein.wasp.service.MessageService;
import edu.yu.einstein.wasp.service.PasswordService;
import edu.yu.einstein.wasp.service.RoleService;
import edu.yu.einstein.wasp.service.UserMetaService;
import edu.yu.einstein.wasp.service.UserPendingMetaService;
import edu.yu.einstein.wasp.service.UserPendingService;
import edu.yu.einstein.wasp.taglib.JQFieldTag;
@Controller
@Transactional
@RequestMapping("/lab")
public class LabController extends WaspController {
@Autowired
private LabService labService;
@Autowired
private LabUserService labUserService;
@Autowired
private RoleService roleService;
@Autowired
private LabMetaService labMetaService;
@Autowired
private DepartmentService deptService;
@Autowired
private UserMetaService userMetaService;
@Autowired
private UserPendingService userPendingService;
@Autowired
private UserPendingMetaService userPendingMetaService;
@Autowired
private LabPendingService labPendingService;
@Autowired
private LabPendingMetaService labPendingMetaService;
@Autowired
private EmailService emailService;
@Autowired
private MessageService messageService;
@Autowired
private AuthenticationService authenticationService;
@Autowired
private PasswordService passwordService;
/**
* get a @{link MetaHelper} instance for working with LabMeta metadata
*
* @return
*/
private final MetaHelper getMetaHelper() {
return new MetaHelper("lab", LabMeta.class, request.getSession());
}
/**
* get a @{link MetaHelper} instance for working with labPending metadata
*
* @return
*/
private final MetaHelper getLabPendingMetaHelper() {
return new MetaHelper("labPending", LabPendingMeta.class,request.getSession());
}
/**
* Return list of labs in JGrid
*
* @param m
* @return
*/
@RequestMapping("/list")
@PreAuthorize("hasRole('god')")
public String list(ModelMap m) {
m.addAttribute("_metaList", getMetaHelper().getMasterList(MetaBase.class));
m.addAttribute(JQFieldTag.AREA_ATTR, getMetaHelper().getArea());
prepareSelectListData(m);
return "lab/list";
}
/**
* Returns list of labs
*
* @param response
* @return
*/
@RequestMapping(value = "/listJSON", method = RequestMethod.GET)
public String getListJSON(HttpServletResponse response) {
// result
Map<String, Object> jqgrid = new HashMap<String, Object>();
List<Lab> labList;
if (request.getParameter("_search") == null || StringUtils.isEmpty(request.getParameter("searchString"))) {
labList = this.labService.findAll();
} else {
Map<String, String> m = new HashMap<String, String>();
m.put(request.getParameter("searchField"), request.getParameter("searchString"));
labList = this.labService.findByMap(m);
if ("ne".equals(request.getParameter("searchOper"))) {
List<Lab> allLabs = new ArrayList<Lab>(this.labService.findAll());
for (Iterator<Lab> it = labList.iterator(); it.hasNext();) {
Lab excludeLab = it.next();
allLabs.remove(excludeLab);
}
labList = allLabs;
}
}
ObjectMapper mapper = new ObjectMapper();
try {
// String labs = mapper.writeValueAsString(labList);
int pageId = Integer.parseInt(request.getParameter("page")); // index of page
int pageRowNum = Integer.parseInt(request.getParameter("rows")); // number of rows in one page
int rowNum = labList.size(); // total number of rows
int pageNum = (rowNum + pageRowNum - 1) / pageRowNum; // total number of pages
jqgrid.put("page", pageId + "");
jqgrid.put("records", rowNum + "");
jqgrid.put("total", pageNum + "");
Map<String, String> userData = new HashMap<String, String>();
userData.put("page", "1");
userData.put("selId", StringUtils.isEmpty(request.getParameter("selId")) ? "" : request.getParameter("selId"));
jqgrid.put("userdata", userData);
List<Map> rows = new ArrayList<Map>();
Map<Integer, String> allDepts = new TreeMap<Integer, String>();
for (Department dept : (List<Department>) deptService.findAll()) {
allDepts.put(dept.getDepartmentId(), dept.getName());
}
Map<Integer, String> allUsers = new TreeMap<Integer, String>();
for (User user : (List<User>) userService.findAll()) {
allUsers.put(user.getUserId(), user.getFirstName() + " " + user.getLastName());
}
int frId = pageRowNum * (pageId - 1);
int toId = pageRowNum * pageId;
toId = toId <= rowNum ? toId : rowNum;
List<Lab> labPage = labList.subList(frId, toId);
for (Lab lab : labPage) {
Map cell = new HashMap();
cell.put("id", lab.getLabId());
List<LabMeta> labMeta = getMetaHelper().syncWithMaster(
lab.getLabMeta());
List<String> cellList = new ArrayList<String>(
Arrays.asList(new String[] {
lab.getName(),
"<a href=/wasp/user/list.do?selId="
+ lab.getPrimaryUserId() + ">"
+ allUsers.get(lab.getPrimaryUserId())
+ "</a>",
allDepts.get(lab.getDepartmentId()),
lab.getIsActive() == 1 ? "yes" : "no" }));
for (LabMeta meta : labMeta) {
cellList.add(meta.getV());
}
int l = cellList.size();
cell.put("cell", cellList);
rows.add(cell);
}
jqgrid.put("rows", rows);
return outputJSON(jqgrid, response);
} catch (Throwable e) {
throw new IllegalStateException("Can't marshall to JSON " + labList, e);
}
}
@RequestMapping(value = "/subgridJSON.do", method = RequestMethod.GET)
public String subgridJSON(@RequestParam("id") Integer labId, ModelMap m, HttpServletResponse response) {
Map<String, Object> jqgrid = new HashMap<String, Object>();
Lab labDb = this.labService.getById(labId);
List<LabUser> users = labDb.getLabUser();
List<Project> projects = labDb.getProject();
List<Sample> samples = labDb.getSample();
List<AcctGrant> accGrants = labDb.getAcctGrant();
List<SampleLab> sampleLabs = labDb.getSampleLab();
List<Job> jobs = labDb.getJob();
// get max lenth of the previous 4 lists
int max = Math.max(Math.max(users.size(), projects.size()), Math.max(samples.size(), accGrants.size()));
max = Math.max(max, Math.max(sampleLabs.size(), jobs.size()));
if (max == 0) {
LabUser lUser = new LabUser();
lUser.setUser(new User());
users.add(lUser);
projects.add(new Project());
samples.add(new Sample());
accGrants.add(new AcctGrant());
SampleLab sampleLab = new SampleLab();
sampleLab.setLab(new Lab());
sampleLabs.add(sampleLab);
jobs.add(new Job());
max = 1;
}
String[][] mtrx = new String[max][6];
ObjectMapper mapper = new ObjectMapper();
String text;
try {
// String labs = mapper.writeValueAsString(labList);
jqgrid.put("page", "1");
jqgrid.put("records", max + "");
jqgrid.put("total", max + "");
int i = 0;
int j = 0;
for (LabUser user : users) {
text = user.getUserId() == 0 ? "No Users"
: "<a href=/wasp/user/list.do?selId="
+ user.getUserId() + ">"
+ user.getUser().getFirstName() + " "
+ user.getUser().getLastName() + "</a>";
mtrx[j][i] = text;
j++;
}
i++;
j = 0;
for (Project project : projects) {
text = project.getProjectId() == 0 ? "No Projects" : project.getName();
mtrx[j][i] = text;
j++;
}
i++;
j = 0;
for (Sample sample : samples) {
text = sample.getSampleId() == 0 ? "No Samples" : sample.getName();
mtrx[j][i] = text;
j++;
}
i++;
j = 0;
for (AcctGrant acc : accGrants) {
text = acc.getGrantId() == 0 ? "No Acc Grants" : acc.getName();
mtrx[j][i] = text;
j++;
}
i++;
j = 0;
for (SampleLab sampleLab : sampleLabs) {
text = sampleLab.getLab().getLabId() == 0 ? "No Sample Labs" : sampleLab.getLab().getName();
mtrx[j][i] = text;
j++;
}
i++;
j = 0;
for (Job job : jobs) {
text = job.getJobId() == 0 ? "No Jobs" : job.getName();
mtrx[j][i] = text;
j++;
}
List<Map> rows = new ArrayList<Map>();
for (j = 0; j < max; j++) {
Map cell = new HashMap();
rows.add(cell);
cell.put("id", j + "");
List<String> cellList = Arrays.asList(mtrx[j]);
cell.put("cell", cellList);
}
jqgrid.put("rows", rows);
return outputJSON(jqgrid, response);
} catch (Throwable e) {
throw new IllegalStateException("Can't marshall to JSON " + labDb,e);
}
}
@RequestMapping(value = "/detail_rw/updateJSON.do", method = RequestMethod.POST)
public String updateDetailJSON(@RequestParam("id") Integer labId,
Lab labForm, ModelMap m, HttpServletResponse response) {
List<LabMeta> labMetaList = getMetaHelper().getFromJsonForm(request, LabMeta.class);
labForm.setLabMeta(labMetaList);
if (labId == 0) {
labForm.setLastUpdTs(new Date());
labForm.setIsActive(1);
Lab labDb = this.labService.save(labForm);
labId = labDb.getLabId();
} else {
Lab labDb = this.labService.getById(labId);
labDb.setName(labForm.getName());
labDb.setIsActive(labForm.getIsActive());
labDb.setDepartmentId(labForm.getDepartmentId());
labDb.setPrimaryUserId(labForm.getPrimaryUserId());
this.labService.merge(labDb);
}
for (LabMeta meta : labMetaList) {
meta.setLabId(labId);
}
labMetaService.updateByLabId(labId, labMetaList);
// MimeMessageHelper a;
try {
response.getWriter().println(messageService.getMessage("lab.updated_success.label"));
return null;
} catch (Throwable e) {
throw new IllegalStateException("Cant output success message ", e);
}
}
@RequestMapping(value = "/pending/detail_rw/updateJSON.do", method = RequestMethod.POST)
public String updatePendingDetailJSON(
@RequestParam("id") Integer labPendingId, LabPending labPendingForm, ModelMap m, HttpServletResponse response) {
List<LabPendingMeta> labPendingMetaList = getLabPendingMetaHelper().getFromJsonForm(request, LabPendingMeta.class);
labPendingForm.setLabPendingMeta(labPendingMetaList);
if (labPendingId == 0) {
labPendingForm.setLastUpdTs(new Date());
// labPendingForm.setIsActive(1);
LabPending labPendingDb = this.labPendingService.save(labPendingForm);
labPendingId = labPendingDb.getLabPendingId();
} else {
LabPending labPendingDb = this.labPendingService.getById(labPendingId);
labPendingDb.setName(labPendingForm.getName());
// labPendingDb.setIsActive(labPendingForm.getIsActive());
labPendingDb.setDepartmentId(labPendingForm.getDepartmentId());
labPendingDb.setPrimaryUserId(labPendingForm.getPrimaryUserId());
this.labPendingService.merge(labPendingDb);
}
for (LabPendingMeta meta : labPendingMetaList) {
meta.setLabpendingId(labPendingId);
}
labPendingMetaService.updateByLabpendingId(labPendingId, labPendingMetaList);
// MimeMessageHelper a;
try {
response.getWriter().println(messageService.getMessage("labPending.updated_success.label"));
return null;
} catch (Throwable e) {
throw new IllegalStateException("Cant output success message ", e);
}
}
@RequestMapping(value = "/detail_rw/{deptId}/{labId}.do", method = RequestMethod.GET)
@PreAuthorize("hasRole('god') or hasRole('sa') or hasRole('ga') or hasRole('da-' + #deptId) or hasRole('lu-' + #labId)")
public String detailRW(@PathVariable("deptId") Integer deptId, @PathVariable("labId") Integer labId, ModelMap m) {
return detail(labId, m, true);
}
@RequestMapping(value = "/detail_ro/{deptId}/{labId}.do", method = RequestMethod.GET)
@PreAuthorize("hasRole('god') or hasRole('sa') or hasRole('ga') or hasRole('da-' + #deptId) or hasRole('lu-' + #labId)")
public String detailRO(@PathVariable("deptId") Integer deptId, @PathVariable("labId") Integer labId, ModelMap m) {
return detail(labId, m, false);
}
private String detail(Integer labId, ModelMap m, boolean isRW) {
Lab lab = this.labService.getById(labId);
lab.setLabMeta(getMetaHelper().syncWithMaster(lab.getLabMeta()));
List<LabUser> labUserList = lab.getLabUser();
labUserList.size();
List<Job> jobList = lab.getJob();
jobList.size();
m.addAttribute("lab", lab);
prepareSelectListData(m);
if (isRW) {
return "lab/detail_rw";
} else {
m.addAttribute("puserFullName", getPiFullNameFromLabId(labId));
return "lab/detail_ro";
}
}
@RequestMapping(value = "/pending/detail_rw/{deptId}/{labPendingId}.do", method = RequestMethod.GET)
@PreAuthorize("hasRole('god') or hasRole('sa') or hasRole('ga') or hasRole('da-' + #deptId)")
public String pendingDetailRW(@PathVariable("deptId") Integer deptId,
@PathVariable("labPendingId") Integer labPendingId, ModelMap m) {
return pendingDetail(labPendingId, m, true);
}
@RequestMapping(value = "/pending/detail_ro/{deptId}/{labPendingId}.do", method = RequestMethod.GET)
@PreAuthorize("hasRole('god') or hasRole('sa') or hasRole('ga') or hasRole('da-' + #deptId)")
public String pendingDetailRO(@PathVariable("deptId") Integer deptId,
@PathVariable("labPendingId") Integer labPendingId, ModelMap m) {
LabPending labPending = this.labPendingService.getLabPendingByLabPendingId(labPendingId);
if (labPending.getLabPendingId() == 0) {// labpendingId doesn't exist
waspMessage("labPending.labpendingid_notexist.error");
return "redirect:/dashboard.do";
}
if (deptId != labPending.getDepartmentId()) {
waspMessage("labPending.departmentid_mismatch.error");
return "redirect:/dashboard.do";
} else if (!labPending.getStatus().equalsIgnoreCase("PENDING")) {
waspMessage("labPending.status_mismatch.error");
return "redirect:/dashboard.do";
} else {
return pendingDetail(labPendingId, m, false);
}
}
private String getPiFullNameFromLabPendingId(int labPendingId) {
LabPending labPending = this.labPendingService.getById(labPendingId);
String puserFullName = "";
if (labPending.getUserpendingId() != null) {
// this PI is currently a pending user.
UserPending userPending = userPendingService.getUserPendingByUserPendingId(labPending.getUserpendingId());
puserFullName = userPending.getFirstName() + " " + userPending.getLastName();
} else if (labPending.getPrimaryUserId() != null){
// the referenced PI of this lab exists in the user table already
User user = userService.getUserByUserId(labPending.getPrimaryUserId());
puserFullName = user.getFirstName() + " " + user.getLastName();
} else {
// shouldn't get here
}
return puserFullName;
}
private String getPiFullNameFromLabId(int labId) {
Lab lab = this.labService.getById(labId);
String puserFullName = "";
User user = userService.getUserByUserId(lab.getPrimaryUserId());
puserFullName = user.getFirstName() + " " + user.getLastName();
return puserFullName;
}
private String pendingDetail(Integer labPendingId, ModelMap m, boolean isRW) {
LabPending labPending = this.labPendingService.getById(labPendingId);
labPending.setLabPendingMeta(getLabPendingMetaHelper().syncWithMaster(
labPending.getLabPendingMeta()));
// List<LabUser> labUserList = labPending.getLabUser();
// labUserList.size();
// List<Job> jobList = labPending.getJob();
// jobList.size();
m.addAttribute("puserFullName", getPiFullNameFromLabPendingId(labPendingId));
m.addAttribute("labPending", labPending);
prepareSelectListData(m);
return isRW ? "lab/pending/detail_rw" : "lab/pending/detail_ro";
}
@RequestMapping(value = "/create/form.do", method = RequestMethod.GET)
@PreAuthorize("hasRole('god')")
public String showEmptyForm(ModelMap m) {
Lab lab = new Lab();
lab.setLabMeta(getMetaHelper().getMasterList(LabMeta.class));
m.addAttribute("lab", lab);
prepareSelectListData(m);
return "lab/detail_rw";
}
@RequestMapping(value = "/create/form.do", method = RequestMethod.POST)
@PreAuthorize("hasRole('god')")
public String create(@Valid Lab labForm, BindingResult result,
SessionStatus status, ModelMap m) {
// read properties from form
List<LabMeta> labMetaList = getMetaHelper().getFromRequest(request, LabMeta.class);
getMetaHelper().validate(labMetaList, result);
labForm.setLabMeta(labMetaList);
if (result.hasErrors()) {
waspMessage("lab.created.error");
return "lab/detail_rw";
}
labForm.setLastUpdTs(new Date());
Lab labDb = this.labService.save(labForm);
for (LabMeta um : labMetaList) {
um.setLabId(labDb.getLabId());
}
labMetaService.updateByLabId(labDb.getLabId(), labMetaList);
status.setComplete();
waspMessage("lab.created_success.label");
return "redirect:/lab/detail_rw/" + labDb.getLabId() + ".do";
}
@RequestMapping(value = "/detail_rw/{deptId}/{labId}.do", method = RequestMethod.POST)
@PreAuthorize("hasRole('god') or hasRole('da-' + #deptId) or hasRole('lm-' + #labId)")
public String updateDetail(@PathVariable("deptId") Integer deptId,
@PathVariable("labId") Integer labId, @Valid Lab labForm,
BindingResult result, SessionStatus status, ModelMap m) {
// return read only version of page if cancel button pressed
String submitValue = (String) request.getParameter("submit");
if ( submitValue.equals(messageService.getMessage("labDetail.cancel.label")) ){
return "redirect:/lab/detail_ro/" + deptId + "/" + labId + ".do";
}
List<LabMeta> labMetaList = getMetaHelper().getFromRequest(request, LabMeta.class);
for (LabMeta meta : labMetaList) {
meta.setLabId(labId);
}
labForm.setLabMeta(labMetaList);
getMetaHelper().validate(labMetaList, result);
if (result.hasErrors()) {
prepareSelectListData(m);
waspMessage("lab.updated.error");
return "lab/detail_rw";
}
Lab labDb = this.labService.getById(labId);
labDb.setName(labForm.getName());
labDb.setDepartmentId(labForm.getDepartmentId());
labDb.setPrimaryUserId(labForm.getPrimaryUserId());
labDb.setLastUpdTs(new Date());
this.labService.merge(labDb);
labMetaService.updateByLabId(labId, labMetaList);
status.setComplete();
waspMessage("lab.updated_success.label");
// return "redirect:" + labId + ".do";
return "redirect:/lab/detail_ro/"
+ Integer.toString(labDb.getDepartmentId()) + "/" + labId
+ ".do";
}
@RequestMapping(value = "/pending/detail_rw/{deptId}/{labPendingId}.do", method = RequestMethod.POST)
@PreAuthorize("hasRole('god') or hasRole('da-' + #deptId) or hasRole('lm-' + #labPendingId)")
public String updatePendingDetail(@PathVariable("deptId") Integer deptId,
@PathVariable("labPendingId") Integer labPendingId,
@Valid LabPending labPendingForm, BindingResult result,
SessionStatus status, ModelMap m) {
// return read only version of page if cancel button pressed
String submitValue = (String) request.getParameter("submit");
if ( submitValue.equals(messageService.getMessage("labPending.cancel.label")) ){
return "redirect:/lab/pending/detail_ro/" + deptId + "/" + labPendingId + ".do";
}
List<LabPendingMeta> labPendingMetaList = getLabPendingMetaHelper().getFromRequest(request, LabPendingMeta.class);
for (LabPendingMeta meta : labPendingMetaList) {
meta.setLabpendingId(labPendingId);
}
labPendingForm.setLabPendingMeta(labPendingMetaList);
getLabPendingMetaHelper().validate(labPendingMetaList, result);
if (result.hasErrors()) {
waspMessage("labPending.updated.error");
prepareSelectListData(m);
m.addAttribute("puserFullName", getPiFullNameFromLabPendingId(labPendingId));
return "lab/pending/detail_rw";
}
LabPending labPendingDb = this.labPendingService.getById(labPendingId);
labPendingDb.setName(labPendingForm.getName());
labPendingDb.setDepartmentId(labPendingForm.getDepartmentId());
labPendingDb.setPrimaryUserId(labPendingForm.getPrimaryUserId());
labPendingDb.setLastUpdTs(new Date());
this.labPendingService.merge(labPendingDb);
labPendingMetaService.updateByLabpendingId(labPendingId, labPendingMetaList);
status.setComplete();
waspMessage("labPending.updated_success.label");
// return "redirect:" + labId + ".do";
return "redirect:/lab/pending/detail_ro/"
+ Integer.toString(labPendingDb.getDepartmentId()) + "/"
+ labPendingId + ".do";
}
@RequestMapping(value = "/user_manager/{labId}.do", method = RequestMethod.GET)
@PreAuthorize("hasRole('god') or hasRole('lu-' + #labId)")
public String userManager(@PathVariable("labId") Integer labId, ModelMap m) {
Lab lab = this.labService.getById(labId);
List<LabUser> labUsers = new ArrayList();
for (LabUser lu: (List<LabUser>) lab.getLabUser()){
if (!lu.getRole().getRoleName().equals("lp")){
labUsers.add(lu);
}
}
m.addAttribute("labuser", labUsers);
// add pending users applying to lab
pendingUserList(labId, m);
return "lab/user_manager";
}
@RequestMapping(value = "/user_list/{labId}.do", method = RequestMethod.GET)
@PreAuthorize("hasRole('god') or hasRole('lu-' + #labId)")
public String userList(@PathVariable("labId") Integer labId, ModelMap m) {
Lab lab = this.labService.getById(labId);
List<User> labManagers = new ArrayList();
List<User> labMembers= new ArrayList();
User pi = new User();
for(LabUser labUser : (List<LabUser>) lab.getLabUser() ){
User currentUser = userService.getUserByUserId(labUser.getUserId());
if (currentUser.getUserId() == lab.getPrimaryUserId()){
pi = currentUser;
} else if (labUser.getRole().getRoleName().equals("lm")){
labManagers.add(currentUser);
} else {
labMembers.add(currentUser);
}
}
m.addAttribute("lab", lab);
m.addAttribute("pi", pi);
m.addAttribute("labManagers", labManagers);
m.addAttribute("labMembers", labMembers);
return "lab/user_list";
}
@RequestMapping(value = "/pendinguser/list/{labId}.do", method = RequestMethod.GET)
@PreAuthorize("hasRole('god') or hasRole('lu-' + #labId)")
public String pendingUserList(@PathVariable("labId") Integer labId, ModelMap m) {
Lab lab = this.labService.getById(labId);
Map userPendingQueryMap = new HashMap();
userPendingQueryMap.put("labId", labId);
userPendingQueryMap.put("status", "PENDING");
List<UserPending> userPending = userPendingService.findByMap(userPendingQueryMap);
Map labUserPendingQueryMap = new HashMap();
labUserPendingQueryMap.put("labId", labId);
labUserPendingQueryMap.put("roleId", roleService.getRoleByRoleName("lp").getRoleId());
List<LabUser> labUserPending = labUserService.findByMap(labUserPendingQueryMap);
m.addAttribute("lab", lab);
m.addAttribute("userpending", userPending);
m.addAttribute("labuserpending", labUserPending);
return "lab/pendinguser/list";
}
@RequestMapping(value = "/user/role/{labId}/{userId}/{roleName}.do", method = RequestMethod.GET)
@PreAuthorize("hasRole('god') or hasRole('lm-' + #labId)")
public String userDetail(@PathVariable("labId") Integer labId,
@PathVariable("userId") Integer userId,
@PathVariable("roleName") String roleName, ModelMap m) {
// TODO CHECK VALID LABUSER
LabUser labUser = labUserService.getLabUserByLabIdUserId(labId, userId);
if (roleName.equals("xx")) {
// TODO CONFIRM ROLE WAS "LP"
labUserService.remove(labUser);
waspMessage("hello.error");
return "redirect:/lab/user_manager/" + labId + ".do";
}
// TODO CHECK VALID ROLE NAME
Role role = roleService.getRoleByRoleName(roleName);
// TODO CHECK VALID ROLE FLOW
labUser.setRoleId(role.getRoleId());
labUserService.merge(labUser);
// TODO ADD MESSAGE
// if i am the user, reauth
User me = authenticationService.getAuthenticatedUser();
if (me.getUserId() == userId) {
doReauth();
}
waspMessage("hello.error");
return "redirect:/lab/user_manager/" + labId + ".do";
}
/**
* Creates a new Lab from a LabPending object. If principal investigator is
* pending, her {@link User} account is generated first.
*
* @param labPending
* @return {@link Lab} the created lab
* @throws MetadataException
*/
public Lab createLabFromLabPending(LabPending labPending) throws MetadataException {
Lab lab = new Lab();
User user;
if (labPending.getUserpendingId() != null) {
// this PI is currently a pending user. Make them a full user before
// creating lab
UserPending userPending = userPendingService.getUserPendingByUserPendingId(labPending.getUserpendingId());
user = createUserFromUserPending(userPending);
} else if (labPending.getPrimaryUserId() != null) {
// the referenced PI of this lab exists in the user table already so
// get their record
user = userService.getUserByUserId(labPending.getPrimaryUserId());
} else {
// shouldn't get here
return lab; // return empty lab
}
lab.setPrimaryUserId(user.getUserId());
lab.setName(labPending.getName());
lab.setDepartmentId(labPending.getDepartmentId());
lab.setIsActive(1);
Lab labDb = labService.save(lab);
// copies meta data from labPendingMeta to labMeta.
MetaHelper labMetaHelper = new MetaHelper("lab", LabMeta.class, request.getSession());
labMetaHelper.getMasterList(LabMeta.class);
MetaHelper labPendingMetaHelper = new MetaHelper("labPending", LabPendingMeta.class, request.getSession());
List<LabPendingMeta> labPendingMetaList = labPendingMetaHelper.syncWithMaster(labPending.getLabPendingMeta());
for (LabPendingMeta lpm : labPendingMetaList) {
// get name from prefix by removing area
String name = lpm.getK().replaceAll("^.*?\\.", "");
try {
labMetaHelper.setMetaValueByName(name, lpm.getV());
} catch (MetadataException e) {
// no match for 'name' in labMeta
logger.debug("No match for labPendingMeta property with name '" + name + "' in labMeta properties");
}
}
for (LabMeta labMeta : (List<LabMeta>) labMetaHelper.getMetaList()) {
labMeta.setLabId(labDb.getLabId());
labMetaService.save(labMeta);
}
// set pi role
Role role = roleService.getRoleByRoleName("pi");
LabUser labUser = new LabUser();
labUser.setUserId(user.getUserId());
labUser.setLabId(lab.getLabId());
labUser.setRoleId(role.getRoleId());
labUserService.save(labUser);
// set status to 'CREATED' for any other pending labs of the same name
// (user may have attempted to apply for their
// lab account more than once)
Map pendingLabQueryMap = new HashMap();
pendingLabQueryMap.put("primaryUserId", user.getUserId());
pendingLabQueryMap.put("name", labDb.getName());
for (LabPending lp : (List<LabPending>) labPendingService.findByMap(pendingLabQueryMap)) {
lp.setStatus("CREATED");
labPendingService.save(lp);
}
// if i am the p.i. reauth
User me = authenticationService.getAuthenticatedUser();
if (me.getUserId() == user.getUserId()) {
doReauth();
}
return labDb;
}
/**
* Creates and returns a new {@link User} object from the supplied
* {@link UserPending} object.
*
* @param userPending
* the pending user
* @return {@link User} the created user
* @throws MetadataException
*/
public User createUserFromUserPending(UserPending userPending) throws MetadataException {
boolean isPiPending = (userPending.getLabId() == null) ? true : false;
User user = new User();
user.setFirstName(userPending.getFirstName());
user.setLastName(userPending.getLastName());
user.setEmail(userPending.getEmail());
user.setPassword(userPending.getPassword());
user.setLocale(userPending.getLocale());
user.setIsActive(1);
user.setLogin(userPending.getLogin());
User userDb = userService.save(user);
int userId = userDb.getUserId();
/*
* List<UserPendingMeta> userPendingMetaList =
* userPendingMetaService.getUserPendingMetaByUserPendingId
* (userPending.getUserPendingId()); copies meta data
*/
MetaHelper userMetaHelper = new MetaHelper("user", UserMeta.class, request.getSession());
userMetaHelper.getMasterList(UserMeta.class);
MetaHelper userPendingMetaHelper = new MetaHelper("userPending",
UserPendingMeta.class, request.getSession());
if (isPiPending)
userPendingMetaHelper.setArea("piPending");
List<UserPendingMeta> userPendingMetaList = userPendingMetaHelper.syncWithMaster(userPending.getUserPendingMeta());
for (UserPendingMeta upm : userPendingMetaList) {
// convert prefix
String name = upm.getK().replaceAll("^.*?\\.", "");
try {
userMetaHelper.setMetaValueByName(name, upm.getV());
} catch (MetadataException e) {
// no match for 'name' in userMeta data
logger.debug("No match for userPendingMeta property with name '" + name + "' in userMeta properties");
}
}
// if this user is not a PI, copy address information from the PI's User
// data.
if (!isPiPending) {
/*
* not a PI application request create a metahelper object to work
* with metadata for PI.
*/
String piUserLogin = userPendingMetaHelper.getMetaByName("primaryuserid").getV();
MetaHelper piMetaHelper = new MetaHelper("user", UserMeta.class, request.getSession());
piMetaHelper.syncWithMaster(userService.getUserByLogin(piUserLogin).getUserMeta()); // get PI meta from database and sync with
// current properties
try {
userMetaHelper.setMetaValueByName("institution", piMetaHelper.getMetaByName("institution").getV());
userMetaHelper.setMetaValueByName("departmentId", piMetaHelper.getMetaByName("departmentId").getV());
userMetaHelper.setMetaValueByName("state", piMetaHelper.getMetaByName("state").getV());
userMetaHelper.setMetaValueByName("city", piMetaHelper.getMetaByName("city").getV());
userMetaHelper.setMetaValueByName("country", piMetaHelper.getMetaByName("country").getV());
userMetaHelper.setMetaValueByName("zip", piMetaHelper.getMetaByName("zip").getV());
} catch (MetadataException e) {
// should never get here because of sync
throw new MetadataException("Metadata user / pi meta name mismatch", e);
}
}
for (UserMeta userMeta : (List<UserMeta>) userMetaHelper.getMetaList()) {
userMeta.setUserId(userId);
userMetaService.save(userMeta);
}
// userDb doesn't have associated metadata so add it
userDb.setUserMeta((List<UserMeta>) userMetaHelper.getMetaList());
/*
* Set status of any other applications from user with the same email
* address to 'CREATED' If the new user is also pending in other labs
* but not yet confirmed by the PI of each of those labs, add the user
* to that lab (via entry into the labUser table) and set their status
* as 'lp' (lab-pending).
*/
Map userPendingQueryMap = new HashMap();
userPendingQueryMap.put("email", userPending.getEmail());
userPendingQueryMap.put("status", "PENDING");
List<UserPending> userPendingList = userPendingService.findByMap(userPendingQueryMap);
userPendingQueryMap.put("status", "WAIT_EMAIL");
userPendingList.addAll(userPendingService.findByMap(userPendingQueryMap));
Role roleLabPending = roleService.getRoleByRoleName("lp");
for (UserPending userPendingCurrent : userPendingList) {
userPendingCurrent.setStatus("CREATED");
userPendingService.save(userPendingCurrent);
if (userPendingCurrent.getLabId() != null) {
// not a PI application request
LabUser labUserCurrent = labUserService.getLabUserByLabIdUserId(userPendingCurrent.getLabId(), userDb.getUserId());
if (labUserCurrent.getLabUserId() > 0) {
// already registered as a user of the requested lab
continue;
}
// add user to requested lab with lab-pending role
labUserCurrent.setUserId(userId);
labUserCurrent.setLabId(userPendingCurrent.getLabId());
labUserCurrent.setRoleId(roleLabPending.getRoleId());
labUserService.save(labUserCurrent);
}
/*
* iterate through list of pending labs. If this user was previously
* registered as 'userPending' in a lab, remove reference to her
* userPendingId and insert reference to her new userId instead
*/
Map labPendingQueryMap = new HashMap();
labPendingQueryMap.put("userpendingId", userPendingCurrent.getUserPendingId());
List<LabPending> labPendingList = labPendingService.findByMap(labPendingQueryMap);
for (LabPending labPending : labPendingList) {
labPending.setUserpendingId((Integer) null);
labPending.setPrimaryUserId(userId);
labPendingService.save(labPending);
}
}
return userDb;
}
/**
* Request-mapped function that allows a principal investigator or lab
* manager to accept or reject an application from a pending lab user (already
* an active WASP user) to join their lab.
* @param labId
* @param labUserId
* @param action
* @param m
* @return
*/
@RequestMapping(value = "/labuserpending/{action}/{labId}/{labUserId}.do", method = RequestMethod.GET)
@PreAuthorize("hasRole('god') or hasRole('lm-' + #labId)")
public String labUserPendingDetail(@PathVariable("labId") Integer labId,
@PathVariable("labUserId") Integer labUserId,
@PathVariable("action") String action, ModelMap m){
if (!(action.equals("approve") || action.equals("reject"))) {
waspMessage("userPending.action.error");
return "redirect:/dashboard.do";
}
LabUser labUserPending = labUserService.getLabUserByLabUserId(labUserId);
if (labUserPending.getLabId() != labId){
waspMessage("labuser.labUserNotFoundInLab.error");
return "redirect:/dashboard.do";
}
if (labUserPending.getRoleId() != roleService.getRoleByRoleName("lp").getRoleId() ) {
waspMessage("userPending.status_not_pending.error");
return "redirect:/dashboard.do";
}
if ("approve".equals(action)) {
// add user to lab (labUser table) with role 'lu' (lab-user) and
// email pending user notification of acceptance
Role roleLabUser = roleService.getRoleByRoleName("lu");
// createUserFromUserPending, should have made this.
labUserPending.setRoleId(roleLabUser.getRoleId());
labUserService.save(labUserPending);
emailService.sendPendingLabUserNotifyAccepted(labUserPending.getUser(), labUserPending.getLab());
waspMessage("userPending.approved.label");
} else {
labUserService.remove(labUserPending);
// email pending user notification of rejection
emailService.sendPendingLabUserNotifyRejected(labUserPending.getUser(), labUserPending.getLab());
waspMessage("userPending.rejected.label");
}
String referer = request.getHeader("Referer");
return "redirect:"+ referer;
}
/**
* Request-mapped function that allows a principal investigator or lab
* manager to accept or reject an application from a pending user (not yet
* an active WASP user) to join their lab.
*
* @param labId
* @param userPendingId
* @param action
* @param m
* @return view
* @throws MetadataException
*/
@RequestMapping(value = "/userpending/{action}/{labId}/{userPendingId}.do", method = RequestMethod.GET)
@PreAuthorize("hasRole('god') or hasRole('lm-' + #labId)")
public String userPendingDetail(@PathVariable("labId") Integer labId,
@PathVariable("userPendingId") Integer userPendingId,
@PathVariable("action") String action, ModelMap m)
throws MetadataException {
if (!(action.equals("approve") || action.equals("reject"))) {
waspMessage("userPending.action.error");
return "redirect:/dashboard.do";
}
UserPending userPending = userPendingService.getUserPendingByUserPendingId(userPendingId);
if (! userPending.getStatus().equals("PENDING") ) {
waspMessage("userPending.status_not_pending.error");
return "redirect:/dashboard.do";
}
if (userPending.getLabId() != labId) {
waspMessage("userPending.labid_mismatch.error");
return "redirect:/dashboard.do";
}
User user;
if ("approve".equals(action)) {
// add user to lab (labUser table) with role 'lu' (lab-user) and
// email pending user notification of acceptance
user = createUserFromUserPending(userPending);
Role roleLabUser = roleService.getRoleByRoleName("lu");
// createUserFromUserPending, should have made this.
LabUser labUser = labUserService.getLabUserByLabIdUserId(labId, user.getUserId());
labUser.setRoleId(roleLabUser.getRoleId());
labUserService.merge(labUser);
emailService.sendPendingUserNotifyAccepted(user, labService.getLabByLabId(labId));
waspMessage("userPending.approved.label");
} else {
// email pending user notification of rejection
emailService.sendPendingUserNotifyRejected(userPending, labService.getLabByLabId(labId));
waspMessage("userPending.rejected.label");
}
userPending.setStatus(action);
userPendingService.save(userPending);
String referer = request.getHeader("Referer");
return "redirect:"+ referer;
}
/**
* Request-mapped function that allows a department administrator to accept
* or reject an application for a new lab within their department.
*
* @param departmentId
* @param labPendingId
* @param action
* @param m
* @return
* @throws MetadataException
*/
@RequestMapping(value = "/pending/{action}/{deptId}/{labPendingId}.do", method = RequestMethod.GET)
@PreAuthorize("hasRole('god') or hasRole('da-' + #deptId) or hasRole('ga-*')")
public String labPendingDetail(@PathVariable("deptId") Integer deptId,
@PathVariable("labPendingId") Integer labPendingId,
@PathVariable("action") String action, ModelMap m)
throws MetadataException {
if (!(action.equals("approve") || action.equals("reject"))) {
waspMessage("labPending.action.error");
//return "redirect:/department/detail/" + deptId + ".do";
return "redirect:/department/dapendingtasklist.do";
}
LabPending labPending = labPendingService.getLabPendingByLabPendingId(labPendingId);
if (! labPending.getStatus().equals("PENDING") ) {
waspMessage("labPending.status_not_pending.error");
//return "redirect:/department/detail/" + deptId + ".do";
return "redirect:/department/dapendingtasklist.do";
}
if (labPending.getDepartmentId() != deptId) {
waspMessage("labPending.departmentid_mismatch.error");
//return "redirect:/department/detail/" + deptId + ".do";
return "redirect:/department/dapendingtasklist.do";
}
if ("approve".equals(action)) {
Lab lab = createLabFromLabPending(labPending);
if (lab.getLabId() == 0){
waspMessage("labPending.could_not_create_lab.error");
//return "redirect:/department/detail/" + deptId + ".do";
return "redirect:/department/dapendingtasklist.do";
}
emailService.sendPendingLabNotifyAccepted(lab);
waspMessage("labPending.approved.label");
} else {
if (labPending.getUserpendingId() != null) {
// this PI is currently a pending user. Reject their pending
// user application too
UserPending userPending = userPendingService.getUserPendingByUserPendingId(labPending.getUserpendingId());
userPending.setStatus(action);
userPendingService.save(userPending);
waspMessage("labPending.rejected.label");
} else if (labPending.getPrimaryUserId() == null){
waspMessage("labPending.could_not_create_lab.error");
//return "redirect:/department/detail/" + deptId + ".do";
return "redirect:/department/dapendingtasklist.do";
}
emailService.sendPendingLabNotifyRejected(labPending);
}
labPending.setStatus(action);
labPendingService.save(labPending);
//return "redirect:/department/detail/" + deptId + ".do";
return "redirect:/department/dapendingtasklist.do";
}
/**
* Handles request to create new laboratory by GET.
* Pre-populates as much of the form as possible given current user information.
* @param m model
* @return view
* @throws MetadataException
*/
@RequestMapping(value = "/newrequest", method = RequestMethod.GET)
public String showRequestForm(ModelMap m) throws MetadataException {
MetaHelper labPendingMetaHelper = new MetaHelper("labPending", LabPendingMeta.class, request.getSession());
labPendingMetaHelper.getMasterList(LabPendingMeta.class);
MetaHelper userMetaHelper = new MetaHelper("user", UserMeta.class, request.getSession());
// Pre-populate some metadata from user's current information
User me = authenticationService.getAuthenticatedUser();
userMetaHelper.syncWithMaster(me.getUserMeta()); // get user meta from database and sync with current properties
LabPending labPending = new LabPending();
try {
String departmentId = userMetaHelper.getMetaByName("departmentId").getV();
if (departmentId != null && !departmentId.isEmpty()){
labPendingMetaHelper.setMetaValueByName("billing_departmentId",departmentId);
labPending.setDepartmentId(Integer.valueOf(departmentId));
String internalExternal = (deptService.findById( Integer.valueOf(departmentId) ).getIsInternal() == 1) ? "internal" : "external";
labPendingMetaHelper.setMetaValueByName("internal_external_lab", internalExternal);
}
labPendingMetaHelper.setMetaValueByName("billing_institution", userMetaHelper.getMetaByName("institution").getV());
labPendingMetaHelper.setMetaValueByName("billing_state", userMetaHelper.getMetaByName("state").getV());
labPendingMetaHelper.setMetaValueByName("billing_city", userMetaHelper.getMetaByName("city").getV());
labPendingMetaHelper.setMetaValueByName("billing_country", userMetaHelper.getMetaByName("country").getV());
labPendingMetaHelper.setMetaValueByName("billing_zip", userMetaHelper.getMetaByName("zip").getV());
labPendingMetaHelper.setMetaValueByName("billing_contact", me.getFirstName() + " " + me.getLastName());
} catch (MetadataException e) {
// report meta problem
logger.warn("Meta data mismatch when pre-populating labMeta data from userMeta (" + e.getMessage() + ")");
}
labPending.setLabPendingMeta( (List<LabPendingMeta>) labPendingMetaHelper.getMetaList());
m.addAttribute("labPending", labPending);
prepareSelectListData(m);
return "lab/newrequest";
}
/**
* Handles request to create new laboratory by POST.
* Validates LabPending form.
* @param labPendingForm
* @param result
* @param status
* @param m model
* @return view
*/
@RequestMapping(value = "/newrequest", method = RequestMethod.POST)
public String createNewLabPending(@Valid LabPending labPendingForm, BindingResult result, SessionStatus status, ModelMap m) {
MetaHelper pendingMetaHelper = new MetaHelper("labPending",LabPendingMeta.class, request.getSession());
List<LabPendingMeta> labPendingMetaList = pendingMetaHelper.getFromRequest(request, LabPendingMeta.class);
pendingMetaHelper.validate(labPendingMetaList, result);
User me = authenticationService.getAuthenticatedUser();
labPendingForm.setPrimaryUserId(me.getUserId());
labPendingForm.setStatus("PENDING");
if (result.hasErrors()) {
labPendingForm.setLabPendingMeta(labPendingMetaList);
prepareSelectListData(m);
waspMessage("user.created.error");
return "lab/newrequest";
}
LabPending labPendingDb = labPendingService.save(labPendingForm);
for (LabPendingMeta lpm : labPendingMetaList) {
lpm.setLabpendingId(labPendingDb.getLabPendingId());
labPendingMetaService.save(lpm);
}
status.setComplete();
emailService.sendPendingPrincipalConfirmRequest(labPendingDb);
waspMessage("labuser.request_success.label");
return "redirect:/dashboard.do";
}
/**
* Handles request to join an existing lab by logged in user.
* @param primaryUserLogin The login name of the PI of the lab which the user wishes to join
* @param m model
* @return view
*/
@RequestMapping(value = "/request.do", method = RequestMethod.POST)
public String requestAccess(
@RequestParam("primaryUserLogin") String primaryUserLogin,
ModelMap m) {
// check existence of primaryUser/lab
if (primaryUserLogin == null || primaryUserLogin.isEmpty()){
waspMessage("labuser.request_primaryuser.error");
return "redirect:/lab/newrequest.do";
}
User primaryUser = userService.getUserByLogin(primaryUserLogin);
if (primaryUser.getUserId() == 0) {
waspMessage("labuser.request_primaryuser.error");
return "redirect:/lab/newrequest.do";
}
Lab lab = labService.getLabByPrimaryUserId(primaryUser.getUserId());
if (lab.getLabId() == 0) {
waspMessage("labuser.request_primaryuser.error");
return "redirect:/lab/newrequest.do";
}
// check role of lab user
User me = authenticationService.getAuthenticatedUser();
LabUser labUser = labUserService.getLabUserByLabIdUserId(lab.getLabId(), me.getUserId());
if (labUser.getLabUserId() != 0) {
ArrayList<String> alreadyPendingRoles = new ArrayList();
alreadyPendingRoles.add("lp");
if (alreadyPendingRoles.contains(labUser.getRole().getRoleName())) {
waspMessage("labuser.request_alreadypending.error");
return "redirect:/lab/newrequest.do";
}
ArrayList<String> alreadyAccessRoles = new ArrayList();
alreadyAccessRoles.add("pi");
alreadyAccessRoles.add("lm");
alreadyAccessRoles.add("lu");
if (alreadyAccessRoles.contains(labUser.getRole().getRoleName())) {
waspMessage("labuser.request_alreadyaccess.error");
return "redirect:/lab/newrequest.do";
}
}
Role role = roleService.getRoleByRoleName("lp");
labUser.setLabId(lab.getLabId());
labUser.setUserId(me.getUserId());
labUser.setRoleId(role.getRoleId());
labUserService.save(labUser);
labUserService.refresh(labUser);
emailService.sendPendingLabUserConfirmRequest(labUser);
waspMessage("labuser.request_success.label");
return "redirect:/dashboard.do";
}
protected void prepareSelectListData(ModelMap m) {
Map userQueryMap = new HashMap();
userQueryMap.put("isActive", 1);
m.addAttribute("pusers", userService.findByMap(userQueryMap));
super.prepareSelectListData(m);
m.addAttribute("departments", deptService.findAll());
}
}
| fixes WS-92
| src/main/java/edu/yu/einstein/wasp/controller/LabController.java | fixes WS-92 | <ide><path>rc/main/java/edu/yu/einstein/wasp/controller/LabController.java
<ide> return "redirect:/dashboard.do";
<ide> }
<ide>
<del> if (userPending.getLabId() != labId) {
<add> if (userPending.getLabId().intValue() != labId.intValue()) {
<ide> waspMessage("userPending.labid_mismatch.error");
<ide> return "redirect:/dashboard.do";
<ide> } |
|
JavaScript | mit | 623592b7887389db37220e63673405fb54e93a1b | 0 | diego-leal/connapp-web-cms,diego-leal/connapp-web-cms,diego-leal/connapp-web-cms | module.exports = function( app ) {
const
Model = app.models.user,
user = require( '../lib/mongoose')( Model );
function createUser( req, res ) {
let doc = req.body;
Promise.resolve( doc )
.then( validateName )
.then( validateGroup )
.then( validatePassword )
.then( validateEmail )
.then( save )
.then( resolveResponse )
.catch( rejectResponse );
function validateName( _doc ) {
if ( !( _doc.firstName || _doc.lastName ) ) {
throw new Error( 'O nome do usuário deve ser informado.' );
}
return _doc;
}
function validateGroup( _doc ) {
const
groups = [ 'admin', 'user' ],
validGroup = group => _doc.group === group,
isValid = groups.some( validGroup );
if( !isValid ) {
throw new Error( 'O grupo informado não é válido.' );
}
return _doc;
}
function validateEmail( _doc ) {
return new Promise( ( resolve, reject ) => {
user.get( { email: _doc.email } )
.then( userDoc => {
if ( userDoc ) {
return reject( new Error( 'O email informada já está sendo usado por outro usuário' ) );
}
resolve( _doc );
});
});
}
function validatePassword( _doc ) {
if ( !_doc.password || _doc.password.length < 8 ) {
throw new Error( 'A senha não pode está vazia ou ser menor que 8 caracteres' );
}
return _doc;
}
function save( _doc ) {
return new Promise( ( resolve, reject ) => {
user.save( _doc )
.then( _user => resolve( _user ) )
.catch( error => reject( error ) );
});
}
function resolveResponse( _user ) {
res.status( 200 ).json( _user );
}
function rejectResponse( error ) {
console.log( error );
res.status( 500 ).json( error );
}
}
return {
createUser
};
};
| api/controllers/user.js | module.exports = function( app ) {
const
Model = app.models.user,
user = require( '../lib/mongoose')( Model );
function createUser( req, res ) {
let doc = req.body;
user.save( doc )
.then( status => res.json( status ) )
.catch( error => res.status( 500 ).json( error ) );
}
return {
createUser
};
};
| [UPDATE]: Adicionado validação dos parametros da requisição
| api/controllers/user.js | [UPDATE]: Adicionado validação dos parametros da requisição | <ide><path>pi/controllers/user.js
<ide> function createUser( req, res ) {
<ide> let doc = req.body;
<ide>
<del> user.save( doc )
<del> .then( status => res.json( status ) )
<del> .catch( error => res.status( 500 ).json( error ) );
<add> Promise.resolve( doc )
<add> .then( validateName )
<add> .then( validateGroup )
<add> .then( validatePassword )
<add> .then( validateEmail )
<add> .then( save )
<add> .then( resolveResponse )
<add> .catch( rejectResponse );
<add>
<add> function validateName( _doc ) {
<add> if ( !( _doc.firstName || _doc.lastName ) ) {
<add> throw new Error( 'O nome do usuário deve ser informado.' );
<add> }
<add> return _doc;
<add> }
<add>
<add> function validateGroup( _doc ) {
<add> const
<add> groups = [ 'admin', 'user' ],
<add> validGroup = group => _doc.group === group,
<add> isValid = groups.some( validGroup );
<add>
<add> if( !isValid ) {
<add> throw new Error( 'O grupo informado não é válido.' );
<add> }
<add>
<add> return _doc;
<add> }
<add>
<add> function validateEmail( _doc ) {
<add> return new Promise( ( resolve, reject ) => {
<add> user.get( { email: _doc.email } )
<add> .then( userDoc => {
<add> if ( userDoc ) {
<add> return reject( new Error( 'O email informada já está sendo usado por outro usuário' ) );
<add> }
<add>
<add> resolve( _doc );
<add> });
<add> });
<add> }
<add>
<add> function validatePassword( _doc ) {
<add> if ( !_doc.password || _doc.password.length < 8 ) {
<add> throw new Error( 'A senha não pode está vazia ou ser menor que 8 caracteres' );
<add> }
<add> return _doc;
<add> }
<add>
<add> function save( _doc ) {
<add> return new Promise( ( resolve, reject ) => {
<add> user.save( _doc )
<add> .then( _user => resolve( _user ) )
<add> .catch( error => reject( error ) );
<add> });
<add> }
<add>
<add> function resolveResponse( _user ) {
<add> res.status( 200 ).json( _user );
<add> }
<add>
<add> function rejectResponse( error ) {
<add> console.log( error );
<add> res.status( 500 ).json( error );
<add> }
<ide> }
<ide>
<ide> return { |
|
Java | apache-2.0 | e9cb99572d4ea1edebf48004361c7e0473c9b1db | 0 | tomgibara/storage | /*
* Copyright 2015 Tom Gibara
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.tomgibara.storage;
import static com.tomgibara.storage.Stores.immutableException;
import java.util.Arrays;
import java.util.Spliterator;
import java.util.Spliterators;
abstract class PrimitiveStore<V> extends AbstractStore<V> {
private static void failGrowCopy() {
throw new IllegalArgumentException("cannot increase size, null not settable");
}
private static final <T> StoreType<T> newType(Class<T> clss, boolean nullSettable, T nullValue) {
//TODO can we avoid intermediate object creation?
StoreType<T> type = StoreType.of(clss);
return nullSettable ? type.settingNullToValue(nullValue) : type.settingNullDisallowed();
}
private static abstract class PrimitiveStorage<P> implements Storage<P> {
final StoreType<P> type;
PrimitiveStorage(StoreType<P> type) { this.type = type; }
@Override final public StoreType<P> type() { return type; }
}
private static final Storage<Byte> byteStorage(StoreType<Byte> type) {
return new PrimitiveStorage<Byte>(type) {
@Override public PrimitiveStore<Byte> newStore(int size, Byte initialValue) { return new ByteStore(size, type, initialValue); }
};
};
private static final Storage<Float> floatStorage(StoreType<Float> type) {
return new PrimitiveStorage<Float>(type) {
@Override public PrimitiveStore<Float> newStore(int size, Float initialValue) { return new FloatStore(size, type, initialValue); }
};
};
private static final Storage<Character> charStorage(StoreType<Character> type) {
return new PrimitiveStorage<Character>(type) {
@Override public PrimitiveStore<Character> newStore(int size, Character initialValue) { return new CharacterStore(size, type, initialValue); }
};
};
private static final Storage<Short> shortStorage(StoreType<Short> type) {
return new PrimitiveStorage<Short>(type) {
@Override public PrimitiveStore<Short> newStore(int size, Short initialValue) { return new ShortStore(size, type, initialValue); }
};
};
private static final Storage<Long> longStorage(StoreType<Long> type) {
return new PrimitiveStorage<Long>(type) {
@Override public PrimitiveStore<Long> newStore(int size, Long initialValue) { return new LongStore(size, type, initialValue); }
};
};
private static final Storage<Integer> intStorage(StoreType<Integer> type) {
return new PrimitiveStorage<Integer>(type) {
@Override public PrimitiveStore<Integer> newStore(int size, Integer initialValue) { return new IntegerStore(size, type, initialValue); }
};
};
private static final Storage<Double> doubleStorage(StoreType<Double> type) {
return new PrimitiveStorage<Double>(type) {
@Override public PrimitiveStore<Double> newStore(int size, Double initialValue) { return new DoubleStore(size, type, initialValue); }
};
};
private static final Storage<Boolean> booleanStorage(StoreType<Boolean> type) {
return new PrimitiveStorage<Boolean>(type) {
@Override public PrimitiveStore<Boolean> newStore(int size, Boolean initialValue) { return new BooleanStore(size, type, initialValue); }
};
};
@SuppressWarnings("unchecked")
static <V> Storage<V> newStorage(StoreType<V> type) {
switch((type.valueType.getName().hashCode() >> 8) & 0xf) {
case Stores.BYTE: return (Storage<V>) byteStorage ((StoreType<Byte> ) type);
case Stores.FLOAT: return (Storage<V>) floatStorage ((StoreType<Float> ) type);
case Stores.CHAR: return (Storage<V>) charStorage ((StoreType<Character>) type);
case Stores.SHORT: return (Storage<V>) shortStorage ((StoreType<Short> ) type);
case Stores.LONG: return (Storage<V>) longStorage ((StoreType<Long> ) type);
case Stores.INT: return (Storage<V>) intStorage ((StoreType<Integer> ) type);
case Stores.DOUBLE: return (Storage<V>) doubleStorage ((StoreType<Double> ) type);
case Stores.BOOLEAN: return (Storage<V>) booleanStorage((StoreType<Boolean> ) type);
default: throw new IllegalArgumentException(type.valueType.getName());
}
}
@SuppressWarnings("unchecked")
static <V> PrimitiveStore<V> newStore(StoreType<V> type, int size, V value) {
switch((type.valueType.getName().hashCode() >> 8) & 0xf) {
case Stores.BYTE: return (PrimitiveStore<V>) new ByteStore (size, (StoreType<Byte> ) type, (Byte) value);
case Stores.FLOAT: return (PrimitiveStore<V>) new FloatStore (size, (StoreType<Float> ) type, (Float) value);
case Stores.CHAR: return (PrimitiveStore<V>) new CharacterStore(size, (StoreType<Character>) type, (Character) value);
case Stores.SHORT: return (PrimitiveStore<V>) new ShortStore (size, (StoreType<Short> ) type, (Short) value);
case Stores.LONG: return (PrimitiveStore<V>) new LongStore (size, (StoreType<Long> ) type, (Long) value);
case Stores.INT: return (PrimitiveStore<V>) new IntegerStore (size, (StoreType<Integer> ) type, (Integer) value);
case Stores.DOUBLE: return (PrimitiveStore<V>) new DoubleStore (size, (StoreType<Double> ) type, (Double) value);
case Stores.BOOLEAN: return (PrimitiveStore<V>) new BooleanStore (size, (StoreType<Boolean> ) type, (Boolean) value);
default: throw new IllegalArgumentException(type.valueType.getName());
}
}
@SuppressWarnings("unchecked")
static <V> PrimitiveStore<V> newStore(StoreType<V> type, Object array) {
switch((type.valueType.getName().hashCode() >> 8) & 0xf) {
case Stores.BYTE: return (PrimitiveStore<V>) new ByteStore ((byte []) array, (StoreType<Byte> ) type);
case Stores.FLOAT: return (PrimitiveStore<V>) new FloatStore ((float []) array, (StoreType<Float> ) type);
case Stores.CHAR: return (PrimitiveStore<V>) new CharacterStore((char []) array, (StoreType<Character>) type);
case Stores.SHORT: return (PrimitiveStore<V>) new ShortStore ((short []) array, (StoreType<Short> ) type);
case Stores.LONG: return (PrimitiveStore<V>) new LongStore ((long []) array, (StoreType<Long> ) type);
case Stores.INT: return (PrimitiveStore<V>) new IntegerStore ((int []) array, (StoreType<Integer> ) type);
case Stores.DOUBLE: return (PrimitiveStore<V>) new DoubleStore ((double []) array, (StoreType<Double> ) type);
case Stores.BOOLEAN: return (PrimitiveStore<V>) new BooleanStore ((boolean[]) array, (StoreType<Boolean> ) type);
default: throw new IllegalArgumentException(type.valueType.getName());
}
}
static <V> PrimitiveStore<V> newStore(Store<V> store, int newSize) {
return newStore(store.type(), Stores.toPrimitiveArray(store, newSize, store.type().nullValue));
}
final boolean mutable;
final boolean nullSettable;
protected PrimitiveStore(boolean nullSettable) {
mutable = true;
this.nullSettable = nullSettable;
}
protected PrimitiveStore(boolean mutable, boolean nullSettable) {
this.mutable = mutable;
this.nullSettable = nullSettable;
}
// store
@Override
public int count() {
return size();
}
@Override
public void fill(V value) {
if (!mutable) throw immutableException();
if (value == null) {
clear();
} else {
fillImpl(value);
}
}
@Override
public V get(int index) {
return getImpl(index);
}
@Override
public boolean isNull(int index) {
if (index < 0 || index >= size()) throw new IllegalArgumentException("invalid index");
return false;
}
@Override
public boolean isSettable(Object value) {
if (value == null) return nullSettable;
Class<?> clss = value.getClass();
return clss == primitiveType() || clss == wrapperType();
}
@Override
public V set(int index, V value) {
if (value == null && !nullSettable) StoreType.failNull();
V previous = getImpl(index);
setImpl(index, value);
return previous;
}
@Override
public Store<V> resizedCopy(int newSize) {
if (newSize < 0) throw new IllegalArgumentException();
return resize(newSize);
}
@Override
@SuppressWarnings("unchecked")
public <W extends V> void setStore(int position, Store<W> store) {
int from = 0;
int to = checkSetStore(position, store);
if (store instanceof RangeStore<?>) {
RangeStore<W> range = (RangeStore<W>) store;
store = range.store;
from = range.from;
to = range.to;
}
if (store.getClass() == this.getClass()) {
System.arraycopy(((PrimitiveStore<V>) store).values(), from, values(), position, to - from);
} else {
setStoreImpl(position, store, from, to);
}
}
// for extension
abstract protected Class<?> primitiveType();
abstract protected Class<?> wrapperType();
abstract protected Object values();
abstract protected V getImpl(int index);
abstract protected void setImpl(int index, V value);
abstract protected void fillImpl(V value);
abstract protected PrimitiveStore<V> duplicate(boolean copy, boolean mutable);
abstract protected PrimitiveStore<V> resize(int newSize);
// mutability
@Override
public boolean isMutable() {
return mutable;
}
@Override
public Store<V> mutableCopy() {
return duplicate(true, true);
}
@Override
public Store<V> immutableCopy() {
return duplicate(true, false);
}
// helper methods
void checkSize(int size) {
if (!nullSettable && size > 0) throw new IllegalArgumentException("no null value with which to populate store");
}
// inner classes
final static class ByteStore extends PrimitiveStore<Byte> {
private final byte[] values;
private final byte nullValue;
ByteStore(int size, StoreType<Byte> type, Byte initialValue) {
super(type.nullSettable);
if (initialValue == null) checkSize(size);
values = new byte[size];
nullValue = nullSettable ? type.nullValue : (byte) 0;
if (initialValue == null) initialValue = nullValue;
if (initialValue != (byte) 0) Arrays.fill(values, initialValue);
}
ByteStore(byte[] values, StoreType<Byte> type) {
super(type.nullSettable);
this.values = values;
this.nullValue = nullSettable ? type.nullValue : (byte) 0;
}
private ByteStore(byte[] values, byte nullValue, boolean nullSettable) {
super(nullSettable);
this.values = values;
this.nullValue = nullValue;
}
private ByteStore(byte[] values, byte nullValue, boolean mutable, boolean nullSettable) {
super(mutable, nullSettable);
this.values = values;
this.nullValue = nullValue;
}
@Override
public int size() {
return values.length;
}
@Override
protected Class<?> primitiveType() {
return byte.class;
}
@Override
protected Class<?> wrapperType() {
return Byte.class;
}
@Override
protected Object values() {
return values;
}
@Override
protected Byte getImpl(int index) {
return values[index];
}
@Override
protected void setImpl(int index, Byte value) {
values[index] = value == null ? nullValue : value.byteValue();
}
@Override
protected void fillImpl(Byte value) {
Arrays.fill(values, value == null ? nullValue : value.byteValue());
}
@Override
protected ByteStore duplicate(boolean copy, boolean mutable) {
return new ByteStore(copy ? values.clone() : values, nullValue, mutable, nullSettable);
}
@Override
protected ByteStore resize(int newSize) {
int oldSize = values.length;
boolean growing = newSize > oldSize;
if (growing && !nullSettable) failGrowCopy();
byte[] newValues = Arrays.copyOf(values, newSize);
if (growing && nullValue != (byte) 0) Arrays.fill(newValues, oldSize, newSize, nullValue);
return new ByteStore(newValues, nullValue, nullSettable);
}
@Override
public StoreType<Byte> type() {
return newType(byte.class, nullSettable, nullValue);
}
}
final static class FloatStore extends PrimitiveStore<Float> {
private final float[] values;
private final float nullValue;
FloatStore(int size, StoreType<Float> type, Float initialValue) {
super(type.nullSettable);
if (initialValue == null) checkSize(size);
values = new float[size];
nullValue = nullSettable ? type.nullValue : 0.0f;
if (initialValue == null) initialValue = nullValue;
if (initialValue != (float) 0) Arrays.fill(values, initialValue);
}
FloatStore(float[] values, StoreType<Float> type) {
super(type.nullSettable);
this.values = values;
this.nullValue = nullSettable ? type.nullValue : 0.0f;
}
private FloatStore(float[] values, float nullValue, boolean nullSettable) {
super(nullSettable);
this.values = values;
this.nullValue = nullValue;
}
private FloatStore(float[] values, float nullValue, boolean mutable, boolean nullSettable) {
super(mutable, nullSettable);
this.values = values;
this.nullValue = nullValue;
}
@Override
public int size() {
return values.length;
}
@Override
protected Class<?> primitiveType() {
return float.class;
}
@Override
protected Class<?> wrapperType() {
return Float.class;
}
@Override
protected Object values() {
return values;
}
@Override
protected Float getImpl(int index) {
return values[index];
}
@Override
protected void setImpl(int index, Float value) {
values[index] = value == null ? nullValue : value.floatValue();
}
@Override
protected void fillImpl(Float value) {
Arrays.fill(values, value == null ? nullValue : value.floatValue());
}
@Override
protected FloatStore duplicate(boolean copy, boolean mutable) {
return new FloatStore(copy ? values.clone() : values, nullValue, mutable, nullSettable);
}
@Override
protected FloatStore resize(int newSize) {
int oldSize = values.length;
boolean growing = newSize > oldSize;
if (growing && !nullSettable) failGrowCopy();
float[] newValues = Arrays.copyOf(values, newSize);
if (growing && nullValue != 0.0f) Arrays.fill(newValues, oldSize, newSize, nullValue);
return new FloatStore(newValues, nullValue, nullSettable);
}
@Override
public StoreType<Float> type() {
return newType(float.class, nullSettable, nullValue);
}
}
final static class CharacterStore extends PrimitiveStore<Character> {
private final char[] values;
private final char nullValue;
CharacterStore(int size, StoreType<Character> type, Character initialValue) {
super(type.nullSettable);
if (initialValue == null) checkSize(size);
values = new char[size];
nullValue = nullSettable ? type.nullValue : '\0';
if (initialValue == null) initialValue = nullValue;
if (initialValue != (char) 0) Arrays.fill(values, initialValue);
}
CharacterStore(char[] values, StoreType<Character> type) {
super(type.nullSettable);
this.values = values;
this.nullValue = nullSettable ? type.nullValue : '\0';
}
private CharacterStore(char[] values, char nullValue, boolean nullSettable) {
super(nullSettable);
this.values = values;
this.nullValue = nullValue;
}
private CharacterStore(char[] values, char nullValue, boolean mutable, boolean nullSettable) {
super(mutable, nullSettable);
this.values = values;
this.nullValue = nullValue;
}
@Override
public int size() {
return values.length;
}
@Override
protected Class<?> primitiveType() {
return char.class;
}
@Override
protected Class<?> wrapperType() {
return Character.class;
}
@Override
protected Object values() {
return values;
}
@Override
protected Character getImpl(int index) {
return values[index];
}
@Override
protected void setImpl(int index, Character value) {
values[index] = value == null ? nullValue : value.charValue();
}
@Override
protected void fillImpl(Character value) {
Arrays.fill(values, value == null ? nullValue : value.charValue());
}
@Override
protected CharacterStore duplicate(boolean copy, boolean mutable) {
return new CharacterStore(copy ? values.clone() : values, nullValue, mutable, nullSettable);
}
@Override
protected CharacterStore resize(int newSize) {
int oldSize = values.length;
boolean growing = newSize > oldSize;
if (growing && !nullSettable) failGrowCopy();
char[] newValues = Arrays.copyOf(values, newSize);
if (growing && nullValue != '\0') Arrays.fill(newValues, oldSize, newSize, nullValue);
return new CharacterStore(newValues, nullValue, nullSettable);
}
@Override
public StoreType<Character> type() {
return newType(char.class, nullSettable, nullValue);
}
}
final static class ShortStore extends PrimitiveStore<Short> {
private final short[] values;
private final short nullValue;
ShortStore(int size, StoreType<Short> type, Short initialValue) {
super(type.nullSettable);
if (initialValue == null) checkSize(size);
values = new short[size];
nullValue = nullSettable ? type.nullValue : (short) 0;
if (initialValue == null) initialValue = nullValue;
if (initialValue != (short) 0) Arrays.fill(values, initialValue);
}
ShortStore(short[] values, StoreType<Short> type) {
super(type.nullSettable);
this.values = values;
this.nullValue = nullSettable ? type.nullValue : (short) 0;
}
private ShortStore(short[] values, short nullValue, boolean nullSettable) {
super(nullSettable);
this.values = values;
this.nullValue = nullValue;
}
private ShortStore(short[] values, short nullValue, boolean mutable, boolean nullSettable) {
super(mutable, nullSettable);
this.values = values;
this.nullValue = nullValue;
}
@Override
public int size() {
return values.length;
}
@Override
protected Class<?> primitiveType() {
return short.class;
}
@Override
protected Class<?> wrapperType() {
return Short.class;
}
@Override
protected Object values() {
return values;
}
@Override
protected Short getImpl(int index) {
return values[index];
}
@Override
protected void setImpl(int index, Short value) {
values[index] = value == null ? nullValue : value.shortValue();
}
@Override
protected void fillImpl(Short value) {
Arrays.fill(values, value == null ? nullValue : value.shortValue());
}
@Override
protected ShortStore duplicate(boolean copy, boolean mutable) {
return new ShortStore(copy ? values.clone() : values, nullValue, mutable, nullSettable);
}
@Override
protected ShortStore resize(int newSize) {
int oldSize = values.length;
boolean growing = newSize > oldSize;
if (growing && !nullSettable) failGrowCopy();
short[] newValues = Arrays.copyOf(values, newSize);
if (growing && nullValue != (short) 0) Arrays.fill(newValues, oldSize, newSize, nullValue);
return new ShortStore(newValues, nullValue, nullSettable);
}
@Override
public StoreType<Short> type() {
return newType(short.class, nullSettable, nullValue);
}
}
final static class LongStore extends PrimitiveStore<Long> {
private final long[] values;
private final long nullValue;
LongStore(int size, StoreType<Long> type, Long initialValue) {
super(type.nullSettable);
if (initialValue == null) checkSize(size);
values = new long[size];
nullValue = nullSettable ? type.nullValue : 0L;
if (initialValue == null) initialValue = nullValue;
if (initialValue != (long) 0) Arrays.fill(values, initialValue);
}
LongStore(long[] values, StoreType<Long> type) {
super(type.nullSettable);
this.values = values;
this.nullValue = nullSettable ? type.nullValue : 0L;
}
private LongStore(long[] values, long nullValue, boolean nullSettable) {
super(nullSettable);
this.values = values;
this.nullValue = nullValue;
}
private LongStore(long[] values, long nullValue, boolean mutable, boolean nullSettable) {
super(mutable, nullSettable);
this.values = values;
this.nullValue = nullValue;
}
@Override
public int size() {
return values.length;
}
@Override
protected Class<?> primitiveType() {
return long.class;
}
@Override
protected Class<?> wrapperType() {
return Long.class;
}
@Override
protected Object values() {
return values;
}
@Override
protected Long getImpl(int index) {
return values[index];
}
@Override
protected void setImpl(int index, Long value) {
values[index] = value == null ? nullValue : value.longValue();
}
@Override
protected void fillImpl(Long value) {
Arrays.fill(values, value == null ? nullValue : value.longValue());
}
@Override
protected LongStore duplicate(boolean copy, boolean mutable) {
return new LongStore(copy ? values.clone() : values, nullValue, mutable, nullSettable);
}
@Override
protected LongStore resize(int newSize) {
int oldSize = values.length;
boolean growing = newSize > oldSize;
if (growing && !nullSettable) failGrowCopy();
long[] newValues = Arrays.copyOf(values, newSize);
if (growing && nullValue != 0L) Arrays.fill(newValues, oldSize, newSize, nullValue);
return new LongStore(newValues, nullValue, nullSettable);
}
@Override
public StoreType<Long> type() {
return newType(long.class, nullSettable, nullValue);
}
@Override
public Spliterator.OfLong spliterator() {
return Spliterators.spliterator(values, Spliterator.ORDERED | Spliterator.NONNULL);
}
}
final static class IntegerStore extends PrimitiveStore<Integer> {
private final int[] values;
private final int nullValue;
IntegerStore(int size, StoreType<Integer> type, Integer initialValue) {
super(type.nullSettable);
if (initialValue == null) checkSize(size);
values = new int[size];
nullValue = nullSettable ? type.nullValue : 0;
if (initialValue == null) initialValue = nullValue;
if (initialValue != (int) 0) Arrays.fill(values, initialValue);
}
IntegerStore(int[] values, StoreType<Integer> type) {
super(type.nullSettable);
this.values = values;
this.nullValue = nullSettable ? type.nullValue : 0;
}
private IntegerStore(int[] values, int nullValue, boolean nullSettable) {
super(nullSettable);
this.values = values;
this.nullValue = nullValue;
}
private IntegerStore(int[] values, int nullValue, boolean mutable, boolean nullSettable) {
super(mutable, nullSettable);
this.values = values;
this.nullValue = nullValue;
}
@Override
public int size() {
return values.length;
}
@Override
protected Class<?> primitiveType() {
return int.class;
}
@Override
protected Class<?> wrapperType() {
return Integer.class;
}
@Override
protected Object values() {
return values;
}
@Override
protected Integer getImpl(int index) {
return values[index];
}
@Override
protected void setImpl(int index, Integer value) {
values[index] = value == null ? nullValue : value.intValue();
}
@Override
protected void fillImpl(Integer value) {
Arrays.fill(values, value == null ? nullValue : value.intValue());
}
@Override
protected IntegerStore duplicate(boolean copy, boolean mutable) {
return new IntegerStore(copy ? values.clone() : values, nullValue, mutable, nullSettable);
}
@Override
protected IntegerStore resize(int newSize) {
int oldSize = values.length;
boolean growing = newSize > oldSize;
if (growing && !nullSettable) failGrowCopy();
int[] newValues = Arrays.copyOf(values, newSize);
if (growing && nullValue != 0) Arrays.fill(newValues, oldSize, newSize, nullValue);
return new IntegerStore(newValues, nullValue, nullSettable);
}
@Override
public StoreType<Integer> type() {
return newType(int.class, nullSettable, nullValue);
}
@Override
public Spliterator.OfInt spliterator() {
return Spliterators.spliterator(values, Spliterator.ORDERED | Spliterator.NONNULL);
}
}
final static class DoubleStore extends PrimitiveStore<Double> {
private final double[] values;
private final double nullValue;
DoubleStore(int size, StoreType<Double> type, Double initialValue) {
super(type.nullSettable);
if (initialValue == null) checkSize(size);
values = new double[size];
nullValue = nullSettable ? type.nullValue : 0.0;
if (initialValue == null) initialValue = nullValue;
if (initialValue != (double) 0) Arrays.fill(values, initialValue);
}
DoubleStore(double[] values, StoreType<Double> type) {
super(type.nullSettable);
this.values = values;
this.nullValue = nullSettable ? type.nullValue : 0.0;
}
private DoubleStore(double[] values, double nullValue, boolean nullSettable) {
super(nullSettable);
this.values = values;
this.nullValue = nullValue;
}
private DoubleStore(double[] values, double nullValue, boolean mutable, boolean nullSettable) {
super(mutable, nullSettable);
this.values = values;
this.nullValue = nullValue;
}
@Override
public int size() {
return values.length;
}
@Override
protected Class<?> primitiveType() {
return double.class;
}
@Override
protected Class<?> wrapperType() {
return Double.class;
}
@Override
protected Object values() {
return values;
}
@Override
protected Double getImpl(int index) {
return values[index];
}
@Override
protected void setImpl(int index, Double value) {
values[index] = value == null ? nullValue : value.doubleValue();
}
@Override
protected void fillImpl(Double value) {
Arrays.fill(values, value == null ? nullValue : value.doubleValue());
}
@Override
protected DoubleStore duplicate(boolean copy, boolean mutable) {
return new DoubleStore(copy ? values.clone() : values, nullValue, mutable, nullSettable);
}
@Override
protected DoubleStore resize(int newSize) {
int oldSize = values.length;
boolean growing = newSize > oldSize;
if (growing && !nullSettable) failGrowCopy();
double[] newValues = Arrays.copyOf(values, newSize);
if (growing && nullValue != 0L) Arrays.fill(newValues, oldSize, newSize, nullValue);
return new DoubleStore(newValues, nullValue, nullSettable);
}
@Override
public StoreType<Double> type() {
return newType(double.class, nullSettable, nullValue);
}
@Override
public Spliterator.OfDouble spliterator() {
return Spliterators.spliterator(values, Spliterator.ORDERED | Spliterator.NONNULL);
}
}
final static class BooleanStore extends PrimitiveStore<Boolean> {
private final boolean[] values;
private final boolean nullValue;
BooleanStore(int size, StoreType<Boolean> type, Boolean initialValue) {
super(type.nullSettable);
if (initialValue == null) checkSize(size);
values = new boolean[size];
nullValue = nullSettable && type.nullValue;
if (initialValue == null) initialValue = nullValue;
if (initialValue) Arrays.fill(values, initialValue);
}
BooleanStore(boolean[] values, StoreType<Boolean> type) {
super(type.nullSettable);
this.values = values;
this.nullValue = nullSettable && type.nullValue;
}
private BooleanStore(boolean[] values, boolean nullValue, boolean nullSettable) {
super(nullSettable);
this.values = values;
this.nullValue = nullValue;
}
private BooleanStore(boolean[] values, boolean nullValue, boolean mutable, boolean nullSettable) {
super(mutable, nullSettable);
this.values = values;
this.nullValue = nullValue;
}
@Override
public int size() {
return values.length;
}
@Override
protected Class<?> primitiveType() {
return boolean.class;
}
@Override
protected Class<?> wrapperType() {
return Boolean.class;
}
@Override
protected Object values() {
return values;
}
@Override
protected Boolean getImpl(int index) {
return values[index];
}
@Override
protected void setImpl(int index, Boolean value) {
values[index] = value == null ? nullValue : value.booleanValue();
}
@Override
protected void fillImpl(Boolean value) {
Arrays.fill(values, value == null ? nullValue : value.booleanValue());
}
@Override
protected BooleanStore duplicate(boolean copy, boolean mutable) {
return new BooleanStore(copy ? values.clone() : values, nullValue, mutable, nullSettable);
}
@Override
protected BooleanStore resize(int newSize) {
int oldSize = values.length;
boolean growing = newSize > oldSize;
if (growing && !nullSettable) failGrowCopy();
boolean[] newValues = Arrays.copyOf(values, newSize);
if (growing && nullValue) Arrays.fill(newValues, oldSize, newSize, nullValue);
return new BooleanStore(newValues, nullValue, nullSettable);
}
@Override
public StoreType<Boolean> type() {
return newType(boolean.class, nullSettable, nullValue);
}
}
}
| src/main/java/com/tomgibara/storage/PrimitiveStore.java | /*
* Copyright 2015 Tom Gibara
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.tomgibara.storage;
import static com.tomgibara.storage.Stores.immutableException;
import java.util.Arrays;
import java.util.Spliterator;
import java.util.Spliterators;
abstract class PrimitiveStore<V> extends AbstractStore<V> {
private static void failGrowCopy() {
throw new IllegalArgumentException("cannot increase size, null not settable");
}
private static final <T> StoreType<T> newType(Class<T> clss, boolean nullSettable, T nullValue) {
//TODO can we avoid intermediate object creation?
StoreType<T> type = StoreType.of(clss);
return nullSettable ? type.settingNullToValue(nullValue) : type.settingNullDisallowed();
}
private static abstract class PrimitiveStorage<P> implements Storage<P> {
final StoreType<P> type;
PrimitiveStorage(StoreType<P> type) { this.type = type; }
@Override final public StoreType<P> type() { return type; }
}
private static final Storage<Byte> byteStorage(StoreType<Byte> type) {
return new PrimitiveStorage<Byte>(type) {
@Override public PrimitiveStore<Byte> newStore(int size, Byte initialValue) { return new ByteStore(size, type, initialValue); }
};
};
private static final Storage<Float> floatStorage(StoreType<Float> type) {
return new PrimitiveStorage<Float>(type) {
@Override public PrimitiveStore<Float> newStore(int size, Float initialValue) { return new FloatStore(size, type, initialValue); }
};
};
private static final Storage<Character> charStorage(StoreType<Character> type) {
return new PrimitiveStorage<Character>(type) {
@Override public PrimitiveStore<Character> newStore(int size, Character initialValue) { return new CharacterStore(size, type, initialValue); }
};
};
private static final Storage<Short> shortStorage(StoreType<Short> type) {
return new PrimitiveStorage<Short>(type) {
@Override public PrimitiveStore<Short> newStore(int size, Short initialValue) { return new ShortStore(size, type, initialValue); }
};
};
private static final Storage<Long> longStorage(StoreType<Long> type) {
return new PrimitiveStorage<Long>(type) {
@Override public PrimitiveStore<Long> newStore(int size, Long initialValue) { return new LongStore(size, type, initialValue); }
};
};
private static final Storage<Integer> intStorage(StoreType<Integer> type) {
return new PrimitiveStorage<Integer>(type) {
@Override public PrimitiveStore<Integer> newStore(int size, Integer initialValue) { return new IntegerStore(size, type, initialValue); }
};
};
private static final Storage<Double> doubleStorage(StoreType<Double> type) {
return new PrimitiveStorage<Double>(type) {
@Override public PrimitiveStore<Double> newStore(int size, Double initialValue) { return new DoubleStore(size, type, initialValue); }
};
};
private static final Storage<Boolean> booleanStorage(StoreType<Boolean> type) {
return new PrimitiveStorage<Boolean>(type) {
@Override public PrimitiveStore<Boolean> newStore(int size, Boolean initialValue) { return new BooleanStore(size, type, initialValue); }
};
};
@SuppressWarnings("unchecked")
static <V> Storage<V> newStorage(StoreType<V> type) {
switch((type.valueType.getName().hashCode() >> 8) & 0xf) {
case Stores.BYTE: return (Storage<V>) byteStorage ((StoreType<Byte> ) type);
case Stores.FLOAT: return (Storage<V>) floatStorage ((StoreType<Float> ) type);
case Stores.CHAR: return (Storage<V>) charStorage ((StoreType<Character>) type);
case Stores.SHORT: return (Storage<V>) shortStorage ((StoreType<Short> ) type);
case Stores.LONG: return (Storage<V>) longStorage ((StoreType<Long> ) type);
case Stores.INT: return (Storage<V>) intStorage ((StoreType<Integer> ) type);
case Stores.DOUBLE: return (Storage<V>) doubleStorage ((StoreType<Double> ) type);
case Stores.BOOLEAN: return (Storage<V>) booleanStorage((StoreType<Boolean> ) type);
default: throw new IllegalArgumentException(type.valueType.getName());
}
}
@SuppressWarnings("unchecked")
static <V> PrimitiveStore<V> newStore(StoreType<V> type, int size, V value) {
switch((type.valueType.getName().hashCode() >> 8) & 0xf) {
case Stores.BYTE: return (PrimitiveStore<V>) new ByteStore (size, (StoreType<Byte> ) type, (Byte) value);
case Stores.FLOAT: return (PrimitiveStore<V>) new FloatStore (size, (StoreType<Float> ) type, (Float) value);
case Stores.CHAR: return (PrimitiveStore<V>) new CharacterStore(size, (StoreType<Character>) type, (Character) value);
case Stores.SHORT: return (PrimitiveStore<V>) new ShortStore (size, (StoreType<Short> ) type, (Short) value);
case Stores.LONG: return (PrimitiveStore<V>) new LongStore (size, (StoreType<Long> ) type, (Long) value);
case Stores.INT: return (PrimitiveStore<V>) new IntegerStore (size, (StoreType<Integer> ) type, (Integer) value);
case Stores.DOUBLE: return (PrimitiveStore<V>) new DoubleStore (size, (StoreType<Double> ) type, (Double) value);
case Stores.BOOLEAN: return (PrimitiveStore<V>) new BooleanStore (size, (StoreType<Boolean> ) type, (Boolean) value);
default: throw new IllegalArgumentException(type.valueType.getName());
}
}
@SuppressWarnings("unchecked")
static <V> PrimitiveStore<V> newStore(StoreType<V> type, Object array) {
switch((type.valueType.getName().hashCode() >> 8) & 0xf) {
case Stores.BYTE: return (PrimitiveStore<V>) new ByteStore ((byte []) array, (StoreType<Byte> ) type);
case Stores.FLOAT: return (PrimitiveStore<V>) new FloatStore ((float []) array, (StoreType<Float> ) type);
case Stores.CHAR: return (PrimitiveStore<V>) new CharacterStore((char []) array, (StoreType<Character>) type);
case Stores.SHORT: return (PrimitiveStore<V>) new ShortStore ((short []) array, (StoreType<Short> ) type);
case Stores.LONG: return (PrimitiveStore<V>) new LongStore ((long []) array, (StoreType<Long> ) type);
case Stores.INT: return (PrimitiveStore<V>) new IntegerStore ((int []) array, (StoreType<Integer> ) type);
case Stores.DOUBLE: return (PrimitiveStore<V>) new DoubleStore ((double []) array, (StoreType<Double> ) type);
case Stores.BOOLEAN: return (PrimitiveStore<V>) new BooleanStore ((boolean[]) array, (StoreType<Boolean> ) type);
default: throw new IllegalArgumentException(type.valueType.getName());
}
}
static <V> PrimitiveStore<V> newStore(Store<V> store, int newSize) {
return newStore(store.type(), Stores.toPrimitiveArray(store, newSize, store.type().nullValue));
}
final boolean mutable;
final boolean nullSettable;
protected PrimitiveStore(boolean nullSettable) {
mutable = true;
this.nullSettable = nullSettable;
}
protected PrimitiveStore(boolean mutable, boolean nullSettable) {
this.mutable = mutable;
this.nullSettable = nullSettable;
}
// store
@Override
public int count() {
return size();
}
@Override
public void fill(V value) {
if (!mutable) throw immutableException();
if (value == null) {
clear();
} else {
fillImpl(value);
}
}
@Override
public V get(int index) {
return getImpl(index);
}
@Override
public boolean isNull(int index) {
if (index < 0 || index >= size()) throw new IllegalArgumentException("invalid index");
return false;
}
@Override
public boolean isSettable(Object value) {
if (value == null) return nullSettable;
Class<?> clss = value.getClass();
return clss == primitiveType() || clss == wrapperType();
}
@Override
public V set(int index, V value) {
if (value == null && !nullSettable) StoreType.failNull();
V previous = getImpl(index);
setImpl(index, value);
return previous;
}
@Override
public Store<V> resizedCopy(int newSize) {
if (newSize < 0) throw new IllegalArgumentException();
return resize(newSize);
}
@Override
@SuppressWarnings("unchecked")
public <W extends V> void setStore(int position, Store<W> store) {
int from = 0;
int to = checkSetStore(position, store);
if (store instanceof RangeStore<?>) {
RangeStore<W> range = (RangeStore<W>) store;
store = range.store;
from = range.from;
to = range.to;
}
if (store.getClass() == this.getClass()) {
System.arraycopy(((PrimitiveStore<V>) store).values(), from, values(), position, to - from);
} else {
setStoreImpl(position, store, from, to);
}
}
// for extension
abstract protected Class<?> primitiveType();
abstract protected Class<?> wrapperType();
abstract protected Object values();
abstract protected V getImpl(int index);
abstract protected void setImpl(int index, V value);
abstract protected void fillImpl(V value);
abstract protected PrimitiveStore<V> duplicate(boolean copy, boolean mutable);
abstract protected PrimitiveStore<V> resize(int newSize);
// mutability
@Override
public boolean isMutable() {
return mutable;
}
@Override
public Store<V> mutableCopy() {
return duplicate(true, true);
}
@Override
public Store<V> immutableCopy() {
return duplicate(true, false);
}
// helper methods
void checkSize(int size) {
if (!nullSettable && size > 0) throw new IllegalArgumentException("no null value with which to populate store");
}
// inner classes
final static class ByteStore extends PrimitiveStore<Byte> {
private final byte[] values;
private final byte nullValue;
ByteStore(int size, StoreType<Byte> type, Byte initialValue) {
super(type.nullSettable);
if (initialValue == null) checkSize(size);
values = new byte[size];
nullValue = nullSettable ? type.nullValue : (byte) 0;
if (initialValue == null) initialValue = nullValue;
if (nullValue != (byte) 0) Arrays.fill(values, initialValue);
}
ByteStore(byte[] values, StoreType<Byte> type) {
super(type.nullSettable);
this.values = values;
this.nullValue = nullSettable ? type.nullValue : (byte) 0;
}
private ByteStore(byte[] values, byte nullValue, boolean nullSettable) {
super(nullSettable);
this.values = values;
this.nullValue = nullValue;
}
private ByteStore(byte[] values, byte nullValue, boolean mutable, boolean nullSettable) {
super(mutable, nullSettable);
this.values = values;
this.nullValue = nullValue;
}
@Override
public int size() {
return values.length;
}
@Override
protected Class<?> primitiveType() {
return byte.class;
}
@Override
protected Class<?> wrapperType() {
return Byte.class;
}
@Override
protected Object values() {
return values;
}
@Override
protected Byte getImpl(int index) {
return values[index];
}
@Override
protected void setImpl(int index, Byte value) {
values[index] = value == null ? nullValue : value.byteValue();
}
@Override
protected void fillImpl(Byte value) {
Arrays.fill(values, value == null ? nullValue : value.byteValue());
}
@Override
protected ByteStore duplicate(boolean copy, boolean mutable) {
return new ByteStore(copy ? values.clone() : values, nullValue, mutable, nullSettable);
}
@Override
protected ByteStore resize(int newSize) {
int oldSize = values.length;
boolean growing = newSize > oldSize;
if (growing && !nullSettable) failGrowCopy();
byte[] newValues = Arrays.copyOf(values, newSize);
if (growing && nullValue != (byte) 0) Arrays.fill(newValues, oldSize, newSize, nullValue);
return new ByteStore(newValues, nullValue, nullSettable);
}
@Override
public StoreType<Byte> type() {
return newType(byte.class, nullSettable, nullValue);
}
}
final static class FloatStore extends PrimitiveStore<Float> {
private final float[] values;
private final float nullValue;
FloatStore(int size, StoreType<Float> type, Float initialValue) {
super(type.nullSettable);
if (initialValue == null) checkSize(size);
values = new float[size];
nullValue = nullSettable ? type.nullValue : 0.0f;
if (initialValue == null) initialValue = nullValue;
if (nullValue != (float) 0) Arrays.fill(values, nullValue);
}
FloatStore(float[] values, StoreType<Float> type) {
super(type.nullSettable);
this.values = values;
this.nullValue = nullSettable ? type.nullValue : 0.0f;
}
private FloatStore(float[] values, float nullValue, boolean nullSettable) {
super(nullSettable);
this.values = values;
this.nullValue = nullValue;
}
private FloatStore(float[] values, float nullValue, boolean mutable, boolean nullSettable) {
super(mutable, nullSettable);
this.values = values;
this.nullValue = nullValue;
}
@Override
public int size() {
return values.length;
}
@Override
protected Class<?> primitiveType() {
return float.class;
}
@Override
protected Class<?> wrapperType() {
return Float.class;
}
@Override
protected Object values() {
return values;
}
@Override
protected Float getImpl(int index) {
return values[index];
}
@Override
protected void setImpl(int index, Float value) {
values[index] = value == null ? nullValue : value.floatValue();
}
@Override
protected void fillImpl(Float value) {
Arrays.fill(values, value == null ? nullValue : value.floatValue());
}
@Override
protected FloatStore duplicate(boolean copy, boolean mutable) {
return new FloatStore(copy ? values.clone() : values, nullValue, mutable, nullSettable);
}
@Override
protected FloatStore resize(int newSize) {
int oldSize = values.length;
boolean growing = newSize > oldSize;
if (growing && !nullSettable) failGrowCopy();
float[] newValues = Arrays.copyOf(values, newSize);
if (growing && nullValue != 0.0f) Arrays.fill(newValues, oldSize, newSize, nullValue);
return new FloatStore(newValues, nullValue, nullSettable);
}
@Override
public StoreType<Float> type() {
return newType(float.class, nullSettable, nullValue);
}
}
final static class CharacterStore extends PrimitiveStore<Character> {
private final char[] values;
private final char nullValue;
CharacterStore(int size, StoreType<Character> type, Character initialValue) {
super(type.nullSettable);
if (initialValue == null) checkSize(size);
values = new char[size];
nullValue = nullSettable ? type.nullValue : '\0';
if (initialValue == null) initialValue = nullValue;
if (nullValue != (char) 0) Arrays.fill(values, nullValue);
}
CharacterStore(char[] values, StoreType<Character> type) {
super(type.nullSettable);
this.values = values;
this.nullValue = nullSettable ? type.nullValue : '\0';
}
private CharacterStore(char[] values, char nullValue, boolean nullSettable) {
super(nullSettable);
this.values = values;
this.nullValue = nullValue;
}
private CharacterStore(char[] values, char nullValue, boolean mutable, boolean nullSettable) {
super(mutable, nullSettable);
this.values = values;
this.nullValue = nullValue;
}
@Override
public int size() {
return values.length;
}
@Override
protected Class<?> primitiveType() {
return char.class;
}
@Override
protected Class<?> wrapperType() {
return Character.class;
}
@Override
protected Object values() {
return values;
}
@Override
protected Character getImpl(int index) {
return values[index];
}
@Override
protected void setImpl(int index, Character value) {
values[index] = value == null ? nullValue : value.charValue();
}
@Override
protected void fillImpl(Character value) {
Arrays.fill(values, value == null ? nullValue : value.charValue());
}
@Override
protected CharacterStore duplicate(boolean copy, boolean mutable) {
return new CharacterStore(copy ? values.clone() : values, nullValue, mutable, nullSettable);
}
@Override
protected CharacterStore resize(int newSize) {
int oldSize = values.length;
boolean growing = newSize > oldSize;
if (growing && !nullSettable) failGrowCopy();
char[] newValues = Arrays.copyOf(values, newSize);
if (growing && nullValue != '\0') Arrays.fill(newValues, oldSize, newSize, nullValue);
return new CharacterStore(newValues, nullValue, nullSettable);
}
@Override
public StoreType<Character> type() {
return newType(char.class, nullSettable, nullValue);
}
}
final static class ShortStore extends PrimitiveStore<Short> {
private final short[] values;
private final short nullValue;
ShortStore(int size, StoreType<Short> type, Short initialValue) {
super(type.nullSettable);
if (initialValue == null) checkSize(size);
values = new short[size];
nullValue = nullSettable ? type.nullValue : (short) 0;
if (initialValue == null) initialValue = nullValue;
if (nullValue != (short) 0) Arrays.fill(values, nullValue);
}
ShortStore(short[] values, StoreType<Short> type) {
super(type.nullSettable);
this.values = values;
this.nullValue = nullSettable ? type.nullValue : (short) 0;
}
private ShortStore(short[] values, short nullValue, boolean nullSettable) {
super(nullSettable);
this.values = values;
this.nullValue = nullValue;
}
private ShortStore(short[] values, short nullValue, boolean mutable, boolean nullSettable) {
super(mutable, nullSettable);
this.values = values;
this.nullValue = nullValue;
}
@Override
public int size() {
return values.length;
}
@Override
protected Class<?> primitiveType() {
return short.class;
}
@Override
protected Class<?> wrapperType() {
return Short.class;
}
@Override
protected Object values() {
return values;
}
@Override
protected Short getImpl(int index) {
return values[index];
}
@Override
protected void setImpl(int index, Short value) {
values[index] = value == null ? nullValue : value.shortValue();
}
@Override
protected void fillImpl(Short value) {
Arrays.fill(values, value == null ? nullValue : value.shortValue());
}
@Override
protected ShortStore duplicate(boolean copy, boolean mutable) {
return new ShortStore(copy ? values.clone() : values, nullValue, mutable, nullSettable);
}
@Override
protected ShortStore resize(int newSize) {
int oldSize = values.length;
boolean growing = newSize > oldSize;
if (growing && !nullSettable) failGrowCopy();
short[] newValues = Arrays.copyOf(values, newSize);
if (growing && nullValue != (short) 0) Arrays.fill(newValues, oldSize, newSize, nullValue);
return new ShortStore(newValues, nullValue, nullSettable);
}
@Override
public StoreType<Short> type() {
return newType(short.class, nullSettable, nullValue);
}
}
final static class LongStore extends PrimitiveStore<Long> {
private final long[] values;
private final long nullValue;
LongStore(int size, StoreType<Long> type, Long initialValue) {
super(type.nullSettable);
if (initialValue == null) checkSize(size);
values = new long[size];
nullValue = nullSettable ? type.nullValue : 0L;
if (initialValue == null) initialValue = nullValue;
if (nullValue != (long) 0) Arrays.fill(values, nullValue);
}
LongStore(long[] values, StoreType<Long> type) {
super(type.nullSettable);
this.values = values;
this.nullValue = nullSettable ? type.nullValue : 0L;
}
private LongStore(long[] values, long nullValue, boolean nullSettable) {
super(nullSettable);
this.values = values;
this.nullValue = nullValue;
}
private LongStore(long[] values, long nullValue, boolean mutable, boolean nullSettable) {
super(mutable, nullSettable);
this.values = values;
this.nullValue = nullValue;
}
@Override
public int size() {
return values.length;
}
@Override
protected Class<?> primitiveType() {
return long.class;
}
@Override
protected Class<?> wrapperType() {
return Long.class;
}
@Override
protected Object values() {
return values;
}
@Override
protected Long getImpl(int index) {
return values[index];
}
@Override
protected void setImpl(int index, Long value) {
values[index] = value == null ? nullValue : value.longValue();
}
@Override
protected void fillImpl(Long value) {
Arrays.fill(values, value == null ? nullValue : value.longValue());
}
@Override
protected LongStore duplicate(boolean copy, boolean mutable) {
return new LongStore(copy ? values.clone() : values, nullValue, mutable, nullSettable);
}
@Override
protected LongStore resize(int newSize) {
int oldSize = values.length;
boolean growing = newSize > oldSize;
if (growing && !nullSettable) failGrowCopy();
long[] newValues = Arrays.copyOf(values, newSize);
if (growing && nullValue != 0L) Arrays.fill(newValues, oldSize, newSize, nullValue);
return new LongStore(newValues, nullValue, nullSettable);
}
@Override
public StoreType<Long> type() {
return newType(long.class, nullSettable, nullValue);
}
@Override
public Spliterator.OfLong spliterator() {
return Spliterators.spliterator(values, Spliterator.ORDERED | Spliterator.NONNULL);
}
}
final static class IntegerStore extends PrimitiveStore<Integer> {
private final int[] values;
private final int nullValue;
IntegerStore(int size, StoreType<Integer> type, Integer initialValue) {
super(type.nullSettable);
if (initialValue == null) checkSize(size);
values = new int[size];
nullValue = nullSettable ? type.nullValue : 0;
if (initialValue == null) initialValue = nullValue;
if (nullValue != (int) 0) Arrays.fill(values, nullValue);
}
IntegerStore(int[] values, StoreType<Integer> type) {
super(type.nullSettable);
this.values = values;
this.nullValue = nullSettable ? type.nullValue : 0;
}
private IntegerStore(int[] values, int nullValue, boolean nullSettable) {
super(nullSettable);
this.values = values;
this.nullValue = nullValue;
}
private IntegerStore(int[] values, int nullValue, boolean mutable, boolean nullSettable) {
super(mutable, nullSettable);
this.values = values;
this.nullValue = nullValue;
}
@Override
public int size() {
return values.length;
}
@Override
protected Class<?> primitiveType() {
return int.class;
}
@Override
protected Class<?> wrapperType() {
return Integer.class;
}
@Override
protected Object values() {
return values;
}
@Override
protected Integer getImpl(int index) {
return values[index];
}
@Override
protected void setImpl(int index, Integer value) {
values[index] = value == null ? nullValue : value.intValue();
}
@Override
protected void fillImpl(Integer value) {
Arrays.fill(values, value == null ? nullValue : value.intValue());
}
@Override
protected IntegerStore duplicate(boolean copy, boolean mutable) {
return new IntegerStore(copy ? values.clone() : values, nullValue, mutable, nullSettable);
}
@Override
protected IntegerStore resize(int newSize) {
int oldSize = values.length;
boolean growing = newSize > oldSize;
if (growing && !nullSettable) failGrowCopy();
int[] newValues = Arrays.copyOf(values, newSize);
if (growing && nullValue != 0) Arrays.fill(newValues, oldSize, newSize, nullValue);
return new IntegerStore(newValues, nullValue, nullSettable);
}
@Override
public StoreType<Integer> type() {
return newType(int.class, nullSettable, nullValue);
}
@Override
public Spliterator.OfInt spliterator() {
return Spliterators.spliterator(values, Spliterator.ORDERED | Spliterator.NONNULL);
}
}
final static class DoubleStore extends PrimitiveStore<Double> {
private final double[] values;
private final double nullValue;
DoubleStore(int size, StoreType<Double> type, Double initialValue) {
super(type.nullSettable);
if (initialValue == null) checkSize(size);
values = new double[size];
nullValue = nullSettable ? type.nullValue : 0.0;
if (initialValue == null) initialValue = nullValue;
if (nullValue != (double) 0) Arrays.fill(values, nullValue);
}
DoubleStore(double[] values, StoreType<Double> type) {
super(type.nullSettable);
this.values = values;
this.nullValue = nullSettable ? type.nullValue : 0.0;
}
private DoubleStore(double[] values, double nullValue, boolean nullSettable) {
super(nullSettable);
this.values = values;
this.nullValue = nullValue;
}
private DoubleStore(double[] values, double nullValue, boolean mutable, boolean nullSettable) {
super(mutable, nullSettable);
this.values = values;
this.nullValue = nullValue;
}
@Override
public int size() {
return values.length;
}
@Override
protected Class<?> primitiveType() {
return double.class;
}
@Override
protected Class<?> wrapperType() {
return Double.class;
}
@Override
protected Object values() {
return values;
}
@Override
protected Double getImpl(int index) {
return values[index];
}
@Override
protected void setImpl(int index, Double value) {
values[index] = value == null ? nullValue : value.doubleValue();
}
@Override
protected void fillImpl(Double value) {
Arrays.fill(values, value == null ? nullValue : value.doubleValue());
}
@Override
protected DoubleStore duplicate(boolean copy, boolean mutable) {
return new DoubleStore(copy ? values.clone() : values, nullValue, mutable, nullSettable);
}
@Override
protected DoubleStore resize(int newSize) {
int oldSize = values.length;
boolean growing = newSize > oldSize;
if (growing && !nullSettable) failGrowCopy();
double[] newValues = Arrays.copyOf(values, newSize);
if (growing && nullValue != 0L) Arrays.fill(newValues, oldSize, newSize, nullValue);
return new DoubleStore(newValues, nullValue, nullSettable);
}
@Override
public StoreType<Double> type() {
return newType(double.class, nullSettable, nullValue);
}
@Override
public Spliterator.OfDouble spliterator() {
return Spliterators.spliterator(values, Spliterator.ORDERED | Spliterator.NONNULL);
}
}
final static class BooleanStore extends PrimitiveStore<Boolean> {
private final boolean[] values;
private final boolean nullValue;
BooleanStore(int size, StoreType<Boolean> type, Boolean initialValue) {
super(type.nullSettable);
if (initialValue == null) checkSize(size);
values = new boolean[size];
nullValue = nullSettable && type.nullValue;
if (initialValue == null) initialValue = nullValue;
if (nullValue) Arrays.fill(values, nullValue);
}
BooleanStore(boolean[] values, StoreType<Boolean> type) {
super(type.nullSettable);
this.values = values;
this.nullValue = nullSettable && type.nullValue;
}
private BooleanStore(boolean[] values, boolean nullValue, boolean nullSettable) {
super(nullSettable);
this.values = values;
this.nullValue = nullValue;
}
private BooleanStore(boolean[] values, boolean nullValue, boolean mutable, boolean nullSettable) {
super(mutable, nullSettable);
this.values = values;
this.nullValue = nullValue;
}
@Override
public int size() {
return values.length;
}
@Override
protected Class<?> primitiveType() {
return boolean.class;
}
@Override
protected Class<?> wrapperType() {
return Boolean.class;
}
@Override
protected Object values() {
return values;
}
@Override
protected Boolean getImpl(int index) {
return values[index];
}
@Override
protected void setImpl(int index, Boolean value) {
values[index] = value == null ? nullValue : value.booleanValue();
}
@Override
protected void fillImpl(Boolean value) {
Arrays.fill(values, value == null ? nullValue : value.booleanValue());
}
@Override
protected BooleanStore duplicate(boolean copy, boolean mutable) {
return new BooleanStore(copy ? values.clone() : values, nullValue, mutable, nullSettable);
}
@Override
protected BooleanStore resize(int newSize) {
int oldSize = values.length;
boolean growing = newSize > oldSize;
if (growing && !nullSettable) failGrowCopy();
boolean[] newValues = Arrays.copyOf(values, newSize);
if (growing && nullValue) Arrays.fill(newValues, oldSize, newSize, nullValue);
return new BooleanStore(newValues, nullValue, nullSettable);
}
@Override
public StoreType<Boolean> type() {
return newType(boolean.class, nullSettable, nullValue);
}
}
}
| Corrects creation of primitive stores with initial values.
| src/main/java/com/tomgibara/storage/PrimitiveStore.java | Corrects creation of primitive stores with initial values. | <ide><path>rc/main/java/com/tomgibara/storage/PrimitiveStore.java
<ide> values = new byte[size];
<ide> nullValue = nullSettable ? type.nullValue : (byte) 0;
<ide> if (initialValue == null) initialValue = nullValue;
<del> if (nullValue != (byte) 0) Arrays.fill(values, initialValue);
<add> if (initialValue != (byte) 0) Arrays.fill(values, initialValue);
<ide> }
<ide>
<ide> ByteStore(byte[] values, StoreType<Byte> type) {
<ide> values = new float[size];
<ide> nullValue = nullSettable ? type.nullValue : 0.0f;
<ide> if (initialValue == null) initialValue = nullValue;
<del> if (nullValue != (float) 0) Arrays.fill(values, nullValue);
<add> if (initialValue != (float) 0) Arrays.fill(values, initialValue);
<ide> }
<ide>
<ide> FloatStore(float[] values, StoreType<Float> type) {
<ide> values = new char[size];
<ide> nullValue = nullSettable ? type.nullValue : '\0';
<ide> if (initialValue == null) initialValue = nullValue;
<del> if (nullValue != (char) 0) Arrays.fill(values, nullValue);
<add> if (initialValue != (char) 0) Arrays.fill(values, initialValue);
<ide> }
<ide>
<ide> CharacterStore(char[] values, StoreType<Character> type) {
<ide> values = new short[size];
<ide> nullValue = nullSettable ? type.nullValue : (short) 0;
<ide> if (initialValue == null) initialValue = nullValue;
<del> if (nullValue != (short) 0) Arrays.fill(values, nullValue);
<add> if (initialValue != (short) 0) Arrays.fill(values, initialValue);
<ide> }
<ide>
<ide> ShortStore(short[] values, StoreType<Short> type) {
<ide> values = new long[size];
<ide> nullValue = nullSettable ? type.nullValue : 0L;
<ide> if (initialValue == null) initialValue = nullValue;
<del> if (nullValue != (long) 0) Arrays.fill(values, nullValue);
<add> if (initialValue != (long) 0) Arrays.fill(values, initialValue);
<ide> }
<ide>
<ide> LongStore(long[] values, StoreType<Long> type) {
<ide> values = new int[size];
<ide> nullValue = nullSettable ? type.nullValue : 0;
<ide> if (initialValue == null) initialValue = nullValue;
<del> if (nullValue != (int) 0) Arrays.fill(values, nullValue);
<add> if (initialValue != (int) 0) Arrays.fill(values, initialValue);
<ide> }
<ide>
<ide> IntegerStore(int[] values, StoreType<Integer> type) {
<ide> values = new double[size];
<ide> nullValue = nullSettable ? type.nullValue : 0.0;
<ide> if (initialValue == null) initialValue = nullValue;
<del> if (nullValue != (double) 0) Arrays.fill(values, nullValue);
<add> if (initialValue != (double) 0) Arrays.fill(values, initialValue);
<ide> }
<ide>
<ide> DoubleStore(double[] values, StoreType<Double> type) {
<ide> values = new boolean[size];
<ide> nullValue = nullSettable && type.nullValue;
<ide> if (initialValue == null) initialValue = nullValue;
<del> if (nullValue) Arrays.fill(values, nullValue);
<add> if (initialValue) Arrays.fill(values, initialValue);
<ide> }
<ide>
<ide> BooleanStore(boolean[] values, StoreType<Boolean> type) { |
|
Java | apache-2.0 | 79a2c2441d4a9870a59e6bc1b68d4f21c97911c8 | 0 | dallascard/TemporalFrames | import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.nio.file.Paths;
import java.nio.file.Path;
import java.util.*;
import org.apache.commons.math3.distribution.BetaDistribution;
import org.apache.commons.math3.distribution.NormalDistribution;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import umontreal.ssj.probdistmulti.DirichletDist;
import umontreal.ssj.rng.*;
import org.apache.commons.math3.distribution.MultivariateNormalDistribution;
import org.apache.commons.math3.analysis.function.Sigmoid;
public class CombinedModel {
private int nArticlesWithFraming;
private int nArticlesWithTone;
private int nFramingAnnotators;
private int nToneAnnotators;
private int nTimes;
private int nNewspapers;
private static int nLabels = 15;
private static int nTones = 3;
private static int firstYear = 1990;
private static int firstQuarter = 0;
private static int nMonthsPerYear = 12;
private static int nQuartersPerYear = 4;
private static int nMonthsPerQuarter = 3;
private static int nFeatures = 7;
private Set<String> irrelevantArticles;
private Set<String> trainingArticles;
private HashMap<String, Integer> newspaperIndices;
private HashMap<String, Integer> articleNameTime;
private HashMap<String, Integer> articleNameNewspaper;
private HashMap<Integer, Integer> framingArticleTime;
private HashMap<Integer, Integer> toneArticleTime;
private HashMap<Integer, Integer> framingArticleNewspaper;
private HashMap<Integer, Integer> toneArticleNewspaper;
private HashMap<Integer, ArrayList<Integer>> timeFramingArticles;
private HashMap<Integer, ArrayList<Integer>> timeToneArticles;
private HashMap<String, Integer> framingAnnotatorIndices;
private HashMap<String, Integer> toneAnnotatorIndices;
private HashMap<Integer, ArrayList<Integer>> framingAnnotatorArticles;
private HashMap<Integer, ArrayList<Integer>> toneAnnotatorArticles;
private ArrayList<String> framingArticleNames;
private ArrayList<String> toneArticleNames;
private ArrayList<HashMap<Integer, int[]>> framingAnnotations;
private ArrayList<HashMap<Integer, Integer>> toneAnnotations;
private ArrayList<double[]> timeFramesReals; // phi
private ArrayList<double[]> timeFramesCube;
private ArrayList<int[]> articleFrames ; // theta
private double[] timeEntropy;
private ArrayList<double[]> timeToneReals; // phi
private ArrayList<double[]> timeToneSimplex;
private int[] articleTone ;
private double[][] q; // framing sensitivity
private double[][] r; // framing specificity
private double[][][] sSimplex; // combined equivalent of sens / spec for tone
private double[][][] sReal;
private double[] weights;
private double[] framesMean;
private double[] tonesMean;
private double[] globalMean;
private double[] mood;
private double[] nArticlesAtTime;
private double timeFramesRealSigma = 0.01;
private double timeToneRealSigma = 0.01;
private double weightSigma = 5.0;
private double moodSigma = 0.25;
// Metropolis-Hastings step parameters
private static double mhTimeFramesStepSigma = 0.05 ;
private static double mhTimeFramesRealSigmaStep = 0.005;
private static double mhTimeToneStepSigma = 0.1 ;
private static double mhTimeToneRealSigmaStep = 0.01;
private static double [] mhWeightsStepSigma = {0.05, 0.1, 0.2, 0.2, 0.5, 0.01, 0.05};
private static double mhOneWeightStepSigma = 0.0001;
private static double mhQSigma = 0.05;
private static double mhRSigma = 0.02;
private static double mhSSigma = 0.01;
private static double [][] mhSCovariance = {{mhSSigma, 0, 0}, {0, mhSSigma, 0}, {0, 0, mhSSigma}};
private static double mhMoodSigmaStep = 0.01;
private static Random rand = new Random();
private static RandomStream randomStream = new MRG32k3a();
private static Sigmoid sigmoid = new Sigmoid();
public CombinedModel(String inputFilename, String metadataFilename, String predictionsFilename, String moodFilename,
boolean normalizeStoriesAtTime, boolean normalizeMood) throws Exception {
Path inputPath = Paths.get(inputFilename);
JSONParser parser = new JSONParser();
JSONObject data = (JSONObject) parser.parse(new FileReader(inputPath.toString()));
Path metadataPath = Paths.get(metadataFilename);
JSONObject metadata = (JSONObject) parser.parse(new FileReader(metadataPath.toString()));
// index newspapers
Set<String> newspapers = gatherNewspapers(metadata);
nNewspapers = newspapers.size();
System.out.println(nNewspapers + " newspapers");
newspaperIndices = new HashMap<>();
int n = 0;
for (String newspaper : newspapers) {
newspaperIndices.put(newspaper, n++);
}
// record the time and paper of each article
articleNameTime = new HashMap<>();
articleNameNewspaper = new HashMap<>();
nTimes = 0;
for (Object articleName : metadata.keySet()) {
JSONObject articleMetadata = (JSONObject)metadata.get(articleName);
String source = (String) articleMetadata.get("source");
int year = ((Long) articleMetadata.get("year")).intValue();
int month = ((Long) articleMetadata.get("month")).intValue() - 1;
//int quarter = (int) Math.floor((double) month / (double) nMonthsPerQuarter);
//int time = (year - firstYear) * nQuartersPerYear + quarter;
int time = yearAndMonthToTime(year, month);
if (time >= 0) {
articleNameTime.put(articleName.toString(), time);
articleNameNewspaper.put(articleName.toString(), newspaperIndices.get(source));
}
if (time >= nTimes) {
nTimes = time + 1;
}
}
System.out.println(nTimes + " time periods");
// record the total number of articles at each time step
nArticlesAtTime = new double[nTimes];
for (int time : articleNameTime.values()) {
nArticlesAtTime[time] += 1;
}
// normalize nArticles
double nMax = 0;
for (int t = 0; t < nTimes; t++) {
nMax = Math.max(nMax, nArticlesAtTime[t]);
}
if (normalizeStoriesAtTime) {
for (int t = 0; t < nTimes; t++) {
nArticlesAtTime[t] = nArticlesAtTime[t] / nMax;
}
}
// intialize some empty arrays
timeFramingArticles = new HashMap<>();
for (int t = 0; t < nTimes; t++) {
timeFramingArticles.put(t, new ArrayList<>());
}
timeToneArticles = new HashMap<>();
for (int t = 0; t < nTimes; t++) {
timeToneArticles.put(t, new ArrayList<>());
}
// determine the relevant articles based on annotations
irrelevantArticles = getIrrelevantArticles(data);
// index annotators
Set<String> framingAnnotators = gatherFramingAnnotators(data);
nFramingAnnotators= framingAnnotators.size();
Set<String> toneAnnotators = gatherToneAnnotators(data);
nToneAnnotators = toneAnnotators.size();
System.out.println(nFramingAnnotators + " framing annotators");
System.out.println(nToneAnnotators + " tone annotators");
framingAnnotatorIndices = new HashMap<>();
toneAnnotatorIndices = new HashMap<>();
framingAnnotatorArticles = new HashMap<>();
toneAnnotatorArticles = new HashMap<>();
int k = 0;
for (String annotator : framingAnnotators) {
framingAnnotatorIndices.put(annotator, k);
framingAnnotatorArticles.put(k, new ArrayList<>());
k += 1;
}
System.out.println(framingAnnotatorIndices);
k = 0;
for (String annotator : toneAnnotators) {
toneAnnotatorIndices.put(annotator, k);
toneAnnotatorArticles.put(k, new ArrayList<>());
k += 1;
}
System.out.println(toneAnnotatorIndices);
// read in the annotations and build up all relevant information
trainingArticles = new HashSet<>();
framingArticleNames = new ArrayList<>();
toneArticleNames = new ArrayList<>();
framingArticleTime = new HashMap<>();
toneArticleTime = new HashMap<>();
framingArticleNewspaper = new HashMap<>();
toneArticleNewspaper = new HashMap<>();
framingAnnotations = new ArrayList<>();
toneAnnotations = new ArrayList<>();
framesMean = new double[nLabels];
tonesMean = new double[nTones];
int framingCount = 0;
int toneCount = 0;
for (Object articleName : data.keySet()) {
// check if this article is in the list of valid articles
if (articleNameTime.containsKey(articleName.toString())) {
if (!irrelevantArticles.contains(articleName.toString())) {
JSONObject article = (JSONObject) data.get(articleName);
JSONObject annotationsJson = (JSONObject) article.get("annotations");
JSONObject articleFramingAnnotations = (JSONObject) annotationsJson.get("framing");
JSONObject articleToneAnnotations = (JSONObject) annotationsJson.get("tone");
// make sure this article has annotations
if (articleFramingAnnotations.size() > 0) {
// get a new article id (i)
int i = framingArticleNames.size();
// store the article name for future reference
framingArticleNames.add(articleName.toString());
// get the timestep for this article (by name)
int time = articleNameTime.get(articleName.toString());
framingArticleTime.put(i, time);
// get the newspaper for this article (by name)
framingArticleNewspaper.put(i, articleNameNewspaper.get(articleName.toString()));
// create a hashmap to store the annotations for this article
HashMap<Integer, int[]> articleAnnotations = new HashMap<>();
// loop through the annotators for this article
for (Object annotator : articleFramingAnnotations.keySet()) {
// for each one, create an array to hold the annotations, and set to zero
int annotationArray[] = new int[nLabels];
// get the anntoator name and index
String parts[] = annotator.toString().split("_");
int annotatorIndex = framingAnnotatorIndices.get(parts[0]);
// loop through this annotator's annotations
JSONArray annotatorAnnotations = (JSONArray) articleFramingAnnotations.get(annotator);
for (Object annotation : annotatorAnnotations) {
// get the code
double realCode = (Double) ((JSONObject) annotation).get("code");
// subtract 1 for zero-based indexing
int code = (int) Math.round(realCode) - 1;
// record this code as being present
annotationArray[code] = 1;
}
// store the annotations for this annotator
articleAnnotations.put(annotatorIndex, annotationArray);
framingAnnotatorArticles.get(annotatorIndex).add(i);
for (int j = 0; j < nLabels; j++) {
framesMean[j] += (double) annotationArray[j];
}
framingCount += 1;
}
// store the annotations for this article
framingAnnotations.add(articleAnnotations);
timeFramingArticles.get(time).add(i);
}
if (articleToneAnnotations.size() > 0) {
// get a new article id (i)
int i = toneArticleNames.size();
// store the article name for future reference
toneArticleNames.add(articleName.toString());
// get the timestep for this article (by name)
int time = articleNameTime.get(articleName.toString());
toneArticleTime.put(i, time);
// get the newspaper for this article (by name)
toneArticleNewspaper.put(i, articleNameNewspaper.get(articleName.toString()));
// create a hashmap to store the annotations for this article
HashMap<Integer, Integer> articleAnnotations = new HashMap<>();
for (Object annotator : articleToneAnnotations.keySet()) {
// for each one, prepare to hold the tone annotation
int toneAnnotation = 0;
// get the anntoator name and index
String parts[] = annotator.toString().split("_");
int annotatorIndex = toneAnnotatorIndices.get(parts[0]);
// loop through this annotator's annotations (should be only 1)
JSONArray annotatorAnnotations = (JSONArray) articleToneAnnotations.get(annotator);
for (Object annotation : annotatorAnnotations) {
// get the code
double realCode = (Double) ((JSONObject) annotation).get("code");
// subtract 17 for zero-based indexing
toneAnnotation = (int) Math.round(realCode) - 17;
}
// store the annotations for this annotator
articleAnnotations.put(annotatorIndex, toneAnnotation);
toneAnnotatorArticles.get(annotatorIndex).add(i);
tonesMean[toneAnnotation] += 1.0;
toneCount += 1;
}
// store the annotations for this article
toneAnnotations.add(articleAnnotations);
timeToneArticles.get(time).add(i);
}
}
}
}
System.out.println(toneCount + " tone annotations used");
// read in predictions and add to annotations
Scanner scanner = new Scanner(new File(predictionsFilename));
HashMap<String, int[]> framingPredictions = new HashMap<>();
HashMap<String, Integer> tonePredictions = new HashMap<>();
scanner.useDelimiter(",");
// skip the header
for (int i = 0; i < 19; i++) {
String next = scanner.next();
next = "";
}
String rowArticleName = "";
int[] pArray = new int[nLabels];
int tVal = 0;
int iNext = 0;
int isTrain = 0;
while (scanner.hasNext()) {
String next = scanner.next();
int j = iNext % 19;
//System.out.println(j + " " + next);
if (j == 1) {
rowArticleName = next;
}
if (j == 2) {
if (Integer.parseInt(next) > 0) {
trainingArticles.add(rowArticleName);
}
}
else if (j > 2 && j < 18) {
pArray[j-3] = Integer.parseInt(next);
}
else if (j == 18) {
tVal = Integer.parseInt(next);
framingPredictions.put(rowArticleName, pArray);
tonePredictions.put(rowArticleName, tVal);
pArray = new int[nLabels];
}
iNext += 1;
}
//Do not forget to close the scanner
scanner.close();
// incorporate the predictions into the annotations
int annotatorIndex = nFramingAnnotators;
framingAnnotatorArticles.put(annotatorIndex, new ArrayList<>());
for (String articleName : framingPredictions.keySet()) {
// check if this article is in the list of valid articles
if (articleNameTime.containsKey(articleName)) {
if (!irrelevantArticles.contains(articleName)) {
//JSONObject article = (JSONObject) data.get(articleName);
if (framingArticleNames.contains(articleName)) {
if (!trainingArticles.contains(articleName)) {
// add the prediction to the set of new annotations
// get the article ID
int i = framingArticleNames.indexOf(articleName);
// create a hashmap to store the annotations for this article
HashMap<Integer, int[]> articleAnnotations = framingAnnotations.get(i);
// treat predictions as coming from a separate annotator
articleAnnotations.put(annotatorIndex, framingPredictions.get(articleName));
// store the annotations for this article
framingAnnotations.set(i, articleAnnotations);
// if this is not a training article, use it to estimate classifier properties
framingAnnotatorArticles.get(annotatorIndex).add(i);
}
} else {
// add information for a new article
// get a new article id (i)
int i = framingArticleNames.size();
// store the article name for future reference
framingArticleNames.add(articleName);
// get the timestep for this article (by name)
int time = articleNameTime.get(articleName);
framingArticleTime.put(i, time);
// get the newspaper for this article (by name)
framingArticleNewspaper.put(i, articleNameNewspaper.get(articleName));
// create a hashmap to store the annotations for this article
HashMap<Integer, int[]> articleAnnotations = new HashMap<>();
// treat predictions as coming from a separate anntoator
// loop through this annotator's annotations
articleAnnotations.put(annotatorIndex, framingPredictions.get(articleName));
// also use these unannotated articles for estimation of classifier properties
framingAnnotatorArticles.get(annotatorIndex).add(i);
//for (int j = 0; j < nLabels; j++) {
// framesMean[j] += (double) framingPredictions.get(articleName)[j];
//}
// store the annotations for this article
framingAnnotations.add(articleAnnotations);
timeFramingArticles.get(time).add(i);
//framingCount += 1;
}
}
}
}
nFramingAnnotators += 1;
System.out.println(framingAnnotations.size() + " articles with framing annotations");
for (k = 0; k < nFramingAnnotators; k++) {
System.out.println("Annotator: " + k + "; annotations: " + framingAnnotatorArticles.get(k).size());
}
System.out.println(toneAnnotations.size() + " articles with tone annotations");
for (k = 0; k < nToneAnnotators; k++) {
System.out.println("Annotator: " + k + "; annotations: " + toneAnnotatorArticles.get(k).size());
}
/*
// Try using all articles
// treat the predictions as a new anntotator
int annotatorIndex = nFramingAnnotators;
framingAnnotatorArticles.put(annotatorIndex, new ArrayList<>());
for (String articleName : framingPredictions.keySet()) {
// check if this article is in the list of valid articles
if (articleNameTime.containsKey(articleName)) {
if (framingArticleNames.contains(articleName)) {
// get the article ID
int i = framingArticleNames.indexOf(articleName);
// create a hashmap to store the annotations for this article
HashMap<Integer, int[]> articleAnnotations = framingAnnotations.get(i);
// treat predictions as coming from a separate annotator
articleAnnotations.put(annotatorIndex, framingPredictions.get(articleName));
framingAnnotatorArticles.get(annotatorIndex).add(i);
// store the annotations for this article
framingAnnotations.set(i, articleAnnotations);
}
}
}
nFramingAnnotators += 1;
*/
// treat the predictions as a new anntotator
annotatorIndex = nToneAnnotators;
toneAnnotatorArticles.put(annotatorIndex, new ArrayList<>());
for (String articleName : tonePredictions.keySet()) {
// check if this article is in the list of valid articles
if (articleNameTime.containsKey(articleName)) {
if (!irrelevantArticles.contains(articleName)) {
if (toneArticleNames.contains(articleName)) {
if (!trainingArticles.contains(articleName)) {
// get the article ID
int i = toneArticleNames.indexOf(articleName);
// create a hashmap to store the annotations for this article
HashMap<Integer, Integer> articleAnnotations = toneAnnotations.get(i);
// treat predictions as coming from a separate annotator
articleAnnotations.put(annotatorIndex, tonePredictions.get(articleName));
// store the annotations for this article
toneAnnotations.set(i, articleAnnotations);
// as above
toneAnnotatorArticles.get(annotatorIndex).add(i);
}
} else {
// add information for a new article
// get a new article id (i)
int i = toneArticleNames.size();
// store the article name for future reference
toneArticleNames.add(articleName);
// get the timestep for this article (by name)
int time = articleNameTime.get(articleName);
toneArticleTime.put(i, time);
// get the newspaper for this article (by name)
toneArticleNewspaper.put(i, articleNameNewspaper.get(articleName));
// create a hashmap to store the annotations for this article
HashMap<Integer, Integer> articleAnnotations = new HashMap<>();
// treat predictions as coming from a separate anntoator
// loop through this annotator's annotations
Integer tonePrediction = tonePredictions.get(articleName);
articleAnnotations.put(annotatorIndex, tonePrediction);
// as above
toneAnnotatorArticles.get(annotatorIndex).add(i);
//tonesMean[tonePrediction] += 1.0;
// store the annotations for this article
toneAnnotations.add(articleAnnotations);
timeToneArticles.get(time).add(i);
//toneCount += 1;
}
}
}
}
nToneAnnotators += 1;
System.out.println(framingAnnotations.size() + " articles with tone annotations");
// get the mean of the annotations as a sanity check
for (int j = 0; j < nLabels; j++) {
framesMean[j] = framesMean[j] / (double) framingCount;
}
for (int j = 0; j < nTones; j++) {
tonesMean[j] = tonesMean[j] / (double) toneCount;
}
nArticlesWithFraming = framingAnnotations.size();
nArticlesWithTone = toneAnnotations.size();
System.out.println("Mean of annotations:");
for (int j = 0; j < nLabels; j++) {
System.out.print(framesMean[j] + " ");
}
System.out.println("Mean of tone annotations:");
for (int j = 0; j < nTones; j++) {
System.out.print(tonesMean[j] + " ");
}
System.out.println("");
// read in mood data
mood = new double[nTimes];
scanner = new Scanner(new File(moodFilename));
scanner.useDelimiter(",");
// skip the header
for (int i = 0; i < 6; i++) {
String next = scanner.next();
}
int year = 0;
int quarter = 0;
double moodVal = 0;
iNext = 0;
while (scanner.hasNext()) {
String next = scanner.next();
int j = iNext % 6;
if (j == 1) {
year = Integer.parseInt(next);
}
else if (j == 2) {
quarter = Integer.parseInt(next)-1;
}
else if (j == 3) {
if (normalizeMood) {
// normalize mood to be in the range (-1, 1)
moodVal = Double.parseDouble(next) / 100.0;
} else {
moodVal = Double.parseDouble(next);
}
}
else if (j == 5) {
int time = yearAndQuarterToTime(year, quarter);
if (time >= 0 && time < nTimes) {
mood[time] = moodVal;
}
}
iNext += 1;
}
//Do not forget to close the scanner
scanner.close();
// save mood data
Path output_path;
output_path = Paths.get("samples", "mood.csv");
try (FileWriter file = new FileWriter(output_path.toString())) {
for (int t = 0; t < nTimes; t++) {
file.write(mood[t] + ",");
}
}
// display mood data
/*
for (int t = 0; t < nTimes; t++) {
//quarter = t % nQuartersPerYear;
//year = (t - quarter) / nQuartersPerYear + firstYear;
int nFramingArticles = timeFramingArticles.get(t).size();
int nToneArticles = timeToneArticles.get(t).size();
double yearQuarter = timeToYearAndQuarter(t);
//System.out.println(yearQuarter + " : " + nFramingArticles + ", " + nToneArticles);
//System.out.println(yearQuarter + " : " + mood[t]);
}
*/
initialize();
}
private int yearAndMonthToTime(int year, int month) {
int quarter = (int) Math.floor((double) month / (double) nMonthsPerQuarter);
return yearAndQuarterToTime(year, quarter);
}
private int yearAndQuarterToTime(int year, int quarter) {
return (year - firstYear) * nQuartersPerYear + quarter - firstQuarter;
}
private double timeToYearAndQuarter(int time) {
return (double) (time + firstQuarter) / (double) nQuartersPerYear + firstYear;
}
private Set<String> gatherNewspapers(JSONObject metadata) {
/*
Read in the metadata and build up the set of newspapers for valid articles
*/
Set <String> newspapers = new HashSet<>();
for (Object key : metadata.keySet()) {
JSONObject articleMetadata = (JSONObject)metadata.get(key);
String source = (String) articleMetadata.get("source");
int year = ((Long) articleMetadata.get("year")).intValue();
if (year >= firstYear) {
newspapers.add(source);
}
}
return newspapers;
}
private Set<String> getIrrelevantArticles(JSONObject data) {
Set<String> irrelevantArticles = new HashSet<>();
for (Object articleName : data.keySet()) {
// check if this article is in the list of valid articles
if (articleNameTime.containsKey(articleName.toString())) {
boolean relevant = true;
JSONObject article = (JSONObject) data.get(articleName);
JSONObject annotations = (JSONObject) article.get("annotations");
JSONObject relevanceJudgements = (JSONObject) annotations.get("irrelevant");
for (Object annotator : relevanceJudgements.keySet()) {
boolean irrelevant = (boolean) relevanceJudgements.get(annotator);
if (irrelevant) {
relevant = false;
}
}
if (!relevant) {
irrelevantArticles.add(articleName.toString());
}
}
}
return irrelevantArticles;
}
private Set<String> gatherFramingAnnotators(JSONObject data) {
/*
Read in the data and build up the set of annotators for valid articles
*/
Set<String> annotators = new HashSet<>();
for (Object articleName : data.keySet()) {
// check if this article is in the list of valid articles
if (articleNameTime.containsKey(articleName.toString())) {
if (!irrelevantArticles.contains(articleName.toString())) {
JSONObject article = (JSONObject) data.get(articleName);
JSONObject annotations = (JSONObject) article.get("annotations");
JSONObject framingAnnotations = (JSONObject) annotations.get("framing");
for (Object annotator : framingAnnotations.keySet()) {
String parts[] = annotator.toString().split("_");
annotators.add(parts[0]);
}
}
}
}
return annotators;
}
private Set<String> gatherToneAnnotators(JSONObject data) {
/*
Read in the data and build up the set of annotators for valid articles
*/
Set<String> annotators = new HashSet<>();
for (Object articleName : data.keySet()) {
// check if this article is in the list of valid articles
if (articleNameTime.containsKey(articleName.toString())) {
if (!irrelevantArticles.contains(articleName.toString())) {
JSONObject article = (JSONObject) data.get(articleName);
JSONObject annotations = (JSONObject) article.get("annotations");
JSONObject framingAnnotations = (JSONObject) annotations.get("tone");
for (Object annotator : framingAnnotations.keySet()) {
String parts[] = annotator.toString().split("_");
annotators.add(parts[0]);
}
}
}
}
return annotators;
}
private void initialize() {
// initialize article frames based on annotations
articleFrames = new ArrayList<>();
for (int i = 0; i < nArticlesWithFraming; i++) {
int initialLabels[] = new int[nLabels];
double annotationCounts[] = new double[nLabels];
// add the contributions of each annotator
HashMap<Integer, int[]> articleAnnotations = framingAnnotations.get(i);
double nAnnotators = (double) articleAnnotations.size();
for (int annotator : articleAnnotations.keySet()) {
int annotatorAnnotations[] = articleAnnotations.get(annotator);
for (int j = 0; j < nLabels; j++) {
annotationCounts[j] += (double) annotatorAnnotations[j] / nAnnotators;
}
}
for (int j = 0; j < nLabels; j++) {
double u = rand.nextDouble();
if (u < annotationCounts[j]) {
initialLabels[j] = 1;
}
}
articleFrames.add(initialLabels);
}
// initialize article tones based on annotations
articleTone = new int[nArticlesWithTone];
for (int i = 0; i < nArticlesWithTone; i++) {
double annotationCounts[] = new double[nTones];
// add the contributions of each annotator
HashMap<Integer, Integer> articleAnnotations = toneAnnotations.get(i);
double nAnnotators = (double) articleAnnotations.size();
for (int annotator : articleAnnotations.keySet()) {
int annotatorTone = articleAnnotations.get(annotator);
annotationCounts[annotatorTone] += 1.0 / nAnnotators;
}
MultinomialDistribution multinomialDistribution = new MultinomialDistribution(annotationCounts, nTones);
int initialTone = multinomialDistribution.sample(rand);
articleTone[i] = initialTone;
}
// initialize timeFrames as the mean of the corresponding articles (+ global mean)
timeFramesReals = new ArrayList<>();
timeFramesCube = new ArrayList<>();
timeToneReals = new ArrayList<>();
timeToneSimplex = new ArrayList<>();
timeEntropy = new double[nTimes];
for (int t = 0; t < nTimes; t++) {
double timeFramesMean[] = new double[nLabels];
double timeFramesMeanReals[] = new double[nLabels];
// initialize everything with the global mean
ArrayList<Integer> articles = timeFramingArticles.get(t);
double nTimeFramingArticles = (double) articles.size();
for (int j = 0; j < nLabels; j++) {
timeFramesMean[j] += framesMean[j] / (nTimeFramingArticles + 1);
}
for (int i : articles) {
int frames[] = articleFrames.get(i);
for (int j = 0; j < nLabels; j++) {
timeFramesMean[j] += (double) frames[j] / (nTimeFramingArticles + 1);
}
}
timeFramesMeanReals = Transformations.cubeToReals(timeFramesMean, nLabels);
timeFramesCube.add(timeFramesMean);
timeFramesReals.add(timeFramesMeanReals);
timeEntropy[t] = computeEntropy(timeFramesMean);
double timeTonesMeanSimplex[] = new double[nTones];
// initialize everything with the global mean
articles = timeToneArticles.get(t);
double nTimeToneArticles = (double) articles.size();
for (int j = 0; j < nTones; j++) {
timeTonesMeanSimplex[j] += tonesMean[j] / (nTimeToneArticles + 1);
}
for (int i : articles) {
int tone = articleTone[i];
timeTonesMeanSimplex[tone] += 1.0 / (nTimeToneArticles + 1);
}
double timeTonesMeanReals[] = Transformations.simplexToReals(timeTonesMeanSimplex, nTones);
timeToneSimplex.add(timeTonesMeanSimplex);
timeToneReals.add(timeTonesMeanReals);
}
System.out.println("");
// initialize annotator parameters to reasonable values
q = new double[nFramingAnnotators][nLabels];
r = new double[nFramingAnnotators][nLabels];
for (int k = 0; k < nFramingAnnotators; k++) {
for (int j = 0; j < nLabels; j++) {
q[k][j] = 0.8;
r[k][j] = 0.8;
}
}
double priorCorrect = 0.8;
sSimplex = new double[nToneAnnotators][nTones][nTones];
sReal = new double[nToneAnnotators][nTones][nTones];
for (int k = 0; k < nToneAnnotators; k++) {
for (int j = 0; j < nTones; j++) {
for (int j2 = 0; j2 < nTones; j2++) {
if (j == j2) {
sSimplex[k][j][j2] = priorCorrect;
} else {
sSimplex[k][j][j2] = (1.0 - priorCorrect) / (nTones - 1);
}
}
sReal[k][j] = Transformations.simplexToReals(sSimplex[k][j], nTones);
}
}
// initialize weights
weights = new double[nFeatures];
/*
weights[0] = 0.18;
weights[1] = 0.82;
weights[2] = 0.0;
weights[3] = 2.0;
weights[4] = 1.1;
weights[5] = 0.0;
weights[6] = -0.3;
*/
}
void run(int nIter, int burnIn, int samplingPeriod, int printPeriod) throws Exception {
int nSamples = (int) Math.floor((nIter - burnIn) / (double) samplingPeriod);
System.out.println("Collecting " + nSamples + " samples");
double timeFrameSamples [][][] = new double[nSamples][nTimes][nLabels];
int articleFrameSamples [][][] = new int[nSamples][nArticlesWithFraming][nLabels];
double timeFrameRealSigmaSamples [] = new double[nSamples];
double timeToneSamples [][][] = new double[nSamples][nTimes][nLabels];
int articleToneSamples [][] = new int[nSamples][nArticlesWithTone];
double timeToneRealSigmaSamples [] = new double[nSamples];
double weightSamples [][] = new double[nSamples][nFeatures];
double qSamples [][][] = new double[nSamples][nFramingAnnotators][nLabels];
double rSamples [][][] = new double[nSamples][nFramingAnnotators][nLabels];
double sSamples [][][][] = new double[nSamples][nToneAnnotators][nTones][nTones];
double entropySamples [][] = new double[nSamples][nTimes];
double moodSamples[][] = new double[nSamples][nTimes];
double moodSigmaSamples[] = new double[nSamples];
double timeFrameRate = 0.0;
double articleFramesRate = 0;
double timeTonesRate = 0.0;
double articleToneRates = 0.0;
double timeFramesSigmaRate = 0;
double timeToneSigmaRate = 0;
double [] weightRate = new double[nFeatures];
double oneWeightRate = 0.0;
double [][] qRate = new double[nFramingAnnotators][nLabels];
double [][] rRate = new double[nFramingAnnotators][nLabels];
double [][] sRate = new double[nToneAnnotators][nTones];
double moodSigmaRate = 0.0;
int sample = 0;
int i = 0;
while (sample < nSamples) {
timeFrameRate += sampleTimeFrames();
sampleArticleFrames();
timeFramesSigmaRate += sampleTimeFramesRealSigma();
timeTonesRate += sampleTimeTones();
sampleArticleTones();
timeToneSigmaRate += sampleTimeToneRealSigma();
double [] weightAcceptances = sampleWeights();
for (int f = 0; f < nFeatures; f++) {
weightRate[f] += (double) weightAcceptances[f];
}
//oneWeightRate += sampleAllWeights();
//moodSigmaRate += sampleMoodSigma();
double [][] qAcceptances = sampleQ();
for (int k = 0; k < nFramingAnnotators; k++) {
for (int j = 0; j < nLabels; j++) {
qRate[k][j] += qAcceptances[k][j];
}
}
double [][] rAcceptances = sampleR();
for (int k = 0; k < nFramingAnnotators; k++) {
for (int j = 0; j < nLabels; j++) {
rRate[k][j] += rAcceptances[k][j];
}
}
double [][] sAcceptances = sampleS();
for (int k = 0; k < nToneAnnotators; k++) {
for (int j = 0; j < nTones; j++) {
sRate[k][j] += sAcceptances[k][j];
}
}
//globalMean = recomputeGlobalMean();
// save samples
if (i > burnIn && i % samplingPeriod == 0) {
for (int t = 0; t < nTimes; t++) {
System.arraycopy(timeFramesCube.get(t), 0, timeFrameSamples[sample][t], 0, nLabels);
}
for (int t = 0; t < nTimes; t++) {
System.arraycopy(timeToneSimplex.get(t), 0, timeToneSamples[sample][t], 0, nTones);
}
timeFrameRealSigmaSamples[sample] = timeFramesRealSigma;
timeToneRealSigmaSamples[sample] = timeToneRealSigma;
for (int f = 0; f < nFeatures; f++) {
System.arraycopy(weights, 0, weightSamples[sample], 0, nFeatures);
}
/*
for (int a = 0; a < nArticlesWithFraming; a++) {
System.arraycopy(articleFrames.get(a), 0, articleFrameSamples[sample][a], 0, nLabels);
}
System.arraycopy(articleTone, 0, articleToneSamples[sample], 0, nArticlesWithTone);
*/
moodSigmaSamples[sample] = moodSigma;
for (int k = 0; k < nFramingAnnotators; k++) {
System.arraycopy(q[k], 0, qSamples[sample][k], 0, nLabels);
System.arraycopy(r[k], 0, rSamples[sample][k], 0, nLabels);
}
for (int k = 0; k < nToneAnnotators; k++) {
for (int l = 0; l < nTones; l++) {
System.arraycopy(sSimplex[k][l], 0, sSamples[sample][k][l], 0, nTones);
}
}
System.arraycopy(timeEntropy, 0, entropySamples[sample], 0, nTimes);
for (int t = 0; t < nTimes; t++) {
double [] featureVector = computeFeatureVector(t, timeToneSimplex.get(t), timeEntropy[t]);
double moodMean = 0.0;
for (int f = 0; f < nFeatures; f++) {
moodMean += featureVector[f] * weights[f];
}
moodSamples[sample][t] = moodMean;
}
sample += 1;
}
i += 1;
if (i % printPeriod == 0) {
System.out.print(i + ": ");
for (int f = 0; f < nFeatures; f++) {
System.out.print(weights[f] + " ");
}
//for (int k = 0; k < nLabels; k++) {
// System.out.print(globalMean[k] + " ");
//}
System.out.print("\n");
}
}
// Display acceptance rates
System.out.println(timeFrameRate / i);
System.out.println(timeFramesSigmaRate / i);
System.out.println(timeTonesRate / i);
System.out.println(timeToneSigmaRate / i);
System.out.println(moodSigmaRate / i);
System.out.println("weight rates");
for (int f = 0; f < nFeatures; f++) {
System.out.println(weightRate[f] / i);
}
//System.out.println("weight rates: " + oneWeightRate / i);
System.out.println(articleFramesRate / i);
System.out.println(articleToneRates / i);
System.out.println("Q rates");
for (int k = 0; k < nFramingAnnotators; k++) {
for (int j = 0; j < nLabels; j++) {
System.out.print(qRate[k][j] / i + " ");
}
System.out.print("\n");
}
System.out.println("R rates");
for (int k = 0; k < nFramingAnnotators; k++) {
for (int j = 0; j < nLabels; j++) {
System.out.print(rRate[k][j] / i + " ");
}
System.out.print("\n");
}
System.out.println("S rates");
for (int k = 0; k < nToneAnnotators; k++) {
for (int j = 0; j < nTones; j++) {
System.out.print(sRate[k][j] / i + " ");
}
System.out.print("\n");
}
// save results
Path output_path;
for (int k = 0; k < nLabels; k++) {
output_path = Paths.get("samples", "timeFramesSamples" + k + ".csv");
try (FileWriter file = new FileWriter(output_path.toString())) {
for (sample = 0; sample < nSamples; sample++) {
for (int t = 0; t < nTimes; t++) {
file.write(timeFrameSamples[sample][t][k] + ",");
}
file.write("\n");
}
}
}
output_path = Paths.get("samples", "timeFrameRealSigmaSamples.csv");
try (FileWriter file = new FileWriter(output_path.toString())) {
for (sample = 0; sample < nSamples; sample++) {
file.write(timeFrameRealSigmaSamples[sample] + ",\n" );
}
}
for (int k = 0; k < nTones; k++) {
output_path = Paths.get("samples", "timeToneSamples" + k + ".csv");
try (FileWriter file = new FileWriter(output_path.toString())) {
for (sample = 0; sample < nSamples; sample++) {
for (int t = 0; t < nTimes; t++) {
file.write(timeToneSamples[sample][t][k] + ",");
}
file.write("\n");
}
}
}
output_path = Paths.get("samples", "timeToneRealSigmaSamples.csv");
try (FileWriter file = new FileWriter(output_path.toString())) {
for (sample = 0; sample < nSamples; sample++) {
file.write(timeToneRealSigmaSamples[sample] + ",\n");
}
}
output_path = Paths.get("samples", "entropySamples.csv");
try (FileWriter file = new FileWriter(output_path.toString())) {
for (sample = 0; sample < nSamples; sample++) {
for (int t = 0; t < nTimes; t++) {
file.write(entropySamples[sample][t] + ",");
}
file.write("\n");
}
}
output_path = Paths.get("samples", "weightSamples.csv");
try (FileWriter file = new FileWriter(output_path.toString())) {
for (sample = 0; sample < nSamples; sample++) {
for (int f = 0; f < nFeatures; f++) {
file.write(weightSamples[sample][f] + ",");
}
file.write("\n");
}
}
for (int j = 0; j < nLabels; j++) {
output_path = Paths.get("samples", "qSamples" + j + ".csv");
try (FileWriter file = new FileWriter(output_path.toString())) {
for (sample = 0; sample < nSamples; sample++) {
for (int k = 0; k < nFramingAnnotators; k++) {
file.write(qSamples[sample][k][j] + ",");
}
file.write("\n");
}
}
}
for (int j = 0; j < nLabels; j++) {
output_path = Paths.get("samples", "rSamples" + j + ".csv");
try (FileWriter file = new FileWriter(output_path.toString())) {
for (sample = 0; sample < nSamples; sample++) {
for (int k = 0; k < nFramingAnnotators; k++) {
file.write(rSamples[sample][k][j] + ",");
}
file.write("\n");
}
}
}
for (int j = 0; j < nTones; j++) {
output_path = Paths.get("samples", "sSensitivitySamples" + j + ".csv");
try (FileWriter file = new FileWriter(output_path.toString())) {
for (sample = 0; sample < nSamples; sample++) {
for (int k = 0; k < nToneAnnotators; k++) {
file.write(sSamples[sample][k][j][j] + ",");
}
file.write("\n");
}
}
}
output_path = Paths.get("samples", "moodSamples.csv");
try (FileWriter file = new FileWriter(output_path.toString())) {
for (sample = 0; sample < nSamples; sample++) {
for (int t = 0; t < nTimes; t++) {
file.write(moodSamples[sample][t] + ",");
}
file.write("\n");
}
}
// What I actually want is maybe the annotation probabilities (?)
/*
output_path = Paths.get("samples", "articleMeans.csv");
try (FileWriter file = new FileWriter(output_path.toString())) {
for (int a = 0; a < nArticles; a++) {
double mean [] = new double[nLabels];
HashMap<Integer, int[]> articleAnnotations = annotations.get(a);
for (int annotator : articleAnnotations.keySet()) {
for (int k = 0; k < nLabels; k++) {
mean[k] += (double) articleAnnotations.get(annotator)[k] / (double) articleAnnotations.size();
}
}
for (int k = 0; k < nLabels; k++) {
file.write(mean[k] + ",");
}
file.write("\n");
}
}
*/
/*
for (int k = 0; k < nLabels; k++) {
output_path = Paths.get("samples", "articleProbs" + k + ".csv");
try (FileWriter file = new FileWriter(output_path.toString())) {
for (s = 0; s < nSamples; s++) {
for (int a = 0; a < nArticles; a++) {
double pk = sigmoid.value(articleFrameSamples[s][a][k] * zealSamples[s][0][k] - biasSamples[s][0][k]);
file.write(pk + ",");
}
file.write("\n");
}
}
}
*/
}
private double[] computeFeatureVector(int time, double [] toneProbs, double entropy) {
double featureVector[] = new double[nFeatures];
featureVector[0] = 1; // intercept
if (time > 0) {
featureVector[1] = mood[time - 1]; // mood at t-1
}
else {
featureVector[1] = mood[time]; // cheap substitute for previous mood in first year
}
featureVector[2] = nArticlesAtTime[time]; // number of articles published in time t
featureVector[3] = toneProbs[0] - toneProbs[2]; // net tone at time t
featureVector[4] = featureVector[2] * featureVector[3]; // interaction b/w tone and nArticles
featureVector[5] = entropy; // entropy
featureVector[6] = featureVector[3] * featureVector[5]; // interaction b/w tone and entropy
return featureVector;
}
private double computeEntropy(double [] framingProbs) {
double entropy = 0;
for (int j = 0; j < nLabels; j++) {
entropy -= (framingProbs[j] * Math.log(framingProbs[j]) + (1-framingProbs[j]) * Math.log(1-framingProbs[j]));
}
return entropy;
}
private double computeLogProbMood(double [] featureVector, double [] weights, double mood, double moodSigma) {
double mean = 0;
for (int f = 0; f < nFeatures; f++) {
mean += weights[f] * featureVector[f];
}
NormalDistribution currentMoodDist = new NormalDistribution(mean, moodSigma);
double pLogMood = Math.log(currentMoodDist.density(mood));
return pLogMood;
}
private double sampleTimeFrames() {
// run the distribution over frames for the first time point
double nAccepted = 0;
// loop through all time points
for (int t = 0; t < nTimes; t++) {
// get the current distribution over frames
double currentCube[] = timeFramesCube.get(t);
double currentReals[] = timeFramesReals.get(t);
// create a variable for a proposal
double proposalReals[] = new double[nLabels];
double mean[] = new double[nLabels];
double covariance[][] = new double[nLabels][nLabels];
for (int k = 0; k < nLabels; k++) {
covariance[k][k] = 1;
}
MultivariateNormalDistribution normDist = new MultivariateNormalDistribution(mean, covariance);
double normalStep[] = normDist.sample();
double step = rand.nextGaussian() * mhTimeFramesStepSigma;
// apply the step to generate a proposal
for (int k = 0; k < nLabels; k++) {
proposalReals[k] = currentReals[k] + normalStep[k] * step;
}
// transform the proposal to the cube
double proposalCube[] = Transformations.realsToCube(proposalReals, nLabels);
// get the distribution over frames at the previous time point
double previousReals[] = new double[nLabels];
double priorCovariance[][] = new double[nLabels][nLabels];
double priorNextCovariance[][] = new double[nLabels][nLabels];
if (t > 0) {
previousReals = timeFramesReals.get(t-1);
for (int k = 0; k < nLabels; k++) {
priorCovariance[k][k] = timeFramesRealSigma;
priorNextCovariance[k][k] = timeFramesRealSigma;
}
} else {
// if t == 0, use the global mean
//double [] previousCube = new double[nLabels];
//System.arraycopy(framesMean, 0, previousCube, 0, nLabels);
//previousReals = Transformations.cubeToReals(previousCube, nLabels);
for (int k = 0; k < nLabels; k++) {
priorCovariance[k][k] = timeFramesRealSigma * 100;
priorNextCovariance[k][k] = timeFramesRealSigma;
}
}
MultivariateNormalDistribution previousDist = new MultivariateNormalDistribution(previousReals, priorCovariance);
double pLogCurrent = Math.log(previousDist.density(currentReals));
double pLogProposal = Math.log(previousDist.density(proposalReals));
// get the distribution over frames in the next time point
if (t < nTimes-1) {
double nextReals[] = timeFramesReals.get(t+1);
// compute a distribution over a new distribution over frames for the current distribution
MultivariateNormalDistribution currentDist = new MultivariateNormalDistribution(currentReals, priorNextCovariance);
MultivariateNormalDistribution proposalDist = new MultivariateNormalDistribution(proposalReals, priorNextCovariance);
pLogCurrent += Math.log(currentDist.density(nextReals));
pLogProposal += Math.log(proposalDist.density(nextReals));
}
// compute the probability of the article distributions for both current and proposal
ArrayList<Integer> articles = timeFramingArticles.get(t);
for (int i : articles) {
int articleLabels[] = articleFrames.get(i);
for (int k = 0; k < nLabels; k++) {
pLogCurrent += articleLabels[k] * Math.log(currentCube[k]) + (1-articleLabels[k]) * Math.log(1-currentCube[k]);
pLogProposal += articleLabels[k] * Math.log(proposalCube[k]) + (1-articleLabels[k]) * Math.log(1-proposalCube[k]);
}
}
// compute probabilities of mood for current and proposed latent framing probs
double currentVector[] = computeFeatureVector(t, timeToneSimplex.get(t), timeEntropy[t]);
double proposalEntropy = computeEntropy(proposalCube);
double proposalVector[] = computeFeatureVector(t, timeToneSimplex.get(t), proposalEntropy);
pLogCurrent += computeLogProbMood(currentVector, weights, mood[t], moodSigma);
pLogProposal += computeLogProbMood(proposalVector, weights, mood[t], moodSigma);
double a = Math.exp(pLogProposal - pLogCurrent);
double u = rand.nextDouble();
if (u < a) {
timeFramesCube.set(t, proposalCube);
timeFramesReals.set(t, proposalReals);
nAccepted += 1;
timeEntropy[t] = proposalEntropy;
}
}
return nAccepted / nTimes;
}
private void sampleArticleFrames() {
// don't bother to track acceptance because we're going to properly use Gibbs for this
// loop through all articles
for (int i = 0; i < nArticlesWithFraming; i++) {
// get the current article dist
int articleLabels[] = articleFrames.get(i);
int proposedLabels[] = new int[nLabels];
int time = framingArticleTime.get(i);
double timeFrames[] = timeFramesCube.get(time);
for (int j = 0; j < nLabels; j++) {
double pLogPosGivenTime = Math.log(timeFrames[j]);
double pLogNegGivenTime = Math.log(1-timeFrames[j]);
// compute the probability of the labels for both current and proposal
HashMap<Integer, int[]> articleAnnotations = framingAnnotations.get(i);
for (int annotator : articleAnnotations.keySet()) {
int labels[] = articleAnnotations.get(annotator);
pLogPosGivenTime += labels[j] * Math.log(q[annotator][j]) + (1-labels[j]) * Math.log(1-r[annotator][j]);
pLogNegGivenTime += labels[j] * Math.log(1-q[annotator][j]) + (1-labels[j]) * Math.log(r[annotator][j]);
}
double pPosUnnorm = Math.exp(pLogPosGivenTime);
double pNegUnnorm = Math.exp(pLogNegGivenTime);
double pPos = pPosUnnorm / (pPosUnnorm + pNegUnnorm);
double u = rand.nextDouble();
if (u < pPos) {
proposedLabels[j] = 1;
}
}
articleFrames.set(i, proposedLabels);
}
}
private double sampleTimeFramesRealSigma() {
double acceptance = 0.0;
double current = timeFramesRealSigma;
double proposal = current + rand.nextGaussian() * mhTimeFramesRealSigmaStep;
double pLogCurrent = 0.0;
double pLogProposal = 0.0;
double [][] currentCovar = new double[nLabels][nLabels];
double [][] proposalCovar = new double[nLabels][nLabels];
for (int j = 0; j < nLabels; j++) {
currentCovar[j][j] = current;
proposalCovar[j][j] = proposal;
}
if (proposal > 0) {
for (int t = 1; t < nTimes; t++) {
MultivariateNormalDistribution priorCurrent = new MultivariateNormalDistribution(timeFramesReals.get(t-1), currentCovar);
MultivariateNormalDistribution priorProposal = new MultivariateNormalDistribution(timeFramesReals.get(t-1), proposalCovar);
pLogCurrent += Math.log(priorCurrent.density(timeFramesReals.get(t)));
pLogProposal += Math.log(priorProposal.density(timeFramesReals.get(t)));
}
double a = Math.exp(pLogProposal - pLogCurrent);
double u = rand.nextDouble();
if (u < a) {
timeFramesRealSigma = proposal;
acceptance += 1;
}
}
return acceptance;
}
private double sampleTimeToneRealSigma() {
double acceptance = 0.0;
double current = timeToneRealSigma;
double proposal = current + rand.nextGaussian() * mhTimeToneRealSigmaStep;
double pLogCurrent = 0.0;
double pLogProposal = 0.0;
double [][] currentCovar = new double[nTones][nTones];
double [][] proposalCovar = new double[nTones][nTones];
for (int j = 0; j < nTones; j++) {
currentCovar[j][j] = current;
proposalCovar[j][j] = proposal;
}
if (proposal > 0) {
for (int t = 1; t < nTimes; t++) {
MultivariateNormalDistribution priorCurrent = new MultivariateNormalDistribution(timeToneReals.get(t-1), currentCovar);
MultivariateNormalDistribution priorProposal = new MultivariateNormalDistribution(timeToneReals.get(t-1), proposalCovar);
pLogCurrent += Math.log(priorCurrent.density(timeToneReals.get(t)));
pLogProposal += Math.log(priorProposal.density(timeToneReals.get(t)));
}
double a = Math.exp(pLogProposal - pLogCurrent);
double u = rand.nextDouble();
if (u < a) {
timeToneRealSigma = proposal;
acceptance += 1;
}
}
return acceptance;
}
private double sampleTimeTones() {
// run the distribution over tones for the first time point
double nAccepted = 0;
// loop through all time points
for (int t = 0; t < nTimes; t++) {
// get the current distribution over tones
double currentSimplex[] = timeToneSimplex.get(t);
double currentReals[] = timeToneReals.get(t);
// create a variable for a proposal
double proposalReals[] = new double[nTones];
double mean[] = new double[nTones];
double covariance[][] = new double[nTones][nTones];
for (int k = 0; k < nTones; k++) {
covariance[k][k] = 1;
}
MultivariateNormalDistribution normDist = new MultivariateNormalDistribution(mean, covariance);
double normalStep[] = normDist.sample();
double step = rand.nextGaussian() * mhTimeToneStepSigma;
// apply the step to generate a proposal
for (int k = 0; k < nTones; k++) {
proposalReals[k] = currentReals[k] + normalStep[k] * step;
}
// transform the proposal to the simplex
double proposalSimplex[] = Transformations.realsToSimplex(proposalReals, nTones);
// get the distribution over tones at the previous time point
double previousReals[] = new double[nTones];
double priorCovariance[][] = new double[nTones][nTones];
double priorNextCovariance[][] = new double[nTones][nTones];
if (t > 0) {
previousReals = timeToneReals.get(t-1);
// compute a distribution over the current time point given previous
for (int k = 0; k < nTones; k++) {
priorCovariance[k][k] = timeToneRealSigma;
priorNextCovariance[k][k] = timeToneRealSigma;
}
} else {
// if t == 0, use the global mean
//double [] previousSimplex = new double[nTones];
//System.arraycopy(tonesMean, 0, previousSimplex, 0, nTones);
//previousReals = Transformations.simplexToReals(previousSimplex, nTones);
// compute a distribution over the current time point given previous
for (int k = 0; k < nTones; k++) {
priorCovariance[k][k] = timeToneRealSigma * 100;
priorNextCovariance[k][k] = timeToneRealSigma;
}
}
MultivariateNormalDistribution previousDist = new MultivariateNormalDistribution(previousReals, priorCovariance);
double pLogCurrent = Math.log(previousDist.density(currentReals));
double pLogProposal = Math.log(previousDist.density(proposalReals));
// get the distribution over tones in the next time point
if (t < nTimes-1) {
double nextReals[] = timeToneReals.get(t+1);
// compute a distribution over a new distribution over tones for the current distribution
MultivariateNormalDistribution currentDist = new MultivariateNormalDistribution(currentReals, priorNextCovariance);
MultivariateNormalDistribution proposalDist = new MultivariateNormalDistribution(proposalReals, priorNextCovariance);
pLogCurrent += Math.log(currentDist.density(nextReals));
pLogProposal += Math.log(proposalDist.density(nextReals));
}
// compute the probability of the article tones for both current and proposal
ArrayList<Integer> articles = timeToneArticles.get(t);
for (int i : articles) {
int iTone = articleTone[i];
pLogCurrent += Math.log(currentSimplex[iTone]);
pLogProposal += Math.log(proposalSimplex[iTone]);
}
// compute probabilities of mood for current and proposed latent framing probs
double currentVector[] = computeFeatureVector(t, currentSimplex, timeEntropy[t]);
double proposalVector[] = computeFeatureVector(t, proposalSimplex, timeEntropy[t]);
pLogCurrent += computeLogProbMood(currentVector, weights, mood[t], moodSigma);
pLogProposal += computeLogProbMood(proposalVector, weights, mood[t], moodSigma);
double a = Math.exp(pLogProposal - pLogCurrent);
double u = rand.nextDouble();
if (u < a) {
timeToneSimplex.set(t, proposalSimplex);
timeToneReals.set(t, proposalReals);
nAccepted += 1;
}
}
return nAccepted / nTimes;
}
private void sampleArticleTones() {
// don't bother to track acceptance because we're going to properly use Gibbs for this
// loop through all articles
for (int i = 0; i < nArticlesWithTone; i++) {
// get the current article dist
int tone = articleTone[i];
int time = toneArticleTime.get(i);
double timeTones[] = timeToneSimplex.get(time);
double pLogPositive = Math.log(timeTones[0]);
double pLogNeutral = Math.log(timeTones[1]);
double pLogAnti = Math.log(timeTones[2]);
HashMap<Integer, Integer> articleAnnotations = toneAnnotations.get(i);
for (int annotator : articleAnnotations.keySet()) {
int annotatorTone = articleAnnotations.get(annotator);
pLogPositive += Math.log(sSimplex[annotator][0][annotatorTone]);
pLogNeutral += Math.log(sSimplex[annotator][1][annotatorTone]);
pLogAnti += Math.log(sSimplex[annotator][2][annotatorTone]);
}
double pPositiveUnnorm = Math.exp(pLogPositive);
double pNeutralUnnorm = Math.exp(pLogNeutral);
double pAntiUnnorm = Math.exp(pLogAnti);
double pPos = pPositiveUnnorm / (pPositiveUnnorm + pNeutralUnnorm + pAntiUnnorm);
double pProNeutral = pPos + pNeutralUnnorm / (pPositiveUnnorm + pNeutralUnnorm + pAntiUnnorm);
double u = rand.nextDouble();
if (u < pPos) {
articleTone[i] = 0;
}
else if (u < pProNeutral) {
articleTone[i] = 1;
}
else {
articleTone[i] = 2;
}
}
}
private double [] sampleWeights() {
double [] nAccepted = new double[nFeatures];
for (int f = 0; f < nFeatures; f++) {
double [] current = new double[nFeatures];
double [] proposal = new double[nFeatures];
System.arraycopy(weights, 0, current, 0, nFeatures);
System.arraycopy(weights, 0, proposal, 0, nFeatures);
double currentVal = current[f];
double proposalVal = currentVal + rand.nextGaussian() * mhWeightsStepSigma[f];
proposal[f] = proposalVal;
NormalDistribution prior = new NormalDistribution(0, weightSigma);
double pLogCurrent = Math.log(prior.density(currentVal));
double pLogProposal = Math.log(prior.density(proposalVal));
for (int t = 0; t < nTimes; t++) {
double [] featureVector = computeFeatureVector(t, timeToneSimplex.get(t), timeEntropy[t]);
pLogCurrent += computeLogProbMood(featureVector, current, mood[t], moodSigma);
pLogProposal += computeLogProbMood(featureVector, proposal, mood[t], moodSigma);
}
double a = Math.exp(pLogProposal - pLogCurrent);
double u = rand.nextDouble();
if (u < a) {
weights[f] = proposalVal;
nAccepted[f] += 1;
}
if (Double.isInfinite(pLogProposal)) {
System.out.println("Inf in sample weight " + f);
}
}
return nAccepted;
}
private double sampleAllWeights() {
double nAccepted = 0.0;
double [] current = new double[nFeatures];
double [] proposal = new double[nFeatures];
System.arraycopy(weights, 0, current, 0, nFeatures);
//System.arraycopy(weights, 0, proposal, 0, nFeatures);
//double currentVal = current[f];
double [][] covar = new double [nFeatures][nFeatures];
for (int f = 0; f < nFeatures; f++) {
covar[f][f] = mhOneWeightStepSigma;
}
MultivariateNormalDistribution proposalDist = new MultivariateNormalDistribution(current, covar);
proposal = proposalDist.sample();
/*
double [] means = new double[nFeatures];
for (int f = 0; f < nFeatures; f++) {
covar[f][f] = weightSigma;
}
*/
NormalDistribution prior = new NormalDistribution(0, weightSigma);
double pLogCurrent = 0.0;
double pLogProposal = 0.0;
for (int f = 0; f < nFeatures; f++) {
pLogCurrent += Math.log(prior.density(current[f]));
pLogProposal += Math.log(prior.density(proposal[f]));
}
for (int t = 0; t < nTimes; t++) {
double [] featureVector = computeFeatureVector(t, timeToneSimplex.get(t), timeEntropy[t]);
pLogCurrent += computeLogProbMood(featureVector, current, mood[t], moodSigma);
pLogProposal += computeLogProbMood(featureVector, proposal, mood[t], moodSigma);
}
double a = Math.exp(pLogProposal - pLogCurrent);
double u = rand.nextDouble();
if (u < a) {
System.arraycopy(proposal, 0, weights, 0, nFeatures);
nAccepted += 1;
}
return nAccepted;
}
private double sampleMoodSigma() {
double acceptance = 0.0;
double current = moodSigma;
double proposal = current + rand.nextGaussian() * mhMoodSigmaStep;
double pLogCurrent = 0.0;
double pLogProposal = 0.0;
if (proposal > 0) {
for (int t = 1; t < nTimes; t++) {
double [] featureVector = computeFeatureVector(t, timeToneSimplex.get(t), timeEntropy[t]);
pLogCurrent += Math.log(computeLogProbMood(featureVector, weights, mood[t], current));
pLogProposal += Math.log(computeLogProbMood(featureVector, weights, mood[t], proposal));
}
double a = Math.exp(pLogProposal - pLogCurrent);
double u = rand.nextDouble();
if (u < a) {
timeFramesRealSigma = proposal;
acceptance += 1;
}
}
return acceptance;
}
double [][] sampleQ() {
double nAccepted [][] = new double[nFramingAnnotators][nLabels];
for (int k = 0; k < nFramingAnnotators; k++) {
ArrayList<Integer> articles = framingAnnotatorArticles.get(k);
for (int j = 0; j < nLabels; j++) {
double current = q[k][j];
// transform from (0.5,1) to R and back
//double proposalReal = Math.log(-Math.log(current)) + rand.nextGaussian() * mhQSigma;
//double proposal = Math.exp(-Math.exp(proposalReal));
double proposal = current + rand.nextGaussian() * mhQSigma;
double a;
if (proposal > 0 && proposal < 1) {
/*
// using somewhat strong beta prior for now
double alpha = Transformations.betaMuGammaToAlpha(mu_q, gamma_q);
double beta = Transformations.betaMuGammaToBeta(mu_q, gamma_q);
if (alpha < 1 || beta < 1) {
System.out.println("Undesired beta parameters in Q");
alpha = Transformations.betaMuGammaToAlpha(mu_q, gamma_q);
beta = Transformations.betaMuGammaToBeta(mu_q, gamma_q);
}
BetaDistribution prior = new BetaDistribution(alpha, beta);
double pLogCurrent = prior.density(current);
double pLogProposal = prior.density(proposal);
*/
// try using a U[0,1] prior and hope initialization guides us to identifiability
double pLogCurrent = 0.0;
double pLogProposal = 0.0;
for (int article : articles) {
int frames[] = articleFrames.get(article);
HashMap<Integer, int[]> articleAnnotations = framingAnnotations.get(article);
int labels[] = articleAnnotations.get(k);
double pPosCurrent = frames[j] * current + (1 - frames[j]) * (1 - r[k][j]);
double pPosProposal = frames[j] * proposal + (1 - frames[j]) * (1 - r[k][j]);
pLogCurrent += labels[j] * Math.log(pPosCurrent) + (1 - labels[j]) * Math.log(1 - pPosCurrent);
pLogProposal += labels[j] * Math.log(pPosProposal) + (1 - labels[j]) * Math.log(1 - pPosProposal);
}
a = Math.exp(pLogProposal - pLogCurrent);
}
else {
a = -1;
}
if (Double.isNaN(a)) {
System.out.println("NaN in Q:" + current + " to " + proposal);
}
if (Double.isInfinite(a)) {
System.out.println("Inf in Q:" + current + " to " + proposal);
}
double u = rand.nextDouble();
if (u < a) {
q[k][j] = proposal;
nAccepted[k][j] += 1;
}
}
}
return nAccepted;
}
double [][] sampleR() {
double nAccepted [][] = new double[nFramingAnnotators][nLabels];
for (int k = 0; k < nFramingAnnotators; k++) {
ArrayList<Integer> articles = framingAnnotatorArticles.get(k);
for (int j = 0; j < nLabels; j++) {
double current = r[k][j];
// transform from (0.5,1) to R and back
//double proposalReal = Math.log(-Math.log((current-0.5)*2)) + rand.nextGaussian() * mhQSigma;
//double proposal = Math.exp(-Math.exp(proposalReal)) / 2 + 0.5;
double proposal = current + rand.nextGaussian() * mhRSigma;
double a;
if (proposal > 0 && proposal < 1) {
/*
// using somewhat strong beta prior for now
//BetaDistribution prior = new BetaDistribution(q_mu * q_gamma / (1 - q_mu), q_gamma);
double alpha = Transformations.betaMuGammaToAlpha(mu_q, gamma_q);
double beta = Transformations.betaMuGammaToBeta(mu_q, gamma_q);
if (alpha < 1 || beta < 1) {
System.out.println("Undesired beta parameters in R");
alpha = Transformations.betaMuGammaToAlpha(mu_q, gamma_q);
beta = Transformations.betaMuGammaToBeta(mu_q, gamma_q);
}
BetaDistribution prior = new BetaDistribution(alpha, beta);
double pLogCurrent = prior.density(current);
double pLogProposal = prior.density(proposal);
*/
double pLogCurrent = 0.0;
double pLogProposal = 0.0;
for (int article : articles) {
int frames[] = articleFrames.get(article);
HashMap<Integer, int[]> articleAnnotations = framingAnnotations.get(article);
int labels[] = articleAnnotations.get(k);
double pPosCurrent = frames[j] * q[k][j] + (1 - frames[j]) * (1 - current);
double pPosProposal = frames[j] * q[k][j] + (1 - frames[j]) * (1 - proposal);
pLogCurrent += labels[j] * Math.log(pPosCurrent) + (1 - labels[j]) * Math.log(1 - pPosCurrent);
pLogProposal += labels[j] * Math.log(pPosProposal) + (1 - labels[j]) * Math.log(1 - pPosProposal);
}
a = Math.exp(pLogProposal - pLogCurrent);
if (Double.isNaN(a)) {
System.out.println("NaN in R:" + current + " to " + proposal);
}
if (Double.isInfinite(a)) {
System.out.println("Inf in R:" + current + " to " + proposal);
}
}
else {
a = -1;
}
double u = rand.nextDouble();
if (u < a) {
r[k][j] = proposal;
nAccepted[k][j] += 1;
}
}
}
return nAccepted;
}
double [][] sampleS() {
double nAccepted [][] = new double[nToneAnnotators][nTones];
for (int k = 0; k < nToneAnnotators; k++) {
ArrayList<Integer> articles = toneAnnotatorArticles.get(k);
for (int l = 0; l < nTones; l++) {
double currentSimplex [] = sSimplex[k][l];
double currentReals [] = sReal[k][l];
MultivariateNormalDistribution multNormDist = new MultivariateNormalDistribution(currentReals, mhSCovariance);
double proposalReal [] = multNormDist.sample();
double proposalSimplex [] = Transformations.realsToSimplex(proposalReal, nTones);
double a;
if (proposalSimplex[l] > 0) {
// using pretty strong Dirichlet prior for now
double alpha[] = {1.0, 1.0, 1.0};
alpha[l] = 3;
DirichletDist prior = new DirichletDist(alpha);
double pLogCurrent = Math.log(prior.density(currentSimplex));
double pLogProposal = Math.log(prior.density(proposalSimplex));
//double pLogCurrent = 0.0;
//double pLogProposal = 0.0;
for (int article : articles) {
int tone = articleTone[article];
if (tone == l) {
HashMap<Integer, Integer> articleAnnotations = toneAnnotations.get(article);
int annotatorTone = articleAnnotations.get(k);
pLogCurrent += Math.log(currentSimplex[annotatorTone]);
pLogProposal += Math.log(proposalSimplex[annotatorTone]);
}
}
a = Math.exp(pLogProposal - pLogCurrent);
if (Double.isNaN(a)) {
System.out.println("NaN in S");
}
if (Double.isInfinite(a)) {
System.out.println("Inf in S");
}
} else {
a = -1;
}
double u = rand.nextDouble();
if (u < a) {
System.arraycopy(proposalReal, 0, sReal[k][l], 0, nTones);
System.arraycopy(proposalSimplex, 0, sSimplex[k][l], 0, nTones);
nAccepted[k][l] += 1;
}
}
}
return nAccepted;
}
private double[] recomputeGlobalMean() {
double mean[] = new double[nLabels];
// loop through all articles
for (int i = 0; i < nArticlesWithFraming; i++) {
// get the current article dist
int articleLabels[] = articleFrames.get(i);
for (int k = 0; k < nLabels; k++) {
mean[k] += (double) articleLabels[k];
}
}
for (int k = 0; k < nLabels; k++) {
mean[k] = mean[k] / (double) nArticlesWithFraming;
}
return mean;
}
/*
private double sampleTimeFramesGuassian() {
double nAccepted = 0;
// loop through all time points
for (int t = 0; t < nTimes; t++) {
// get the distribution over frames at the previous time point
double previous[];
if (t > 0) {
previous = timeFrames.get(t-1);
} else {
previous = new double[nLabels];
for (int k = 0; k < nLabels; k++) {
previous[k] = 1.0 / nLabels;
}
}
// use this to compute a distribution over the current distribution over frames
double previousDist[] = new double[nLabels];
for (int k = 0; k < nLabels; k++) {
previousDist[k] = previous[k] * nLabels * alpha + alpha0;
}
// get the current distribution over frames
double current[] = timeFrames.get(t);
// create a variable for a proposal
double proposal[] = new double[nLabels];
// get the distribution over frames in the next time point
double next[] = new double[nLabels];
if (t < nTimes-1) {
next = timeFrames.get(t + 1);
}
// generate a proposal (symmetrically)
double temp[] = new double[nLabels];
double total = 0;
for (int k = 0; k < nLabels; k++) {
temp[k] = Math.exp(Math.log(current[k]) + rand.nextGaussian() * mhTimeFrameSigma);
total += temp[k];
}
for (int k = 0; k < nLabels; k++) {
proposal[k] = temp[k] / total;
}
/ *
// compute a distribution for generating a proposal
double mhProposalDist[] = new double[nLabels];
for (int k = 0; k < nLabels; k++) {
mhProposalDist[k] = mhDirichletScale * current[k] + mhDirichletBias;
}
// generate a point from this distribution
DirichletGen.nextPoint(randomStream, mhProposalDist, proposal);
// evaluate the probability of generating this new point from the proposal
DirichletDist dirichletDist = new DirichletDist(mhProposalDist);
double mhpProposal = dirichletDist.density(proposal);
// compute the probability of the generating the current point from the proposal
double reverseDist[] = new double[nLabels];
for (int k = 0; k < nLabels; k++) {
reverseDist[k] = mhDirichletScale * proposal[k] + mhDirichletBias;
}
DirichletDist dirichletDistReverse = new DirichletDist(reverseDist);
double mhpReverse = dirichletDist.density(current);
* /
// compute a distribution over a new distribution over frames for the current distribution
double currentDist[] = new double[nLabels];
for (int k = 0; k < nLabels; k++) {
currentDist[k] = current[k] * nLabels * alpha + alpha0;
}
// do the same for the proposal
double proposalDist[] = new double[nLabels];
for (int k = 0; k < nLabels; k++) {
proposalDist[k] = proposal[k] * nLabels * alpha + alpha0;
}
// compute the probability of the current distribution over frames conditioned on the previous
DirichletDist dirichletDistPrevious = new DirichletDist(previousDist);
double pCurrentGivenPrev = dirichletDistPrevious.density(current);
double pProposalGivenPrev = dirichletDistPrevious.density(proposal);
// do the same for the next time point conditioned on the current and proposal
DirichletDist dirichletDistCurrent = new DirichletDist(currentDist);
double pNextGivenCurrent = dirichletDistCurrent.density(next);
DirichletDist dirichletDistProposal = new DirichletDist(proposalDist);
double pNextGivenProposal = dirichletDistProposal.density(next);
double pLogCurrent = Math.log(pCurrentGivenPrev);
if (t < t-1) {
pLogCurrent += Math.log(pNextGivenCurrent);
}
double pLogProposal = Math.log(pProposalGivenPrev);
if (t < t-1) {
pLogProposal += Math.log(pNextGivenProposal);
}
double beta = betas.get(t);
// compute distributions over distributions for articles
double currentDistArticle[] = new double[nLabels];
for (int k = 0; k < nLabels; k++) {
currentDistArticle[k] = current[k] * nLabels * beta + beta0;
}
DirichletDist dirichletDistArticleCurrent = new DirichletDist(currentDistArticle);
double proposalDistArticle[] = new double[nLabels];
for (int k = 0; k < nLabels; k++) {
proposalDistArticle[k] = proposal[k] * nLabels * beta + beta0;
}
DirichletDist dirichletDistArticleProposal = new DirichletDist(proposalDistArticle);
// compute the probability of the article disrtibutions for both current and proposal
ArrayList<Integer> articles = timeArticles.get(t);
for (int i : articles) {
double articleDist[] = articleFrames.get(i);
double pArticleCurrent = dirichletDistArticleCurrent.density(articleDist);
pLogCurrent += Math.log(pArticleCurrent);
double pArticleProposal= dirichletDistArticleProposal.density(articleDist);
pLogProposal += Math.log(pArticleProposal);
}
double a = Math.exp(pLogProposal - pLogCurrent);
double u = rand.nextDouble();
if (u < a) {
timeFrames.set(t, proposal);
nAccepted += 1;
}
}
return nAccepted / nTimes;
}
*/
}
| src/CombinedModel.java | import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.nio.file.Paths;
import java.nio.file.Path;
import java.util.*;
import org.apache.commons.math3.distribution.BetaDistribution;
import org.apache.commons.math3.distribution.NormalDistribution;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import umontreal.ssj.probdistmulti.DirichletDist;
import umontreal.ssj.rng.*;
import org.apache.commons.math3.distribution.MultivariateNormalDistribution;
import org.apache.commons.math3.analysis.function.Sigmoid;
public class CombinedModel {
private int nArticlesWithFraming;
private int nArticlesWithTone;
private int nFramingAnnotators;
private int nToneAnnotators;
private int nTimes;
private int nNewspapers;
private static int nLabels = 15;
private static int nTones = 3;
private static int firstYear = 1990;
private static int firstQuarter = 0;
private static int nMonthsPerYear = 12;
private static int nQuartersPerYear = 4;
private static int nMonthsPerQuarter = 3;
private static int nFeatures = 7;
private Set<String> irrelevantArticles;
private Set<String> trainingArticles;
private HashMap<String, Integer> newspaperIndices;
private HashMap<String, Integer> articleNameTime;
private HashMap<String, Integer> articleNameNewspaper;
private HashMap<Integer, Integer> framingArticleTime;
private HashMap<Integer, Integer> toneArticleTime;
private HashMap<Integer, Integer> framingArticleNewspaper;
private HashMap<Integer, Integer> toneArticleNewspaper;
private HashMap<Integer, ArrayList<Integer>> timeFramingArticles;
private HashMap<Integer, ArrayList<Integer>> timeToneArticles;
private HashMap<String, Integer> framingAnnotatorIndices;
private HashMap<String, Integer> toneAnnotatorIndices;
private HashMap<Integer, ArrayList<Integer>> framingAnnotatorArticles;
private HashMap<Integer, ArrayList<Integer>> toneAnnotatorArticles;
private ArrayList<String> framingArticleNames;
private ArrayList<String> toneArticleNames;
private ArrayList<HashMap<Integer, int[]>> framingAnnotations;
private ArrayList<HashMap<Integer, Integer>> toneAnnotations;
private ArrayList<double[]> timeFramesReals; // phi
private ArrayList<double[]> timeFramesCube;
private ArrayList<int[]> articleFrames ; // theta
private double[] timeEntropy;
private ArrayList<double[]> timeToneReals; // phi
private ArrayList<double[]> timeToneSimplex;
private int[] articleTone ;
private double[][] q; // framing sensitivity
private double[][] r; // framing specificity
private double[][][] sSimplex; // combined equivalent of sens / spec for tone
private double[][][] sReal;
private double[] weights;
private double[] framesMean;
private double[] tonesMean;
private double[] globalMean;
private double[] mood;
private double[] nArticlesAtTime;
private double timeFramesRealSigma = 0.01;
private double timeToneRealSigma = 0.01;
private double weightSigma = 5.0;
private double moodSigma = 0.25;
// Metropolis-Hastings step parameters
private static double mhTimeFramesStepSigma = 0.05 ;
private static double mhTimeFramesRealSigmaStep = 0.005;
private static double mhTimeToneStepSigma = 0.1 ;
private static double mhTimeToneRealSigmaStep = 0.01;
private static double [] mhWeightsStepSigma = {0.05, 0.1, 0.2, 0.2, 0.5, 0.01, 0.05};
private static double mhOneWeightStepSigma = 0.0001;
private static double mhQSigma = 0.05;
private static double mhRSigma = 0.02;
private static double mhSSigma = 0.01;
private static double [][] mhSCovariance = {{mhSSigma, 0, 0}, {0, mhSSigma, 0}, {0, 0, mhSSigma}};
private static double mhMoodSigmaStep = 0.01;
private static Random rand = new Random();
private static RandomStream randomStream = new MRG32k3a();
private static Sigmoid sigmoid = new Sigmoid();
public CombinedModel(String inputFilename, String metadataFilename, String predictionsFilename, String moodFilename,
boolean normalizeStoriesAtTime, boolean normalizeMood) throws Exception {
Path inputPath = Paths.get(inputFilename);
JSONParser parser = new JSONParser();
JSONObject data = (JSONObject) parser.parse(new FileReader(inputPath.toString()));
Path metadataPath = Paths.get(metadataFilename);
JSONObject metadata = (JSONObject) parser.parse(new FileReader(metadataPath.toString()));
// index newspapers
Set<String> newspapers = gatherNewspapers(metadata);
nNewspapers = newspapers.size();
System.out.println(nNewspapers + " newspapers");
newspaperIndices = new HashMap<>();
int n = 0;
for (String newspaper : newspapers) {
newspaperIndices.put(newspaper, n++);
}
// record the time and paper of each article
articleNameTime = new HashMap<>();
articleNameNewspaper = new HashMap<>();
nTimes = 0;
for (Object articleName : metadata.keySet()) {
JSONObject articleMetadata = (JSONObject)metadata.get(articleName);
String source = (String) articleMetadata.get("source");
int year = ((Long) articleMetadata.get("year")).intValue();
int month = ((Long) articleMetadata.get("month")).intValue() - 1;
//int quarter = (int) Math.floor((double) month / (double) nMonthsPerQuarter);
//int time = (year - firstYear) * nQuartersPerYear + quarter;
int time = yearAndMonthToTime(year, month);
if (time >= 0) {
articleNameTime.put(articleName.toString(), time);
articleNameNewspaper.put(articleName.toString(), newspaperIndices.get(source));
}
if (time >= nTimes) {
nTimes = time + 1;
}
}
System.out.println(nTimes + " time periods");
// record the total number of articles at each time step
nArticlesAtTime = new double[nTimes];
for (int time : articleNameTime.values()) {
nArticlesAtTime[time] += 1;
}
// normalize nArticles
double nMax = 0;
for (int t = 0; t < nTimes; t++) {
nMax = Math.max(nMax, nArticlesAtTime[t]);
}
if (normalizeStoriesAtTime) {
for (int t = 0; t < nTimes; t++) {
nArticlesAtTime[t] = nArticlesAtTime[t] / nMax;
}
}
// intialize some empty arrays
timeFramingArticles = new HashMap<>();
for (int t = 0; t < nTimes; t++) {
timeFramingArticles.put(t, new ArrayList<>());
}
timeToneArticles = new HashMap<>();
for (int t = 0; t < nTimes; t++) {
timeToneArticles.put(t, new ArrayList<>());
}
// determine the relevant articles based on annotations
irrelevantArticles = getIrrelevantArticles(data);
// index annotators
Set<String> framingAnnotators = gatherFramingAnnotators(data);
nFramingAnnotators= framingAnnotators.size();
Set<String> toneAnnotators = gatherToneAnnotators(data);
nToneAnnotators = toneAnnotators.size();
System.out.println(nFramingAnnotators + " framing annotators");
System.out.println(nToneAnnotators + " tone annotators");
framingAnnotatorIndices = new HashMap<>();
toneAnnotatorIndices = new HashMap<>();
framingAnnotatorArticles = new HashMap<>();
toneAnnotatorArticles = new HashMap<>();
int k = 0;
for (String annotator : framingAnnotators) {
framingAnnotatorIndices.put(annotator, k);
framingAnnotatorArticles.put(k, new ArrayList<>());
k += 1;
}
System.out.println(framingAnnotatorIndices);
k = 0;
for (String annotator : toneAnnotators) {
toneAnnotatorIndices.put(annotator, k);
toneAnnotatorArticles.put(k, new ArrayList<>());
k += 1;
}
System.out.println(toneAnnotatorIndices);
// read in the annotations and build up all relevant information
trainingArticles = new HashSet<>();
framingArticleNames = new ArrayList<>();
toneArticleNames = new ArrayList<>();
framingArticleTime = new HashMap<>();
toneArticleTime = new HashMap<>();
framingArticleNewspaper = new HashMap<>();
toneArticleNewspaper = new HashMap<>();
framingAnnotations = new ArrayList<>();
toneAnnotations = new ArrayList<>();
framesMean = new double[nLabels];
tonesMean = new double[nTones];
int framingCount = 0;
int toneCount = 0;
for (Object articleName : data.keySet()) {
// check if this article is in the list of valid articles
if (articleNameTime.containsKey(articleName.toString())) {
if (!irrelevantArticles.contains(articleName.toString())) {
JSONObject article = (JSONObject) data.get(articleName);
JSONObject annotationsJson = (JSONObject) article.get("annotations");
JSONObject articleFramingAnnotations = (JSONObject) annotationsJson.get("framing");
JSONObject articleToneAnnotations = (JSONObject) annotationsJson.get("tone");
// make sure this article has annotations
if (articleFramingAnnotations.size() > 0) {
// get a new article id (i)
int i = framingArticleNames.size();
// store the article name for future reference
framingArticleNames.add(articleName.toString());
// get the timestep for this article (by name)
int time = articleNameTime.get(articleName.toString());
framingArticleTime.put(i, time);
// get the newspaper for this article (by name)
framingArticleNewspaper.put(i, articleNameNewspaper.get(articleName.toString()));
// create a hashmap to store the annotations for this article
HashMap<Integer, int[]> articleAnnotations = new HashMap<>();
// loop through the annotators for this article
for (Object annotator : articleFramingAnnotations.keySet()) {
// for each one, create an array to hold the annotations, and set to zero
int annotationArray[] = new int[nLabels];
// get the anntoator name and index
String parts[] = annotator.toString().split("_");
int annotatorIndex = framingAnnotatorIndices.get(parts[0]);
// loop through this annotator's annotations
JSONArray annotatorAnnotations = (JSONArray) articleFramingAnnotations.get(annotator);
for (Object annotation : annotatorAnnotations) {
// get the code
double realCode = (Double) ((JSONObject) annotation).get("code");
// subtract 1 for zero-based indexing
int code = (int) Math.round(realCode) - 1;
// record this code as being present
annotationArray[code] = 1;
}
// store the annotations for this annotator
articleAnnotations.put(annotatorIndex, annotationArray);
framingAnnotatorArticles.get(annotatorIndex).add(i);
for (int j = 0; j < nLabels; j++) {
framesMean[j] += (double) annotationArray[j];
}
framingCount += 1;
}
// store the annotations for this article
framingAnnotations.add(articleAnnotations);
timeFramingArticles.get(time).add(i);
}
if (articleToneAnnotations.size() > 0) {
// get a new article id (i)
int i = toneArticleNames.size();
// store the article name for future reference
toneArticleNames.add(articleName.toString());
// get the timestep for this article (by name)
int time = articleNameTime.get(articleName.toString());
toneArticleTime.put(i, time);
// get the newspaper for this article (by name)
toneArticleNewspaper.put(i, articleNameNewspaper.get(articleName.toString()));
// create a hashmap to store the annotations for this article
HashMap<Integer, Integer> articleAnnotations = new HashMap<>();
// only take one annotation for the tone, as they should all be the same
int randAnnotator = rand.nextInt(articleToneAnnotations.size());
int aCount = 0;
for (Object annotator : articleToneAnnotations.keySet()) {
// for each one, prepare to hold the tone annotation
int toneAnnotation = 0;
// get the anntoator name and index
String parts[] = annotator.toString().split("_");
int annotatorIndex = toneAnnotatorIndices.get(parts[0]);
// loop through this annotator's annotations (should be only 1)
JSONArray annotatorAnnotations = (JSONArray) articleToneAnnotations.get(annotator);
for (Object annotation : annotatorAnnotations) {
// get the code
double realCode = (Double) ((JSONObject) annotation).get("code");
// subtract 17 for zero-based indexing
toneAnnotation = (int) Math.round(realCode) - 17;
}
// store the annotations for this annotator
if (aCount == randAnnotator) {
articleAnnotations.put(annotatorIndex, toneAnnotation);
toneAnnotatorArticles.get(annotatorIndex).add(i);
tonesMean[toneAnnotation] += 1.0;
toneCount += 1;
}
aCount += 1;
}
// store the annotations for this article
toneAnnotations.add(articleAnnotations);
timeToneArticles.get(time).add(i);
}
}
}
}
System.out.println(toneCount + " tone annotations used");
// read in predictions and add to annotations
Scanner scanner = new Scanner(new File(predictionsFilename));
HashMap<String, int[]> framingPredictions = new HashMap<>();
HashMap<String, Integer> tonePredictions = new HashMap<>();
scanner.useDelimiter(",");
// skip the header
for (int i = 0; i < 19; i++) {
String next = scanner.next();
next = "";
}
String rowArticleName = "";
int[] pArray = new int[nLabels];
int tVal = 0;
int iNext = 0;
int isTrain = 0;
while (scanner.hasNext()) {
String next = scanner.next();
int j = iNext % 19;
//System.out.println(j + " " + next);
if (j == 1) {
rowArticleName = next;
}
if (j == 2) {
if (Integer.parseInt(next) > 0) {
trainingArticles.add(rowArticleName);
}
}
else if (j > 2 && j < 18) {
pArray[j-3] = Integer.parseInt(next);
}
else if (j == 18) {
tVal = Integer.parseInt(next);
framingPredictions.put(rowArticleName, pArray);
tonePredictions.put(rowArticleName, tVal);
pArray = new int[nLabels];
}
iNext += 1;
}
//Do not forget to close the scanner
scanner.close();
// incorporate the predictions into the annotations
int annotatorIndex = nFramingAnnotators;
framingAnnotatorArticles.put(annotatorIndex, new ArrayList<>());
for (String articleName : framingPredictions.keySet()) {
// check if this article is in the list of valid articles
if (articleNameTime.containsKey(articleName)) {
if (!irrelevantArticles.contains(articleName)) {
//JSONObject article = (JSONObject) data.get(articleName);
if (framingArticleNames.contains(articleName)) {
if (!trainingArticles.contains(articleName)) {
// add the prediction to the set of new annotations
// get the article ID
int i = framingArticleNames.indexOf(articleName);
// create a hashmap to store the annotations for this article
HashMap<Integer, int[]> articleAnnotations = framingAnnotations.get(i);
// treat predictions as coming from a separate annotator
articleAnnotations.put(annotatorIndex, framingPredictions.get(articleName));
// store the annotations for this article
framingAnnotations.set(i, articleAnnotations);
// if this is not a training article, use it to estimate classifier properties
framingAnnotatorArticles.get(annotatorIndex).add(i);
}
} else {
// add information for a new article
// get a new article id (i)
int i = framingArticleNames.size();
// store the article name for future reference
framingArticleNames.add(articleName);
// get the timestep for this article (by name)
int time = articleNameTime.get(articleName);
framingArticleTime.put(i, time);
// get the newspaper for this article (by name)
framingArticleNewspaper.put(i, articleNameNewspaper.get(articleName));
// create a hashmap to store the annotations for this article
HashMap<Integer, int[]> articleAnnotations = new HashMap<>();
// treat predictions as coming from a separate anntoator
// loop through this annotator's annotations
articleAnnotations.put(annotatorIndex, framingPredictions.get(articleName));
// also use these unannotated articles for estimation of classifier properties
framingAnnotatorArticles.get(annotatorIndex).add(i);
//for (int j = 0; j < nLabels; j++) {
// framesMean[j] += (double) framingPredictions.get(articleName)[j];
//}
// store the annotations for this article
framingAnnotations.add(articleAnnotations);
timeFramingArticles.get(time).add(i);
//framingCount += 1;
}
}
}
}
nFramingAnnotators += 1;
System.out.println(framingAnnotations.size() + " articles with framing annotations");
for (k = 0; k < nFramingAnnotators; k++) {
System.out.println("Annotator: " + k + "; annotations: " + framingAnnotatorArticles.get(k).size());
}
System.out.println(toneAnnotations.size() + " articles with tone annotations");
for (k = 0; k < nToneAnnotators; k++) {
System.out.println("Annotator: " + k + "; annotations: " + toneAnnotatorArticles.get(k).size());
}
/*
// Try using all articles
// treat the predictions as a new anntotator
int annotatorIndex = nFramingAnnotators;
framingAnnotatorArticles.put(annotatorIndex, new ArrayList<>());
for (String articleName : framingPredictions.keySet()) {
// check if this article is in the list of valid articles
if (articleNameTime.containsKey(articleName)) {
if (framingArticleNames.contains(articleName)) {
// get the article ID
int i = framingArticleNames.indexOf(articleName);
// create a hashmap to store the annotations for this article
HashMap<Integer, int[]> articleAnnotations = framingAnnotations.get(i);
// treat predictions as coming from a separate annotator
articleAnnotations.put(annotatorIndex, framingPredictions.get(articleName));
framingAnnotatorArticles.get(annotatorIndex).add(i);
// store the annotations for this article
framingAnnotations.set(i, articleAnnotations);
}
}
}
nFramingAnnotators += 1;
*/
// treat the predictions as a new anntotator
annotatorIndex = nToneAnnotators;
toneAnnotatorArticles.put(annotatorIndex, new ArrayList<>());
for (String articleName : tonePredictions.keySet()) {
// check if this article is in the list of valid articles
if (articleNameTime.containsKey(articleName)) {
if (!irrelevantArticles.contains(articleName)) {
if (toneArticleNames.contains(articleName)) {
if (!trainingArticles.contains(articleName)) {
// get the article ID
int i = toneArticleNames.indexOf(articleName);
// create a hashmap to store the annotations for this article
HashMap<Integer, Integer> articleAnnotations = toneAnnotations.get(i);
// treat predictions as coming from a separate annotator
articleAnnotations.put(annotatorIndex, tonePredictions.get(articleName));
// store the annotations for this article
toneAnnotations.set(i, articleAnnotations);
// as above
toneAnnotatorArticles.get(annotatorIndex).add(i);
}
} else {
// add information for a new article
// get a new article id (i)
int i = toneArticleNames.size();
// store the article name for future reference
toneArticleNames.add(articleName);
// get the timestep for this article (by name)
int time = articleNameTime.get(articleName);
toneArticleTime.put(i, time);
// get the newspaper for this article (by name)
toneArticleNewspaper.put(i, articleNameNewspaper.get(articleName));
// create a hashmap to store the annotations for this article
HashMap<Integer, Integer> articleAnnotations = new HashMap<>();
// treat predictions as coming from a separate anntoator
// loop through this annotator's annotations
Integer tonePrediction = tonePredictions.get(articleName);
articleAnnotations.put(annotatorIndex, tonePrediction);
// as above
toneAnnotatorArticles.get(annotatorIndex).add(i);
//tonesMean[tonePrediction] += 1.0;
// store the annotations for this article
toneAnnotations.add(articleAnnotations);
timeToneArticles.get(time).add(i);
//toneCount += 1;
}
}
}
}
nToneAnnotators += 1;
System.out.println(framingAnnotations.size() + " articles with tone annotations");
// get the mean of the annotations as a sanity check
for (int j = 0; j < nLabels; j++) {
framesMean[j] = framesMean[j] / (double) framingCount;
}
for (int j = 0; j < nTones; j++) {
tonesMean[j] = tonesMean[j] / (double) toneCount;
}
nArticlesWithFraming = framingAnnotations.size();
nArticlesWithTone = toneAnnotations.size();
System.out.println("Mean of annotations:");
for (int j = 0; j < nLabels; j++) {
System.out.print(framesMean[j] + " ");
}
System.out.println("Mean of tone annotations:");
for (int j = 0; j < nTones; j++) {
System.out.print(tonesMean[j] + " ");
}
System.out.println("");
// read in mood data
mood = new double[nTimes];
scanner = new Scanner(new File(moodFilename));
scanner.useDelimiter(",");
// skip the header
for (int i = 0; i < 6; i++) {
String next = scanner.next();
}
int year = 0;
int quarter = 0;
double moodVal = 0;
iNext = 0;
while (scanner.hasNext()) {
String next = scanner.next();
int j = iNext % 6;
if (j == 1) {
year = Integer.parseInt(next);
}
else if (j == 2) {
quarter = Integer.parseInt(next)-1;
}
else if (j == 3) {
if (normalizeMood) {
// normalize mood to be in the range (-1, 1)
moodVal = Double.parseDouble(next) / 100.0;
} else {
moodVal = Double.parseDouble(next);
}
}
else if (j == 5) {
int time = yearAndQuarterToTime(year, quarter);
if (time >= 0 && time < nTimes) {
mood[time] = moodVal;
}
}
iNext += 1;
}
//Do not forget to close the scanner
scanner.close();
// save mood data
Path output_path;
output_path = Paths.get("samples", "mood.csv");
try (FileWriter file = new FileWriter(output_path.toString())) {
for (int t = 0; t < nTimes; t++) {
file.write(mood[t] + ",");
}
}
// display mood data
/*
for (int t = 0; t < nTimes; t++) {
//quarter = t % nQuartersPerYear;
//year = (t - quarter) / nQuartersPerYear + firstYear;
int nFramingArticles = timeFramingArticles.get(t).size();
int nToneArticles = timeToneArticles.get(t).size();
double yearQuarter = timeToYearAndQuarter(t);
//System.out.println(yearQuarter + " : " + nFramingArticles + ", " + nToneArticles);
//System.out.println(yearQuarter + " : " + mood[t]);
}
*/
initialize();
}
private int yearAndMonthToTime(int year, int month) {
int quarter = (int) Math.floor((double) month / (double) nMonthsPerQuarter);
return yearAndQuarterToTime(year, quarter);
}
private int yearAndQuarterToTime(int year, int quarter) {
return (year - firstYear) * nQuartersPerYear + quarter - firstQuarter;
}
private double timeToYearAndQuarter(int time) {
return (double) (time + firstQuarter) / (double) nQuartersPerYear + firstYear;
}
private Set<String> gatherNewspapers(JSONObject metadata) {
/*
Read in the metadata and build up the set of newspapers for valid articles
*/
Set <String> newspapers = new HashSet<>();
for (Object key : metadata.keySet()) {
JSONObject articleMetadata = (JSONObject)metadata.get(key);
String source = (String) articleMetadata.get("source");
int year = ((Long) articleMetadata.get("year")).intValue();
if (year >= firstYear) {
newspapers.add(source);
}
}
return newspapers;
}
private Set<String> getIrrelevantArticles(JSONObject data) {
Set<String> irrelevantArticles = new HashSet<>();
for (Object articleName : data.keySet()) {
// check if this article is in the list of valid articles
if (articleNameTime.containsKey(articleName.toString())) {
boolean relevant = true;
JSONObject article = (JSONObject) data.get(articleName);
JSONObject annotations = (JSONObject) article.get("annotations");
JSONObject relevanceJudgements = (JSONObject) annotations.get("irrelevant");
for (Object annotator : relevanceJudgements.keySet()) {
boolean irrelevant = (boolean) relevanceJudgements.get(annotator);
if (irrelevant) {
relevant = false;
}
}
if (!relevant) {
irrelevantArticles.add(articleName.toString());
}
}
}
return irrelevantArticles;
}
private Set<String> gatherFramingAnnotators(JSONObject data) {
/*
Read in the data and build up the set of annotators for valid articles
*/
Set<String> annotators = new HashSet<>();
for (Object articleName : data.keySet()) {
// check if this article is in the list of valid articles
if (articleNameTime.containsKey(articleName.toString())) {
if (!irrelevantArticles.contains(articleName.toString())) {
JSONObject article = (JSONObject) data.get(articleName);
JSONObject annotations = (JSONObject) article.get("annotations");
JSONObject framingAnnotations = (JSONObject) annotations.get("framing");
for (Object annotator : framingAnnotations.keySet()) {
String parts[] = annotator.toString().split("_");
annotators.add(parts[0]);
}
}
}
}
return annotators;
}
private Set<String> gatherToneAnnotators(JSONObject data) {
/*
Read in the data and build up the set of annotators for valid articles
*/
Set<String> annotators = new HashSet<>();
for (Object articleName : data.keySet()) {
// check if this article is in the list of valid articles
if (articleNameTime.containsKey(articleName.toString())) {
if (!irrelevantArticles.contains(articleName.toString())) {
JSONObject article = (JSONObject) data.get(articleName);
JSONObject annotations = (JSONObject) article.get("annotations");
JSONObject framingAnnotations = (JSONObject) annotations.get("tone");
for (Object annotator : framingAnnotations.keySet()) {
String parts[] = annotator.toString().split("_");
annotators.add(parts[0]);
}
}
}
}
return annotators;
}
private void initialize() {
// initialize article frames based on annotations
articleFrames = new ArrayList<>();
for (int i = 0; i < nArticlesWithFraming; i++) {
int initialLabels[] = new int[nLabels];
double annotationCounts[] = new double[nLabels];
// add the contributions of each annotator
HashMap<Integer, int[]> articleAnnotations = framingAnnotations.get(i);
double nAnnotators = (double) articleAnnotations.size();
for (int annotator : articleAnnotations.keySet()) {
int annotatorAnnotations[] = articleAnnotations.get(annotator);
for (int j = 0; j < nLabels; j++) {
annotationCounts[j] += (double) annotatorAnnotations[j] / nAnnotators;
}
}
for (int j = 0; j < nLabels; j++) {
double u = rand.nextDouble();
if (u < annotationCounts[j]) {
initialLabels[j] = 1;
}
}
articleFrames.add(initialLabels);
}
// initialize article tones based on annotations
articleTone = new int[nArticlesWithTone];
for (int i = 0; i < nArticlesWithTone; i++) {
double annotationCounts[] = new double[nTones];
// add the contributions of each annotator
HashMap<Integer, Integer> articleAnnotations = toneAnnotations.get(i);
double nAnnotators = (double) articleAnnotations.size();
for (int annotator : articleAnnotations.keySet()) {
int annotatorTone = articleAnnotations.get(annotator);
annotationCounts[annotatorTone] += 1.0 / nAnnotators;
}
MultinomialDistribution multinomialDistribution = new MultinomialDistribution(annotationCounts, nTones);
int initialTone = multinomialDistribution.sample(rand);
articleTone[i] = initialTone;
}
// initialize timeFrames as the mean of the corresponding articles (+ global mean)
timeFramesReals = new ArrayList<>();
timeFramesCube = new ArrayList<>();
timeToneReals = new ArrayList<>();
timeToneSimplex = new ArrayList<>();
timeEntropy = new double[nTimes];
for (int t = 0; t < nTimes; t++) {
double timeFramesMean[] = new double[nLabels];
double timeFramesMeanReals[] = new double[nLabels];
// initialize everything with the global mean
ArrayList<Integer> articles = timeFramingArticles.get(t);
double nTimeFramingArticles = (double) articles.size();
for (int j = 0; j < nLabels; j++) {
timeFramesMean[j] += framesMean[j] / (nTimeFramingArticles + 1);
}
for (int i : articles) {
int frames[] = articleFrames.get(i);
for (int j = 0; j < nLabels; j++) {
timeFramesMean[j] += (double) frames[j] / (nTimeFramingArticles + 1);
}
}
timeFramesMeanReals = Transformations.cubeToReals(timeFramesMean, nLabels);
timeFramesCube.add(timeFramesMean);
timeFramesReals.add(timeFramesMeanReals);
timeEntropy[t] = computeEntropy(timeFramesMean);
double timeTonesMeanSimplex[] = new double[nTones];
// initialize everything with the global mean
articles = timeToneArticles.get(t);
double nTimeToneArticles = (double) articles.size();
for (int j = 0; j < nTones; j++) {
timeTonesMeanSimplex[j] += tonesMean[j] / (nTimeToneArticles + 1);
}
for (int i : articles) {
int tone = articleTone[i];
timeTonesMeanSimplex[tone] += 1.0 / (nTimeToneArticles + 1);
}
double timeTonesMeanReals[] = Transformations.simplexToReals(timeTonesMeanSimplex, nTones);
timeToneSimplex.add(timeTonesMeanSimplex);
timeToneReals.add(timeTonesMeanReals);
}
System.out.println("");
// initialize annotator parameters to reasonable values
q = new double[nFramingAnnotators][nLabels];
r = new double[nFramingAnnotators][nLabels];
for (int k = 0; k < nFramingAnnotators; k++) {
for (int j = 0; j < nLabels; j++) {
q[k][j] = 0.8;
r[k][j] = 0.8;
}
}
double priorCorrect = 0.8;
sSimplex = new double[nToneAnnotators][nTones][nTones];
sReal = new double[nToneAnnotators][nTones][nTones];
for (int k = 0; k < nToneAnnotators; k++) {
for (int j = 0; j < nTones; j++) {
for (int j2 = 0; j2 < nTones; j2++) {
if (j == j2) {
sSimplex[k][j][j2] = priorCorrect;
} else {
sSimplex[k][j][j2] = (1.0 - priorCorrect) / (nTones - 1);
}
}
sReal[k][j] = Transformations.simplexToReals(sSimplex[k][j], nTones);
}
}
// initialize weights
weights = new double[nFeatures];
/*
weights[0] = 0.18;
weights[1] = 0.82;
weights[2] = 0.0;
weights[3] = 2.0;
weights[4] = 1.1;
weights[5] = 0.0;
weights[6] = -0.3;
*/
}
void run(int nIter, int burnIn, int samplingPeriod, int printPeriod) throws Exception {
int nSamples = (int) Math.floor((nIter - burnIn) / (double) samplingPeriod);
System.out.println("Collecting " + nSamples + " samples");
double timeFrameSamples [][][] = new double[nSamples][nTimes][nLabels];
int articleFrameSamples [][][] = new int[nSamples][nArticlesWithFraming][nLabels];
double timeFrameRealSigmaSamples [] = new double[nSamples];
double timeToneSamples [][][] = new double[nSamples][nTimes][nLabels];
int articleToneSamples [][] = new int[nSamples][nArticlesWithTone];
double timeToneRealSigmaSamples [] = new double[nSamples];
double weightSamples [][] = new double[nSamples][nFeatures];
double qSamples [][][] = new double[nSamples][nFramingAnnotators][nLabels];
double rSamples [][][] = new double[nSamples][nFramingAnnotators][nLabels];
double sSamples [][][][] = new double[nSamples][nToneAnnotators][nTones][nTones];
double entropySamples [][] = new double[nSamples][nTimes];
double moodSamples[][] = new double[nSamples][nTimes];
double moodSigmaSamples[] = new double[nSamples];
double timeFrameRate = 0.0;
double articleFramesRate = 0;
double timeTonesRate = 0.0;
double articleToneRates = 0.0;
double timeFramesSigmaRate = 0;
double timeToneSigmaRate = 0;
double [] weightRate = new double[nFeatures];
double oneWeightRate = 0.0;
double [][] qRate = new double[nFramingAnnotators][nLabels];
double [][] rRate = new double[nFramingAnnotators][nLabels];
double [][] sRate = new double[nToneAnnotators][nTones];
double moodSigmaRate = 0.0;
int sample = 0;
int i = 0;
while (sample < nSamples) {
timeFrameRate += sampleTimeFrames();
sampleArticleFrames();
timeFramesSigmaRate += sampleTimeFramesRealSigma();
timeTonesRate += sampleTimeTones();
sampleArticleTones();
timeToneSigmaRate += sampleTimeToneRealSigma();
double [] weightAcceptances = sampleWeights();
for (int f = 0; f < nFeatures; f++) {
weightRate[f] += (double) weightAcceptances[f];
}
//oneWeightRate += sampleAllWeights();
//moodSigmaRate += sampleMoodSigma();
double [][] qAcceptances = sampleQ();
for (int k = 0; k < nFramingAnnotators; k++) {
for (int j = 0; j < nLabels; j++) {
qRate[k][j] += qAcceptances[k][j];
}
}
double [][] rAcceptances = sampleR();
for (int k = 0; k < nFramingAnnotators; k++) {
for (int j = 0; j < nLabels; j++) {
rRate[k][j] += rAcceptances[k][j];
}
}
double [][] sAcceptances = sampleS();
for (int k = 0; k < nToneAnnotators; k++) {
for (int j = 0; j < nTones; j++) {
sRate[k][j] += sAcceptances[k][j];
}
}
//globalMean = recomputeGlobalMean();
// save samples
if (i > burnIn && i % samplingPeriod == 0) {
for (int t = 0; t < nTimes; t++) {
System.arraycopy(timeFramesCube.get(t), 0, timeFrameSamples[sample][t], 0, nLabels);
}
for (int t = 0; t < nTimes; t++) {
System.arraycopy(timeToneSimplex.get(t), 0, timeToneSamples[sample][t], 0, nTones);
}
timeFrameRealSigmaSamples[sample] = timeFramesRealSigma;
timeToneRealSigmaSamples[sample] = timeToneRealSigma;
for (int f = 0; f < nFeatures; f++) {
System.arraycopy(weights, 0, weightSamples[sample], 0, nFeatures);
}
/*
for (int a = 0; a < nArticlesWithFraming; a++) {
System.arraycopy(articleFrames.get(a), 0, articleFrameSamples[sample][a], 0, nLabels);
}
System.arraycopy(articleTone, 0, articleToneSamples[sample], 0, nArticlesWithTone);
*/
moodSigmaSamples[sample] = moodSigma;
for (int k = 0; k < nFramingAnnotators; k++) {
System.arraycopy(q[k], 0, qSamples[sample][k], 0, nLabels);
System.arraycopy(r[k], 0, rSamples[sample][k], 0, nLabels);
}
for (int k = 0; k < nToneAnnotators; k++) {
for (int l = 0; l < nTones; l++) {
System.arraycopy(sSimplex[k][l], 0, sSamples[sample][k][l], 0, nTones);
}
}
System.arraycopy(timeEntropy, 0, entropySamples[sample], 0, nTimes);
for (int t = 0; t < nTimes; t++) {
double [] featureVector = computeFeatureVector(t, timeToneSimplex.get(t), timeEntropy[t]);
double moodMean = 0.0;
for (int f = 0; f < nFeatures; f++) {
moodMean += featureVector[f] * weights[f];
}
moodSamples[sample][t] = moodMean;
}
sample += 1;
}
i += 1;
if (i % printPeriod == 0) {
System.out.print(i + ": ");
for (int f = 0; f < nFeatures; f++) {
System.out.print(weights[f] + " ");
}
//for (int k = 0; k < nLabels; k++) {
// System.out.print(globalMean[k] + " ");
//}
System.out.print("\n");
}
}
// Display acceptance rates
System.out.println(timeFrameRate / i);
System.out.println(timeFramesSigmaRate / i);
System.out.println(timeTonesRate / i);
System.out.println(timeToneSigmaRate / i);
System.out.println(moodSigmaRate / i);
System.out.println("weight rates");
for (int f = 0; f < nFeatures; f++) {
System.out.println(weightRate[f] / i);
}
//System.out.println("weight rates: " + oneWeightRate / i);
System.out.println(articleFramesRate / i);
System.out.println(articleToneRates / i);
System.out.println("Q rates");
for (int k = 0; k < nFramingAnnotators; k++) {
for (int j = 0; j < nLabels; j++) {
System.out.print(qRate[k][j] / i + " ");
}
System.out.print("\n");
}
System.out.println("R rates");
for (int k = 0; k < nFramingAnnotators; k++) {
for (int j = 0; j < nLabels; j++) {
System.out.print(rRate[k][j] / i + " ");
}
System.out.print("\n");
}
System.out.println("S rates");
for (int k = 0; k < nToneAnnotators; k++) {
for (int j = 0; j < nTones; j++) {
System.out.print(sRate[k][j] / i + " ");
}
System.out.print("\n");
}
// save results
Path output_path;
for (int k = 0; k < nLabels; k++) {
output_path = Paths.get("samples", "timeFramesSamples" + k + ".csv");
try (FileWriter file = new FileWriter(output_path.toString())) {
for (sample = 0; sample < nSamples; sample++) {
for (int t = 0; t < nTimes; t++) {
file.write(timeFrameSamples[sample][t][k] + ",");
}
file.write("\n");
}
}
}
output_path = Paths.get("samples", "timeFrameRealSigmaSamples.csv");
try (FileWriter file = new FileWriter(output_path.toString())) {
for (sample = 0; sample < nSamples; sample++) {
file.write(timeFrameRealSigmaSamples[sample] + ",\n" );
}
}
for (int k = 0; k < nTones; k++) {
output_path = Paths.get("samples", "timeToneSamples" + k + ".csv");
try (FileWriter file = new FileWriter(output_path.toString())) {
for (sample = 0; sample < nSamples; sample++) {
for (int t = 0; t < nTimes; t++) {
file.write(timeToneSamples[sample][t][k] + ",");
}
file.write("\n");
}
}
}
output_path = Paths.get("samples", "timeToneRealSigmaSamples.csv");
try (FileWriter file = new FileWriter(output_path.toString())) {
for (sample = 0; sample < nSamples; sample++) {
file.write(timeToneRealSigmaSamples[sample] + ",\n");
}
}
output_path = Paths.get("samples", "entropySamples.csv");
try (FileWriter file = new FileWriter(output_path.toString())) {
for (sample = 0; sample < nSamples; sample++) {
for (int t = 0; t < nTimes; t++) {
file.write(entropySamples[sample][t] + ",");
}
file.write("\n");
}
}
output_path = Paths.get("samples", "weightSamples.csv");
try (FileWriter file = new FileWriter(output_path.toString())) {
for (sample = 0; sample < nSamples; sample++) {
for (int f = 0; f < nFeatures; f++) {
file.write(weightSamples[sample][f] + ",");
}
file.write("\n");
}
}
for (int j = 0; j < nLabels; j++) {
output_path = Paths.get("samples", "qSamples" + j + ".csv");
try (FileWriter file = new FileWriter(output_path.toString())) {
for (sample = 0; sample < nSamples; sample++) {
for (int k = 0; k < nFramingAnnotators; k++) {
file.write(qSamples[sample][k][j] + ",");
}
file.write("\n");
}
}
}
for (int j = 0; j < nLabels; j++) {
output_path = Paths.get("samples", "rSamples" + j + ".csv");
try (FileWriter file = new FileWriter(output_path.toString())) {
for (sample = 0; sample < nSamples; sample++) {
for (int k = 0; k < nFramingAnnotators; k++) {
file.write(rSamples[sample][k][j] + ",");
}
file.write("\n");
}
}
}
for (int j = 0; j < nTones; j++) {
output_path = Paths.get("samples", "sSensitivitySamples" + j + ".csv");
try (FileWriter file = new FileWriter(output_path.toString())) {
for (sample = 0; sample < nSamples; sample++) {
for (int k = 0; k < nToneAnnotators; k++) {
file.write(sSamples[sample][k][j][j] + ",");
}
file.write("\n");
}
}
}
output_path = Paths.get("samples", "moodSamples.csv");
try (FileWriter file = new FileWriter(output_path.toString())) {
for (sample = 0; sample < nSamples; sample++) {
for (int t = 0; t < nTimes; t++) {
file.write(moodSamples[sample][t] + ",");
}
file.write("\n");
}
}
// What I actually want is maybe the annotation probabilities (?)
/*
output_path = Paths.get("samples", "articleMeans.csv");
try (FileWriter file = new FileWriter(output_path.toString())) {
for (int a = 0; a < nArticles; a++) {
double mean [] = new double[nLabels];
HashMap<Integer, int[]> articleAnnotations = annotations.get(a);
for (int annotator : articleAnnotations.keySet()) {
for (int k = 0; k < nLabels; k++) {
mean[k] += (double) articleAnnotations.get(annotator)[k] / (double) articleAnnotations.size();
}
}
for (int k = 0; k < nLabels; k++) {
file.write(mean[k] + ",");
}
file.write("\n");
}
}
*/
/*
for (int k = 0; k < nLabels; k++) {
output_path = Paths.get("samples", "articleProbs" + k + ".csv");
try (FileWriter file = new FileWriter(output_path.toString())) {
for (s = 0; s < nSamples; s++) {
for (int a = 0; a < nArticles; a++) {
double pk = sigmoid.value(articleFrameSamples[s][a][k] * zealSamples[s][0][k] - biasSamples[s][0][k]);
file.write(pk + ",");
}
file.write("\n");
}
}
}
*/
}
private double[] computeFeatureVector(int time, double [] toneProbs, double entropy) {
double featureVector[] = new double[nFeatures];
featureVector[0] = 1; // intercept
if (time > 0) {
featureVector[1] = mood[time - 1]; // mood at t-1
}
else {
featureVector[1] = mood[time]; // cheap substitute for previous mood in first year
}
featureVector[2] = nArticlesAtTime[time]; // number of articles published in time t
featureVector[3] = toneProbs[0] - toneProbs[2]; // net tone at time t
featureVector[4] = featureVector[2] * featureVector[3]; // interaction b/w tone and nArticles
featureVector[5] = entropy; // entropy
featureVector[6] = featureVector[3] * featureVector[5]; // interaction b/w tone and entropy
return featureVector;
}
private double computeEntropy(double [] framingProbs) {
double entropy = 0;
for (int j = 0; j < nLabels; j++) {
entropy -= (framingProbs[j] * Math.log(framingProbs[j]) + (1-framingProbs[j]) * Math.log(1-framingProbs[j]));
}
return entropy;
}
private double computeLogProbMood(double [] featureVector, double [] weights, double mood, double moodSigma) {
double mean = 0;
for (int f = 0; f < nFeatures; f++) {
mean += weights[f] * featureVector[f];
}
NormalDistribution currentMoodDist = new NormalDistribution(mean, moodSigma);
double pLogMood = Math.log(currentMoodDist.density(mood));
return pLogMood;
}
private double sampleTimeFrames() {
// run the distribution over frames for the first time point
double nAccepted = 0;
// loop through all time points
for (int t = 0; t < nTimes; t++) {
// get the current distribution over frames
double currentCube[] = timeFramesCube.get(t);
double currentReals[] = timeFramesReals.get(t);
// create a variable for a proposal
double proposalReals[] = new double[nLabels];
double mean[] = new double[nLabels];
double covariance[][] = new double[nLabels][nLabels];
for (int k = 0; k < nLabels; k++) {
covariance[k][k] = 1;
}
MultivariateNormalDistribution normDist = new MultivariateNormalDistribution(mean, covariance);
double normalStep[] = normDist.sample();
double step = rand.nextGaussian() * mhTimeFramesStepSigma;
// apply the step to generate a proposal
for (int k = 0; k < nLabels; k++) {
proposalReals[k] = currentReals[k] + normalStep[k] * step;
}
// transform the proposal to the cube
double proposalCube[] = Transformations.realsToCube(proposalReals, nLabels);
// get the distribution over frames at the previous time point
double previousReals[] = new double[nLabels];
double priorCovariance[][] = new double[nLabels][nLabels];
double priorNextCovariance[][] = new double[nLabels][nLabels];
if (t > 0) {
previousReals = timeFramesReals.get(t-1);
for (int k = 0; k < nLabels; k++) {
priorCovariance[k][k] = timeFramesRealSigma;
priorNextCovariance[k][k] = timeFramesRealSigma;
}
} else {
// if t == 0, use the global mean
//double [] previousCube = new double[nLabels];
//System.arraycopy(framesMean, 0, previousCube, 0, nLabels);
//previousReals = Transformations.cubeToReals(previousCube, nLabels);
for (int k = 0; k < nLabels; k++) {
priorCovariance[k][k] = timeFramesRealSigma * 100;
priorNextCovariance[k][k] = timeFramesRealSigma;
}
}
MultivariateNormalDistribution previousDist = new MultivariateNormalDistribution(previousReals, priorCovariance);
double pLogCurrent = Math.log(previousDist.density(currentReals));
double pLogProposal = Math.log(previousDist.density(proposalReals));
// get the distribution over frames in the next time point
if (t < nTimes-1) {
double nextReals[] = timeFramesReals.get(t+1);
// compute a distribution over a new distribution over frames for the current distribution
MultivariateNormalDistribution currentDist = new MultivariateNormalDistribution(currentReals, priorNextCovariance);
MultivariateNormalDistribution proposalDist = new MultivariateNormalDistribution(proposalReals, priorNextCovariance);
pLogCurrent += Math.log(currentDist.density(nextReals));
pLogProposal += Math.log(proposalDist.density(nextReals));
}
// compute the probability of the article distributions for both current and proposal
ArrayList<Integer> articles = timeFramingArticles.get(t);
for (int i : articles) {
int articleLabels[] = articleFrames.get(i);
for (int k = 0; k < nLabels; k++) {
pLogCurrent += articleLabels[k] * Math.log(currentCube[k]) + (1-articleLabels[k]) * Math.log(1-currentCube[k]);
pLogProposal += articleLabels[k] * Math.log(proposalCube[k]) + (1-articleLabels[k]) * Math.log(1-proposalCube[k]);
}
}
// compute probabilities of mood for current and proposed latent framing probs
double currentVector[] = computeFeatureVector(t, timeToneSimplex.get(t), timeEntropy[t]);
double proposalEntropy = computeEntropy(proposalCube);
double proposalVector[] = computeFeatureVector(t, timeToneSimplex.get(t), proposalEntropy);
pLogCurrent += computeLogProbMood(currentVector, weights, mood[t], moodSigma);
pLogProposal += computeLogProbMood(proposalVector, weights, mood[t], moodSigma);
double a = Math.exp(pLogProposal - pLogCurrent);
double u = rand.nextDouble();
if (u < a) {
timeFramesCube.set(t, proposalCube);
timeFramesReals.set(t, proposalReals);
nAccepted += 1;
timeEntropy[t] = proposalEntropy;
}
}
return nAccepted / nTimes;
}
private void sampleArticleFrames() {
// don't bother to track acceptance because we're going to properly use Gibbs for this
// loop through all articles
for (int i = 0; i < nArticlesWithFraming; i++) {
// get the current article dist
int articleLabels[] = articleFrames.get(i);
int proposedLabels[] = new int[nLabels];
int time = framingArticleTime.get(i);
double timeFrames[] = timeFramesCube.get(time);
for (int j = 0; j < nLabels; j++) {
double pLogPosGivenTime = Math.log(timeFrames[j]);
double pLogNegGivenTime = Math.log(1-timeFrames[j]);
// compute the probability of the labels for both current and proposal
HashMap<Integer, int[]> articleAnnotations = framingAnnotations.get(i);
for (int annotator : articleAnnotations.keySet()) {
int labels[] = articleAnnotations.get(annotator);
pLogPosGivenTime += labels[j] * Math.log(q[annotator][j]) + (1-labels[j]) * Math.log(1-r[annotator][j]);
pLogNegGivenTime += labels[j] * Math.log(1-q[annotator][j]) + (1-labels[j]) * Math.log(r[annotator][j]);
}
double pPosUnnorm = Math.exp(pLogPosGivenTime);
double pNegUnnorm = Math.exp(pLogNegGivenTime);
double pPos = pPosUnnorm / (pPosUnnorm + pNegUnnorm);
double u = rand.nextDouble();
if (u < pPos) {
proposedLabels[j] = 1;
}
}
articleFrames.set(i, proposedLabels);
}
}
private double sampleTimeFramesRealSigma() {
double acceptance = 0.0;
double current = timeFramesRealSigma;
double proposal = current + rand.nextGaussian() * mhTimeFramesRealSigmaStep;
double pLogCurrent = 0.0;
double pLogProposal = 0.0;
double [][] currentCovar = new double[nLabels][nLabels];
double [][] proposalCovar = new double[nLabels][nLabels];
for (int j = 0; j < nLabels; j++) {
currentCovar[j][j] = current;
proposalCovar[j][j] = proposal;
}
if (proposal > 0) {
for (int t = 1; t < nTimes; t++) {
MultivariateNormalDistribution priorCurrent = new MultivariateNormalDistribution(timeFramesReals.get(t-1), currentCovar);
MultivariateNormalDistribution priorProposal = new MultivariateNormalDistribution(timeFramesReals.get(t-1), proposalCovar);
pLogCurrent += Math.log(priorCurrent.density(timeFramesReals.get(t)));
pLogProposal += Math.log(priorProposal.density(timeFramesReals.get(t)));
}
double a = Math.exp(pLogProposal - pLogCurrent);
double u = rand.nextDouble();
if (u < a) {
timeFramesRealSigma = proposal;
acceptance += 1;
}
}
return acceptance;
}
private double sampleTimeToneRealSigma() {
double acceptance = 0.0;
double current = timeToneRealSigma;
double proposal = current + rand.nextGaussian() * mhTimeToneRealSigmaStep;
double pLogCurrent = 0.0;
double pLogProposal = 0.0;
double [][] currentCovar = new double[nTones][nTones];
double [][] proposalCovar = new double[nTones][nTones];
for (int j = 0; j < nTones; j++) {
currentCovar[j][j] = current;
proposalCovar[j][j] = proposal;
}
if (proposal > 0) {
for (int t = 1; t < nTimes; t++) {
MultivariateNormalDistribution priorCurrent = new MultivariateNormalDistribution(timeToneReals.get(t-1), currentCovar);
MultivariateNormalDistribution priorProposal = new MultivariateNormalDistribution(timeToneReals.get(t-1), proposalCovar);
pLogCurrent += Math.log(priorCurrent.density(timeToneReals.get(t)));
pLogProposal += Math.log(priorProposal.density(timeToneReals.get(t)));
}
double a = Math.exp(pLogProposal - pLogCurrent);
double u = rand.nextDouble();
if (u < a) {
timeToneRealSigma = proposal;
acceptance += 1;
}
}
return acceptance;
}
private double sampleTimeTones() {
// run the distribution over tones for the first time point
double nAccepted = 0;
// loop through all time points
for (int t = 0; t < nTimes; t++) {
// get the current distribution over tones
double currentSimplex[] = timeToneSimplex.get(t);
double currentReals[] = timeToneReals.get(t);
// create a variable for a proposal
double proposalReals[] = new double[nTones];
double mean[] = new double[nTones];
double covariance[][] = new double[nTones][nTones];
for (int k = 0; k < nTones; k++) {
covariance[k][k] = 1;
}
MultivariateNormalDistribution normDist = new MultivariateNormalDistribution(mean, covariance);
double normalStep[] = normDist.sample();
double step = rand.nextGaussian() * mhTimeToneStepSigma;
// apply the step to generate a proposal
for (int k = 0; k < nTones; k++) {
proposalReals[k] = currentReals[k] + normalStep[k] * step;
}
// transform the proposal to the simplex
double proposalSimplex[] = Transformations.realsToSimplex(proposalReals, nTones);
// get the distribution over tones at the previous time point
double previousReals[] = new double[nTones];
double priorCovariance[][] = new double[nTones][nTones];
double priorNextCovariance[][] = new double[nTones][nTones];
if (t > 0) {
previousReals = timeToneReals.get(t-1);
// compute a distribution over the current time point given previous
for (int k = 0; k < nTones; k++) {
priorCovariance[k][k] = timeToneRealSigma;
priorNextCovariance[k][k] = timeToneRealSigma;
}
} else {
// if t == 0, use the global mean
//double [] previousSimplex = new double[nTones];
//System.arraycopy(tonesMean, 0, previousSimplex, 0, nTones);
//previousReals = Transformations.simplexToReals(previousSimplex, nTones);
// compute a distribution over the current time point given previous
for (int k = 0; k < nTones; k++) {
priorCovariance[k][k] = timeToneRealSigma * 100;
priorNextCovariance[k][k] = timeToneRealSigma;
}
}
MultivariateNormalDistribution previousDist = new MultivariateNormalDistribution(previousReals, priorCovariance);
double pLogCurrent = Math.log(previousDist.density(currentReals));
double pLogProposal = Math.log(previousDist.density(proposalReals));
// get the distribution over tones in the next time point
if (t < nTimes-1) {
double nextReals[] = timeToneReals.get(t+1);
// compute a distribution over a new distribution over tones for the current distribution
MultivariateNormalDistribution currentDist = new MultivariateNormalDistribution(currentReals, priorNextCovariance);
MultivariateNormalDistribution proposalDist = new MultivariateNormalDistribution(proposalReals, priorNextCovariance);
pLogCurrent += Math.log(currentDist.density(nextReals));
pLogProposal += Math.log(proposalDist.density(nextReals));
}
// compute the probability of the article tones for both current and proposal
ArrayList<Integer> articles = timeToneArticles.get(t);
for (int i : articles) {
int iTone = articleTone[i];
pLogCurrent += Math.log(currentSimplex[iTone]);
pLogProposal += Math.log(proposalSimplex[iTone]);
}
// compute probabilities of mood for current and proposed latent framing probs
double currentVector[] = computeFeatureVector(t, currentSimplex, timeEntropy[t]);
double proposalVector[] = computeFeatureVector(t, proposalSimplex, timeEntropy[t]);
pLogCurrent += computeLogProbMood(currentVector, weights, mood[t], moodSigma);
pLogProposal += computeLogProbMood(proposalVector, weights, mood[t], moodSigma);
double a = Math.exp(pLogProposal - pLogCurrent);
double u = rand.nextDouble();
if (u < a) {
timeToneSimplex.set(t, proposalSimplex);
timeToneReals.set(t, proposalReals);
nAccepted += 1;
}
}
return nAccepted / nTimes;
}
private void sampleArticleTones() {
// don't bother to track acceptance because we're going to properly use Gibbs for this
// loop through all articles
for (int i = 0; i < nArticlesWithTone; i++) {
// get the current article dist
int tone = articleTone[i];
int time = toneArticleTime.get(i);
double timeTones[] = timeToneSimplex.get(time);
double pLogPositive = Math.log(timeTones[0]);
double pLogNeutral = Math.log(timeTones[1]);
double pLogAnti = Math.log(timeTones[2]);
HashMap<Integer, Integer> articleAnnotations = toneAnnotations.get(i);
for (int annotator : articleAnnotations.keySet()) {
int annotatorTone = articleAnnotations.get(annotator);
pLogPositive += Math.log(sSimplex[annotator][0][annotatorTone]);
pLogNeutral += Math.log(sSimplex[annotator][1][annotatorTone]);
pLogAnti += Math.log(sSimplex[annotator][2][annotatorTone]);
}
double pPositiveUnnorm = Math.exp(pLogPositive);
double pNeutralUnnorm = Math.exp(pLogNeutral);
double pAntiUnnorm = Math.exp(pLogAnti);
double pPos = pPositiveUnnorm / (pPositiveUnnorm + pNeutralUnnorm + pAntiUnnorm);
double pProNeutral = pPos + pNeutralUnnorm / (pPositiveUnnorm + pNeutralUnnorm + pAntiUnnorm);
double u = rand.nextDouble();
if (u < pPos) {
articleTone[i] = 0;
}
else if (u < pProNeutral) {
articleTone[i] = 1;
}
else {
articleTone[i] = 2;
}
}
}
private double [] sampleWeights() {
double [] nAccepted = new double[nFeatures];
for (int f = 0; f < nFeatures; f++) {
double [] current = new double[nFeatures];
double [] proposal = new double[nFeatures];
System.arraycopy(weights, 0, current, 0, nFeatures);
System.arraycopy(weights, 0, proposal, 0, nFeatures);
double currentVal = current[f];
double proposalVal = currentVal + rand.nextGaussian() * mhWeightsStepSigma[f];
proposal[f] = proposalVal;
NormalDistribution prior = new NormalDistribution(0, weightSigma);
double pLogCurrent = Math.log(prior.density(currentVal));
double pLogProposal = Math.log(prior.density(proposalVal));
for (int t = 0; t < nTimes; t++) {
double [] featureVector = computeFeatureVector(t, timeToneSimplex.get(t), timeEntropy[t]);
pLogCurrent += computeLogProbMood(featureVector, current, mood[t], moodSigma);
pLogProposal += computeLogProbMood(featureVector, proposal, mood[t], moodSigma);
}
double a = Math.exp(pLogProposal - pLogCurrent);
double u = rand.nextDouble();
if (u < a) {
weights[f] = proposalVal;
nAccepted[f] += 1;
}
if (Double.isInfinite(pLogProposal)) {
System.out.println("Inf in sample weight " + f);
}
}
return nAccepted;
}
private double sampleAllWeights() {
double nAccepted = 0.0;
double [] current = new double[nFeatures];
double [] proposal = new double[nFeatures];
System.arraycopy(weights, 0, current, 0, nFeatures);
//System.arraycopy(weights, 0, proposal, 0, nFeatures);
//double currentVal = current[f];
double [][] covar = new double [nFeatures][nFeatures];
for (int f = 0; f < nFeatures; f++) {
covar[f][f] = mhOneWeightStepSigma;
}
MultivariateNormalDistribution proposalDist = new MultivariateNormalDistribution(current, covar);
proposal = proposalDist.sample();
/*
double [] means = new double[nFeatures];
for (int f = 0; f < nFeatures; f++) {
covar[f][f] = weightSigma;
}
*/
NormalDistribution prior = new NormalDistribution(0, weightSigma);
double pLogCurrent = 0.0;
double pLogProposal = 0.0;
for (int f = 0; f < nFeatures; f++) {
pLogCurrent += Math.log(prior.density(current[f]));
pLogProposal += Math.log(prior.density(proposal[f]));
}
for (int t = 0; t < nTimes; t++) {
double [] featureVector = computeFeatureVector(t, timeToneSimplex.get(t), timeEntropy[t]);
pLogCurrent += computeLogProbMood(featureVector, current, mood[t], moodSigma);
pLogProposal += computeLogProbMood(featureVector, proposal, mood[t], moodSigma);
}
double a = Math.exp(pLogProposal - pLogCurrent);
double u = rand.nextDouble();
if (u < a) {
System.arraycopy(proposal, 0, weights, 0, nFeatures);
nAccepted += 1;
}
return nAccepted;
}
private double sampleMoodSigma() {
double acceptance = 0.0;
double current = moodSigma;
double proposal = current + rand.nextGaussian() * mhMoodSigmaStep;
double pLogCurrent = 0.0;
double pLogProposal = 0.0;
if (proposal > 0) {
for (int t = 1; t < nTimes; t++) {
double [] featureVector = computeFeatureVector(t, timeToneSimplex.get(t), timeEntropy[t]);
pLogCurrent += Math.log(computeLogProbMood(featureVector, weights, mood[t], current));
pLogProposal += Math.log(computeLogProbMood(featureVector, weights, mood[t], proposal));
}
double a = Math.exp(pLogProposal - pLogCurrent);
double u = rand.nextDouble();
if (u < a) {
timeFramesRealSigma = proposal;
acceptance += 1;
}
}
return acceptance;
}
double [][] sampleQ() {
double nAccepted [][] = new double[nFramingAnnotators][nLabels];
for (int k = 0; k < nFramingAnnotators; k++) {
ArrayList<Integer> articles = framingAnnotatorArticles.get(k);
for (int j = 0; j < nLabels; j++) {
double current = q[k][j];
// transform from (0.5,1) to R and back
//double proposalReal = Math.log(-Math.log(current)) + rand.nextGaussian() * mhQSigma;
//double proposal = Math.exp(-Math.exp(proposalReal));
double proposal = current + rand.nextGaussian() * mhQSigma;
double a;
if (proposal > 0 && proposal < 1) {
/*
// using somewhat strong beta prior for now
double alpha = Transformations.betaMuGammaToAlpha(mu_q, gamma_q);
double beta = Transformations.betaMuGammaToBeta(mu_q, gamma_q);
if (alpha < 1 || beta < 1) {
System.out.println("Undesired beta parameters in Q");
alpha = Transformations.betaMuGammaToAlpha(mu_q, gamma_q);
beta = Transformations.betaMuGammaToBeta(mu_q, gamma_q);
}
BetaDistribution prior = new BetaDistribution(alpha, beta);
double pLogCurrent = prior.density(current);
double pLogProposal = prior.density(proposal);
*/
// try using a U[0,1] prior and hope initialization guides us to identifiability
double pLogCurrent = 0.0;
double pLogProposal = 0.0;
for (int article : articles) {
int frames[] = articleFrames.get(article);
HashMap<Integer, int[]> articleAnnotations = framingAnnotations.get(article);
int labels[] = articleAnnotations.get(k);
double pPosCurrent = frames[j] * current + (1 - frames[j]) * (1 - r[k][j]);
double pPosProposal = frames[j] * proposal + (1 - frames[j]) * (1 - r[k][j]);
pLogCurrent += labels[j] * Math.log(pPosCurrent) + (1 - labels[j]) * Math.log(1 - pPosCurrent);
pLogProposal += labels[j] * Math.log(pPosProposal) + (1 - labels[j]) * Math.log(1 - pPosProposal);
}
a = Math.exp(pLogProposal - pLogCurrent);
}
else {
a = -1;
}
if (Double.isNaN(a)) {
System.out.println("NaN in Q:" + current + " to " + proposal);
}
if (Double.isInfinite(a)) {
System.out.println("Inf in Q:" + current + " to " + proposal);
}
double u = rand.nextDouble();
if (u < a) {
q[k][j] = proposal;
nAccepted[k][j] += 1;
}
}
}
return nAccepted;
}
double [][] sampleR() {
double nAccepted [][] = new double[nFramingAnnotators][nLabels];
for (int k = 0; k < nFramingAnnotators; k++) {
ArrayList<Integer> articles = framingAnnotatorArticles.get(k);
for (int j = 0; j < nLabels; j++) {
double current = r[k][j];
// transform from (0.5,1) to R and back
//double proposalReal = Math.log(-Math.log((current-0.5)*2)) + rand.nextGaussian() * mhQSigma;
//double proposal = Math.exp(-Math.exp(proposalReal)) / 2 + 0.5;
double proposal = current + rand.nextGaussian() * mhRSigma;
double a;
if (proposal > 0 && proposal < 1) {
/*
// using somewhat strong beta prior for now
//BetaDistribution prior = new BetaDistribution(q_mu * q_gamma / (1 - q_mu), q_gamma);
double alpha = Transformations.betaMuGammaToAlpha(mu_q, gamma_q);
double beta = Transformations.betaMuGammaToBeta(mu_q, gamma_q);
if (alpha < 1 || beta < 1) {
System.out.println("Undesired beta parameters in R");
alpha = Transformations.betaMuGammaToAlpha(mu_q, gamma_q);
beta = Transformations.betaMuGammaToBeta(mu_q, gamma_q);
}
BetaDistribution prior = new BetaDistribution(alpha, beta);
double pLogCurrent = prior.density(current);
double pLogProposal = prior.density(proposal);
*/
double pLogCurrent = 0.0;
double pLogProposal = 0.0;
for (int article : articles) {
int frames[] = articleFrames.get(article);
HashMap<Integer, int[]> articleAnnotations = framingAnnotations.get(article);
int labels[] = articleAnnotations.get(k);
double pPosCurrent = frames[j] * q[k][j] + (1 - frames[j]) * (1 - current);
double pPosProposal = frames[j] * q[k][j] + (1 - frames[j]) * (1 - proposal);
pLogCurrent += labels[j] * Math.log(pPosCurrent) + (1 - labels[j]) * Math.log(1 - pPosCurrent);
pLogProposal += labels[j] * Math.log(pPosProposal) + (1 - labels[j]) * Math.log(1 - pPosProposal);
}
a = Math.exp(pLogProposal - pLogCurrent);
if (Double.isNaN(a)) {
System.out.println("NaN in R:" + current + " to " + proposal);
}
if (Double.isInfinite(a)) {
System.out.println("Inf in R:" + current + " to " + proposal);
}
}
else {
a = -1;
}
double u = rand.nextDouble();
if (u < a) {
r[k][j] = proposal;
nAccepted[k][j] += 1;
}
}
}
return nAccepted;
}
double [][] sampleS() {
double nAccepted [][] = new double[nToneAnnotators][nTones];
for (int k = 0; k < nToneAnnotators; k++) {
ArrayList<Integer> articles = toneAnnotatorArticles.get(k);
for (int l = 0; l < nTones; l++) {
double currentSimplex [] = sSimplex[k][l];
double currentReals [] = sReal[k][l];
MultivariateNormalDistribution multNormDist = new MultivariateNormalDistribution(currentReals, mhSCovariance);
double proposalReal [] = multNormDist.sample();
double proposalSimplex [] = Transformations.realsToSimplex(proposalReal, nTones);
double a;
if (proposalSimplex[l] > 0) {
// using pretty strong Dirichlet prior for now
double alpha[] = {1.0, 1.0, 1.0};
alpha[l] = 3;
DirichletDist prior = new DirichletDist(alpha);
double pLogCurrent = Math.log(prior.density(currentSimplex));
double pLogProposal = Math.log(prior.density(proposalSimplex));
//double pLogCurrent = 0.0;
//double pLogProposal = 0.0;
for (int article : articles) {
int tone = articleTone[article];
if (tone == l) {
HashMap<Integer, Integer> articleAnnotations = toneAnnotations.get(article);
int annotatorTone = articleAnnotations.get(k);
pLogCurrent += Math.log(currentSimplex[annotatorTone]);
pLogProposal += Math.log(proposalSimplex[annotatorTone]);
}
}
a = Math.exp(pLogProposal - pLogCurrent);
if (Double.isNaN(a)) {
System.out.println("NaN in S");
}
if (Double.isInfinite(a)) {
System.out.println("Inf in S");
}
} else {
a = -1;
}
double u = rand.nextDouble();
if (u < a) {
System.arraycopy(proposalReal, 0, sReal[k][l], 0, nTones);
System.arraycopy(proposalSimplex, 0, sSimplex[k][l], 0, nTones);
nAccepted[k][l] += 1;
}
}
}
return nAccepted;
}
private double[] recomputeGlobalMean() {
double mean[] = new double[nLabels];
// loop through all articles
for (int i = 0; i < nArticlesWithFraming; i++) {
// get the current article dist
int articleLabels[] = articleFrames.get(i);
for (int k = 0; k < nLabels; k++) {
mean[k] += (double) articleLabels[k];
}
}
for (int k = 0; k < nLabels; k++) {
mean[k] = mean[k] / (double) nArticlesWithFraming;
}
return mean;
}
/*
private double sampleTimeFramesGuassian() {
double nAccepted = 0;
// loop through all time points
for (int t = 0; t < nTimes; t++) {
// get the distribution over frames at the previous time point
double previous[];
if (t > 0) {
previous = timeFrames.get(t-1);
} else {
previous = new double[nLabels];
for (int k = 0; k < nLabels; k++) {
previous[k] = 1.0 / nLabels;
}
}
// use this to compute a distribution over the current distribution over frames
double previousDist[] = new double[nLabels];
for (int k = 0; k < nLabels; k++) {
previousDist[k] = previous[k] * nLabels * alpha + alpha0;
}
// get the current distribution over frames
double current[] = timeFrames.get(t);
// create a variable for a proposal
double proposal[] = new double[nLabels];
// get the distribution over frames in the next time point
double next[] = new double[nLabels];
if (t < nTimes-1) {
next = timeFrames.get(t + 1);
}
// generate a proposal (symmetrically)
double temp[] = new double[nLabels];
double total = 0;
for (int k = 0; k < nLabels; k++) {
temp[k] = Math.exp(Math.log(current[k]) + rand.nextGaussian() * mhTimeFrameSigma);
total += temp[k];
}
for (int k = 0; k < nLabels; k++) {
proposal[k] = temp[k] / total;
}
/ *
// compute a distribution for generating a proposal
double mhProposalDist[] = new double[nLabels];
for (int k = 0; k < nLabels; k++) {
mhProposalDist[k] = mhDirichletScale * current[k] + mhDirichletBias;
}
// generate a point from this distribution
DirichletGen.nextPoint(randomStream, mhProposalDist, proposal);
// evaluate the probability of generating this new point from the proposal
DirichletDist dirichletDist = new DirichletDist(mhProposalDist);
double mhpProposal = dirichletDist.density(proposal);
// compute the probability of the generating the current point from the proposal
double reverseDist[] = new double[nLabels];
for (int k = 0; k < nLabels; k++) {
reverseDist[k] = mhDirichletScale * proposal[k] + mhDirichletBias;
}
DirichletDist dirichletDistReverse = new DirichletDist(reverseDist);
double mhpReverse = dirichletDist.density(current);
* /
// compute a distribution over a new distribution over frames for the current distribution
double currentDist[] = new double[nLabels];
for (int k = 0; k < nLabels; k++) {
currentDist[k] = current[k] * nLabels * alpha + alpha0;
}
// do the same for the proposal
double proposalDist[] = new double[nLabels];
for (int k = 0; k < nLabels; k++) {
proposalDist[k] = proposal[k] * nLabels * alpha + alpha0;
}
// compute the probability of the current distribution over frames conditioned on the previous
DirichletDist dirichletDistPrevious = new DirichletDist(previousDist);
double pCurrentGivenPrev = dirichletDistPrevious.density(current);
double pProposalGivenPrev = dirichletDistPrevious.density(proposal);
// do the same for the next time point conditioned on the current and proposal
DirichletDist dirichletDistCurrent = new DirichletDist(currentDist);
double pNextGivenCurrent = dirichletDistCurrent.density(next);
DirichletDist dirichletDistProposal = new DirichletDist(proposalDist);
double pNextGivenProposal = dirichletDistProposal.density(next);
double pLogCurrent = Math.log(pCurrentGivenPrev);
if (t < t-1) {
pLogCurrent += Math.log(pNextGivenCurrent);
}
double pLogProposal = Math.log(pProposalGivenPrev);
if (t < t-1) {
pLogProposal += Math.log(pNextGivenProposal);
}
double beta = betas.get(t);
// compute distributions over distributions for articles
double currentDistArticle[] = new double[nLabels];
for (int k = 0; k < nLabels; k++) {
currentDistArticle[k] = current[k] * nLabels * beta + beta0;
}
DirichletDist dirichletDistArticleCurrent = new DirichletDist(currentDistArticle);
double proposalDistArticle[] = new double[nLabels];
for (int k = 0; k < nLabels; k++) {
proposalDistArticle[k] = proposal[k] * nLabels * beta + beta0;
}
DirichletDist dirichletDistArticleProposal = new DirichletDist(proposalDistArticle);
// compute the probability of the article disrtibutions for both current and proposal
ArrayList<Integer> articles = timeArticles.get(t);
for (int i : articles) {
double articleDist[] = articleFrames.get(i);
double pArticleCurrent = dirichletDistArticleCurrent.density(articleDist);
pLogCurrent += Math.log(pArticleCurrent);
double pArticleProposal= dirichletDistArticleProposal.density(articleDist);
pLogProposal += Math.log(pArticleProposal);
}
double a = Math.exp(pLogProposal - pLogCurrent);
double u = rand.nextDouble();
if (u < a) {
timeFrames.set(t, proposal);
nAccepted += 1;
}
}
return nAccepted / nTimes;
}
*/
}
| removing random annotator thing
| src/CombinedModel.java | removing random annotator thing | <ide><path>rc/CombinedModel.java
<ide> // create a hashmap to store the annotations for this article
<ide> HashMap<Integer, Integer> articleAnnotations = new HashMap<>();
<ide>
<del> // only take one annotation for the tone, as they should all be the same
<del> int randAnnotator = rand.nextInt(articleToneAnnotations.size());
<del> int aCount = 0;
<del>
<ide> for (Object annotator : articleToneAnnotations.keySet()) {
<ide> // for each one, prepare to hold the tone annotation
<ide> int toneAnnotation = 0;
<ide> toneAnnotation = (int) Math.round(realCode) - 17;
<ide> }
<ide> // store the annotations for this annotator
<del> if (aCount == randAnnotator) {
<del> articleAnnotations.put(annotatorIndex, toneAnnotation);
<del> toneAnnotatorArticles.get(annotatorIndex).add(i);
<del> tonesMean[toneAnnotation] += 1.0;
<del> toneCount += 1;
<del> }
<del> aCount += 1;
<add> articleAnnotations.put(annotatorIndex, toneAnnotation);
<add> toneAnnotatorArticles.get(annotatorIndex).add(i);
<add> tonesMean[toneAnnotation] += 1.0;
<add> toneCount += 1;
<ide> }
<ide> // store the annotations for this article
<ide> toneAnnotations.add(articleAnnotations); |
|
Java | mit | error: pathspec 'src/me/vrekt/lunar/world/WorldGrid.java' did not match any file(s) known to git
| 5b109cfe218892826b75065d1bf5bf3bfd65b398 | 1 | Vrekt/Lunar | package me.vrekt.lunar.world;
import java.awt.Graphics;
import java.awt.Rectangle;
import java.util.ArrayList;
import java.util.List;
/**
* Created by Vrekt on 3/16/2017.
*/
public class WorldGrid {
private int tileWidth, tileHeight;
private int width, height;
private List<Rectangle> worldGrid;
/**
* Initialize
*
* @param width the width of the world
* @param height the height of the world
* @param tileWidth the width of the tiles
* @param tileHeight the height of the tiles.
*/
public WorldGrid(int width, int height, int tileWidth, int tileHeight) {
this.tileWidth = tileWidth;
this.tileHeight = tileHeight;
this.width = width;
this.height = height;
worldGrid = generateGrid();
}
/**
* Generate the grid based on width and height.
*/
public List<Rectangle> generateGrid() {
List<Rectangle> list = new ArrayList<>();
for (int x = 0; x < width; x += tileWidth) {
for (int y = 0; y < height; y += tileHeight) {
list.add(new Rectangle(x, y, tileWidth, tileHeight));
}
}
return list;
}
/**
* Draw the grid.
*/
public void drawGrid(Graphics graphics) {
worldGrid.forEach(rec -> graphics.drawRect((int) rec.getX(), (int) rec.getY(), (int) rec.getWidth(), (int) rec.getHeight()));
}
/**
* This can return null if the grid has not been generated.
*
* @return a list of rectangles that represent the grid.
*/
public List<Rectangle> getWorldGrid() {
return worldGrid;
}
/**
* @return the tile width
*/
public int getTileWidth() {
return tileWidth;
}
/**
* @return the tile height
*/
public int getTileHeight() {
return tileHeight;
}
/**
* @return the width
*/
public int getWidth() {
return width;
}
/**
* @return the height
*/
public int getHeight() {
return height;
}
}
| src/me/vrekt/lunar/world/WorldGrid.java | WorldGrid file
| src/me/vrekt/lunar/world/WorldGrid.java | WorldGrid file | <ide><path>rc/me/vrekt/lunar/world/WorldGrid.java
<add>package me.vrekt.lunar.world;
<add>
<add>import java.awt.Graphics;
<add>import java.awt.Rectangle;
<add>import java.util.ArrayList;
<add>import java.util.List;
<add>
<add>/**
<add> * Created by Vrekt on 3/16/2017.
<add> */
<add>public class WorldGrid {
<add>
<add> private int tileWidth, tileHeight;
<add> private int width, height;
<add>
<add> private List<Rectangle> worldGrid;
<add>
<add> /**
<add> * Initialize
<add> *
<add> * @param width the width of the world
<add> * @param height the height of the world
<add> * @param tileWidth the width of the tiles
<add> * @param tileHeight the height of the tiles.
<add> */
<add> public WorldGrid(int width, int height, int tileWidth, int tileHeight) {
<add> this.tileWidth = tileWidth;
<add> this.tileHeight = tileHeight;
<add>
<add> this.width = width;
<add> this.height = height;
<add>
<add> worldGrid = generateGrid();
<add>
<add> }
<add>
<add> /**
<add> * Generate the grid based on width and height.
<add> */
<add> public List<Rectangle> generateGrid() {
<add> List<Rectangle> list = new ArrayList<>();
<add>
<add> for (int x = 0; x < width; x += tileWidth) {
<add> for (int y = 0; y < height; y += tileHeight) {
<add> list.add(new Rectangle(x, y, tileWidth, tileHeight));
<add> }
<add> }
<add>
<add> return list;
<add>
<add> }
<add>
<add> /**
<add> * Draw the grid.
<add> */
<add> public void drawGrid(Graphics graphics) {
<add> worldGrid.forEach(rec -> graphics.drawRect((int) rec.getX(), (int) rec.getY(), (int) rec.getWidth(), (int) rec.getHeight()));
<add> }
<add>
<add> /**
<add> * This can return null if the grid has not been generated.
<add> *
<add> * @return a list of rectangles that represent the grid.
<add> */
<add> public List<Rectangle> getWorldGrid() {
<add> return worldGrid;
<add> }
<add>
<add> /**
<add> * @return the tile width
<add> */
<add> public int getTileWidth() {
<add> return tileWidth;
<add> }
<add>
<add> /**
<add> * @return the tile height
<add> */
<add> public int getTileHeight() {
<add> return tileHeight;
<add> }
<add>
<add> /**
<add> * @return the width
<add> */
<add> public int getWidth() {
<add> return width;
<add> }
<add>
<add> /**
<add> * @return the height
<add> */
<add> public int getHeight() {
<add> return height;
<add> }
<add>} |
|
JavaScript | agpl-3.0 | 606c601fc01257e336c53898ceb46d8f9946280e | 0 | suyashphadtare/vestasi-erp-final,gangadhar-kadam/verve_live_erp,MartinEnder/erpnext-de,dieface/erpnext,mbauskar/helpdesk-erpnext,saurabh6790/test-erp,rohitwaghchaure/erpnext-receipher,indictranstech/trufil-erpnext,rohitwaghchaure/GenieManager-erpnext,indictranstech/reciphergroup-erpnext,BhupeshGupta/erpnext,indictranstech/trufil-erpnext,shft117/SteckerApp,gangadharkadam/office_erp,shitolepriya/test-erp,mahabuber/erpnext,indictranstech/reciphergroup-erpnext,rohitwaghchaure/New_Theme_Erp,MartinEnder/erpnext-de,njmube/erpnext,indictranstech/osmosis-erpnext,gangadharkadam/v5_erp,mbauskar/phrerp,susuchina/ERPNEXT,suyashphadtare/gd-erp,gangadhar-kadam/latestchurcherp,aruizramon/alec_erpnext,4commerce-technologies-AG/erpnext,suyashphadtare/test,SPKian/Testing,hatwar/focal-erpnext,mbauskar/omnitech-demo-erpnext,meisterkleister/erpnext,sagar30051991/ozsmart-erp,mbauskar/Das_Erpnext,gangadharkadam/v6_erp,BhupeshGupta/erpnext,indictranstech/biggift-erpnext,anandpdoshi/erpnext,indictranstech/focal-erpnext,tmimori/erpnext,shitolepriya/test-erp,suyashphadtare/vestasi-erp-jan-end,sheafferusa/erpnext,indictranstech/phrerp,gsnbng/erpnext,tmimori/erpnext,gangadhar-kadam/helpdesk-erpnext,netfirms/erpnext,geekroot/erpnext,indictranstech/internal-erpnext,rohitwaghchaure/erpnext_smart,hatwar/Das_erpnext,mbauskar/omnitech-erpnext,ThiagoGarciaAlves/erpnext,pombredanne/erpnext,gangadhar-kadam/verve_erp,anandpdoshi/erpnext,hatwar/focal-erpnext,indictranstech/trufil-erpnext,indictranstech/vestasi-erpnext,mbauskar/omnitech-erpnext,indictranstech/buyback-erp,ThiagoGarciaAlves/erpnext,ShashaQin/erpnext,indictranstech/Das_Erpnext,hatwar/buyback-erpnext,Suninus/erpnext,indictranstech/focal-erpnext,shft117/SteckerApp,ShashaQin/erpnext,Drooids/erpnext,SPKian/Testing,mahabuber/erpnext,gangadharkadam/v6_erp,gangadharkadam/vlinkerp,gangadhar-kadam/latestchurcherp,suyashphadtare/gd-erp,indictranstech/buyback-erp,rohitwaghchaure/digitales_erpnext,hanselke/erpnext-1,njmube/erpnext,gangadhar-kadam/verve-erp,Tejal011089/osmosis_erpnext,indictranstech/fbd_erpnext,indictranstech/erpnext,ShashaQin/erpnext,Suninus/erpnext,Tejal011089/digitales_erpnext,indictranstech/internal-erpnext,Tejal011089/trufil-erpnext,shft117/SteckerApp,anandpdoshi/erpnext,SPKian/Testing2,gangadharkadam/vlinkerp,indictranstech/tele-erpnext,indictranstech/internal-erpnext,pombredanne/erpnext,susuchina/ERPNEXT,gangadharkadam/contributionerp,gangadharkadam/verveerp,suyashphadtare/vestasi-erp-jan-end,gangadhar-kadam/verve_test_erp,njmube/erpnext,rohitwaghchaure/New_Theme_Erp,gangadharkadam/office_erp,hanselke/erpnext-1,mbauskar/alec_frappe5_erpnext,mbauskar/omnitech-demo-erpnext,mbauskar/phrerp,Tejal011089/trufil-erpnext,suyashphadtare/vestasi-erp-final,4commerce-technologies-AG/erpnext,mbauskar/sapphire-erpnext,suyashphadtare/sajil-erp,gangadhar-kadam/verve_live_erp,gangadhar-kadam/verve_test_erp,gangadhar-kadam/verve-erp,hatwar/Das_erpnext,mbauskar/sapphire-erpnext,saurabh6790/test-erp,mbauskar/alec_frappe5_erpnext,gangadharkadam/saloon_erp,gangadhar-kadam/verve_test_erp,Suninus/erpnext,indictranstech/phrerp,hanselke/erpnext-1,treejames/erpnext,ThiagoGarciaAlves/erpnext,gangadhar-kadam/smrterp,Tejal011089/osmosis_erpnext,tmimori/erpnext,Tejal011089/fbd_erpnext,hatwar/buyback-erpnext,Tejal011089/paypal_erpnext,SPKian/Testing,rohitwaghchaure/erpnext-receipher,gangadharkadam/sterp,mbauskar/helpdesk-erpnext,gangadharkadam/smrterp,anandpdoshi/erpnext,mbauskar/phrerp,suyashphadtare/vestasi-erp-jan-end,hernad/erpnext,SPKian/Testing2,indictranstech/vestasi-erpnext,gangadharkadam/letzerp,gangadhar-kadam/helpdesk-erpnext,susuchina/ERPNEXT,indictranstech/reciphergroup-erpnext,gangadharkadam/verveerp,gangadharkadam/letzerp,gangadharkadam/v5_erp,mahabuber/erpnext,suyashphadtare/vestasi-erp-1,indictranstech/focal-erpnext,mbauskar/omnitech-demo-erpnext,pawaranand/phrerp,gangadharkadam/vlinkerp,indictranstech/osmosis-erpnext,mbauskar/alec_frappe5_erpnext,Tejal011089/digitales_erpnext,susuchina/ERPNEXT,gangadharkadam/saloon_erp_install,Drooids/erpnext,gangadharkadam/saloon_erp,suyashphadtare/sajil-erp,pombredanne/erpnext,gangadharkadam/contributionerp,gangadharkadam/v6_erp,treejames/erpnext,indictranstech/focal-erpnext,SPKian/Testing2,aruizramon/alec_erpnext,gangadharkadam/contributionerp,sheafferusa/erpnext,meisterkleister/erpnext,Tejal011089/paypal_erpnext,gangadhar-kadam/verve_erp,MartinEnder/erpnext-de,indictranstech/phrerp,ShashaQin/erpnext,gangadharkadam/contributionerp,indictranstech/tele-erpnext,fuhongliang/erpnext,gangadhar-kadam/latestchurcherp,Tejal011089/huntercamp_erpnext,Tejal011089/fbd_erpnext,sagar30051991/ozsmart-erp,mbauskar/phrerp,gangadharkadam/letzerp,sheafferusa/erpnext,geekroot/erpnext,BhupeshGupta/erpnext,indictranstech/erpnext,suyashphadtare/sajil-final-erp,gangadharkadam/johnerp,mbauskar/Das_Erpnext,rohitwaghchaure/erpnext_smart,treejames/erpnext,rohitwaghchaure/GenieManager-erpnext,pawaranand/phrerp,njmube/erpnext,gangadharkadam/v4_erp,fuhongliang/erpnext,gangadharkadam/saloon_erp,hatwar/Das_erpnext,Tejal011089/osmosis_erpnext,treejames/erpnext,gangadharkadam/saloon_erp_install,MartinEnder/erpnext-de,gangadharkadam/v5_erp,gangadhar-kadam/laganerp,indictranstech/vestasi-erpnext,gmarke/erpnext,rohitwaghchaure/GenieManager-erpnext,indictranstech/erpnext,gangadharkadam/office_erp,suyashphadtare/sajil-final-erp,rohitwaghchaure/GenieManager-erpnext,sagar30051991/ozsmart-erp,Tejal011089/digitales_erpnext,Tejal011089/fbd_erpnext,gangadhar-kadam/verve_erp,Tejal011089/trufil-erpnext,Tejal011089/fbd_erpnext,rohitwaghchaure/digitales_erpnext,indictranstech/fbd_erpnext,aruizramon/alec_erpnext,rohitwaghchaure/New_Theme_Erp,Aptitudetech/ERPNext,mbauskar/omnitech-erpnext,indictranstech/biggift-erpnext,tmimori/erpnext,saurabh6790/test-erp,shitolepriya/test-erp,hatwar/focal-erpnext,gangadharkadam/smrterp,Tejal011089/digitales_erpnext,gangadharkadam/v5_erp,suyashphadtare/gd-erp,rohitwaghchaure/erpnext-receipher,mbauskar/Das_Erpnext,Tejal011089/huntercamp_erpnext,gangadharkadam/saloon_erp,indictranstech/tele-erpnext,shitolepriya/test-erp,Tejal011089/trufil-erpnext,indictranstech/osmosis-erpnext,fuhongliang/erpnext,mbauskar/alec_frappe5_erpnext,hernad/erpnext,gangadharkadam/v4_erp,gangadharkadam/saloon_erp_install,sheafferusa/erpnext,indictranstech/Das_Erpnext,gmarke/erpnext,gangadharkadam/johnerp,hatwar/Das_erpnext,pawaranand/phrerp,indictranstech/fbd_erpnext,gangadhar-kadam/latestchurcherp,gangadhar-kadam/verve_live_erp,suyashphadtare/gd-erp,fuhongliang/erpnext,SPKian/Testing2,geekroot/erpnext,mahabuber/erpnext,dieface/erpnext,gangadharkadam/saloon_erp_install,gmarke/erpnext,gangadhar-kadam/laganerp,hernad/erpnext,hatwar/buyback-erpnext,suyashphadtare/test,mbauskar/sapphire-erpnext,Tejal011089/huntercamp_erpnext,Tejal011089/paypal_erpnext,geekroot/erpnext,indictranstech/Das_Erpnext,gangadharkadam/sterp,hanselke/erpnext-1,ThiagoGarciaAlves/erpnext,mbauskar/omnitech-erpnext,Suninus/erpnext,hernad/erpnext,gsnbng/erpnext,Tejal011089/paypal_erpnext,suyashphadtare/test,Drooids/erpnext,gangadhar-kadam/smrterp,meisterkleister/erpnext,indictranstech/buyback-erp,netfirms/erpnext,suyashphadtare/vestasi-erp-1,mbauskar/helpdesk-erpnext,gangadharkadam/sher,gangadharkadam/v4_erp,indictranstech/Das_Erpnext,netfirms/erpnext,gangadhar-kadam/helpdesk-erpnext,suyashphadtare/vestasi-erp-final,gangadharkadam/sher,gangadharkadam/tailorerp,gangadhar-kadam/verve_erp,suyashphadtare/vestasi-update-erp,indictranstech/reciphergroup-erpnext,gangadhar-kadam/verve_test_erp,hatwar/focal-erpnext,gmarke/erpnext,pawaranand/phrerp,rohitwaghchaure/erpnext-receipher,indictranstech/osmosis-erpnext,rohitwaghchaure/erpnext_smart,mbauskar/helpdesk-erpnext,suyashphadtare/vestasi-erp-jan-end,gangadharkadam/letzerp,gangadharkadam/tailorerp,pombredanne/erpnext,mbauskar/Das_Erpnext,gangadhar-kadam/verve-erp,indictranstech/internal-erpnext,suyashphadtare/vestasi-update-erp,mbauskar/sapphire-erpnext,suyashphadtare/vestasi-erp-1,gangadharkadam/v6_erp,rohitwaghchaure/digitales_erpnext,suyashphadtare/sajil-erp,indictranstech/fbd_erpnext,indictranstech/vestasi-erpnext,aruizramon/alec_erpnext,gsnbng/erpnext,BhupeshGupta/erpnext,gangadhar-kadam/helpdesk-erpnext,gangadharkadam/vlinkerp,gangadharkadam/verveerp,Drooids/erpnext,SPKian/Testing,saurabh6790/test-erp,dieface/erpnext,dieface/erpnext,shft117/SteckerApp,4commerce-technologies-AG/erpnext,gangadhar-kadam/verve_live_erp,indictranstech/trufil-erpnext,gangadhar-kadam/laganerp,gsnbng/erpnext,mbauskar/omnitech-demo-erpnext,gangadharkadam/verveerp,Tejal011089/osmosis_erpnext,indictranstech/biggift-erpnext,suyashphadtare/sajil-final-erp,meisterkleister/erpnext,indictranstech/buyback-erp,indictranstech/biggift-erpnext,rohitwaghchaure/digitales_erpnext,indictranstech/erpnext,rohitwaghchaure/New_Theme_Erp,indictranstech/tele-erpnext,hatwar/buyback-erpnext,indictranstech/phrerp,gangadharkadam/v4_erp,netfirms/erpnext,Tejal011089/huntercamp_erpnext,sagar30051991/ozsmart-erp,suyashphadtare/vestasi-update-erp | // Copyright (c) 2013, Web Notes Technologies Pvt. Ltd. and Contributors
// License: GNU General Public License v3. See license.txt
cur_frm.cscript.tname = "Stock Entry Detail";
cur_frm.cscript.fname = "mtn_details";
frappe.require("assets/erpnext/js/controllers/stock_controller.js");
frappe.provide("erpnext.stock");
erpnext.stock.StockEntry = erpnext.stock.StockController.extend({
setup: function() {
var me = this;
this.frm.fields_dict.delivery_note_no.get_query = function() {
return { query: "erpnext.stock.doctype.stock_entry.stock_entry.query_sales_return_doc" };
};
this.frm.fields_dict.sales_invoice_no.get_query =
this.frm.fields_dict.delivery_note_no.get_query;
this.frm.fields_dict.purchase_receipt_no.get_query = function() {
return {
filters:{ 'docstatus': 1 }
};
};
this.frm.fields_dict.mtn_details.grid.get_field('item_code').get_query = function() {
if(in_list(["Sales Return", "Purchase Return"], me.frm.doc.purpose) &&
me.get_doctype_docname()) {
return {
query: "erpnext.stock.doctype.stock_entry.stock_entry.query_return_item",
filters: {
purpose: me.frm.doc.purpose,
delivery_note_no: me.frm.doc.delivery_note_no,
sales_invoice_no: me.frm.doc.sales_invoice_no,
purchase_receipt_no: me.frm.doc.purchase_receipt_no
}
};
} else {
return erpnext.queries.item({is_stock_item: "Yes"});
}
};
if(cint(frappe.defaults.get_default("auto_accounting_for_stock"))) {
this.frm.add_fetch("company", "stock_adjustment_account", "expense_account");
this.frm.fields_dict.mtn_details.grid.get_field('expense_account').get_query =
function() {
return {
filters: {
"company": me.frm.doc.company,
"group_or_ledger": "Ledger"
}
}
}
}
},
onload_post_render: function() {
cur_frm.get_field(this.fname).grid.set_multiple_add("item_code", "qty");
this.set_default_account();
},
refresh: function() {
var me = this;
erpnext.toggle_naming_series();
this.toggle_related_fields(this.frm.doc);
this.toggle_enable_bom();
this.show_stock_ledger();
this.show_general_ledger();
if(this.frm.doc.docstatus === 1 &&
frappe.boot.user.can_create.indexOf("Journal Voucher")!==-1) {
if(this.frm.doc.purpose === "Sales Return") {
this.frm.add_custom_button(__("Make Credit Note"), function() { me.make_return_jv(); });
this.add_excise_button();
} else if(this.frm.doc.purpose === "Purchase Return") {
this.frm.add_custom_button(__("Make Debit Note"), function() { me.make_return_jv(); });
this.add_excise_button();
}
}
},
on_submit: function() {
this.clean_up();
},
after_cancel: function() {
this.clean_up();
},
set_default_account: function() {
var me = this;
if(cint(frappe.defaults.get_default("auto_accounting_for_stock"))) {
var account_for = "stock_adjustment_account";
if (this.frm.doc.purpose == "Purchase Return")
account_for = "stock_received_but_not_billed";
return this.frm.call({
method: "erpnext.accounts.utils.get_company_default",
args: {
"fieldname": account_for,
"company": this.frm.doc.company
},
callback: function(r) {
if (!r.exc) {
$.each(me.frm.doc.mtn_details || [], function(i, d) {
if(!d.expense_account) d.expense_account = r.message;
});
}
}
});
}
},
clean_up: function() {
// Clear Production Order record from locals, because it is updated via Stock Entry
if(this.frm.doc.production_order &&
this.frm.doc.purpose == "Manufacture/Repack") {
frappe.model.remove_from_locals("Production Order",
this.frm.doc.production_order);
}
},
get_items: function() {
if(this.frm.doc.production_order || this.frm.doc.bom_no) {
// if production order / bom is mentioned, get items
return this.frm.call({
doc: this.frm.doc,
method: "get_items",
callback: function(r) {
if(!r.exc) refresh_field("mtn_details");
}
});
}
},
qty: function(doc, cdt, cdn) {
var d = locals[cdt][cdn];
d.transfer_qty = flt(d.qty) * flt(d.conversion_factor);
refresh_field('mtn_details');
},
production_order: function() {
var me = this;
this.toggle_enable_bom();
return this.frm.call({
method: "get_production_order_details",
args: {production_order: this.frm.doc.production_order},
callback: function(r) {
if (!r.exc) {
if (me.frm.doc.purpose == "Material Transfer" && !me.frm.doc.to_warehouse)
me.frm.set_value("to_warehouse", r.message["wip_warehouse"]);
}
}
});
},
toggle_enable_bom: function() {
this.frm.toggle_enable("bom_no", !this.frm.doc.production_order);
},
get_doctype_docname: function() {
if(this.frm.doc.purpose === "Sales Return") {
if(this.frm.doc.delivery_note_no && this.frm.doc.sales_invoice_no) {
// both specified
msgprint(__("You can not enter both Delivery Note No and Sales Invoice No. Please enter any one."));
} else if(!(this.frm.doc.delivery_note_no || this.frm.doc.sales_invoice_no)) {
// none specified
msgprint(__("Please enter Delivery Note No or Sales Invoice No to proceed"));
} else if(this.frm.doc.delivery_note_no) {
return {doctype: "Delivery Note", docname: this.frm.doc.delivery_note_no};
} else if(this.frm.doc.sales_invoice_no) {
return {doctype: "Sales Invoice", docname: this.frm.doc.sales_invoice_no};
}
} else if(this.frm.doc.purpose === "Purchase Return") {
if(this.frm.doc.purchase_receipt_no) {
return {doctype: "Purchase Receipt", docname: this.frm.doc.purchase_receipt_no};
} else {
// not specified
msgprint(__("Please enter Purchase Receipt No to proceed"));
}
}
},
add_excise_button: function() {
if(frappe.boot.sysdefaults.country === "India")
this.frm.add_custom_button(__("Make Excise Invoice"), function() {
var excise = frappe.model.make_new_doc_and_get_name('Journal Voucher');
excise = locals['Journal Voucher'][excise];
excise.voucher_type = 'Excise Voucher';
loaddoc('Journal Voucher', excise.name);
});
},
make_return_jv: function() {
if(this.get_doctype_docname()) {
return this.frm.call({
method: "make_return_jv",
args: {
stock_entry: this.frm.doc.name
},
callback: function(r) {
if(!r.exc) {
var jv_name = frappe.model.make_new_doc_and_get_name('Journal Voucher');
var jv = locals["Journal Voucher"][jv_name];
$.extend(jv, r.message);
loaddoc("Journal Voucher", jv_name);
}
}
});
}
},
mtn_details_add: function(doc, cdt, cdn) {
var row = frappe.get_doc(cdt, cdn);
this.frm.script_manager.copy_from_first_row("mtn_details", row,
["expense_account", "cost_center"]);
if(!row.s_warehouse) row.s_warehouse = this.frm.doc.from_warehouse;
if(!row.t_warehouse) row.t_warehouse = this.frm.doc.to_warehouse;
},
mtn_details_on_form_rendered: function(doc, grid_row) {
erpnext.setup_serial_no(grid_row)
},
customer: function() {
return this.frm.call({
method: "erpnext.accounts.party.get_party_details",
args: { party: this.frm.doc.customer, party_type:"Customer", doctype: this.frm.doc.doctype }
});
},
supplier: function() {
return this.frm.call({
method: "erpnext.accounts.party.get_party_details",
args: { party: this.frm.doc.supplier, party_type:"Supplier", doctype: this.frm.doc.doctype }
});
},
delivery_note_no: function() {
this.get_party_details({
ref_dt: "Delivery Note",
ref_dn: this.frm.doc.delivery_note_no
})
},
sales_invoice_no: function() {
this.get_party_details({
ref_dt: "Sales Invoice",
ref_dn: this.frm.doc.sales_invoice_no
})
},
purchase_receipt_no: function() {
this.get_party_details({
ref_dt: "Purchase Receipt",
ref_dn: this.frm.doc.purchase_receipt_no
})
},
get_party_details: function(args) {
return this.frm.call({
method: "erpnext.stock.doctype.stock_entry.stock_entry.get_party_details",
args: args,
})
}
});
cur_frm.script_manager.make(erpnext.stock.StockEntry);
cur_frm.cscript.toggle_related_fields = function(doc) {
disable_from_warehouse = inList(["Material Receipt", "Sales Return"], doc.purpose);
disable_to_warehouse = inList(["Material Issue", "Purchase Return"], doc.purpose);
cur_frm.toggle_enable("from_warehouse", !disable_from_warehouse);
cur_frm.toggle_enable("to_warehouse", !disable_to_warehouse);
cur_frm.fields_dict["mtn_details"].grid.set_column_disp("s_warehouse", !disable_from_warehouse);
cur_frm.fields_dict["mtn_details"].grid.set_column_disp("t_warehouse", !disable_to_warehouse);
if(doc.purpose == 'Purchase Return') {
doc.customer = doc.customer_name = doc.customer_address =
doc.delivery_note_no = doc.sales_invoice_no = null;
doc.bom_no = doc.production_order = doc.fg_completed_qty = null;
} else if(doc.purpose == 'Sales Return') {
doc.supplier=doc.supplier_name = doc.supplier_address = doc.purchase_receipt_no=null;
doc.bom_no = doc.production_order = doc.fg_completed_qty = null;
} else {
doc.customer = doc.customer_name = doc.customer_address =
doc.delivery_note_no = doc.sales_invoice_no = doc.supplier =
doc.supplier_name = doc.supplier_address = doc.purchase_receipt_no = null;
}
}
cur_frm.fields_dict['production_order'].get_query = function(doc) {
return {
filters: [
['Production Order', 'docstatus', '=', 1],
['Production Order', 'qty', '>','`tabProduction Order`.produced_qty']
]
}
}
cur_frm.cscript.purpose = function(doc, cdt, cdn) {
cur_frm.cscript.toggle_related_fields(doc);
}
// Overloaded query for link batch_no
cur_frm.fields_dict['mtn_details'].grid.get_field('batch_no').get_query = function(doc, cdt, cdn) {
var d = locals[cdt][cdn];
if(d.item_code) {
return{
query: "erpnext.stock.doctype.stock_entry.stock_entry.get_batch_no",
filters:{
'item_code': d.item_code,
's_warehouse': d.s_warehouse,
'posting_date': doc.posting_date
}
}
} else {
msgprint(__("Please enter Item Code to get batch no"));
}
}
cur_frm.cscript.item_code = function(doc, cdt, cdn) {
var d = locals[cdt][cdn];
if(d.item_code) {
args = {
'item_code' : d.item_code,
'warehouse' : cstr(d.s_warehouse) || cstr(d.t_warehouse),
'transfer_qty' : d.transfer_qty,
'serial_no' : d.serial_no,
'bom_no' : d.bom_no,
'expense_account' : d.expense_account,
'cost_center' : d.cost_center,
'company' : cur_frm.doc.company
};
return get_server_fields('get_item_details', JSON.stringify(args),
'mtn_details', doc, cdt, cdn, 1);
}
}
cur_frm.cscript.s_warehouse = function(doc, cdt, cdn) {
var d = locals[cdt][cdn];
if(!d.bom_no) {
args = {
'item_code' : d.item_code,
'warehouse' : cstr(d.s_warehouse) || cstr(d.t_warehouse),
'transfer_qty' : d.transfer_qty,
'serial_no' : d.serial_no,
'qty' : d.s_warehouse ? -1* d.qty : d.qty
}
return get_server_fields('get_warehouse_details', JSON.stringify(args),
'mtn_details', doc, cdt, cdn, 1);
}
}
cur_frm.cscript.t_warehouse = cur_frm.cscript.s_warehouse;
cur_frm.cscript.uom = function(doc, cdt, cdn) {
var d = locals[cdt][cdn];
if(d.uom && d.item_code){
var arg = {'item_code':d.item_code, 'uom':d.uom, 'qty':d.qty}
return get_server_fields('get_uom_details', JSON.stringify(arg),
'mtn_details', doc, cdt, cdn, 1);
}
}
cur_frm.cscript.validate = function(doc, cdt, cdn) {
cur_frm.cscript.validate_items(doc);
if($.inArray(cur_frm.doc.purpose, ["Purchase Return", "Sales Return"])!==-1)
validated = cur_frm.cscript.get_doctype_docname() ? true : false;
}
cur_frm.cscript.validate_items = function(doc) {
cl = doc.mtn_details || [];
if (!cl.length) {
msgprint(__("Item table can not be blank"));
validated = false;
}
}
cur_frm.cscript.expense_account = function(doc, cdt, cdn) {
cur_frm.cscript.copy_account_in_all_row(doc, cdt, cdn, "expense_account");
}
cur_frm.cscript.cost_center = function(doc, cdt, cdn) {
cur_frm.cscript.copy_account_in_all_row(doc, cdt, cdn, "cost_center");
}
cur_frm.fields_dict.customer.get_query = function(doc, cdt, cdn) {
return { query: "erpnext.controllers.queries.customer_query" }
}
cur_frm.fields_dict.supplier.get_query = function(doc, cdt, cdn) {
return { query: "erpnext.controllers.queries.supplier_query" }
}
| erpnext/stock/doctype/stock_entry/stock_entry.js | // Copyright (c) 2013, Web Notes Technologies Pvt. Ltd. and Contributors
// License: GNU General Public License v3. See license.txt
cur_frm.cscript.tname = "Stock Entry Detail";
cur_frm.cscript.fname = "mtn_details";
frappe.require("assets/erpnext/js/controllers/stock_controller.js");
frappe.provide("erpnext.stock");
erpnext.stock.StockEntry = erpnext.stock.StockController.extend({
setup: function() {
var me = this;
this.frm.fields_dict.delivery_note_no.get_query = function() {
return { query: "erpnext.stock.doctype.stock_entry.stock_entry.query_sales_return_doc" };
};
this.frm.fields_dict.sales_invoice_no.get_query =
this.frm.fields_dict.delivery_note_no.get_query;
this.frm.fields_dict.purchase_receipt_no.get_query = function() {
return {
filters:{ 'docstatus': 1 }
};
};
this.frm.fields_dict.mtn_details.grid.get_field('item_code').get_query = function() {
if(in_list(["Sales Return", "Purchase Return"], me.frm.doc.purpose) &&
me.get_doctype_docname()) {
return {
query: "erpnext.stock.doctype.stock_entry.stock_entry.query_return_item",
filters: {
purpose: me.frm.doc.purpose,
delivery_note_no: me.frm.doc.delivery_note_no,
sales_invoice_no: me.frm.doc.sales_invoice_no,
purchase_receipt_no: me.frm.doc.purchase_receipt_no
}
};
} else {
return erpnext.queries.item({is_stock_item: "Yes"});
}
};
if(cint(frappe.defaults.get_default("auto_accounting_for_stock"))) {
this.frm.add_fetch("company", "stock_adjustment_account", "expense_account");
this.frm.fields_dict.mtn_details.grid.get_field('expense_account').get_query =
function() {
return {
filters: {
"company": me.frm.doc.company,
"group_or_ledger": "Ledger"
}
}
}
}
},
onload_post_render: function() {
cur_frm.get_field(this.fname).grid.set_multiple_add("item_code", "qty");
this.set_default_account();
},
refresh: function() {
var me = this;
erpnext.toggle_naming_series();
this.toggle_related_fields(this.frm.doc);
this.toggle_enable_bom();
this.show_stock_ledger();
this.show_general_ledger();
if(this.frm.doc.docstatus === 1 &&
frappe.boot.user.can_create.indexOf("Journal Voucher")!==-1) {
if(this.frm.doc.purpose === "Sales Return") {
this.frm.add_custom_button(__("Make Credit Note"), function() { me.make_return_jv(); });
this.add_excise_button();
} else if(this.frm.doc.purpose === "Purchase Return") {
this.frm.add_custom_button(__("Make Debit Note"), function() { me.make_return_jv(); });
this.add_excise_button();
}
}
},
on_submit: function() {
this.clean_up();
},
after_cancel: function() {
this.clean_up();
},
set_default_account: function() {
var me = this;
if(cint(frappe.defaults.get_default("auto_accounting_for_stock"))) {
var account_for = "stock_adjustment_account";
if (this.frm.doc.purpose == "Purchase Return")
account_for = "stock_received_but_not_billed";
return this.frm.call({
method: "erpnext.accounts.utils.get_company_default",
args: {
"fieldname": account_for,
"company": this.frm.doc.company
},
callback: function(r) {
if (!r.exc) {
$.each(me.frm.doc.mtn_details || [], function(i, d) {
if(!d.expense_account) d.expense_account = r.message;
});
}
}
});
}
},
clean_up: function() {
// Clear Production Order record from locals, because it is updated via Stock Entry
if(this.frm.doc.production_order &&
this.frm.doc.purpose == "Manufacture/Repack") {
frappe.model.remove_from_locals("Production Order",
this.frm.doc.production_order);
}
},
get_items: function() {
if(this.frm.doc.production_order || this.frm.doc.bom_no) {
// if production order / bom is mentioned, get items
return this.frm.call({
doc: this.frm.doc,
method: "get_items",
callback: function(r) {
if(!r.exc) refresh_field("mtn_details");
}
});
}
},
qty: function(doc, cdt, cdn) {
var d = locals[cdt][cdn];
d.transfer_qty = flt(d.qty) * flt(d.conversion_factor);
refresh_field('mtn_details');
},
production_order: function() {
var me = this;
this.toggle_enable_bom();
return this.frm.call({
method: "get_production_order_details",
args: {production_order: this.frm.doc.production_order},
callback: function(r) {
if (!r.exc) {
if (me.frm.doc.purpose == "Material Transfer" && !me.frm.doc.to_warehouse)
me.frm.set_value("to_warehouse", r.message["wip_warehouse"]);
}
}
});
},
toggle_enable_bom: function() {
this.frm.toggle_enable("bom_no", !this.frm.doc.production_order);
},
get_doctype_docname: function() {
if(this.frm.doc.purpose === "Sales Return") {
if(this.frm.doc.delivery_note_no && this.frm.doc.sales_invoice_no) {
// both specified
msgprint(__("You can not enter both Delivery Note No and Sales Invoice No. Please enter any one."));
} else if(!(this.frm.doc.delivery_note_no || this.frm.doc.sales_invoice_no)) {
// none specified
msgprint(__("Please enter Delivery Note No or Sales Invoice No to proceed"));
} else if(this.frm.doc.delivery_note_no) {
return {doctype: "Delivery Note", docname: this.frm.doc.delivery_note_no};
} else if(this.frm.doc.sales_invoice_no) {
return {doctype: "Sales Invoice", docname: this.frm.doc.sales_invoice_no};
}
} else if(this.frm.doc.purpose === "Purchase Return") {
if(this.frm.doc.purchase_receipt_no) {
return {doctype: "Purchase Receipt", docname: this.frm.doc.purchase_receipt_no};
} else {
// not specified
msgprint(__("Please enter Purchase Receipt No to proceed"));
}
}
},
add_excise_button: function() {
if(frappe.boot.sysdefaults.country === "India")
this.frm.add_custom_button(__("Make Excise Invoice"), function() {
var excise = frappe.model.make_new_doc_and_get_name('Journal Voucher');
excise = locals['Journal Voucher'][excise];
excise.voucher_type = 'Excise Voucher';
loaddoc('Journal Voucher', excise.name);
});
},
make_return_jv: function() {
if(this.get_doctype_docname()) {
return this.frm.call({
method: "make_return_jv",
args: {
stock_entry: this.frm.doc.name
},
callback: function(r) {
if(!r.exc) {
var jv_name = frappe.model.make_new_doc_and_get_name('Journal Voucher');
var jv = locals["Journal Voucher"][jv_name];
$.extend(jv, r.message[0]);
$.each(r.message.slice(1), function(i, jvd) {
var child = frappe.model.add_child(jv, "Journal Voucher Detail", "entries");
$.extend(child, jvd);
});
loaddoc("Journal Voucher", jv_name);
}
}
});
}
},
mtn_details_add: function(doc, cdt, cdn) {
var row = frappe.get_doc(cdt, cdn);
this.frm.script_manager.copy_from_first_row("mtn_details", row,
["expense_account", "cost_center"]);
if(!row.s_warehouse) row.s_warehouse = this.frm.doc.from_warehouse;
if(!row.t_warehouse) row.t_warehouse = this.frm.doc.to_warehouse;
},
mtn_details_on_form_rendered: function(doc, grid_row) {
erpnext.setup_serial_no(grid_row)
},
customer: function() {
return this.frm.call({
method: "erpnext.accounts.party.get_party_details",
args: { party: this.frm.doc.customer, party_type:"Customer", doctype: this.frm.doc.doctype }
});
},
supplier: function() {
return this.frm.call({
method: "erpnext.accounts.party.get_party_details",
args: { party: this.frm.doc.supplier, party_type:"Supplier", doctype: this.frm.doc.doctype }
});
},
delivery_note_no: function() {
this.get_party_details({
ref_dt: "Delivery Note",
ref_dn: this.frm.doc.delivery_note_no
})
},
sales_invoice_no: function() {
this.get_party_details({
ref_dt: "Sales Invoice",
ref_dn: this.frm.doc.sales_invoice_no
})
},
purchase_receipt_no: function() {
this.get_party_details({
ref_dt: "Purchase Receipt",
ref_dn: this.frm.doc.purchase_receipt_no
})
},
get_party_details: function(args) {
return this.frm.call({
method: "erpnext.stock.doctype.stock_entry.stock_entry.get_party_details",
args: args,
})
}
});
cur_frm.script_manager.make(erpnext.stock.StockEntry);
cur_frm.cscript.toggle_related_fields = function(doc) {
disable_from_warehouse = inList(["Material Receipt", "Sales Return"], doc.purpose);
disable_to_warehouse = inList(["Material Issue", "Purchase Return"], doc.purpose);
cur_frm.toggle_enable("from_warehouse", !disable_from_warehouse);
cur_frm.toggle_enable("to_warehouse", !disable_to_warehouse);
cur_frm.fields_dict["mtn_details"].grid.set_column_disp("s_warehouse", !disable_from_warehouse);
cur_frm.fields_dict["mtn_details"].grid.set_column_disp("t_warehouse", !disable_to_warehouse);
if(doc.purpose == 'Purchase Return') {
doc.customer = doc.customer_name = doc.customer_address =
doc.delivery_note_no = doc.sales_invoice_no = null;
doc.bom_no = doc.production_order = doc.fg_completed_qty = null;
} else if(doc.purpose == 'Sales Return') {
doc.supplier=doc.supplier_name = doc.supplier_address = doc.purchase_receipt_no=null;
doc.bom_no = doc.production_order = doc.fg_completed_qty = null;
} else {
doc.customer = doc.customer_name = doc.customer_address =
doc.delivery_note_no = doc.sales_invoice_no = doc.supplier =
doc.supplier_name = doc.supplier_address = doc.purchase_receipt_no = null;
}
}
cur_frm.fields_dict['production_order'].get_query = function(doc) {
return {
filters: [
['Production Order', 'docstatus', '=', 1],
['Production Order', 'qty', '>','`tabProduction Order`.produced_qty']
]
}
}
cur_frm.cscript.purpose = function(doc, cdt, cdn) {
cur_frm.cscript.toggle_related_fields(doc);
}
// Overloaded query for link batch_no
cur_frm.fields_dict['mtn_details'].grid.get_field('batch_no').get_query = function(doc, cdt, cdn) {
var d = locals[cdt][cdn];
if(d.item_code) {
return{
query: "erpnext.stock.doctype.stock_entry.stock_entry.get_batch_no",
filters:{
'item_code': d.item_code,
's_warehouse': d.s_warehouse,
'posting_date': doc.posting_date
}
}
} else {
msgprint(__("Please enter Item Code to get batch no"));
}
}
cur_frm.cscript.item_code = function(doc, cdt, cdn) {
var d = locals[cdt][cdn];
if(d.item_code) {
args = {
'item_code' : d.item_code,
'warehouse' : cstr(d.s_warehouse) || cstr(d.t_warehouse),
'transfer_qty' : d.transfer_qty,
'serial_no' : d.serial_no,
'bom_no' : d.bom_no,
'expense_account' : d.expense_account,
'cost_center' : d.cost_center,
'company' : cur_frm.doc.company
};
return get_server_fields('get_item_details', JSON.stringify(args),
'mtn_details', doc, cdt, cdn, 1);
}
}
cur_frm.cscript.s_warehouse = function(doc, cdt, cdn) {
var d = locals[cdt][cdn];
if(!d.bom_no) {
args = {
'item_code' : d.item_code,
'warehouse' : cstr(d.s_warehouse) || cstr(d.t_warehouse),
'transfer_qty' : d.transfer_qty,
'serial_no' : d.serial_no,
'qty' : d.s_warehouse ? -1* d.qty : d.qty
}
return get_server_fields('get_warehouse_details', JSON.stringify(args),
'mtn_details', doc, cdt, cdn, 1);
}
}
cur_frm.cscript.t_warehouse = cur_frm.cscript.s_warehouse;
cur_frm.cscript.uom = function(doc, cdt, cdn) {
var d = locals[cdt][cdn];
if(d.uom && d.item_code){
var arg = {'item_code':d.item_code, 'uom':d.uom, 'qty':d.qty}
return get_server_fields('get_uom_details', JSON.stringify(arg),
'mtn_details', doc, cdt, cdn, 1);
}
}
cur_frm.cscript.validate = function(doc, cdt, cdn) {
cur_frm.cscript.validate_items(doc);
if($.inArray(cur_frm.doc.purpose, ["Purchase Return", "Sales Return"])!==-1)
validated = cur_frm.cscript.get_doctype_docname() ? true : false;
}
cur_frm.cscript.validate_items = function(doc) {
cl = doc.mtn_details || [];
if (!cl.length) {
msgprint(__("Item table can not be blank"));
validated = false;
}
}
cur_frm.cscript.expense_account = function(doc, cdt, cdn) {
cur_frm.cscript.copy_account_in_all_row(doc, cdt, cdn, "expense_account");
}
cur_frm.cscript.cost_center = function(doc, cdt, cdn) {
cur_frm.cscript.copy_account_in_all_row(doc, cdt, cdn, "cost_center");
}
cur_frm.fields_dict.customer.get_query = function(doc, cdt, cdn) {
return { query: "erpnext.controllers.queries.customer_query" }
}
cur_frm.fields_dict.supplier.get_query = function(doc, cdt, cdn) {
return { query: "erpnext.controllers.queries.supplier_query" }
}
| Make debit/credit note from sales/purchase return
| erpnext/stock/doctype/stock_entry/stock_entry.js | Make debit/credit note from sales/purchase return | <ide><path>rpnext/stock/doctype/stock_entry/stock_entry.js
<ide> if(!r.exc) {
<ide> var jv_name = frappe.model.make_new_doc_and_get_name('Journal Voucher');
<ide> var jv = locals["Journal Voucher"][jv_name];
<del> $.extend(jv, r.message[0]);
<del> $.each(r.message.slice(1), function(i, jvd) {
<del> var child = frappe.model.add_child(jv, "Journal Voucher Detail", "entries");
<del> $.extend(child, jvd);
<del> });
<add> $.extend(jv, r.message);
<ide> loaddoc("Journal Voucher", jv_name);
<ide> }
<ide> } |
|
Java | apache-2.0 | c2853da73d98c59691e2985ad6337171d574940b | 0 | RussellWilby/Aeron,UIKit0/Aeron,galderz/Aeron,mikeb01/Aeron,RussellWilby/Aeron,johnpr01/Aeron,gkamal/Aeron,rlankenau/Aeron,strangelydim/Aeron,ycaihua/Aeron,qed-/Aeron,EvilMcJerkface/Aeron,real-logic/Aeron,mikeb01/Aeron,EvilMcJerkface/Aeron,real-logic/Aeron,gkamal/Aeron,gkamal/Aeron,real-logic/Aeron,galderz/Aeron,strangelydim/Aeron,johnpr01/Aeron,buybackoff/Aeron,real-logic/Aeron,mikeb01/Aeron,mikeb01/Aeron,jessefugitt/Aeron,UIKit0/Aeron,oleksiyp/Aeron,jessefugitt/Aeron,buybackoff/Aeron,qed-/Aeron,galderz/Aeron,johnpr01/Aeron,qed-/Aeron,ycaihua/Aeron,strangelydim/Aeron,jerrinot/Aeron,ycaihua/Aeron,qed-/Aeron,rlankenau/Aeron,UIKit0/Aeron,oleksiyp/Aeron,galderz/Aeron,tbrooks8/Aeron,rlankenau/Aeron,lennartj/Aeron,EvilMcJerkface/Aeron,oleksiyp/Aeron,lennartj/Aeron,buybackoff/Aeron,jerrinot/Aeron,EvilMcJerkface/Aeron,lennartj/Aeron,jerrinot/Aeron,tbrooks8/Aeron,jessefugitt/Aeron,RussellWilby/Aeron,tbrooks8/Aeron | /*
* Copyright 2014 Real Logic Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package uk.co.real_logic.aeron.util;
import org.junit.Test;
import java.util.HashSet;
import java.util.Set;
import static java.util.Arrays.asList;
import static org.junit.Assert.assertTrue;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.empty;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertNull;
public class AtomicArrayTest
{
private final AtomicArray<Integer> array = new AtomicArray<>();
@Test
public void shouldHandleAddToEmptyArray()
{
array.add(10);
assertThat(array.size(), is(1));
assertThat(array.get(0), is(10));
}
@Test
public void shouldHandleAddToNonEmptyArray()
{
array.add(10);
array.add(20);
assertThat(array.size(), is(2));
assertThat(array.get(0), is(10));
assertThat(array.get(1), is(20));
}
@Test
public void shouldHandleRemoveFromEmptyArray()
{
array.remove(10);
assertThat(array.size(), is(0));
}
@Test
public void shouldHandleRemoveFromOneElementArray()
{
array.add(10);
array.remove(10);
assertThat(array.size(), is(0));
}
@Test
public void shouldHandleRemoveOfNonExistentElementFromOneElementArray()
{
array.add(10);
array.remove(20);
assertThat(array.size(), is(1));
assertThat(array.get(0), is(10));
}
@Test
public void shouldHandleRemoveOfNonExistentElementFromArray()
{
array.add(10);
array.add(20);
array.remove(30);
assertThat(array.size(), is(2));
assertThat(array.get(0), is(10));
assertThat(array.get(1), is(20));
}
@Test
public void shouldHandleRemoveElementFromArrayEnd()
{
array.add(10);
array.add(20);
array.remove(20);
assertThat(array.size(), is(1));
assertThat(array.get(0), is(10));
}
@Test
public void shouldHandleRemoveElementFromArrayBegin()
{
array.add(10);
array.add(20);
array.remove(10);
assertThat(array.size(), is(1));
assertThat(array.get(0), is(20));
}
@Test
public void shouldHandleRemoveElementFromArrayMiddle()
{
array.add(10);
array.add(20);
array.add(30);
array.remove(20);
assertThat(array.size(), is(2));
assertThat(array.get(0), is(10));
assertThat(array.get(1), is(30));
}
@Test
public void shouldIterateOverValuesInTheArray()
{
for (int start : new int[]{0, 1})
{
final Set<Integer> values = new HashSet<>(asList(10, 20, 30));
final AtomicArray<Integer> array = new AtomicArray<>();
values.forEach(array::add);
assertThat(array.forEach(start, (e) -> values.remove(e) ? 1 : 0), is(3));
assertThat(values, empty());
}
}
@Test
public void shouldHandleStartTooLargeTransparently()
{
final Set<Integer> values = new HashSet<>(asList(10, 20, 30));
values.forEach(array::add);
assertThat(array.forEach(4, (e) -> values.remove(e) ? 1 : 0), is(3));
assertThat(values, empty());
}
@Test
public void shouldNotFindInEmptyArray()
{
final Integer found = array.findFirst((e) -> e.equals(7));
assertNull(found);
}
@Test
public void shouldFindInArray()
{
final Integer matchItem = 3;
asList(1, 2, 3, 4, 5).forEach(array::add);
final Integer found = array.findFirst((e) -> e.equals(matchItem));
assertThat(found, is(matchItem));
}
@Test
public void shouldIterateValues()
{
asList(1, 2, 3, 4, 5).forEach(array::add);
int i = 1;
for (final int v : array)
{
assertThat(v, is(i++));
}
}
@Test
public void shouldReportEmpty()
{
assertTrue(array.isEmpty());
}
}
| aeron-util/src/test/java/uk/co/real_logic/aeron/util/AtomicArrayTest.java | /*
* Copyright 2014 Real Logic Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package uk.co.real_logic.aeron.util;
import org.junit.Test;
import java.util.HashSet;
import java.util.Set;
import static java.util.Arrays.asList;
import static junit.framework.Assert.assertTrue;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.empty;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertNull;
public class AtomicArrayTest
{
private final AtomicArray<Integer> array = new AtomicArray<>();
@Test
public void shouldHandleAddToEmptyArray()
{
array.add(10);
assertThat(array.size(), is(1));
assertThat(array.get(0), is(10));
}
@Test
public void shouldHandleAddToNonEmptyArray()
{
array.add(10);
array.add(20);
assertThat(array.size(), is(2));
assertThat(array.get(0), is(10));
assertThat(array.get(1), is(20));
}
@Test
public void shouldHandleRemoveFromEmptyArray()
{
array.remove(10);
assertThat(array.size(), is(0));
}
@Test
public void shouldHandleRemoveFromOneElementArray()
{
array.add(10);
array.remove(10);
assertThat(array.size(), is(0));
}
@Test
public void shouldHandleRemoveOfNonExistentElementFromOneElementArray()
{
array.add(10);
array.remove(20);
assertThat(array.size(), is(1));
assertThat(array.get(0), is(10));
}
@Test
public void shouldHandleRemoveOfNonExistentElementFromArray()
{
array.add(10);
array.add(20);
array.remove(30);
assertThat(array.size(), is(2));
assertThat(array.get(0), is(10));
assertThat(array.get(1), is(20));
}
@Test
public void shouldHandleRemoveElementFromArrayEnd()
{
array.add(10);
array.add(20);
array.remove(20);
assertThat(array.size(), is(1));
assertThat(array.get(0), is(10));
}
@Test
public void shouldHandleRemoveElementFromArrayBegin()
{
array.add(10);
array.add(20);
array.remove(10);
assertThat(array.size(), is(1));
assertThat(array.get(0), is(20));
}
@Test
public void shouldHandleRemoveElementFromArrayMiddle()
{
array.add(10);
array.add(20);
array.add(30);
array.remove(20);
assertThat(array.size(), is(2));
assertThat(array.get(0), is(10));
assertThat(array.get(1), is(30));
}
@Test
public void shouldIterateOverValuesInTheArray()
{
for (int start : new int[]{0, 1})
{
final Set<Integer> values = new HashSet<>(asList(10, 20, 30));
final AtomicArray<Integer> array = new AtomicArray<>();
values.forEach(array::add);
assertThat(array.forEach(start, (e) -> values.remove(e) ? 1 : 0), is(3));
assertThat(values, empty());
}
}
@Test
public void shouldHandleStartTooLargeTransparently()
{
final Set<Integer> values = new HashSet<>(asList(10, 20, 30));
values.forEach(array::add);
assertThat(array.forEach(4, (e) -> values.remove(e) ? 1 : 0), is(3));
assertThat(values, empty());
}
@Test
public void shouldNotFindInEmptyArray()
{
final Integer found = array.findFirst((e) -> e.equals(7));
assertNull(found);
}
@Test
public void shouldFindInArray()
{
final Integer matchItem = 3;
asList(1, 2, 3, 4, 5).forEach(array::add);
final Integer found = array.findFirst((e) -> e.equals(matchItem));
assertThat(found, is(matchItem));
}
@Test
public void shouldIterateValues()
{
asList(1, 2, 3, 4, 5).forEach(array::add);
int i = 1;
for (final int v : array)
{
assertThat(v, is(i++));
}
}
@Test
public void shouldReportEmpty()
{
assertTrue(array.isEmpty());
}
}
| [Java:] Replace deprecated method call.
| aeron-util/src/test/java/uk/co/real_logic/aeron/util/AtomicArrayTest.java | [Java:] Replace deprecated method call. | <ide><path>eron-util/src/test/java/uk/co/real_logic/aeron/util/AtomicArrayTest.java
<ide> import java.util.Set;
<ide>
<ide> import static java.util.Arrays.asList;
<del>import static junit.framework.Assert.assertTrue;
<add>import static org.junit.Assert.assertTrue;
<ide> import static org.hamcrest.MatcherAssert.assertThat;
<ide> import static org.hamcrest.Matchers.empty;
<ide> import static org.hamcrest.core.Is.is; |
|
Java | apache-2.0 | 60a688509e66cb9e06359598d3800a42ebec8f52 | 0 | buzzxu/nifty,andrewcox/nifty,szulijun/nifty,alandau/nifty,facebook/nifty,javazhangtao/nifty,electrum/nifty,ivmaykov/nifty | /*
* Copyright (C) 2012-2013 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.facebook.nifty.client;
import com.google.common.base.Strings;
import org.jboss.netty.channel.socket.nio.NioClientBossPool;
import org.jboss.netty.util.ThreadNameDeterminer;
import com.facebook.nifty.client.socks.Socks4ClientBootstrap;
import com.facebook.nifty.core.ShutdownUtil;
import com.google.common.util.concurrent.AbstractFuture;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.ThreadFactoryBuilder;
import io.airlift.units.Duration;
import org.apache.thrift.transport.TTransportException;
import org.jboss.netty.bootstrap.ClientBootstrap;
import org.jboss.netty.channel.Channel;
import org.jboss.netty.channel.ChannelFuture;
import org.jboss.netty.channel.ChannelFutureListener;
import org.jboss.netty.channel.group.ChannelGroup;
import org.jboss.netty.channel.group.DefaultChannelGroup;
import org.jboss.netty.channel.socket.nio.NioClientSocketChannelFactory;
import org.jboss.netty.channel.socket.nio.NioWorkerPool;
import org.jboss.netty.util.HashedWheelTimer;
import javax.annotation.Nullable;
import java.io.Closeable;
import java.net.InetSocketAddress;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;
import static java.util.concurrent.Executors.newCachedThreadPool;
public class NiftyClient implements Closeable
{
public static final Duration DEFAULT_CONNECT_TIMEOUT = new Duration(2, TimeUnit.SECONDS);
public static final Duration DEFAULT_READ_TIMEOUT = new Duration(2, TimeUnit.SECONDS);
private static final Duration DEFAULT_WRITE_TIMEOUT = new Duration(2, TimeUnit.SECONDS);
private static final int DEFAULT_MAX_FRAME_SIZE = 16777216;
private final NettyClientConfigBuilder configBuilder;
private final ExecutorService bossExecutor;
private final ExecutorService workerExecutor;
private final NioClientSocketChannelFactory channelFactory;
private final InetSocketAddress defaultSocksProxyAddress;
private final ChannelGroup allChannels = new DefaultChannelGroup();
private final HashedWheelTimer hashedWheelTimer;
/**
* Creates a new NiftyClient with defaults: cachedThreadPool for bossExecutor and workerExecutor
*/
public NiftyClient()
{
this(new NettyClientConfigBuilder());
}
public NiftyClient(NettyClientConfigBuilder configBuilder)
{
this(configBuilder, null);
}
public NiftyClient(
NettyClientConfigBuilder configBuilder,
@Nullable InetSocketAddress defaultSocksProxyAddress)
{
this.configBuilder = configBuilder;
String name = configBuilder.getNiftyName();
String prefix = "nifty-client" + (Strings.isNullOrEmpty(name) ? "" : "-" + name);
this.hashedWheelTimer = new HashedWheelTimer(renamingDaemonThreadFactory(prefix + "-timer-%s"));
this.bossExecutor = newCachedThreadPool(renamingDaemonThreadFactory(prefix + "-boss-%s"));
this.workerExecutor = newCachedThreadPool(renamingDaemonThreadFactory(prefix + "-worker-%s"));
this.defaultSocksProxyAddress = defaultSocksProxyAddress;
int bossThreadCount = configBuilder.getNiftyBossThreadCount();
int workerThreadCount = configBuilder.getNiftyWorkerThreadCount();
NioWorkerPool workerPool = new NioWorkerPool(workerExecutor, workerThreadCount, ThreadNameDeterminer.CURRENT);
NioClientBossPool bossPool = new NioClientBossPool(bossExecutor, bossThreadCount, hashedWheelTimer, ThreadNameDeterminer.CURRENT);
this.channelFactory = new NioClientSocketChannelFactory(bossPool, workerPool);
}
public <T extends NiftyClientChannel> ListenableFuture<T> connectAsync(
NiftyClientConnector<T> clientChannelConnector)
{
return connectAsync(clientChannelConnector,
DEFAULT_CONNECT_TIMEOUT,
DEFAULT_READ_TIMEOUT,
DEFAULT_WRITE_TIMEOUT,
DEFAULT_MAX_FRAME_SIZE,
defaultSocksProxyAddress);
}
public <T extends NiftyClientChannel> ListenableFuture<T> connectAsync(
NiftyClientConnector<T> clientChannelConnector,
Duration connectTimeout,
Duration receiveTimeout,
Duration sendTimeout,
int maxFrameSize)
{
return connectAsync(clientChannelConnector,
connectTimeout,
receiveTimeout,
sendTimeout,
maxFrameSize,
defaultSocksProxyAddress);
}
public <T extends NiftyClientChannel> ListenableFuture<T> connectAsync(
NiftyClientConnector<T> clientChannelConnector,
Duration connectTimeout,
Duration receiveTimeout,
Duration sendTimeout,
int maxFrameSize,
@Nullable InetSocketAddress socksProxyAddress)
{
ClientBootstrap bootstrap = createClientBootstrap(socksProxyAddress);
bootstrap.setOptions(configBuilder.getOptions());
bootstrap.setOption("connectTimeoutMillis", (long)connectTimeout.toMillis());
bootstrap.setPipelineFactory(clientChannelConnector.newChannelPipelineFactory(maxFrameSize));
ChannelFuture nettyChannelFuture = clientChannelConnector.connect(bootstrap);
nettyChannelFuture.addListener(new ChannelFutureListener() {
@Override
public void operationComplete(ChannelFuture future) throws Exception {
Channel channel = future.getChannel();
if (channel != null && channel.isOpen()) {
allChannels.add(channel);
}
}
});
return new TNiftyFuture<>(clientChannelConnector,
receiveTimeout,
sendTimeout,
nettyChannelFuture);
}
// trying to mirror the synchronous nature of TSocket as much as possible here.
public TNiftyClientTransport connectSync(InetSocketAddress addr)
throws TTransportException, InterruptedException
{
return connectSync(addr, DEFAULT_CONNECT_TIMEOUT, DEFAULT_READ_TIMEOUT, DEFAULT_WRITE_TIMEOUT, DEFAULT_MAX_FRAME_SIZE);
}
public TNiftyClientTransport connectSync(
InetSocketAddress addr,
Duration connectTimeout,
Duration receiveTimeout,
Duration sendTimeout,
int maxFrameSize)
throws TTransportException, InterruptedException
{
return connectSync(addr, connectTimeout, receiveTimeout, sendTimeout, maxFrameSize, defaultSocksProxyAddress);
}
public TNiftyClientTransport connectSync(
InetSocketAddress addr,
Duration connectTimeout,
Duration receiveTimeout,
Duration sendTimeout,
int maxFrameSize,
@Nullable InetSocketAddress socksProxyAddress)
throws TTransportException, InterruptedException
{
// TODO: implement send timeout for sync client
ClientBootstrap bootstrap = createClientBootstrap(socksProxyAddress);
bootstrap.setOptions(configBuilder.getOptions());
bootstrap.setOption("connectTimeoutMillis", (long) connectTimeout.toMillis());
bootstrap.setPipelineFactory(new NiftyClientChannelPipelineFactory(maxFrameSize));
ChannelFuture f = bootstrap.connect(addr);
f.await();
Channel channel = f.getChannel();
if (f.getCause() != null) {
String message = String.format("unable to connect to %s:%d %s",
addr.getHostName(),
addr.getPort(),
socksProxyAddress == null ? "" : "via socks proxy at " + socksProxyAddress);
throw new TTransportException(message, f.getCause());
}
if (f.isSuccess() && (channel != null)) {
if (channel.isOpen()) {
allChannels.add(channel);
}
TNiftyClientTransport transport = new TNiftyClientTransport(channel, receiveTimeout);
channel.getPipeline().addLast("thrift", transport);
return transport;
}
throw new TTransportException(String.format(
"unknown error connecting to %s:%d %s",
addr.getHostName(),
addr.getPort(),
socksProxyAddress == null ? "" : "via socks proxy at " + socksProxyAddress
));
}
@Override
public void close()
{
// Stop the timer thread first, so no timeouts can fire during the rest of the
// shutdown process
hashedWheelTimer.stop();
ShutdownUtil.shutdownChannelFactory(channelFactory,
bossExecutor,
workerExecutor,
allChannels);
}
private ThreadFactory renamingDaemonThreadFactory(String nameFormat)
{
return new ThreadFactoryBuilder().setNameFormat(nameFormat).setDaemon(true).build();
}
private ClientBootstrap createClientBootstrap(InetSocketAddress socksProxyAddress)
{
if (socksProxyAddress != null) {
return new Socks4ClientBootstrap(channelFactory, socksProxyAddress);
}
else {
return new ClientBootstrap(channelFactory);
}
}
private class TNiftyFuture<T extends NiftyClientChannel> extends AbstractFuture<T>
{
private TNiftyFuture(final NiftyClientConnector<T> clientChannelConnector,
final Duration receiveTimeout,
final Duration sendTimeout,
final ChannelFuture channelFuture)
{
channelFuture.addListener(new ChannelFutureListener()
{
@Override
public void operationComplete(ChannelFuture future)
throws Exception
{
if (future.isSuccess()) {
Channel nettyChannel = future.getChannel();
T channel = clientChannelConnector.newThriftClientChannel(nettyChannel,
hashedWheelTimer);
channel.setReceiveTimeout(receiveTimeout);
channel.setSendTimeout(sendTimeout);
set(channel);
}
else if (future.isCancelled()) {
cancel(true);
}
else {
setException(future.getCause());
}
}
});
}
}
}
| nifty-client/src/main/java/com/facebook/nifty/client/NiftyClient.java | /*
* Copyright (C) 2012-2013 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.facebook.nifty.client;
import com.google.common.base.Strings;
import org.jboss.netty.channel.socket.nio.NioClientBossPool;
import org.jboss.netty.util.ThreadNameDeterminer;
import com.facebook.nifty.client.socks.Socks4ClientBootstrap;
import com.facebook.nifty.core.ShutdownUtil;
import com.google.common.util.concurrent.AbstractFuture;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.ThreadFactoryBuilder;
import io.airlift.units.Duration;
import org.apache.thrift.transport.TTransportException;
import org.jboss.netty.bootstrap.ClientBootstrap;
import org.jboss.netty.channel.Channel;
import org.jboss.netty.channel.ChannelFuture;
import org.jboss.netty.channel.ChannelFutureListener;
import org.jboss.netty.channel.group.ChannelGroup;
import org.jboss.netty.channel.group.DefaultChannelGroup;
import org.jboss.netty.channel.socket.nio.NioClientSocketChannelFactory;
import org.jboss.netty.channel.socket.nio.NioWorkerPool;
import org.jboss.netty.util.HashedWheelTimer;
import javax.annotation.Nullable;
import java.io.Closeable;
import java.net.InetSocketAddress;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;
import static java.util.concurrent.Executors.newCachedThreadPool;
public class NiftyClient implements Closeable
{
public static final Duration DEFAULT_CONNECT_TIMEOUT = new Duration(2, TimeUnit.SECONDS);
public static final Duration DEFAULT_READ_TIMEOUT = new Duration(2, TimeUnit.SECONDS);
private static final Duration DEFAULT_WRITE_TIMEOUT = new Duration(2, TimeUnit.SECONDS);
private static final int DEFAULT_MAX_FRAME_SIZE = 16777216;
private final NettyClientConfigBuilder configBuilder;
private final ExecutorService bossExecutor;
private final ExecutorService workerExecutor;
private final NioClientSocketChannelFactory channelFactory;
private final InetSocketAddress defaultSocksProxyAddress;
private final ChannelGroup allChannels = new DefaultChannelGroup();
private final HashedWheelTimer hashedWheelTimer;
/**
* Creates a new NiftyClient with defaults: cachedThreadPool for bossExecutor and workerExecutor
*/
public NiftyClient()
{
this(new NettyClientConfigBuilder());
}
public NiftyClient(NettyClientConfigBuilder configBuilder)
{
this(configBuilder, null);
}
public NiftyClient(
NettyClientConfigBuilder configBuilder,
@Nullable InetSocketAddress defaultSocksProxyAddress)
{
this.configBuilder = configBuilder;
String name = configBuilder.getNiftyName();
String prefix = "nifty-client" + (Strings.isNullOrEmpty(name) ? "" : "-" + name);
this.hashedWheelTimer = new HashedWheelTimer(renamingDaemonThreadFactory(prefix + "-timer-%s"));
this.bossExecutor = newCachedThreadPool(renamingDaemonThreadFactory(prefix + "-boss-%s"));
this.workerExecutor = newCachedThreadPool(renamingDaemonThreadFactory(prefix + "-worker-%s"));
this.defaultSocksProxyAddress = defaultSocksProxyAddress;
int bossThreadCount = configBuilder.getNiftyBossThreadCount();
int workerThreadCount = configBuilder.getNiftyWorkerThreadCount();
NioWorkerPool workerPool = new NioWorkerPool(workerExecutor, workerThreadCount, ThreadNameDeterminer.CURRENT);
NioClientBossPool bossPool = new NioClientBossPool(bossExecutor, bossThreadCount, hashedWheelTimer, ThreadNameDeterminer.CURRENT);
this.channelFactory = new NioClientSocketChannelFactory(bossPool, workerPool);
}
public <T extends NiftyClientChannel> ListenableFuture<T> connectAsync(
NiftyClientConnector<T> clientChannelConnector)
{
return connectAsync(clientChannelConnector,
DEFAULT_CONNECT_TIMEOUT,
DEFAULT_READ_TIMEOUT,
DEFAULT_WRITE_TIMEOUT,
DEFAULT_MAX_FRAME_SIZE,
defaultSocksProxyAddress);
}
public <T extends NiftyClientChannel> ListenableFuture<T> connectAsync(
NiftyClientConnector<T> clientChannelConnector,
Duration connectTimeout,
Duration receiveTimeout,
Duration sendTimeout,
int maxFrameSize)
{
return connectAsync(clientChannelConnector,
connectTimeout,
receiveTimeout,
sendTimeout,
maxFrameSize,
defaultSocksProxyAddress);
}
public <T extends NiftyClientChannel> ListenableFuture<T> connectAsync(
NiftyClientConnector<T> clientChannelConnector,
Duration connectTimeout,
Duration receiveTimeout,
Duration sendTimeout,
int maxFrameSize,
@Nullable InetSocketAddress socksProxyAddress)
{
ClientBootstrap bootstrap = createClientBootstrap(socksProxyAddress);
bootstrap.setOptions(configBuilder.getOptions());
bootstrap.setOption("connectTimeoutMillis", (long)connectTimeout.toMillis());
bootstrap.setPipelineFactory(clientChannelConnector.newChannelPipelineFactory(maxFrameSize));
ChannelFuture nettyChannelFuture = clientChannelConnector.connect(bootstrap);
nettyChannelFuture.addListener(new ChannelFutureListener() {
@Override
public void operationComplete(ChannelFuture future) throws Exception {
Channel channel = future.getChannel();
if (channel != null && channel.isOpen()) {
allChannels.add(channel);
channel.getCloseFuture().addListener(new ChannelFutureListener() {
@Override
public void operationComplete(ChannelFuture future) throws Exception {
Channel channel = future.getChannel();
allChannels.remove(channel);
}
});
}
}
});
return new TNiftyFuture<>(clientChannelConnector,
receiveTimeout,
sendTimeout,
nettyChannelFuture);
}
// trying to mirror the synchronous nature of TSocket as much as possible here.
public TNiftyClientTransport connectSync(InetSocketAddress addr)
throws TTransportException, InterruptedException
{
return connectSync(addr, DEFAULT_CONNECT_TIMEOUT, DEFAULT_READ_TIMEOUT, DEFAULT_WRITE_TIMEOUT, DEFAULT_MAX_FRAME_SIZE);
}
public TNiftyClientTransport connectSync(
InetSocketAddress addr,
Duration connectTimeout,
Duration receiveTimeout,
Duration sendTimeout,
int maxFrameSize)
throws TTransportException, InterruptedException
{
return connectSync(addr, connectTimeout, receiveTimeout, sendTimeout, maxFrameSize, defaultSocksProxyAddress);
}
public TNiftyClientTransport connectSync(
InetSocketAddress addr,
Duration connectTimeout,
Duration receiveTimeout,
Duration sendTimeout,
int maxFrameSize,
@Nullable InetSocketAddress socksProxyAddress)
throws TTransportException, InterruptedException
{
// TODO: implement send timeout for sync client
ClientBootstrap bootstrap = createClientBootstrap(socksProxyAddress);
bootstrap.setOptions(configBuilder.getOptions());
bootstrap.setOption("connectTimeoutMillis", (long) connectTimeout.toMillis());
bootstrap.setPipelineFactory(new NiftyClientChannelPipelineFactory(maxFrameSize));
ChannelFuture f = bootstrap.connect(addr);
f.await();
Channel channel = f.getChannel();
if (f.getCause() != null) {
String message = String.format("unable to connect to %s:%d %s",
addr.getHostName(),
addr.getPort(),
socksProxyAddress == null ? "" : "via socks proxy at " + socksProxyAddress);
throw new TTransportException(message, f.getCause());
}
if (f.isSuccess() && (channel != null)) {
if (channel.isOpen()) {
allChannels.add(channel);
channel.getCloseFuture().addListener(new ChannelFutureListener() {
@Override
public void operationComplete(ChannelFuture future) throws Exception {
Channel channel = future.getChannel();
allChannels.remove(channel);
}
});
}
TNiftyClientTransport transport = new TNiftyClientTransport(channel, receiveTimeout);
channel.getPipeline().addLast("thrift", transport);
return transport;
}
throw new TTransportException(String.format(
"unknown error connecting to %s:%d %s",
addr.getHostName(),
addr.getPort(),
socksProxyAddress == null ? "" : "via socks proxy at " + socksProxyAddress
));
}
@Override
public void close()
{
// Stop the timer thread first, so no timeouts can fire during the rest of the
// shutdown process
hashedWheelTimer.stop();
ShutdownUtil.shutdownChannelFactory(channelFactory,
bossExecutor,
workerExecutor,
allChannels);
}
private ThreadFactory renamingDaemonThreadFactory(String nameFormat)
{
return new ThreadFactoryBuilder().setNameFormat(nameFormat).setDaemon(true).build();
}
private ClientBootstrap createClientBootstrap(InetSocketAddress socksProxyAddress)
{
if (socksProxyAddress != null) {
return new Socks4ClientBootstrap(channelFactory, socksProxyAddress);
}
else {
return new ClientBootstrap(channelFactory);
}
}
private class TNiftyFuture<T extends NiftyClientChannel> extends AbstractFuture<T>
{
private TNiftyFuture(final NiftyClientConnector<T> clientChannelConnector,
final Duration receiveTimeout,
final Duration sendTimeout,
final ChannelFuture channelFuture)
{
channelFuture.addListener(new ChannelFutureListener()
{
@Override
public void operationComplete(ChannelFuture future)
throws Exception
{
if (future.isSuccess()) {
Channel nettyChannel = future.getChannel();
T channel = clientChannelConnector.newThriftClientChannel(nettyChannel,
hashedWheelTimer);
channel.setReceiveTimeout(receiveTimeout);
channel.setSendTimeout(sendTimeout);
set(channel);
}
else if (future.isCancelled()) {
cancel(true);
}
else {
setException(future.getCause());
}
}
});
}
}
}
| Remove unnecessary close future handlers
When you add a channel to DefaultChannelGroup, netty already sets up a close future to remove the channel from the group when it is closed
| nifty-client/src/main/java/com/facebook/nifty/client/NiftyClient.java | Remove unnecessary close future handlers | <ide><path>ifty-client/src/main/java/com/facebook/nifty/client/NiftyClient.java
<ide> Channel channel = future.getChannel();
<ide> if (channel != null && channel.isOpen()) {
<ide> allChannels.add(channel);
<del> channel.getCloseFuture().addListener(new ChannelFutureListener() {
<del> @Override
<del> public void operationComplete(ChannelFuture future) throws Exception {
<del> Channel channel = future.getChannel();
<del> allChannels.remove(channel);
<del> }
<del> });
<ide> }
<ide> }
<ide> });
<ide> if (f.isSuccess() && (channel != null)) {
<ide> if (channel.isOpen()) {
<ide> allChannels.add(channel);
<del> channel.getCloseFuture().addListener(new ChannelFutureListener() {
<del> @Override
<del> public void operationComplete(ChannelFuture future) throws Exception {
<del> Channel channel = future.getChannel();
<del> allChannels.remove(channel);
<del> }
<del> });
<ide> }
<ide>
<ide> TNiftyClientTransport transport = new TNiftyClientTransport(channel, receiveTimeout); |
|
Java | mit | 3d7e2fc6c9486294a967a58c273552acf82fe7ad | 0 | dongguangming/python-for-android,chozabu/p4a-ctypes,tsdl2013/python-for-android,eHealthAfrica/python-for-android,germn/python-for-android,ckudzu/python-for-android,dongguangming/python-for-android,Cheaterman/python-for-android,renpytom/python-for-android,manashmndl/python-for-android,gonboy/python-for-android,ehealthafrica-ci/python-for-android,gonboy/python-for-android,manashmndl/python-for-android,olymk2/python-for-android,chozabu/p4a-ctypes,tsdl2013/python-for-android,ravsa/python-for-android,kronenpj/python-for-android,Cheaterman/python-for-android,dvenkatsagar/python-for-android,cbenhagen/python-for-android,kived/python-for-android,niavlys/python-for-android,ibobalo/python-for-android,kivatu/python-for-android,kronenpj/python-for-android,kivatu/python-for-android,dvenkatsagar/python-for-android,olymk2/python-for-android,ehealthafrica-ci/python-for-android,ibobalo/python-for-android,kivatu/python-for-android,dongguangming/python-for-android,rnixx/python-for-android,kived/python-for-android,kived/python-for-android,Cheaterman/python-for-android,dvenkatsagar/python-for-android,kronenpj/python-for-android,cbenhagen/python-for-android,niavlys/python-for-android,PKRoma/python-for-android,kerr-huang/python-for-android,gonboy/python-for-android,bob-the-hamster/python-for-android,dongguangming/python-for-android,germn/python-for-android,alanjds/python-for-android,dvenkatsagar/python-for-android,ehealthafrica-ci/python-for-android,ASMfreaK/python-for-android,gonboy/python-for-android,ibobalo/python-for-android,tsdl2013/python-for-android,kivatu/python-for-android,lc-soft/python-for-android,manashmndl/python-for-android,renpytom/python-for-android,Stocarson/python-for-android,kived/python-for-android,rnixx/python-for-android,dongguangming/python-for-android,olymk2/python-for-android,rnixx/python-for-android,EMATech/python-for-android,dl1ksv/python-for-android,ckudzu/python-for-android,cbenhagen/python-for-android,dl1ksv/python-for-android,joliet0l/python-for-android,kivy/python-for-android,ASMfreaK/python-for-android,dvenkatsagar/python-for-android,ehealthafrica-ci/python-for-android,kronenpj/python-for-android,joliet0l/python-for-android,niavlys/python-for-android,lc-soft/python-for-android,wexi/python-for-android,ehealthafrica-ci/python-for-android,eHealthAfrica/python-for-android,Cheaterman/python-for-android,olymk2/python-for-android,dongguangming/python-for-android,gonboy/python-for-android,kerr-huang/python-for-android,EMATech/python-for-android,kerr-huang/python-for-android,lc-soft/python-for-android,eHealthAfrica/python-for-android,tsdl2013/python-for-android,kerr-huang/python-for-android,ASMfreaK/python-for-android,chozabu/p4a-ctypes,ckudzu/python-for-android,alanjds/python-for-android,kivatu/python-for-android,inclement/python-for-android,wexi/python-for-android,eHealthAfrica/python-for-android,chozabu/p4a-ctypes,ASMfreaK/python-for-android,dl1ksv/python-for-android,joliet0l/python-for-android,dl1ksv/python-for-android,kivy/python-for-android,olymk2/python-for-android,PKRoma/python-for-android,olymk2/python-for-android,pybee/Python-Android-support,codingang/python-for-android,kivy/python-for-android,EMATech/python-for-android,wexi/python-for-android,Cheaterman/python-for-android,ravsa/python-for-android,ravsa/python-for-android,niavlys/python-for-android,kivatu/python-for-android,dl1ksv/python-for-android,pybee/Python-Android-support,eHealthAfrica/python-for-android,inclement/python-for-android,codingang/python-for-android,eHealthAfrica/python-for-android,tsdl2013/python-for-android,eHealthAfrica/python-for-android,ravsa/python-for-android,Stocarson/python-for-android,cbenhagen/python-for-android,inclement/python-for-android,gonboy/python-for-android,kivy/python-for-android,dl1ksv/python-for-android,ehealthafrica-ci/python-for-android,joliet0l/python-for-android,ckudzu/python-for-android,joliet0l/python-for-android,niavlys/python-for-android,germn/python-for-android,PKRoma/python-for-android,ibobalo/python-for-android,ASMfreaK/python-for-android,Stocarson/python-for-android,dvenkatsagar/python-for-android,dvenkatsagar/python-for-android,codingang/python-for-android,ibobalo/python-for-android,ckudzu/python-for-android,rnixx/python-for-android,bob-the-hamster/python-for-android,codingang/python-for-android,EMATech/python-for-android,niavlys/python-for-android,Stocarson/python-for-android,dl1ksv/python-for-android,EMATech/python-for-android,niavlys/python-for-android,alanjds/python-for-android,tsdl2013/python-for-android,manashmndl/python-for-android,renpytom/python-for-android,chozabu/p4a-ctypes,EMATech/python-for-android,alanjds/python-for-android,dl1ksv/python-for-android,Cheaterman/python-for-android,joliet0l/python-for-android,ravsa/python-for-android,inclement/python-for-android,ravsa/python-for-android,chozabu/p4a-ctypes,tsdl2013/python-for-android,chozabu/p4a-ctypes,bob-the-hamster/python-for-android,ravsa/python-for-android,ehealthafrica-ci/python-for-android,ehealthafrica-ci/python-for-android,alanjds/python-for-android,alanjds/python-for-android,ASMfreaK/python-for-android,bob-the-hamster/python-for-android,ibobalo/python-for-android,ASMfreaK/python-for-android,germn/python-for-android,Cheaterman/python-for-android,Cheaterman/python-for-android,PKRoma/python-for-android,kerr-huang/python-for-android,wexi/python-for-android,Stocarson/python-for-android,dongguangming/python-for-android,kivy/python-for-android,renpytom/python-for-android,dvenkatsagar/python-for-android,manashmndl/python-for-android,kived/python-for-android,manashmndl/python-for-android,inclement/python-for-android,ravsa/python-for-android,dongguangming/python-for-android,manashmndl/python-for-android,kived/python-for-android,renpytom/python-for-android,Stocarson/python-for-android,ckudzu/python-for-android,manashmndl/python-for-android,olymk2/python-for-android,cbenhagen/python-for-android,germn/python-for-android,joliet0l/python-for-android,lc-soft/python-for-android,kerr-huang/python-for-android,codingang/python-for-android,kerr-huang/python-for-android,bob-the-hamster/python-for-android,gonboy/python-for-android,cbenhagen/python-for-android,lc-soft/python-for-android,wexi/python-for-android,inclement/python-for-android,renpytom/python-for-android,rnixx/python-for-android,germn/python-for-android,bob-the-hamster/python-for-android,joliet0l/python-for-android,kronenpj/python-for-android,Stocarson/python-for-android,ASMfreaK/python-for-android,gonboy/python-for-android,EMATech/python-for-android,rnixx/python-for-android,wexi/python-for-android,ckudzu/python-for-android,niavlys/python-for-android,olymk2/python-for-android,codingang/python-for-android,Stocarson/python-for-android,alanjds/python-for-android,EMATech/python-for-android,codingang/python-for-android,kivatu/python-for-android,ckudzu/python-for-android,codingang/python-for-android,lc-soft/python-for-android,tsdl2013/python-for-android,PKRoma/python-for-android | package org.renpy.android;
import android.app.Service;
import android.os.IBinder;
import android.os.Bundle;
import android.content.Intent;
import android.content.Context;
import android.util.Log;
import android.app.Notification;
import android.app.PendingIntent;
import android.os.Process;
public class PythonService extends Service implements Runnable {
// Thread for Python code
private Thread pythonThread = null;
// Python environment variables
private String androidPrivate;
private String androidArgument;
private String pythonHome;
private String pythonPath;
// Argument to pass to Python code,
private String pythonServiceArgument;
@Override
public IBinder onBind(Intent arg0) {
return null;
}
@Override
public void onCreate() {
super.onCreate();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (pythonThread != null) {
Log.v("python service", "service exists, do not start again");
return START_NOT_STICKY;
}
Bundle extras = intent.getExtras();
androidPrivate = extras.getString("androidPrivate");
androidArgument = extras.getString("androidArgument") + "/service";
pythonHome = extras.getString("pythonHome");
pythonPath = extras.getString("pythonPath");
pythonServiceArgument = extras.getString("pythonServiceArgument");
String serviceTitle = extras.getString("serviceTitle");
String serviceDescription = extras.getString("serviceDescription");
pythonThread = new Thread(this);
pythonThread.start();
Context context = getApplicationContext();
Notification notification = new Notification(context.getApplicationInfo().icon,
serviceTitle,
System.currentTimeMillis());
Intent contextIntent = new Intent(context, PythonActivity.class);
PendingIntent pIntent = PendingIntent.getActivity(context, 0, contextIntent,
PendingIntent.FLAG_UPDATE_CURRENT);
notification.setLatestEventInfo(context, serviceTitle, serviceDescription, pIntent);
startForeground(1, notification);
return START_NOT_STICKY;
}
@Override
public void onDestroy() {
super.onDestroy();
pythonThread = null;
Process.killProcess(Process.myPid());
}
@Override
public void run(){
System.loadLibrary("sdl");
System.loadLibrary("sdl_image");
System.loadLibrary("sdl_ttf");
System.loadLibrary("sdl_mixer");
System.loadLibrary("python2.7");
System.loadLibrary("application");
System.loadLibrary("sdl_main");
System.load(getFilesDir() + "/lib/python2.7/lib-dynload/_io.so");
System.load(getFilesDir() + "/lib/python2.7/lib-dynload/unicodedata.so");
try {
System.loadLibrary("sqlite3");
System.load(getFilesDir() + "/lib/python2.7/lib-dynload/_sqlite3.so");
} catch(UnsatisfiedLinkError e) {
}
try {
System.load(getFilesDir() + "/lib/python2.7/lib-dynload/_imaging.so");
System.load(getFilesDir() + "/lib/python2.7/lib-dynload/_imagingft.so");
System.load(getFilesDir() + "/lib/python2.7/lib-dynload/_imagingmath.so");
} catch(UnsatisfiedLinkError e) {
}
nativeStart(androidPrivate, androidArgument, pythonHome, pythonPath,
pythonServiceArgument);
}
// Native part
public static native void nativeStart(String androidPrivate, String androidArgument,
String pythonHome, String pythonPath,
String pythonServiceArgument);
}
| src/src/org/renpy/android/PythonService.java | package org.renpy.android;
import android.app.Service;
import android.os.IBinder;
import android.os.Bundle;
import android.content.Intent;
import android.content.Context;
import android.util.Log;
import android.app.Notification;
import android.app.PendingIntent;
import android.os.Process;
import android.R;
public class PythonService extends Service implements Runnable {
// Thread for Python code
private Thread pythonThread = null;
// Python environment variables
private String androidPrivate;
private String androidArgument;
private String pythonHome;
private String pythonPath;
// Argument to pass to Python code,
private String pythonServiceArgument;
@Override
public IBinder onBind(Intent arg0) {
return null;
}
@Override
public void onCreate() {
super.onCreate();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (pythonThread != null) {
Log.v("python service", "service exists, do not start again");
return START_NOT_STICKY;
}
Bundle extras = intent.getExtras();
androidPrivate = extras.getString("androidPrivate");
androidArgument = extras.getString("androidArgument") + "/service";
pythonHome = extras.getString("pythonHome");
pythonPath = extras.getString("pythonPath");
pythonServiceArgument = extras.getString("pythonServiceArgument");
String serviceTitle = extras.getString("serviceTitle");
String serviceDescription = extras.getString("serviceDescription");
pythonThread = new Thread(this);
pythonThread.start();
Notification notification = new Notification(R.drawable.sym_def_app_icon,
serviceTitle,
System.currentTimeMillis());
Context context = getApplicationContext();
Intent contextIntent = new Intent(context, PythonActivity.class);
PendingIntent pIntent = PendingIntent.getActivity(context, 0, contextIntent,
PendingIntent.FLAG_UPDATE_CURRENT);
notification.setLatestEventInfo(context, serviceTitle, serviceDescription, pIntent);
startForeground(1, notification);
return START_NOT_STICKY;
}
@Override
public void onDestroy() {
super.onDestroy();
pythonThread = null;
Process.killProcess(Process.myPid());
}
@Override
public void run(){
System.loadLibrary("sdl");
System.loadLibrary("sdl_image");
System.loadLibrary("sdl_ttf");
System.loadLibrary("sdl_mixer");
System.loadLibrary("python2.7");
System.loadLibrary("application");
System.loadLibrary("sdl_main");
System.load(getFilesDir() + "/lib/python2.7/lib-dynload/_io.so");
System.load(getFilesDir() + "/lib/python2.7/lib-dynload/unicodedata.so");
try {
System.loadLibrary("sqlite3");
System.load(getFilesDir() + "/lib/python2.7/lib-dynload/_sqlite3.so");
} catch(UnsatisfiedLinkError e) {
}
try {
System.load(getFilesDir() + "/lib/python2.7/lib-dynload/_imaging.so");
System.load(getFilesDir() + "/lib/python2.7/lib-dynload/_imagingft.so");
System.load(getFilesDir() + "/lib/python2.7/lib-dynload/_imagingmath.so");
} catch(UnsatisfiedLinkError e) {
}
nativeStart(androidPrivate, androidArgument, pythonHome, pythonPath,
pythonServiceArgument);
}
// Native part
public static native void nativeStart(String androidPrivate, String androidArgument,
String pythonHome, String pythonPath,
String pythonServiceArgument);
}
| use application icon for notification
| src/src/org/renpy/android/PythonService.java | use application icon for notification | <ide><path>rc/src/org/renpy/android/PythonService.java
<ide> import android.app.Notification;
<ide> import android.app.PendingIntent;
<ide> import android.os.Process;
<del>import android.R;
<ide>
<ide> public class PythonService extends Service implements Runnable {
<ide>
<ide> pythonThread = new Thread(this);
<ide> pythonThread.start();
<ide>
<del> Notification notification = new Notification(R.drawable.sym_def_app_icon,
<add> Context context = getApplicationContext();
<add> Notification notification = new Notification(context.getApplicationInfo().icon,
<ide> serviceTitle,
<ide> System.currentTimeMillis());
<del> Context context = getApplicationContext();
<ide> Intent contextIntent = new Intent(context, PythonActivity.class);
<ide> PendingIntent pIntent = PendingIntent.getActivity(context, 0, contextIntent,
<ide> PendingIntent.FLAG_UPDATE_CURRENT); |
|
Java | apache-2.0 | 7a2eb4636c5887008eafd4df686cc70318aa6c2c | 0 | FlatBallFlyer/IBM-Data-Merge-Utility,FlatBallFlyer/IBM-Data-Merge-Utility,FlatBallFlyer/IBM-Data-Merge-Utility | /*
* Copyright 2015-2017 IBM
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.ibm.util.merge;
import java.io.File;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.concurrent.ConcurrentHashMap;
import java.util.logging.Level;
import java.util.logging.Logger;
import com.ibm.util.merge.data.parser.DataProxyJson;
import com.ibm.util.merge.exception.Merge403;
import com.ibm.util.merge.exception.Merge404;
import com.ibm.util.merge.exception.MergeException;
import com.ibm.util.merge.template.Stats;
import com.ibm.util.merge.template.Template;
import com.ibm.util.merge.template.TemplateId;
import com.ibm.util.merge.template.TemplateList;
import com.ibm.util.merge.template.directive.Enrich;
import com.ibm.util.merge.template.directive.Insert;
import com.ibm.util.merge.template.directive.ParseData;
import com.ibm.util.merge.template.directive.Replace;
import com.ibm.util.merge.template.directive.SaveFile;
/**
* A Cache of Templates used by the Merge Process.
* In production use cases the Cache should be initialized once, and then used for multiple merges.
*
* @author Mike Storey
* @since: v4.0
* @see #Cache()
* @see #Cache(File)
* @see com.ibm.util.merge.Config
* @see com.ibm.util.merge.template.Template
*/
public class Cache implements Iterable<String> {
private static final Logger LOGGER = Logger.getLogger(Cache.class.getName());
private final ConcurrentHashMap<String, Template> cache;
private final DataProxyJson gsonProxy = new DataProxyJson(Config.isPrettyJson());
// Cache Statistics
private double cacheHits = 0;
Date initialized = new Date();
/**
* Instantiates a new template cache with only default System templates
* @throws MergeException on processing errors
*/
public Cache() throws MergeException {
this.cache = new ConcurrentHashMap<String, Template>();
this.initialized = new Date();
this.buildDefaultSystemTemplates();
}
/**
* Instantiates a new template cache and loads from a specified file folder
* @param load A folder with one or more json tempalte group files.
* @throws MergeException on processing errors
*/
public Cache(File load) throws MergeException {
this.cache = new ConcurrentHashMap<String, Template>();
this.initialized = new Date();
this.buildDefaultSystemTemplates();
loadGroups(load);
}
/**
* load template groups from a folder of Template Group json files
* @param templateFolder a Folder with one or more .json files that contain a valid Template Group
*/
public void loadGroups(File templateFolder) {
if (!templateFolder.exists()) {
LOGGER.log(Level.WARNING, "Template Load Folder not found: " + templateFolder.getPath());
return;
}
File[] groups = templateFolder.listFiles();
if (null == groups) {
LOGGER.log(Level.WARNING, "Template Load Folder is empty: " + templateFolder.getPath());
return;
}
for (File file : groups) {
try {
this.postGroup(new String(Files.readAllBytes(file.toPath()), "ISO-8859-1"));
} catch (Throwable e) {
LOGGER.log(Level.WARNING, "Template Group failed to load: " + file.getAbsolutePath());
}
}
}
/**
* Build the system default templates (exception handling)
*/
public void buildDefaultSystemTemplates() {
// Build Default Templates
try {
this.deleteGroup("system");
} catch (Throwable e) {
// ignore not found
}
// Add System Templates
try {
Template error403 = new Template("system","error403","","Error - Forbidden");
Template error404 = new Template("system","error404","","Error - Not Found");
Template error500 = new Template("system","error500","","Error - Merge Error");
Template sample = new Template("system","sample","");
sample.addDirective(new Enrich());
sample.addDirective(new Insert());
sample.addDirective(new ParseData());
sample.addDirective(new Replace());
sample.addDirective(new SaveFile());
postTemplate(error403);
postTemplate(error404);
postTemplate(error500);
postTemplate(sample);
} catch (Throwable e) {
LOGGER.log(Level.SEVERE, "Load System Templates Failed!" + e.getMessage());
}
}
/**
* Gets a mergable template - getting the default template if the primary template does not exist.
*
* @param context The Merge Context
* @param templateShortname The Template Name
* @param templateDefault The Default template to use if Name not found
* @param replace The initial replace stack to be added to the template
* @return the Mergable template
* @throws MergeException on processing errors
*/
public Template getMergable(Merger context, String templateShortname, String templateDefault, HashMap<String,String> replace) throws MergeException {
if (cache.containsKey(templateShortname)) {
Template template = cache.get(templateShortname);
this.cacheHits++;
return template.getMergable(context, replace);
} else if (cache.containsKey(templateDefault)) {
Template template = cache.get(templateDefault);
this.cacheHits++;
return template.getMergable(context, replace);
}
throw new Merge404("Template not found - " + templateShortname + "-" + templateDefault);
}
/**
* Gets a mergable template
*
* @param context The Merge Context
* @param templateShortname Template Name
* @param replace Replace Stack to initialize
* @return the Mergable template
* @throws MergeException on processing errors
*/
public Template getMergable(Merger context, String templateShortname, HashMap<String,String> replace) throws MergeException {
if (!cache.containsKey(templateShortname)) {
throw new Merge404("Template not found:" + templateShortname);
}
Template template = cache.get(templateShortname);
this.cacheHits++;
return template.getMergable(context, replace);
}
/**
* Get a mergable template with an empty replace stack
*
* @param context The Merge Context
* @param templateShortname The template name
* @return The Mergable template
* @throws MergeException on processing errors
*/
public Template getMergable(Merger context, String templateShortname) throws MergeException {
return getMergable(context, templateShortname, new HashMap<String,String>());
}
/**
* Post template.
*
* @param templateJson the template json
* @return the string
* @throws MergeException on processing errors
*/
public String postTemplate(String templateJson) throws MergeException {
Template template;
template = gsonProxy.fromString(templateJson, Template.class);
if (null == template) {
throw new Merge403("Invalid Json");
}
return postTemplate(template);
}
/**
* Post template.
*
* @param template the template
* @return the string
* @throws MergeException on processing errors
*/
public String postTemplate(Template template) throws MergeException {
String name = template.getId().shorthand();
if (cache.containsKey(name)) {
throw new Merge403("Duplicate Found:" + name);
}
template.cachePrepare();
cache.put(name, template);
return "ok";
}
/**
* Gets the template.
*
* @param shortHand the Template Name
* @return the template
*/
public String getTemplate(String shortHand) {
TemplateId id = new TemplateId(shortHand);
TemplateList templates = getTemplates(id);
return gsonProxy.toString(templates);
}
/**
* Gets the template.
*
* @param id the template id
* @return the template List
*/
public TemplateList getTemplates(TemplateId id) {
TemplateList templates = new TemplateList();
for (Template template : cache.values()) {
if ( (id.group.isEmpty() || id.group.equals(template.getId().group)) &&
(id.name.isEmpty() || id.name.equals(template.getId().name) ) &&
(id.variant.isEmpty() || id.variant.equals(template.getId().variant))) {
templates.add(template);
}
}
return templates;
}
/**
* Put template.
*
* @param templateJson the template json
* @return the string
* @throws MergeException on processing errors
*/
public String putTemplate(String templateJson) throws MergeException {
Template template = gsonProxy.fromString(templateJson, Template.class);
if (null == template) {
throw new Merge403("Invalid Json");
}
return putTemplate(template);
}
/**
* Put template.
*
* @param template the template
* @return the string
* @throws MergeException when template not found in cache
*/
public String putTemplate(Template template) throws MergeException {
String name = template.getId().shorthand();
if (!cache.containsKey(name)) {
throw new Merge404("Not Found:" + template.getId().shorthand());
}
template.cachePrepare();
cache.put(name, template);
return "ok";
}
/**
* Delete template.
*
* @param shorthand the template id
* @return the string
* @throws MergeException on processing errors
*/
public String deleteTemplate(String shorthand) throws MergeException {
TemplateId id = new TemplateId(shorthand);
deleteTemplate(id);
return "ok";
}
/**
* Delete template.
*
* @param id The template id
* @return The success message
* @throws MergeException on processing errors
*/
public String deleteTemplate(TemplateId id) throws MergeException {
if (!cache.containsKey(id.shorthand())) {
throw new Merge403("Not Found:" + id.shorthand());
}
cache.remove(id.shorthand());
return "ok";
}
/**
* Gets the list of template groups.
*
* @return the group
*/
public HashSet<String> getGroupList() {
HashSet<String> groups = new HashSet<String>();
for (Template template : cache.values()) {
groups.add(template.getId().group);
}
return groups;
}
/**
* Post group.
*
* @param groupJson the group json
* @return the string
* @throws MergeException on processing errors
*/
public String postGroup(String groupJson) throws MergeException {
TemplateList templates = gsonProxy.fromString(groupJson, TemplateList.class);
if (null == templates) {
throw new Merge403("Invalid Json");
}
String group = templates.get(0).getId().group;
if (getGroupList().contains(group)) {
throw new Merge403("Duplicate Found:" + group);
}
for (Template template : templates) {
if (template.getId().group.equals(group)) {
this.postTemplate(template);
} else {
throw new Merge403("Invalid Group - multi-group:" + group + ":" + template.getId().group);
}
}
return "ok";
}
/**
* Gets the group.
*
* @param groupName the group name
* @return the group
*/
public String getGroup(String groupName) {
if (groupName.isEmpty()) {
return this.gsonProxy.toString(getGroupList());
}
TemplateList group = new TemplateList();
for (Template template : cache.values()) {
if (template.getId().group.equals(groupName)) {
group.add(template);
}
}
return gsonProxy.toString(group);
}
/**
* Put group.
*
* @param groupJson the group json
* @return the string
* @throws MergeException on processing errors
*/
public String putGroup(String groupJson) throws MergeException {
TemplateList templates = gsonProxy.fromString(groupJson, TemplateList.class);
if (null == templates) {
throw new Merge403("Invalid Json");
}
String groupName = templates.get(0).getId().group;
if (!this.getGroupList().contains(groupName)) {
throw new Merge403("Not Found:" + groupName);
}
deleteTheGroup(groupName);
for (Template template : templates) {
this.postTemplate(template);
}
return "ok";
}
/**
* Delete group.
*
* @param groupName the group name
* @return the string
* @throws MergeException on processing errors
*/
public String deleteGroup(String groupName) throws MergeException {
if (groupName.equals("system")) {
throw new Merge403("Forbidden:" + groupName);
}
if (!this.getGroupList().contains(groupName)) {
throw new Merge403("Not Found:" + groupName);
}
deleteTheGroup(groupName);
return "ok";
}
/**
* Gets the list of template groups and template names.
*
* @return JSON String
*/
public String getGroupAndTemplateList() {
HashMap<String, ArrayList<String>> theTemplates = new HashMap<String, ArrayList<String>>();
for (Template template : cache.values()) {
if (!theTemplates.containsKey(template.getId().group)) {
theTemplates.put(template.getId().group, new ArrayList<String>());
}
theTemplates.get(template.getId().group).add(template.getId().shorthand());
}
return gsonProxy.toString(theTemplates);
}
/**
* Update cached template statistics - NOT SYNCRONIZED Subject to inaccuracy
* @param template The template shortname to update
* @param response The response time of merging the template
*/
public void postStats(String template, Long response) {
if (this.contains(template)) {
this.cache.get(template).postStats(response);
}
}
/**
* @return template statistics
*/
public Stats getStats() {
Stats stats = new Stats();
for (String name : cache.keySet()) {
stats.add(cache.get(name).getStats());
}
return stats;
}
/**
* @return number of templates in cache
*/
public int getSize() {
return this.cache.size();
}
/**
* @param key Template ID
* @return if cache contains a template
*/
public boolean contains(String key) {
return this.cache.containsKey(key);
}
/**
* @return number of cache hits since instantiation
*/
public double getCacheHits() {
return this.cacheHits;
}
/**
* @return the date/time the cache was initialized
*/
public Date getInitialized() {
return initialized;
}
@Override
public Iterator<String> iterator() {
return cache.keySet().iterator();
}
/**
* Delete the group
* @param groupName
*/
private void deleteTheGroup(String groupName) {
HashSet<String> names = new HashSet<String>();
for (String name : cache.keySet()) {
if (cache.get(name).getId().group.equals(groupName)) {
names.add(name);
}
}
for (String name : names) {
cache.remove(name);
}
}
}
| src/main/java/com/ibm/util/merge/Cache.java | /*
* Copyright 2015-2017 IBM
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.ibm.util.merge;
import java.io.File;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.logging.Level;
import java.util.logging.Logger;
import com.ibm.util.merge.data.parser.DataProxyJson;
import com.ibm.util.merge.exception.Merge403;
import com.ibm.util.merge.exception.Merge404;
import com.ibm.util.merge.exception.MergeException;
import com.ibm.util.merge.template.Stats;
import com.ibm.util.merge.template.Template;
import com.ibm.util.merge.template.TemplateId;
import com.ibm.util.merge.template.TemplateList;
import com.ibm.util.merge.template.directive.Enrich;
import com.ibm.util.merge.template.directive.Insert;
import com.ibm.util.merge.template.directive.ParseData;
import com.ibm.util.merge.template.directive.Replace;
import com.ibm.util.merge.template.directive.SaveFile;
/**
* A Cache of Templates used by the Merge Process.
* In production use cases the Cache should be initialized once, and then used for multiple merges.
*
* @author Mike Storey
* @since: v4.0
* @see #Cache()
* @see #Cache(File)
* @see com.ibm.util.merge.Config
* @see com.ibm.util.merge.template.Template
*/
public class Cache implements Iterable<String> {
private static final Logger LOGGER = Logger.getLogger(Cache.class.getName());
private final HashMap<String, Template> cache;
private final DataProxyJson gsonProxy = new DataProxyJson(Config.isPrettyJson());
// Cache Statistics
private double cacheHits = 0;
Date initialized = new Date();
/**
* Instantiates a new template cache with only default System templates
* @throws MergeException on processing errors
*/
public Cache() throws MergeException {
this.cache = new HashMap<String, Template>();
this.initialized = new Date();
this.buildDefaultSystemTemplates();
}
/**
* Instantiates a new template cache and loads from a specified file folder
* @param load A folder with one or more json tempalte group files.
* @throws MergeException on processing errors
*/
public Cache(File load) throws MergeException {
this.cache = new HashMap<String, Template>();
this.initialized = new Date();
this.buildDefaultSystemTemplates();
loadGroups(load);
}
/**
* load template groups from a folder of Template Group json files
* @param templateFolder a Folder with one or more .json files that contain a valid Template Group
*/
public void loadGroups(File templateFolder) {
if (!templateFolder.exists()) {
LOGGER.log(Level.WARNING, "Template Load Folder not found: " + templateFolder.getPath());
return;
}
File[] groups = templateFolder.listFiles();
if (null == groups) {
LOGGER.log(Level.WARNING, "Template Load Folder is empty: " + templateFolder.getPath());
return;
}
for (File file : groups) {
try {
this.postGroup(new String(Files.readAllBytes(file.toPath()), "ISO-8859-1"));
} catch (Throwable e) {
LOGGER.log(Level.WARNING, "Template Group failed to load: " + file.getAbsolutePath());
}
}
}
/**
* Build the system default templates (exception handling)
*/
public void buildDefaultSystemTemplates() {
// Build Default Templates
try {
this.deleteGroup("system");
} catch (Throwable e) {
// ignore not found
}
// Add System Templates
try {
Template error403 = new Template("system","error403","","Error - Forbidden");
Template error404 = new Template("system","error404","","Error - Not Found");
Template error500 = new Template("system","error500","","Error - Merge Error");
Template sample = new Template("system","sample","");
sample.addDirective(new Enrich());
sample.addDirective(new Insert());
sample.addDirective(new ParseData());
sample.addDirective(new Replace());
sample.addDirective(new SaveFile());
postTemplate(error403);
postTemplate(error404);
postTemplate(error500);
postTemplate(sample);
} catch (Throwable e) {
LOGGER.log(Level.SEVERE, "Load System Templates Failed!" + e.getMessage());
}
}
/**
* Gets a mergable template - getting the default template if the primary template does not exist.
*
* @param context The Merge Context
* @param templateShortname The Template Name
* @param templateDefault The Default template to use if Name not found
* @param replace The initial replace stack to be added to the template
* @return the Mergable template
* @throws MergeException on processing errors
*/
public Template getMergable(Merger context, String templateShortname, String templateDefault, HashMap<String,String> replace) throws MergeException {
if (cache.containsKey(templateShortname)) {
Template template = cache.get(templateShortname);
this.cacheHits++;
return template.getMergable(context, replace);
} else if (cache.containsKey(templateDefault)) {
Template template = cache.get(templateDefault);
this.cacheHits++;
return template.getMergable(context, replace);
}
throw new Merge404("Template not found - " + templateShortname + "-" + templateDefault);
}
/**
* Gets a mergable template
*
* @param context The Merge Context
* @param templateShortname Template Name
* @param replace Replace Stack to initialize
* @return the Mergable template
* @throws MergeException on processing errors
*/
public Template getMergable(Merger context, String templateShortname, HashMap<String,String> replace) throws MergeException {
if (!cache.containsKey(templateShortname)) {
throw new Merge404("Template not found:" + templateShortname);
}
Template template = cache.get(templateShortname);
this.cacheHits++;
return template.getMergable(context, replace);
}
/**
* Get a mergable template with an empty replace stack
*
* @param context The Merge Context
* @param templateShortname The template name
* @return The Mergable template
* @throws MergeException on processing errors
*/
public Template getMergable(Merger context, String templateShortname) throws MergeException {
return getMergable(context, templateShortname, new HashMap<String,String>());
}
/**
* Post template.
*
* @param templateJson the template json
* @return the string
* @throws MergeException on processing errors
*/
public String postTemplate(String templateJson) throws MergeException {
Template template;
template = gsonProxy.fromString(templateJson, Template.class);
if (null == template) {
throw new Merge403("Invalid Json");
}
return postTemplate(template);
}
/**
* Post template.
*
* @param template the template
* @return the string
* @throws MergeException on processing errors
*/
public String postTemplate(Template template) throws MergeException {
String name = template.getId().shorthand();
if (cache.containsKey(name)) {
throw new Merge403("Duplicate Found:" + name);
}
template.cachePrepare();
cache.put(name, template);
return "ok";
}
/**
* Gets the template.
*
* @param shortHand the Template Name
* @return the template
*/
public String getTemplate(String shortHand) {
TemplateId id = new TemplateId(shortHand);
TemplateList templates = getTemplates(id);
return gsonProxy.toString(templates);
}
/**
* Gets the template.
*
* @param id the template id
* @return the template List
*/
public TemplateList getTemplates(TemplateId id) {
TemplateList templates = new TemplateList();
for (Template template : cache.values()) {
if ( (id.group.isEmpty() || id.group.equals(template.getId().group)) &&
(id.name.isEmpty() || id.name.equals(template.getId().name) ) &&
(id.variant.isEmpty() || id.variant.equals(template.getId().variant))) {
templates.add(template);
}
}
return templates;
}
/**
* Put template.
*
* @param templateJson the template json
* @return the string
* @throws MergeException on processing errors
*/
public String putTemplate(String templateJson) throws MergeException {
Template template = gsonProxy.fromString(templateJson, Template.class);
if (null == template) {
throw new Merge403("Invalid Json");
}
return putTemplate(template);
}
/**
* Put template.
*
* @param template the template
* @return the string
* @throws MergeException when template not found in cache
*/
public String putTemplate(Template template) throws MergeException {
String name = template.getId().shorthand();
if (!cache.containsKey(name)) {
throw new Merge404("Not Found:" + template.getId().shorthand());
}
template.cachePrepare();
cache.put(name, template);
return "ok";
}
/**
* Delete template.
*
* @param shorthand the template id
* @return the string
* @throws MergeException on processing errors
*/
public String deleteTemplate(String shorthand) throws MergeException {
TemplateId id = new TemplateId(shorthand);
deleteTemplate(id);
return "ok";
}
/**
* Delete template.
*
* @param id The template id
* @return The success message
* @throws MergeException on processing errors
*/
public String deleteTemplate(TemplateId id) throws MergeException {
if (!cache.containsKey(id.shorthand())) {
throw new Merge403("Not Found:" + id.shorthand());
}
cache.remove(id.shorthand());
return "ok";
}
/**
* Gets the list of template groups.
*
* @return the group
*/
public HashSet<String> getGroupList() {
HashSet<String> groups = new HashSet<String>();
for (Template template : cache.values()) {
groups.add(template.getId().group);
}
return groups;
}
/**
* Post group.
*
* @param groupJson the group json
* @return the string
* @throws MergeException on processing errors
*/
public String postGroup(String groupJson) throws MergeException {
TemplateList templates = gsonProxy.fromString(groupJson, TemplateList.class);
if (null == templates) {
throw new Merge403("Invalid Json");
}
String group = templates.get(0).getId().group;
if (getGroupList().contains(group)) {
throw new Merge403("Duplicate Found:" + group);
}
for (Template template : templates) {
if (template.getId().group.equals(group)) {
this.postTemplate(template);
} else {
throw new Merge403("Invalid Group - multi-group:" + group + ":" + template.getId().group);
}
}
return "ok";
}
/**
* Gets the group.
*
* @param groupName the group name
* @return the group
*/
public String getGroup(String groupName) {
if (groupName.isEmpty()) {
return this.gsonProxy.toString(getGroupList());
}
TemplateList group = new TemplateList();
for (Template template : cache.values()) {
if (template.getId().group.equals(groupName)) {
group.add(template);
}
}
return gsonProxy.toString(group);
}
/**
* Put group.
*
* @param groupJson the group json
* @return the string
* @throws MergeException on processing errors
*/
public String putGroup(String groupJson) throws MergeException {
TemplateList templates = gsonProxy.fromString(groupJson, TemplateList.class);
if (null == templates) {
throw new Merge403("Invalid Json");
}
String groupName = templates.get(0).getId().group;
if (!this.getGroupList().contains(groupName)) {
throw new Merge403("Not Found:" + groupName);
}
deleteTheGroup(groupName);
for (Template template : templates) {
this.postTemplate(template);
}
return "ok";
}
/**
* Delete group.
*
* @param groupName the group name
* @return the string
* @throws MergeException on processing errors
*/
public String deleteGroup(String groupName) throws MergeException {
if (groupName.equals("system")) {
throw new Merge403("Forbidden:" + groupName);
}
if (!this.getGroupList().contains(groupName)) {
throw new Merge403("Not Found:" + groupName);
}
deleteTheGroup(groupName);
return "ok";
}
/**
* Gets the list of template groups and template names.
*
* @return JSON String
*/
public String getGroupAndTemplateList() {
HashMap<String, ArrayList<String>> theTemplates = new HashMap<String, ArrayList<String>>();
for (Template template : cache.values()) {
if (!theTemplates.containsKey(template.getId().group)) {
theTemplates.put(template.getId().group, new ArrayList<String>());
}
theTemplates.get(template.getId().group).add(template.getId().shorthand());
}
return gsonProxy.toString(theTemplates);
}
/**
* Update cached template statistics - NOT SYNCRONIZED Subject to inaccuracy
* @param template The template shortname to update
* @param response The response time of merging the template
*/
public void postStats(String template, Long response) {
if (this.contains(template)) {
this.cache.get(template).postStats(response);
}
}
/**
* @return template statistics
*/
public Stats getStats() {
Stats stats = new Stats();
for (String name : cache.keySet()) {
stats.add(cache.get(name).getStats());
}
return stats;
}
/**
* @return number of templates in cache
*/
public int getSize() {
return this.cache.size();
}
/**
* @param key Template ID
* @return if cache contains a template
*/
public boolean contains(String key) {
return this.cache.containsKey(key);
}
/**
* @return number of cache hits since instantiation
*/
public double getCacheHits() {
return this.cacheHits;
}
/**
* @return the date/time the cache was initialized
*/
public Date getInitialized() {
return initialized;
}
@Override
public Iterator<String> iterator() {
return cache.keySet().iterator();
}
/**
* Delete the group
* @param groupName
*/
private void deleteTheGroup(String groupName) {
HashSet<String> names = new HashSet<String>();
for (String name : cache.keySet()) {
if (cache.get(name).getId().group.equals(groupName)) {
names.add(name);
}
}
for (String name : names) {
cache.remove(name);
}
}
}
| Shifted cache to use ConcurrentHashMap
| src/main/java/com/ibm/util/merge/Cache.java | Shifted cache to use ConcurrentHashMap | <ide><path>rc/main/java/com/ibm/util/merge/Cache.java
<ide> import java.util.HashMap;
<ide> import java.util.HashSet;
<ide> import java.util.Iterator;
<add>import java.util.concurrent.ConcurrentHashMap;
<ide> import java.util.logging.Level;
<ide> import java.util.logging.Logger;
<ide>
<ide> */
<ide> public class Cache implements Iterable<String> {
<ide> private static final Logger LOGGER = Logger.getLogger(Cache.class.getName());
<del> private final HashMap<String, Template> cache;
<add> private final ConcurrentHashMap<String, Template> cache;
<ide> private final DataProxyJson gsonProxy = new DataProxyJson(Config.isPrettyJson());
<ide>
<ide> // Cache Statistics
<ide> * @throws MergeException on processing errors
<ide> */
<ide> public Cache() throws MergeException {
<del> this.cache = new HashMap<String, Template>();
<add> this.cache = new ConcurrentHashMap<String, Template>();
<ide> this.initialized = new Date();
<ide> this.buildDefaultSystemTemplates();
<ide> }
<ide> * @throws MergeException on processing errors
<ide> */
<ide> public Cache(File load) throws MergeException {
<del> this.cache = new HashMap<String, Template>();
<add> this.cache = new ConcurrentHashMap<String, Template>();
<ide> this.initialized = new Date();
<ide> this.buildDefaultSystemTemplates();
<ide> |
|
Java | mit | 32d98bea99ccae997798ebc89ad15a1a5858c171 | 0 | bandwidthcom/java-bandwidth-iris | package com.bandwidth.iris.sdk.model;
import com.bandwidth.iris.sdk.IrisClient;
import com.bandwidth.iris.sdk.IrisPath;
import com.bandwidth.iris.sdk.IrisResponse;
import com.bandwidth.iris.sdk.utils.XmlUtils;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import java.util.List;
import java.util.Map;
/**
* Created by sbarstow on 11/17/14.
*/
@XmlRootElement(name = "AvailableNpaNxx")
@XmlAccessorType(XmlAccessType.FIELD)
public class AvailableNpaNxx {
@XmlElement(name = "City")
private String city;
@XmlElement(name = "Npa")
private String npa;
@XmlElement(name = "Nxx")
private String nxx;
@XmlElement(name = "Quantity")
private int quantity;
@XmlElement(name = "State")
private String state;
public static List<AvailableNpaNxx> list(IrisClient client, Map<String, Object> query)
throws Exception {
SearchResultForAvailableNpaNxx searchResult = null;
List<AvailableNpaNxx> availableNpaNxxList = null;
IrisResponse irisResponse = client
.get(client.buildAccountModelUri(new String[] { IrisPath.AVAILABLE_NPANXX_URI_PATH }, query));
searchResult = XmlUtils.fromXml(irisResponse.getResponseBody(),
SearchResultForAvailableNpaNxx.class);
availableNpaNxxList = searchResult.getAvailableNpaNxxList();
return availableNpaNxxList;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getNpa() {
return npa;
}
public void setNpa(String npa) {
this.npa = npa;
}
public String getNxx() {
return nxx;
}
public void setNxx(String nxx) {
this.nxx = nxx;
}
public int getQuantity() {
return quantity;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
public int getState() {
return state;
}
public void setState(int state) {
this.state = state;
}
}
| src/main/java/com/bandwidth/iris/sdk/model/AvailableNpaNxx.java | package com.bandwidth.iris.sdk.model;
import com.bandwidth.iris.sdk.IrisClient;
import com.bandwidth.iris.sdk.IrisPath;
import com.bandwidth.iris.sdk.IrisResponse;
import com.bandwidth.iris.sdk.utils.XmlUtils;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import java.util.List;
import java.util.Map;
/**
* Created by sbarstow on 11/17/14.
*/
@XmlRootElement(name = "AvailableNpaNxx")
@XmlAccessorType(XmlAccessType.FIELD)
public class AvailableNpaNxx {
@XmlElement(name = "City")
private String city;
@XmlElement(name = "Npa")
private String npa;
@XmlElement(name = "Nxx")
private String nxx;
@XmlElement(name = "Quantity")
private int quantity;
@XmlElement(name = "State")
private int state;
public static List<AvailableNpaNxx> list(IrisClient client, Map<String, Object> query)
throws Exception {
SearchResultForAvailableNpaNxx searchResult = null;
List<AvailableNpaNxx> availableNpaNxxList = null;
IrisResponse irisResponse = client
.get(client.buildAccountModelUri(new String[] { IrisPath.AVAILABLE_NPANXX_URI_PATH }, query));
searchResult = XmlUtils.fromXml(irisResponse.getResponseBody(),
SearchResultForAvailableNpaNxx.class);
availableNpaNxxList = searchResult.getAvailableNpaNxxList();
return availableNpaNxxList;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getNpa() {
return npa;
}
public void setNpa(String npa) {
this.npa = npa;
}
public String getNxx() {
return nxx;
}
public void setNxx(String nxx) {
this.nxx = nxx;
}
public int getQuantity() {
return quantity;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
public int getState() {
return state;
}
public void setState(int state) {
this.state = state;
}
}
| Resolves #30
| src/main/java/com/bandwidth/iris/sdk/model/AvailableNpaNxx.java | Resolves #30 | <ide><path>rc/main/java/com/bandwidth/iris/sdk/model/AvailableNpaNxx.java
<ide> @XmlElement(name = "Quantity")
<ide> private int quantity;
<ide> @XmlElement(name = "State")
<del> private int state;
<add> private String state;
<ide>
<ide> public static List<AvailableNpaNxx> list(IrisClient client, Map<String, Object> query)
<ide> throws Exception { |
|
Java | apache-2.0 | 68b30f2dc47277bfbf10f56d2d49997bbfbe722c | 0 | f2prateek/device-frame-generator,f2prateek/device-frame-generator,f2prateek/device-frame-generator | /*
* Copyright 2014 Prateek Srivastava (@f2prateek)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.f2prateek.dfg.ui.fragments;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.net.Uri;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import butterknife.InjectView;
import butterknife.OnClick;
import com.f2prateek.dart.InjectExtra;
import com.f2prateek.dfg.Events;
import com.f2prateek.dfg.R;
import com.f2prateek.dfg.core.AbstractGenerateFrameService;
import com.f2prateek.dfg.core.GenerateFrameService;
import com.f2prateek.dfg.model.Device;
import com.f2prateek.dfg.prefs.DefaultDevice;
import com.f2prateek.dfg.prefs.model.StringPreference;
import com.f2prateek.dfg.util.BitmapUtils;
import com.squareup.otto.Subscribe;
import com.squareup.picasso.Picasso;
import de.keyboardsurfer.android.widget.crouton.Crouton;
import de.keyboardsurfer.android.widget.crouton.Style;
import java.util.List;
import javax.inject.Inject;
public class DeviceFragment extends BaseFragment {
private static final String EXTRA_DEVICE = "device";
private static final int RESULT_SELECT_PICTURE = 542;
@Inject @DefaultDevice StringPreference defaultDevice;
@Inject Picasso picasso;
@InjectView(R.id.tv_device_resolution) TextView deviceResolutionText;
@InjectView(R.id.tv_device_size) TextView deviceSizeText;
@InjectView(R.id.tv_device_name) TextView deviceNameText;
@InjectView(R.id.iv_device_thumbnail) ImageView deviceThumbnailText;
@InjectView(R.id.iv_device_default) ImageView deviceDefaultText;
@InjectExtra(EXTRA_DEVICE) Device device;
public static DeviceFragment newInstance(Device device) {
DeviceFragment f = new DeviceFragment();
Bundle args = new Bundle();
args.putParcelable(EXTRA_DEVICE, device);
f.setArguments(args);
f.setRetainInstance(true);
return f;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_device, container, false);
}
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
picasso.load(BitmapUtils.getResourceIdentifierForDrawable(getActivity(),
device.getThumbnailResourceName())).fit().centerInside().into(deviceThumbnailText);
deviceDefaultText.bringToFront();
deviceDefaultText.setImageResource(
isDefault() ? R.drawable.ic_action_star_selected : R.drawable.ic_action_star);
deviceSizeText.setText(device.physicalSize() + "\" @ " + device.density());
deviceNameText.setText(device.name());
deviceResolutionText.setText(device.realSize().x() + "x" + device.realSize().y());
}
@OnClick(R.id.iv_device_default)
public void updateDefaultDevice() {
if (isDefault()) {
return;
}
defaultDevice.set(device.id());
bus.post(new Events.DefaultDeviceUpdated(device));
}
@Subscribe
public void onDefaultDeviceUpdated(Events.DefaultDeviceUpdated event) {
deviceDefaultText.post(new Runnable() {
@Override public void run() {
deviceDefaultText.setImageResource(
isDefault() ? R.drawable.ic_action_star_selected : R.drawable.ic_action_star);
}
});
}
private boolean isDefault() {
return device.id().compareTo(defaultDevice.get()) == 0;
}
@OnClick(R.id.iv_device_thumbnail)
public void getScreenshotImageFromUser() {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
if (isAvailable(activityContext, intent)) {
startActivityForResult(Intent.createChooser(intent, getString(R.string.select_picture)),
RESULT_SELECT_PICTURE);
} else {
Crouton.makeText(getActivity(), R.string.no_apps_available, Style.ALERT).show();
}
}
/**
* Check if any apps are installed on the app to receive this intent.
*/
public static boolean isAvailable(Context ctx, Intent intent) {
final PackageManager mgr = ctx.getPackageManager();
List<ResolveInfo> list = mgr.queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY);
return list.size() > 0;
}
@OnClick(R.id.tv_device_name)
public void openDevicePage() {
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(device.url()));
startActivity(i);
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == RESULT_SELECT_PICTURE && resultCode == Activity.RESULT_OK) {
if (data == null) {
return;
}
Uri selectedImageUri = data.getData();
Intent intent = new Intent(getActivity(), GenerateFrameService.class);
intent.putExtra(AbstractGenerateFrameService.KEY_EXTRA_DEVICE, device);
intent.putExtra(GenerateFrameService.KEY_EXTRA_SCREENSHOT, selectedImageUri);
getActivity().startService(intent);
} else {
super.onActivityResult(requestCode, resultCode, data);
}
}
} | app/src/main/java/com/f2prateek/dfg/ui/fragments/DeviceFragment.java | /*
* Copyright 2014 Prateek Srivastava (@f2prateek)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.f2prateek.dfg.ui.fragments;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.net.Uri;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import butterknife.InjectView;
import butterknife.OnClick;
import com.f2prateek.dart.InjectExtra;
import com.f2prateek.dfg.Events;
import com.f2prateek.dfg.R;
import com.f2prateek.dfg.core.AbstractGenerateFrameService;
import com.f2prateek.dfg.core.GenerateFrameService;
import com.f2prateek.dfg.model.Device;
import com.f2prateek.dfg.prefs.DefaultDevice;
import com.f2prateek.dfg.prefs.model.StringPreference;
import com.f2prateek.dfg.util.BitmapUtils;
import com.squareup.otto.Subscribe;
import com.squareup.picasso.Picasso;
import de.keyboardsurfer.android.widget.crouton.Crouton;
import de.keyboardsurfer.android.widget.crouton.Style;
import java.util.List;
import javax.inject.Inject;
public class DeviceFragment extends BaseFragment {
private static final String EXTRA_DEVICE = "device";
private static final int RESULT_SELECT_PICTURE = 542;
@Inject @DefaultDevice StringPreference defaultDevice;
@Inject Picasso picasso;
@InjectView(R.id.tv_device_resolution) TextView deviceResolutionText;
@InjectView(R.id.tv_device_size) TextView deviceSizeText;
@InjectView(R.id.tv_device_name) TextView deviceNameText;
@InjectView(R.id.iv_device_thumbnail) ImageView deviceThumbnailText;
@InjectView(R.id.iv_device_default) ImageView deviceDefaultText;
@InjectExtra(EXTRA_DEVICE) Device device;
public static DeviceFragment newInstance(Device device) {
DeviceFragment f = new DeviceFragment();
Bundle args = new Bundle();
args.putParcelable(EXTRA_DEVICE, device);
f.setArguments(args);
f.setRetainInstance(true);
return f;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_device, container, false);
}
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
picasso.load(BitmapUtils.getResourceIdentifierForDrawable(getActivity(),
device.getThumbnailResourceName())).into(deviceThumbnailText);
deviceDefaultText.bringToFront();
deviceDefaultText.setImageResource(
isDefault() ? R.drawable.ic_action_star_selected : R.drawable.ic_action_star);
deviceSizeText.setText(device.physicalSize() + "\" @ " + device.density());
deviceNameText.setText(device.name());
deviceResolutionText.setText(device.realSize().x() + "x" + device.realSize().y());
}
@OnClick(R.id.iv_device_default)
public void updateDefaultDevice() {
if (isDefault()) {
return;
}
defaultDevice.set(device.id());
bus.post(new Events.DefaultDeviceUpdated(device));
}
@Subscribe
public void onDefaultDeviceUpdated(Events.DefaultDeviceUpdated event) {
deviceDefaultText.post(new Runnable() {
@Override public void run() {
deviceDefaultText.setImageResource(
isDefault() ? R.drawable.ic_action_star_selected : R.drawable.ic_action_star);
}
});
}
private boolean isDefault() {
return device.id().compareTo(defaultDevice.get()) == 0;
}
@OnClick(R.id.iv_device_thumbnail)
public void getScreenshotImageFromUser() {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
if (isAvailable(activityContext, intent)) {
startActivityForResult(Intent.createChooser(intent, getString(R.string.select_picture)),
RESULT_SELECT_PICTURE);
} else {
Crouton.makeText(getActivity(), R.string.no_apps_available, Style.ALERT).show();
}
}
/**
* Check if any apps are installed on the app to receive this intent.
*/
public static boolean isAvailable(Context ctx, Intent intent) {
final PackageManager mgr = ctx.getPackageManager();
List<ResolveInfo> list = mgr.queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY);
return list.size() > 0;
}
@OnClick(R.id.tv_device_name)
public void openDevicePage() {
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(device.url()));
startActivity(i);
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == RESULT_SELECT_PICTURE && resultCode == Activity.RESULT_OK) {
if (data == null) {
return;
}
Uri selectedImageUri = data.getData();
Intent intent = new Intent(getActivity(), GenerateFrameService.class);
intent.putExtra(AbstractGenerateFrameService.KEY_EXTRA_DEVICE, device);
intent.putExtra(GenerateFrameService.KEY_EXTRA_SCREENSHOT, selectedImageUri);
getActivity().startService(intent);
} else {
super.onActivityResult(requestCode, resultCode, data);
}
}
} | Load by size of views
| app/src/main/java/com/f2prateek/dfg/ui/fragments/DeviceFragment.java | Load by size of views | <ide><path>pp/src/main/java/com/f2prateek/dfg/ui/fragments/DeviceFragment.java
<ide> public void onViewCreated(View view, Bundle savedInstanceState) {
<ide> super.onViewCreated(view, savedInstanceState);
<ide> picasso.load(BitmapUtils.getResourceIdentifierForDrawable(getActivity(),
<del> device.getThumbnailResourceName())).into(deviceThumbnailText);
<add> device.getThumbnailResourceName())).fit().centerInside().into(deviceThumbnailText);
<ide> deviceDefaultText.bringToFront();
<ide> deviceDefaultText.setImageResource(
<ide> isDefault() ? R.drawable.ic_action_star_selected : R.drawable.ic_action_star); |
|
Java | bsd-3-clause | 8770501b88e6ae5d716e52720aab61b4d0bb34c6 | 0 | shakalaca/BeautyClockLiveWallpaper | package com.corner23.android.beautyclocklivewallpaper;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.Closeable;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.net.SocketAddress;
import java.net.SocketTimeoutException;
import java.net.URL;
import java.net.URLConnection;
import java.util.TimeZone;
import java.util.concurrent.RejectedExecutionException;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.service.wallpaper.WallpaperService;
import android.text.format.Time;
import android.util.Log;
import android.view.SurfaceHolder;
public class BeautyClockLiveWallpaper extends WallpaperService {
public static final String BROADCAST_WALLPAPER_UPDATE = BeautyClockLiveWallpaper.class.getName() + ":UPDATE";
private static final String TAG = "BeautyClockLiveWallpaper";
private static final int IO_BUFFER_SIZE = 4096;
private int mPictureSource = 0;
private static final String END_STR = "_0";
private static final String ARTHUR_PICTURE_URL = "http://www.arthur.com.tw/photo/images/400/%02d%02d%s.JPG";
private static final String CLOCKM_PICTURE_URL = "http://www.clockm.com/tw/img/clk/hour/%02d%02d.jpg";
private static final String BIJIN_PICTURE_URL_L = "http://www.bijint.com/assets/pict/bijin/590x450/%02d%02d.jpg";
private static final String BIJIN_PICTURE_URL = "http://www.bijint.com/assets/pict/bijin/240x320/%02d%02d.jpg";
private static final String BIJIN_KOREA_PICTURE_URL_L = "http://www.bijint.com/assets/pict/kr/590x450/%02d%02d.jpg";
private static final String BIJIN_KOREA_PICTURE_URL = "http://www.bijint.com/assets/pict/kr/240x320/%02d%02d.jpg";
private static final String BIJIN_GAL_PICTURE_URL_L = "http://gal.bijint.com/assets/pict/gal/590x450/%02d%02d.jpg";
private static final String BIJIN_GAL_PICTURE_URL = "http://gal.bijint.com/assets/pict/gal/240x320/%02d%02d.jpg";
private static final String BIJIN_CC_PICTURE_URL = "http://www.bijint.com/assets/pict/cc/590x450/%02d%02d.jpg";
private static final String BINAN_PICTURE_URL_L = "http://www.bijint.com/assets/pict/bijin/590x450/%02d%02d.jpg";
private static final String BINAN_PICTURE_URL = "http://www.bijint.com/assets/pict/bijin/240x320/%02d%02d.jpg";
private static final String BIJIN_HK_PICTURE_URL_L = "http://www.bijint.com/assets/pict/hk/590x450/%02d%02d.jpg";
private static final String BIJIN_HK_PICTURE_URL = "http://www.bijint.com/assets/pict/hk/240x320/%02d%02d.jpg";
private static final String LOVELY_TIME_PICTURE_URL = "http://gameflier.lovelytime.com.tw/photo/%02d%02d.JPG";
private static final String AVTOKEI_PICTURE_URL = "http://www.avtokei.jp/images/clocks/%02d/%02d%02d.jpg";
private static final String BELL_TO_PLAY = "/sdcard/BeautyClock/bell/bell%02d.mp3";
private static final String SDCARD_BASE_PATH = "/sdcard/BeautyClock/pic";
private static final String ARTHUR_PICTURE_PATH = SDCARD_BASE_PATH + "/arthur/%02d%02d%s.JPG";
private static final String CLOCKM_PICTURE_PATH = SDCARD_BASE_PATH + "/clockm/%02d%02d.jpg";
private static final String BIJIN_PICTURE_PATH = SDCARD_BASE_PATH + "/bijin/%02d%02d.jpg";
private static final String BIJIN_KOREA_PICTURE_PATH = SDCARD_BASE_PATH + "/bijin-kr/%02d%02d.jpg";
private static final String BIJIN_GAL_PICTURE_PATH = SDCARD_BASE_PATH + "/bijin-gal/%02d%02d.jpg";
private static final String BIJIN_CC_PICTURE_PATH = SDCARD_BASE_PATH + "/bijin-cc/%02d%02d.jpg";
private static final String BINAN_PICTURE_PATH = SDCARD_BASE_PATH + "/binan/%02d%02d.jpg";
private static final String BIJIN_HK_PICTURE_PATH = SDCARD_BASE_PATH + "/bijin-hk/%02d%02d.jpg";
private static final String LOVELY_TIME_PICTURE_PATH = SDCARD_BASE_PATH + "/lovely/%02d%02d.JPG";
private static final String AVTOKEI_PICTURE_PATH = SDCARD_BASE_PATH + "/av/%02d%02d.jpg";
private static final String CUSTOM_PICTURE_PATH = SDCARD_BASE_PATH + "/custom/%02d%02d.jpg";
private static final int BCLW_FETCH_STATE_OTHER_FAILED = -1;
private static final int BCLW_FETCH_STATE_SUCCESS = 0;
private static final int BCLW_FETCH_STATE_FILE_NOT_FOUND = 1;
private static final int BCLW_FETCH_STATE_TIMEOUT = 2;
private static final int BCLW_FETCH_STATE_IO_ERROR = 3;
private Time mTime = new Time();
private int mHour = 0;
private int mMinute = 0;
private int mNextHour = 0;
private int mNextMinute = 0;
// private Bitmap mErrorBitmap = null;
private Bitmap mCurrentBeautyBitmap = null;
private Bitmap mNextBeautyBitmap = null;
private FetchNextBeautyPictureTask mFetchNextBeautyPictureTask = null;
private FetchCurrentBeautyPictureTask mFetchCurrentBeautyPictureTask = null;
private PlayBellTask mPlayBellTask = null;
// preferences
private boolean mBellHourly = false;
private boolean mFetchWhenScreenOff = true;
private boolean mFetchLargerPicture = true;
private boolean mFitScreen = false;
private boolean mSaveCopy = false;
private Proxy httpProxy;
private String httpProxyHost;
private Integer httpProxyPort;
private ConnectivityManager cm = null;
private boolean mIsScreenOn = true;
private boolean mRegScreenBR = false;
private boolean mRegTimeBR = false;
private String getPATH(int hour, int minutes) {
String URLstr = null;
switch (mPictureSource) {
default:
case 0: URLstr = String.format(ARTHUR_PICTURE_PATH, hour, minutes, (minutes == 0) ? END_STR : ""); break;
case 1: URLstr = String.format(CLOCKM_PICTURE_PATH, hour, minutes); break;
case 2: URLstr = String.format(BIJIN_PICTURE_PATH, hour, minutes); break;
case 3: URLstr = String.format(BIJIN_KOREA_PICTURE_PATH, hour, minutes); break;
case 4: URLstr = String.format(BIJIN_HK_PICTURE_PATH, hour, minutes); break;
case 5: URLstr = String.format(BIJIN_GAL_PICTURE_PATH, hour, minutes); break;
case 6: URLstr = String.format(BIJIN_CC_PICTURE_PATH, hour, minutes); break;
case 7: URLstr = String.format(BINAN_PICTURE_PATH, hour, minutes); break;
case 8: URLstr = String.format(LOVELY_TIME_PICTURE_PATH, hour, minutes); break;
case 9: URLstr = String.format(CUSTOM_PICTURE_PATH, hour, minutes); break;
case 10: URLstr = String.format(AVTOKEI_PICTURE_PATH, hour, hour, minutes); break;
}
return URLstr;
}
private String getURL(int hour, int minutes) {
String URLstr = null;
switch (mPictureSource) {
default:
case 0: URLstr = String.format(ARTHUR_PICTURE_URL, hour, minutes, (minutes == 0) ? END_STR : ""); break;
case 1: URLstr = String.format(CLOCKM_PICTURE_URL, hour, minutes); break;
case 2: URLstr = String.format(mFetchLargerPicture ? BIJIN_PICTURE_URL_L : BIJIN_PICTURE_URL, hour, minutes); break;
case 3: URLstr = String.format(mFetchLargerPicture ? BIJIN_KOREA_PICTURE_URL_L : BIJIN_KOREA_PICTURE_URL, hour, minutes); break;
case 4: URLstr = String.format(mFetchLargerPicture ? BIJIN_HK_PICTURE_URL_L : BIJIN_HK_PICTURE_URL, hour, minutes); break;
case 5: URLstr = String.format(mFetchLargerPicture ? BIJIN_GAL_PICTURE_URL_L : BIJIN_GAL_PICTURE_URL, hour, minutes); break;
case 6: URLstr = String.format(BIJIN_CC_PICTURE_URL, hour, minutes); break;
case 7: URLstr = String.format(mFetchLargerPicture ? BINAN_PICTURE_URL_L : BINAN_PICTURE_URL, hour, minutes); break;
case 8: URLstr = String.format(LOVELY_TIME_PICTURE_URL, hour, minutes); break;
case 10: URLstr = String.format(AVTOKEI_PICTURE_URL, hour, hour, minutes); break;
}
return URLstr;
}
private class FetchNextBeautyPictureTask extends AsyncTask<Void, Void, Integer> {
@Override
protected Integer doInBackground(Void... arg0) {
Log.w(TAG, "doInBackground:FetchNextBeautyPictureTask");
int ret = BCLW_FETCH_STATE_OTHER_FAILED;
mNextBeautyBitmap = null;
try {
String fpath = getPATH(mNextHour, mNextMinute);
File mFile = new File(fpath);
if (mFile.exists()) {
mNextBeautyBitmap = fetchBeautyPictureBitmapFromFile(fpath);
} else {
URL mURL = new URL(getURL(mNextHour, mNextMinute));
mNextBeautyBitmap = fetchBeautyPictureBitmapFromURL(mURL, mFile);
}
ret = BCLW_FETCH_STATE_SUCCESS;
} catch (FileNotFoundException e) {
e.printStackTrace();
ret = BCLW_FETCH_STATE_FILE_NOT_FOUND;
} catch (IOException e) {
e.printStackTrace();
ret = BCLW_FETCH_STATE_IO_ERROR;
if (cm != null) {
NetworkInfo ni = cm.getActiveNetworkInfo();
if (ni != null && ni.isConnected()) {
ret = BCLW_FETCH_STATE_TIMEOUT;
}
}
}
return ret;
}
protected void onPostExecute(Integer ret) {
Log.w(TAG, "onPostExecute:FetchNextBeautyPictureTask");
mFetchNextBeautyPictureTask = null;
if (ret == BCLW_FETCH_STATE_TIMEOUT) {
Log.w("BeautyClockUpdateService", "timeout, startToFetchNextBeautyPicture");
startToFetchNextBeautyPicture();
}
}
}
private void startToFetchNextBeautyPicture() {
try {
if (mFetchNextBeautyPictureTask != null &&
mFetchNextBeautyPictureTask.getStatus() == AsyncTask.Status.RUNNING) {
mFetchNextBeautyPictureTask.cancel(true);
}
mFetchNextBeautyPictureTask = new FetchNextBeautyPictureTask();
mFetchNextBeautyPictureTask.execute();
} catch (RejectedExecutionException e) {
e.printStackTrace();
}
}
private class FetchCurrentBeautyPictureTask extends AsyncTask<Void, Void, Integer> {
@Override
protected Integer doInBackground(Void... arg0) {
Log.w(TAG, "doInBackground:FetchCurrentBeautyPictureTask");
int ret = BCLW_FETCH_STATE_OTHER_FAILED;
try {
String fpath = getPATH(mHour, mMinute);
File mFile = new File(fpath);
if (mFile.exists()) {
mCurrentBeautyBitmap = fetchBeautyPictureBitmapFromFile(fpath);
} else {
URL mURL = new URL(getURL(mHour, mMinute));
mCurrentBeautyBitmap = fetchBeautyPictureBitmapFromURL(mURL, mFile);
}
ret = BCLW_FETCH_STATE_SUCCESS;
} catch (FileNotFoundException e) {
e.printStackTrace();
ret = BCLW_FETCH_STATE_FILE_NOT_FOUND;
} catch (IOException e) {
e.printStackTrace();
ret = BCLW_FETCH_STATE_IO_ERROR;
if (cm != null) {
NetworkInfo ni = cm.getActiveNetworkInfo();
if (ni != null && ni.isConnected()) {
ret = BCLW_FETCH_STATE_TIMEOUT;
}
}
}
return ret;
}
protected void onPostExecute(Integer ret) {
Log.w(TAG, "onPostExecute:FetchCurrentBeautyPictureTask");
mFetchCurrentBeautyPictureTask = null;
if (mCurrentBeautyBitmap == null) {
if (ret == BCLW_FETCH_STATE_TIMEOUT) {
Log.w("BeautyClockUpdateService", "timeout, startToFetchCurrentBeautyPicture");
startToFetchCurrentBeautyPicture();
return;
}
} else {
Intent i = new Intent(BROADCAST_WALLPAPER_UPDATE);
sendBroadcast(i);
}
startToFetchNextBeautyPicture();
}
}
private void startToFetchCurrentBeautyPicture(){
try {
if (mFetchCurrentBeautyPictureTask != null &&
mFetchCurrentBeautyPictureTask.getStatus() == AsyncTask.Status.RUNNING) {
mFetchCurrentBeautyPictureTask.cancel(true);
}
mFetchCurrentBeautyPictureTask = new FetchCurrentBeautyPictureTask();
mFetchCurrentBeautyPictureTask.execute();
} catch(RejectedExecutionException e) {
e.printStackTrace();
}
}
private class PlayBellTask extends AsyncTask<Void, Void, Void> {
@Override
protected Void doInBackground(Void... params) {
if (!mBellHourly) {
return null;
}
if (mMinute == 0) {
// check phone settings first, if it's in silent or vibration mode, don't play bell!
AudioManager am = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
if (am != null && (am.getRingerMode() == AudioManager.RINGER_MODE_SILENT ||
am.getRingerMode() == AudioManager.RINGER_MODE_VIBRATE)) {
Log.i(TAG, "Phone is in vibration mode or silent mode");
return null;
}
try {
MediaPlayer mp = new MediaPlayer();
mp.setDataSource(String.format(BELL_TO_PLAY, mHour));
mp.prepare();
mp.start();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
@Override
protected void onPostExecute(Void result) {
mPlayBellTask = null;
}
}
private void startToPlayBell() {
try {
if (mPlayBellTask != null &&
mPlayBellTask.getStatus() == AsyncTask.Status.RUNNING) {
mPlayBellTask.cancel(true);
}
mPlayBellTask = new PlayBellTask();
mPlayBellTask.execute();
} catch(RejectedExecutionException e) {
e.printStackTrace();
}
}
private void configureHttpProxy() {
this.httpProxyHost = android.net.Proxy.getDefaultHost();
this.httpProxyPort = android.net.Proxy.getDefaultPort();
if (this.httpProxyHost != null && this.httpProxyPort != null) {
SocketAddress proxyAddress = new InetSocketAddress(this.httpProxyHost, this.httpProxyPort);
this.httpProxy = new Proxy(Proxy.Type.HTTP, proxyAddress);
} else {
this.httpProxy = Proxy.NO_PROXY;
}
}
private Bitmap fetchBeautyPictureBitmapFromFile(String fpath) {
try {
// Bitmap bitmap = BitmapFactory.decodeFile(fpath);
// return ResizeBitmap(bitmap);
return BitmapFactory.decodeFile(fpath);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
private Bitmap fetchBeautyPictureBitmapFromURL(URL url, File saveFile) throws IOException {
Bitmap bitmap = null;
InputStream in = null;
OutputStream out = null;
URLConnection urlc = null;
try {
if (cm != null) {
// network is turned off by user
if (!cm.getBackgroundDataSetting()) {
return null;
}
// network is not connected
NetworkInfo ni = cm.getActiveNetworkInfo();
if (ni != null && ni.getState() != NetworkInfo.State.CONNECTED) {
return null;
}
// if we're using WIFI, then there's no proxy from APN
if (ni != null && ni.getType() == ConnectivityManager.TYPE_WIFI) {
this.httpProxy = Proxy.NO_PROXY;
} else {
this.configureHttpProxy();
}
}
} catch (Exception e) {
}
try {
urlc = url.openConnection(this.httpProxy);
urlc.setRequestProperty("User-Agent", "Mozilla/5.0");
if (mPictureSource == 10) {
urlc.setRequestProperty("Referer", "http://www.avtokei.jp/index.html");
} else if (mPictureSource == 7) {
urlc.setRequestProperty("Referer", "http://www.bijint.com/binan/");
} else if (mPictureSource == 6) {
urlc.setRequestProperty("Referer", "http://www.bijint.com/cc/");
} else if (mPictureSource == 5) {
urlc.setRequestProperty("Referer", "http://gal.bijint.com/");
} else if (mPictureSource == 4) {
urlc.setRequestProperty("Referer", "http://www.bijint.com/hk/");
} else if (mPictureSource == 3) {
urlc.setRequestProperty("Referer", "http://www.bijint.com/kr/");
} else if (mPictureSource == 2) {
urlc.setRequestProperty("Referer", "http://www.bijint.com/jp/");
}
urlc.setReadTimeout(10000);
urlc.setConnectTimeout(10000);
in = new BufferedInputStream(urlc.getInputStream(), IO_BUFFER_SIZE);
final ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
out = new BufferedOutputStream(dataStream, IO_BUFFER_SIZE);
copy(in, out);
out.flush();
final byte[] data = dataStream.toByteArray();
bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
if (mSaveCopy && saveFile != null && !saveFile.exists()) {
saveCopy(bitmap, saveFile);
}
// Bitmap newbitmap = ResizeBitmap(bitmap);
// if (newbitmap != null) {
// bitmap = newbitmap;
// }
} finally {
closeStream(in);
closeStream(out);
}
return bitmap;
}
private static int copy(InputStream in, OutputStream out) throws IOException, SocketTimeoutException {
byte[] b = new byte[IO_BUFFER_SIZE];
int read, size = 0;
while ((read = in.read(b)) != -1) {
out.write(b, 0, read);
size += read;
}
return size;
}
private static void closeStream(Closeable stream) {
if (stream != null) {
try {
stream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
private boolean saveCopy(Bitmap bitmap, File new_file) {
if (bitmap == null || new_file == null) {
return false;
}
try {
// Try to create neccessary directory
new_file.mkdirs();
// output to tmp file
String fname_tmp = new_file.getAbsolutePath() + ".tmp";
FileOutputStream out = new FileOutputStream(fname_tmp);
bitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
out.flush();
out.close();
// if success, rename to correct file name
File tmp_file = new File(fname_tmp);
new_file.delete();
tmp_file.renameTo(new_file);
} catch (Exception e) {
e.printStackTrace();
return false;
}
return true;
}
private void update() {
try {
boolean reget = false;
if (mFetchCurrentBeautyPictureTask != null) {
mFetchCurrentBeautyPictureTask.cancel(true);
reget = true;
}
if (mFetchNextBeautyPictureTask != null) {
mFetchNextBeautyPictureTask.cancel(true);
reget = true;
}
if (reget) {
firstUpdate();
return;
}
if (mNextBeautyBitmap != null) {
mCurrentBeautyBitmap = mNextBeautyBitmap;
Intent i = new Intent(BROADCAST_WALLPAPER_UPDATE);
sendBroadcast(i);
}
mTime.setToNow();
updateTimeForNextUpdate();
startToFetchNextBeautyPicture();
} catch (Exception e) {
e.printStackTrace();
}
}
private final BroadcastReceiver mScreenBroadcastReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
Log.w(TAG, "mScreenBroadcastReceiver:onReceive");
if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) {
// Log.v(TAG, "Intent.ACTION_SCREEN_ON");
mIsScreenOn = true;
firstUpdate();
registerTimeBroadcastReceiver();
} else if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
// Log.v(TAG, "Intent.ACTION_SCREEN_OFF");
mIsScreenOn = false;
unregisterTimeBroadcastReceiver();
}
}
};
private final BroadcastReceiver mTimeBroadcastReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
Log.w(TAG, "mTimeBroadcastReceiver:onReceive");
if (intent.getAction().equals(Intent.ACTION_TIMEZONE_CHANGED)) {
String tz = intent.getStringExtra("time-zone");
mTime = new Time(TimeZone.getTimeZone(tz).getID());
if (mFetchCurrentBeautyPictureTask != null) {
mFetchCurrentBeautyPictureTask.cancel(true);
}
if (mFetchNextBeautyPictureTask != null) {
mFetchNextBeautyPictureTask.cancel(true);
}
firstUpdate();
return;
}
mTime.setToNow();
if (!(mHour == mTime.hour && mMinute == mTime.minute)) {
mHour = mTime.hour;
mMinute = mTime.minute;
if (!mFetchWhenScreenOff && !mIsScreenOn) {
updateTimeForNextUpdate();
startToPlayBell();
return;
}
update();
startToPlayBell();
}
}
};
private void updateTimeForNextUpdate() {
mNextHour = mTime.hour;
mNextMinute = mTime.minute;
if (mNextMinute == 59) {
mNextHour++;
if (mNextHour == 24) {
mNextHour = 0;
}
mNextMinute = -1;
}
mNextMinute++;
}
private void firstUpdate() {
mTime.setToNow();
mHour = mTime.hour;
mMinute = mTime.minute;
updateTimeForNextUpdate();
startToFetchCurrentBeautyPicture();
}
private void readDefaultPrefs(SharedPreferences prefs) {
if (prefs == null) {
return;
}
mFetchWhenScreenOff = prefs.getBoolean(Settings.PREF_FETCH_WHEN_SCREEN_OFF, true);
mBellHourly = prefs.getBoolean(Settings.PREF_RING_HOURLY, false);
mSaveCopy = prefs.getBoolean(Settings.PREF_SAVE_COPY, false);
mFitScreen = prefs.getBoolean(Settings.PREF_FIT_SCREEN, false);
mFetchLargerPicture = prefs.getBoolean(Settings.PREF_FETCH_LARGER_PICTURE, true);
mPictureSource = Integer.parseInt(prefs.getString(Settings.PREF_PICTURE_SOURCE, "0"));
}
private void registerTimeBroadcastReceiver() {
if (!mRegTimeBR) {
IntentFilter filter = new IntentFilter();
filter.addAction(Intent.ACTION_TIME_TICK);
filter.addAction(Intent.ACTION_TIME_CHANGED);
filter.addAction(Intent.ACTION_TIMEZONE_CHANGED);
this.registerReceiver(mTimeBroadcastReceiver, filter);
mRegTimeBR = true;
}
}
private void unregisterTimeBroadcastReceiver() {
if (mRegTimeBR) {
this.unregisterReceiver(mTimeBroadcastReceiver);
mRegTimeBR = false;
}
}
private void registerScreenBroadcastReceiver() {
if (!mRegScreenBR) {
IntentFilter filter = new IntentFilter();
filter.addAction(Intent.ACTION_SCREEN_ON);
filter.addAction(Intent.ACTION_SCREEN_OFF);
this.registerReceiver(mScreenBroadcastReceiver, filter);
mRegScreenBR = true;
}
}
private void unregisterScreenBroadcastReceiver() {
if (mRegScreenBR) {
this.unregisterReceiver(mScreenBroadcastReceiver);
mRegScreenBR = false;
}
}
@Override
public void onCreate() {
// read configuration
SharedPreferences mSharedPreferences = this.getSharedPreferences(Settings.SHARED_PREFS_NAME, 0);
readDefaultPrefs(mSharedPreferences);
// register notification
registerTimeBroadcastReceiver();
registerScreenBroadcastReceiver();
// get connection manager for checking network status
cm = (ConnectivityManager) this.getSystemService(Context.CONNECTIVITY_SERVICE);
// setup proxy
this.configureHttpProxy();
}
@Override
public void onStart(Intent intent, int startId) {
Log.w(TAG, "onStart");
onStartCommand(intent, 0, startId);
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.w(TAG, "onStartCommand");
firstUpdate();
return START_STICKY;
}
public void onDestroy() {
if (mPlayBellTask != null) {
mPlayBellTask.cancel(true);
}
if (mFetchCurrentBeautyPictureTask != null) {
mFetchCurrentBeautyPictureTask.cancel(true);
}
if (mFetchNextBeautyPictureTask != null) {
mFetchNextBeautyPictureTask.cancel(true);
}
unregisterTimeBroadcastReceiver();
unregisterScreenBroadcastReceiver();
super.onDestroy();
}
@Override
public Engine onCreateEngine() {
return new BeautyClockEngine();
}
class BeautyClockEngine extends Engine implements SharedPreferences.OnSharedPreferenceChangeListener {
private static final int STATUS_BAR_HEIGHT = 38;
private int mScreenHeight = 0;
private int mScreenWidth = 0;
private int nXOffset = 0;
private SharedPreferences mPrefs;
private boolean bIsLarge = false;
private BroadcastReceiver mWallpaperUpdateBroadcastReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
draw();
}
};
BeautyClockEngine() {
mScreenHeight = getResources().getDisplayMetrics().heightPixels;
mScreenWidth = getResources().getDisplayMetrics().widthPixels;
mPrefs = BeautyClockLiveWallpaper.this.getSharedPreferences(Settings.SHARED_PREFS_NAME, 0);
mPrefs.registerOnSharedPreferenceChangeListener(this);
onSharedPreferenceChanged(mPrefs, null);
firstUpdate();
}
public void onSharedPreferenceChanged(SharedPreferences prefs, String key) {
if (prefs == null) {
return;
}
if (key == null) {
readDefaultPrefs(prefs);
return;
}
if (key.equals(Settings.PREF_FETCH_WHEN_SCREEN_OFF)) {
mFetchWhenScreenOff = prefs.getBoolean(Settings.PREF_FETCH_WHEN_SCREEN_OFF, true);
} else if (key.equals(Settings.PREF_RING_HOURLY)) {
mBellHourly = prefs.getBoolean(Settings.PREF_RING_HOURLY, false);
} else if (key.equals(Settings.PREF_SAVE_COPY)) {
mSaveCopy = prefs.getBoolean(Settings.PREF_SAVE_COPY, false);
} else if (key.equals(Settings.PREF_FIT_SCREEN)) {
mFitScreen = prefs.getBoolean(Settings.PREF_FIT_SCREEN, false);
draw();
} else if (key.equals(Settings.PREF_FETCH_LARGER_PICTURE)) {
mFetchLargerPicture = prefs.getBoolean(Settings.PREF_FETCH_LARGER_PICTURE, true);
firstUpdate();
} else if (key.equals(Settings.PREF_PICTURE_SOURCE)) {
mPictureSource = Integer.parseInt(prefs.getString(Settings.PREF_PICTURE_SOURCE, "0"));
firstUpdate();
}
}
/*
@Override
public void onSurfaceCreated(SurfaceHolder holder) {
Log.d(TAG, "onSurfaceCreated");
super.onSurfaceCreated(holder);
}
@Override
public int getDesiredMinimumHeight() {
Log.d(TAG, "getDesiredMinimumHeight");
return super.getDesiredMinimumHeight();
}
@Override
public int getDesiredMinimumWidth() {
Log.d(TAG, "getDesiredMinimumWidth");
return super.getDesiredMinimumWidth();
}
@Override
public SurfaceHolder getSurfaceHolder() {
Log.d(TAG, "getSurfaceHolder");
return super.getSurfaceHolder();
}
@Override
public boolean isPreview() {
Log.d(TAG, "isPreview");
return super.isPreview();
}
@Override
public boolean isVisible() {
Log.d(TAG, "isVisible");
return super.isVisible();
}
@Override
public Bundle onCommand(String action, int x, int y, int z,
Bundle extras, boolean resultRequested) {
Log.d(TAG, "onCommand");
return super.onCommand(action, x, y, z, extras, resultRequested);
}
@Override
public void onTouchEvent(MotionEvent event) {
Log.d(TAG, "onTouchEvent");
super.onTouchEvent(event);
}
@Override
public void setTouchEventsEnabled(boolean enabled) {
Log.d(TAG, "setTouchEventsEnabled:" + enabled);
super.setTouchEventsEnabled(enabled);
}
@Override
public void onDesiredSizeChanged(int desiredWidth, int desiredHeight) {
Log.d(TAG, "onDesiredSizeChanged");
super.onDesiredSizeChanged(desiredWidth, desiredHeight);
}
@Override
public void onSurfaceDestroyed(SurfaceHolder holder) {
Log.d(TAG, "onSurfaceDestroyed");
super.onSurfaceDestroyed(holder);
}
*/
@Override
public void onCreate(SurfaceHolder surfaceHolder) {
// Log.d(TAG, "onCreate (engine)");
super.onCreate(surfaceHolder);
setTouchEventsEnabled(false);
IntentFilter filter = new IntentFilter();
filter.addAction(BROADCAST_WALLPAPER_UPDATE);
BeautyClockLiveWallpaper.this.registerReceiver(mWallpaperUpdateBroadcastReceiver, filter);
}
@Override
public void onDestroy() {
// Log.d(TAG, "onDestroy (engine)");
super.onDestroy();
BeautyClockLiveWallpaper.this.unregisterReceiver(mWallpaperUpdateBroadcastReceiver);
}
@Override
public void onOffsetsChanged(float xOffset, float yOffset,
float xOffsetStep, float yOffsetStep, int xPixelOffset,
int yPixelOffset) {
// Log.d(TAG, "onOffsetsChanged");
// Log.d(TAG, "x:" + xPixelOffset + ", y:" + yPixelOffset);
nXOffset = xPixelOffset;
if (bIsLarge) {
draw();
}
}
@Override
public void onSurfaceChanged(SurfaceHolder holder, int format,
int width, int height) {
// Log.d(TAG, "onSurfaceChanged:" + width + "," + height);
mScreenHeight = height;
mScreenWidth = width;
draw();
}
@Override
public void onVisibilityChanged(boolean visible) {
Log.d(TAG, "onVisibilityChanged:" + visible);
if (visible) {
mIsScreenOn = true;
registerTimeBroadcastReceiver();
draw();
} else {
mIsScreenOn = false;
unregisterTimeBroadcastReceiver();
}
}
private Bitmap ResizeBitmap(Bitmap bitmap) {
if (bitmap == null) {
return null;
}
int width = bitmap.getWidth();
int height = bitmap.getHeight();
if (width == 0 || height == 0) {
return null;
}
if (mScreenWidth > mScreenHeight) {
double ratio = (float) (mScreenHeight - STATUS_BAR_HEIGHT) / height;
width = (int) (width * ratio);
height = mScreenHeight - STATUS_BAR_HEIGHT;
} else {
if (height > width) {
if (mFitScreen) {
height = mScreenHeight - STATUS_BAR_HEIGHT;
} else {
double ratio = (float) mScreenWidth / width;
height = (int) (height * ratio);
}
width = mScreenWidth;
/*
double ratio = (float) (mScreenHeight - 60) / height;
height = mScreenHeight - 60;
width = (int) (width * ratio);
*/
} else {
if (mFitScreen) {
height = mScreenHeight - STATUS_BAR_HEIGHT;
} else {
double ratio = (float) mScreenWidth*2 / width;
height = (int) (height * ratio);
}
width = mScreenWidth*2;
}
}
// Log.w(TAG, "bitmap:"+ bitmap.getWidth() + "x" + bitmap.getHeight() + ":"+ bitmap.getDensity());
// Log.w(TAG, "bitmap:"+ bitmap.getWidth()*bitmap.getHeight());
Bitmap bitmapNew = Bitmap.createScaledBitmap(bitmap, width, height, true);
// Log.w(TAG,"scaled !!!!!!!!!!");
// Log.w(TAG,"bitmap:"+ bitmap.getWidth() + "x" + bitmap.getHeight() + ":"+ bitmap.getDensity());
// Log.w(TAG,"bitmap:"+ bitmap.getWidth()*bitmap.getHeight());
return bitmapNew;
}
private void drawBeautyClock(Canvas c, Bitmap bitmap_src) {
if (c == null || bitmap_src == null) {
return;
}
Bitmap bitmap_resized = ResizeBitmap(bitmap_src);
int width = bitmap_resized.getWidth();
int height = bitmap_resized.getHeight();
int Xpos = 0, Ypos = STATUS_BAR_HEIGHT;
// picture across virtual desktop, set scrolling
if (width > height) {
Xpos = nXOffset;
bIsLarge = true;
} else {
bIsLarge = false;
}
if (mScreenWidth > mScreenHeight) {
int offset = (int) (mScreenWidth * (bIsLarge ? 1.2 : 1) - width) / 2;
if (offset > 0) {
Xpos += offset;
}
} else {
if (!mFitScreen) {
int offset = (mScreenHeight - STATUS_BAR_HEIGHT - height) / 2;
if (offset > 0) {
Ypos += offset;
}
}
}
// clean before drawing
c.drawColor(Color.BLACK);
c.drawBitmap(bitmap_resized, Xpos, Ypos, null);
}
private void drawErrorScreen(Canvas c) {
// setup paint for drawing digitl clock
Paint paint = new Paint();
paint.setColor(Color.YELLOW);
paint.setAntiAlias(true);
paint.setStrokeCap(Paint.Cap.ROUND);
paint.setStyle(Paint.Style.STROKE);
paint.setStrokeWidth(5);
paint.setTextSize(120);
String time = String.format("%02d:%02d", mHour, mMinute);
c.drawColor(Color.BLACK);
c.drawText(time, mScreenWidth/2-150, mScreenHeight/2-30, paint);
/*
Paint paint = new Paint();
paint.setColor(Color.BLACK);
paint.setAntiAlias(true);
paint.setStrokeCap(Paint.Cap.ROUND);
paint.setStyle(Paint.Style.STROKE);
paint.setStrokeWidth(5);
paint.setTextSize(120);
if (mErrorBitmap == null) {
Drawable dw = getResources().getDrawable(R.drawable.beautyclock_retry);
mErrorBitmap = ResizeBitmap(((BitmapDrawable)dw).getBitmap());
}
c.drawBitmap(mErrorBitmap, 0, 15, paint);
String time = String.format("%02d:%02d", mHour, mMinute);
/c.drawText(time, mScreenWidth/2-150, 140, paint);
*/
}
private void draw() {
final SurfaceHolder holder = getSurfaceHolder();
Canvas c = null;
try {
c = holder.lockCanvas();
if (c != null) {
if (mCurrentBeautyBitmap != null) {
drawBeautyClock(c, mCurrentBeautyBitmap);
} else {
drawErrorScreen(c);
}
}
} finally {
if (c != null) {
holder.unlockCanvasAndPost(c);
}
}
}
}
} | src/com/corner23/android/beautyclocklivewallpaper/BeautyClockLiveWallpaper.java | package com.corner23.android.beautyclocklivewallpaper;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.Closeable;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.net.SocketAddress;
import java.net.SocketTimeoutException;
import java.net.URL;
import java.net.URLConnection;
import java.util.TimeZone;
import java.util.concurrent.RejectedExecutionException;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.service.wallpaper.WallpaperService;
import android.text.format.Time;
import android.util.Log;
import android.view.SurfaceHolder;
public class BeautyClockLiveWallpaper extends WallpaperService {
public static final String BROADCAST_WALLPAPER_UPDATE = BeautyClockLiveWallpaper.class.getName() + ":UPDATE";
private static final String TAG = "BeautyClockLiveWallpaper";
private static final int IO_BUFFER_SIZE = 4096;
private int mPictureSource = 0;
private static final String END_STR = "_0";
private static final String ARTHUR_PICTURE_URL = "http://www.arthur.com.tw/photo/images/400/%02d%02d%s.JPG";
private static final String CLOCKM_PICTURE_URL = "http://www.clockm.com/tw/img/clk/hour/%02d%02d.jpg";
private static final String BIJIN_PICTURE_URL_L = "http://www.bijint.com/assets/pict/bijin/590x450/%02d%02d.jpg";
private static final String BIJIN_PICTURE_URL = "http://www.bijint.com/assets/pict/bijin/240x320/%02d%02d.jpg";
private static final String BIJIN_KOREA_PICTURE_URL_L = "http://www.bijint.com/assets/pict/kr/590x450/%02d%02d.jpg";
private static final String BIJIN_KOREA_PICTURE_URL = "http://www.bijint.com/assets/pict/kr/240x320/%02d%02d.jpg";
private static final String BIJIN_GAL_PICTURE_URL_L = "http://gal.bijint.com/assets/pict/gal/590x450/%02d%02d.jpg";
private static final String BIJIN_GAL_PICTURE_URL = "http://gal.bijint.com/assets/pict/gal/240x320/%02d%02d.jpg";
private static final String BIJIN_CC_PICTURE_URL = "http://www.bijint.com/assets/pict/cc/590x450/%02d%02d.jpg";
private static final String BINAN_PICTURE_URL_L = "http://www.bijint.com/assets/pict/bijin/590x450/%02d%02d.jpg";
private static final String BINAN_PICTURE_URL = "http://www.bijint.com/assets/pict/bijin/240x320/%02d%02d.jpg";
private static final String BIJIN_HK_PICTURE_URL_L = "http://www.bijint.com/assets/pict/hk/590x450/%02d%02d.jpg";
private static final String BIJIN_HK_PICTURE_URL = "http://www.bijint.com/assets/pict/hk/240x320/%02d%02d.jpg";
private static final String LOVELY_TIME_PICTURE_URL = "http://gameflier.lovelytime.com.tw/photo/%02d%02d.JPG";
private static final String AVTOKEI_PICTURE_URL = "http://www.avtokei.jp/images/clocks/%02d/%02d%02d.jpg";
private static final String BELL_TO_PLAY = "/sdcard/BeautyClock/bell/bell%02d.mp3";
private static final String SDCARD_BASE_PATH = "/sdcard/BeautyClock/pic";
private static final String ARTHUR_PICTURE_PATH = SDCARD_BASE_PATH + "/arthur/%02d%02d%s.JPG";
private static final String CLOCKM_PICTURE_PATH = SDCARD_BASE_PATH + "/clockm/%02d%02d.jpg";
private static final String BIJIN_PICTURE_PATH = SDCARD_BASE_PATH + "/bijin/%02d%02d.jpg";
private static final String BIJIN_KOREA_PICTURE_PATH = SDCARD_BASE_PATH + "/bijin-kr/%02d%02d.jpg";
private static final String BIJIN_GAL_PICTURE_PATH = SDCARD_BASE_PATH + "/bijin-gal/%02d%02d.jpg";
private static final String BIJIN_CC_PICTURE_PATH = SDCARD_BASE_PATH + "/bijin-cc/%02d%02d.jpg";
private static final String BINAN_PICTURE_PATH = SDCARD_BASE_PATH + "/binan/%02d%02d.jpg";
private static final String BIJIN_HK_PICTURE_PATH = SDCARD_BASE_PATH + "/bijin-hk/%02d%02d.jpg";
private static final String LOVELY_TIME_PICTURE_PATH = SDCARD_BASE_PATH + "/lovely/%02d%02d.JPG";
private static final String AVTOKEI_PICTURE_PATH = SDCARD_BASE_PATH + "/av/%02d%02d.jpg";
private static final String CUSTOM_PICTURE_PATH = SDCARD_BASE_PATH + "/custom/%02d%02d.jpg";
private static final int BCLW_FETCH_STATE_OTHER_FAILED = -1;
private static final int BCLW_FETCH_STATE_SUCCESS = 0;
private static final int BCLW_FETCH_STATE_FILE_NOT_FOUND = 1;
private static final int BCLW_FETCH_STATE_TIMEOUT = 2;
private static final int BCLW_FETCH_STATE_IO_ERROR = 3;
private Time mTime = new Time();
private int mHour = 0;
private int mMinute = 0;
private int mNextHour = 0;
private int mNextMinute = 0;
// private Bitmap mErrorBitmap = null;
private Bitmap mCurrentBeautyBitmap = null;
private Bitmap mNextBeautyBitmap = null;
private FetchNextBeautyPictureTask mFetchNextBeautyPictureTask = null;
private FetchCurrentBeautyPictureTask mFetchCurrentBeautyPictureTask = null;
private PlayBellTask mPlayBellTask = null;
// preferences
private boolean mBellHourly = false;
private boolean mFetchWhenScreenOff = true;
private boolean mFetchLargerPicture = true;
private boolean mFitScreen = false;
private boolean mSaveCopy = false;
private Proxy httpProxy;
private String httpProxyHost;
private Integer httpProxyPort;
private ConnectivityManager cm = null;
private boolean mIsScreenOn = true;
private String getPATH(int hour, int minutes) {
String URLstr = null;
switch (mPictureSource) {
default:
case 0: URLstr = String.format(ARTHUR_PICTURE_PATH, hour, minutes, (minutes == 0) ? END_STR : ""); break;
case 1: URLstr = String.format(CLOCKM_PICTURE_PATH, hour, minutes); break;
case 2: URLstr = String.format(BIJIN_PICTURE_PATH, hour, minutes); break;
case 3: URLstr = String.format(BIJIN_KOREA_PICTURE_PATH, hour, minutes); break;
case 4: URLstr = String.format(BIJIN_HK_PICTURE_PATH, hour, minutes); break;
case 5: URLstr = String.format(BIJIN_GAL_PICTURE_PATH, hour, minutes); break;
case 6: URLstr = String.format(BIJIN_CC_PICTURE_PATH, hour, minutes); break;
case 7: URLstr = String.format(BINAN_PICTURE_PATH, hour, minutes); break;
case 8: URLstr = String.format(LOVELY_TIME_PICTURE_PATH, hour, minutes); break;
case 9: URLstr = String.format(CUSTOM_PICTURE_PATH, hour, minutes); break;
case 10: URLstr = String.format(AVTOKEI_PICTURE_PATH, hour, hour, minutes); break;
}
return URLstr;
}
private String getURL(int hour, int minutes) {
String URLstr = null;
switch (mPictureSource) {
default:
case 0: URLstr = String.format(ARTHUR_PICTURE_URL, hour, minutes, (minutes == 0) ? END_STR : ""); break;
case 1: URLstr = String.format(CLOCKM_PICTURE_URL, hour, minutes); break;
case 2: URLstr = String.format(mFetchLargerPicture ? BIJIN_PICTURE_URL_L : BIJIN_PICTURE_URL, hour, minutes); break;
case 3: URLstr = String.format(mFetchLargerPicture ? BIJIN_KOREA_PICTURE_URL_L : BIJIN_KOREA_PICTURE_URL, hour, minutes); break;
case 4: URLstr = String.format(mFetchLargerPicture ? BIJIN_HK_PICTURE_URL_L : BIJIN_HK_PICTURE_URL, hour, minutes); break;
case 5: URLstr = String.format(mFetchLargerPicture ? BIJIN_GAL_PICTURE_URL_L : BIJIN_GAL_PICTURE_URL, hour, minutes); break;
case 6: URLstr = String.format(BIJIN_CC_PICTURE_URL, hour, minutes); break;
case 7: URLstr = String.format(mFetchLargerPicture ? BINAN_PICTURE_URL_L : BINAN_PICTURE_URL, hour, minutes); break;
case 8: URLstr = String.format(LOVELY_TIME_PICTURE_URL, hour, minutes); break;
case 10: URLstr = String.format(AVTOKEI_PICTURE_URL, hour, hour, minutes); break;
}
return URLstr;
}
private class FetchNextBeautyPictureTask extends AsyncTask<Void, Void, Integer> {
@Override
protected Integer doInBackground(Void... arg0) {
Log.w(TAG, "doInBackground:FetchNextBeautyPictureTask");
int ret = BCLW_FETCH_STATE_OTHER_FAILED;
mNextBeautyBitmap = null;
try {
String fpath = getPATH(mNextHour, mNextMinute);
File mFile = new File(fpath);
if (mFile.exists()) {
mNextBeautyBitmap = fetchBeautyPictureBitmapFromFile(fpath);
} else {
URL mURL = new URL(getURL(mNextHour, mNextMinute));
mNextBeautyBitmap = fetchBeautyPictureBitmapFromURL(mURL, mFile);
}
ret = BCLW_FETCH_STATE_SUCCESS;
} catch (FileNotFoundException e) {
e.printStackTrace();
ret = BCLW_FETCH_STATE_FILE_NOT_FOUND;
} catch (IOException e) {
e.printStackTrace();
ret = BCLW_FETCH_STATE_IO_ERROR;
if (cm != null) {
NetworkInfo ni = cm.getActiveNetworkInfo();
if (ni != null && ni.isConnected()) {
ret = BCLW_FETCH_STATE_TIMEOUT;
}
}
}
return ret;
}
protected void onPostExecute(Integer ret) {
Log.w(TAG, "onPostExecute:FetchNextBeautyPictureTask");
mFetchNextBeautyPictureTask = null;
if (ret == BCLW_FETCH_STATE_TIMEOUT) {
Log.w("BeautyClockUpdateService", "timeout, startToFetchNextBeautyPicture");
startToFetchNextBeautyPicture();
}
}
}
private void startToFetchNextBeautyPicture() {
try {
if (mFetchNextBeautyPictureTask == null) {
mFetchNextBeautyPictureTask = new FetchNextBeautyPictureTask();
}
mFetchNextBeautyPictureTask.execute();
} catch(RejectedExecutionException e) {
e.printStackTrace();
}
}
private class FetchCurrentBeautyPictureTask extends AsyncTask<Void, Void, Integer> {
@Override
protected Integer doInBackground(Void... arg0) {
Log.w(TAG, "doInBackground:FetchCurrentBeautyPictureTask");
int ret = BCLW_FETCH_STATE_OTHER_FAILED;
try {
String fpath = getPATH(mHour, mMinute);
File mFile = new File(fpath);
if (mFile.exists()) {
mCurrentBeautyBitmap = fetchBeautyPictureBitmapFromFile(fpath);
} else {
URL mURL = new URL(getURL(mHour, mMinute));
mCurrentBeautyBitmap = fetchBeautyPictureBitmapFromURL(mURL, mFile);
}
ret = BCLW_FETCH_STATE_SUCCESS;
} catch (FileNotFoundException e) {
e.printStackTrace();
ret = BCLW_FETCH_STATE_FILE_NOT_FOUND;
} catch (IOException e) {
e.printStackTrace();
ret = BCLW_FETCH_STATE_IO_ERROR;
if (cm != null) {
NetworkInfo ni = cm.getActiveNetworkInfo();
if (ni != null && ni.isConnected()) {
ret = BCLW_FETCH_STATE_TIMEOUT;
}
}
}
return ret;
}
protected void onPostExecute(Integer ret) {
Log.w(TAG, "onPostExecute:FetchCurrentBeautyPictureTask");
mFetchCurrentBeautyPictureTask = null;
if (mCurrentBeautyBitmap == null) {
if (ret == BCLW_FETCH_STATE_TIMEOUT) {
Log.w("BeautyClockUpdateService", "timeout, startToFetchCurrentBeautyPicture");
startToFetchCurrentBeautyPicture();
return;
}
} else {
Intent i = new Intent(BROADCAST_WALLPAPER_UPDATE);
sendBroadcast(i);
}
startToFetchNextBeautyPicture();
}
}
private void startToFetchCurrentBeautyPicture(){
try {
if (mFetchCurrentBeautyPictureTask == null) {
mFetchCurrentBeautyPictureTask = new FetchCurrentBeautyPictureTask();
}
mFetchCurrentBeautyPictureTask.execute();
} catch(RejectedExecutionException e) {
e.printStackTrace();
}
}
private class PlayBellTask extends AsyncTask<Void, Void, Void> {
@Override
protected Void doInBackground(Void... params) {
if (!mBellHourly) {
return null;
}
if (mMinute == 0) {
// check phone settings first, if it's in silent or vibration mode, don't play bell!
AudioManager am = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
if (am != null && (am.getRingerMode() == AudioManager.RINGER_MODE_SILENT ||
am.getRingerMode() == AudioManager.RINGER_MODE_VIBRATE)) {
Log.i(TAG, "Phone is in vibration mode or silent mode");
return null;
}
try {
MediaPlayer mp = new MediaPlayer();
mp.setDataSource(String.format(BELL_TO_PLAY, mHour));
mp.prepare();
mp.start();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
@Override
protected void onPostExecute(Void result) {
mPlayBellTask = null;
}
}
private void startToPlayBell() {
try {
if (mPlayBellTask == null) {
mPlayBellTask = new PlayBellTask();
}
mPlayBellTask.execute();
} catch(RejectedExecutionException e) {
e.printStackTrace();
}
}
private void configureHttpProxy() {
this.httpProxyHost = android.net.Proxy.getDefaultHost();
this.httpProxyPort = android.net.Proxy.getDefaultPort();
if (this.httpProxyHost != null && this.httpProxyPort != null) {
SocketAddress proxyAddress = new InetSocketAddress(this.httpProxyHost, this.httpProxyPort);
this.httpProxy = new Proxy(Proxy.Type.HTTP, proxyAddress);
} else {
this.httpProxy = Proxy.NO_PROXY;
}
}
private Bitmap fetchBeautyPictureBitmapFromFile(String fpath) {
try {
// Bitmap bitmap = BitmapFactory.decodeFile(fpath);
// return ResizeBitmap(bitmap);
return BitmapFactory.decodeFile(fpath);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
private Bitmap fetchBeautyPictureBitmapFromURL(URL url, File saveFile) throws IOException {
Bitmap bitmap = null;
InputStream in = null;
OutputStream out = null;
URLConnection urlc = null;
try {
if (cm != null) {
// network is turned off by user
if (!cm.getBackgroundDataSetting()) {
return null;
}
// network is not connected
NetworkInfo ni = cm.getActiveNetworkInfo();
if (ni != null && ni.getState() != NetworkInfo.State.CONNECTED) {
return null;
}
// if we're using WIFI, then there's no proxy from APN
if (ni != null && ni.getType() == ConnectivityManager.TYPE_WIFI) {
this.httpProxy = Proxy.NO_PROXY;
} else {
this.configureHttpProxy();
}
}
} catch (Exception e) {
}
try {
urlc = url.openConnection(this.httpProxy);
urlc.setRequestProperty("User-Agent", "Mozilla/5.0");
if (mPictureSource == 10) {
urlc.setRequestProperty("Referer", "http://www.avtokei.jp/index.html");
} else if (mPictureSource == 7) {
urlc.setRequestProperty("Referer", "http://www.bijint.com/binan/");
} else if (mPictureSource == 6) {
urlc.setRequestProperty("Referer", "http://www.bijint.com/cc/");
} else if (mPictureSource == 5) {
urlc.setRequestProperty("Referer", "http://gal.bijint.com/");
} else if (mPictureSource == 4) {
urlc.setRequestProperty("Referer", "http://www.bijint.com/hk/");
} else if (mPictureSource == 3) {
urlc.setRequestProperty("Referer", "http://www.bijint.com/kr/");
} else if (mPictureSource == 2) {
urlc.setRequestProperty("Referer", "http://www.bijint.com/jp/");
}
urlc.setReadTimeout(10000);
urlc.setConnectTimeout(10000);
in = new BufferedInputStream(urlc.getInputStream(), IO_BUFFER_SIZE);
final ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
out = new BufferedOutputStream(dataStream, IO_BUFFER_SIZE);
copy(in, out);
out.flush();
final byte[] data = dataStream.toByteArray();
bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
if (mSaveCopy && saveFile != null && !saveFile.exists()) {
saveCopy(bitmap, saveFile);
}
// Bitmap newbitmap = ResizeBitmap(bitmap);
// if (newbitmap != null) {
// bitmap = newbitmap;
// }
} finally {
closeStream(in);
closeStream(out);
}
return bitmap;
}
private static int copy(InputStream in, OutputStream out) throws IOException, SocketTimeoutException {
byte[] b = new byte[IO_BUFFER_SIZE];
int read, size = 0;
while ((read = in.read(b)) != -1) {
out.write(b, 0, read);
size += read;
}
return size;
}
private static void closeStream(Closeable stream) {
if (stream != null) {
try {
stream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
private boolean saveCopy(Bitmap bitmap, File new_file) {
if (bitmap == null || new_file == null) {
return false;
}
try {
// Try to create neccessary directory
new_file.mkdirs();
// output to tmp file
String fname_tmp = new_file.getAbsolutePath() + ".tmp";
FileOutputStream out = new FileOutputStream(fname_tmp);
bitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
out.flush();
out.close();
// if success, rename to correct file name
File tmp_file = new File(fname_tmp);
new_file.delete();
tmp_file.renameTo(new_file);
} catch (Exception e) {
e.printStackTrace();
return false;
}
return true;
}
private void update() {
try {
boolean reget = false;
if (mFetchCurrentBeautyPictureTask != null) {
mFetchCurrentBeautyPictureTask.cancel(true);
reget = true;
}
if (mFetchNextBeautyPictureTask != null) {
mFetchNextBeautyPictureTask.cancel(true);
reget = true;
}
if (reget) {
firstUpdate();
return;
}
if (mNextBeautyBitmap != null) {
mCurrentBeautyBitmap = mNextBeautyBitmap;
Intent i = new Intent(BROADCAST_WALLPAPER_UPDATE);
sendBroadcast(i);
}
mTime.setToNow();
updateTimeForNextUpdate();
startToFetchNextBeautyPicture();
} catch (Exception e) {
e.printStackTrace();
}
}
private final BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
Log.w(TAG, "onReceive");
if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) {
// Log.v(TAG, "Intent.ACTION_SCREEN_ON");
mIsScreenOn = true;
firstUpdate();
return;
} else if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
// Log.v(TAG, "Intent.ACTION_SCREEN_OFF");
mIsScreenOn = false;
}
if (intent.getAction().equals(Intent.ACTION_TIMEZONE_CHANGED)) {
String tz = intent.getStringExtra("time-zone");
mTime = new Time(TimeZone.getTimeZone(tz).getID());
if (mFetchCurrentBeautyPictureTask != null) {
mFetchCurrentBeautyPictureTask.cancel(true);
}
if (mFetchNextBeautyPictureTask != null) {
mFetchNextBeautyPictureTask.cancel(true);
}
firstUpdate();
return;
}
mTime.setToNow();
if (!(mHour == mTime.hour && mMinute == mTime.minute)) {
mHour = mTime.hour;
mMinute = mTime.minute;
if (!mFetchWhenScreenOff && !mIsScreenOn) {
updateTimeForNextUpdate();
startToPlayBell();
return;
}
update();
startToPlayBell();
}
}
};
private void updateTimeForNextUpdate() {
mNextHour = mTime.hour;
mNextMinute = mTime.minute;
if (mNextMinute == 59) {
mNextHour++;
if (mNextHour == 24) {
mNextHour = 0;
}
mNextMinute = -1;
}
mNextMinute++;
}
private void firstUpdate() {
mTime.setToNow();
mHour = mTime.hour;
mMinute = mTime.minute;
updateTimeForNextUpdate();
startToFetchCurrentBeautyPicture();
}
private void readDefaultPrefs(SharedPreferences prefs) {
if (prefs == null) {
return;
}
mFetchWhenScreenOff = prefs.getBoolean(Settings.PREF_FETCH_WHEN_SCREEN_OFF, true);
mBellHourly = prefs.getBoolean(Settings.PREF_RING_HOURLY, false);
mSaveCopy = prefs.getBoolean(Settings.PREF_SAVE_COPY, false);
mFitScreen = prefs.getBoolean(Settings.PREF_FIT_SCREEN, false);
mFetchLargerPicture = prefs.getBoolean(Settings.PREF_FETCH_LARGER_PICTURE, true);
mPictureSource = Integer.parseInt(prefs.getString(Settings.PREF_PICTURE_SOURCE, "0"));
}
@Override
public void onCreate() {
// read configuration
SharedPreferences mSharedPreferences = this.getSharedPreferences(Settings.SHARED_PREFS_NAME, 0);
readDefaultPrefs(mSharedPreferences);
// register notification
IntentFilter filter = new IntentFilter();
filter.addAction(Intent.ACTION_TIME_TICK);
filter.addAction(Intent.ACTION_TIME_CHANGED);
filter.addAction(Intent.ACTION_TIMEZONE_CHANGED);
filter.addAction(Intent.ACTION_SCREEN_ON);
filter.addAction(Intent.ACTION_SCREEN_OFF);
this.registerReceiver(mBroadcastReceiver, filter);
// get connection manager for checking network status
cm = (ConnectivityManager) this.getSystemService(Context.CONNECTIVITY_SERVICE);
// setup proxy
this.configureHttpProxy();
}
@Override
public void onStart(Intent intent, int startId) {
Log.w(TAG, "onStart");
onStartCommand(intent, 0, startId);
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.w(TAG, "onStartCommand");
firstUpdate();
return START_STICKY;
}
public void onDestroy() {
if (mPlayBellTask != null) {
mPlayBellTask.cancel(true);
}
if (mFetchCurrentBeautyPictureTask != null) {
mFetchCurrentBeautyPictureTask.cancel(true);
}
if (mFetchNextBeautyPictureTask != null) {
mFetchNextBeautyPictureTask.cancel(true);
}
this.unregisterReceiver(mBroadcastReceiver);
super.onDestroy();
}
@Override
public Engine onCreateEngine() {
return new BeautyClockEngine();
}
class BeautyClockEngine extends Engine implements SharedPreferences.OnSharedPreferenceChangeListener {
private static final int STATUS_BAR_HEIGHT = 38;
private int mScreenHeight = 0;
private int mScreenWidth = 0;
private int nXOffset = 0;
private SharedPreferences mPrefs;
private boolean bIsLarge = false;
private BroadcastReceiver mWallpaperUpdateBroadcastReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
draw();
}
};
BeautyClockEngine() {
mScreenHeight = getResources().getDisplayMetrics().heightPixels;
mScreenWidth = getResources().getDisplayMetrics().widthPixels;
mPrefs = BeautyClockLiveWallpaper.this.getSharedPreferences(Settings.SHARED_PREFS_NAME, 0);
mPrefs.registerOnSharedPreferenceChangeListener(this);
onSharedPreferenceChanged(mPrefs, null);
firstUpdate();
}
public void onSharedPreferenceChanged(SharedPreferences prefs, String key) {
if (prefs == null) {
return;
}
if (key == null) {
readDefaultPrefs(prefs);
return;
}
if (key.equals(Settings.PREF_FETCH_WHEN_SCREEN_OFF)) {
mFetchWhenScreenOff = prefs.getBoolean(Settings.PREF_FETCH_WHEN_SCREEN_OFF, true);
} else if (key.equals(Settings.PREF_RING_HOURLY)) {
mBellHourly = prefs.getBoolean(Settings.PREF_RING_HOURLY, false);
} else if (key.equals(Settings.PREF_SAVE_COPY)) {
mSaveCopy = prefs.getBoolean(Settings.PREF_SAVE_COPY, false);
} else if (key.equals(Settings.PREF_FIT_SCREEN)) {
mFitScreen = prefs.getBoolean(Settings.PREF_FIT_SCREEN, false);
draw();
} else if (key.equals(Settings.PREF_FETCH_LARGER_PICTURE)) {
mFetchLargerPicture = prefs.getBoolean(Settings.PREF_FETCH_LARGER_PICTURE, true);
firstUpdate();
} else if (key.equals(Settings.PREF_PICTURE_SOURCE)) {
mPictureSource = Integer.parseInt(prefs.getString(Settings.PREF_PICTURE_SOURCE, "0"));
firstUpdate();
}
}
/*
@Override
public void onSurfaceCreated(SurfaceHolder holder) {
Log.d(TAG, "onSurfaceCreated");
super.onSurfaceCreated(holder);
}
@Override
public int getDesiredMinimumHeight() {
Log.d(TAG, "getDesiredMinimumHeight");
return super.getDesiredMinimumHeight();
}
@Override
public int getDesiredMinimumWidth() {
Log.d(TAG, "getDesiredMinimumWidth");
return super.getDesiredMinimumWidth();
}
@Override
public SurfaceHolder getSurfaceHolder() {
Log.d(TAG, "getSurfaceHolder");
return super.getSurfaceHolder();
}
@Override
public boolean isPreview() {
Log.d(TAG, "isPreview");
return super.isPreview();
}
@Override
public boolean isVisible() {
Log.d(TAG, "isVisible");
return super.isVisible();
}
@Override
public Bundle onCommand(String action, int x, int y, int z,
Bundle extras, boolean resultRequested) {
Log.d(TAG, "onCommand");
return super.onCommand(action, x, y, z, extras, resultRequested);
}
@Override
public void onTouchEvent(MotionEvent event) {
Log.d(TAG, "onTouchEvent");
super.onTouchEvent(event);
}
@Override
public void setTouchEventsEnabled(boolean enabled) {
Log.d(TAG, "setTouchEventsEnabled:" + enabled);
super.setTouchEventsEnabled(enabled);
}
@Override
public void onDesiredSizeChanged(int desiredWidth, int desiredHeight) {
Log.d(TAG, "onDesiredSizeChanged");
super.onDesiredSizeChanged(desiredWidth, desiredHeight);
}
@Override
public void onSurfaceDestroyed(SurfaceHolder holder) {
Log.d(TAG, "onSurfaceDestroyed");
super.onSurfaceDestroyed(holder);
}
*/
@Override
public void onCreate(SurfaceHolder surfaceHolder) {
// Log.d(TAG, "onCreate (engine)");
super.onCreate(surfaceHolder);
setTouchEventsEnabled(false);
IntentFilter filter = new IntentFilter();
filter.addAction(BROADCAST_WALLPAPER_UPDATE);
BeautyClockLiveWallpaper.this.registerReceiver(mWallpaperUpdateBroadcastReceiver, filter);
}
@Override
public void onDestroy() {
// Log.d(TAG, "onDestroy (engine)");
super.onDestroy();
BeautyClockLiveWallpaper.this.unregisterReceiver(mWallpaperUpdateBroadcastReceiver);
}
@Override
public void onOffsetsChanged(float xOffset, float yOffset,
float xOffsetStep, float yOffsetStep, int xPixelOffset,
int yPixelOffset) {
// Log.d(TAG, "onOffsetsChanged");
// Log.d(TAG, "x:" + xPixelOffset + ", y:" + yPixelOffset);
nXOffset = xPixelOffset;
if (bIsLarge) {
draw();
}
}
@Override
public void onSurfaceChanged(SurfaceHolder holder, int format,
int width, int height) {
// Log.d(TAG, "onSurfaceChanged:" + width + "," + height);
mScreenHeight = height;
mScreenWidth = width;
draw();
}
@Override
public void onVisibilityChanged(boolean visible) {
// Log.d(TAG, "onVisibilityChanged:" + visible);
if (visible) {
draw();
}
}
private Bitmap ResizeBitmap(Bitmap bitmap) {
if (bitmap == null) {
return null;
}
int width = bitmap.getWidth();
int height = bitmap.getHeight();
if (width == 0 || height == 0) {
return null;
}
if (mScreenWidth > mScreenHeight) {
double ratio = (float) (mScreenHeight - STATUS_BAR_HEIGHT) / height;
width = (int) (width * ratio);
height = mScreenHeight - STATUS_BAR_HEIGHT;
} else {
if (height > width) {
if (mFitScreen) {
height = mScreenHeight - STATUS_BAR_HEIGHT;
} else {
double ratio = (float) mScreenWidth / width;
height = (int) (height * ratio);
}
width = mScreenWidth;
/*
double ratio = (float) (mScreenHeight - 60) / height;
height = mScreenHeight - 60;
width = (int) (width * ratio);
*/
} else {
if (mFitScreen) {
height = mScreenHeight - STATUS_BAR_HEIGHT;
} else {
double ratio = (float) mScreenWidth*2 / width;
height = (int) (height * ratio);
}
width = mScreenWidth*2;
}
}
// Log.w(TAG, "bitmap:"+ bitmap.getWidth() + "x" + bitmap.getHeight() + ":"+ bitmap.getDensity());
// Log.w(TAG, "bitmap:"+ bitmap.getWidth()*bitmap.getHeight());
Bitmap bitmapNew = Bitmap.createScaledBitmap(bitmap, width, height, true);
// Log.w(TAG,"scaled !!!!!!!!!!");
// Log.w(TAG,"bitmap:"+ bitmap.getWidth() + "x" + bitmap.getHeight() + ":"+ bitmap.getDensity());
// Log.w(TAG,"bitmap:"+ bitmap.getWidth()*bitmap.getHeight());
return bitmapNew;
}
private void drawBeautyClock(Canvas c, Bitmap bitmap_src) {
if (c == null || bitmap_src == null) {
return;
}
Bitmap bitmap_resized = ResizeBitmap(bitmap_src);
int width = bitmap_resized.getWidth();
int height = bitmap_resized.getHeight();
int Xpos = 0, Ypos = STATUS_BAR_HEIGHT;
// picture across virtual desktop, set scrolling
if (width > height) {
Xpos = nXOffset;
bIsLarge = true;
} else {
bIsLarge = false;
}
if (mScreenWidth > mScreenHeight) {
int offset = (int) (mScreenWidth * (bIsLarge ? 1.2 : 1) - width) / 2;
if (offset > 0) {
Xpos += offset;
}
} else {
if (!mFitScreen) {
int offset = (mScreenHeight - STATUS_BAR_HEIGHT - height) / 2;
if (offset > 0) {
Ypos += offset;
}
}
}
// clean before drawing
c.drawColor(Color.BLACK);
c.drawBitmap(bitmap_resized, Xpos, Ypos, null);
}
private void drawErrorScreen(Canvas c) {
// setup paint for drawing digitl clock
Paint paint = new Paint();
paint.setColor(Color.YELLOW);
paint.setAntiAlias(true);
paint.setStrokeCap(Paint.Cap.ROUND);
paint.setStyle(Paint.Style.STROKE);
paint.setStrokeWidth(5);
paint.setTextSize(120);
String time = String.format("%02d:%02d", mHour, mMinute);
c.drawColor(Color.BLACK);
c.drawText(time, mScreenWidth/2-150, mScreenHeight/2-30, paint);
/*
Paint paint = new Paint();
paint.setColor(Color.BLACK);
paint.setAntiAlias(true);
paint.setStrokeCap(Paint.Cap.ROUND);
paint.setStyle(Paint.Style.STROKE);
paint.setStrokeWidth(5);
paint.setTextSize(120);
if (mErrorBitmap == null) {
Drawable dw = getResources().getDrawable(R.drawable.beautyclock_retry);
mErrorBitmap = ResizeBitmap(((BitmapDrawable)dw).getBitmap());
}
c.drawBitmap(mErrorBitmap, 0, 15, paint);
String time = String.format("%02d:%02d", mHour, mMinute);
/c.drawText(time, mScreenWidth/2-150, 140, paint);
*/
}
private void draw() {
final SurfaceHolder holder = getSurfaceHolder();
Canvas c = null;
try {
c = holder.lockCanvas();
if (c != null) {
if (mCurrentBeautyBitmap != null) {
drawBeautyClock(c, mCurrentBeautyBitmap);
} else {
drawErrorScreen(c);
}
}
} finally {
if (c != null) {
holder.unlockCanvasAndPost(c);
}
}
}
}
} | [New Feature] Separate screen & timer broadcast receiver, may save battery.. / fix async task error
| src/com/corner23/android/beautyclocklivewallpaper/BeautyClockLiveWallpaper.java | [New Feature] Separate screen & timer broadcast receiver, may save battery.. / fix async task error | <ide><path>rc/com/corner23/android/beautyclocklivewallpaper/BeautyClockLiveWallpaper.java
<ide> private ConnectivityManager cm = null;
<ide>
<ide> private boolean mIsScreenOn = true;
<add> private boolean mRegScreenBR = false;
<add> private boolean mRegTimeBR = false;
<ide>
<ide> private String getPATH(int hour, int minutes) {
<ide> String URLstr = null;
<ide>
<ide> private void startToFetchNextBeautyPicture() {
<ide> try {
<del> if (mFetchNextBeautyPictureTask == null) {
<del> mFetchNextBeautyPictureTask = new FetchNextBeautyPictureTask();
<del> }
<add> if (mFetchNextBeautyPictureTask != null &&
<add> mFetchNextBeautyPictureTask.getStatus() == AsyncTask.Status.RUNNING) {
<add> mFetchNextBeautyPictureTask.cancel(true);
<add> }
<add>
<add> mFetchNextBeautyPictureTask = new FetchNextBeautyPictureTask();
<ide> mFetchNextBeautyPictureTask.execute();
<del> } catch(RejectedExecutionException e) {
<add> } catch (RejectedExecutionException e) {
<ide> e.printStackTrace();
<ide> }
<ide> }
<ide>
<ide> private void startToFetchCurrentBeautyPicture(){
<ide> try {
<del> if (mFetchCurrentBeautyPictureTask == null) {
<del> mFetchCurrentBeautyPictureTask = new FetchCurrentBeautyPictureTask();
<del> }
<add> if (mFetchCurrentBeautyPictureTask != null &&
<add> mFetchCurrentBeautyPictureTask.getStatus() == AsyncTask.Status.RUNNING) {
<add> mFetchCurrentBeautyPictureTask.cancel(true);
<add> }
<add>
<add> mFetchCurrentBeautyPictureTask = new FetchCurrentBeautyPictureTask();
<ide> mFetchCurrentBeautyPictureTask.execute();
<ide> } catch(RejectedExecutionException e) {
<ide> e.printStackTrace();
<ide>
<ide> private void startToPlayBell() {
<ide> try {
<del> if (mPlayBellTask == null) {
<del> mPlayBellTask = new PlayBellTask();
<del> }
<add> if (mPlayBellTask != null &&
<add> mPlayBellTask.getStatus() == AsyncTask.Status.RUNNING) {
<add> mPlayBellTask.cancel(true);
<add> }
<add>
<add> mPlayBellTask = new PlayBellTask();
<ide> mPlayBellTask.execute();
<ide> } catch(RejectedExecutionException e) {
<ide> e.printStackTrace();
<ide> }
<ide> }
<ide>
<del> private final BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
<add> private final BroadcastReceiver mScreenBroadcastReceiver = new BroadcastReceiver() {
<ide> @Override
<ide> public void onReceive(Context context, Intent intent) {
<del> Log.w(TAG, "onReceive");
<add> Log.w(TAG, "mScreenBroadcastReceiver:onReceive");
<ide> if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) {
<ide> // Log.v(TAG, "Intent.ACTION_SCREEN_ON");
<ide> mIsScreenOn = true;
<ide> firstUpdate();
<del> return;
<add> registerTimeBroadcastReceiver();
<ide> } else if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
<ide> // Log.v(TAG, "Intent.ACTION_SCREEN_OFF");
<ide> mIsScreenOn = false;
<add> unregisterTimeBroadcastReceiver();
<ide> }
<del>
<add> }
<add> };
<add>
<add> private final BroadcastReceiver mTimeBroadcastReceiver = new BroadcastReceiver() {
<add> @Override
<add> public void onReceive(Context context, Intent intent) {
<add> Log.w(TAG, "mTimeBroadcastReceiver:onReceive");
<ide> if (intent.getAction().equals(Intent.ACTION_TIMEZONE_CHANGED)) {
<ide> String tz = intent.getStringExtra("time-zone");
<ide> mTime = new Time(TimeZone.getTimeZone(tz).getID());
<ide> }
<ide> }
<ide> };
<del>
<add>
<ide> private void updateTimeForNextUpdate() {
<ide> mNextHour = mTime.hour;
<ide> mNextMinute = mTime.minute;
<ide> mPictureSource = Integer.parseInt(prefs.getString(Settings.PREF_PICTURE_SOURCE, "0"));
<ide> }
<ide>
<add> private void registerTimeBroadcastReceiver() {
<add> if (!mRegTimeBR) {
<add> IntentFilter filter = new IntentFilter();
<add> filter.addAction(Intent.ACTION_TIME_TICK);
<add> filter.addAction(Intent.ACTION_TIME_CHANGED);
<add> filter.addAction(Intent.ACTION_TIMEZONE_CHANGED);
<add> this.registerReceiver(mTimeBroadcastReceiver, filter);
<add> mRegTimeBR = true;
<add> }
<add> }
<add>
<add> private void unregisterTimeBroadcastReceiver() {
<add> if (mRegTimeBR) {
<add> this.unregisterReceiver(mTimeBroadcastReceiver);
<add> mRegTimeBR = false;
<add> }
<add> }
<add>
<add> private void registerScreenBroadcastReceiver() {
<add> if (!mRegScreenBR) {
<add> IntentFilter filter = new IntentFilter();
<add> filter.addAction(Intent.ACTION_SCREEN_ON);
<add> filter.addAction(Intent.ACTION_SCREEN_OFF);
<add> this.registerReceiver(mScreenBroadcastReceiver, filter);
<add> mRegScreenBR = true;
<add> }
<add> }
<add>
<add> private void unregisterScreenBroadcastReceiver() {
<add> if (mRegScreenBR) {
<add> this.unregisterReceiver(mScreenBroadcastReceiver);
<add> mRegScreenBR = false;
<add> }
<add> }
<add>
<ide> @Override
<ide> public void onCreate() {
<ide> // read configuration
<ide> readDefaultPrefs(mSharedPreferences);
<ide>
<ide> // register notification
<del> IntentFilter filter = new IntentFilter();
<del> filter.addAction(Intent.ACTION_TIME_TICK);
<del> filter.addAction(Intent.ACTION_TIME_CHANGED);
<del> filter.addAction(Intent.ACTION_TIMEZONE_CHANGED);
<del> filter.addAction(Intent.ACTION_SCREEN_ON);
<del> filter.addAction(Intent.ACTION_SCREEN_OFF);
<del> this.registerReceiver(mBroadcastReceiver, filter);
<add> registerTimeBroadcastReceiver();
<add> registerScreenBroadcastReceiver();
<ide>
<ide> // get connection manager for checking network status
<ide> cm = (ConnectivityManager) this.getSystemService(Context.CONNECTIVITY_SERVICE);
<ide> if (mFetchNextBeautyPictureTask != null) {
<ide> mFetchNextBeautyPictureTask.cancel(true);
<ide> }
<del> this.unregisterReceiver(mBroadcastReceiver);
<add> unregisterTimeBroadcastReceiver();
<add> unregisterScreenBroadcastReceiver();
<ide> super.onDestroy();
<ide> }
<ide>
<ide>
<ide> @Override
<ide> public void onVisibilityChanged(boolean visible) {
<del> // Log.d(TAG, "onVisibilityChanged:" + visible);
<add> Log.d(TAG, "onVisibilityChanged:" + visible);
<ide> if (visible) {
<add> mIsScreenOn = true;
<add> registerTimeBroadcastReceiver();
<ide> draw();
<add> } else {
<add> mIsScreenOn = false;
<add> unregisterTimeBroadcastReceiver();
<ide> }
<ide> }
<ide> |
|
Java | apache-2.0 | 4f1eb8d6dd3eb03fe67162f448334e7e61bf19ce | 0 | wido/cloudstack,DaanHoogland/cloudstack,jcshen007/cloudstack,wido/cloudstack,resmo/cloudstack,resmo/cloudstack,GabrielBrascher/cloudstack,resmo/cloudstack,GabrielBrascher/cloudstack,resmo/cloudstack,wido/cloudstack,GabrielBrascher/cloudstack,DaanHoogland/cloudstack,DaanHoogland/cloudstack,DaanHoogland/cloudstack,wido/cloudstack,jcshen007/cloudstack,DaanHoogland/cloudstack,GabrielBrascher/cloudstack,resmo/cloudstack,GabrielBrascher/cloudstack,jcshen007/cloudstack,GabrielBrascher/cloudstack,DaanHoogland/cloudstack,jcshen007/cloudstack,jcshen007/cloudstack,resmo/cloudstack,GabrielBrascher/cloudstack,jcshen007/cloudstack,jcshen007/cloudstack,DaanHoogland/cloudstack,wido/cloudstack,wido/cloudstack,wido/cloudstack,resmo/cloudstack | // Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
package com.cloud.host.dao;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TimeZone;
import javax.annotation.PostConstruct;
import javax.ejb.Local;
import javax.inject.Inject;
import javax.persistence.TableGenerator;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Component;
import com.cloud.agent.api.VgpuTypesInfo;
import com.cloud.cluster.agentlb.HostTransferMapVO;
import com.cloud.cluster.agentlb.dao.HostTransferMapDao;
import com.cloud.dc.ClusterVO;
import com.cloud.dc.dao.ClusterDao;
import com.cloud.gpu.dao.HostGpuGroupsDao;
import com.cloud.gpu.dao.VGPUTypesDao;
import com.cloud.host.Host;
import com.cloud.host.Host.Type;
import com.cloud.host.HostTagVO;
import com.cloud.host.HostVO;
import com.cloud.host.Status;
import com.cloud.host.Status.Event;
import com.cloud.info.RunningHostCountInfo;
import com.cloud.org.Managed;
import com.cloud.resource.ResourceState;
import com.cloud.utils.DateUtil;
import com.cloud.utils.db.Attribute;
import com.cloud.utils.db.DB;
import com.cloud.utils.db.Filter;
import com.cloud.utils.db.GenericDaoBase;
import com.cloud.utils.db.GenericSearchBuilder;
import com.cloud.utils.db.JoinBuilder;
import com.cloud.utils.db.JoinBuilder.JoinType;
import com.cloud.utils.db.SearchBuilder;
import com.cloud.utils.db.SearchCriteria;
import com.cloud.utils.db.SearchCriteria.Func;
import com.cloud.utils.db.SearchCriteria.Op;
import com.cloud.utils.db.TransactionLegacy;
import com.cloud.utils.db.UpdateBuilder;
import com.cloud.utils.exception.CloudRuntimeException;
@Component
@Local(value = {HostDao.class})
@DB
@TableGenerator(name = "host_req_sq", table = "op_host", pkColumnName = "id", valueColumnName = "sequence", allocationSize = 1)
public class HostDaoImpl extends GenericDaoBase<HostVO, Long> implements HostDao { //FIXME: , ExternalIdDao {
private static final Logger s_logger = Logger.getLogger(HostDaoImpl.class);
private static final Logger status_logger = Logger.getLogger(Status.class);
private static final Logger state_logger = Logger.getLogger(ResourceState.class);
protected SearchBuilder<HostVO> TypePodDcStatusSearch;
protected SearchBuilder<HostVO> IdStatusSearch;
protected SearchBuilder<HostVO> TypeDcSearch;
protected SearchBuilder<HostVO> TypeDcStatusSearch;
protected SearchBuilder<HostVO> TypeClusterStatusSearch;
protected SearchBuilder<HostVO> MsStatusSearch;
protected SearchBuilder<HostVO> DcPrivateIpAddressSearch;
protected SearchBuilder<HostVO> DcStorageIpAddressSearch;
protected SearchBuilder<HostVO> PublicIpAddressSearch;
protected SearchBuilder<HostVO> GuidSearch;
protected SearchBuilder<HostVO> DcSearch;
protected SearchBuilder<HostVO> PodSearch;
protected SearchBuilder<HostVO> ClusterSearch;
protected SearchBuilder<HostVO> TypeSearch;
protected SearchBuilder<HostVO> StatusSearch;
protected SearchBuilder<HostVO> ResourceStateSearch;
protected SearchBuilder<HostVO> NameLikeSearch;
protected SearchBuilder<HostVO> NameSearch;
protected SearchBuilder<HostVO> SequenceSearch;
protected SearchBuilder<HostVO> DirectlyConnectedSearch;
protected SearchBuilder<HostVO> UnmanagedDirectConnectSearch;
protected SearchBuilder<HostVO> UnmanagedApplianceSearch;
protected SearchBuilder<HostVO> MaintenanceCountSearch;
protected SearchBuilder<HostVO> ClusterStatusSearch;
protected SearchBuilder<HostVO> TypeNameZoneSearch;
protected SearchBuilder<HostVO> AvailHypevisorInZone;
protected SearchBuilder<HostVO> DirectConnectSearch;
protected SearchBuilder<HostVO> ManagedDirectConnectSearch;
protected SearchBuilder<HostVO> ManagedRoutingServersSearch;
protected SearchBuilder<HostVO> SecondaryStorageVMSearch;
protected GenericSearchBuilder<HostVO, Long> HostIdSearch;
protected GenericSearchBuilder<HostVO, Long> HostsInStatusSearch;
protected GenericSearchBuilder<HostVO, Long> CountRoutingByDc;
protected SearchBuilder<HostTransferMapVO> HostTransferSearch;
protected SearchBuilder<ClusterVO> ClusterManagedSearch;
protected SearchBuilder<HostVO> RoutingSearch;
protected SearchBuilder<HostVO> HostsForReconnectSearch;
protected GenericSearchBuilder<HostVO, Long> ClustersOwnedByMSSearch;
protected GenericSearchBuilder<HostVO, Long> ClustersForHostsNotOwnedByAnyMSSearch;
protected GenericSearchBuilder<ClusterVO, Long> AllClustersSearch;
protected SearchBuilder<HostVO> HostsInClusterSearch;
protected Attribute _statusAttr;
protected Attribute _resourceStateAttr;
protected Attribute _msIdAttr;
protected Attribute _pingTimeAttr;
@Inject
protected HostDetailsDao _detailsDao;
@Inject
protected HostGpuGroupsDao _hostGpuGroupsDao;
@Inject
protected VGPUTypesDao _vgpuTypesDao;
@Inject
protected HostTagsDao _hostTagsDao;
@Inject
protected HostTransferMapDao _hostTransferDao;
@Inject
protected ClusterDao _clusterDao;
public HostDaoImpl() {
super();
}
@PostConstruct
public void init() {
MaintenanceCountSearch = createSearchBuilder();
MaintenanceCountSearch.and("cluster", MaintenanceCountSearch.entity().getClusterId(), SearchCriteria.Op.EQ);
MaintenanceCountSearch.and("resourceState", MaintenanceCountSearch.entity().getResourceState(), SearchCriteria.Op.IN);
MaintenanceCountSearch.done();
TypePodDcStatusSearch = createSearchBuilder();
HostVO entity = TypePodDcStatusSearch.entity();
TypePodDcStatusSearch.and("type", entity.getType(), SearchCriteria.Op.EQ);
TypePodDcStatusSearch.and("pod", entity.getPodId(), SearchCriteria.Op.EQ);
TypePodDcStatusSearch.and("dc", entity.getDataCenterId(), SearchCriteria.Op.EQ);
TypePodDcStatusSearch.and("cluster", entity.getClusterId(), SearchCriteria.Op.EQ);
TypePodDcStatusSearch.and("status", entity.getStatus(), SearchCriteria.Op.EQ);
TypePodDcStatusSearch.and("resourceState", entity.getResourceState(), SearchCriteria.Op.EQ);
TypePodDcStatusSearch.done();
MsStatusSearch = createSearchBuilder();
MsStatusSearch.and("ms", MsStatusSearch.entity().getManagementServerId(), SearchCriteria.Op.EQ);
MsStatusSearch.and("type", MsStatusSearch.entity().getType(), SearchCriteria.Op.EQ);
MsStatusSearch.and("resourceState", MsStatusSearch.entity().getResourceState(), SearchCriteria.Op.NIN);
MsStatusSearch.done();
TypeDcSearch = createSearchBuilder();
TypeDcSearch.and("type", TypeDcSearch.entity().getType(), SearchCriteria.Op.EQ);
TypeDcSearch.and("dc", TypeDcSearch.entity().getDataCenterId(), SearchCriteria.Op.EQ);
TypeDcSearch.done();
SecondaryStorageVMSearch = createSearchBuilder();
SecondaryStorageVMSearch.and("type", SecondaryStorageVMSearch.entity().getType(), SearchCriteria.Op.EQ);
SecondaryStorageVMSearch.and("dc", SecondaryStorageVMSearch.entity().getDataCenterId(), SearchCriteria.Op.EQ);
SecondaryStorageVMSearch.and("status", SecondaryStorageVMSearch.entity().getStatus(), SearchCriteria.Op.EQ);
SecondaryStorageVMSearch.done();
TypeDcStatusSearch = createSearchBuilder();
TypeDcStatusSearch.and("type", TypeDcStatusSearch.entity().getType(), SearchCriteria.Op.EQ);
TypeDcStatusSearch.and("dc", TypeDcStatusSearch.entity().getDataCenterId(), SearchCriteria.Op.EQ);
TypeDcStatusSearch.and("status", TypeDcStatusSearch.entity().getStatus(), SearchCriteria.Op.EQ);
TypeDcStatusSearch.and("resourceState", TypeDcStatusSearch.entity().getResourceState(), SearchCriteria.Op.EQ);
TypeDcStatusSearch.done();
TypeClusterStatusSearch = createSearchBuilder();
TypeClusterStatusSearch.and("type", TypeClusterStatusSearch.entity().getType(), SearchCriteria.Op.EQ);
TypeClusterStatusSearch.and("cluster", TypeClusterStatusSearch.entity().getClusterId(), SearchCriteria.Op.EQ);
TypeClusterStatusSearch.and("status", TypeClusterStatusSearch.entity().getStatus(), SearchCriteria.Op.EQ);
TypeClusterStatusSearch.and("resourceState", TypeClusterStatusSearch.entity().getResourceState(), SearchCriteria.Op.EQ);
TypeClusterStatusSearch.done();
IdStatusSearch = createSearchBuilder();
IdStatusSearch.and("id", IdStatusSearch.entity().getId(), SearchCriteria.Op.EQ);
IdStatusSearch.and("states", IdStatusSearch.entity().getStatus(), SearchCriteria.Op.IN);
IdStatusSearch.done();
DcPrivateIpAddressSearch = createSearchBuilder();
DcPrivateIpAddressSearch.and("privateIpAddress", DcPrivateIpAddressSearch.entity().getPrivateIpAddress(), SearchCriteria.Op.EQ);
DcPrivateIpAddressSearch.and("dc", DcPrivateIpAddressSearch.entity().getDataCenterId(), SearchCriteria.Op.EQ);
DcPrivateIpAddressSearch.done();
DcStorageIpAddressSearch = createSearchBuilder();
DcStorageIpAddressSearch.and("storageIpAddress", DcStorageIpAddressSearch.entity().getStorageIpAddress(), SearchCriteria.Op.EQ);
DcStorageIpAddressSearch.and("dc", DcStorageIpAddressSearch.entity().getDataCenterId(), SearchCriteria.Op.EQ);
DcStorageIpAddressSearch.done();
PublicIpAddressSearch = createSearchBuilder();
PublicIpAddressSearch.and("publicIpAddress", PublicIpAddressSearch.entity().getPublicIpAddress(), SearchCriteria.Op.EQ);
PublicIpAddressSearch.done();
GuidSearch = createSearchBuilder();
GuidSearch.and("guid", GuidSearch.entity().getGuid(), SearchCriteria.Op.EQ);
GuidSearch.done();
DcSearch = createSearchBuilder();
DcSearch.and("dc", DcSearch.entity().getDataCenterId(), SearchCriteria.Op.EQ);
DcSearch.and("type", DcSearch.entity().getType(), Op.EQ);
DcSearch.and("status", DcSearch.entity().getStatus(), Op.EQ);
DcSearch.and("resourceState", DcSearch.entity().getResourceState(), Op.EQ);
DcSearch.done();
ClusterStatusSearch = createSearchBuilder();
ClusterStatusSearch.and("cluster", ClusterStatusSearch.entity().getClusterId(), SearchCriteria.Op.EQ);
ClusterStatusSearch.and("status", ClusterStatusSearch.entity().getStatus(), SearchCriteria.Op.EQ);
ClusterStatusSearch.done();
TypeNameZoneSearch = createSearchBuilder();
TypeNameZoneSearch.and("name", TypeNameZoneSearch.entity().getName(), SearchCriteria.Op.EQ);
TypeNameZoneSearch.and("type", TypeNameZoneSearch.entity().getType(), SearchCriteria.Op.EQ);
TypeNameZoneSearch.and("zoneId", TypeNameZoneSearch.entity().getDataCenterId(), SearchCriteria.Op.EQ);
TypeNameZoneSearch.done();
PodSearch = createSearchBuilder();
PodSearch.and("podId", PodSearch.entity().getPodId(), SearchCriteria.Op.EQ);
PodSearch.done();
ClusterSearch = createSearchBuilder();
ClusterSearch.and("clusterId", ClusterSearch.entity().getClusterId(), SearchCriteria.Op.EQ);
ClusterSearch.done();
TypeSearch = createSearchBuilder();
TypeSearch.and("type", TypeSearch.entity().getType(), SearchCriteria.Op.EQ);
TypeSearch.done();
StatusSearch = createSearchBuilder();
StatusSearch.and("status", StatusSearch.entity().getStatus(), SearchCriteria.Op.IN);
StatusSearch.done();
ResourceStateSearch = createSearchBuilder();
ResourceStateSearch.and("resourceState", ResourceStateSearch.entity().getResourceState(), SearchCriteria.Op.IN);
ResourceStateSearch.done();
NameLikeSearch = createSearchBuilder();
NameLikeSearch.and("name", NameLikeSearch.entity().getName(), SearchCriteria.Op.LIKE);
NameLikeSearch.done();
NameSearch = createSearchBuilder();
NameSearch.and("name", NameSearch.entity().getName(), SearchCriteria.Op.EQ);
NameSearch.done();
SequenceSearch = createSearchBuilder();
SequenceSearch.and("id", SequenceSearch.entity().getId(), SearchCriteria.Op.EQ);
// SequenceSearch.addRetrieve("sequence", SequenceSearch.entity().getSequence());
SequenceSearch.done();
DirectlyConnectedSearch = createSearchBuilder();
DirectlyConnectedSearch.and("resource", DirectlyConnectedSearch.entity().getResource(), SearchCriteria.Op.NNULL);
DirectlyConnectedSearch.and("ms", DirectlyConnectedSearch.entity().getManagementServerId(), SearchCriteria.Op.EQ);
DirectlyConnectedSearch.and("statuses", DirectlyConnectedSearch.entity().getStatus(), SearchCriteria.Op.EQ);
DirectlyConnectedSearch.and("resourceState", DirectlyConnectedSearch.entity().getResourceState(), SearchCriteria.Op.NOTIN);
DirectlyConnectedSearch.done();
UnmanagedDirectConnectSearch = createSearchBuilder();
UnmanagedDirectConnectSearch.and("resource", UnmanagedDirectConnectSearch.entity().getResource(), SearchCriteria.Op.NNULL);
UnmanagedDirectConnectSearch.and("server", UnmanagedDirectConnectSearch.entity().getManagementServerId(), SearchCriteria.Op.NULL);
UnmanagedDirectConnectSearch.and("lastPinged", UnmanagedDirectConnectSearch.entity().getLastPinged(), SearchCriteria.Op.LTEQ);
UnmanagedDirectConnectSearch.and("resourceStates", UnmanagedDirectConnectSearch.entity().getResourceState(), SearchCriteria.Op.NIN);
UnmanagedDirectConnectSearch.and("clusterIn", UnmanagedDirectConnectSearch.entity().getClusterId(), SearchCriteria.Op.IN);
/*
* UnmanagedDirectConnectSearch.op(SearchCriteria.Op.OR, "managementServerId",
* UnmanagedDirectConnectSearch.entity().getManagementServerId(), SearchCriteria.Op.EQ);
* UnmanagedDirectConnectSearch.and("lastPinged", UnmanagedDirectConnectSearch.entity().getLastPinged(),
* SearchCriteria.Op.LTEQ); UnmanagedDirectConnectSearch.cp(); UnmanagedDirectConnectSearch.cp();
*/
try {
HostTransferSearch = _hostTransferDao.createSearchBuilder();
} catch (Throwable e) {
s_logger.debug("error", e);
}
HostTransferSearch.and("id", HostTransferSearch.entity().getId(), SearchCriteria.Op.NULL);
UnmanagedDirectConnectSearch.join("hostTransferSearch", HostTransferSearch, HostTransferSearch.entity().getId(), UnmanagedDirectConnectSearch.entity().getId(),
JoinType.LEFTOUTER);
ClusterManagedSearch = _clusterDao.createSearchBuilder();
ClusterManagedSearch.and("managed", ClusterManagedSearch.entity().getManagedState(), SearchCriteria.Op.EQ);
UnmanagedDirectConnectSearch.join("ClusterManagedSearch", ClusterManagedSearch, ClusterManagedSearch.entity().getId(), UnmanagedDirectConnectSearch.entity()
.getClusterId(), JoinType.INNER);
UnmanagedDirectConnectSearch.done();
DirectConnectSearch = createSearchBuilder();
DirectConnectSearch.and("resource", DirectConnectSearch.entity().getResource(), SearchCriteria.Op.NNULL);
DirectConnectSearch.and("id", DirectConnectSearch.entity().getId(), SearchCriteria.Op.EQ);
DirectConnectSearch.and().op("nullserver", DirectConnectSearch.entity().getManagementServerId(), SearchCriteria.Op.NULL);
DirectConnectSearch.or("server", DirectConnectSearch.entity().getManagementServerId(), SearchCriteria.Op.EQ);
DirectConnectSearch.cp();
DirectConnectSearch.done();
UnmanagedApplianceSearch = createSearchBuilder();
UnmanagedApplianceSearch.and("resource", UnmanagedApplianceSearch.entity().getResource(), SearchCriteria.Op.NNULL);
UnmanagedApplianceSearch.and("server", UnmanagedApplianceSearch.entity().getManagementServerId(), SearchCriteria.Op.NULL);
UnmanagedApplianceSearch.and("types", UnmanagedApplianceSearch.entity().getType(), SearchCriteria.Op.IN);
UnmanagedApplianceSearch.and("lastPinged", UnmanagedApplianceSearch.entity().getLastPinged(), SearchCriteria.Op.LTEQ);
UnmanagedApplianceSearch.done();
AvailHypevisorInZone = createSearchBuilder();
AvailHypevisorInZone.and("zoneId", AvailHypevisorInZone.entity().getDataCenterId(), SearchCriteria.Op.EQ);
AvailHypevisorInZone.and("hostId", AvailHypevisorInZone.entity().getId(), SearchCriteria.Op.NEQ);
AvailHypevisorInZone.and("type", AvailHypevisorInZone.entity().getType(), SearchCriteria.Op.EQ);
AvailHypevisorInZone.groupBy(AvailHypevisorInZone.entity().getHypervisorType());
AvailHypevisorInZone.done();
HostsInStatusSearch = createSearchBuilder(Long.class);
HostsInStatusSearch.selectFields(HostsInStatusSearch.entity().getId());
HostsInStatusSearch.and("dc", HostsInStatusSearch.entity().getDataCenterId(), Op.EQ);
HostsInStatusSearch.and("pod", HostsInStatusSearch.entity().getPodId(), Op.EQ);
HostsInStatusSearch.and("cluster", HostsInStatusSearch.entity().getClusterId(), Op.EQ);
HostsInStatusSearch.and("type", HostsInStatusSearch.entity().getType(), Op.EQ);
HostsInStatusSearch.and("statuses", HostsInStatusSearch.entity().getStatus(), Op.IN);
HostsInStatusSearch.done();
CountRoutingByDc = createSearchBuilder(Long.class);
CountRoutingByDc.select(null, Func.COUNT, null);
CountRoutingByDc.and("dc", CountRoutingByDc.entity().getDataCenterId(), SearchCriteria.Op.EQ);
CountRoutingByDc.and("type", CountRoutingByDc.entity().getType(), SearchCriteria.Op.EQ);
CountRoutingByDc.and("status", CountRoutingByDc.entity().getStatus(), SearchCriteria.Op.EQ);
CountRoutingByDc.done();
ManagedDirectConnectSearch = createSearchBuilder();
ManagedDirectConnectSearch.and("resource", ManagedDirectConnectSearch.entity().getResource(), SearchCriteria.Op.NNULL);
ManagedDirectConnectSearch.and("server", ManagedDirectConnectSearch.entity().getManagementServerId(), SearchCriteria.Op.NULL);
ManagedDirectConnectSearch.done();
ManagedRoutingServersSearch = createSearchBuilder();
ManagedRoutingServersSearch.and("server", ManagedRoutingServersSearch.entity().getManagementServerId(), SearchCriteria.Op.NNULL);
ManagedRoutingServersSearch.and("type", ManagedRoutingServersSearch.entity().getType(), SearchCriteria.Op.EQ);
ManagedRoutingServersSearch.done();
RoutingSearch = createSearchBuilder();
RoutingSearch.and("type", RoutingSearch.entity().getType(), SearchCriteria.Op.EQ);
RoutingSearch.done();
HostsForReconnectSearch = createSearchBuilder();
HostsForReconnectSearch.and("resource", HostsForReconnectSearch.entity().getResource(), SearchCriteria.Op.NNULL);
HostsForReconnectSearch.and("server", HostsForReconnectSearch.entity().getManagementServerId(), SearchCriteria.Op.EQ);
HostsForReconnectSearch.and("lastPinged", HostsForReconnectSearch.entity().getLastPinged(), SearchCriteria.Op.LTEQ);
HostsForReconnectSearch.and("resourceStates", HostsForReconnectSearch.entity().getResourceState(), SearchCriteria.Op.NIN);
HostsForReconnectSearch.and("cluster", HostsForReconnectSearch.entity().getClusterId(), SearchCriteria.Op.NNULL);
HostsForReconnectSearch.and("status", HostsForReconnectSearch.entity().getStatus(), SearchCriteria.Op.IN);
HostsForReconnectSearch.done();
ClustersOwnedByMSSearch = createSearchBuilder(Long.class);
ClustersOwnedByMSSearch.select(null, Func.DISTINCT, ClustersOwnedByMSSearch.entity().getClusterId());
ClustersOwnedByMSSearch.and("resource", ClustersOwnedByMSSearch.entity().getResource(), SearchCriteria.Op.NNULL);
ClustersOwnedByMSSearch.and("cluster", ClustersOwnedByMSSearch.entity().getClusterId(), SearchCriteria.Op.NNULL);
ClustersOwnedByMSSearch.and("server", ClustersOwnedByMSSearch.entity().getManagementServerId(), SearchCriteria.Op.EQ);
ClustersOwnedByMSSearch.done();
ClustersForHostsNotOwnedByAnyMSSearch = createSearchBuilder(Long.class);
ClustersForHostsNotOwnedByAnyMSSearch.select(null, Func.DISTINCT, ClustersForHostsNotOwnedByAnyMSSearch.entity().getClusterId());
ClustersForHostsNotOwnedByAnyMSSearch.and("resource", ClustersForHostsNotOwnedByAnyMSSearch.entity().getResource(), SearchCriteria.Op.NNULL);
ClustersForHostsNotOwnedByAnyMSSearch.and("cluster", ClustersForHostsNotOwnedByAnyMSSearch.entity().getClusterId(), SearchCriteria.Op.NNULL);
ClustersForHostsNotOwnedByAnyMSSearch.and("server", ClustersForHostsNotOwnedByAnyMSSearch.entity().getManagementServerId(), SearchCriteria.Op.NULL);
ClustersForHostsNotOwnedByAnyMSSearch.done();
AllClustersSearch = _clusterDao.createSearchBuilder(Long.class);
AllClustersSearch.select(null, Func.NATIVE, AllClustersSearch.entity().getId());
AllClustersSearch.and("managed", AllClustersSearch.entity().getManagedState(), SearchCriteria.Op.EQ);
AllClustersSearch.done();
HostsInClusterSearch = createSearchBuilder();
HostsInClusterSearch.and("resource", HostsInClusterSearch.entity().getResource(), SearchCriteria.Op.NNULL);
HostsInClusterSearch.and("cluster", HostsInClusterSearch.entity().getClusterId(), SearchCriteria.Op.EQ);
HostsInClusterSearch.and("server", HostsInClusterSearch.entity().getManagementServerId(), SearchCriteria.Op.NNULL);
HostsInClusterSearch.done();
HostIdSearch = createSearchBuilder(Long.class);
HostIdSearch.selectFields(HostIdSearch.entity().getId());
HostIdSearch.and("dataCenterId", HostIdSearch.entity().getDataCenterId(), Op.EQ);
HostIdSearch.done();
_statusAttr = _allAttributes.get("status");
_msIdAttr = _allAttributes.get("managementServerId");
_pingTimeAttr = _allAttributes.get("lastPinged");
_resourceStateAttr = _allAttributes.get("resourceState");
assert (_statusAttr != null && _msIdAttr != null && _pingTimeAttr != null) : "Couldn't find one of these attributes";
}
@Override
public long countBy(long clusterId, ResourceState... states) {
SearchCriteria<HostVO> sc = MaintenanceCountSearch.create();
sc.setParameters("resourceState", (Object[])states);
sc.setParameters("cluster", clusterId);
List<HostVO> hosts = listBy(sc);
return hosts.size();
}
@Override
public List<HostVO> listByDataCenterId(long id) {
SearchCriteria<HostVO> sc = DcSearch.create();
sc.setParameters("dc", id);
sc.setParameters("status", Status.Up);
sc.setParameters("type", Host.Type.Routing);
sc.setParameters("resourceState", ResourceState.Enabled);
return listBy(sc);
}
@Override
public HostVO findByGuid(String guid) {
SearchCriteria<HostVO> sc = GuidSearch.create("guid", guid);
return findOneBy(sc);
}
/*
* Find hosts which is in Disconnected, Down, Alert and ping timeout and server is not null, set server to null
*/
private void resetHosts(long managementServerId, long lastPingSecondsAfter) {
SearchCriteria<HostVO> sc = HostsForReconnectSearch.create();
sc.setParameters("server", managementServerId);
sc.setParameters("lastPinged", lastPingSecondsAfter);
sc.setParameters("status", Status.Disconnected, Status.Down, Status.Alert);
StringBuilder sb = new StringBuilder();
List<HostVO> hosts = lockRows(sc, null, true); // exclusive lock
for (HostVO host : hosts) {
host.setManagementServerId(null);
update(host.getId(), host);
sb.append(host.getId());
sb.append(" ");
}
if (s_logger.isTraceEnabled()) {
s_logger.trace("Following hosts got reset: " + sb.toString());
}
}
/*
* Returns a list of cluster owned by @managementServerId
*/
private List<Long> findClustersOwnedByManagementServer(long managementServerId) {
SearchCriteria<Long> sc = ClustersOwnedByMSSearch.create();
sc.setParameters("server", managementServerId);
List<Long> clusters = customSearch(sc, null);
return clusters;
}
/*
* Returns clusters based on the list of hosts not owned by any MS
*/
private List<Long> findClustersForHostsNotOwnedByAnyManagementServer() {
SearchCriteria<Long> sc = ClustersForHostsNotOwnedByAnyMSSearch.create();
List<Long> clusters = customSearch(sc, null);
return clusters;
}
/*
* Returns a list of all cluster Ids
*/
private List<Long> listAllClusters() {
SearchCriteria<Long> sc = AllClustersSearch.create();
sc.setParameters("managed", Managed.ManagedState.Managed);
List<Long> clusters = _clusterDao.customSearch(sc, null);
return clusters;
}
/*
* This determines if hosts belonging to cluster(@clusterId) are up for grabs
*
* This is used for handling following cases:
* 1. First host added in cluster
* 2. During MS restart all hosts in a cluster are without any MS
*/
private boolean canOwnCluster(long clusterId) {
SearchCriteria<HostVO> sc = HostsInClusterSearch.create();
sc.setParameters("cluster", clusterId);
List<HostVO> hosts = search(sc, null);
boolean ownCluster = (hosts == null || hosts.size() == 0);
return ownCluster;
}
@Override
@DB
public List<HostVO> findAndUpdateDirectAgentToLoad(long lastPingSecondsAfter, Long limit, long managementServerId) {
TransactionLegacy txn = TransactionLegacy.currentTxn();
txn.start();
if (s_logger.isDebugEnabled()) {
s_logger.debug("Resetting hosts suitable for reconnect");
}
// reset hosts that are suitable candidates for reconnect
resetHosts(managementServerId, lastPingSecondsAfter);
if (s_logger.isDebugEnabled()) {
s_logger.debug("Completed resetting hosts suitable for reconnect");
}
List<HostVO> assignedHosts = new ArrayList<HostVO>();
if (s_logger.isDebugEnabled()) {
s_logger.debug("Acquiring hosts for clusters already owned by this management server");
}
List<Long> clusters = findClustersOwnedByManagementServer(managementServerId);
if (clusters.size() > 0) {
// handle clusters already owned by @managementServerId
SearchCriteria<HostVO> sc = UnmanagedDirectConnectSearch.create();
sc.setParameters("lastPinged", lastPingSecondsAfter);
sc.setJoinParameters("ClusterManagedSearch", "managed", Managed.ManagedState.Managed);
sc.setParameters("clusterIn", clusters.toArray());
List<HostVO> unmanagedHosts = lockRows(sc, new Filter(HostVO.class, "clusterId", true, 0L, limit), true); // host belongs to clusters owned by @managementServerId
StringBuilder sb = new StringBuilder();
for (HostVO host : unmanagedHosts) {
host.setManagementServerId(managementServerId);
update(host.getId(), host);
assignedHosts.add(host);
sb.append(host.getId());
sb.append(" ");
}
if (s_logger.isTraceEnabled()) {
s_logger.trace("Following hosts got acquired for clusters already owned: " + sb.toString());
}
}
if (s_logger.isDebugEnabled()) {
s_logger.debug("Completed acquiring hosts for clusters already owned by this management server");
}
if (assignedHosts.size() < limit) {
if (s_logger.isDebugEnabled()) {
s_logger.debug("Acquiring hosts for clusters not owned by any management server");
}
// for remaining hosts not owned by any MS check if they can be owned (by owning full cluster)
clusters = findClustersForHostsNotOwnedByAnyManagementServer();
List<Long> updatedClusters = clusters;
if (clusters.size() > limit) {
updatedClusters = clusters.subList(0, limit.intValue());
}
if (updatedClusters.size() > 0) {
SearchCriteria<HostVO> sc = UnmanagedDirectConnectSearch.create();
sc.setParameters("lastPinged", lastPingSecondsAfter);
sc.setJoinParameters("ClusterManagedSearch", "managed", Managed.ManagedState.Managed);
sc.setParameters("clusterIn", updatedClusters.toArray());
List<HostVO> unmanagedHosts = lockRows(sc, null, true);
// group hosts based on cluster
Map<Long, List<HostVO>> hostMap = new HashMap<Long, List<HostVO>>();
for (HostVO host : unmanagedHosts) {
if (hostMap.get(host.getClusterId()) == null) {
hostMap.put(host.getClusterId(), new ArrayList<HostVO>());
}
hostMap.get(host.getClusterId()).add(host);
}
StringBuilder sb = new StringBuilder();
for (Long clusterId : hostMap.keySet()) {
if (canOwnCluster(clusterId)) { // cluster is not owned by any other MS, so @managementServerId can own it
List<HostVO> hostList = hostMap.get(clusterId);
for (HostVO host : hostList) {
host.setManagementServerId(managementServerId);
update(host.getId(), host);
assignedHosts.add(host);
sb.append(host.getId());
sb.append(" ");
}
}
if (assignedHosts.size() > limit) {
break;
}
}
if (s_logger.isTraceEnabled()) {
s_logger.trace("Following hosts got acquired from newly owned clusters: " + sb.toString());
}
}
if (s_logger.isDebugEnabled()) {
s_logger.debug("Completed acquiring hosts for clusters not owned by any management server");
}
}
txn.commit();
return assignedHosts;
}
@Override
@DB
public List<HostVO> findAndUpdateApplianceToLoad(long lastPingSecondsAfter, long managementServerId) {
TransactionLegacy txn = TransactionLegacy.currentTxn();
txn.start();
SearchCriteria<HostVO> sc = UnmanagedApplianceSearch.create();
sc.setParameters("lastPinged", lastPingSecondsAfter);
sc.setParameters("types", Type.ExternalDhcp, Type.ExternalFirewall, Type.ExternalLoadBalancer, Type.BaremetalDhcp, Type.BaremetalPxe, Type.TrafficMonitor,
Type.L2Networking);
List<HostVO> hosts = lockRows(sc, null, true);
for (HostVO host : hosts) {
host.setManagementServerId(managementServerId);
update(host.getId(), host);
}
txn.commit();
return hosts;
}
@Override
public void markHostsAsDisconnected(long msId, long lastPing) {
SearchCriteria<HostVO> sc = MsStatusSearch.create();
sc.setParameters("ms", msId);
HostVO host = createForUpdate();
host.setLastPinged(lastPing);
host.setDisconnectedOn(new Date());
UpdateBuilder ub = getUpdateBuilder(host);
ub.set(host, "status", Status.Disconnected);
update(ub, sc, null);
sc = MsStatusSearch.create();
sc.setParameters("ms", msId);
host = createForUpdate();
host.setManagementServerId(null);
host.setLastPinged(lastPing);
host.setDisconnectedOn(new Date());
ub = getUpdateBuilder(host);
update(ub, sc, null);
}
@Override
public List<HostVO> listByHostTag(Host.Type type, Long clusterId, Long podId, long dcId, String hostTag) {
SearchBuilder<HostTagVO> hostTagSearch = _hostTagsDao.createSearchBuilder();
HostTagVO tagEntity = hostTagSearch.entity();
hostTagSearch.and("tag", tagEntity.getTag(), SearchCriteria.Op.EQ);
SearchBuilder<HostVO> hostSearch = createSearchBuilder();
HostVO entity = hostSearch.entity();
hostSearch.and("type", entity.getType(), SearchCriteria.Op.EQ);
hostSearch.and("pod", entity.getPodId(), SearchCriteria.Op.EQ);
hostSearch.and("dc", entity.getDataCenterId(), SearchCriteria.Op.EQ);
hostSearch.and("cluster", entity.getClusterId(), SearchCriteria.Op.EQ);
hostSearch.and("status", entity.getStatus(), SearchCriteria.Op.EQ);
hostSearch.and("resourceState", entity.getResourceState(), SearchCriteria.Op.EQ);
hostSearch.join("hostTagSearch", hostTagSearch, entity.getId(), tagEntity.getHostId(), JoinBuilder.JoinType.INNER);
SearchCriteria<HostVO> sc = hostSearch.create();
sc.setJoinParameters("hostTagSearch", "tag", hostTag);
sc.setParameters("type", type.toString());
if (podId != null) {
sc.setParameters("pod", podId);
}
if (clusterId != null) {
sc.setParameters("cluster", clusterId);
}
sc.setParameters("dc", dcId);
sc.setParameters("status", Status.Up.toString());
sc.setParameters("resourceState", ResourceState.Enabled.toString());
return listBy(sc);
}
@Override
public List<HostVO> listAllUpAndEnabledNonHAHosts(Type type, Long clusterId, Long podId, long dcId, String haTag) {
SearchBuilder<HostTagVO> hostTagSearch = null;
if (haTag != null && !haTag.isEmpty()) {
hostTagSearch = _hostTagsDao.createSearchBuilder();
hostTagSearch.and().op("tag", hostTagSearch.entity().getTag(), SearchCriteria.Op.NEQ);
hostTagSearch.or("tagNull", hostTagSearch.entity().getTag(), SearchCriteria.Op.NULL);
hostTagSearch.cp();
}
SearchBuilder<HostVO> hostSearch = createSearchBuilder();
hostSearch.and("type", hostSearch.entity().getType(), SearchCriteria.Op.EQ);
hostSearch.and("clusterId", hostSearch.entity().getClusterId(), SearchCriteria.Op.EQ);
hostSearch.and("podId", hostSearch.entity().getPodId(), SearchCriteria.Op.EQ);
hostSearch.and("zoneId", hostSearch.entity().getDataCenterId(), SearchCriteria.Op.EQ);
hostSearch.and("status", hostSearch.entity().getStatus(), SearchCriteria.Op.EQ);
hostSearch.and("resourceState", hostSearch.entity().getResourceState(), SearchCriteria.Op.EQ);
if (haTag != null && !haTag.isEmpty()) {
hostSearch.join("hostTagSearch", hostTagSearch, hostSearch.entity().getId(), hostTagSearch.entity().getHostId(), JoinBuilder.JoinType.LEFTOUTER);
}
SearchCriteria<HostVO> sc = hostSearch.create();
if (haTag != null && !haTag.isEmpty()) {
sc.setJoinParameters("hostTagSearch", "tag", haTag);
}
if (type != null) {
sc.setParameters("type", type);
}
if (clusterId != null) {
sc.setParameters("clusterId", clusterId);
}
if (podId != null) {
sc.setParameters("podId", podId);
}
sc.setParameters("zoneId", dcId);
sc.setParameters("status", Status.Up);
sc.setParameters("resourceState", ResourceState.Enabled);
return listBy(sc);
}
@Override
public void loadDetails(HostVO host) {
Map<String, String> details = _detailsDao.findDetails(host.getId());
host.setDetails(details);
}
@Override
public void loadHostTags(HostVO host) {
List<String> hostTags = _hostTagsDao.gethostTags(host.getId());
host.setHostTags(hostTags);
}
@DB
@Override
public List<HostVO> findLostHosts(long timeout) {
List<HostVO> result = new ArrayList<HostVO>();
String sql =
"select h.id from host h left join cluster c on h.cluster_id=c.id where h.mgmt_server_id is not null and h.last_ping < ? and h.status in ('Up', 'Updating', 'Disconnected', 'Connecting') and h.type not in ('ExternalFirewall', 'ExternalLoadBalancer', 'TrafficMonitor', 'SecondaryStorage', 'LocalSecondaryStorage', 'L2Networking') and (h.cluster_id is null or c.managed_state = 'Managed') ;";
try (
TransactionLegacy txn = TransactionLegacy.currentTxn();
PreparedStatement pstmt = txn.prepareStatement(sql);) {
pstmt.setLong(1, timeout);
try (ResultSet rs = pstmt.executeQuery();) {
while (rs.next()) {
long id = rs.getLong(1); //ID column
result.add(findById(id));
}
}
} catch (SQLException e) {
s_logger.warn("Exception: ", e);
}
return result;
}
@Override
public void saveDetails(HostVO host) {
Map<String, String> details = host.getDetails();
if (details == null) {
return;
}
_detailsDao.persist(host.getId(), details);
}
protected void saveHostTags(HostVO host) {
List<String> hostTags = host.getHostTags();
if (hostTags == null || (hostTags != null && hostTags.isEmpty())) {
return;
}
_hostTagsDao.persist(host.getId(), hostTags);
}
protected void saveGpuRecords(HostVO host) {
HashMap<String, HashMap<String, VgpuTypesInfo>> groupDetails = host.getGpuGroupDetails();
if (groupDetails != null) {
// Create/Update GPU group entries
_hostGpuGroupsDao.persist(host.getId(), new ArrayList<String>(groupDetails.keySet()));
// Create/Update VGPU types entries
_vgpuTypesDao.persist(host.getId(), groupDetails);
}
}
@Override
@DB
public HostVO persist(HostVO host) {
final String InsertSequenceSql = "INSERT INTO op_host(id) VALUES(?)";
TransactionLegacy txn = TransactionLegacy.currentTxn();
txn.start();
HostVO dbHost = super.persist(host);
try {
PreparedStatement pstmt = txn.prepareAutoCloseStatement(InsertSequenceSql);
pstmt.setLong(1, dbHost.getId());
pstmt.executeUpdate();
} catch (SQLException e) {
throw new CloudRuntimeException("Unable to persist the sequence number for this host");
}
saveDetails(host);
loadDetails(dbHost);
saveHostTags(host);
loadHostTags(dbHost);
saveGpuRecords(host);
txn.commit();
return dbHost;
}
@Override
@DB
public boolean update(Long hostId, HostVO host) {
TransactionLegacy txn = TransactionLegacy.currentTxn();
txn.start();
boolean persisted = super.update(hostId, host);
if (!persisted) {
return persisted;
}
saveDetails(host);
saveHostTags(host);
saveGpuRecords(host);
txn.commit();
return persisted;
}
@Override
@DB
public List<RunningHostCountInfo> getRunningHostCounts(Date cutTime) {
String sql =
"select * from (" + "select h.data_center_id, h.type, count(*) as count from host as h INNER JOIN mshost as m ON h.mgmt_server_id=m.msid "
+ "where h.status='Up' and h.type='SecondaryStorage' and m.last_update > ? " + "group by h.data_center_id, h.type " + "UNION ALL "
+ "select h.data_center_id, h.type, count(*) as count from host as h INNER JOIN mshost as m ON h.mgmt_server_id=m.msid "
+ "where h.status='Up' and h.type='Routing' and m.last_update > ? " + "group by h.data_center_id, h.type) as t " + "ORDER by t.data_center_id, t.type";
ArrayList<RunningHostCountInfo> l = new ArrayList<RunningHostCountInfo>();
TransactionLegacy txn = TransactionLegacy.currentTxn();
;
PreparedStatement pstmt = null;
try {
pstmt = txn.prepareAutoCloseStatement(sql);
String gmtCutTime = DateUtil.getDateDisplayString(TimeZone.getTimeZone("GMT"), cutTime);
pstmt.setString(1, gmtCutTime);
pstmt.setString(2, gmtCutTime);
ResultSet rs = pstmt.executeQuery();
while (rs.next()) {
RunningHostCountInfo info = new RunningHostCountInfo();
info.setDcId(rs.getLong(1));
info.setHostType(rs.getString(2));
info.setCount(rs.getInt(3));
l.add(info);
}
} catch (SQLException e) {
s_logger.debug("SQLException caught", e);
}
return l;
}
@Override
public long getNextSequence(long hostId) {
if (s_logger.isTraceEnabled()) {
s_logger.trace("getNextSequence(), hostId: " + hostId);
}
TableGenerator tg = _tgs.get("host_req_sq");
assert tg != null : "how can this be wrong!";
return s_seqFetcher.getNextSequence(Long.class, tg, hostId);
}
/*TODO: this is used by mycloud, check if it needs resource state Enabled */
@Override
public long countRoutingHostsByDataCenter(long dcId) {
SearchCriteria<Long> sc = CountRoutingByDc.create();
sc.setParameters("dc", dcId);
sc.setParameters("type", Host.Type.Routing);
sc.setParameters("status", Status.Up.toString());
return customSearch(sc, null).get(0);
}
@Override
public boolean updateState(Status oldStatus, Event event, Status newStatus, Host vo, Object data) {
// lock target row from beginning to avoid lock-promotion caused deadlock
HostVO host = lockRow(vo.getId(), true);
if (host == null) {
if (event == Event.Remove && newStatus == Status.Removed) {
host = findByIdIncludingRemoved(vo.getId());
}
}
if (host == null) {
return false;
}
long oldPingTime = host.getLastPinged();
SearchBuilder<HostVO> sb = createSearchBuilder();
sb.and("status", sb.entity().getStatus(), SearchCriteria.Op.EQ);
sb.and("id", sb.entity().getId(), SearchCriteria.Op.EQ);
sb.and("update", sb.entity().getUpdated(), SearchCriteria.Op.EQ);
if (newStatus.checkManagementServer()) {
sb.and("ping", sb.entity().getLastPinged(), SearchCriteria.Op.EQ);
sb.and().op("nullmsid", sb.entity().getManagementServerId(), SearchCriteria.Op.NULL);
sb.or("msid", sb.entity().getManagementServerId(), SearchCriteria.Op.EQ);
sb.cp();
}
sb.done();
SearchCriteria<HostVO> sc = sb.create();
sc.setParameters("status", oldStatus);
sc.setParameters("id", host.getId());
sc.setParameters("update", host.getUpdated());
long oldUpdateCount = host.getUpdated();
if (newStatus.checkManagementServer()) {
sc.setParameters("ping", oldPingTime);
sc.setParameters("msid", host.getManagementServerId());
}
long newUpdateCount = host.incrUpdated();
UpdateBuilder ub = getUpdateBuilder(host);
ub.set(host, _statusAttr, newStatus);
if (newStatus.updateManagementServer()) {
if (newStatus.lostConnection()) {
ub.set(host, _msIdAttr, null);
} else {
ub.set(host, _msIdAttr, host.getManagementServerId());
}
if (event.equals(Event.Ping) || event.equals(Event.AgentConnected)) {
ub.set(host, _pingTimeAttr, System.currentTimeMillis() >> 10);
}
}
if (event.equals(Event.ManagementServerDown)) {
ub.set(host, _pingTimeAttr, ((System.currentTimeMillis() >> 10) - (10 * 60)));
}
int result = update(ub, sc, null);
assert result <= 1 : "How can this update " + result + " rows? ";
if (result == 0) {
HostVO ho = findById(host.getId());
assert ho != null : "How how how? : " + host.getId();
if (status_logger.isDebugEnabled()) {
StringBuilder str = new StringBuilder("Unable to update host for event:").append(event.toString());
str.append(". Name=").append(host.getName());
str.append("; New=[status=")
.append(newStatus.toString())
.append(":msid=")
.append(newStatus.lostConnection() ? "null" : host.getManagementServerId())
.append(":lastpinged=")
.append(host.getLastPinged())
.append("]");
str.append("; Old=[status=").append(oldStatus.toString()).append(":msid=").append(host.getManagementServerId()).append(":lastpinged=").append(oldPingTime)
.append("]");
str.append("; DB=[status=")
.append(vo.getStatus().toString())
.append(":msid=")
.append(vo.getManagementServerId())
.append(":lastpinged=")
.append(vo.getLastPinged())
.append(":old update count=")
.append(oldUpdateCount)
.append("]");
status_logger.debug(str.toString());
} else {
StringBuilder msg = new StringBuilder("Agent status update: [");
msg.append("id = " + host.getId());
msg.append("; name = " + host.getName());
msg.append("; old status = " + oldStatus);
msg.append("; event = " + event);
msg.append("; new status = " + newStatus);
msg.append("; old update count = " + oldUpdateCount);
msg.append("; new update count = " + newUpdateCount + "]");
status_logger.debug(msg.toString());
}
if (ho.getState() == newStatus) {
status_logger.debug("Host " + ho.getName() + " state has already been updated to " + newStatus);
return true;
}
}
return result > 0;
}
@Override
public boolean updateResourceState(ResourceState oldState, ResourceState.Event event, ResourceState newState, Host vo) {
HostVO host = (HostVO)vo;
SearchBuilder<HostVO> sb = createSearchBuilder();
sb.and("resource_state", sb.entity().getResourceState(), SearchCriteria.Op.EQ);
sb.and("id", sb.entity().getId(), SearchCriteria.Op.EQ);
sb.done();
SearchCriteria<HostVO> sc = sb.create();
sc.setParameters("resource_state", oldState);
sc.setParameters("id", host.getId());
UpdateBuilder ub = getUpdateBuilder(host);
ub.set(host, _resourceStateAttr, newState);
int result = update(ub, sc, null);
assert result <= 1 : "How can this update " + result + " rows? ";
if (state_logger.isDebugEnabled() && result == 0) {
HostVO ho = findById(host.getId());
assert ho != null : "How how how? : " + host.getId();
StringBuilder str = new StringBuilder("Unable to update resource state: [");
str.append("m = " + host.getId());
str.append("; name = " + host.getName());
str.append("; old state = " + oldState);
str.append("; event = " + event);
str.append("; new state = " + newState + "]");
state_logger.debug(str.toString());
} else {
StringBuilder msg = new StringBuilder("Resource state update: [");
msg.append("id = " + host.getId());
msg.append("; name = " + host.getName());
msg.append("; old state = " + oldState);
msg.append("; event = " + event);
msg.append("; new state = " + newState + "]");
state_logger.debug(msg.toString());
}
return result > 0;
}
@Override
public HostVO findByTypeNameAndZoneId(long zoneId, String name, Host.Type type) {
SearchCriteria<HostVO> sc = TypeNameZoneSearch.create();
sc.setParameters("type", type);
sc.setParameters("name", name);
sc.setParameters("zoneId", zoneId);
return findOneBy(sc);
}
@Override
public List<HostVO> findByPodId(Long podId) {
SearchCriteria<HostVO> sc = PodSearch.create();
sc.setParameters("podId", podId);
return listBy(sc);
}
@Override
public List<HostVO> findByClusterId(Long clusterId) {
SearchCriteria<HostVO> sc = ClusterSearch.create();
sc.setParameters("clusterId", clusterId);
return listBy(sc);
}
@Override
public HostVO findByPublicIp(String publicIp) {
SearchCriteria<HostVO> sc = PublicIpAddressSearch.create();
sc.setParameters("publicIpAddress", publicIp);
return findOneBy(sc);
}
@Override
public List<HostVO> findHypervisorHostInCluster(long clusterId) {
SearchCriteria<HostVO> sc = TypeClusterStatusSearch.create();
sc.setParameters("type", Host.Type.Routing);
sc.setParameters("cluster", clusterId);
sc.setParameters("status", Status.Up);
sc.setParameters("resourceState", ResourceState.Enabled);
return listBy(sc);
}
@Override
public List<Long> listAllHosts(long zoneId) {
SearchCriteria<Long> sc = HostIdSearch.create();
sc.addAnd("dataCenterId", SearchCriteria.Op.EQ, zoneId);
return customSearch(sc, null);
}
}
| engine/schema/src/com/cloud/host/dao/HostDaoImpl.java | // Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
package com.cloud.host.dao;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TimeZone;
import javax.annotation.PostConstruct;
import javax.ejb.Local;
import javax.inject.Inject;
import javax.persistence.TableGenerator;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Component;
import com.cloud.agent.api.VgpuTypesInfo;
import com.cloud.cluster.agentlb.HostTransferMapVO;
import com.cloud.cluster.agentlb.dao.HostTransferMapDao;
import com.cloud.dc.ClusterVO;
import com.cloud.dc.dao.ClusterDao;
import com.cloud.gpu.dao.HostGpuGroupsDao;
import com.cloud.gpu.dao.VGPUTypesDao;
import com.cloud.host.Host;
import com.cloud.host.Host.Type;
import com.cloud.host.HostTagVO;
import com.cloud.host.HostVO;
import com.cloud.host.Status;
import com.cloud.host.Status.Event;
import com.cloud.info.RunningHostCountInfo;
import com.cloud.org.Managed;
import com.cloud.resource.ResourceState;
import com.cloud.utils.DateUtil;
import com.cloud.utils.db.Attribute;
import com.cloud.utils.db.DB;
import com.cloud.utils.db.Filter;
import com.cloud.utils.db.GenericDaoBase;
import com.cloud.utils.db.GenericSearchBuilder;
import com.cloud.utils.db.JoinBuilder;
import com.cloud.utils.db.JoinBuilder.JoinType;
import com.cloud.utils.db.SearchBuilder;
import com.cloud.utils.db.SearchCriteria;
import com.cloud.utils.db.SearchCriteria.Func;
import com.cloud.utils.db.SearchCriteria.Op;
import com.cloud.utils.db.TransactionLegacy;
import com.cloud.utils.db.UpdateBuilder;
import com.cloud.utils.exception.CloudRuntimeException;
@Component
@Local(value = {HostDao.class})
@DB
@TableGenerator(name = "host_req_sq", table = "op_host", pkColumnName = "id", valueColumnName = "sequence", allocationSize = 1)
public class HostDaoImpl extends GenericDaoBase<HostVO, Long> implements HostDao { //FIXME: , ExternalIdDao {
private static final Logger s_logger = Logger.getLogger(HostDaoImpl.class);
private static final Logger status_logger = Logger.getLogger(Status.class);
private static final Logger state_logger = Logger.getLogger(ResourceState.class);
protected SearchBuilder<HostVO> TypePodDcStatusSearch;
protected SearchBuilder<HostVO> IdStatusSearch;
protected SearchBuilder<HostVO> TypeDcSearch;
protected SearchBuilder<HostVO> TypeDcStatusSearch;
protected SearchBuilder<HostVO> TypeClusterStatusSearch;
protected SearchBuilder<HostVO> MsStatusSearch;
protected SearchBuilder<HostVO> DcPrivateIpAddressSearch;
protected SearchBuilder<HostVO> DcStorageIpAddressSearch;
protected SearchBuilder<HostVO> PublicIpAddressSearch;
protected SearchBuilder<HostVO> GuidSearch;
protected SearchBuilder<HostVO> DcSearch;
protected SearchBuilder<HostVO> PodSearch;
protected SearchBuilder<HostVO> ClusterSearch;
protected SearchBuilder<HostVO> TypeSearch;
protected SearchBuilder<HostVO> StatusSearch;
protected SearchBuilder<HostVO> ResourceStateSearch;
protected SearchBuilder<HostVO> NameLikeSearch;
protected SearchBuilder<HostVO> NameSearch;
protected SearchBuilder<HostVO> SequenceSearch;
protected SearchBuilder<HostVO> DirectlyConnectedSearch;
protected SearchBuilder<HostVO> UnmanagedDirectConnectSearch;
protected SearchBuilder<HostVO> UnmanagedApplianceSearch;
protected SearchBuilder<HostVO> MaintenanceCountSearch;
protected SearchBuilder<HostVO> ClusterStatusSearch;
protected SearchBuilder<HostVO> TypeNameZoneSearch;
protected SearchBuilder<HostVO> AvailHypevisorInZone;
protected SearchBuilder<HostVO> DirectConnectSearch;
protected SearchBuilder<HostVO> ManagedDirectConnectSearch;
protected SearchBuilder<HostVO> ManagedRoutingServersSearch;
protected SearchBuilder<HostVO> SecondaryStorageVMSearch;
protected GenericSearchBuilder<HostVO, Long> HostIdSearch;
protected GenericSearchBuilder<HostVO, Long> HostsInStatusSearch;
protected GenericSearchBuilder<HostVO, Long> CountRoutingByDc;
protected SearchBuilder<HostTransferMapVO> HostTransferSearch;
protected SearchBuilder<ClusterVO> ClusterManagedSearch;
protected SearchBuilder<HostVO> RoutingSearch;
protected SearchBuilder<HostVO> HostsForReconnectSearch;
protected GenericSearchBuilder<HostVO, Long> ClustersOwnedByMSSearch;
protected GenericSearchBuilder<HostVO, Long> ClustersForHostsNotOwnedByAnyMSSearch;
protected GenericSearchBuilder<ClusterVO, Long> AllClustersSearch;
protected SearchBuilder<HostVO> HostsInClusterSearch;
protected Attribute _statusAttr;
protected Attribute _resourceStateAttr;
protected Attribute _msIdAttr;
protected Attribute _pingTimeAttr;
@Inject
protected HostDetailsDao _detailsDao;
@Inject
protected HostGpuGroupsDao _hostGpuGroupsDao;
@Inject
protected VGPUTypesDao _vgpuTypesDao;
@Inject
protected HostTagsDao _hostTagsDao;
@Inject
protected HostTransferMapDao _hostTransferDao;
@Inject
protected ClusterDao _clusterDao;
public HostDaoImpl() {
super();
}
@PostConstruct
public void init() {
MaintenanceCountSearch = createSearchBuilder();
MaintenanceCountSearch.and("cluster", MaintenanceCountSearch.entity().getClusterId(), SearchCriteria.Op.EQ);
MaintenanceCountSearch.and("resourceState", MaintenanceCountSearch.entity().getResourceState(), SearchCriteria.Op.IN);
MaintenanceCountSearch.done();
TypePodDcStatusSearch = createSearchBuilder();
HostVO entity = TypePodDcStatusSearch.entity();
TypePodDcStatusSearch.and("type", entity.getType(), SearchCriteria.Op.EQ);
TypePodDcStatusSearch.and("pod", entity.getPodId(), SearchCriteria.Op.EQ);
TypePodDcStatusSearch.and("dc", entity.getDataCenterId(), SearchCriteria.Op.EQ);
TypePodDcStatusSearch.and("cluster", entity.getClusterId(), SearchCriteria.Op.EQ);
TypePodDcStatusSearch.and("status", entity.getStatus(), SearchCriteria.Op.EQ);
TypePodDcStatusSearch.and("resourceState", entity.getResourceState(), SearchCriteria.Op.EQ);
TypePodDcStatusSearch.done();
MsStatusSearch = createSearchBuilder();
MsStatusSearch.and("ms", MsStatusSearch.entity().getManagementServerId(), SearchCriteria.Op.EQ);
MsStatusSearch.and("type", MsStatusSearch.entity().getType(), SearchCriteria.Op.EQ);
MsStatusSearch.and("resourceState", MsStatusSearch.entity().getResourceState(), SearchCriteria.Op.NIN);
MsStatusSearch.done();
TypeDcSearch = createSearchBuilder();
TypeDcSearch.and("type", TypeDcSearch.entity().getType(), SearchCriteria.Op.EQ);
TypeDcSearch.and("dc", TypeDcSearch.entity().getDataCenterId(), SearchCriteria.Op.EQ);
TypeDcSearch.done();
SecondaryStorageVMSearch = createSearchBuilder();
SecondaryStorageVMSearch.and("type", SecondaryStorageVMSearch.entity().getType(), SearchCriteria.Op.EQ);
SecondaryStorageVMSearch.and("dc", SecondaryStorageVMSearch.entity().getDataCenterId(), SearchCriteria.Op.EQ);
SecondaryStorageVMSearch.and("status", SecondaryStorageVMSearch.entity().getStatus(), SearchCriteria.Op.EQ);
SecondaryStorageVMSearch.done();
TypeDcStatusSearch = createSearchBuilder();
TypeDcStatusSearch.and("type", TypeDcStatusSearch.entity().getType(), SearchCriteria.Op.EQ);
TypeDcStatusSearch.and("dc", TypeDcStatusSearch.entity().getDataCenterId(), SearchCriteria.Op.EQ);
TypeDcStatusSearch.and("status", TypeDcStatusSearch.entity().getStatus(), SearchCriteria.Op.EQ);
TypeDcStatusSearch.and("resourceState", TypeDcStatusSearch.entity().getResourceState(), SearchCriteria.Op.EQ);
TypeDcStatusSearch.done();
TypeClusterStatusSearch = createSearchBuilder();
TypeClusterStatusSearch.and("type", TypeClusterStatusSearch.entity().getType(), SearchCriteria.Op.EQ);
TypeClusterStatusSearch.and("cluster", TypeClusterStatusSearch.entity().getClusterId(), SearchCriteria.Op.EQ);
TypeClusterStatusSearch.and("status", TypeClusterStatusSearch.entity().getStatus(), SearchCriteria.Op.EQ);
TypeClusterStatusSearch.and("resourceState", TypeClusterStatusSearch.entity().getResourceState(), SearchCriteria.Op.EQ);
TypeClusterStatusSearch.done();
IdStatusSearch = createSearchBuilder();
IdStatusSearch.and("id", IdStatusSearch.entity().getId(), SearchCriteria.Op.EQ);
IdStatusSearch.and("states", IdStatusSearch.entity().getStatus(), SearchCriteria.Op.IN);
IdStatusSearch.done();
DcPrivateIpAddressSearch = createSearchBuilder();
DcPrivateIpAddressSearch.and("privateIpAddress", DcPrivateIpAddressSearch.entity().getPrivateIpAddress(), SearchCriteria.Op.EQ);
DcPrivateIpAddressSearch.and("dc", DcPrivateIpAddressSearch.entity().getDataCenterId(), SearchCriteria.Op.EQ);
DcPrivateIpAddressSearch.done();
DcStorageIpAddressSearch = createSearchBuilder();
DcStorageIpAddressSearch.and("storageIpAddress", DcStorageIpAddressSearch.entity().getStorageIpAddress(), SearchCriteria.Op.EQ);
DcStorageIpAddressSearch.and("dc", DcStorageIpAddressSearch.entity().getDataCenterId(), SearchCriteria.Op.EQ);
DcStorageIpAddressSearch.done();
PublicIpAddressSearch = createSearchBuilder();
PublicIpAddressSearch.and("publicIpAddress", PublicIpAddressSearch.entity().getPublicIpAddress(), SearchCriteria.Op.EQ);
PublicIpAddressSearch.done();
GuidSearch = createSearchBuilder();
GuidSearch.and("guid", GuidSearch.entity().getGuid(), SearchCriteria.Op.EQ);
GuidSearch.done();
DcSearch = createSearchBuilder();
DcSearch.and("dc", DcSearch.entity().getDataCenterId(), SearchCriteria.Op.EQ);
DcSearch.and("type", DcSearch.entity().getType(), Op.EQ);
DcSearch.and("status", DcSearch.entity().getStatus(), Op.EQ);
DcSearch.and("resourceState", DcSearch.entity().getResourceState(), Op.EQ);
DcSearch.done();
ClusterStatusSearch = createSearchBuilder();
ClusterStatusSearch.and("cluster", ClusterStatusSearch.entity().getClusterId(), SearchCriteria.Op.EQ);
ClusterStatusSearch.and("status", ClusterStatusSearch.entity().getStatus(), SearchCriteria.Op.EQ);
ClusterStatusSearch.done();
TypeNameZoneSearch = createSearchBuilder();
TypeNameZoneSearch.and("name", TypeNameZoneSearch.entity().getName(), SearchCriteria.Op.EQ);
TypeNameZoneSearch.and("type", TypeNameZoneSearch.entity().getType(), SearchCriteria.Op.EQ);
TypeNameZoneSearch.and("zoneId", TypeNameZoneSearch.entity().getDataCenterId(), SearchCriteria.Op.EQ);
TypeNameZoneSearch.done();
PodSearch = createSearchBuilder();
PodSearch.and("podId", PodSearch.entity().getPodId(), SearchCriteria.Op.EQ);
PodSearch.done();
ClusterSearch = createSearchBuilder();
ClusterSearch.and("clusterId", ClusterSearch.entity().getClusterId(), SearchCriteria.Op.EQ);
ClusterSearch.done();
TypeSearch = createSearchBuilder();
TypeSearch.and("type", TypeSearch.entity().getType(), SearchCriteria.Op.EQ);
TypeSearch.done();
StatusSearch = createSearchBuilder();
StatusSearch.and("status", StatusSearch.entity().getStatus(), SearchCriteria.Op.IN);
StatusSearch.done();
ResourceStateSearch = createSearchBuilder();
ResourceStateSearch.and("resourceState", ResourceStateSearch.entity().getResourceState(), SearchCriteria.Op.IN);
ResourceStateSearch.done();
NameLikeSearch = createSearchBuilder();
NameLikeSearch.and("name", NameLikeSearch.entity().getName(), SearchCriteria.Op.LIKE);
NameLikeSearch.done();
NameSearch = createSearchBuilder();
NameSearch.and("name", NameSearch.entity().getName(), SearchCriteria.Op.EQ);
NameSearch.done();
SequenceSearch = createSearchBuilder();
SequenceSearch.and("id", SequenceSearch.entity().getId(), SearchCriteria.Op.EQ);
// SequenceSearch.addRetrieve("sequence", SequenceSearch.entity().getSequence());
SequenceSearch.done();
DirectlyConnectedSearch = createSearchBuilder();
DirectlyConnectedSearch.and("resource", DirectlyConnectedSearch.entity().getResource(), SearchCriteria.Op.NNULL);
DirectlyConnectedSearch.and("ms", DirectlyConnectedSearch.entity().getManagementServerId(), SearchCriteria.Op.EQ);
DirectlyConnectedSearch.and("statuses", DirectlyConnectedSearch.entity().getStatus(), SearchCriteria.Op.EQ);
DirectlyConnectedSearch.and("resourceState", DirectlyConnectedSearch.entity().getResourceState(), SearchCriteria.Op.NOTIN);
DirectlyConnectedSearch.done();
UnmanagedDirectConnectSearch = createSearchBuilder();
UnmanagedDirectConnectSearch.and("resource", UnmanagedDirectConnectSearch.entity().getResource(), SearchCriteria.Op.NNULL);
UnmanagedDirectConnectSearch.and("server", UnmanagedDirectConnectSearch.entity().getManagementServerId(), SearchCriteria.Op.NULL);
UnmanagedDirectConnectSearch.and("lastPinged", UnmanagedDirectConnectSearch.entity().getLastPinged(), SearchCriteria.Op.LTEQ);
UnmanagedDirectConnectSearch.and("resourceStates", UnmanagedDirectConnectSearch.entity().getResourceState(), SearchCriteria.Op.NIN);
UnmanagedDirectConnectSearch.and("clusterIn", UnmanagedDirectConnectSearch.entity().getClusterId(), SearchCriteria.Op.IN);
/*
* UnmanagedDirectConnectSearch.op(SearchCriteria.Op.OR, "managementServerId",
* UnmanagedDirectConnectSearch.entity().getManagementServerId(), SearchCriteria.Op.EQ);
* UnmanagedDirectConnectSearch.and("lastPinged", UnmanagedDirectConnectSearch.entity().getLastPinged(),
* SearchCriteria.Op.LTEQ); UnmanagedDirectConnectSearch.cp(); UnmanagedDirectConnectSearch.cp();
*/
try {
HostTransferSearch = _hostTransferDao.createSearchBuilder();
} catch (Throwable e) {
s_logger.debug("error", e);
}
HostTransferSearch.and("id", HostTransferSearch.entity().getId(), SearchCriteria.Op.NULL);
UnmanagedDirectConnectSearch.join("hostTransferSearch", HostTransferSearch, HostTransferSearch.entity().getId(), UnmanagedDirectConnectSearch.entity().getId(),
JoinType.LEFTOUTER);
ClusterManagedSearch = _clusterDao.createSearchBuilder();
ClusterManagedSearch.and("managed", ClusterManagedSearch.entity().getManagedState(), SearchCriteria.Op.EQ);
UnmanagedDirectConnectSearch.join("ClusterManagedSearch", ClusterManagedSearch, ClusterManagedSearch.entity().getId(), UnmanagedDirectConnectSearch.entity()
.getClusterId(), JoinType.INNER);
UnmanagedDirectConnectSearch.done();
DirectConnectSearch = createSearchBuilder();
DirectConnectSearch.and("resource", DirectConnectSearch.entity().getResource(), SearchCriteria.Op.NNULL);
DirectConnectSearch.and("id", DirectConnectSearch.entity().getId(), SearchCriteria.Op.EQ);
DirectConnectSearch.and().op("nullserver", DirectConnectSearch.entity().getManagementServerId(), SearchCriteria.Op.NULL);
DirectConnectSearch.or("server", DirectConnectSearch.entity().getManagementServerId(), SearchCriteria.Op.EQ);
DirectConnectSearch.cp();
DirectConnectSearch.done();
UnmanagedApplianceSearch = createSearchBuilder();
UnmanagedApplianceSearch.and("resource", UnmanagedApplianceSearch.entity().getResource(), SearchCriteria.Op.NNULL);
UnmanagedApplianceSearch.and("server", UnmanagedApplianceSearch.entity().getManagementServerId(), SearchCriteria.Op.NULL);
UnmanagedApplianceSearch.and("types", UnmanagedApplianceSearch.entity().getType(), SearchCriteria.Op.IN);
UnmanagedApplianceSearch.and("lastPinged", UnmanagedApplianceSearch.entity().getLastPinged(), SearchCriteria.Op.LTEQ);
UnmanagedApplianceSearch.done();
AvailHypevisorInZone = createSearchBuilder();
AvailHypevisorInZone.and("zoneId", AvailHypevisorInZone.entity().getDataCenterId(), SearchCriteria.Op.EQ);
AvailHypevisorInZone.and("hostId", AvailHypevisorInZone.entity().getId(), SearchCriteria.Op.NEQ);
AvailHypevisorInZone.and("type", AvailHypevisorInZone.entity().getType(), SearchCriteria.Op.EQ);
AvailHypevisorInZone.groupBy(AvailHypevisorInZone.entity().getHypervisorType());
AvailHypevisorInZone.done();
HostsInStatusSearch = createSearchBuilder(Long.class);
HostsInStatusSearch.selectFields(HostsInStatusSearch.entity().getId());
HostsInStatusSearch.and("dc", HostsInStatusSearch.entity().getDataCenterId(), Op.EQ);
HostsInStatusSearch.and("pod", HostsInStatusSearch.entity().getPodId(), Op.EQ);
HostsInStatusSearch.and("cluster", HostsInStatusSearch.entity().getClusterId(), Op.EQ);
HostsInStatusSearch.and("type", HostsInStatusSearch.entity().getType(), Op.EQ);
HostsInStatusSearch.and("statuses", HostsInStatusSearch.entity().getStatus(), Op.IN);
HostsInStatusSearch.done();
CountRoutingByDc = createSearchBuilder(Long.class);
CountRoutingByDc.select(null, Func.COUNT, null);
CountRoutingByDc.and("dc", CountRoutingByDc.entity().getDataCenterId(), SearchCriteria.Op.EQ);
CountRoutingByDc.and("type", CountRoutingByDc.entity().getType(), SearchCriteria.Op.EQ);
CountRoutingByDc.and("status", CountRoutingByDc.entity().getStatus(), SearchCriteria.Op.EQ);
CountRoutingByDc.done();
ManagedDirectConnectSearch = createSearchBuilder();
ManagedDirectConnectSearch.and("resource", ManagedDirectConnectSearch.entity().getResource(), SearchCriteria.Op.NNULL);
ManagedDirectConnectSearch.and("server", ManagedDirectConnectSearch.entity().getManagementServerId(), SearchCriteria.Op.NULL);
ManagedDirectConnectSearch.done();
ManagedRoutingServersSearch = createSearchBuilder();
ManagedRoutingServersSearch.and("server", ManagedRoutingServersSearch.entity().getManagementServerId(), SearchCriteria.Op.NNULL);
ManagedRoutingServersSearch.and("type", ManagedRoutingServersSearch.entity().getType(), SearchCriteria.Op.EQ);
ManagedRoutingServersSearch.done();
RoutingSearch = createSearchBuilder();
RoutingSearch.and("type", RoutingSearch.entity().getType(), SearchCriteria.Op.EQ);
RoutingSearch.done();
HostsForReconnectSearch = createSearchBuilder();
HostsForReconnectSearch.and("resource", HostsForReconnectSearch.entity().getResource(), SearchCriteria.Op.NNULL);
HostsForReconnectSearch.and("server", HostsForReconnectSearch.entity().getManagementServerId(), SearchCriteria.Op.EQ);
HostsForReconnectSearch.and("lastPinged", HostsForReconnectSearch.entity().getLastPinged(), SearchCriteria.Op.LTEQ);
HostsForReconnectSearch.and("resourceStates", HostsForReconnectSearch.entity().getResourceState(), SearchCriteria.Op.NIN);
HostsForReconnectSearch.and("cluster", HostsForReconnectSearch.entity().getClusterId(), SearchCriteria.Op.NNULL);
HostsForReconnectSearch.and("status", HostsForReconnectSearch.entity().getStatus(), SearchCriteria.Op.IN);
HostsForReconnectSearch.done();
ClustersOwnedByMSSearch = createSearchBuilder(Long.class);
ClustersOwnedByMSSearch.select(null, Func.DISTINCT, ClustersOwnedByMSSearch.entity().getClusterId());
ClustersOwnedByMSSearch.and("resource", ClustersOwnedByMSSearch.entity().getResource(), SearchCriteria.Op.NNULL);
ClustersOwnedByMSSearch.and("cluster", ClustersOwnedByMSSearch.entity().getClusterId(), SearchCriteria.Op.NNULL);
ClustersOwnedByMSSearch.and("server", ClustersOwnedByMSSearch.entity().getManagementServerId(), SearchCriteria.Op.EQ);
ClustersOwnedByMSSearch.done();
ClustersForHostsNotOwnedByAnyMSSearch = createSearchBuilder(Long.class);
ClustersForHostsNotOwnedByAnyMSSearch.select(null, Func.DISTINCT, ClustersForHostsNotOwnedByAnyMSSearch.entity().getClusterId());
ClustersForHostsNotOwnedByAnyMSSearch.and("resource", ClustersForHostsNotOwnedByAnyMSSearch.entity().getResource(), SearchCriteria.Op.NNULL);
ClustersForHostsNotOwnedByAnyMSSearch.and("cluster", ClustersForHostsNotOwnedByAnyMSSearch.entity().getClusterId(), SearchCriteria.Op.NNULL);
ClustersForHostsNotOwnedByAnyMSSearch.and("server", ClustersForHostsNotOwnedByAnyMSSearch.entity().getManagementServerId(), SearchCriteria.Op.NULL);
ClustersForHostsNotOwnedByAnyMSSearch.done();
AllClustersSearch = _clusterDao.createSearchBuilder(Long.class);
AllClustersSearch.select(null, Func.NATIVE, AllClustersSearch.entity().getId());
AllClustersSearch.and("managed", AllClustersSearch.entity().getManagedState(), SearchCriteria.Op.EQ);
AllClustersSearch.done();
HostsInClusterSearch = createSearchBuilder();
HostsInClusterSearch.and("resource", HostsInClusterSearch.entity().getResource(), SearchCriteria.Op.NNULL);
HostsInClusterSearch.and("cluster", HostsInClusterSearch.entity().getClusterId(), SearchCriteria.Op.EQ);
HostsInClusterSearch.and("server", HostsInClusterSearch.entity().getManagementServerId(), SearchCriteria.Op.NNULL);
HostsInClusterSearch.done();
HostIdSearch = createSearchBuilder(Long.class);
HostIdSearch.selectFields(HostIdSearch.entity().getId());
HostIdSearch.and("dataCenterId", HostIdSearch.entity().getDataCenterId(), Op.EQ);
HostIdSearch.done();
_statusAttr = _allAttributes.get("status");
_msIdAttr = _allAttributes.get("managementServerId");
_pingTimeAttr = _allAttributes.get("lastPinged");
_resourceStateAttr = _allAttributes.get("resourceState");
assert (_statusAttr != null && _msIdAttr != null && _pingTimeAttr != null) : "Couldn't find one of these attributes";
}
@Override
public long countBy(long clusterId, ResourceState... states) {
SearchCriteria<HostVO> sc = MaintenanceCountSearch.create();
sc.setParameters("resourceState", (Object[])states);
sc.setParameters("cluster", clusterId);
List<HostVO> hosts = listBy(sc);
return hosts.size();
}
@Override
public List<HostVO> listByDataCenterId(long id) {
SearchCriteria<HostVO> sc = DcSearch.create();
sc.setParameters("dc", id);
sc.setParameters("status", Status.Up);
sc.setParameters("type", Host.Type.Routing);
sc.setParameters("resourceState", ResourceState.Enabled);
return listBy(sc);
}
@Override
public HostVO findByGuid(String guid) {
SearchCriteria<HostVO> sc = GuidSearch.create("guid", guid);
return findOneBy(sc);
}
/*
* Find hosts which is in Disconnected, Down, Alert and ping timeout and server is not null, set server to null
*/
private void resetHosts(long managementServerId, long lastPingSecondsAfter) {
SearchCriteria<HostVO> sc = HostsForReconnectSearch.create();
sc.setParameters("server", managementServerId);
sc.setParameters("lastPinged", lastPingSecondsAfter);
sc.setParameters("status", Status.Disconnected, Status.Down, Status.Alert);
StringBuilder sb = new StringBuilder();
List<HostVO> hosts = lockRows(sc, null, true); // exclusive lock
for (HostVO host : hosts) {
host.setManagementServerId(null);
update(host.getId(), host);
sb.append(host.getId());
sb.append(" ");
}
if (s_logger.isTraceEnabled()) {
s_logger.trace("Following hosts got reset: " + sb.toString());
}
}
/*
* Returns a list of cluster owned by @managementServerId
*/
private List<Long> findClustersOwnedByManagementServer(long managementServerId) {
SearchCriteria<Long> sc = ClustersOwnedByMSSearch.create();
sc.setParameters("server", managementServerId);
List<Long> clusters = customSearch(sc, null);
return clusters;
}
/*
* Returns clusters based on the list of hosts not owned by any MS
*/
private List<Long> findClustersForHostsNotOwnedByAnyManagementServer() {
SearchCriteria<Long> sc = ClustersForHostsNotOwnedByAnyMSSearch.create();
List<Long> clusters = customSearch(sc, null);
return clusters;
}
/*
* Returns a list of all cluster Ids
*/
private List<Long> listAllClusters() {
SearchCriteria<Long> sc = AllClustersSearch.create();
sc.setParameters("managed", Managed.ManagedState.Managed);
List<Long> clusters = _clusterDao.customSearch(sc, null);
return clusters;
}
/*
* This determines if hosts belonging to cluster(@clusterId) are up for grabs
*
* This is used for handling following cases:
* 1. First host added in cluster
* 2. During MS restart all hosts in a cluster are without any MS
*/
private boolean canOwnCluster(long clusterId) {
SearchCriteria<HostVO> sc = HostsInClusterSearch.create();
sc.setParameters("cluster", clusterId);
List<HostVO> hosts = search(sc, null);
boolean ownCluster = (hosts == null || hosts.size() == 0);
return ownCluster;
}
@Override
@DB
public List<HostVO> findAndUpdateDirectAgentToLoad(long lastPingSecondsAfter, Long limit, long managementServerId) {
TransactionLegacy txn = TransactionLegacy.currentTxn();
txn.start();
if (s_logger.isDebugEnabled()) {
s_logger.debug("Resetting hosts suitable for reconnect");
}
// reset hosts that are suitable candidates for reconnect
resetHosts(managementServerId, lastPingSecondsAfter);
if (s_logger.isDebugEnabled()) {
s_logger.debug("Completed resetting hosts suitable for reconnect");
}
List<HostVO> assignedHosts = new ArrayList<HostVO>();
if (s_logger.isDebugEnabled()) {
s_logger.debug("Acquiring hosts for clusters already owned by this management server");
}
List<Long> clusters = findClustersOwnedByManagementServer(managementServerId);
if (clusters.size() > 0) {
// handle clusters already owned by @managementServerId
SearchCriteria<HostVO> sc = UnmanagedDirectConnectSearch.create();
sc.setParameters("lastPinged", lastPingSecondsAfter);
sc.setJoinParameters("ClusterManagedSearch", "managed", Managed.ManagedState.Managed);
sc.setParameters("clusterIn", clusters.toArray());
List<HostVO> unmanagedHosts = lockRows(sc, new Filter(HostVO.class, "clusterId", true, 0L, limit), true); // host belongs to clusters owned by @managementServerId
StringBuilder sb = new StringBuilder();
for (HostVO host : unmanagedHosts) {
host.setManagementServerId(managementServerId);
update(host.getId(), host);
assignedHosts.add(host);
sb.append(host.getId());
sb.append(" ");
}
if (s_logger.isTraceEnabled()) {
s_logger.trace("Following hosts got acquired for clusters already owned: " + sb.toString());
}
}
if (s_logger.isDebugEnabled()) {
s_logger.debug("Completed acquiring hosts for clusters already owned by this management server");
}
if (assignedHosts.size() < limit) {
if (s_logger.isDebugEnabled()) {
s_logger.debug("Acquiring hosts for clusters not owned by any management server");
}
// for remaining hosts not owned by any MS check if they can be owned (by owning full cluster)
clusters = findClustersForHostsNotOwnedByAnyManagementServer();
List<Long> updatedClusters = clusters;
if (clusters.size() > limit) {
updatedClusters = clusters.subList(0, limit.intValue());
}
if (updatedClusters.size() > 0) {
SearchCriteria<HostVO> sc = UnmanagedDirectConnectSearch.create();
sc.setParameters("lastPinged", lastPingSecondsAfter);
sc.setJoinParameters("ClusterManagedSearch", "managed", Managed.ManagedState.Managed);
sc.setParameters("clusterIn", updatedClusters.toArray());
List<HostVO> unmanagedHosts = lockRows(sc, null, true);
// group hosts based on cluster
Map<Long, List<HostVO>> hostMap = new HashMap<Long, List<HostVO>>();
for (HostVO host : unmanagedHosts) {
if (hostMap.get(host.getClusterId()) == null) {
hostMap.put(host.getClusterId(), new ArrayList<HostVO>());
}
hostMap.get(host.getClusterId()).add(host);
}
StringBuilder sb = new StringBuilder();
for (Long clusterId : hostMap.keySet()) {
if (canOwnCluster(clusterId)) { // cluster is not owned by any other MS, so @managementServerId can own it
List<HostVO> hostList = hostMap.get(clusterId);
for (HostVO host : hostList) {
host.setManagementServerId(managementServerId);
update(host.getId(), host);
assignedHosts.add(host);
sb.append(host.getId());
sb.append(" ");
}
}
if (assignedHosts.size() > limit) {
break;
}
}
if (s_logger.isTraceEnabled()) {
s_logger.trace("Following hosts got acquired from newly owned clusters: " + sb.toString());
}
}
if (s_logger.isDebugEnabled()) {
s_logger.debug("Completed acquiring hosts for clusters not owned by any management server");
}
}
txn.commit();
return assignedHosts;
}
@Override
@DB
public List<HostVO> findAndUpdateApplianceToLoad(long lastPingSecondsAfter, long managementServerId) {
TransactionLegacy txn = TransactionLegacy.currentTxn();
txn.start();
SearchCriteria<HostVO> sc = UnmanagedApplianceSearch.create();
sc.setParameters("lastPinged", lastPingSecondsAfter);
sc.setParameters("types", Type.ExternalDhcp, Type.ExternalFirewall, Type.ExternalLoadBalancer, Type.BaremetalDhcp, Type.BaremetalPxe, Type.TrafficMonitor,
Type.L2Networking);
List<HostVO> hosts = lockRows(sc, null, true);
for (HostVO host : hosts) {
host.setManagementServerId(managementServerId);
update(host.getId(), host);
}
txn.commit();
return hosts;
}
@Override
public void markHostsAsDisconnected(long msId, long lastPing) {
SearchCriteria<HostVO> sc = MsStatusSearch.create();
sc.setParameters("ms", msId);
HostVO host = createForUpdate();
host.setLastPinged(lastPing);
host.setDisconnectedOn(new Date());
UpdateBuilder ub = getUpdateBuilder(host);
ub.set(host, "status", Status.Disconnected);
update(ub, sc, null);
sc = MsStatusSearch.create();
sc.setParameters("ms", msId);
host = createForUpdate();
host.setManagementServerId(null);
host.setLastPinged(lastPing);
host.setDisconnectedOn(new Date());
ub = getUpdateBuilder(host);
update(ub, sc, null);
}
@Override
public List<HostVO> listByHostTag(Host.Type type, Long clusterId, Long podId, long dcId, String hostTag) {
SearchBuilder<HostTagVO> hostTagSearch = _hostTagsDao.createSearchBuilder();
HostTagVO tagEntity = hostTagSearch.entity();
hostTagSearch.and("tag", tagEntity.getTag(), SearchCriteria.Op.EQ);
SearchBuilder<HostVO> hostSearch = createSearchBuilder();
HostVO entity = hostSearch.entity();
hostSearch.and("type", entity.getType(), SearchCriteria.Op.EQ);
hostSearch.and("pod", entity.getPodId(), SearchCriteria.Op.EQ);
hostSearch.and("dc", entity.getDataCenterId(), SearchCriteria.Op.EQ);
hostSearch.and("cluster", entity.getClusterId(), SearchCriteria.Op.EQ);
hostSearch.and("status", entity.getStatus(), SearchCriteria.Op.EQ);
hostSearch.and("resourceState", entity.getResourceState(), SearchCriteria.Op.EQ);
hostSearch.join("hostTagSearch", hostTagSearch, entity.getId(), tagEntity.getHostId(), JoinBuilder.JoinType.INNER);
SearchCriteria<HostVO> sc = hostSearch.create();
sc.setJoinParameters("hostTagSearch", "tag", hostTag);
sc.setParameters("type", type.toString());
if (podId != null) {
sc.setParameters("pod", podId);
}
if (clusterId != null) {
sc.setParameters("cluster", clusterId);
}
sc.setParameters("dc", dcId);
sc.setParameters("status", Status.Up.toString());
sc.setParameters("resourceState", ResourceState.Enabled.toString());
return listBy(sc);
}
@Override
public List<HostVO> listAllUpAndEnabledNonHAHosts(Type type, Long clusterId, Long podId, long dcId, String haTag) {
SearchBuilder<HostTagVO> hostTagSearch = null;
if (haTag != null && !haTag.isEmpty()) {
hostTagSearch = _hostTagsDao.createSearchBuilder();
hostTagSearch.and().op("tag", hostTagSearch.entity().getTag(), SearchCriteria.Op.NEQ);
hostTagSearch.or("tagNull", hostTagSearch.entity().getTag(), SearchCriteria.Op.NULL);
hostTagSearch.cp();
}
SearchBuilder<HostVO> hostSearch = createSearchBuilder();
hostSearch.and("type", hostSearch.entity().getType(), SearchCriteria.Op.EQ);
hostSearch.and("clusterId", hostSearch.entity().getClusterId(), SearchCriteria.Op.EQ);
hostSearch.and("podId", hostSearch.entity().getPodId(), SearchCriteria.Op.EQ);
hostSearch.and("zoneId", hostSearch.entity().getDataCenterId(), SearchCriteria.Op.EQ);
hostSearch.and("status", hostSearch.entity().getStatus(), SearchCriteria.Op.EQ);
hostSearch.and("resourceState", hostSearch.entity().getResourceState(), SearchCriteria.Op.EQ);
if (haTag != null && !haTag.isEmpty()) {
hostSearch.join("hostTagSearch", hostTagSearch, hostSearch.entity().getId(), hostTagSearch.entity().getHostId(), JoinBuilder.JoinType.LEFTOUTER);
}
SearchCriteria<HostVO> sc = hostSearch.create();
if (haTag != null && !haTag.isEmpty()) {
sc.setJoinParameters("hostTagSearch", "tag", haTag);
}
if (type != null) {
sc.setParameters("type", type);
}
if (clusterId != null) {
sc.setParameters("clusterId", clusterId);
}
if (podId != null) {
sc.setParameters("podId", podId);
}
sc.setParameters("zoneId", dcId);
sc.setParameters("status", Status.Up);
sc.setParameters("resourceState", ResourceState.Enabled);
return listBy(sc);
}
@Override
public void loadDetails(HostVO host) {
Map<String, String> details = _detailsDao.findDetails(host.getId());
host.setDetails(details);
}
@Override
public void loadHostTags(HostVO host) {
List<String> hostTags = _hostTagsDao.gethostTags(host.getId());
host.setHostTags(hostTags);
}
@DB
@Override
public List<HostVO> findLostHosts(long timeout) {
TransactionLegacy txn = TransactionLegacy.currentTxn();
PreparedStatement pstmt = null;
List<HostVO> result = new ArrayList<HostVO>();
ResultSet rs = null;
try {
String sql =
"select h.id from host h left join cluster c on h.cluster_id=c.id where h.mgmt_server_id is not null and h.last_ping < ? and h.status in ('Up', 'Updating', 'Disconnected', 'Connecting') and h.type not in ('ExternalFirewall', 'ExternalLoadBalancer', 'TrafficMonitor', 'SecondaryStorage', 'LocalSecondaryStorage', 'L2Networking') and (h.cluster_id is null or c.managed_state = 'Managed') ;";
pstmt = txn.prepareStatement(sql);
pstmt.setLong(1, timeout);
rs = pstmt.executeQuery();
while (rs.next()) {
long id = rs.getLong(1); //ID column
result.add(findById(id));
}
} catch (Exception e) {
s_logger.warn("Exception: ", e);
} finally {
try {
if (rs != null) {
rs.close();
}
if (pstmt != null) {
pstmt.close();
}
} catch (SQLException e) {
}
}
return result;
}
@Override
public void saveDetails(HostVO host) {
Map<String, String> details = host.getDetails();
if (details == null) {
return;
}
_detailsDao.persist(host.getId(), details);
}
protected void saveHostTags(HostVO host) {
List<String> hostTags = host.getHostTags();
if (hostTags == null || (hostTags != null && hostTags.isEmpty())) {
return;
}
_hostTagsDao.persist(host.getId(), hostTags);
}
protected void saveGpuRecords(HostVO host) {
HashMap<String, HashMap<String, VgpuTypesInfo>> groupDetails = host.getGpuGroupDetails();
if (groupDetails != null) {
// Create/Update GPU group entries
_hostGpuGroupsDao.persist(host.getId(), new ArrayList<String>(groupDetails.keySet()));
// Create/Update VGPU types entries
_vgpuTypesDao.persist(host.getId(), groupDetails);
}
}
@Override
@DB
public HostVO persist(HostVO host) {
final String InsertSequenceSql = "INSERT INTO op_host(id) VALUES(?)";
TransactionLegacy txn = TransactionLegacy.currentTxn();
txn.start();
HostVO dbHost = super.persist(host);
try {
PreparedStatement pstmt = txn.prepareAutoCloseStatement(InsertSequenceSql);
pstmt.setLong(1, dbHost.getId());
pstmt.executeUpdate();
} catch (SQLException e) {
throw new CloudRuntimeException("Unable to persist the sequence number for this host");
}
saveDetails(host);
loadDetails(dbHost);
saveHostTags(host);
loadHostTags(dbHost);
saveGpuRecords(host);
txn.commit();
return dbHost;
}
@Override
@DB
public boolean update(Long hostId, HostVO host) {
TransactionLegacy txn = TransactionLegacy.currentTxn();
txn.start();
boolean persisted = super.update(hostId, host);
if (!persisted) {
return persisted;
}
saveDetails(host);
saveHostTags(host);
saveGpuRecords(host);
txn.commit();
return persisted;
}
@Override
@DB
public List<RunningHostCountInfo> getRunningHostCounts(Date cutTime) {
String sql =
"select * from (" + "select h.data_center_id, h.type, count(*) as count from host as h INNER JOIN mshost as m ON h.mgmt_server_id=m.msid "
+ "where h.status='Up' and h.type='SecondaryStorage' and m.last_update > ? " + "group by h.data_center_id, h.type " + "UNION ALL "
+ "select h.data_center_id, h.type, count(*) as count from host as h INNER JOIN mshost as m ON h.mgmt_server_id=m.msid "
+ "where h.status='Up' and h.type='Routing' and m.last_update > ? " + "group by h.data_center_id, h.type) as t " + "ORDER by t.data_center_id, t.type";
ArrayList<RunningHostCountInfo> l = new ArrayList<RunningHostCountInfo>();
TransactionLegacy txn = TransactionLegacy.currentTxn();
;
PreparedStatement pstmt = null;
try {
pstmt = txn.prepareAutoCloseStatement(sql);
String gmtCutTime = DateUtil.getDateDisplayString(TimeZone.getTimeZone("GMT"), cutTime);
pstmt.setString(1, gmtCutTime);
pstmt.setString(2, gmtCutTime);
ResultSet rs = pstmt.executeQuery();
while (rs.next()) {
RunningHostCountInfo info = new RunningHostCountInfo();
info.setDcId(rs.getLong(1));
info.setHostType(rs.getString(2));
info.setCount(rs.getInt(3));
l.add(info);
}
} catch (SQLException e) {
s_logger.debug("SQLException caught", e);
}
return l;
}
@Override
public long getNextSequence(long hostId) {
if (s_logger.isTraceEnabled()) {
s_logger.trace("getNextSequence(), hostId: " + hostId);
}
TableGenerator tg = _tgs.get("host_req_sq");
assert tg != null : "how can this be wrong!";
return s_seqFetcher.getNextSequence(Long.class, tg, hostId);
}
/*TODO: this is used by mycloud, check if it needs resource state Enabled */
@Override
public long countRoutingHostsByDataCenter(long dcId) {
SearchCriteria<Long> sc = CountRoutingByDc.create();
sc.setParameters("dc", dcId);
sc.setParameters("type", Host.Type.Routing);
sc.setParameters("status", Status.Up.toString());
return customSearch(sc, null).get(0);
}
@Override
public boolean updateState(Status oldStatus, Event event, Status newStatus, Host vo, Object data) {
// lock target row from beginning to avoid lock-promotion caused deadlock
HostVO host = lockRow(vo.getId(), true);
if (host == null) {
if (event == Event.Remove && newStatus == Status.Removed) {
host = findByIdIncludingRemoved(vo.getId());
}
}
if (host == null) {
return false;
}
long oldPingTime = host.getLastPinged();
SearchBuilder<HostVO> sb = createSearchBuilder();
sb.and("status", sb.entity().getStatus(), SearchCriteria.Op.EQ);
sb.and("id", sb.entity().getId(), SearchCriteria.Op.EQ);
sb.and("update", sb.entity().getUpdated(), SearchCriteria.Op.EQ);
if (newStatus.checkManagementServer()) {
sb.and("ping", sb.entity().getLastPinged(), SearchCriteria.Op.EQ);
sb.and().op("nullmsid", sb.entity().getManagementServerId(), SearchCriteria.Op.NULL);
sb.or("msid", sb.entity().getManagementServerId(), SearchCriteria.Op.EQ);
sb.cp();
}
sb.done();
SearchCriteria<HostVO> sc = sb.create();
sc.setParameters("status", oldStatus);
sc.setParameters("id", host.getId());
sc.setParameters("update", host.getUpdated());
long oldUpdateCount = host.getUpdated();
if (newStatus.checkManagementServer()) {
sc.setParameters("ping", oldPingTime);
sc.setParameters("msid", host.getManagementServerId());
}
long newUpdateCount = host.incrUpdated();
UpdateBuilder ub = getUpdateBuilder(host);
ub.set(host, _statusAttr, newStatus);
if (newStatus.updateManagementServer()) {
if (newStatus.lostConnection()) {
ub.set(host, _msIdAttr, null);
} else {
ub.set(host, _msIdAttr, host.getManagementServerId());
}
if (event.equals(Event.Ping) || event.equals(Event.AgentConnected)) {
ub.set(host, _pingTimeAttr, System.currentTimeMillis() >> 10);
}
}
if (event.equals(Event.ManagementServerDown)) {
ub.set(host, _pingTimeAttr, ((System.currentTimeMillis() >> 10) - (10 * 60)));
}
int result = update(ub, sc, null);
assert result <= 1 : "How can this update " + result + " rows? ";
if (result == 0) {
HostVO ho = findById(host.getId());
assert ho != null : "How how how? : " + host.getId();
if (status_logger.isDebugEnabled()) {
StringBuilder str = new StringBuilder("Unable to update host for event:").append(event.toString());
str.append(". Name=").append(host.getName());
str.append("; New=[status=")
.append(newStatus.toString())
.append(":msid=")
.append(newStatus.lostConnection() ? "null" : host.getManagementServerId())
.append(":lastpinged=")
.append(host.getLastPinged())
.append("]");
str.append("; Old=[status=").append(oldStatus.toString()).append(":msid=").append(host.getManagementServerId()).append(":lastpinged=").append(oldPingTime)
.append("]");
str.append("; DB=[status=")
.append(vo.getStatus().toString())
.append(":msid=")
.append(vo.getManagementServerId())
.append(":lastpinged=")
.append(vo.getLastPinged())
.append(":old update count=")
.append(oldUpdateCount)
.append("]");
status_logger.debug(str.toString());
} else {
StringBuilder msg = new StringBuilder("Agent status update: [");
msg.append("id = " + host.getId());
msg.append("; name = " + host.getName());
msg.append("; old status = " + oldStatus);
msg.append("; event = " + event);
msg.append("; new status = " + newStatus);
msg.append("; old update count = " + oldUpdateCount);
msg.append("; new update count = " + newUpdateCount + "]");
status_logger.debug(msg.toString());
}
if (ho.getState() == newStatus) {
status_logger.debug("Host " + ho.getName() + " state has already been updated to " + newStatus);
return true;
}
}
return result > 0;
}
@Override
public boolean updateResourceState(ResourceState oldState, ResourceState.Event event, ResourceState newState, Host vo) {
HostVO host = (HostVO)vo;
SearchBuilder<HostVO> sb = createSearchBuilder();
sb.and("resource_state", sb.entity().getResourceState(), SearchCriteria.Op.EQ);
sb.and("id", sb.entity().getId(), SearchCriteria.Op.EQ);
sb.done();
SearchCriteria<HostVO> sc = sb.create();
sc.setParameters("resource_state", oldState);
sc.setParameters("id", host.getId());
UpdateBuilder ub = getUpdateBuilder(host);
ub.set(host, _resourceStateAttr, newState);
int result = update(ub, sc, null);
assert result <= 1 : "How can this update " + result + " rows? ";
if (state_logger.isDebugEnabled() && result == 0) {
HostVO ho = findById(host.getId());
assert ho != null : "How how how? : " + host.getId();
StringBuilder str = new StringBuilder("Unable to update resource state: [");
str.append("m = " + host.getId());
str.append("; name = " + host.getName());
str.append("; old state = " + oldState);
str.append("; event = " + event);
str.append("; new state = " + newState + "]");
state_logger.debug(str.toString());
} else {
StringBuilder msg = new StringBuilder("Resource state update: [");
msg.append("id = " + host.getId());
msg.append("; name = " + host.getName());
msg.append("; old state = " + oldState);
msg.append("; event = " + event);
msg.append("; new state = " + newState + "]");
state_logger.debug(msg.toString());
}
return result > 0;
}
@Override
public HostVO findByTypeNameAndZoneId(long zoneId, String name, Host.Type type) {
SearchCriteria<HostVO> sc = TypeNameZoneSearch.create();
sc.setParameters("type", type);
sc.setParameters("name", name);
sc.setParameters("zoneId", zoneId);
return findOneBy(sc);
}
@Override
public List<HostVO> findByPodId(Long podId) {
SearchCriteria<HostVO> sc = PodSearch.create();
sc.setParameters("podId", podId);
return listBy(sc);
}
@Override
public List<HostVO> findByClusterId(Long clusterId) {
SearchCriteria<HostVO> sc = ClusterSearch.create();
sc.setParameters("clusterId", clusterId);
return listBy(sc);
}
@Override
public HostVO findByPublicIp(String publicIp) {
SearchCriteria<HostVO> sc = PublicIpAddressSearch.create();
sc.setParameters("publicIpAddress", publicIp);
return findOneBy(sc);
}
@Override
public List<HostVO> findHypervisorHostInCluster(long clusterId) {
SearchCriteria<HostVO> sc = TypeClusterStatusSearch.create();
sc.setParameters("type", Host.Type.Routing);
sc.setParameters("cluster", clusterId);
sc.setParameters("status", Status.Up);
sc.setParameters("resourceState", ResourceState.Enabled);
return listBy(sc);
}
@Override
public List<Long> listAllHosts(long zoneId) {
SearchCriteria<Long> sc = HostIdSearch.create();
sc.addAnd("dataCenterId", SearchCriteria.Op.EQ, zoneId);
return customSearch(sc, null);
}
}
| coverity 1116711: findLostHost trivial try-with-resource inserted
Signed-off-by: Daan Hoogland <[email protected]>
| engine/schema/src/com/cloud/host/dao/HostDaoImpl.java | coverity 1116711: findLostHost trivial try-with-resource inserted | <ide><path>ngine/schema/src/com/cloud/host/dao/HostDaoImpl.java
<ide> @DB
<ide> @Override
<ide> public List<HostVO> findLostHosts(long timeout) {
<del> TransactionLegacy txn = TransactionLegacy.currentTxn();
<del> PreparedStatement pstmt = null;
<ide> List<HostVO> result = new ArrayList<HostVO>();
<del> ResultSet rs = null;
<del> try {
<del> String sql =
<add> String sql =
<ide> "select h.id from host h left join cluster c on h.cluster_id=c.id where h.mgmt_server_id is not null and h.last_ping < ? and h.status in ('Up', 'Updating', 'Disconnected', 'Connecting') and h.type not in ('ExternalFirewall', 'ExternalLoadBalancer', 'TrafficMonitor', 'SecondaryStorage', 'LocalSecondaryStorage', 'L2Networking') and (h.cluster_id is null or c.managed_state = 'Managed') ;";
<del> pstmt = txn.prepareStatement(sql);
<add> try (
<add> TransactionLegacy txn = TransactionLegacy.currentTxn();
<add> PreparedStatement pstmt = txn.prepareStatement(sql);) {
<ide> pstmt.setLong(1, timeout);
<del> rs = pstmt.executeQuery();
<del> while (rs.next()) {
<del> long id = rs.getLong(1); //ID column
<del> result.add(findById(id));
<del> }
<del> } catch (Exception e) {
<add> try (ResultSet rs = pstmt.executeQuery();) {
<add> while (rs.next()) {
<add> long id = rs.getLong(1); //ID column
<add> result.add(findById(id));
<add> }
<add> }
<add> } catch (SQLException e) {
<ide> s_logger.warn("Exception: ", e);
<del> } finally {
<del> try {
<del> if (rs != null) {
<del> rs.close();
<del> }
<del> if (pstmt != null) {
<del> pstmt.close();
<del> }
<del> } catch (SQLException e) {
<del> }
<ide> }
<ide> return result;
<ide> } |
|
Java | apache-2.0 | error: pathspec 'mavenproject1/src/main/java/fasam/global/entidades/Artigo.java' did not match any file(s) known to git
| 5448ae1f3637e40ad2104c7f1b86af0a54be6593 | 1 | FASAM-ES/Global | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package fasam.global.entidades;
/**
*
* @author Aluno
*/
public class Artigo {
}
| mavenproject1/src/main/java/fasam/global/entidades/Artigo.java | Incluindo classe artigo | mavenproject1/src/main/java/fasam/global/entidades/Artigo.java | Incluindo classe artigo | <ide><path>avenproject1/src/main/java/fasam/global/entidades/Artigo.java
<add>/*
<add> * To change this template, choose Tools | Templates
<add> * and open the template in the editor.
<add> */
<add>package fasam.global.entidades;
<add>
<add>/**
<add> *
<add> * @author Aluno
<add> */
<add>public class Artigo {
<add>
<add>} |
|
JavaScript | mit | ee4bfc627bb4e00f386db4b880fba9199688d63c | 0 | kevinb7/iframe-overlay,kevinbarabash/iframe-overlay | /*global describe, beforeEach, afterEach, it */
describe("Iframe Overlay", function () {
var iframe, listener, overlay, overlayElement;
beforeEach(function (done) {
iframe = document.createElement("iframe");
iframe.onload = function () {
done();
};
iframe.setAttribute("src", "iframe.html");
var container = document.querySelector("#container");
container.appendChild(iframe);
overlay = iframeOverlay.createOverlay(iframe);
overlayElement = document.querySelector(".overlay");
});
afterEach(function () {
$(".wrapper").remove();
$(document).off("message", listener);
});
describe("Mouse Events", function () {
function testMouseEvent(name) {
it("should transmit " + name + " events", function (done) {
listener = function (e) {
var data = e.originalEvent.data;
expect(data.type).to.be(name);
expect(data.x).to.be(200);
expect(data.y).to.be(100);
expect(data.shiftKey).to.be(true);
expect(data.altKey).to.be(true);
expect(data.metaKey).to.be(true);
expect(data.ctrlKey).to.be(true);
$(window).off("message", listener);
done();
};
$(window).on("message", listener);
EventSim.simulate(overlayElement, name, { clientX: 200, clientY: 100, shiftKey: true, altKey: true, metaKey: true, ctrlKey: true });
});
}
var mouseEvents = ["click", "dblclick", "mousedown", "mousemove", "mouseover", "mouseout"];
mouseEvents.forEach(testMouseEvent);
it("should transmit mouseup events", function (done) {
listener = function (e) {
var data = e.originalEvent.data;
if (data.type === "mouseup") {
expect(data.type).to.be("mouseup");
expect(data.x).to.be(200);
expect(data.y).to.be(100);
expect(data.shiftKey).to.be(true);
expect(data.altKey).to.be(true);
expect(data.metaKey).to.be(true);
expect(data.ctrlKey).to.be(true);
$(window).off("message", listener);
done();
}
};
$(window).on("message", listener);
EventSim.simulate(overlayElement, "mousedown", { clientX: 200, clientY: 100, shiftKey: true, altKey: true, metaKey: true, ctrlKey: true });
EventSim.simulate(window, "mouseup", { clientX: 200, clientY: 100, shiftKey: true, altKey: true, metaKey: true, ctrlKey: true });
});
});
describe("Keyboard Events", function () {
function testKeyboardEvent(name) {
it("should transmit " + name + " events", function (done) {
listener = function (e) {
var data = e.originalEvent.data;
expect(data.type).to.be(name);
expect(data.keyCode).to.be(65);
expect(data.shiftKey).to.be(true);
expect(data.altKey).to.be(true);
expect(data.metaKey).to.be(true);
expect(data.ctrlKey).to.be(true);
$(window).off("message", listener);
done();
};
$(window).on("message", listener);
EventSim.simulate(overlayElement, name, { keyCode: 65, shiftKey: true, altKey: true, metaKey: true, ctrlKey: true });
});
}
var mouseEvents = ["keydown", "keyup", "keypress"];
mouseEvents.forEach(testKeyboardEvent);
});
describe("Sequences of events", function () {
it("should send all events if it isn't paused", function (done) {
var eventCount = 0;
listener = function (e) {
eventCount++;
};
setTimeout(function () {
expect(eventCount).to.be(3);
$(window).off("message", listener); // cleanup
done();
}, 200);
$(window).on("message", listener);
EventSim.simulate(overlayElement, "mousedown", { clientX: 200, clientY: 100 });
// pause before sending the next event otherwise there's not enough time for the listener to set the paused flag
// in practice this is perfectly acceptable because even if a user is spamming us by mashing a physical keyboard
// there will still be slight delays in between
setTimeout(function () {
EventSim.simulate(window, "mousemove", { clientX: 200, clientY: 100 });
EventSim.simulate(window, "mouseup", { clientX: 200, clientY: 100 });
}, 50);
});
it("should not send events after being paused", function (done) {
var eventCount = 0;
listener = function (e) {
var data = e.originalEvent.data;
if (data.type === "mousedown") {
overlay.pause();
}
eventCount++;
};
setTimeout(function () {
expect(eventCount).to.be(1);
$(window).off("message", listener); // cleanup
done();
}, 200);
$(window).on("message", listener);
EventSim.simulate(overlayElement, "mousedown", { clientX: 200, clientY: 100 });
// pause before sending the next event otherwise there's not enough time for the listener to set the paused flag
// in practice this is perfectly acceptable because even if a user is spamming us by mashing a physical keyboard
// there will still be slight delays in between
setTimeout(function () {
EventSim.simulate(window, "mousemove", { clientX: 200, clientY: 100 });
EventSim.simulate(window, "mouseup", { clientX: 200, clientY: 100 });
}, 50);
});
it("should queue events and trigger then after resuming a paused instance", function (done) {
var eventCount = 0;
listener = function (e) {
var data = e.originalEvent.data;
if (data.type === "mousedown") {
overlay.pause();
}
eventCount++;
};
setTimeout(function () {
expect(eventCount).to.be(3);
$(window).off("message", listener); // cleanup
done();
}, 200);
$(window).on("message", listener);
EventSim.simulate(overlayElement, "mousedown", { clientX: 200, clientY: 100 });
// pause before sending the next event otherwise there's not enough time for the listener to set the paused flag
// in practice this is perfectly acceptable because even if a user is spamming us by mashing a physical keyboard
// there will still be slight delays in between
setTimeout(function () {
EventSim.simulate(window, "mousemove", { clientX: 200, clientY: 100 });
EventSim.simulate(window, "mouseup", { clientX: 200, clientY: 100 });
setTimeout(function () {
overlay.resume();
}, 30);
}, 30);
});
it("should trigger keyboard events with the right keyCode", function (done) {
var keyCodes = [65, 97, 65, 66, 98, 66, 67, 99, 67];
var eventCount = 0;
listener = function (e) {
var data = e.originalEvent.data;
if (data.type === "keydown") {
overlay.pause();
}
expect(data.keyCode).to.be(keyCodes[eventCount]);
eventCount++;
};
setTimeout(function () {
expect(eventCount).to.be(9);
$(window).off("message", listener); // cleanup
done();
}, 500);
$(window).on("message", listener);
EventSim.simulate(overlayElement, "keydown", { keyCode: 65 });
EventSim.simulate(overlayElement, "keypress", { keyCode: 97 });
EventSim.simulate(overlayElement, "keyup", { keyCode: 65 });
// pause before sending the next event otherwise there's not enough time for the listener to set the paused flag
// in practice this is perfectly acceptable because even if a user is spamming us by mashing a physical keyboard
// there will still be slight delays in between
setTimeout(function () {
EventSim.simulate(overlayElement, "keydown", { keyCode: 66 });
EventSim.simulate(overlayElement, "keypress", { keyCode: 98 });
EventSim.simulate(overlayElement, "keyup", { keyCode: 66 });
setTimeout(function () {
EventSim.simulate(overlayElement, "keydown", { keyCode: 67 });
EventSim.simulate(overlayElement, "keypress", { keyCode: 99 });
EventSim.simulate(overlayElement, "keyup", { keyCode: 67 });
setTimeout(function () {
overlay.resume();
setTimeout(function () {
overlay.resume();
setTimeout(function () {
overlay.resume();
}, 50);
}, 50);
}, 50);
}, 30);
}, 30);
});
it.only("should trigger keyboard events with the right keyCode (version 2)", function (done) {
var keyCodes = [65, 97, 65, 66, 98, 66, 67, 99, 67];
var eventCount = 0;
listener = function (e) {
var data = e.originalEvent.data;
if (data.type === "keydown") {
overlay.pause();
}
expect(data.keyCode).to.be(keyCodes[eventCount]);
eventCount++;
};
setTimeout(function () {
expect(eventCount).to.be(9);
$(window).off("message", listener); // cleanup
done();
}, 500);
$(window).on("message", listener);
EventSim.simulate(overlayElement, "keydown", { keyCode: 65 });
EventSim.simulate(overlayElement, "keypress", { keyCode: 97 });
EventSim.simulate(overlayElement, "keyup", { keyCode: 65 });
// pause before sending the next event otherwise there's not enough time for the listener to set the paused flag
// in practice this is perfectly acceptable because even if a user is spamming us by mashing a physical keyboard
// there will still be slight delays in between
setTimeout(function () {
EventSim.simulate(overlayElement, "keydown", { keyCode: 66 });
EventSim.simulate(overlayElement, "keypress", { keyCode: 98 });
EventSim.simulate(overlayElement, "keyup", { keyCode: 66 });
setTimeout(function () {
EventSim.simulate(overlayElement, "keydown", { keyCode: 67 });
EventSim.simulate(overlayElement, "keypress", { keyCode: 99 });
EventSim.simulate(overlayElement, "keyup", { keyCode: 67 });
setTimeout(function () {
overlay.resume();
setTimeout(function () {
overlay.resume();
setTimeout(function () {
overlay.resume();
}, 100);
}, 100);
}, 100);
}, 30);
}, 30);
});
});
});
| test/test-spec.js | /*global describe, beforeEach, afterEach, it */
describe("Iframe Overlay", function () {
var iframe, listener, overlay, overlayElement;
beforeEach(function (done) {
iframe = document.createElement("iframe");
iframe.onload = function () {
done();
};
iframe.setAttribute("src", "iframe.html");
var container = document.querySelector("#container");
container.appendChild(iframe);
overlay = iframeOverlay.createOverlay(iframe);
overlayElement = document.querySelector(".overlay");
});
afterEach(function () {
$(".wrapper").remove();
$(document).off("message", listener);
});
describe("Mouse Events", function () {
function testMouseEvent(name) {
it("should transmit " + name + " events", function (done) {
listener = function (e) {
var data = e.originalEvent.data;
expect(data.type).to.be(name);
expect(data.x).to.be(200);
expect(data.y).to.be(100);
expect(data.shiftKey).to.be(true);
expect(data.altKey).to.be(true);
expect(data.metaKey).to.be(true);
expect(data.ctrlKey).to.be(true);
$(window).off("message", listener);
done();
};
$(window).on("message", listener);
EventSim.simulate(overlayElement, name, { clientX: 200, clientY: 100, shiftKey: true, altKey: true, metaKey: true, ctrlKey: true });
});
}
var mouseEvents = ["click", "dblclick", "mousedown", "mousemove", "mouseover", "mouseout"];
mouseEvents.forEach(testMouseEvent);
it("should transmit mouseup events", function (done) {
listener = function (e) {
var data = e.originalEvent.data;
if (data.type === "mouseup") {
expect(data.type).to.be("mouseup");
expect(data.x).to.be(200);
expect(data.y).to.be(100);
expect(data.shiftKey).to.be(true);
expect(data.altKey).to.be(true);
expect(data.metaKey).to.be(true);
expect(data.ctrlKey).to.be(true);
$(window).off("message", listener);
done();
}
};
$(window).on("message", listener);
EventSim.simulate(overlayElement, "mousedown", { clientX: 200, clientY: 100, shiftKey: true, altKey: true, metaKey: true, ctrlKey: true });
EventSim.simulate(window, "mouseup", { clientX: 200, clientY: 100, shiftKey: true, altKey: true, metaKey: true, ctrlKey: true });
});
});
describe("Keyboard Events", function () {
function testKeyboardEvent(name) {
it("should transmit " + name + " events", function (done) {
listener = function (e) {
var data = e.originalEvent.data;
expect(data.type).to.be(name);
expect(data.keyCode).to.be(65);
expect(data.shiftKey).to.be(true);
expect(data.altKey).to.be(true);
expect(data.metaKey).to.be(true);
expect(data.ctrlKey).to.be(true);
$(window).off("message", listener);
done();
};
$(window).on("message", listener);
EventSim.simulate(overlayElement, name, { keyCode: 65, shiftKey: true, altKey: true, metaKey: true, ctrlKey: true });
});
}
var mouseEvents = ["keydown", "keyup", "keypress"];
mouseEvents.forEach(testKeyboardEvent);
});
describe("Sequences of events", function () {
it("should send all events if it isn't paused", function (done) {
var eventCount = 0;
listener = function (e) {
eventCount++;
};
setTimeout(function () {
expect(eventCount).to.be(3);
$(window).off("message", listener); // cleanup
done();
}, 200);
$(window).on("message", listener);
EventSim.simulate(overlayElement, "mousedown", { clientX: 200, clientY: 100 });
// pause before sending the next event otherwise there's not enough time for the listener to set the paused flag
// in practice this is perfectly acceptable because even if a user is spamming us by mashing a physical keyboard
// there will still be slight delays in between
setTimeout(function () {
EventSim.simulate(window, "mousemove", { clientX: 200, clientY: 100 });
EventSim.simulate(window, "mouseup", { clientX: 200, clientY: 100 });
}, 50);
});
it("should not send events after being paused", function (done) {
var eventCount = 0;
listener = function (e) {
var data = e.originalEvent.data;
if (data.type === "mousedown") {
overlay.pause();
}
eventCount++;
};
setTimeout(function () {
expect(eventCount).to.be(1);
$(window).off("message", listener); // cleanup
done();
}, 200);
$(window).on("message", listener);
EventSim.simulate(overlayElement, "mousedown", { clientX: 200, clientY: 100 });
// pause before sending the next event otherwise there's not enough time for the listener to set the paused flag
// in practice this is perfectly acceptable because even if a user is spamming us by mashing a physical keyboard
// there will still be slight delays in between
setTimeout(function () {
EventSim.simulate(window, "mousemove", { clientX: 200, clientY: 100 });
EventSim.simulate(window, "mouseup", { clientX: 200, clientY: 100 });
}, 50);
});
it("should queue events and trigger then after resuming a paused instance", function (done) {
var eventCount = 0;
listener = function (e) {
var data = e.originalEvent.data;
if (data.type === "mousedown") {
overlay.pause();
}
eventCount++;
};
setTimeout(function () {
expect(eventCount).to.be(3);
$(window).off("message", listener); // cleanup
done();
}, 200);
$(window).on("message", listener);
EventSim.simulate(overlayElement, "mousedown", { clientX: 200, clientY: 100 });
// pause before sending the next event otherwise there's not enough time for the listener to set the paused flag
// in practice this is perfectly acceptable because even if a user is spamming us by mashing a physical keyboard
// there will still be slight delays in between
setTimeout(function () {
EventSim.simulate(window, "mousemove", { clientX: 200, clientY: 100 });
EventSim.simulate(window, "mouseup", { clientX: 200, clientY: 100 });
setTimeout(function () {
overlay.resume();
}, 30);
}, 30);
});
it("should trigger keyboard events with the right keyCode", function (done) {
var keyCodes = [65, 66, 67];
var eventCount = 0;
listener = function (e) {
var data = e.originalEvent.data;
overlay.pause();
expect(data.keyCode).to.be(keyCodes[eventCount++]);
};
setTimeout(function () {
expect(eventCount).to.be(3);
$(window).off("message", listener); // cleanup
done();
}, 300);
$(window).on("message", listener);
EventSim.simulate(overlayElement, "keydown", { keyCode: 65 });
// pause before sending the next event otherwise there's not enough time for the listener to set the paused flag
// in practice this is perfectly acceptable because even if a user is spamming us by mashing a physical keyboard
// there will still be slight delays in between
setTimeout(function () {
EventSim.simulate(overlayElement, "keydown", { keyCode: 66 });
setTimeout(function () {
EventSim.simulate(overlayElement, "keydown", { keyCode: 67 });
setTimeout(function () {
overlay.resume();
setTimeout(function () {
overlay.resume();
}, 30);
}, 30);
}, 30);
}, 30);
});
});
});
| added some better tests
| test/test-spec.js | added some better tests | <ide><path>est/test-spec.js
<ide> });
<ide>
<ide> it("should trigger keyboard events with the right keyCode", function (done) {
<del> var keyCodes = [65, 66, 67];
<del> var eventCount = 0;
<del> listener = function (e) {
<del> var data = e.originalEvent.data;
<del> overlay.pause();
<del> expect(data.keyCode).to.be(keyCodes[eventCount++]);
<del> };
<del>
<del> setTimeout(function () {
<del> expect(eventCount).to.be(3);
<del> $(window).off("message", listener); // cleanup
<del> done();
<del> }, 300);
<add> var keyCodes = [65, 97, 65, 66, 98, 66, 67, 99, 67];
<add> var eventCount = 0;
<add> listener = function (e) {
<add> var data = e.originalEvent.data;
<add> if (data.type === "keydown") {
<add> overlay.pause();
<add> }
<add> expect(data.keyCode).to.be(keyCodes[eventCount]);
<add> eventCount++;
<add> };
<add>
<add> setTimeout(function () {
<add> expect(eventCount).to.be(9);
<add> $(window).off("message", listener); // cleanup
<add> done();
<add> }, 500);
<ide>
<ide> $(window).on("message", listener);
<ide>
<ide> EventSim.simulate(overlayElement, "keydown", { keyCode: 65 });
<add> EventSim.simulate(overlayElement, "keypress", { keyCode: 97 });
<add> EventSim.simulate(overlayElement, "keyup", { keyCode: 65 });
<add>
<ide> // pause before sending the next event otherwise there's not enough time for the listener to set the paused flag
<ide> // in practice this is perfectly acceptable because even if a user is spamming us by mashing a physical keyboard
<ide> // there will still be slight delays in between
<ide> setTimeout(function () {
<ide> EventSim.simulate(overlayElement, "keydown", { keyCode: 66 });
<add> EventSim.simulate(overlayElement, "keypress", { keyCode: 98 });
<add> EventSim.simulate(overlayElement, "keyup", { keyCode: 66 });
<ide> setTimeout(function () {
<ide> EventSim.simulate(overlayElement, "keydown", { keyCode: 67 });
<add> EventSim.simulate(overlayElement, "keypress", { keyCode: 99 });
<add> EventSim.simulate(overlayElement, "keyup", { keyCode: 67 });
<ide> setTimeout(function () {
<ide> overlay.resume();
<ide> setTimeout(function () {
<ide> overlay.resume();
<del> }, 30);
<del> }, 30);
<add> setTimeout(function () {
<add> overlay.resume();
<add> }, 50);
<add> }, 50);
<add> }, 50);
<ide> }, 30);
<ide> }, 30);
<ide> });
<add>
<add> it.only("should trigger keyboard events with the right keyCode (version 2)", function (done) {
<add> var keyCodes = [65, 97, 65, 66, 98, 66, 67, 99, 67];
<add> var eventCount = 0;
<add> listener = function (e) {
<add> var data = e.originalEvent.data;
<add> if (data.type === "keydown") {
<add> overlay.pause();
<add> }
<add> expect(data.keyCode).to.be(keyCodes[eventCount]);
<add> eventCount++;
<add> };
<add>
<add> setTimeout(function () {
<add> expect(eventCount).to.be(9);
<add> $(window).off("message", listener); // cleanup
<add> done();
<add> }, 500);
<add>
<add> $(window).on("message", listener);
<add>
<add> EventSim.simulate(overlayElement, "keydown", { keyCode: 65 });
<add> EventSim.simulate(overlayElement, "keypress", { keyCode: 97 });
<add> EventSim.simulate(overlayElement, "keyup", { keyCode: 65 });
<add>
<add> // pause before sending the next event otherwise there's not enough time for the listener to set the paused flag
<add> // in practice this is perfectly acceptable because even if a user is spamming us by mashing a physical keyboard
<add> // there will still be slight delays in between
<add> setTimeout(function () {
<add> EventSim.simulate(overlayElement, "keydown", { keyCode: 66 });
<add> EventSim.simulate(overlayElement, "keypress", { keyCode: 98 });
<add> EventSim.simulate(overlayElement, "keyup", { keyCode: 66 });
<add> setTimeout(function () {
<add> EventSim.simulate(overlayElement, "keydown", { keyCode: 67 });
<add> EventSim.simulate(overlayElement, "keypress", { keyCode: 99 });
<add> EventSim.simulate(overlayElement, "keyup", { keyCode: 67 });
<add> setTimeout(function () {
<add> overlay.resume();
<add> setTimeout(function () {
<add> overlay.resume();
<add> setTimeout(function () {
<add> overlay.resume();
<add> }, 100);
<add> }, 100);
<add> }, 100);
<add> }, 30);
<add> }, 30);
<add> });
<ide> });
<ide> }); |
|
JavaScript | mit | 051d3ffa493ead759e3e2a0a568cb17d0e8f0c25 | 0 | tkless/ccm-components,tkless/ccm-components | /**
* @overview ccm component for real time Forum
* @author Tea Kless <[email protected]>, 2017
* @license The MIT License (MIT)
*/
( function () {
var component = {
name: 'forum',
version:[ 1,0,0 ],
/**
* recommended used framework version
* @type {string}
*/
ccm: {
url: 'https://akless.github.io/ccm/version/ccm-14.3.0.min.js',
integrity: 'sha384-4q30fhc2E3uY9omytSc6dKdoMNQ37dSozhTxgG/wH/9lv+N37TBhwd1jg/u03bRt',
crossorigin: 'anonymous'
},
config: {
templates: {
"main": {
"class": "container-fluid",
"inner": [
{
"id": "questions-view",
"inner":
[
{
"id": "questions-list"
},
{
"tag": "hr"
},
{
"tag": "form",
"onsubmit": "%submit%",
"class": "form-horizontal",
"inner": [
{
"class": "form-group col-sm-12",
"id": "new-title",
"inner":
[
{
"tag": "label",
"class": "control-label col-sm-1",
"for": "%for%",
"inner": "%inner%"
},
{
"class": "col-sm-11",
"inner": {
"tag": "input",
"type": "%type%",
"required": true,
"class": "form-control",
"id":"%id%",
"placeholder": "%value%"
}
}
]
},
{
"id": "editor",
"class": "form-group col-sm-12",
"inner": [
{
"tag": "input",
"name": "new",
"type": "hidden"
},
{
"id": "editor-container"
}
]
},
{
"id": "button",
"class": "form-group col-sm-12",
"inner": {
"class": "row",
"inner": {
"tag": "button",
"type": "submit",
"class": "btn btn-primary",
"inner": "Post new Question"
}
}
}
]
}
]
},
{
"id": "answers-view"
}
]
},
"answers": {
"inner": [
{
"tag": "ul",
"class": "nav nav-tabs",
"inner": [
{
"tag": "li",
"class": "active",
"onclick": "%render_questions%",
"inner": { "tag": "a", "inner": "Questions" }
}
]
},
{
"id": "answers"
}
]
},
"question": {
"class": "question row",
"inner": [
{
"class": "voting-overview col-md-2 text-center",
"inner":
[
{
"class": "row",
"inner": [
{
"class": "vote-sum col-md-6 col-xs-6",
"inner": "%votes%"
},
{
"class": "answer_sum col-md-6 col-xs-6",
"inner": "%answers%"
}
]
},
{
"class": "row",
"inner": [
{
"class": "vote-label col-md-6 col-xs-6",
"inner": "votes"
},
{
"class": "vote-label col-md-6 col-xs-6",
"inner": "answers"
}
]
}
]
},
{
"class": "question-summery col-md-10",
"onclick": "%render_answers%",
"inner": {
"tag": "blockquote",
"inner":[
{
"tag": "p",
"class": "question_title",
"inner": "%title%"
},
{
"tag": "footer",
"class": "question_footer",
"inner": "%signatur%"
}
]
}
}
]
}
},
data: { store: [ 'ccm.store' ] },
editor: [ 'ccm.component', 'https://tkless.github.io/ccm-components/editor/versions/ccm.editor-1.0.1.js',
{ 'settings.modules': {
syntax: true,
toolbar: [
[{ 'size': ['small', false, 'large', 'huge'] }], // custom dropdown
['bold', 'italic', 'underline'], // toggled buttons
['blockquote', 'code-block'],
[{ 'header': 1 }, { 'header': 2 }], // custom button values
[{ 'list': 'ordered'}, { 'list': 'bullet' }],
[{ 'script': 'sub'}, { 'script': 'super' }], // superscript/subscript
[{ 'indent': '-1'}, { 'indent': '+1' }], // outdent/indent
[{ 'color': [] }, { 'background': [] }], // dropdown with defaults from theme
[{ 'align': [] }]
]
} }
],
question: [ 'ccm.component', 'https://tkless.github.io/ccm-components/question/versions/ccm.question-1.0.0.js' ],
libs: [ 'ccm.load',
{ context: 'head', url: 'https://tkless.github.io/ccm-components/lib/bootstrap/css/font-face.css' },
'https://tkless.github.io/ccm-components/lib/bootstrap/css/bootstrap.css',
'https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js',
'https://tkless.github.io/ccm-components/forum/resources/default.css'
]
},
Instance: function () {
var self = this;
this.start = function (callback) {
self.ccm.helper.dataset(self.data.store, self.data.key, function ( dataset ) {
var editor;
if( !dataset.questions ) dataset.questions = [];
self.ccm.helper.setContent( self.element, self.ccm.helper.html( self.templates.main, {
for: "title",
inner: "Title",
id: "title",
type: "text",
value: "What is your Question ?",
submit: function ( event ) { event.preventDefault(); newQuestion(); }
} ) );
renderQuestions();
renderEditor();
function renderQuestions() {
dataset.questions.map( renderQuestion );
function renderQuestion( question_key ) {
// start question instance
self.question.start( { 'data.key': question_key }, function ( question_instance ) {
// get question data of launched question instance
question_instance.data.store.get( question_instance.data.key, function ( question_data ) {
// get voting instance of question instance
question_instance.voting.instance( question_data.voting, function ( voting_instance ) {
self.element.querySelector( '#questions-list' ).appendChild( self.ccm.helper.html( self.templates.question, {
title: question_data.title,
signatur: question_data.user + ' ' + moment( question_data.date ).fromNow(),
votes: voting_instance.getValue(),
answers: question_data.answers.length,
render_answers: function () {
self.element.querySelector( '#questions-view' ).style.display = 'none';
self.ccm.helper.setContent( self.element.querySelector( '#answers-view' ), self.ccm.helper.html( self.templates.answers, {
render_questions: function () {
self.element.querySelector( '#answers-view' ).innerHTML = '';
self.element.querySelector( '#questions-view' ).style.display = 'block';
}
} ) );
self.element.querySelector( '#answers' ).appendChild( question_instance.root );
}
} ) );
} );
} );
} )
}
}
function renderEditor() {
self.editor.start( function ( instance ) {
self.element.querySelector( '#editor-container' ).appendChild( instance.root );
editor = instance;
} );
}
function newQuestion() {
if ( !self.user ) return;
self.user.login( function () {
// is there the user input in editor?
if ( editor.get().getLength() <= 1 )
alert( 'Give Title and Text in the fields!!!' );
return;
var question_key = "forum_" + dataset.key + "_" + ( dataset.questions.length + 1 );
var new_question_data = {
"key": question_key,
"date": moment().format(),
"user": self.user.data().name,
"title": self.element.querySelector( 'input[ id = title ]' ).value,
"content": editor.get().root.innerHTML,
"voting": "question_" + dataset.key + "_" + ( dataset.questions.length + 1 ),
"answers": []
};
self.question.instance( function ( new_question_inst ) {
new_question_inst.data.store.set( new_question_data, function () {
dataset.questions.push( question_key );
self.data.store.set( dataset, function () { self.start(); } );
} );
} );
} );
}
if ( callback ) callback();
} );
};
}
};
function p(){window.ccm[v].component(component)}var f="ccm."+component.name+(component.version?"-"+component.version.join("."):"")+".js";if(window.ccm&&null===window.ccm.files[f])window.ccm.files[f]=component;else{var n=window.ccm&&window.ccm.components[component.name];n&&n.ccm&&(component.ccm=n.ccm),"string"==typeof component.ccm&&(component.ccm={url:component.ccm});var v=component.ccm.url.split("/").pop().split("-");if(v.length>1?(v=v[1].split("."),v.pop(),"min"===v[v.length-1]&&v.pop(),v=v.join(".")):v="latest",window.ccm&&window.ccm[v])p();else{var e=document.createElement("script");document.head.appendChild(e),component.ccm.integrity&&e.setAttribute("integrity",component.ccm.integrity),component.ccm.crossorigin&&e.setAttribute("crossorigin",component.ccm.crossorigin),e.onload=function(){p(),document.head.removeChild(e)},e.src=component.ccm.url}}
}() ); | forum/versions/ccm.forum-1.0.0.js | /**
* @overview ccm component for real time Forum
* @author Tea Kless <[email protected]>, 2017
* @license The MIT License (MIT)
*/
( function () {
var component = {
name: 'forum',
version:[ 1,0,0 ],
ccm: {
url: 'https://akless.github.io/ccm/version/ccm-10.0.0.min.js',
integrity: 'sha384-AND32Wbfnmb3f2vRMHkXSJpi81oFmy3eO1FbMHb5i2XOzwg0z+T1de180FUH1Tjt',
crossorigin: 'anonymous'
},
config: {
templates: {
"main": {
"class": "container-fluid",
"inner": [
{
"id": "questions-view",
"inner":
[
{
"id": "questions-list"
},
{
"tag": "hr"
},
{
"tag": "form",
"onsubmit": "%submit%",
"class": "form-horizontal",
"inner": [
{
"class": "form-group col-sm-12",
"id": "new-title",
"inner":
[
{
"tag": "label",
"class": "control-label col-sm-1",
"for": "%for%",
"inner": "%inner%"
},
{
"class": "col-sm-11",
"inner": {
"tag": "input",
"type": "%type%",
"required": true,
"class": "form-control",
"id":"%id%",
"placeholder": "%value%"
}
}
]
},
{
"id": "editor",
"class": "form-group col-sm-12",
"inner": [
{
"tag": "input",
"name": "new",
"type": "hidden"
},
{
"id": "editor-container"
}
]
},
{
"id": "button",
"class": "form-group col-sm-12",
"inner": {
"class": "row",
"inner": {
"tag": "button",
"type": "submit",
"class": "btn btn-primary",
"inner": "Post new Question"
}
}
}
]
}
]
},
{
"id": "answers-view"
}
]
},
"answers": {
"inner": [
{
"tag": "ul",
"class": "nav nav-tabs",
"inner": [
{
"tag": "li",
"class": "active",
"onclick": "%render_questions%",
"inner": { "tag": "a", "inner": "Questions" }
}
]
},
{
"id": "answers"
}
]
},
"question": {
"class": "question row",
"inner": [
{
"class": "voting-overview col-md-2 text-center",
"inner":
[
{
"class": "row",
"inner": [
{
"class": "vote-sum col-md-6 col-xs-6",
"inner": "%votes%"
},
{
"class": "answer_sum col-md-6 col-xs-6",
"inner": "%answers%"
}
]
},
{
"class": "row",
"inner": [
{
"class": "vote-label col-md-6 col-xs-6",
"inner": "votes"
},
{
"class": "vote-label col-md-6 col-xs-6",
"inner": "answers"
}
]
}
]
},
{
"class": "question-summery col-md-10",
"onclick": "%render_answers%",
"inner": {
"tag": "blockquote",
"inner":[
{
"tag": "p",
"class": "question_title",
"inner": "%title%"
},
{
"tag": "footer",
"class": "question_footer",
"inner": "%signatur%"
}
]
}
}
]
}
},
data: { store: [ 'ccm.store' ] },
editor: [ 'ccm.component', 'https://tkless.github.io/ccm-components/editor/versions/ccm.editor-1.0.1.js',
{ 'settings.modules': {
syntax: true,
toolbar: [
[{ 'size': ['small', false, 'large', 'huge'] }], // custom dropdown
['bold', 'italic', 'underline'], // toggled buttons
['blockquote', 'code-block'],
[{ 'header': 1 }, { 'header': 2 }], // custom button values
[{ 'list': 'ordered'}, { 'list': 'bullet' }],
[{ 'script': 'sub'}, { 'script': 'super' }], // superscript/subscript
[{ 'indent': '-1'}, { 'indent': '+1' }], // outdent/indent
[{ 'color': [] }, { 'background': [] }], // dropdown with defaults from theme
[{ 'align': [] }]
]
} }
],
question: [ 'ccm.component', 'https://tkless.github.io/ccm-components/question/versions/ccm.question-1.0.0.js' ],
libs: [ 'ccm.load',
{ context: 'head', url: 'https://tkless.github.io/ccm-components/lib/bootstrap/css/font-face.css' },
'https://tkless.github.io/ccm-components/lib/bootstrap/css/bootstrap.css',
'https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js',
'https://tkless.github.io/ccm-components/forum/resources/default.css'
]
},
Instance: function () {
var self = this;
this.start = function (callback) {
self.ccm.helper.dataset(self.data.store, self.data.key, function ( dataset ) {
var editor;
if( !dataset.questions ) dataset.questions = [];
self.ccm.helper.setContent( self.element, self.ccm.helper.html( self.templates.main, {
for: "title",
inner: "Title",
id: "title",
type: "text",
value: "What is your Question ?",
submit: function ( event ) { event.preventDefault(); newQuestion(); }
} ) );
renderQuestions();
renderEditor();
function renderQuestions() {
dataset.questions.map( renderQuestion );
function renderQuestion( question_key ) {
// start question instance
self.question.start( { 'data.key': question_key }, function ( question_instance ) {
// get question data of launched question instance
question_instance.data.store.get( question_instance.data.key, function ( question_data ) {
// get voting instance of question instance
question_instance.voting.instance( question_data.voting, function ( voting_instance ) {
self.element.querySelector( '#questions-list' ).appendChild( self.ccm.helper.html( self.templates.question, {
title: question_data.title,
signatur: question_data.user + ' ' + moment( question_data.date ).fromNow(),
votes: voting_instance.getValue(),
answers: question_data.answers.length,
render_answers: function () {
self.element.querySelector( '#questions-view' ).style.display = 'none';
self.ccm.helper.setContent( self.element.querySelector( '#answers-view' ), self.ccm.helper.html( self.templates.answers, {
render_questions: function () {
self.element.querySelector( '#answers-view' ).innerHTML = '';
self.element.querySelector( '#questions-view' ).style.display = 'block';
}
} ) );
self.element.querySelector( '#answers' ).appendChild( question_instance.root );
}
} ) );
} );
} );
} )
}
}
function renderEditor() {
self.editor.start( function ( instance ) {
self.element.querySelector( '#editor-container' ).appendChild( instance.root );
editor = instance;
} );
}
function newQuestion() {
if ( !self.user ) return;
self.user.login( function () {
// is there the user input in editor?
if ( editor.get().getLength() <= 1 )
alert( 'Give Title and Text in the fields!!!' );
return;
var question_key = "forum_" + dataset.key + "_" + ( dataset.questions.length + 1 );
var new_question_data = {
"key": question_key,
"date": moment().format(),
"user": self.user.data().name,
"title": self.element.querySelector( 'input[ id = title ]' ).value,
"content": editor.get().root.innerHTML,
"voting": "question_" + dataset.key + "_" + ( dataset.questions.length + 1 ),
"answers": []
};
self.question.instance( function ( new_question_inst ) {
new_question_inst.data.store.set( new_question_data, function () {
dataset.questions.push( question_key );
self.data.store.set( dataset, function () { self.start(); } );
} );
} );
} );
}
if ( callback ) callback();
} );
};
}
};
function p(){window.ccm[v].component(component)}var f="ccm."+component.name+(component.version?"-"+component.version.join("."):"")+".js";if(window.ccm&&null===window.ccm.files[f])window.ccm.files[f]=component;else{var n=window.ccm&&window.ccm.components[component.name];n&&n.ccm&&(component.ccm=n.ccm),"string"==typeof component.ccm&&(component.ccm={url:component.ccm});var v=component.ccm.url.split("/").pop().split("-");if(v.length>1?(v=v[1].split("."),v.pop(),"min"===v[v.length-1]&&v.pop(),v=v.join(".")):v="latest",window.ccm&&window.ccm[v])p();else{var e=document.createElement("script");document.head.appendChild(e),component.ccm.integrity&&e.setAttribute("integrity",component.ccm.integrity),component.ccm.crossorigin&&e.setAttribute("crossorigin",component.ccm.crossorigin),e.onload=function(){p(),document.head.removeChild(e)},e.src=component.ccm.url}}
}() ); | add latest stable ccm version
| forum/versions/ccm.forum-1.0.0.js | add latest stable ccm version | <ide><path>orum/versions/ccm.forum-1.0.0.js
<ide> name: 'forum',
<ide> version:[ 1,0,0 ],
<ide>
<add> /**
<add> * recommended used framework version
<add> * @type {string}
<add> */
<ide> ccm: {
<del> url: 'https://akless.github.io/ccm/version/ccm-10.0.0.min.js',
<del> integrity: 'sha384-AND32Wbfnmb3f2vRMHkXSJpi81oFmy3eO1FbMHb5i2XOzwg0z+T1de180FUH1Tjt',
<add> url: 'https://akless.github.io/ccm/version/ccm-14.3.0.min.js',
<add> integrity: 'sha384-4q30fhc2E3uY9omytSc6dKdoMNQ37dSozhTxgG/wH/9lv+N37TBhwd1jg/u03bRt',
<ide> crossorigin: 'anonymous'
<ide> },
<ide> |
|
JavaScript | mit | 9022a7b7bf203261378e451141d0f161c3e5cc31 | 0 | marcostomazini/otima,marcostomazini/otima,marcostomazini/otima | 'use strict';
var RaspiCam = require("raspicam");
/**
* Module dependencies.
*/
exports.index = function(req, res) {
res.render('index', {
user: req.user || null,
request: req
});
};
exports.photo = function(req, res) {
var camera = new RaspiCam({
mode: "photo",
output: "teste.jpg",
w: 180
});
camera.start('timelapse');
camera.stop();
camera.on("read", function(err, timestamp, filename){
//do stuff
console.log(err);
console.log(timestamp);
console.log(filename);
});
res.json({'type': 'success', 'teste': photo});
}; | app/controllers/core.server.controller.js | 'use strict';
var RaspiCam = require("raspicam");
/**
* Module dependencies.
*/
exports.index = function(req, res) {
res.render('index', {
user: req.user || null,
request: req
});
};
exports.photo = function(req, res) {
var camera = new RaspiCam({
mode: "photo",
w: 180
});
camera.start('timelapse');
camera.stop();
camera.on("read", function(err, timestamp, filename){
//do stuff
console.log(err);
console.log(timestamp);
console.log(filename);
});
res.json({'type': 'success', 'teste': photo});
}; | camera 2
| app/controllers/core.server.controller.js | camera 2 | <ide><path>pp/controllers/core.server.controller.js
<ide> exports.photo = function(req, res) {
<ide> var camera = new RaspiCam({
<ide> mode: "photo",
<add> output: "teste.jpg",
<ide> w: 180
<ide> });
<ide> camera.start('timelapse'); |
|
Java | lgpl-2.1 | ebef487dc8150d4b4605d6d44950fb9939f612cc | 0 | xwiki/xwiki-platform,xwiki/xwiki-platform,xwiki/xwiki-platform,pbondoer/xwiki-platform,xwiki/xwiki-platform,pbondoer/xwiki-platform,pbondoer/xwiki-platform,pbondoer/xwiki-platform,pbondoer/xwiki-platform,xwiki/xwiki-platform | /*
* See the NOTICE file distributed with this work for additional
* information regarding copyright ownership.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package com.xpn.xwiki.plugin.applicationmanager.core.doc.objects.classes;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import org.jmock.Mock;
import org.jmock.core.Invocation;
import org.jmock.core.stub.CustomStub;
import org.xwiki.localization.LocalizationContext;
import org.xwiki.security.authorization.ContextualAuthorizationManager;
import com.xpn.xwiki.XWiki;
import com.xpn.xwiki.XWikiContext;
import com.xpn.xwiki.XWikiException;
import com.xpn.xwiki.doc.XWikiDocument;
import com.xpn.xwiki.store.XWikiHibernateStore;
import com.xpn.xwiki.store.XWikiHibernateVersioningStore;
import com.xpn.xwiki.store.XWikiStoreInterface;
import com.xpn.xwiki.store.XWikiVersioningStoreInterface;
import com.xpn.xwiki.test.AbstractBridgedXWikiComponentTestCase;
import com.xpn.xwiki.user.api.XWikiRightService;
/**
* Unit tests for {@link com.xpn.xwiki.plugin.applicationmanager.core.doc.objects.classes.DefaultXObjectDocument}.
*
* @version $Id$
*/
public class DefaultXObjectDocumentTest extends AbstractBridgedXWikiComponentTestCase
{
private XWiki xwiki;
private Mock mockXWikiStore;
private Mock mockXWikiVersioningStore;
private Map<String, XWikiDocument> documents = new HashMap<String, XWikiDocument>();
@Override
protected void setUp() throws Exception
{
super.setUp();
registerMockComponent(ContextualAuthorizationManager.class);
this.xwiki = new XWiki();
getContext().setWiki(this.xwiki);
// //////////////////////////////////////////////////
// XWikiHibernateStore
Mock mockLocalizationContext = registerMockComponent(LocalizationContext.class);
mockLocalizationContext.stubs().method("getCurrentLocale").will(returnValue(Locale.ROOT));
this.mockXWikiStore =
mock(XWikiHibernateStore.class, new Class[] {XWiki.class, XWikiContext.class}, new Object[] {this.xwiki,
getContext()});
this.mockXWikiStore.stubs().method("loadXWikiDoc").will(
new CustomStub("Implements XWikiStoreInterface.loadXWikiDoc")
{
@Override
public Object invoke(Invocation invocation) throws Throwable
{
XWikiDocument shallowDoc = (XWikiDocument) invocation.parameterValues.get(0);
if (documents.containsKey(shallowDoc.getFullName())) {
return documents.get(shallowDoc.getFullName());
} else {
return shallowDoc;
}
}
});
this.mockXWikiStore.stubs().method("saveXWikiDoc").will(
new CustomStub("Implements XWikiStoreInterface.saveXWikiDoc")
{
@Override
public Object invoke(Invocation invocation) throws Throwable
{
XWikiDocument document = (XWikiDocument) invocation.parameterValues.get(0);
document.setNew(false);
document.setStore((XWikiStoreInterface) mockXWikiStore.proxy());
documents.put(document.getFullName(), document);
return null;
}
});
this.mockXWikiStore.stubs().method("getTranslationList").will(returnValue(Collections.EMPTY_LIST));
this.mockXWikiVersioningStore =
mock(XWikiHibernateVersioningStore.class, new Class[] {XWiki.class, XWikiContext.class}, new Object[] {
this.xwiki, getContext()});
this.mockXWikiVersioningStore.stubs().method("getXWikiDocumentArchive").will(returnValue(null));
this.mockXWikiVersioningStore.stubs().method("resetRCSArchive").will(returnValue(null));
this.xwiki.setStore((XWikiStoreInterface) mockXWikiStore.proxy());
this.xwiki.setVersioningStore((XWikiVersioningStoreInterface) mockXWikiVersioningStore.proxy());
// ////////////////////////////////////////////////////////////////////////////////
// XWikiRightService
this.xwiki.setRightService(new XWikiRightService()
{
@Override
public boolean checkAccess(String action, XWikiDocument doc, XWikiContext context) throws XWikiException
{
return true;
}
@Override
public boolean hasAccessLevel(String right, String username, String docname, XWikiContext context)
throws XWikiException
{
return true;
}
@Override
public boolean hasAdminRights(XWikiContext context)
{
return true;
}
@Override
public boolean hasProgrammingRights(XWikiContext context)
{
return true;
}
@Override
public boolean hasProgrammingRights(XWikiDocument doc, XWikiContext context)
{
return true;
}
@Override
public List listAllLevels(XWikiContext context) throws XWikiException
{
return Collections.EMPTY_LIST;
}
@Override
public boolean hasWikiAdminRights(XWikiContext context)
{
return true;
}
});
}
// ///////////////////////////////////////////////////////////////////////////////////////:
// Tests
private final String DEFAULT_SPACE = "Space";
private final String DEFAULT_DOCNAME = "Document";
private final String DEFAULT_DOCFULLNAME = DEFAULT_SPACE + "." + DEFAULT_DOCNAME;
public void testInitXObjectDocumentEmpty() throws XWikiException
{
this.documents.clear();
// ///
XClassManager sclass = XClassManagerTest.DispatchXClassManager.getInstance(getContext());
DefaultXObjectDocument sdoc = (DefaultXObjectDocument) sclass.newXObjectDocument(getContext());
assertNotNull(sdoc);
assertTrue(sdoc.isNew());
com.xpn.xwiki.api.Object obj = sdoc.getObject(sclass.getClassFullName());
assertNotNull(obj);
assertEquals(sdoc.getXClassManager(), sclass);
}
public void testInitXObjectDocumentDocName() throws XWikiException
{
this.documents.clear();
// ///
XClassManager sclass = XClassManagerTest.DispatchXClassManager.getInstance(getContext());
DefaultXObjectDocument sdoc =
(DefaultXObjectDocument) sclass.newXObjectDocument(DEFAULT_DOCFULLNAME, 0, getContext());
assertNotNull(sdoc);
assertTrue(sdoc.isNew());
com.xpn.xwiki.api.Object obj = sdoc.getObject(sclass.getClassFullName());
assertNotNull(obj);
assertEquals(sdoc.getXClassManager(), sclass);
}
public void testInitXObjectDocumentDocNameExists() throws XWikiException
{
this.documents.clear();
// ///
XWikiDocument doc = this.xwiki.getDocument(DEFAULT_DOCFULLNAME, getContext());
this.xwiki.saveDocument(doc, getContext());
XClassManager sclass = XClassManagerTest.DispatchXClassManager.getInstance(getContext());
DefaultXObjectDocument sdoc =
(DefaultXObjectDocument) sclass.newXObjectDocument(DEFAULT_DOCFULLNAME, 0, getContext());
assertNotNull(sdoc);
assertTrue(sdoc.isNew());
com.xpn.xwiki.api.Object obj = sdoc.getObject(sclass.getClassFullName());
assertNotNull(obj);
assertEquals(sdoc.getXClassManager(), sclass);
}
public void testMergeObject() throws XWikiException
{
XClassManager sclass = XClassManagerTest.DispatchXClassManager.getInstance(getContext());
DefaultXObjectDocument sdoc1 = (DefaultXObjectDocument) sclass.newXObjectDocument(getContext());
DefaultXObjectDocument sdoc2 = (DefaultXObjectDocument) sclass.newXObjectDocument(getContext());
sdoc1.setStringValue(XClassManagerTest.FIELD_string, "valuesdoc1");
sdoc1.setStringValue(XClassManagerTest.FIELD_string2, "value2sdoc1");
sdoc2.setStringValue(XClassManagerTest.FIELD_string, "valuesdoc2");
sdoc2.setIntValue(XClassManagerTest.FIELD_int, 2);
sdoc1.mergeObject(sdoc2);
assertEquals("The field is not overwritten", sdoc1.getStringValue(XClassManagerTest.FIELD_string),
sdoc2.getStringValue(XClassManagerTest.FIELD_string));
assertEquals("The field is removed", "value2sdoc1", sdoc1
.getStringValue(XClassManagerTest.FIELD_string2));
assertEquals("The field is not added", sdoc1.getIntValue(XClassManagerTest.FIELD_int), sdoc1
.getIntValue(XClassManagerTest.FIELD_int));
}
}
| xwiki-platform-core/xwiki-platform-application-manager/xwiki-platform-application-manager-api/src/test/java/com/xpn/xwiki/plugin/applicationmanager/core/doc/objects/classes/DefaultXObjectDocumentTest.java | /*
* See the NOTICE file distributed with this work for additional
* information regarding copyright ownership.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package com.xpn.xwiki.plugin.applicationmanager.core.doc.objects.classes;
import com.xpn.xwiki.XWiki;
import com.xpn.xwiki.XWikiContext;
import com.xpn.xwiki.XWikiException;
import com.xpn.xwiki.doc.XWikiDocument;
import com.xpn.xwiki.store.XWikiHibernateStore;
import com.xpn.xwiki.store.XWikiHibernateVersioningStore;
import com.xpn.xwiki.store.XWikiStoreInterface;
import com.xpn.xwiki.store.XWikiVersioningStoreInterface;
import com.xpn.xwiki.test.AbstractBridgedXWikiComponentTestCase;
import com.xpn.xwiki.user.api.XWikiRightService;
import org.jmock.Mock;
import org.jmock.core.Invocation;
import org.jmock.core.stub.CustomStub;
import org.xwiki.localization.LocalizationContext;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
/**
* Unit tests for {@link com.xpn.xwiki.plugin.applicationmanager.core.doc.objects.classes.DefaultXObjectDocument}.
*
* @version $Id$
*/
public class DefaultXObjectDocumentTest extends AbstractBridgedXWikiComponentTestCase
{
private XWiki xwiki;
private Mock mockXWikiStore;
private Mock mockXWikiVersioningStore;
private Map<String, XWikiDocument> documents = new HashMap<String, XWikiDocument>();
@Override
protected void setUp() throws Exception
{
super.setUp();
this.xwiki = new XWiki();
getContext().setWiki(this.xwiki);
// //////////////////////////////////////////////////
// XWikiHibernateStore
Mock mockLocalizationContext = registerMockComponent(LocalizationContext.class);
mockLocalizationContext.stubs().method("getCurrentLocale").will(returnValue(Locale.ROOT));
this.mockXWikiStore =
mock(XWikiHibernateStore.class, new Class[] {XWiki.class, XWikiContext.class}, new Object[] {this.xwiki,
getContext()});
this.mockXWikiStore.stubs().method("loadXWikiDoc").will(
new CustomStub("Implements XWikiStoreInterface.loadXWikiDoc")
{
@Override
public Object invoke(Invocation invocation) throws Throwable
{
XWikiDocument shallowDoc = (XWikiDocument) invocation.parameterValues.get(0);
if (documents.containsKey(shallowDoc.getFullName())) {
return documents.get(shallowDoc.getFullName());
} else {
return shallowDoc;
}
}
});
this.mockXWikiStore.stubs().method("saveXWikiDoc").will(
new CustomStub("Implements XWikiStoreInterface.saveXWikiDoc")
{
@Override
public Object invoke(Invocation invocation) throws Throwable
{
XWikiDocument document = (XWikiDocument) invocation.parameterValues.get(0);
document.setNew(false);
document.setStore((XWikiStoreInterface) mockXWikiStore.proxy());
documents.put(document.getFullName(), document);
return null;
}
});
this.mockXWikiStore.stubs().method("getTranslationList").will(returnValue(Collections.EMPTY_LIST));
this.mockXWikiVersioningStore =
mock(XWikiHibernateVersioningStore.class, new Class[] {XWiki.class, XWikiContext.class}, new Object[] {
this.xwiki, getContext()});
this.mockXWikiVersioningStore.stubs().method("getXWikiDocumentArchive").will(returnValue(null));
this.mockXWikiVersioningStore.stubs().method("resetRCSArchive").will(returnValue(null));
this.xwiki.setStore((XWikiStoreInterface) mockXWikiStore.proxy());
this.xwiki.setVersioningStore((XWikiVersioningStoreInterface) mockXWikiVersioningStore.proxy());
// ////////////////////////////////////////////////////////////////////////////////
// XWikiRightService
this.xwiki.setRightService(new XWikiRightService()
{
@Override
public boolean checkAccess(String action, XWikiDocument doc, XWikiContext context) throws XWikiException
{
return true;
}
@Override
public boolean hasAccessLevel(String right, String username, String docname, XWikiContext context)
throws XWikiException
{
return true;
}
@Override
public boolean hasAdminRights(XWikiContext context)
{
return true;
}
@Override
public boolean hasProgrammingRights(XWikiContext context)
{
return true;
}
@Override
public boolean hasProgrammingRights(XWikiDocument doc, XWikiContext context)
{
return true;
}
@Override
public List listAllLevels(XWikiContext context) throws XWikiException
{
return Collections.EMPTY_LIST;
}
@Override
public boolean hasWikiAdminRights(XWikiContext context)
{
return true;
}
});
}
// ///////////////////////////////////////////////////////////////////////////////////////:
// Tests
private final String DEFAULT_SPACE = "Space";
private final String DEFAULT_DOCNAME = "Document";
private final String DEFAULT_DOCFULLNAME = DEFAULT_SPACE + "." + DEFAULT_DOCNAME;
public void testInitXObjectDocumentEmpty() throws XWikiException
{
this.documents.clear();
// ///
XClassManager sclass = XClassManagerTest.DispatchXClassManager.getInstance(getContext());
DefaultXObjectDocument sdoc = (DefaultXObjectDocument) sclass.newXObjectDocument(getContext());
assertNotNull(sdoc);
assertTrue(sdoc.isNew());
com.xpn.xwiki.api.Object obj = sdoc.getObject(sclass.getClassFullName());
assertNotNull(obj);
assertEquals(sdoc.getXClassManager(), sclass);
}
public void testInitXObjectDocumentDocName() throws XWikiException
{
this.documents.clear();
// ///
XClassManager sclass = XClassManagerTest.DispatchXClassManager.getInstance(getContext());
DefaultXObjectDocument sdoc =
(DefaultXObjectDocument) sclass.newXObjectDocument(DEFAULT_DOCFULLNAME, 0, getContext());
assertNotNull(sdoc);
assertTrue(sdoc.isNew());
com.xpn.xwiki.api.Object obj = sdoc.getObject(sclass.getClassFullName());
assertNotNull(obj);
assertEquals(sdoc.getXClassManager(), sclass);
}
public void testInitXObjectDocumentDocNameExists() throws XWikiException
{
this.documents.clear();
// ///
XWikiDocument doc = this.xwiki.getDocument(DEFAULT_DOCFULLNAME, getContext());
this.xwiki.saveDocument(doc, getContext());
XClassManager sclass = XClassManagerTest.DispatchXClassManager.getInstance(getContext());
DefaultXObjectDocument sdoc =
(DefaultXObjectDocument) sclass.newXObjectDocument(DEFAULT_DOCFULLNAME, 0, getContext());
assertNotNull(sdoc);
assertTrue(sdoc.isNew());
com.xpn.xwiki.api.Object obj = sdoc.getObject(sclass.getClassFullName());
assertNotNull(obj);
assertEquals(sdoc.getXClassManager(), sclass);
}
public void testMergeObject() throws XWikiException
{
XClassManager sclass = XClassManagerTest.DispatchXClassManager.getInstance(getContext());
DefaultXObjectDocument sdoc1 = (DefaultXObjectDocument) sclass.newXObjectDocument(getContext());
DefaultXObjectDocument sdoc2 = (DefaultXObjectDocument) sclass.newXObjectDocument(getContext());
sdoc1.setStringValue(XClassManagerTest.FIELD_string, "valuesdoc1");
sdoc1.setStringValue(XClassManagerTest.FIELD_string2, "value2sdoc1");
sdoc2.setStringValue(XClassManagerTest.FIELD_string, "valuesdoc2");
sdoc2.setIntValue(XClassManagerTest.FIELD_int, 2);
sdoc1.mergeObject(sdoc2);
assertEquals("The field is not overwritten", sdoc1.getStringValue(XClassManagerTest.FIELD_string),
sdoc2.getStringValue(XClassManagerTest.FIELD_string));
assertEquals("The field is removed", "value2sdoc1", sdoc1
.getStringValue(XClassManagerTest.FIELD_string2));
assertEquals("The field is not added", sdoc1.getIntValue(XClassManagerTest.FIELD_int), sdoc1
.getIntValue(XClassManagerTest.FIELD_int));
}
}
| XWIKI-10410: Add a new authorization manager component that take care of external context
- Fix more test failures
| xwiki-platform-core/xwiki-platform-application-manager/xwiki-platform-application-manager-api/src/test/java/com/xpn/xwiki/plugin/applicationmanager/core/doc/objects/classes/DefaultXObjectDocumentTest.java | XWIKI-10410: Add a new authorization manager component that take care of external context | <ide><path>wiki-platform-core/xwiki-platform-application-manager/xwiki-platform-application-manager-api/src/test/java/com/xpn/xwiki/plugin/applicationmanager/core/doc/objects/classes/DefaultXObjectDocumentTest.java
<ide>
<ide> package com.xpn.xwiki.plugin.applicationmanager.core.doc.objects.classes;
<ide>
<add>import java.util.Collections;
<add>import java.util.HashMap;
<add>import java.util.List;
<add>import java.util.Locale;
<add>import java.util.Map;
<add>
<add>import org.jmock.Mock;
<add>import org.jmock.core.Invocation;
<add>import org.jmock.core.stub.CustomStub;
<add>import org.xwiki.localization.LocalizationContext;
<add>import org.xwiki.security.authorization.ContextualAuthorizationManager;
<add>
<ide> import com.xpn.xwiki.XWiki;
<ide> import com.xpn.xwiki.XWikiContext;
<ide> import com.xpn.xwiki.XWikiException;
<ide> import com.xpn.xwiki.test.AbstractBridgedXWikiComponentTestCase;
<ide> import com.xpn.xwiki.user.api.XWikiRightService;
<ide>
<del>import org.jmock.Mock;
<del>import org.jmock.core.Invocation;
<del>import org.jmock.core.stub.CustomStub;
<del>import org.xwiki.localization.LocalizationContext;
<del>
<del>import java.util.Collections;
<del>import java.util.HashMap;
<del>import java.util.List;
<del>import java.util.Locale;
<del>import java.util.Map;
<del>
<ide> /**
<ide> * Unit tests for {@link com.xpn.xwiki.plugin.applicationmanager.core.doc.objects.classes.DefaultXObjectDocument}.
<ide> *
<ide> protected void setUp() throws Exception
<ide> {
<ide> super.setUp();
<del>
<add>
<add> registerMockComponent(ContextualAuthorizationManager.class);
<add>
<ide> this.xwiki = new XWiki();
<ide> getContext().setWiki(this.xwiki);
<ide> |
|
Java | apache-2.0 | d4a71ad0c5365c288f6033508fb4f830ab19b641 | 0 | ThiagoGarciaAlves/intellij-community,michaelgallacher/intellij-community,vvv1559/intellij-community,wreckJ/intellij-community,slisson/intellij-community,semonte/intellij-community,fnouama/intellij-community,mglukhikh/intellij-community,FHannes/intellij-community,ThiagoGarciaAlves/intellij-community,fnouama/intellij-community,michaelgallacher/intellij-community,muntasirsyed/intellij-community,da1z/intellij-community,slisson/intellij-community,ibinti/intellij-community,salguarnieri/intellij-community,fnouama/intellij-community,xfournet/intellij-community,nicolargo/intellij-community,lucafavatella/intellij-community,da1z/intellij-community,signed/intellij-community,ibinti/intellij-community,ahb0327/intellij-community,allotria/intellij-community,amith01994/intellij-community,samthor/intellij-community,orekyuu/intellij-community,suncycheng/intellij-community,ahb0327/intellij-community,signed/intellij-community,kool79/intellij-community,slisson/intellij-community,kool79/intellij-community,kdwink/intellij-community,da1z/intellij-community,hurricup/intellij-community,asedunov/intellij-community,da1z/intellij-community,hurricup/intellij-community,muntasirsyed/intellij-community,asedunov/intellij-community,MER-GROUP/intellij-community,idea4bsd/idea4bsd,allotria/intellij-community,semonte/intellij-community,orekyuu/intellij-community,clumsy/intellij-community,slisson/intellij-community,lucafavatella/intellij-community,samthor/intellij-community,youdonghai/intellij-community,mglukhikh/intellij-community,lucafavatella/intellij-community,FHannes/intellij-community,suncycheng/intellij-community,ivan-fedorov/intellij-community,kool79/intellij-community,jagguli/intellij-community,FHannes/intellij-community,ahb0327/intellij-community,apixandru/intellij-community,blademainer/intellij-community,ivan-fedorov/intellij-community,signed/intellij-community,orekyuu/intellij-community,MichaelNedzelsky/intellij-community,asedunov/intellij-community,vladmm/intellij-community,fnouama/intellij-community,semonte/intellij-community,youdonghai/intellij-community,ibinti/intellij-community,ThiagoGarciaAlves/intellij-community,mglukhikh/intellij-community,vladmm/intellij-community,blademainer/intellij-community,signed/intellij-community,ivan-fedorov/intellij-community,clumsy/intellij-community,FHannes/intellij-community,ivan-fedorov/intellij-community,allotria/intellij-community,ibinti/intellij-community,retomerz/intellij-community,asedunov/intellij-community,semonte/intellij-community,slisson/intellij-community,jagguli/intellij-community,clumsy/intellij-community,slisson/intellij-community,hurricup/intellij-community,wreckJ/intellij-community,salguarnieri/intellij-community,jagguli/intellij-community,ivan-fedorov/intellij-community,fnouama/intellij-community,michaelgallacher/intellij-community,nicolargo/intellij-community,slisson/intellij-community,vvv1559/intellij-community,michaelgallacher/intellij-community,vvv1559/intellij-community,samthor/intellij-community,ahb0327/intellij-community,retomerz/intellij-community,michaelgallacher/intellij-community,apixandru/intellij-community,allotria/intellij-community,asedunov/intellij-community,amith01994/intellij-community,kdwink/intellij-community,apixandru/intellij-community,nicolargo/intellij-community,blademainer/intellij-community,slisson/intellij-community,semonte/intellij-community,xfournet/intellij-community,nicolargo/intellij-community,kool79/intellij-community,asedunov/intellij-community,salguarnieri/intellij-community,hurricup/intellij-community,ibinti/intellij-community,nicolargo/intellij-community,ThiagoGarciaAlves/intellij-community,ahb0327/intellij-community,fnouama/intellij-community,idea4bsd/idea4bsd,idea4bsd/idea4bsd,ibinti/intellij-community,fitermay/intellij-community,lucafavatella/intellij-community,blademainer/intellij-community,ahb0327/intellij-community,MichaelNedzelsky/intellij-community,FHannes/intellij-community,wreckJ/intellij-community,samthor/intellij-community,wreckJ/intellij-community,MichaelNedzelsky/intellij-community,MichaelNedzelsky/intellij-community,blademainer/intellij-community,vvv1559/intellij-community,fnouama/intellij-community,michaelgallacher/intellij-community,orekyuu/intellij-community,hurricup/intellij-community,lucafavatella/intellij-community,allotria/intellij-community,signed/intellij-community,muntasirsyed/intellij-community,nicolargo/intellij-community,suncycheng/intellij-community,MichaelNedzelsky/intellij-community,salguarnieri/intellij-community,michaelgallacher/intellij-community,lucafavatella/intellij-community,orekyuu/intellij-community,ThiagoGarciaAlves/intellij-community,idea4bsd/idea4bsd,blademainer/intellij-community,orekyuu/intellij-community,vladmm/intellij-community,apixandru/intellij-community,MER-GROUP/intellij-community,kdwink/intellij-community,apixandru/intellij-community,youdonghai/intellij-community,lucafavatella/intellij-community,wreckJ/intellij-community,vvv1559/intellij-community,idea4bsd/idea4bsd,ahb0327/intellij-community,wreckJ/intellij-community,da1z/intellij-community,fnouama/intellij-community,retomerz/intellij-community,allotria/intellij-community,semonte/intellij-community,jagguli/intellij-community,vladmm/intellij-community,nicolargo/intellij-community,da1z/intellij-community,kool79/intellij-community,semonte/intellij-community,clumsy/intellij-community,wreckJ/intellij-community,suncycheng/intellij-community,kool79/intellij-community,MichaelNedzelsky/intellij-community,jagguli/intellij-community,fitermay/intellij-community,amith01994/intellij-community,apixandru/intellij-community,blademainer/intellij-community,nicolargo/intellij-community,allotria/intellij-community,slisson/intellij-community,kdwink/intellij-community,mglukhikh/intellij-community,suncycheng/intellij-community,suncycheng/intellij-community,hurricup/intellij-community,xfournet/intellij-community,xfournet/intellij-community,fitermay/intellij-community,blademainer/intellij-community,kool79/intellij-community,kdwink/intellij-community,signed/intellij-community,samthor/intellij-community,amith01994/intellij-community,semonte/intellij-community,suncycheng/intellij-community,ahb0327/intellij-community,FHannes/intellij-community,MER-GROUP/intellij-community,blademainer/intellij-community,idea4bsd/idea4bsd,retomerz/intellij-community,vladmm/intellij-community,signed/intellij-community,MichaelNedzelsky/intellij-community,slisson/intellij-community,vvv1559/intellij-community,blademainer/intellij-community,ahb0327/intellij-community,muntasirsyed/intellij-community,orekyuu/intellij-community,muntasirsyed/intellij-community,allotria/intellij-community,ahb0327/intellij-community,vladmm/intellij-community,youdonghai/intellij-community,hurricup/intellij-community,youdonghai/intellij-community,samthor/intellij-community,da1z/intellij-community,signed/intellij-community,allotria/intellij-community,MichaelNedzelsky/intellij-community,ThiagoGarciaAlves/intellij-community,semonte/intellij-community,clumsy/intellij-community,idea4bsd/idea4bsd,mglukhikh/intellij-community,amith01994/intellij-community,suncycheng/intellij-community,samthor/intellij-community,mglukhikh/intellij-community,FHannes/intellij-community,idea4bsd/idea4bsd,salguarnieri/intellij-community,lucafavatella/intellij-community,kool79/intellij-community,vladmm/intellij-community,wreckJ/intellij-community,fitermay/intellij-community,fitermay/intellij-community,samthor/intellij-community,vvv1559/intellij-community,allotria/intellij-community,vvv1559/intellij-community,muntasirsyed/intellij-community,asedunov/intellij-community,vladmm/intellij-community,apixandru/intellij-community,allotria/intellij-community,jagguli/intellij-community,xfournet/intellij-community,nicolargo/intellij-community,allotria/intellij-community,FHannes/intellij-community,allotria/intellij-community,amith01994/intellij-community,hurricup/intellij-community,asedunov/intellij-community,FHannes/intellij-community,MER-GROUP/intellij-community,lucafavatella/intellij-community,ibinti/intellij-community,MER-GROUP/intellij-community,vladmm/intellij-community,michaelgallacher/intellij-community,hurricup/intellij-community,xfournet/intellij-community,wreckJ/intellij-community,ivan-fedorov/intellij-community,kdwink/intellij-community,suncycheng/intellij-community,MER-GROUP/intellij-community,ThiagoGarciaAlves/intellij-community,michaelgallacher/intellij-community,idea4bsd/idea4bsd,kool79/intellij-community,kdwink/intellij-community,xfournet/intellij-community,fnouama/intellij-community,kool79/intellij-community,vvv1559/intellij-community,retomerz/intellij-community,suncycheng/intellij-community,kool79/intellij-community,retomerz/intellij-community,xfournet/intellij-community,blademainer/intellij-community,orekyuu/intellij-community,lucafavatella/intellij-community,ThiagoGarciaAlves/intellij-community,mglukhikh/intellij-community,semonte/intellij-community,hurricup/intellij-community,lucafavatella/intellij-community,ibinti/intellij-community,ivan-fedorov/intellij-community,idea4bsd/idea4bsd,signed/intellij-community,muntasirsyed/intellij-community,apixandru/intellij-community,fitermay/intellij-community,vladmm/intellij-community,youdonghai/intellij-community,FHannes/intellij-community,FHannes/intellij-community,signed/intellij-community,da1z/intellij-community,clumsy/intellij-community,mglukhikh/intellij-community,orekyuu/intellij-community,da1z/intellij-community,da1z/intellij-community,salguarnieri/intellij-community,ibinti/intellij-community,clumsy/intellij-community,ivan-fedorov/intellij-community,ThiagoGarciaAlves/intellij-community,salguarnieri/intellij-community,ibinti/intellij-community,asedunov/intellij-community,retomerz/intellij-community,lucafavatella/intellij-community,MER-GROUP/intellij-community,hurricup/intellij-community,jagguli/intellij-community,nicolargo/intellij-community,samthor/intellij-community,semonte/intellij-community,kdwink/intellij-community,salguarnieri/intellij-community,jagguli/intellij-community,fitermay/intellij-community,apixandru/intellij-community,ThiagoGarciaAlves/intellij-community,suncycheng/intellij-community,youdonghai/intellij-community,vladmm/intellij-community,MER-GROUP/intellij-community,ivan-fedorov/intellij-community,youdonghai/intellij-community,wreckJ/intellij-community,amith01994/intellij-community,suncycheng/intellij-community,samthor/intellij-community,fitermay/intellij-community,salguarnieri/intellij-community,youdonghai/intellij-community,xfournet/intellij-community,MichaelNedzelsky/intellij-community,amith01994/intellij-community,ivan-fedorov/intellij-community,asedunov/intellij-community,MER-GROUP/intellij-community,kdwink/intellij-community,youdonghai/intellij-community,slisson/intellij-community,apixandru/intellij-community,fnouama/intellij-community,retomerz/intellij-community,amith01994/intellij-community,orekyuu/intellij-community,fitermay/intellij-community,FHannes/intellij-community,fitermay/intellij-community,mglukhikh/intellij-community,clumsy/intellij-community,clumsy/intellij-community,jagguli/intellij-community,retomerz/intellij-community,jagguli/intellij-community,kdwink/intellij-community,mglukhikh/intellij-community,vvv1559/intellij-community,asedunov/intellij-community,salguarnieri/intellij-community,xfournet/intellij-community,MER-GROUP/intellij-community,orekyuu/intellij-community,wreckJ/intellij-community,FHannes/intellij-community,da1z/intellij-community,youdonghai/intellij-community,slisson/intellij-community,vladmm/intellij-community,apixandru/intellij-community,kool79/intellij-community,da1z/intellij-community,xfournet/intellij-community,vvv1559/intellij-community,da1z/intellij-community,samthor/intellij-community,lucafavatella/intellij-community,idea4bsd/idea4bsd,retomerz/intellij-community,signed/intellij-community,amith01994/intellij-community,signed/intellij-community,youdonghai/intellij-community,fnouama/intellij-community,orekyuu/intellij-community,ThiagoGarciaAlves/intellij-community,mglukhikh/intellij-community,ahb0327/intellij-community,apixandru/intellij-community,amith01994/intellij-community,muntasirsyed/intellij-community,idea4bsd/idea4bsd,idea4bsd/idea4bsd,muntasirsyed/intellij-community,clumsy/intellij-community,MER-GROUP/intellij-community,apixandru/intellij-community,blademainer/intellij-community,wreckJ/intellij-community,amith01994/intellij-community,mglukhikh/intellij-community,apixandru/intellij-community,jagguli/intellij-community,muntasirsyed/intellij-community,asedunov/intellij-community,youdonghai/intellij-community,MichaelNedzelsky/intellij-community,michaelgallacher/intellij-community,michaelgallacher/intellij-community,muntasirsyed/intellij-community,xfournet/intellij-community,ivan-fedorov/intellij-community,nicolargo/intellij-community,jagguli/intellij-community,clumsy/intellij-community,nicolargo/intellij-community,hurricup/intellij-community,ibinti/intellij-community,retomerz/intellij-community,ahb0327/intellij-community,ivan-fedorov/intellij-community,ibinti/intellij-community,ibinti/intellij-community,MER-GROUP/intellij-community,asedunov/intellij-community,xfournet/intellij-community,ThiagoGarciaAlves/intellij-community,MichaelNedzelsky/intellij-community,fitermay/intellij-community,vvv1559/intellij-community,fitermay/intellij-community,kdwink/intellij-community,clumsy/intellij-community,salguarnieri/intellij-community,retomerz/intellij-community,semonte/intellij-community,mglukhikh/intellij-community,fitermay/intellij-community,fnouama/intellij-community,kdwink/intellij-community,samthor/intellij-community,vvv1559/intellij-community,MichaelNedzelsky/intellij-community,retomerz/intellij-community,salguarnieri/intellij-community,michaelgallacher/intellij-community,hurricup/intellij-community,signed/intellij-community,semonte/intellij-community,muntasirsyed/intellij-community | /*
* Copyright 2000-2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package git4idea;
import com.intellij.execution.ui.ConsoleViewContentType;
import com.intellij.ide.BrowserUtil;
import com.intellij.notification.Notification;
import com.intellij.notification.NotificationListener;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.components.ServiceManager;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.diff.impl.patch.formove.FilePathComparator;
import com.intellij.openapi.editor.markup.TextAttributes;
import com.intellij.openapi.options.Configurable;
import com.intellij.openapi.options.ShowSettingsUtil;
import com.intellij.openapi.progress.Task;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.MessageType;
import com.intellij.openapi.ui.Messages;
import com.intellij.openapi.util.Disposer;
import com.intellij.openapi.vcs.*;
import com.intellij.openapi.vcs.changes.ChangeProvider;
import com.intellij.openapi.vcs.changes.CommitExecutor;
import com.intellij.openapi.vcs.checkin.CheckinEnvironment;
import com.intellij.openapi.vcs.diff.DiffProvider;
import com.intellij.openapi.vcs.diff.RevisionSelector;
import com.intellij.openapi.vcs.history.VcsHistoryProvider;
import com.intellij.openapi.vcs.history.VcsRevisionNumber;
import com.intellij.openapi.vcs.merge.MergeProvider;
import com.intellij.openapi.vcs.rollback.RollbackEnvironment;
import com.intellij.openapi.vcs.roots.VcsRootDetector;
import com.intellij.openapi.vcs.ui.VcsBalloonProblemNotifier;
import com.intellij.openapi.vcs.update.UpdateEnvironment;
import com.intellij.openapi.vcs.versionBrowser.CommittedChangeList;
import com.intellij.openapi.vfs.VfsUtilCore;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.util.containers.ComparatorDelegate;
import com.intellij.util.containers.Convertor;
import com.intellij.util.ui.UIUtil;
import com.intellij.vcs.log.VcsUserRegistry;
import git4idea.annotate.GitAnnotationProvider;
import git4idea.annotate.GitRepositoryForAnnotationsListener;
import git4idea.changes.GitCommittedChangeListProvider;
import git4idea.changes.GitOutgoingChangesProvider;
import git4idea.checkin.GitCheckinEnvironment;
import git4idea.checkin.GitCommitAndPushExecutor;
import git4idea.checkout.GitCheckoutProvider;
import git4idea.commands.Git;
import git4idea.config.*;
import git4idea.diff.GitDiffProvider;
import git4idea.diff.GitTreeDiffProvider;
import git4idea.history.GitHistoryProvider;
import git4idea.i18n.GitBundle;
import git4idea.merge.GitMergeProvider;
import git4idea.rollback.GitRollbackEnvironment;
import git4idea.roots.GitIntegrationEnabler;
import git4idea.status.GitChangeProvider;
import git4idea.ui.branch.GitBranchWidget;
import git4idea.update.GitUpdateEnvironment;
import git4idea.vfs.GitVFSListener;
import org.jetbrains.annotations.CalledInAwt;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.event.HyperlinkEvent;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
/**
* Git VCS implementation
*/
public class GitVcs extends AbstractVcs<CommittedChangeList> {
public static final String NAME = "Git";
public static final String ID = "git";
private static final Logger log = Logger.getInstance(GitVcs.class.getName());
private static final VcsKey ourKey = createKey(NAME);
private final ChangeProvider myChangeProvider;
private final GitCheckinEnvironment myCheckinEnvironment;
private final RollbackEnvironment myRollbackEnvironment;
private final GitUpdateEnvironment myUpdateEnvironment;
private final GitAnnotationProvider myAnnotationProvider;
private final DiffProvider myDiffProvider;
private final VcsHistoryProvider myHistoryProvider;
@NotNull private final Git myGit;
private final ProjectLevelVcsManager myVcsManager;
private final GitVcsApplicationSettings myAppSettings;
private final Configurable myConfigurable;
private final RevisionSelector myRevSelector;
private final GitCommittedChangeListProvider myCommittedChangeListProvider;
private GitVFSListener myVFSListener; // a VFS listener that tracks file addition, deletion, and renaming.
private final ReadWriteLock myCommandLock = new ReentrantReadWriteLock(true); // The command read/write lock
private final TreeDiffProvider myTreeDiffProvider;
private final GitCommitAndPushExecutor myCommitAndPushExecutor;
private final GitExecutableValidator myExecutableValidator;
private GitBranchWidget myBranchWidget;
private GitVersion myVersion = GitVersion.NULL; // version of Git which this plugin uses.
private static final int MAX_CONSOLE_OUTPUT_SIZE = 10000;
private GitRepositoryForAnnotationsListener myRepositoryForAnnotationsListener;
@Nullable
public static GitVcs getInstance(Project project) {
if (project == null || project.isDisposed()) {
return null;
}
return (GitVcs) ProjectLevelVcsManager.getInstance(project).findVcsByName(NAME);
}
public GitVcs(@NotNull Project project, @NotNull Git git,
@NotNull final ProjectLevelVcsManager gitVcsManager,
@NotNull final GitAnnotationProvider gitAnnotationProvider,
@NotNull final GitDiffProvider gitDiffProvider,
@NotNull final GitHistoryProvider gitHistoryProvider,
@NotNull final GitRollbackEnvironment gitRollbackEnvironment,
@NotNull final GitVcsApplicationSettings gitSettings,
@NotNull final GitVcsSettings gitProjectSettings,
@NotNull GitSharedSettings sharedSettings) {
super(project, NAME);
myGit = git;
myVcsManager = gitVcsManager;
myAppSettings = gitSettings;
myChangeProvider = project.isDefault() ? null : ServiceManager.getService(project, GitChangeProvider.class);
myCheckinEnvironment = project.isDefault() ? null : ServiceManager.getService(project, GitCheckinEnvironment.class);
myAnnotationProvider = gitAnnotationProvider;
myDiffProvider = gitDiffProvider;
myHistoryProvider = gitHistoryProvider;
myRollbackEnvironment = gitRollbackEnvironment;
myRevSelector = new GitRevisionSelector();
myConfigurable = new GitVcsConfigurable(myProject, gitProjectSettings, sharedSettings);
myUpdateEnvironment = new GitUpdateEnvironment(myProject, gitProjectSettings);
myCommittedChangeListProvider = new GitCommittedChangeListProvider(myProject);
myOutgoingChangesProvider = new GitOutgoingChangesProvider(myProject);
myTreeDiffProvider = new GitTreeDiffProvider(myProject);
myCommitAndPushExecutor = new GitCommitAndPushExecutor(myCheckinEnvironment);
myExecutableValidator = new GitExecutableValidator(myProject);
}
public ReadWriteLock getCommandLock() {
return myCommandLock;
}
/**
* Run task in background using the common queue (per project)
* @param task the task to run
*/
public static void runInBackground(Task.Backgroundable task) {
task.queue();
}
@Override
public CommittedChangesProvider getCommittedChangesProvider() {
return myCommittedChangeListProvider;
}
@Override
public String getRevisionPattern() {
// return the full commit hash pattern, possibly other revision formats should be supported as well
return "[0-9a-fA-F]+";
}
@Override
@NotNull
public CheckinEnvironment createCheckinEnvironment() {
return myCheckinEnvironment;
}
@NotNull
@Override
public MergeProvider getMergeProvider() {
return GitMergeProvider.detect(myProject);
}
@Override
@NotNull
public RollbackEnvironment createRollbackEnvironment() {
return myRollbackEnvironment;
}
@Override
@NotNull
public VcsHistoryProvider getVcsHistoryProvider() {
return myHistoryProvider;
}
@Override
public VcsHistoryProvider getVcsBlockHistoryProvider() {
return myHistoryProvider;
}
@Override
@NotNull
public String getDisplayName() {
return NAME;
}
@Override
@Nullable
public UpdateEnvironment createUpdateEnvironment() {
return myUpdateEnvironment;
}
@Override
@NotNull
public GitAnnotationProvider getAnnotationProvider() {
return myAnnotationProvider;
}
@Override
@NotNull
public DiffProvider getDiffProvider() {
return myDiffProvider;
}
@Override
@Nullable
public RevisionSelector getRevisionSelector() {
return myRevSelector;
}
@Override
@Nullable
public VcsRevisionNumber parseRevisionNumber(@Nullable String revision, @Nullable FilePath path) throws VcsException {
if (revision == null || revision.length() == 0) return null;
if (revision.length() > 40) { // date & revision-id encoded string
String dateString = revision.substring(0, revision.indexOf("["));
String rev = revision.substring(revision.indexOf("[") + 1, 40);
Date d = new Date(Date.parse(dateString));
return new GitRevisionNumber(rev, d);
}
if (path != null) {
try {
VirtualFile root = GitUtil.getGitRoot(path);
return GitRevisionNumber.resolve(myProject, root, revision);
}
catch (VcsException e) {
log.info("Unexpected problem with resolving the git revision number: ", e);
throw e;
}
}
return new GitRevisionNumber(revision);
}
@Override
@Nullable
public VcsRevisionNumber parseRevisionNumber(@Nullable String revision) throws VcsException {
return parseRevisionNumber(revision, null);
}
@Override
public boolean isVersionedDirectory(VirtualFile dir) {
return dir.isDirectory() && GitUtil.gitRootOrNull(dir) != null;
}
@Override
protected void start() throws VcsException {
}
@Override
protected void shutdown() throws VcsException {
}
@Override
protected void activate() {
checkExecutableAndVersion();
if (myVFSListener == null) {
myVFSListener = new GitVFSListener(myProject, this, myGit);
}
ServiceManager.getService(myProject, VcsUserRegistry.class); // make sure to read the registry before opening commit dialog
if (!ApplicationManager.getApplication().isHeadlessEnvironment()) {
myBranchWidget = new GitBranchWidget(myProject);
myBranchWidget.activate();
}
if (myRepositoryForAnnotationsListener == null) {
myRepositoryForAnnotationsListener = new GitRepositoryForAnnotationsListener(myProject);
}
ServiceManager.getService(myProject, GitUserRegistry.class).activate();
}
private void checkExecutableAndVersion() {
boolean executableIsAlreadyCheckedAndFine = false;
String pathToGit = myAppSettings.getPathToGit();
if (!pathToGit.contains(File.separator)) { // no path, just sole executable, with a hope that it is in path
// subject to redetect the path if executable validator fails
if (!myExecutableValidator.isExecutableValid()) {
myAppSettings.setPathToGit(new GitExecutableDetector().detect());
}
else {
executableIsAlreadyCheckedAndFine = true; // not to check it twice
}
}
if (executableIsAlreadyCheckedAndFine || myExecutableValidator.checkExecutableAndNotifyIfNeeded()) {
checkVersion();
}
}
@Override
protected void deactivate() {
if (myVFSListener != null) {
Disposer.dispose(myVFSListener);
myVFSListener = null;
}
if (myBranchWidget != null) {
myBranchWidget.deactivate();
myBranchWidget = null;
}
}
@NotNull
@Override
public synchronized Configurable getConfigurable() {
return myConfigurable;
}
@Nullable
public ChangeProvider getChangeProvider() {
return myChangeProvider;
}
/**
* Show errors as popup and as messages in vcs view.
*
* @param list a list of errors
* @param action an action
*/
public void showErrors(@NotNull List<VcsException> list, @NotNull String action) {
if (list.size() > 0) {
StringBuilder buffer = new StringBuilder();
buffer.append("\n");
buffer.append(GitBundle.message("error.list.title", action));
for (final VcsException exception : list) {
buffer.append("\n");
buffer.append(exception.getMessage());
}
final String msg = buffer.toString();
UIUtil.invokeLaterIfNeeded(new Runnable() {
@Override
public void run() {
Messages.showErrorDialog(myProject, msg, GitBundle.getString("error.dialog.title"));
}
});
}
}
/**
* Shows a plain message in the Version Control Console.
*/
public void showMessages(@NotNull String message) {
if (message.length() == 0) return;
showMessage(message, ConsoleViewContentType.NORMAL_OUTPUT.getAttributes());
}
/**
* Show message in the Version Control Console
* @param message a message to show
* @param style a style to use
*/
private void showMessage(@NotNull String message, final TextAttributes style) {
if (message.length() > MAX_CONSOLE_OUTPUT_SIZE) {
message = message.substring(0, MAX_CONSOLE_OUTPUT_SIZE);
}
myVcsManager.addMessageToConsoleWindow(message, style);
}
/**
* Checks Git version and updates the myVersion variable.
* In the case of exception or unsupported version reports the problem.
* Note that unsupported version is also applied - some functionality might not work (we warn about that), but no need to disable at all.
*/
public void checkVersion() {
final String executable = myAppSettings.getPathToGit();
try {
myVersion = GitVersion.identifyVersion(executable);
if (! myVersion.isSupported()) {
log.info("Unsupported Git version: " + myVersion);
final String SETTINGS_LINK = "settings";
final String UPDATE_LINK = "update";
String message = String.format("The <a href='" + SETTINGS_LINK + "'>configured</a> version of Git is not supported: %s.<br/> " +
"The minimal supported version is %s. Please <a href='" + UPDATE_LINK + "'>update</a>.",
myVersion, GitVersion.MIN);
VcsNotifier.getInstance(myProject).notifyError("Unsupported Git version", message,
new NotificationListener.Adapter() {
@Override
protected void hyperlinkActivated(@NotNull Notification notification,
@NotNull HyperlinkEvent e) {
if (SETTINGS_LINK.equals(e.getDescription())) {
ShowSettingsUtil.getInstance()
.showSettingsDialog(myProject, getConfigurable().getDisplayName());
}
else if (UPDATE_LINK.equals(e.getDescription())) {
BrowserUtil.browse("http://git-scm.com");
}
}
}
);
}
} catch (Exception e) {
if (getExecutableValidator().checkExecutableAndNotifyIfNeeded()) { // check executable before notifying error
final String reason = (e.getCause() != null ? e.getCause() : e).getMessage();
String message = GitBundle.message("vcs.unable.to.run.git", executable, reason);
if (!myProject.isDefault()) {
showMessage(message, ConsoleViewContentType.SYSTEM_OUTPUT.getAttributes());
}
VcsBalloonProblemNotifier.showOverVersionControlView(myProject, message, MessageType.ERROR);
}
}
}
/**
* @return the version number of Git, which is used by IDEA. Or {@link GitVersion#NULL} if version info is unavailable yet.
*/
@NotNull
public GitVersion getVersion() {
return myVersion;
}
/**
* Shows a command line message in the Version Control Console
*/
public void showCommandLine(final String cmdLine) {
SimpleDateFormat f = new SimpleDateFormat("HH:mm:ss.SSS");
showMessage(f.format(new Date()) + ": " + cmdLine, ConsoleViewContentType.SYSTEM_OUTPUT.getAttributes());
}
/**
* Shows error message in the Version Control Console
*/
public void showErrorMessages(final String line) {
showMessage(line, ConsoleViewContentType.ERROR_OUTPUT.getAttributes());
}
@Override
public boolean allowsNestedRoots() {
return true;
}
@Override
public <S> List<S> filterUniqueRoots(final List<S> in, final Convertor<S, VirtualFile> convertor) {
Collections.sort(in, new ComparatorDelegate<S, VirtualFile>(convertor, FilePathComparator.getInstance()));
for (int i = 1; i < in.size(); i++) {
final S sChild = in.get(i);
final VirtualFile child = convertor.convert(sChild);
final VirtualFile childRoot = GitUtil.gitRootOrNull(child);
if (childRoot == null) {
// non-git file actually, skip it
continue;
}
for (int j = i - 1; j >= 0; --j) {
final S sParent = in.get(j);
final VirtualFile parent = convertor.convert(sParent);
// the method check both that parent is an ancestor of the child and that they share common git root
if (VfsUtilCore.isAncestor(parent, child, false) && VfsUtilCore.isAncestor(childRoot, parent, false)) {
in.remove(i);
//noinspection AssignmentToForLoopParameter
--i;
break;
}
}
}
return in;
}
@Override
public RootsConvertor getCustomConvertor() {
return GitRootConverter.INSTANCE;
}
public static VcsKey getKey() {
return ourKey;
}
@Override
public VcsType getType() {
return VcsType.distributed;
}
private final VcsOutgoingChangesProvider<CommittedChangeList> myOutgoingChangesProvider;
@Override
protected VcsOutgoingChangesProvider<CommittedChangeList> getOutgoingProviderImpl() {
return myOutgoingChangesProvider;
}
@Override
public RemoteDifferenceStrategy getRemoteDifferenceStrategy() {
return RemoteDifferenceStrategy.ASK_TREE_PROVIDER;
}
@Override
protected TreeDiffProvider getTreeDiffProviderImpl() {
return myTreeDiffProvider;
}
@Override
public List<CommitExecutor> getCommitExecutors() {
return Collections.<CommitExecutor>singletonList(myCommitAndPushExecutor);
}
@NotNull
public GitExecutableValidator getExecutableValidator() {
return myExecutableValidator;
}
@Override
public boolean fileListenerIsSynchronous() {
return false;
}
@Override
@CalledInAwt
public void enableIntegration() {
ApplicationManager.getApplication().executeOnPooledThread(new Runnable() {
public void run() {
Collection<VcsRoot> roots = ServiceManager.getService(myProject, VcsRootDetector.class).detect();
new GitIntegrationEnabler(GitVcs.this, myGit).enable(roots);
}
});
}
@Override
public CheckoutProvider getCheckoutProvider() {
return new GitCheckoutProvider(ServiceManager.getService(Git.class));
}
}
| plugins/git4idea/src/git4idea/GitVcs.java | /*
* Copyright 2000-2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package git4idea;
import com.intellij.execution.ui.ConsoleViewContentType;
import com.intellij.ide.BrowserUtil;
import com.intellij.notification.Notification;
import com.intellij.notification.NotificationListener;
import com.intellij.notification.impl.NotificationsConfigurationImpl;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.components.ServiceManager;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.diff.impl.patch.formove.FilePathComparator;
import com.intellij.openapi.editor.markup.TextAttributes;
import com.intellij.openapi.options.Configurable;
import com.intellij.openapi.options.ShowSettingsUtil;
import com.intellij.openapi.progress.Task;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.MessageType;
import com.intellij.openapi.ui.Messages;
import com.intellij.openapi.util.Disposer;
import com.intellij.openapi.vcs.*;
import com.intellij.openapi.vcs.changes.ChangeProvider;
import com.intellij.openapi.vcs.changes.CommitExecutor;
import com.intellij.openapi.vcs.checkin.CheckinEnvironment;
import com.intellij.openapi.vcs.diff.DiffProvider;
import com.intellij.openapi.vcs.diff.RevisionSelector;
import com.intellij.openapi.vcs.history.VcsHistoryProvider;
import com.intellij.openapi.vcs.history.VcsRevisionNumber;
import com.intellij.openapi.vcs.merge.MergeProvider;
import com.intellij.openapi.vcs.rollback.RollbackEnvironment;
import com.intellij.openapi.vcs.roots.VcsRootDetector;
import com.intellij.openapi.vcs.ui.VcsBalloonProblemNotifier;
import com.intellij.openapi.vcs.update.UpdateEnvironment;
import com.intellij.openapi.vcs.versionBrowser.CommittedChangeList;
import com.intellij.openapi.vfs.VfsUtilCore;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.util.containers.ComparatorDelegate;
import com.intellij.util.containers.Convertor;
import com.intellij.util.ui.UIUtil;
import com.intellij.vcs.log.VcsUserRegistry;
import git4idea.annotate.GitAnnotationProvider;
import git4idea.annotate.GitRepositoryForAnnotationsListener;
import git4idea.changes.GitCommittedChangeListProvider;
import git4idea.changes.GitOutgoingChangesProvider;
import git4idea.checkin.GitCheckinEnvironment;
import git4idea.checkin.GitCommitAndPushExecutor;
import git4idea.checkout.GitCheckoutProvider;
import git4idea.commands.Git;
import git4idea.config.*;
import git4idea.diff.GitDiffProvider;
import git4idea.diff.GitTreeDiffProvider;
import git4idea.history.GitHistoryProvider;
import git4idea.i18n.GitBundle;
import git4idea.merge.GitMergeProvider;
import git4idea.rollback.GitRollbackEnvironment;
import git4idea.roots.GitIntegrationEnabler;
import git4idea.status.GitChangeProvider;
import git4idea.ui.branch.GitBranchWidget;
import git4idea.update.GitUpdateEnvironment;
import git4idea.vfs.GitVFSListener;
import org.jetbrains.annotations.CalledInAwt;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.event.HyperlinkEvent;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
/**
* Git VCS implementation
*/
public class GitVcs extends AbstractVcs<CommittedChangeList> {
static {
NotificationsConfigurationImpl.remove("Git");
}
public static final String NAME = "Git";
public static final String ID = "git";
private static final Logger log = Logger.getInstance(GitVcs.class.getName());
private static final VcsKey ourKey = createKey(NAME);
private final ChangeProvider myChangeProvider;
private final GitCheckinEnvironment myCheckinEnvironment;
private final RollbackEnvironment myRollbackEnvironment;
private final GitUpdateEnvironment myUpdateEnvironment;
private final GitAnnotationProvider myAnnotationProvider;
private final DiffProvider myDiffProvider;
private final VcsHistoryProvider myHistoryProvider;
@NotNull private final Git myGit;
private final ProjectLevelVcsManager myVcsManager;
private final GitVcsApplicationSettings myAppSettings;
private final Configurable myConfigurable;
private final RevisionSelector myRevSelector;
private final GitCommittedChangeListProvider myCommittedChangeListProvider;
private GitVFSListener myVFSListener; // a VFS listener that tracks file addition, deletion, and renaming.
private final ReadWriteLock myCommandLock = new ReentrantReadWriteLock(true); // The command read/write lock
private final TreeDiffProvider myTreeDiffProvider;
private final GitCommitAndPushExecutor myCommitAndPushExecutor;
private final GitExecutableValidator myExecutableValidator;
private GitBranchWidget myBranchWidget;
private GitVersion myVersion = GitVersion.NULL; // version of Git which this plugin uses.
private static final int MAX_CONSOLE_OUTPUT_SIZE = 10000;
private GitRepositoryForAnnotationsListener myRepositoryForAnnotationsListener;
@Nullable
public static GitVcs getInstance(Project project) {
if (project == null || project.isDisposed()) {
return null;
}
return (GitVcs) ProjectLevelVcsManager.getInstance(project).findVcsByName(NAME);
}
public GitVcs(@NotNull Project project, @NotNull Git git,
@NotNull final ProjectLevelVcsManager gitVcsManager,
@NotNull final GitAnnotationProvider gitAnnotationProvider,
@NotNull final GitDiffProvider gitDiffProvider,
@NotNull final GitHistoryProvider gitHistoryProvider,
@NotNull final GitRollbackEnvironment gitRollbackEnvironment,
@NotNull final GitVcsApplicationSettings gitSettings,
@NotNull final GitVcsSettings gitProjectSettings,
@NotNull GitSharedSettings sharedSettings) {
super(project, NAME);
myGit = git;
myVcsManager = gitVcsManager;
myAppSettings = gitSettings;
myChangeProvider = project.isDefault() ? null : ServiceManager.getService(project, GitChangeProvider.class);
myCheckinEnvironment = project.isDefault() ? null : ServiceManager.getService(project, GitCheckinEnvironment.class);
myAnnotationProvider = gitAnnotationProvider;
myDiffProvider = gitDiffProvider;
myHistoryProvider = gitHistoryProvider;
myRollbackEnvironment = gitRollbackEnvironment;
myRevSelector = new GitRevisionSelector();
myConfigurable = new GitVcsConfigurable(myProject, gitProjectSettings, sharedSettings);
myUpdateEnvironment = new GitUpdateEnvironment(myProject, gitProjectSettings);
myCommittedChangeListProvider = new GitCommittedChangeListProvider(myProject);
myOutgoingChangesProvider = new GitOutgoingChangesProvider(myProject);
myTreeDiffProvider = new GitTreeDiffProvider(myProject);
myCommitAndPushExecutor = new GitCommitAndPushExecutor(myCheckinEnvironment);
myExecutableValidator = new GitExecutableValidator(myProject);
}
public ReadWriteLock getCommandLock() {
return myCommandLock;
}
/**
* Run task in background using the common queue (per project)
* @param task the task to run
*/
public static void runInBackground(Task.Backgroundable task) {
task.queue();
}
@Override
public CommittedChangesProvider getCommittedChangesProvider() {
return myCommittedChangeListProvider;
}
@Override
public String getRevisionPattern() {
// return the full commit hash pattern, possibly other revision formats should be supported as well
return "[0-9a-fA-F]+";
}
@Override
@NotNull
public CheckinEnvironment createCheckinEnvironment() {
return myCheckinEnvironment;
}
@NotNull
@Override
public MergeProvider getMergeProvider() {
return GitMergeProvider.detect(myProject);
}
@Override
@NotNull
public RollbackEnvironment createRollbackEnvironment() {
return myRollbackEnvironment;
}
@Override
@NotNull
public VcsHistoryProvider getVcsHistoryProvider() {
return myHistoryProvider;
}
@Override
public VcsHistoryProvider getVcsBlockHistoryProvider() {
return myHistoryProvider;
}
@Override
@NotNull
public String getDisplayName() {
return NAME;
}
@Override
@Nullable
public UpdateEnvironment createUpdateEnvironment() {
return myUpdateEnvironment;
}
@Override
@NotNull
public GitAnnotationProvider getAnnotationProvider() {
return myAnnotationProvider;
}
@Override
@NotNull
public DiffProvider getDiffProvider() {
return myDiffProvider;
}
@Override
@Nullable
public RevisionSelector getRevisionSelector() {
return myRevSelector;
}
@Override
@Nullable
public VcsRevisionNumber parseRevisionNumber(@Nullable String revision, @Nullable FilePath path) throws VcsException {
if (revision == null || revision.length() == 0) return null;
if (revision.length() > 40) { // date & revision-id encoded string
String dateString = revision.substring(0, revision.indexOf("["));
String rev = revision.substring(revision.indexOf("[") + 1, 40);
Date d = new Date(Date.parse(dateString));
return new GitRevisionNumber(rev, d);
}
if (path != null) {
try {
VirtualFile root = GitUtil.getGitRoot(path);
return GitRevisionNumber.resolve(myProject, root, revision);
}
catch (VcsException e) {
log.info("Unexpected problem with resolving the git revision number: ", e);
throw e;
}
}
return new GitRevisionNumber(revision);
}
@Override
@Nullable
public VcsRevisionNumber parseRevisionNumber(@Nullable String revision) throws VcsException {
return parseRevisionNumber(revision, null);
}
@Override
public boolean isVersionedDirectory(VirtualFile dir) {
return dir.isDirectory() && GitUtil.gitRootOrNull(dir) != null;
}
@Override
protected void start() throws VcsException {
}
@Override
protected void shutdown() throws VcsException {
}
@Override
protected void activate() {
checkExecutableAndVersion();
if (myVFSListener == null) {
myVFSListener = new GitVFSListener(myProject, this, myGit);
}
ServiceManager.getService(myProject, VcsUserRegistry.class); // make sure to read the registry before opening commit dialog
if (!ApplicationManager.getApplication().isHeadlessEnvironment()) {
myBranchWidget = new GitBranchWidget(myProject);
myBranchWidget.activate();
}
if (myRepositoryForAnnotationsListener == null) {
myRepositoryForAnnotationsListener = new GitRepositoryForAnnotationsListener(myProject);
}
ServiceManager.getService(myProject, GitUserRegistry.class).activate();
}
private void checkExecutableAndVersion() {
boolean executableIsAlreadyCheckedAndFine = false;
String pathToGit = myAppSettings.getPathToGit();
if (!pathToGit.contains(File.separator)) { // no path, just sole executable, with a hope that it is in path
// subject to redetect the path if executable validator fails
if (!myExecutableValidator.isExecutableValid()) {
myAppSettings.setPathToGit(new GitExecutableDetector().detect());
}
else {
executableIsAlreadyCheckedAndFine = true; // not to check it twice
}
}
if (executableIsAlreadyCheckedAndFine || myExecutableValidator.checkExecutableAndNotifyIfNeeded()) {
checkVersion();
}
}
@Override
protected void deactivate() {
if (myVFSListener != null) {
Disposer.dispose(myVFSListener);
myVFSListener = null;
}
if (myBranchWidget != null) {
myBranchWidget.deactivate();
myBranchWidget = null;
}
}
@NotNull
@Override
public synchronized Configurable getConfigurable() {
return myConfigurable;
}
@Nullable
public ChangeProvider getChangeProvider() {
return myChangeProvider;
}
/**
* Show errors as popup and as messages in vcs view.
*
* @param list a list of errors
* @param action an action
*/
public void showErrors(@NotNull List<VcsException> list, @NotNull String action) {
if (list.size() > 0) {
StringBuilder buffer = new StringBuilder();
buffer.append("\n");
buffer.append(GitBundle.message("error.list.title", action));
for (final VcsException exception : list) {
buffer.append("\n");
buffer.append(exception.getMessage());
}
final String msg = buffer.toString();
UIUtil.invokeLaterIfNeeded(new Runnable() {
@Override
public void run() {
Messages.showErrorDialog(myProject, msg, GitBundle.getString("error.dialog.title"));
}
});
}
}
/**
* Shows a plain message in the Version Control Console.
*/
public void showMessages(@NotNull String message) {
if (message.length() == 0) return;
showMessage(message, ConsoleViewContentType.NORMAL_OUTPUT.getAttributes());
}
/**
* Show message in the Version Control Console
* @param message a message to show
* @param style a style to use
*/
private void showMessage(@NotNull String message, final TextAttributes style) {
if (message.length() > MAX_CONSOLE_OUTPUT_SIZE) {
message = message.substring(0, MAX_CONSOLE_OUTPUT_SIZE);
}
myVcsManager.addMessageToConsoleWindow(message, style);
}
/**
* Checks Git version and updates the myVersion variable.
* In the case of exception or unsupported version reports the problem.
* Note that unsupported version is also applied - some functionality might not work (we warn about that), but no need to disable at all.
*/
public void checkVersion() {
final String executable = myAppSettings.getPathToGit();
try {
myVersion = GitVersion.identifyVersion(executable);
if (! myVersion.isSupported()) {
log.info("Unsupported Git version: " + myVersion);
final String SETTINGS_LINK = "settings";
final String UPDATE_LINK = "update";
String message = String.format("The <a href='" + SETTINGS_LINK + "'>configured</a> version of Git is not supported: %s.<br/> " +
"The minimal supported version is %s. Please <a href='" + UPDATE_LINK + "'>update</a>.",
myVersion, GitVersion.MIN);
VcsNotifier.getInstance(myProject).notifyError("Unsupported Git version", message,
new NotificationListener.Adapter() {
@Override
protected void hyperlinkActivated(@NotNull Notification notification,
@NotNull HyperlinkEvent e) {
if (SETTINGS_LINK.equals(e.getDescription())) {
ShowSettingsUtil.getInstance()
.showSettingsDialog(myProject, getConfigurable().getDisplayName());
}
else if (UPDATE_LINK.equals(e.getDescription())) {
BrowserUtil.browse("http://git-scm.com");
}
}
}
);
}
} catch (Exception e) {
if (getExecutableValidator().checkExecutableAndNotifyIfNeeded()) { // check executable before notifying error
final String reason = (e.getCause() != null ? e.getCause() : e).getMessage();
String message = GitBundle.message("vcs.unable.to.run.git", executable, reason);
if (!myProject.isDefault()) {
showMessage(message, ConsoleViewContentType.SYSTEM_OUTPUT.getAttributes());
}
VcsBalloonProblemNotifier.showOverVersionControlView(myProject, message, MessageType.ERROR);
}
}
}
/**
* @return the version number of Git, which is used by IDEA. Or {@link GitVersion#NULL} if version info is unavailable yet.
*/
@NotNull
public GitVersion getVersion() {
return myVersion;
}
/**
* Shows a command line message in the Version Control Console
*/
public void showCommandLine(final String cmdLine) {
SimpleDateFormat f = new SimpleDateFormat("HH:mm:ss.SSS");
showMessage(f.format(new Date()) + ": " + cmdLine, ConsoleViewContentType.SYSTEM_OUTPUT.getAttributes());
}
/**
* Shows error message in the Version Control Console
*/
public void showErrorMessages(final String line) {
showMessage(line, ConsoleViewContentType.ERROR_OUTPUT.getAttributes());
}
@Override
public boolean allowsNestedRoots() {
return true;
}
@Override
public <S> List<S> filterUniqueRoots(final List<S> in, final Convertor<S, VirtualFile> convertor) {
Collections.sort(in, new ComparatorDelegate<S, VirtualFile>(convertor, FilePathComparator.getInstance()));
for (int i = 1; i < in.size(); i++) {
final S sChild = in.get(i);
final VirtualFile child = convertor.convert(sChild);
final VirtualFile childRoot = GitUtil.gitRootOrNull(child);
if (childRoot == null) {
// non-git file actually, skip it
continue;
}
for (int j = i - 1; j >= 0; --j) {
final S sParent = in.get(j);
final VirtualFile parent = convertor.convert(sParent);
// the method check both that parent is an ancestor of the child and that they share common git root
if (VfsUtilCore.isAncestor(parent, child, false) && VfsUtilCore.isAncestor(childRoot, parent, false)) {
in.remove(i);
//noinspection AssignmentToForLoopParameter
--i;
break;
}
}
}
return in;
}
@Override
public RootsConvertor getCustomConvertor() {
return GitRootConverter.INSTANCE;
}
public static VcsKey getKey() {
return ourKey;
}
@Override
public VcsType getType() {
return VcsType.distributed;
}
private final VcsOutgoingChangesProvider<CommittedChangeList> myOutgoingChangesProvider;
@Override
protected VcsOutgoingChangesProvider<CommittedChangeList> getOutgoingProviderImpl() {
return myOutgoingChangesProvider;
}
@Override
public RemoteDifferenceStrategy getRemoteDifferenceStrategy() {
return RemoteDifferenceStrategy.ASK_TREE_PROVIDER;
}
@Override
protected TreeDiffProvider getTreeDiffProviderImpl() {
return myTreeDiffProvider;
}
@Override
public List<CommitExecutor> getCommitExecutors() {
return Collections.<CommitExecutor>singletonList(myCommitAndPushExecutor);
}
@NotNull
public GitExecutableValidator getExecutableValidator() {
return myExecutableValidator;
}
@Override
public boolean fileListenerIsSynchronous() {
return false;
}
@Override
@CalledInAwt
public void enableIntegration() {
ApplicationManager.getApplication().executeOnPooledThread(new Runnable() {
public void run() {
Collection<VcsRoot> roots = ServiceManager.getService(myProject, VcsRootDetector.class).detect();
new GitIntegrationEnabler(GitVcs.this, myGit).enable(roots);
}
});
}
@Override
public CheckoutProvider getCheckoutProvider() {
return new GitCheckoutProvider(ServiceManager.getService(Git.class));
}
}
| [git] remove obsolete code
this code used to remove some hardcoded notification group,
and now can be deleted since 4 years should be enough for such a cleanup.
| plugins/git4idea/src/git4idea/GitVcs.java | [git] remove obsolete code | <ide><path>lugins/git4idea/src/git4idea/GitVcs.java
<ide> import com.intellij.ide.BrowserUtil;
<ide> import com.intellij.notification.Notification;
<ide> import com.intellij.notification.NotificationListener;
<del>import com.intellij.notification.impl.NotificationsConfigurationImpl;
<ide> import com.intellij.openapi.application.ApplicationManager;
<ide> import com.intellij.openapi.components.ServiceManager;
<ide> import com.intellij.openapi.diagnostic.Logger;
<ide> */
<ide> public class GitVcs extends AbstractVcs<CommittedChangeList> {
<ide>
<del> static {
<del> NotificationsConfigurationImpl.remove("Git");
<del> }
<del>
<ide> public static final String NAME = "Git";
<ide> public static final String ID = "git";
<ide> |
|
JavaScript | mit | 23c05f206d6cbf5958d9c3b1dd6b502c86ba069a | 0 | unhommequidort/react_redux,williampuk/ReduxCasts,titusjin/reduxExp,unhommequidort/react_redux,StephenGrider/ReduxCasts,williampuk/ReduxCasts,simplanapp/course,unhommequidort/react_redux,simplanapp/course,titusjin/reduxExp,StephenGrider/ReduxCasts,simplanapp/course,titusjin/reduxExp | import React, { Component } from 'react';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import { fetchWeather } from '../actions/index';
class SearchBar extends Component {
constructor(props) {
super(props);
this.state = { term: '' };
this.onInputChange = this.onInputChange.bind(this);
this.onFormSubmit = this.onFormSubmit.bind(this);
}
onInputChange(event) {
this.setState({ term: event.target.value });
}
onFormSubmit(event) {
event.preventDefault();
// We need to go and fetch weather data
this.props.fetchWeather(this.state.term);
this.setState({ term: '' });
}
render() {
return (
<form onSubmit={this.onFormSubmit} className="input-group">
<input
placeholder="Get a five-day forecast in your favorite cities"
className="form-control"
value={this.state.term}
onChange={this.onInputChange} />
<span className="input-group-btn">
<button type="submit" className="btn btn-secondary">Submit</button>
</span>
</form>
);
}
}
function mapDispatchToProps(dispatch) {
return bindActionCreators({ fetchWeather }, dispatch);
}
export default connect(null, mapDispatchToProps)(SearchBar);
| weather/src/containers/search_bar.js | import React, { Component } from 'react';
export default class SearchBar extends Component {
constructor(props) {
super(props);
this.state = { term: '' };
this.onInputChange = this.onInputChange.bind(this);
}
onInputChange(event) {
this.setState({ term: event.target.value });
}
onFormSubmit(event) {
event.preventDefault();
// We need to go and fetch weather data
}
render() {
return (
<form onSubmit={this.onFormSubmit} className="input-group">
<input
placeholder="Get a five-day forecast in your favorite cities"
className="form-control"
value={this.state.term}
onChange={this.onInputChange} />
<span className="input-group-btn">
<button type="submit" className="btn btn-secondary">Submit</button>
</span>
</form>
);
}
}
| searchbar calls fetch weather action creator
| weather/src/containers/search_bar.js | searchbar calls fetch weather action creator | <ide><path>eather/src/containers/search_bar.js
<ide> import React, { Component } from 'react';
<add>import { connect } from 'react-redux';
<add>import { bindActionCreators } from 'redux';
<add>import { fetchWeather } from '../actions/index';
<ide>
<del>export default class SearchBar extends Component {
<add>class SearchBar extends Component {
<ide> constructor(props) {
<ide> super(props);
<ide>
<ide> this.state = { term: '' };
<ide>
<ide> this.onInputChange = this.onInputChange.bind(this);
<add> this.onFormSubmit = this.onFormSubmit.bind(this);
<ide> }
<ide>
<ide> onInputChange(event) {
<ide> event.preventDefault();
<ide>
<ide> // We need to go and fetch weather data
<add> this.props.fetchWeather(this.state.term);
<add> this.setState({ term: '' });
<ide> }
<ide>
<ide> render() {
<ide> );
<ide> }
<ide> }
<add>
<add>function mapDispatchToProps(dispatch) {
<add> return bindActionCreators({ fetchWeather }, dispatch);
<add>}
<add>
<add>export default connect(null, mapDispatchToProps)(SearchBar); |
|
Java | mit | 9ade612ba68853a364e8e5ebf530f016479f1878 | 0 | FrogCraft-Rebirth/FrogCraft-Rebirth | /**
* This file is a part of FrogCraftRebirth,
* created by 3TSUK at 2:37:47 PM, Jul 21, 2016, CST
* FrogCraftRebirth, is open-source under MIT license,
* check https://github.com/FrogCraft-Rebirth/
* FrogCraft-Rebirth/LICENSE_FrogCraft_Rebirth for
* more information.
*/
package frogcraftrebirth.client;
import frogcraftrebirth.common.FrogBlocks;
import frogcraftrebirth.common.FrogItems;
import net.minecraftforge.fluids.BlockFluidBase;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
@SideOnly(Side.CLIENT)
public class FrogTextures {
public static void initFrogItemsTexture() {
RegHelper.registerModel(FrogItems.coolantAmmonia60K, "AmmoniaCoolant60K");
RegHelper.registerModel(FrogItems.coolantAmmonia180K, "AmmoniaCoolant180K");
RegHelper.registerModel(FrogItems.coolantAmmonia360K, "AmmoniaCoolant360K");
RegHelper.registerModel(FrogItems.decayBatteryPlutoium, "DecayBatteryPlutoium");
RegHelper.registerModel(FrogItems.decayBatteryThorium, "DecayBatteryThorium");
RegHelper.registerModel(FrogItems.decayBatteryUranium, "DecayBatteryUranium");
RegHelper.registerModel(FrogItems.ionCannon);
RegHelper.registerModel(FrogItems.ionCannonFrame);
RegHelper.registerModel(FrogItems.jinkela, "GoldClod");
RegHelper.registerModel(FrogItems.tiberium, 0, "TiberiumRed");
RegHelper.registerModel(FrogItems.tiberium, 1, "TiberiumBlue");
RegHelper.registerModel(FrogItems.tiberium, 2, "TiberiumGreen");
RegHelper.registerModel(FrogItems.itemReactionModule, 0, "ModuleHeating");
RegHelper.registerModel(FrogItems.itemReactionModule, 1, "ModuleElectrolyze");
RegHelper.registerModel(FrogItems.itemReactionModule, 2, "ModuleAmmonia");
RegHelper.registerModel(FrogItems.itemReactionModule, 3, "ModuleSulfuricAcid");
RegHelper.registerModel(FrogItems.itemIngot, 0, "Potassium");
RegHelper.registerModel(FrogItems.itemIngot, 1, "Phosphorus");
RegHelper.registerModel(FrogItems.itemIngot, 2, "NaturalGasHydrate");
RegHelper.registerModel(FrogItems.itemIngot, 3, "Briquette");
RegHelper.registerModel(FrogItems.itemIngot, 4, "ShatteredCoalCoke");
final String[] damnitSubNames = {"Al2O3", "CaF2", "CaO", "CaOH2", "Carnallite", "CaSiO3", "Dewalquite", "Fluorapatite", "KCl", "Magnalium", "MgBr2", "NH4NO3", "TiO2", "Urea", "V2O5"};
for (int index = 0; index < damnitSubNames.length; index++) {
RegHelper.registerModel(FrogItems.itemDust, index, "dust/" + damnitSubNames[index]);
}
}
public static void initFrogBlocksTexture() {
RegHelper.registerModel(FrogBlocks.frogOres, 0, "Carnallite");
RegHelper.registerModel(FrogBlocks.frogOres, 1, "Dewalquite");
RegHelper.registerModel(FrogBlocks.frogOres, 2, "Fluorapatite");
RegHelper.registerModel(FrogBlocks.tiberium, 0);
RegHelper.registerModel(FrogBlocks.tiberium, 1);
RegHelper.registerModel(FrogBlocks.tiberium, 2);
RegHelper.registerModel(FrogBlocks.mobilePowerStation, "MPS");
RegHelper.registerModel(FrogBlocks.condenseTowerPart, 0, "condensetower/Core");
RegHelper.registerModel(FrogBlocks.condenseTowerPart, 1, "condensetower/Cylinder");
RegHelper.registerModel(FrogBlocks.condenseTowerPart, 2, "condensetower/Output");
RegHelper.registerModel(FrogBlocks.machines, 0, "AdvancedChemicalReactor");
RegHelper.registerModel(FrogBlocks.machines, 1, "AirPump");
RegHelper.registerModel(FrogBlocks.machines, 2, "Pyrolyzer");
RegHelper.registerModel(FrogBlocks.machines, 3, "Liquefier");
RegHelper.registerModel(FrogBlocks.generators, "CombustionGenerator");
RegHelper.registerModel(FrogBlocks.hybridStorageUnit, 0, "HSU");
RegHelper.registerModel(FrogBlocks.hybridStorageUnit, 1, "UHSU");
RegHelper.regFluidBlockTexture((BlockFluidBase)FrogBlocks.fluidAmmonia, "ammonia");
RegHelper.regFluidBlockTexture((BlockFluidBase)FrogBlocks.fluidArgon, "argon");
RegHelper.regFluidBlockTexture((BlockFluidBase)FrogBlocks.fluidBenzene, "benzene");
RegHelper.regFluidBlockTexture((BlockFluidBase)FrogBlocks.fluidBromine, "bromine");
RegHelper.regFluidBlockTexture((BlockFluidBase)FrogBlocks.fluidCarbonDioxide, "carbon_dioxide");
RegHelper.regFluidBlockTexture((BlockFluidBase)FrogBlocks.fluidCarbonOxide, "carbon_oxide");
RegHelper.regFluidBlockTexture((BlockFluidBase)FrogBlocks.fluidCoalTar, "coal_tar");
RegHelper.regFluidBlockTexture((BlockFluidBase)FrogBlocks.fluidFluorine, "fluorine");
RegHelper.regFluidBlockTexture((BlockFluidBase)FrogBlocks.fluidNitricAcid, "nitric_acid");
RegHelper.regFluidBlockTexture((BlockFluidBase)FrogBlocks.fluidNitrogenOxide, "nitrogen_oxide");
RegHelper.regFluidBlockTexture((BlockFluidBase)FrogBlocks.fluidOxygen, "oxygen");
RegHelper.regFluidBlockTexture((BlockFluidBase)FrogBlocks.fluidSulfurDioxide, "sulfur_dioxide");
RegHelper.regFluidBlockTexture((BlockFluidBase)FrogBlocks.fluidSulfurTrioxide, "sulfur_trioxide");
}
}
| src/main/java/frogcraftrebirth/client/FrogTextures.java | /**
* This file is a part of FrogCraftRebirth,
* created by 3TSUK at 2:37:47 PM, Jul 21, 2016, CST
* FrogCraftRebirth, is open-source under MIT license,
* check https://github.com/FrogCraft-Rebirth/
* FrogCraft-Rebirth/LICENSE_FrogCraft_Rebirth for
* more information.
*/
package frogcraftrebirth.client;
import frogcraftrebirth.common.FrogBlocks;
import frogcraftrebirth.common.FrogItems;
import net.minecraftforge.fluids.BlockFluidBase;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
@SideOnly(Side.CLIENT)
public class FrogTextures {
public static void initFrogItemsTexture() {
RegHelper.registerModel(FrogItems.coolantAmmonia60K, "AmmoniaCoolant60K");
RegHelper.registerModel(FrogItems.coolantAmmonia180K, "AmmoniaCoolant180K");
RegHelper.registerModel(FrogItems.coolantAmmonia360K, "AmmoniaCoolant360K");
RegHelper.registerModel(FrogItems.decayBatteryPlutoium, "DecayBatteryPlutoium");
RegHelper.registerModel(FrogItems.decayBatteryThorium, "DecayBatteryThorium");
RegHelper.registerModel(FrogItems.decayBatteryUranium, "DecayBatteryUranium");
RegHelper.registerModel(FrogItems.ionCannon);
RegHelper.registerModel(FrogItems.ionCannonFrame);
RegHelper.registerModel(FrogItems.jinkela, "GoldClod");
RegHelper.registerModel(FrogItems.tiberium, 0, "TiberiumRed");
RegHelper.registerModel(FrogItems.tiberium, 1, "TiberiumBlue");
RegHelper.registerModel(FrogItems.tiberium, 2, "TiberiumGreen");
RegHelper.registerModel(FrogItems.itemReactionModule, 0, "ModuleHeating");
RegHelper.registerModel(FrogItems.itemReactionModule, 1, "ModuleElectrolyze");
RegHelper.registerModel(FrogItems.itemReactionModule, 2, "ModuleAmmonia");
RegHelper.registerModel(FrogItems.itemReactionModule, 3, "ModuleSulfuricAcid");
RegHelper.registerModel(FrogItems.itemIngot, 0, "Potassium");
RegHelper.registerModel(FrogItems.itemIngot, 1, "Phosphorus");
RegHelper.registerModel(FrogItems.itemIngot, 2, "NaturalGasHydrate");
RegHelper.registerModel(FrogItems.itemIngot, 3, "Briquette");
RegHelper.registerModel(FrogItems.itemIngot, 4, "ShatteredCoalCoke");
final String[] damnitSubNames = {"Al2O3", "CaF2", "CaO", "CaOH2", "Carnallite", "CaSiO3", "Dewalquite", "Fluorapatite", "KCl", "Magnalium", "MgBr2", "NH4NO3", "TiO2", "Urea", "V2O5"};
for (int index = 0; index < damnitSubNames.length; index++) {
RegHelper.registerModel(FrogItems.itemDust, index, "dust/" + damnitSubNames[index]);
}
}
public static void initFrogBlocksTexture() {
RegHelper.registerModel(FrogBlocks.frogOres, 0, "Carnallite");
RegHelper.registerModel(FrogBlocks.frogOres, 1, "Dewalquite");
RegHelper.registerModel(FrogBlocks.frogOres, 2, "Fluorapatite");
RegHelper.registerModel(FrogBlocks.tiberium, 0);
RegHelper.registerModel(FrogBlocks.tiberium, 1);
RegHelper.registerModel(FrogBlocks.tiberium, 2);
RegHelper.registerModel(FrogBlocks.mobilePowerStation, "MPS");
RegHelper.registerModel(FrogBlocks.condenseTowerPart, 0, "condensetower/Core");
RegHelper.registerModel(FrogBlocks.condenseTowerPart, 1, "condensetower/Cylinder");
RegHelper.registerModel(FrogBlocks.condenseTowerPart, 2, "condensetower/Output");
RegHelper.registerModel(FrogBlocks.machines, 0, "AdvancedChemicalReactor");
RegHelper.registerModel(FrogBlocks.machines, 1, "AirPump");
RegHelper.registerModel(FrogBlocks.machines, 2, "Liquefier");
RegHelper.registerModel(FrogBlocks.machines, 3, "Pyrolyzer");
RegHelper.registerModel(FrogBlocks.generators, "CombustionGenerator");
RegHelper.registerModel(FrogBlocks.hybridStorageUnit, 0, "HSU");
RegHelper.registerModel(FrogBlocks.hybridStorageUnit, 1, "UHSU");
RegHelper.regFluidBlockTexture((BlockFluidBase)FrogBlocks.fluidAmmonia, "ammonia");
RegHelper.regFluidBlockTexture((BlockFluidBase)FrogBlocks.fluidArgon, "argon");
RegHelper.regFluidBlockTexture((BlockFluidBase)FrogBlocks.fluidBenzene, "benzene");
RegHelper.regFluidBlockTexture((BlockFluidBase)FrogBlocks.fluidBromine, "bromine");
RegHelper.regFluidBlockTexture((BlockFluidBase)FrogBlocks.fluidCarbonDioxide, "carbon_dioxide");
RegHelper.regFluidBlockTexture((BlockFluidBase)FrogBlocks.fluidCarbonOxide, "carbon_oxide");
RegHelper.regFluidBlockTexture((BlockFluidBase)FrogBlocks.fluidCoalTar, "coal_tar");
RegHelper.regFluidBlockTexture((BlockFluidBase)FrogBlocks.fluidFluorine, "fluorine");
RegHelper.regFluidBlockTexture((BlockFluidBase)FrogBlocks.fluidNitricAcid, "nitric_acid");
RegHelper.regFluidBlockTexture((BlockFluidBase)FrogBlocks.fluidNitrogenOxide, "nitrogen_oxide");
RegHelper.regFluidBlockTexture((BlockFluidBase)FrogBlocks.fluidOxygen, "oxygen");
RegHelper.regFluidBlockTexture((BlockFluidBase)FrogBlocks.fluidSulfurDioxide, "sulfur_dioxide");
RegHelper.regFluidBlockTexture((BlockFluidBase)FrogBlocks.fluidSulfurTrioxide, "sulfur_trioxide");
}
}
| Switch "Pyrolyzer" and "Liquefier" because I messed up previously | src/main/java/frogcraftrebirth/client/FrogTextures.java | Switch "Pyrolyzer" and "Liquefier" because I messed up previously | <ide><path>rc/main/java/frogcraftrebirth/client/FrogTextures.java
<ide>
<ide> RegHelper.registerModel(FrogBlocks.machines, 0, "AdvancedChemicalReactor");
<ide> RegHelper.registerModel(FrogBlocks.machines, 1, "AirPump");
<del> RegHelper.registerModel(FrogBlocks.machines, 2, "Liquefier");
<del> RegHelper.registerModel(FrogBlocks.machines, 3, "Pyrolyzer");
<add> RegHelper.registerModel(FrogBlocks.machines, 2, "Pyrolyzer");
<add> RegHelper.registerModel(FrogBlocks.machines, 3, "Liquefier");
<ide>
<ide> RegHelper.registerModel(FrogBlocks.generators, "CombustionGenerator");
<ide> |
|
Java | mpl-2.0 | da2886b8027fde4947736fc6d0a864565c2c8a3c | 0 | GreenDelta/Sophena,GreenDelta/Sophena,GreenDelta/Sophena,GreenDelta/Sophena,GreenDelta/Sophena | package sophena.rcp.editors.results.compare;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.ui.forms.widgets.FormToolkit;
import sophena.calc.CO2Result;
import sophena.calc.Comparison;
import sophena.math.energetic.EfficiencyResult;
import sophena.math.energetic.PrimaryEnergyFactor;
import sophena.math.energetic.Producers;
import sophena.math.energetic.UsedHeat;
import sophena.model.Producer;
import sophena.model.Project;
import sophena.rcp.utils.UI;
import sophena.utils.Num;
class KeyFigureTable {
private final Comparison result;
private KeyFigureTable(Comparison result) {
this.result = result;
}
static KeyFigureTable of(Comparison result) {
return new KeyFigureTable(result);
}
void render(Composite body, FormToolkit tk) {
Composite comp = UI.formSection(body, tk,
"Energetische Kennzahlen");
Table table = new Table(result);
createItems(table);
table.render(comp);
}
private void createItems(Table table) {
table.row("Erzeugte Wärmemenge", i -> Num.intStr(
result.results[i].energyResult.totalProducedHeat) + " kWh");
table.row("Installierte Leistung", this::installedPower);
table.row("Trassenlänge",
i -> Num.intStr(result.projects[i].heatNet.length) + " m");
table.row("Wärmebelegungsdichte", this::heatOccupancyDensity);
table.row("Netzverluste", this::distributionLoss);
table.row("CO2-Einsparung (gegen Erdgas dezentral)",
this::emissionSavings);
table.row("Primärenergiefaktor",
i -> Num.str(PrimaryEnergyFactor.get(result.results[i]), 2));
}
private String installedPower(int i) {
Project project = result.projects[i];
double power = 0.0;
for (Producer p : project.producers) {
if (p.disabled)
continue;
power += Producers.maxPower(p);
}
return Num.intStr(power) + " kW";
}
private String heatOccupancyDensity(int i) {
double length = result.projects[i].heatNet.length;
double hl = length == 0 ? 0
: UsedHeat.get(result.results[i]) / (1000 * length);
return Num.str(hl, 2) + " MWh/(m*a)";
}
private String distributionLoss(int i) {
EfficiencyResult er = EfficiencyResult.calculate(result.results[i]);
double loss = 0;
if (er.fuelEnergy > 0) {
loss = 100 * er.distributionLoss / er.fuelEnergy;
}
return Num.intStr(loss) + " %";
}
private String emissionSavings(int i) {
CO2Result co2 = result.results[i].co2Result;
double savings = co2.variantNaturalGas - co2.total;
return Num.intStr(savings) + " kg CO2 eq./a";
}
}
| sophena/src/sophena/rcp/editors/results/compare/KeyFigureTable.java | package sophena.rcp.editors.results.compare;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.ui.forms.widgets.FormToolkit;
import sophena.calc.CO2Result;
import sophena.calc.Comparison;
import sophena.math.energetic.EfficiencyResult;
import sophena.math.energetic.Producers;
import sophena.math.energetic.UsedHeat;
import sophena.model.Producer;
import sophena.model.Project;
import sophena.rcp.utils.UI;
import sophena.utils.Num;
class KeyFigureTable {
private final Comparison result;
private KeyFigureTable(Comparison result) {
this.result = result;
}
static KeyFigureTable of(Comparison result) {
return new KeyFigureTable(result);
}
void render(Composite body, FormToolkit tk) {
Composite comp = UI.formSection(body, tk,
"Energetische Kennzahlen");
Table table = new Table(result);
createItems(table);
table.render(comp);
}
private void createItems(Table table) {
table.row("Erzeugte Wärmemenge", i -> Num.intStr(
result.results[i].energyResult.totalProducedHeat) + " kWh");
table.row("Installierte Leistung", this::installedPower);
table.row("Trassenlänge",
i -> Num.intStr(result.projects[i].heatNet.length) + " m");
table.row("Wärmebelegungsdichte", this::heatOccupancyDensity);
table.row("Netzverluste", this::distributionLoss);
table.row("CO2-Einsparung (gegen Erdgas dezentral)",
this::emissionSavings);
}
private String installedPower(int i) {
Project project = result.projects[i];
double power = 0.0;
for (Producer p : project.producers) {
if (p.disabled)
continue;
power += Producers.maxPower(p);
}
return Num.intStr(power) + " kW";
}
private String heatOccupancyDensity(int i) {
double length = result.projects[i].heatNet.length;
double hl = length == 0 ? 0
: UsedHeat.get(result.results[i]) / (1000 * length);
return Num.str(hl, 2) + " MWh/(m*a)";
}
private String distributionLoss(int i) {
EfficiencyResult er = EfficiencyResult.calculate(result.results[i]);
double loss = 0;
if (er.fuelEnergy > 0) {
loss = 100 * er.distributionLoss / er.fuelEnergy;
}
return Num.intStr(loss) + " %";
}
private String emissionSavings(int i) {
CO2Result co2 = result.results[i].co2Result;
double savings = co2.variantNaturalGas - co2.total;
return Num.intStr(savings) + " kg CO2 eq./a";
}
}
| #64 display primary energy factor in project comparisons | sophena/src/sophena/rcp/editors/results/compare/KeyFigureTable.java | #64 display primary energy factor in project comparisons | <ide><path>ophena/src/sophena/rcp/editors/results/compare/KeyFigureTable.java
<ide> import sophena.calc.CO2Result;
<ide> import sophena.calc.Comparison;
<ide> import sophena.math.energetic.EfficiencyResult;
<add>import sophena.math.energetic.PrimaryEnergyFactor;
<ide> import sophena.math.energetic.Producers;
<ide> import sophena.math.energetic.UsedHeat;
<ide> import sophena.model.Producer;
<ide> table.row("Netzverluste", this::distributionLoss);
<ide> table.row("CO2-Einsparung (gegen Erdgas dezentral)",
<ide> this::emissionSavings);
<add> table.row("Primärenergiefaktor",
<add> i -> Num.str(PrimaryEnergyFactor.get(result.results[i]), 2));
<ide> }
<ide>
<ide> private String installedPower(int i) { |
|
Java | apache-2.0 | 415155f45860560619511ee015b967dad00d4c9e | 0 | mingzuozhibi/mzzb-server,mingzuozhibi/mzzb-server | package mingzuozhibi.config;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.web.bind.annotation.RestController;
@RestController
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
@Autowired
private UserDetailsService userDetailsService;
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService);
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/api/users/**").hasRole("ADMIN")
.antMatchers(HttpMethod.GET).permitAll()
.antMatchers("/api/login").permitAll()
.antMatchers("/api/**").hasRole("USER");
http.csrf().disable();
Logger logger = LoggerFactory.getLogger(getClass());
if (logger.isInfoEnabled()) {
logger.info("设置安全策略");
}
}
}
| src/main/java/mingzuozhibi/config/SecurityConfiguration.java | package mingzuozhibi.config;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.web.bind.annotation.RestController;
@RestController
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
@Autowired
private UserDetailsService userDetailsService;
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService);
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/api/users/**").hasRole("ADMIN")
.antMatchers(HttpMethod.GET).permitAll()
.antMatchers("/api/login").permitAll()
.antMatchers("/api/**").hasRole("USER");
http.httpBasic();
http.csrf().disable();
Logger logger = LoggerFactory.getLogger(getClass());
if (logger.isInfoEnabled()) {
logger.info("设置安全策略");
}
}
}
| feat: remove http basic auth
| src/main/java/mingzuozhibi/config/SecurityConfiguration.java | feat: remove http basic auth | <ide><path>rc/main/java/mingzuozhibi/config/SecurityConfiguration.java
<ide> .antMatchers(HttpMethod.GET).permitAll()
<ide> .antMatchers("/api/login").permitAll()
<ide> .antMatchers("/api/**").hasRole("USER");
<del> http.httpBasic();
<ide> http.csrf().disable();
<ide>
<ide> Logger logger = LoggerFactory.getLogger(getClass()); |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.