diff --git a/app/client/cypress/fixtures/library_export.json b/app/client/cypress/fixtures/library_export.json new file mode 100644 index 0000000000..e7f6636de4 --- /dev/null +++ b/app/client/cypress/fixtures/library_export.json @@ -0,0 +1 @@ +{"clientSchemaVersion":1.0,"serverSchemaVersion":6.0,"exportedApplication":{"name":"Library_export","isPublic":false,"pages":[{"id":"Page1","isDefault":true}],"publishedPages":[{"id":"Page1","isDefault":true}],"viewMode":false,"appIsExample":false,"unreadCommentThreads":0.0,"color":"#E4D8CC","icon":"hat","slug":"library-export","unpublishedCustomJSLibs":[{"uidString":"UUID_https://cdn.jsdelivr.net/npm/uuidjs@4.2.12/src/uuid.min.js"}],"publishedCustomJSLibs":[],"evaluationVersion":2.0,"applicationVersion":2.0,"isManualUpdate":false,"deleted":false},"customJSLibList":[{"name":"uuidjs","uidString":"UUID_https://cdn.jsdelivr.net/npm/uuidjs@4.2.12/src/uuid.min.js","accessor":["UUID"],"url":"https://cdn.jsdelivr.net/npm/uuidjs@4.2.12/src/uuid.min.js","version":"4.2.12","defs":"{\"!name\":\"LIB/UUID\",\"UUID\":{\"!type\":\"fn()\",\"prototype\":{\"_init\":{\"!type\":\"fn()\",\"prototype\":{}},\"toString\":{\"!type\":\"fn()\",\"prototype\":{}},\"equals\":{\"!type\":\"fn()\",\"prototype\":{}}},\"generate\":{\"!type\":\"fn()\",\"prototype\":{}},\"_getRandomInt\":{\"!type\":\"fn()\",\"prototype\":{}},\"_hexAligner\":{\"!type\":\"fn()\",\"prototype\":{}},\"overwrittenUUID\":{\"!type\":\"?\"},\"useMathRandom\":{\"!type\":\"fn()\",\"prototype\":{}},\"FIELD_NAMES\":{\"0\":{\"!type\":\"string\"},\"1\":{\"!type\":\"string\"},\"2\":{\"!type\":\"string\"},\"3\":{\"!type\":\"string\"},\"4\":{\"!type\":\"string\"},\"5\":{\"!type\":\"string\"},\"at\":{\"!type\":\"fn()\"},\"concat\":{\"!type\":\"fn()\"},\"copyWithin\":{\"!type\":\"fn()\"},\"fill\":{\"!type\":\"fn()\"},\"find\":{\"!type\":\"fn()\"},\"findIndex\":{\"!type\":\"fn()\"},\"lastIndexOf\":{\"!type\":\"fn()\"},\"pop\":{\"!type\":\"fn()\"},\"push\":{\"!type\":\"fn()\"},\"reverse\":{\"!type\":\"fn()\"},\"shift\":{\"!type\":\"fn()\"},\"unshift\":{\"!type\":\"fn()\"},\"slice\":{\"!type\":\"fn()\"},\"sort\":{\"!type\":\"fn()\"},\"splice\":{\"!type\":\"fn()\"},\"includes\":{\"!type\":\"fn()\"},\"indexOf\":{\"!type\":\"fn()\"},\"join\":{\"!type\":\"fn()\"},\"keys\":{\"!type\":\"fn()\"},\"entries\":{\"!type\":\"fn()\"},\"values\":{\"!type\":\"fn()\"},\"forEach\":{\"!type\":\"fn()\"},\"filter\":{\"!type\":\"fn()\"},\"flat\":{\"!type\":\"fn()\"},\"flatMap\":{\"!type\":\"fn()\"},\"map\":{\"!type\":\"fn()\"},\"every\":{\"!type\":\"fn()\"},\"some\":{\"!type\":\"fn()\"},\"reduce\":{\"!type\":\"fn()\"},\"reduceRight\":{\"!type\":\"fn()\"},\"toLocaleString\":{\"!type\":\"fn()\"},\"toString\":{\"!type\":\"fn()\"},\"findLast\":{\"!type\":\"fn()\"},\"findLastIndex\":{\"!type\":\"fn()\"}},\"FIELD_SIZES\":{\"0\":{\"!type\":\"number\"},\"1\":{\"!type\":\"number\"},\"2\":{\"!type\":\"number\"},\"3\":{\"!type\":\"number\"},\"4\":{\"!type\":\"number\"},\"5\":{\"!type\":\"number\"},\"at\":{\"!type\":\"fn()\"},\"concat\":{\"!type\":\"fn()\"},\"copyWithin\":{\"!type\":\"fn()\"},\"fill\":{\"!type\":\"fn()\"},\"find\":{\"!type\":\"fn()\"},\"findIndex\":{\"!type\":\"fn()\"},\"lastIndexOf\":{\"!type\":\"fn()\"},\"pop\":{\"!type\":\"fn()\"},\"push\":{\"!type\":\"fn()\"},\"reverse\":{\"!type\":\"fn()\"},\"shift\":{\"!type\":\"fn()\"},\"unshift\":{\"!type\":\"fn()\"},\"slice\":{\"!type\":\"fn()\"},\"sort\":{\"!type\":\"fn()\"},\"splice\":{\"!type\":\"fn()\"},\"includes\":{\"!type\":\"fn()\"},\"indexOf\":{\"!type\":\"fn()\"},\"join\":{\"!type\":\"fn()\"},\"keys\":{\"!type\":\"fn()\"},\"entries\":{\"!type\":\"fn()\"},\"values\":{\"!type\":\"fn()\"},\"forEach\":{\"!type\":\"fn()\"},\"filter\":{\"!type\":\"fn()\"},\"flat\":{\"!type\":\"fn()\"},\"flatMap\":{\"!type\":\"fn()\"},\"map\":{\"!type\":\"fn()\"},\"every\":{\"!type\":\"fn()\"},\"some\":{\"!type\":\"fn()\"},\"reduce\":{\"!type\":\"fn()\"},\"reduceRight\":{\"!type\":\"fn()\"},\"toLocaleString\":{\"!type\":\"fn()\"},\"toString\":{\"!type\":\"fn()\"},\"findLast\":{\"!type\":\"fn()\"},\"findLastIndex\":{\"!type\":\"fn()\"}},\"genV4\":{\"!type\":\"fn()\",\"prototype\":{}},\"parse\":{\"!type\":\"fn()\",\"prototype\":{}},\"_binAligner\":{\"!type\":\"fn()\",\"prototype\":{}},\"NIL\":{\"intFields\":{\"0\":{\"!type\":\"number\"},\"1\":{\"!type\":\"number\"},\"2\":{\"!type\":\"number\"},\"3\":{\"!type\":\"number\"},\"4\":{\"!type\":\"number\"},\"5\":{\"!type\":\"number\"},\"timeLow\":{\"!type\":\"number\"},\"timeMid\":{\"!type\":\"number\"},\"timeHiAndVersion\":{\"!type\":\"number\"},\"clockSeqHiAndReserved\":{\"!type\":\"number\"},\"clockSeqLow\":{\"!type\":\"number\"},\"node\":{\"!type\":\"number\"},\"at\":{\"!type\":\"fn()\"},\"concat\":{\"!type\":\"fn()\"},\"copyWithin\":{\"!type\":\"fn()\"},\"fill\":{\"!type\":\"fn()\"},\"find\":{\"!type\":\"fn()\"},\"findIndex\":{\"!type\":\"fn()\"},\"lastIndexOf\":{\"!type\":\"fn()\"},\"pop\":{\"!type\":\"fn()\"},\"push\":{\"!type\":\"fn()\"},\"reverse\":{\"!type\":\"fn()\"},\"shift\":{\"!type\":\"fn()\"},\"unshift\":{\"!type\":\"fn()\"},\"slice\":{\"!type\":\"fn()\"},\"sort\":{\"!type\":\"fn()\"},\"splice\":{\"!type\":\"fn()\"},\"includes\":{\"!type\":\"fn()\"},\"indexOf\":{\"!type\":\"fn()\"},\"join\":{\"!type\":\"fn()\"},\"keys\":{\"!type\":\"fn()\"},\"entries\":{\"!type\":\"fn()\"},\"values\":{\"!type\":\"fn()\"},\"forEach\":{\"!type\":\"fn()\"},\"filter\":{\"!type\":\"fn()\"},\"flat\":{\"!type\":\"fn()\"},\"flatMap\":{\"!type\":\"fn()\"},\"map\":{\"!type\":\"fn()\"},\"every\":{\"!type\":\"fn()\"},\"some\":{\"!type\":\"fn()\"},\"reduce\":{\"!type\":\"fn()\"},\"reduceRight\":{\"!type\":\"fn()\"},\"toLocaleString\":{\"!type\":\"fn()\"},\"toString\":{\"!type\":\"fn()\"},\"findLast\":{\"!type\":\"fn()\"},\"findLastIndex\":{\"!type\":\"fn()\"}},\"bitFields\":{\"0\":{\"!type\":\"string\"},\"1\":{\"!type\":\"string\"},\"2\":{\"!type\":\"string\"},\"3\":{\"!type\":\"string\"},\"4\":{\"!type\":\"string\"},\"5\":{\"!type\":\"string\"},\"timeLow\":{\"!type\":\"string\"},\"timeMid\":{\"!type\":\"string\"},\"timeHiAndVersion\":{\"!type\":\"string\"},\"clockSeqHiAndReserved\":{\"!type\":\"string\"},\"clockSeqLow\":{\"!type\":\"string\"},\"node\":{\"!type\":\"string\"},\"at\":{\"!type\":\"fn()\"},\"concat\":{\"!type\":\"fn()\"},\"copyWithin\":{\"!type\":\"fn()\"},\"fill\":{\"!type\":\"fn()\"},\"find\":{\"!type\":\"fn()\"},\"findIndex\":{\"!type\":\"fn()\"},\"lastIndexOf\":{\"!type\":\"fn()\"},\"pop\":{\"!type\":\"fn()\"},\"push\":{\"!type\":\"fn()\"},\"reverse\":{\"!type\":\"fn()\"},\"shift\":{\"!type\":\"fn()\"},\"unshift\":{\"!type\":\"fn()\"},\"slice\":{\"!type\":\"fn()\"},\"sort\":{\"!type\":\"fn()\"},\"splice\":{\"!type\":\"fn()\"},\"includes\":{\"!type\":\"fn()\"},\"indexOf\":{\"!type\":\"fn()\"},\"join\":{\"!type\":\"fn()\"},\"keys\":{\"!type\":\"fn()\"},\"entries\":{\"!type\":\"fn()\"},\"values\":{\"!type\":\"fn()\"},\"forEach\":{\"!type\":\"fn()\"},\"filter\":{\"!type\":\"fn()\"},\"flat\":{\"!type\":\"fn()\"},\"flatMap\":{\"!type\":\"fn()\"},\"map\":{\"!type\":\"fn()\"},\"every\":{\"!type\":\"fn()\"},\"some\":{\"!type\":\"fn()\"},\"reduce\":{\"!type\":\"fn()\"},\"reduceRight\":{\"!type\":\"fn()\"},\"toLocaleString\":{\"!type\":\"fn()\"},\"toString\":{\"!type\":\"fn()\"},\"findLast\":{\"!type\":\"fn()\"},\"findLastIndex\":{\"!type\":\"fn()\"}},\"hexFields\":{\"0\":{\"!type\":\"string\"},\"1\":{\"!type\":\"string\"},\"2\":{\"!type\":\"string\"},\"3\":{\"!type\":\"string\"},\"4\":{\"!type\":\"string\"},\"5\":{\"!type\":\"string\"},\"timeLow\":{\"!type\":\"string\"},\"timeMid\":{\"!type\":\"string\"},\"timeHiAndVersion\":{\"!type\":\"string\"},\"clockSeqHiAndReserved\":{\"!type\":\"string\"},\"clockSeqLow\":{\"!type\":\"string\"},\"node\":{\"!type\":\"string\"},\"at\":{\"!type\":\"fn()\"},\"concat\":{\"!type\":\"fn()\"},\"copyWithin\":{\"!type\":\"fn()\"},\"fill\":{\"!type\":\"fn()\"},\"find\":{\"!type\":\"fn()\"},\"findIndex\":{\"!type\":\"fn()\"},\"lastIndexOf\":{\"!type\":\"fn()\"},\"pop\":{\"!type\":\"fn()\"},\"push\":{\"!type\":\"fn()\"},\"reverse\":{\"!type\":\"fn()\"},\"shift\":{\"!type\":\"fn()\"},\"unshift\":{\"!type\":\"fn()\"},\"slice\":{\"!type\":\"fn()\"},\"sort\":{\"!type\":\"fn()\"},\"splice\":{\"!type\":\"fn()\"},\"includes\":{\"!type\":\"fn()\"},\"indexOf\":{\"!type\":\"fn()\"},\"join\":{\"!type\":\"fn()\"},\"keys\":{\"!type\":\"fn()\"},\"entries\":{\"!type\":\"fn()\"},\"values\":{\"!type\":\"fn()\"},\"forEach\":{\"!type\":\"fn()\"},\"filter\":{\"!type\":\"fn()\"},\"flat\":{\"!type\":\"fn()\"},\"flatMap\":{\"!type\":\"fn()\"},\"map\":{\"!type\":\"fn()\"},\"every\":{\"!type\":\"fn()\"},\"some\":{\"!type\":\"fn()\"},\"reduce\":{\"!type\":\"fn()\"},\"reduceRight\":{\"!type\":\"fn()\"},\"toLocaleString\":{\"!type\":\"fn()\"},\"toString\":{\"!type\":\"fn()\"},\"findLast\":{\"!type\":\"fn()\"},\"findLastIndex\":{\"!type\":\"fn()\"}},\"version\":{\"!type\":\"number\"},\"bitString\":{\"!type\":\"string\"},\"hexNoDelim\":{\"!type\":\"string\"},\"hexString\":{\"!type\":\"string\"},\"urn\":{\"!type\":\"string\"},\"_init\":{\"!type\":\"fn()\",\"prototype\":{}},\"toString\":{\"!type\":\"fn()\",\"prototype\":{}},\"equals\":{\"!type\":\"fn()\",\"prototype\":{}}},\"genV1\":{\"!type\":\"fn()\",\"prototype\":{}},\"resetState\":{\"!type\":\"fn()\",\"prototype\":{}},\"_tsRatio\":{\"!type\":\"number\"},\"_state\":{\"!type\":\"?\"},\"_getTimeFieldValues\":{\"!type\":\"fn()\",\"prototype\":{}}}}","id":"638f4fadf55aed39870d4fc6","createdAt":"2022-12-06T14:20:29Z","updatedAt":"2022-12-06T14:20:29Z","deleted":false,"policies":[],"userPermissions":[]}],"datasourceList":[],"pageList":[{"unpublishedPage":{"name":"Page1","slug":"page1","layouts":[{"viewMode":false,"dsl":{"widgetName":"MainContainer","backgroundColor":"none","rightColumn":4896.0,"snapColumns":64.0,"detachFromLayout":true,"widgetId":"0","topRow":0.0,"bottomRow":5000.0,"containerStyle":"none","snapRows":125.0,"parentRowSpace":1.0,"type":"CANVAS_WIDGET","canExtend":true,"version":72.0,"minHeight":1292.0,"dynamicTriggerPathList":[],"parentColumnSpace":1.0,"dynamicBindingPathList":[],"leftColumn":0.0,"children":[]},"layoutOnLoadActions":[[{"id":"Page1_JSObject1.myFun2","name":"JSObject1.myFun2","collectionId":"Page1_JSObject1","clientSideExecution":true,"confirmBeforeExecute":false,"pluginType":"JS","jsonPathKeys":["async () => {\n showAlert((typeof UUID !== undefined).toString());\n}"],"timeoutInMillisecond":10000.0}]],"layoutOnLoadActionErrors":[],"validOnPageLoadActions":true,"id":"Page1","deleted":false,"policies":[],"userPermissions":[]}],"userPermissions":[],"policies":[]},"publishedPage":{"name":"Page1","slug":"page1","layouts":[{"viewMode":false,"dsl":{"widgetName":"MainContainer","backgroundColor":"none","rightColumn":1224.0,"snapColumns":16.0,"detachFromLayout":true,"widgetId":"0","topRow":0.0,"bottomRow":1250.0,"containerStyle":"none","snapRows":33.0,"parentRowSpace":1.0,"type":"CANVAS_WIDGET","canExtend":true,"version":4.0,"minHeight":1292.0,"dynamicTriggerPathList":[],"parentColumnSpace":1.0,"dynamicBindingPathList":[],"leftColumn":0.0,"children":[]},"validOnPageLoadActions":true,"id":"Page1","deleted":false,"policies":[],"userPermissions":[]}],"userPermissions":[],"policies":[]},"deleted":false,"gitSyncId":"63a05e664de0da6d2f4b7567_63a05e664de0da6d2f4b7569"}],"actionList":[{"pluginType":"JS","pluginId":"js-plugin","unpublishedAction":{"name":"myFun1","fullyQualifiedName":"JSObject1.myFun1","datasource":{"name":"UNUSED_DATASOURCE","pluginId":"js-plugin","messages":[],"isAutoGenerated":false,"deleted":false,"policies":[],"userPermissions":[]},"pageId":"Page1","collectionId":"Page1_JSObject1","actionConfiguration":{"timeoutInMillisecond":10000.0,"paginationType":"NONE","encodeParamsToggle":true,"body":"() => {}","selfReferencingDataPaths":[],"jsArguments":[],"isAsync":false},"executeOnLoad":false,"clientSideExecution":true,"dynamicBindingPathList":[{"key":"body"}],"isValid":true,"invalids":[],"messages":[],"jsonPathKeys":["() => {}"],"userSetOnLoad":false,"confirmBeforeExecute":false,"policies":[],"userPermissions":[]},"publishedAction":{"datasource":{"messages":[],"isAutoGenerated":false,"deleted":false,"policies":[],"userPermissions":[]},"messages":[],"userSetOnLoad":false,"confirmBeforeExecute":false,"policies":[],"userPermissions":[]},"id":"Page1_JSObject1.myFun1","deleted":false,"gitSyncId":"63a05e664de0da6d2f4b7567_63a05e6c4de0da6d2f4b756b"},{"pluginType":"JS","pluginId":"js-plugin","unpublishedAction":{"name":"myFun2","fullyQualifiedName":"JSObject1.myFun2","datasource":{"name":"UNUSED_DATASOURCE","pluginId":"js-plugin","messages":[],"isAutoGenerated":false,"deleted":false,"policies":[],"userPermissions":[]},"pageId":"Page1","collectionId":"Page1_JSObject1","actionConfiguration":{"timeoutInMillisecond":10000.0,"paginationType":"NONE","encodeParamsToggle":true,"body":"async () => {\n showAlert((typeof UUID !== undefined).toString());\n}","selfReferencingDataPaths":[],"jsArguments":[],"isAsync":true},"executeOnLoad":true,"clientSideExecution":true,"dynamicBindingPathList":[{"key":"body"}],"isValid":true,"invalids":[],"messages":[],"jsonPathKeys":["async () => {\n showAlert((typeof UUID !== undefined).toString());\n}"],"userSetOnLoad":true,"confirmBeforeExecute":false,"policies":[],"userPermissions":[]},"publishedAction":{"datasource":{"messages":[],"isAutoGenerated":false,"deleted":false,"policies":[],"userPermissions":[]},"messages":[],"userSetOnLoad":false,"confirmBeforeExecute":false,"policies":[],"userPermissions":[]},"id":"Page1_JSObject1.myFun2","deleted":false,"gitSyncId":"63a05e664de0da6d2f4b7567_63a05e6c4de0da6d2f4b756c"}],"actionCollectionList":[{"unpublishedCollection":{"name":"JSObject1","pageId":"Page1","pluginId":"js-plugin","pluginType":"JS","actions":[],"archivedActions":[],"body":"export default {\n\tmyVar1: [],\n\tmyVar2: {},\n\tmyFun1: () => {\n\t\t\n\t},\n\tmyFun2: async () => {\n\t\tshowAlert((typeof UUID !== undefined).toString())\n\t}\n}","variables":[{"name":"myVar1","value":"[]"},{"name":"myVar2","value":"{}"}],"userPermissions":[]},"id":"Page1_JSObject1","deleted":false,"gitSyncId":"63a05e664de0da6d2f4b7567_63a05e6c4de0da6d2f4b756f"}],"updatedResources":{"actionList":["JSObject1.myFun2##ENTITY_SEPARATOR##Page1","JSObject1.myFun1##ENTITY_SEPARATOR##Page1"],"pageList":["Page1"],"actionCollectionList":["JSObject1##ENTITY_SEPARATOR##Page1"]},"editModeTheme":{"name":"Default","displayName":"Modern","isSystemTheme":true,"deleted":false},"publishedTheme":{"name":"Default","displayName":"Modern","isSystemTheme":true,"deleted":false}} \ No newline at end of file diff --git a/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/BugTests/Autocomplete_Spec.ts b/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/BugTests/Autocomplete_Spec.ts index ba8e3490f1..e796eb6668 100644 --- a/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/BugTests/Autocomplete_Spec.ts +++ b/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/BugTests/Autocomplete_Spec.ts @@ -4,6 +4,7 @@ const { AggregateHelper: agHelper, CommonLocators: locator, EntityExplorer: ee, + LibraryInstaller: installer, PropertyPane: propPane, } = ObjectsRegistry; @@ -66,9 +67,26 @@ describe("Autocomplete bug fixes", function() { it("4. feat #16426 Autocomplete for fast-xml-parser", function() { ee.SelectEntityByName("Text1"); propPane.TypeTextIntoField("Text", "{{xmlParser.j"); - agHelper.GetNAssertElementText(locator._hints, "j2xParser()"); + agHelper.GetNAssertElementText(locator._hints, "j2xParser"); propPane.TypeTextIntoField("Text", "{{new xmlParser.j2xParser().p"); - agHelper.GetNAssertElementText(locator._hints, "parse()"); + agHelper.GetNAssertElementText(locator._hints, "parse"); + }); + + it("5. Installed library should show up in autocomplete", function() { + ee.ExpandCollapseEntity("Libraries"); + installer.openInstaller(); + installer.installLibrary("uuidjs", "UUID"); + installer.closeInstaller(); + ee.SelectEntityByName("Text1"); + propPane.TypeTextIntoField("Text", "{{UUI"); + agHelper.GetNAssertElementText(locator._hints, "UUID"); + }); + + it("6. No autocomplete for Removed libraries", function() { + ee.RenameEntityFromExplorer("Text1Copy", "UUIDTEXT"); + installer.uninstallLibrary("uuidjs"); + propPane.TypeTextIntoField("Text", "{{UUID."); + agHelper.AssertElementAbsence(locator._hints); }); }); diff --git a/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/ExplorerTests/Scrolling_Spec.ts b/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/ExplorerTests/Scrolling_Spec.ts index f7d4c8328f..412943a7de 100644 --- a/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/ExplorerTests/Scrolling_Spec.ts +++ b/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/ExplorerTests/Scrolling_Spec.ts @@ -11,7 +11,7 @@ describe("Entity explorer context menu should hide on scrolling", function() { // Setup to make the explorer scrollable ee.ExpandCollapseEntity("Queries/JS"); ee.ExpandCollapseEntity("Datasources"); - agHelper.ContainsNClick("Dependencies"); + agHelper.ContainsNClick("Libraries"); dataSources.NavigateToDSCreateNew(); agHelper.GetNClick(dataSources._mockDB("Users")); cy.wait("@getMockDb").then(($createdMock) => { diff --git a/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/JSLibrary/Library_spec.ts b/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/JSLibrary/Library_spec.ts new file mode 100644 index 0000000000..45fc504d5c --- /dev/null +++ b/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/JSLibrary/Library_spec.ts @@ -0,0 +1,36 @@ +import { WIDGET } from "../../../../locators/WidgetLocators"; +import { ObjectsRegistry } from "../../../../support/Objects/Registry"; + +const explorer = ObjectsRegistry.EntityExplorer; +const installer = ObjectsRegistry.LibraryInstaller; +const aggregateHelper = ObjectsRegistry.AggregateHelper; +const homePage = ObjectsRegistry.HomePage; + +describe("Tests JS Libraries", () => { + it("1. Validates Library install/uninstall", () => { + explorer.ExpandCollapseEntity("Libraries"); + installer.openInstaller(); + installer.installLibrary("uuidjs", "UUID"); + installer.uninstallLibrary("uuidjs"); + installer.assertUnInstall("uuidjs"); + }); + it("2. Checks for naming collision", () => { + explorer.DragDropWidgetNVerify(WIDGET.TABLE, 200, 200); + explorer.NavigateToSwitcher("explorer"); + explorer.RenameEntityFromExplorer("Table1", "jsonwebtoken"); + explorer.ExpandCollapseEntity("Libraries"); + installer.openInstaller(); + installer.installLibrary("jsonwebtoken", "jsonwebtoken", false); + aggregateHelper.AssertContains("Name collision detected: jsonwebtoken"); + }); + it("3. Checks installation in exported app", () => { + homePage.NavigateToHome(); + homePage.ImportApp("library_export.json"); + aggregateHelper.AssertContains("true"); + }); + it("4. Checks installation in duplicated app", () => { + homePage.NavigateToHome(); + homePage.DuplicateApplication("Library_export"); + aggregateHelper.AssertContains("true"); + }); +}); diff --git a/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/Linting/BasicLint_spec.ts b/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/Linting/BasicLint_spec.ts index 1c9c44820c..3c26f5a48f 100644 --- a/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/Linting/BasicLint_spec.ts +++ b/app/client/cypress/integration/Smoke_TestSuite/ClientSideTests/Linting/BasicLint_spec.ts @@ -6,7 +6,9 @@ const jsEditor = ObjectsRegistry.JSEditor, apiPage = ObjectsRegistry.ApiPage, agHelper = ObjectsRegistry.AggregateHelper, dataSources = ObjectsRegistry.DataSources, - propPane = ObjectsRegistry.PropertyPane; + propPane = ObjectsRegistry.PropertyPane, + installer = ObjectsRegistry.LibraryInstaller, + home = ObjectsRegistry.HomePage; const successMessage = "Successful Trigger"; const errorMessage = "Unsuccessful Trigger"; @@ -271,7 +273,7 @@ describe("Linting", () => { apiPage.CreateAndFillApi("https://jsonplaceholder.typicode.com/"); createMySQLDatasourceQuery(); - agHelper.RefreshPage();//Since this seems failing a bit + agHelper.RefreshPage(); //Since this seems failing a bit clickButtonAndAssertLintError(false); }); @@ -291,4 +293,48 @@ describe("Linting", () => { // expect no lint error agHelper.AssertElementAbsence(locator._lintErrorElement); }); + + it("9. Shows lint errors for usage of library that are not installed yet", () => { + const JS_OBJECT_WITH_LIB_API = `export default { + myFun1: () => { + return UUID.generate(); + }, + }`; + jsEditor.CreateJSObject(JS_OBJECT_WITH_LIB_API, { + paste: true, + completeReplace: true, + toRun: false, + shouldCreateNewJSObj: true, + }); + + agHelper.AssertElementExist(locator._lintErrorElement); + ee.ExpandCollapseEntity("Libraries"); + // install the library + installer.openInstaller(); + installer.installLibrary("uuidjs", "UUID"); + installer.closeInstaller(); + + agHelper.AssertElementAbsence(locator._lintErrorElement); + + installer.uninstallLibrary("uuidjs"); + + agHelper.AssertElementExist(locator._lintErrorElement); + agHelper.Sleep(2000); + installer.openInstaller(); + installer.installLibrary("uuidjs", "UUID"); + installer.closeInstaller(); + + home.NavigateToHome(); + + home.CreateNewApplication(); + + jsEditor.CreateJSObject(JS_OBJECT_WITH_LIB_API, { + paste: true, + completeReplace: true, + toRun: false, + shouldCreateNewJSObj: true, + }); + + agHelper.AssertElementExist(locator._lintErrorElement); + }); }); diff --git a/app/client/cypress/support/Objects/Registry.ts b/app/client/cypress/support/Objects/Registry.ts index dffc1c7343..e88e3b6895 100644 --- a/app/client/cypress/support/Objects/Registry.ts +++ b/app/client/cypress/support/Objects/Registry.ts @@ -12,6 +12,7 @@ import { DeployMode } from "../Pages/DeployModeHelper"; import { GitSync } from "../Pages/GitSync"; import { FakerHelper } from "../Pages/FakerHelper"; import { DebuggerHelper } from "../Pages/DebuggerHelper"; +import { LibraryInstaller } from "../Pages/LibraryInstaller"; import { AppSettings } from "../Pages/AppSettings/AppSettings"; import { GeneralSettings } from "../Pages/AppSettings/GeneralSettings"; import { PageSettings } from "../Pages/AppSettings/PageSettings"; @@ -161,6 +162,14 @@ export class ObjectsRegistry { } return ObjectsRegistry.themeSettings__; } + + private static LibraryInstaller__: LibraryInstaller; + static get LibraryInstaller(): LibraryInstaller { + if (ObjectsRegistry.LibraryInstaller__ === undefined) { + ObjectsRegistry.LibraryInstaller__ = new LibraryInstaller(); + } + return ObjectsRegistry.LibraryInstaller__; + } } export const initLocalstorageRegistry = () => { diff --git a/app/client/cypress/support/Pages/LibraryInstaller.ts b/app/client/cypress/support/Pages/LibraryInstaller.ts new file mode 100644 index 0000000000..9a3ae8670d --- /dev/null +++ b/app/client/cypress/support/Pages/LibraryInstaller.ts @@ -0,0 +1,62 @@ +import { ObjectsRegistry } from "../Objects/Registry"; + +export class LibraryInstaller { + private _aggregateHelper = ObjectsRegistry.AggregateHelper; + private _installer_trigger_locator = ".t--entity-add-btn.group.libraries"; + private _installer_close_locator = ".t--close-installer"; + + private getLibraryLocatorInExplorer(libraryName: string) { + return `.t--installed-library-${libraryName}`; + } + + private getLibraryCardLocator(libraryName: string) { + return `div.library-card.t--${libraryName}`; + } + + public openInstaller() { + this._aggregateHelper.GetNClick(this._installer_trigger_locator); + } + + public closeInstaller() { + this._aggregateHelper.GetNClick(this._installer_close_locator); + } + + public installLibrary( + libraryName: string, + accessor: string, + checkIfSuccessful = true, + ) { + cy.get(this.getLibraryCardLocator(libraryName)) + .find(".t--download") + .click(); + if (checkIfSuccessful) this.assertInstall(libraryName, accessor); + } + + private assertInstall(libraryName: string, accessor: string) { + this._aggregateHelper.AssertContains( + `Installation Successful. You can access the library via ${accessor}`, + ); + cy.get(this.getLibraryCardLocator(libraryName)) + .find(".installed") + .should("be.visible"); + this._aggregateHelper.AssertElementExist( + this.getLibraryLocatorInExplorer(libraryName), + ); + } + + public uninstallLibrary(libraryName: string) { + cy.get(this.getLibraryLocatorInExplorer(libraryName)) + .realHover() + .find(".t--uninstall-library") + .click(); + } + + public assertUnInstall(libraryName: string) { + this._aggregateHelper.AssertContains( + `${libraryName} is uninstalled successfully.`, + ); + this._aggregateHelper.AssertElementAbsence( + this.getLibraryLocatorInExplorer(libraryName), + ); + } +} diff --git a/app/client/jest.config.js b/app/client/jest.config.js index 3fde8cf983..26ca4d38ef 100644 --- a/app/client/jest.config.js +++ b/app/client/jest.config.js @@ -17,7 +17,7 @@ module.exports = { moduleFileExtensions: ["ts", "tsx", "js", "jsx", "json", "node", "css"], moduleDirectories: ["node_modules", "src", "test"], transformIgnorePatterns: [ - "/node_modules/(?!codemirror|design-system|react-dnd|dnd-core|@babel|(@blueprintjs/core/lib/esnext)|(@blueprintjs/core/lib/esm)|@github|lodash-es|@draft-js-plugins|react-documents)", + "/node_modules/(?!codemirror|design-system|react-dnd|dnd-core|@babel|(@blueprintjs/core/lib/esnext)|(@blueprintjs/core/lib/esm)|@github|lodash-es|@draft-js-plugins|react-documents|linkedom)", ], moduleNameMapper: { "\\.(css|less)$": "/test/__mocks__/styleMock.js", diff --git a/app/client/package.json b/app/client/package.json index 281f6f1b9e..d499c0504a 100644 --- a/app/client/package.json +++ b/app/client/package.json @@ -70,6 +70,7 @@ "jshint": "^2.13.4", "klona": "^2.0.5", "libphonenumber-js": "^1.9.44", + "linkedom": "^0.14.20", "lint-staged": "^13.0.3", "localforage": "^1.7.3", "lodash": "^4.17.21", diff --git a/app/client/public/libraries/fast-csv@4.3.6.js b/app/client/public/libraries/fast-csv@4.3.6.js new file mode 100644 index 0000000000..634b5ef4b5 --- /dev/null +++ b/app/client/public/libraries/fast-csv@4.3.6.js @@ -0,0 +1 @@ +!function(e){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{("undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:this).fastCsv=e()}}(function(){return function(){return function e(t,r,n){function i(s,a){if(!r[s]){if(!t[s]){var u="function"==typeof require&&require;if(!a&&u)return u(s,!0);if(o)return o(s,!0);var f=new Error("Cannot find module '"+s+"'");throw f.code="MODULE_NOT_FOUND",f}var l=r[s]={exports:{}};t[s][0].call(l.exports,function(e){return i(t[s][1][e]||e)},l,l.exports,e,t,r,n)}return r[s].exports}for(var o="function"==typeof require&&require,s=0;se?(i=!0,n(e)):(r&&r.forEach(e=>{this.push(t.from(e,"utf8"))}),i=!0,n()))}catch(e){if(i)throw e;n(e)}}_flush(e){this.rowFormatter.finish((r,n)=>r?e(r):(n&&n.forEach(e=>{this.push(t.from(e,"utf8"))}),e()))}}}).call(this,e("buffer").Buffer)},{"./formatter":6,buffer:37,stream:62}],3:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.FormatterOptions=void 0;r.FormatterOptions=class{constructor(e={}){var t;this.objectMode=!0,this.delimiter=",",this.rowDelimiter="\n",this.quote='"',this.escape=this.quote,this.quoteColumns=!1,this.quoteHeaders=this.quoteColumns,this.headers=null,this.includeEndRowDelimiter=!1,this.writeBOM=!1,this.BOM="\ufeff",this.alwaysWriteHeaders=!1,Object.assign(this,e||{}),void 0===(null==e?void 0:e.quoteHeaders)&&(this.quoteHeaders=this.quoteColumns),!0===(null==e?void 0:e.quote)?this.quote='"':!1===(null==e?void 0:e.quote)&&(this.quote=""),"string"!=typeof(null==e?void 0:e.escape)&&(this.escape=this.quote),this.shouldWriteHeaders=!!this.headers&&(null===(t=e.writeHeaders)||void 0===t||t),this.headers=Array.isArray(this.headers)?this.headers:null,this.escapedQuote=`${this.escape}${this.quote}`}}},{}],4:[function(e,t,r){"use strict";var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(r,"__esModule",{value:!0}),r.FieldFormatter=void 0;const i=n(e("lodash.isboolean")),o=n(e("lodash.isnil")),s=n(e("lodash.escaperegexp"));r.FieldFormatter=class{constructor(e){this._headers=null,this.formatterOptions=e,null!==e.headers&&(this.headers=e.headers),this.REPLACE_REGEXP=new RegExp(e.quote,"g");const t=`[${e.delimiter}${s.default(e.rowDelimiter)}|\r|\n]`;this.ESCAPE_REGEXP=new RegExp(t)}set headers(e){this._headers=e}shouldQuote(e,t){const r=t?this.formatterOptions.quoteHeaders:this.formatterOptions.quoteColumns;return i.default(r)?r:Array.isArray(r)?r[e]:null!==this._headers&&r[this._headers[e]]}format(e,t,r){const n=`${o.default(e)?"":e}`.replace(/\0/g,""),{formatterOptions:i}=this;return""!==i.quote&&-1!==n.indexOf(i.quote)?this.quoteField(n.replace(this.REPLACE_REGEXP,i.escapedQuote)):-1!==n.search(this.ESCAPE_REGEXP)||this.shouldQuote(t,r)?this.quoteField(n):n}quoteField(e){const{quote:t}=this.formatterOptions;return`${t}${e}${t}`}}},{"lodash.escaperegexp":26,"lodash.isboolean":28,"lodash.isnil":31}],5:[function(e,t,r){"use strict";var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(r,"__esModule",{value:!0}),r.RowFormatter=void 0;const i=n(e("lodash.isfunction")),o=n(e("lodash.isequal")),s=e("./FieldFormatter"),a=e("../types");class u{constructor(e){this.rowCount=0,this.formatterOptions=e,this.fieldFormatter=new s.FieldFormatter(e),this.headers=e.headers,this.shouldWriteHeaders=e.shouldWriteHeaders,this.hasWrittenHeaders=!1,null!==this.headers&&(this.fieldFormatter.headers=this.headers),e.transform&&(this.rowTransform=e.transform)}static isRowHashArray(e){return!!Array.isArray(e)&&(Array.isArray(e[0])&&2===e[0].length)}static isRowArray(e){return Array.isArray(e)&&!this.isRowHashArray(e)}static gatherHeaders(e){return u.isRowHashArray(e)?e.map(e=>e[0]):Array.isArray(e)?e:Object.keys(e)}static createTransform(e){return a.isSyncTransform(e)?(t,r)=>{let n=null;try{n=e(t)}catch(e){return r(e)}return r(null,n)}:(t,r)=>{e(t,r)}}set rowTransform(e){if(!i.default(e))throw new TypeError("The transform should be a function");this._rowTransform=u.createTransform(e)}format(e,t){this.callTransformer(e,(r,n)=>{if(r)return t(r);if(!e)return t(null);const i=[];if(n){const{shouldFormatColumns:e,headers:t}=this.checkHeaders(n);if(this.shouldWriteHeaders&&t&&!this.hasWrittenHeaders&&(i.push(this.formatColumns(t,!0)),this.hasWrittenHeaders=!0),e){const e=this.gatherColumns(n);i.push(this.formatColumns(e,!1))}}return t(null,i)})}finish(e){const t=[];if(this.formatterOptions.alwaysWriteHeaders&&0===this.rowCount){if(!this.headers)return e(new Error("`alwaysWriteHeaders` option is set to true but `headers` option not provided."));t.push(this.formatColumns(this.headers,!0))}return this.formatterOptions.includeEndRowDelimiter&&t.push(this.formatterOptions.rowDelimiter),e(null,t)}checkHeaders(e){if(this.headers)return{shouldFormatColumns:!0,headers:this.headers};const t=u.gatherHeaders(e);return this.headers=t,this.fieldFormatter.headers=t,this.shouldWriteHeaders?{shouldFormatColumns:!o.default(t,e),headers:t}:{shouldFormatColumns:!0,headers:null}}gatherColumns(e){if(null===this.headers)throw new Error("Headers is currently null");return Array.isArray(e)?u.isRowHashArray(e)?this.headers.map((t,r)=>{const n=e[r];return n?n[1]:""}):u.isRowArray(e)&&!this.shouldWriteHeaders?e:this.headers.map((t,r)=>e[r]):this.headers.map(t=>e[t])}callTransformer(e,t){return this._rowTransform?this._rowTransform(e,t):t(null,e)}formatColumns(e,t){const r=e.map((e,r)=>this.fieldFormatter.format(e,r,t)).join(this.formatterOptions.delimiter),{rowCount:n}=this;return this.rowCount+=1,n?[this.formatterOptions.rowDelimiter,r].join(""):r}}r.RowFormatter=u},{"../types":8,"./FieldFormatter":4,"lodash.isequal":29,"lodash.isfunction":30}],6:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.FieldFormatter=r.RowFormatter=void 0;var n=e("./RowFormatter");Object.defineProperty(r,"RowFormatter",{enumerable:!0,get:function(){return n.RowFormatter}});var i=e("./FieldFormatter");Object.defineProperty(r,"FieldFormatter",{enumerable:!0,get:function(){return i.FieldFormatter}})},{"./FieldFormatter":4,"./RowFormatter":5}],7:[function(e,t,r){(function(t){"use strict";var n=this&&this.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=r),Object.defineProperty(e,n,{enumerable:!0,get:function(){return t[r]}})}:function(e,t,r,n){void 0===n&&(n=r),e[n]=t[r]}),i=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),o=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r in e)"default"!==r&&Object.prototype.hasOwnProperty.call(e,r)&&n(t,e,r);return i(t,e),t},s=this&&this.__exportStar||function(e,t){for(var r in e)"default"===r||Object.prototype.hasOwnProperty.call(t,r)||n(t,e,r)};Object.defineProperty(r,"__esModule",{value:!0}),r.writeToPath=r.writeToString=r.writeToBuffer=r.writeToStream=r.write=r.format=r.FormatterOptions=r.CsvFormatterStream=void 0;const a=e("util"),u=e("stream"),f=o(e("fs")),l=e("./FormatterOptions"),c=e("./CsvFormatterStream");s(e("./types"),r);var h=e("./CsvFormatterStream");Object.defineProperty(r,"CsvFormatterStream",{enumerable:!0,get:function(){return h.CsvFormatterStream}});var d=e("./FormatterOptions");Object.defineProperty(r,"FormatterOptions",{enumerable:!0,get:function(){return d.FormatterOptions}}),r.format=(e=>new c.CsvFormatterStream(new l.FormatterOptions(e))),r.write=((e,t)=>{const n=r.format(t),i=a.promisify((e,t)=>{n.write(e,void 0,t)});return e.reduce((e,t)=>e.then(()=>i(t)),Promise.resolve()).then(()=>n.end()).catch(e=>{n.emit("error",e)}),n}),r.writeToStream=((e,t,n)=>r.write(t,n).pipe(e)),r.writeToBuffer=((e,n={})=>{const i=[],o=new u.Writable({write(e,t,r){i.push(e),r()}});return new Promise((s,a)=>{o.on("error",a).on("finish",()=>s(t.concat(i))),r.write(e,n).pipe(o)})}),r.writeToString=((e,t)=>r.writeToBuffer(e,t).then(e=>e.toString())),r.writeToPath=((e,t,n)=>{const i=f.createWriteStream(e,{encoding:"utf8"});return r.write(t,n).pipe(i)})}).call(this,e("buffer").Buffer)},{"./CsvFormatterStream":2,"./FormatterOptions":3,"./types":8,buffer:37,fs:36,stream:62,util:68}],8:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.isSyncTransform=void 0,r.isSyncTransform=(e=>1===e.length)},{}],9:[function(e,t,r){(function(t){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.CsvParserStream=void 0;const n=e("string_decoder"),i=e("stream"),o=e("./transforms"),s=e("./parser");class a extends i.Transform{constructor(e){super({objectMode:e.objectMode}),this.lines="",this.rowCount=0,this.parsedRowCount=0,this.parsedLineCount=0,this.endEmitted=!1,this.headersEmitted=!1,this.parserOptions=e,this.parser=new s.Parser(e),this.headerTransformer=new o.HeaderTransformer(e),this.decoder=new n.StringDecoder(e.encoding),this.rowTransformerValidator=new o.RowTransformerValidator}get hasHitRowLimit(){return this.parserOptions.limitRows&&this.rowCount>=this.parserOptions.maxRows}get shouldEmitRows(){return this.parsedRowCount>this.parserOptions.skipRows}get shouldSkipLine(){return this.parsedLineCount<=this.parserOptions.skipLines}transform(e){return this.rowTransformerValidator.rowTransform=e,this}validate(e){return this.rowTransformerValidator.rowValidator=e,this}emit(e,...t){return"end"===e?(this.endEmitted||(this.endEmitted=!0,super.emit("end",this.rowCount)),!1):super.emit(e,...t)}_transform(e,t,r){if(this.hasHitRowLimit)return r();const n=a.wrapDoneCallback(r);try{const{lines:t}=this,r=t+this.decoder.write(e),i=this.parse(r,!0);return this.processRows(i,n)}catch(e){return n(e)}}_flush(e){const t=a.wrapDoneCallback(e);if(this.hasHitRowLimit)return t();try{const e=this.lines+this.decoder.end(),r=this.parse(e,!1);return this.processRows(r,t)}catch(e){return t(e)}}parse(e,t){if(!e)return[];const{line:r,rows:n}=this.parser.parse(e,t);return this.lines=r,n}processRows(e,r){const n=e.length,i=o=>{const s=e=>e?r(e):o%100!=0?i(o+1):void t(()=>i(o+1));if(this.checkAndEmitHeaders(),o>=n||this.hasHitRowLimit)return r();if(this.parsedLineCount+=1,this.shouldSkipLine)return s();const a=e[o];this.rowCount+=1,this.parsedRowCount+=1;const u=this.rowCount;return this.transformRow(a,(e,t)=>{if(e)return this.rowCount-=1,s(e);if(!t)return s(new Error("expected transform result"));if(t.isValid){if(t.row)return this.pushRow(t.row,s)}else this.emit("data-invalid",t.row,u,t.reason);return s()})};i(0)}transformRow(e,t){try{this.headerTransformer.transform(e,(r,n)=>r?t(r):n?n.isValid?n.row?this.shouldEmitRows?this.rowTransformerValidator.transformAndValidate(n.row,t):this.skipRow(t):(this.rowCount-=1,this.parsedRowCount-=1,t(null,{row:null,isValid:!0})):this.shouldEmitRows?t(null,{isValid:!1,row:e}):this.skipRow(t):t(new Error("Expected result from header transform")))}catch(e){t(e)}}checkAndEmitHeaders(){!this.headersEmitted&&this.headerTransformer.headers&&(this.headersEmitted=!0,this.emit("headers",this.headerTransformer.headers))}skipRow(e){return this.rowCount-=1,e(null,{row:null,isValid:!0})}pushRow(e,t){try{this.parserOptions.objectMode?this.push(e):this.push(JSON.stringify(e)),t()}catch(e){t(e)}}static wrapDoneCallback(e){let t=!1;return(r,...n)=>{if(r){if(t)throw r;return t=!0,void e(r)}e(...n)}}}r.CsvParserStream=a}).call(this,e("timers").setImmediate)},{"./parser":21,"./transforms":24,stream:62,string_decoder:63,timers:64}],10:[function(e,t,r){"use strict";var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(r,"__esModule",{value:!0}),r.ParserOptions=void 0;const i=n(e("lodash.escaperegexp")),o=n(e("lodash.isnil"));r.ParserOptions=class{constructor(e){var t;if(this.objectMode=!0,this.delimiter=",",this.ignoreEmpty=!1,this.quote='"',this.escape=null,this.escapeChar=this.quote,this.comment=null,this.supportsComments=!1,this.ltrim=!1,this.rtrim=!1,this.trim=!1,this.headers=null,this.renameHeaders=!1,this.strictColumnHandling=!1,this.discardUnmappedColumns=!1,this.carriageReturn="\r",this.encoding="utf8",this.limitRows=!1,this.maxRows=0,this.skipLines=0,this.skipRows=0,Object.assign(this,e||{}),this.delimiter.length>1)throw new Error("delimiter option must be one character long");this.escapedDelimiter=i.default(this.delimiter),this.escapeChar=null!==(t=this.escape)&&void 0!==t?t:this.quote,this.supportsComments=!o.default(this.comment),this.NEXT_TOKEN_REGEXP=new RegExp(`([^\\s]|\\r\\n|\\n|\\r|${this.escapedDelimiter})`),this.maxRows>0&&(this.limitRows=!0)}}},{"lodash.escaperegexp":26,"lodash.isnil":31}],11:[function(e,t,r){"use strict";var n=this&&this.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=r),Object.defineProperty(e,n,{enumerable:!0,get:function(){return t[r]}})}:function(e,t,r,n){void 0===n&&(n=r),e[n]=t[r]}),i=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),o=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r in e)"default"!==r&&Object.prototype.hasOwnProperty.call(e,r)&&n(t,e,r);return i(t,e),t},s=this&&this.__exportStar||function(e,t){for(var r in e)"default"===r||Object.prototype.hasOwnProperty.call(t,r)||n(t,e,r)};Object.defineProperty(r,"__esModule",{value:!0}),r.parseString=r.parseFile=r.parseStream=r.parse=r.ParserOptions=r.CsvParserStream=void 0;const a=o(e("fs")),u=e("stream"),f=e("./ParserOptions"),l=e("./CsvParserStream");s(e("./types"),r);var c=e("./CsvParserStream");Object.defineProperty(r,"CsvParserStream",{enumerable:!0,get:function(){return c.CsvParserStream}});var h=e("./ParserOptions");Object.defineProperty(r,"ParserOptions",{enumerable:!0,get:function(){return h.ParserOptions}}),r.parse=(e=>new l.CsvParserStream(new f.ParserOptions(e))),r.parseStream=((e,t)=>e.pipe(new l.CsvParserStream(new f.ParserOptions(t)))),r.parseFile=((e,t={})=>a.createReadStream(e).pipe(new l.CsvParserStream(new f.ParserOptions(t)))),r.parseString=((e,t)=>{const r=new u.Readable;return r.push(e),r.push(null),r.pipe(new l.CsvParserStream(new f.ParserOptions(t)))})},{"./CsvParserStream":9,"./ParserOptions":10,"./types":25,fs:36,stream:62}],12:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.Parser=void 0;const n=e("./Scanner"),i=e("./RowParser"),o=e("./Token");class s{constructor(e){this.parserOptions=e,this.rowParser=new i.RowParser(this.parserOptions)}static removeBOM(e){return e&&65279===e.charCodeAt(0)?e.slice(1):e}parse(e,t){const r=new n.Scanner({line:s.removeBOM(e),parserOptions:this.parserOptions,hasMoreData:t});return this.parserOptions.supportsComments?this.parseWithComments(r):this.parseWithoutComments(r)}parseWithoutComments(e){const t=[];let r=!0;for(;r;)r=this.parseRow(e,t);return{line:e.line,rows:t}}parseWithComments(e){const{parserOptions:t}=this,r=[];for(let n=e.nextCharacterToken;null!==n;n=e.nextCharacterToken)if(o.Token.isTokenComment(n,t)){if(null===e.advancePastLine())return{line:e.lineFromCursor,rows:r};if(!e.hasMoreCharacters)return{line:e.lineFromCursor,rows:r};e.truncateToCursor()}else if(!this.parseRow(e,r))break;return{line:e.line,rows:r}}parseRow(e,t){if(!e.nextNonSpaceToken)return!1;const r=this.rowParser.parse(e);return null!==r&&(!(!this.parserOptions.ignoreEmpty||!i.RowParser.isEmptyRow(r))||(t.push(r),!0))}}r.Parser=s},{"./RowParser":13,"./Scanner":14,"./Token":15}],13:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.RowParser=void 0;const n=e("./column"),i=e("./Token"),o="";r.RowParser=class{constructor(e){this.parserOptions=e,this.columnParser=new n.ColumnParser(e)}static isEmptyRow(e){return e.join(o).replace(/\s+/g,o)===o}parse(e){const{parserOptions:t}=this,{hasMoreData:r}=e,n=e,o=[];let s=this.getStartToken(n,o);for(;s;){if(i.Token.isTokenRowDelimiter(s))return n.advancePastToken(s),!n.hasMoreCharacters&&i.Token.isTokenCarriageReturn(s,t)&&r?null:(n.truncateToCursor(),o);if(!this.shouldSkipColumnParse(n,s,o)){const e=this.columnParser.parse(n);if(null===e)return null;o.push(e)}s=n.nextNonSpaceToken}return r?null:(n.truncateToCursor(),o)}getStartToken(e,t){const r=e.nextNonSpaceToken;return null!==r&&i.Token.isTokenDelimiter(r,this.parserOptions)?(t.push(""),e.nextNonSpaceToken):r}shouldSkipColumnParse(e,t,r){const{parserOptions:n}=this;if(i.Token.isTokenDelimiter(t,n)){e.advancePastToken(t);const o=e.nextCharacterToken;if(!e.hasMoreCharacters||null!==o&&i.Token.isTokenRowDelimiter(o))return r.push(""),!0;if(null!==o&&i.Token.isTokenDelimiter(o,n))return r.push(""),!0}return!1}}},{"./Token":15,"./column":20}],14:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.Scanner=void 0;const n=e("./Token"),i=/((?:\r\n)|\n|\r)/;r.Scanner=class{constructor(e){this.cursor=0,this.line=e.line,this.lineLength=this.line.length,this.parserOptions=e.parserOptions,this.hasMoreData=e.hasMoreData,this.cursor=e.cursor||0}get hasMoreCharacters(){return this.lineLength>this.cursor}get nextNonSpaceToken(){const{lineFromCursor:e}=this,t=this.parserOptions.NEXT_TOKEN_REGEXP;if(-1===e.search(t))return null;const r=t.exec(e);if(null==r)return null;const i=r[1],o=this.cursor+(r.index||0);return new n.Token({token:i,startCursor:o,endCursor:o+i.length-1})}get nextCharacterToken(){const{cursor:e,lineLength:t}=this;return t<=e?null:new n.Token({token:this.line[e],startCursor:e,endCursor:e})}get lineFromCursor(){return this.line.substr(this.cursor)}advancePastLine(){const e=i.exec(this.lineFromCursor);return e?(this.cursor+=(e.index||0)+e[0].length,this):this.hasMoreData?null:(this.cursor=this.lineLength,this)}advanceTo(e){return this.cursor=e,this}advanceToToken(e){return this.cursor=e.startCursor,this}advancePastToken(e){return this.cursor=e.endCursor+1,this}truncateToCursor(){return this.line=this.lineFromCursor,this.lineLength=this.line.length,this.cursor=0,this}}},{"./Token":15}],15:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.Token=void 0;r.Token=class{constructor(e){this.token=e.token,this.startCursor=e.startCursor,this.endCursor=e.endCursor}static isTokenRowDelimiter(e){const t=e.token;return"\r"===t||"\n"===t||"\r\n"===t}static isTokenCarriageReturn(e,t){return e.token===t.carriageReturn}static isTokenComment(e,t){return t.supportsComments&&!!e&&e.token===t.comment}static isTokenEscapeCharacter(e,t){return e.token===t.escapeChar}static isTokenQuote(e,t){return e.token===t.quote}static isTokenDelimiter(e,t){return e.token===t.delimiter}}},{}],16:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.ColumnFormatter=void 0;r.ColumnFormatter=class{constructor(e){e.trim?this.format=(e=>e.trim()):e.ltrim?this.format=(e=>e.trimLeft()):e.rtrim?this.format=(e=>e.trimRight()):this.format=(e=>e)}}},{}],17:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.ColumnParser=void 0;const n=e("./NonQuotedColumnParser"),i=e("./QuotedColumnParser"),o=e("../Token");r.ColumnParser=class{constructor(e){this.parserOptions=e,this.quotedColumnParser=new i.QuotedColumnParser(e),this.nonQuotedColumnParser=new n.NonQuotedColumnParser(e)}parse(e){const{nextNonSpaceToken:t}=e;return null!==t&&o.Token.isTokenQuote(t,this.parserOptions)?(e.advanceToToken(t),this.quotedColumnParser.parse(e)):this.nonQuotedColumnParser.parse(e)}}},{"../Token":15,"./NonQuotedColumnParser":18,"./QuotedColumnParser":19}],18:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.NonQuotedColumnParser=void 0;const n=e("./ColumnFormatter"),i=e("../Token");r.NonQuotedColumnParser=class{constructor(e){this.parserOptions=e,this.columnFormatter=new n.ColumnFormatter(e)}parse(e){if(!e.hasMoreCharacters)return null;const{parserOptions:t}=this,r=[];let n=e.nextCharacterToken;for(;n&&!i.Token.isTokenDelimiter(n,t)&&!i.Token.isTokenRowDelimiter(n);n=e.nextCharacterToken)r.push(n.token),e.advancePastToken(n);return this.columnFormatter.format(r.join(""))}}},{"../Token":15,"./ColumnFormatter":16}],19:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.QuotedColumnParser=void 0;const n=e("./ColumnFormatter"),i=e("../Token");r.QuotedColumnParser=class{constructor(e){this.parserOptions=e,this.columnFormatter=new n.ColumnFormatter(e)}parse(e){if(!e.hasMoreCharacters)return null;const t=e.cursor,{foundClosingQuote:r,col:n}=this.gatherDataBetweenQuotes(e);if(!r){if(e.advanceTo(t),!e.hasMoreData)throw new Error(`Parse Error: missing closing: '${this.parserOptions.quote||""}' in line: at '${e.lineFromCursor.replace(/[\r\n]/g,"\\n'")}'`);return null}return this.checkForMalformedColumn(e),n}gatherDataBetweenQuotes(e){const{parserOptions:t}=this;let r=!1,n=!1;const o=[];let s=e.nextCharacterToken;for(;!n&&null!==s;s=e.nextCharacterToken){const a=i.Token.isTokenQuote(s,t);if(!r&&a)r=!0;else if(r)if(i.Token.isTokenEscapeCharacter(s,t)){e.advancePastToken(s);const r=e.nextCharacterToken;null!==r&&(i.Token.isTokenQuote(r,t)||i.Token.isTokenEscapeCharacter(r,t))?(o.push(r.token),s=r):a?n=!0:o.push(s.token)}else a?n=!0:o.push(s.token);e.advancePastToken(s)}return{col:this.columnFormatter.format(o.join("")),foundClosingQuote:n}}checkForMalformedColumn(e){const{parserOptions:t}=this,{nextNonSpaceToken:r}=e;if(r){const n=i.Token.isTokenDelimiter(r,t),o=i.Token.isTokenRowDelimiter(r);if(!n&&!o){const n=e.lineFromCursor.substr(0,10).replace(/[\r\n]/g,"\\n'");throw new Error(`Parse Error: expected: '${t.escapedDelimiter}' OR new line got: '${r.token}'. at '${n}`)}e.advanceToToken(r)}else e.hasMoreData||e.advancePastLine()}}},{"../Token":15,"./ColumnFormatter":16}],20:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.ColumnFormatter=r.QuotedColumnParser=r.NonQuotedColumnParser=r.ColumnParser=void 0;var n=e("./ColumnParser");Object.defineProperty(r,"ColumnParser",{enumerable:!0,get:function(){return n.ColumnParser}});var i=e("./NonQuotedColumnParser");Object.defineProperty(r,"NonQuotedColumnParser",{enumerable:!0,get:function(){return i.NonQuotedColumnParser}});var o=e("./QuotedColumnParser");Object.defineProperty(r,"QuotedColumnParser",{enumerable:!0,get:function(){return o.QuotedColumnParser}});var s=e("./ColumnFormatter");Object.defineProperty(r,"ColumnFormatter",{enumerable:!0,get:function(){return s.ColumnFormatter}})},{"./ColumnFormatter":16,"./ColumnParser":17,"./NonQuotedColumnParser":18,"./QuotedColumnParser":19}],21:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.QuotedColumnParser=r.NonQuotedColumnParser=r.ColumnParser=r.Token=r.Scanner=r.RowParser=r.Parser=void 0;var n=e("./Parser");Object.defineProperty(r,"Parser",{enumerable:!0,get:function(){return n.Parser}});var i=e("./RowParser");Object.defineProperty(r,"RowParser",{enumerable:!0,get:function(){return i.RowParser}});var o=e("./Scanner");Object.defineProperty(r,"Scanner",{enumerable:!0,get:function(){return o.Scanner}});var s=e("./Token");Object.defineProperty(r,"Token",{enumerable:!0,get:function(){return s.Token}});var a=e("./column");Object.defineProperty(r,"ColumnParser",{enumerable:!0,get:function(){return a.ColumnParser}}),Object.defineProperty(r,"NonQuotedColumnParser",{enumerable:!0,get:function(){return a.NonQuotedColumnParser}}),Object.defineProperty(r,"QuotedColumnParser",{enumerable:!0,get:function(){return a.QuotedColumnParser}})},{"./Parser":12,"./RowParser":13,"./Scanner":14,"./Token":15,"./column":20}],22:[function(e,t,r){"use strict";var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(r,"__esModule",{value:!0}),r.HeaderTransformer=void 0;const i=n(e("lodash.isundefined")),o=n(e("lodash.isfunction")),s=n(e("lodash.uniq")),a=n(e("lodash.groupby"));r.HeaderTransformer=class{constructor(e){this.headers=null,this.receivedHeaders=!1,this.shouldUseFirstRow=!1,this.processedFirstRow=!1,this.headersLength=0,this.parserOptions=e,!0===e.headers?this.shouldUseFirstRow=!0:Array.isArray(e.headers)?this.setHeaders(e.headers):o.default(e.headers)&&(this.headersTransform=e.headers)}transform(e,t){return this.shouldMapRow(e)?t(null,this.processRow(e)):t(null,{row:null,isValid:!0})}shouldMapRow(e){const{parserOptions:t}=this;if(!this.headersTransform&&t.renameHeaders&&!this.processedFirstRow){if(!this.receivedHeaders)throw new Error("Error renaming headers: new headers must be provided in an array");return this.processedFirstRow=!0,!1}if(!this.receivedHeaders&&Array.isArray(e)){if(this.headersTransform)this.setHeaders(this.headersTransform(e));else{if(!this.shouldUseFirstRow)return!0;this.setHeaders(e)}return!1}return!0}processRow(e){if(!this.headers)return{row:e,isValid:!0};const{parserOptions:t}=this;if(!t.discardUnmappedColumns&&e.length>this.headersLength){if(!t.strictColumnHandling)throw new Error(`Unexpected Error: column header mismatch expected: ${this.headersLength} columns got: ${e.length}`);return{row:e,isValid:!1,reason:`Column header mismatch expected: ${this.headersLength} columns got: ${e.length}`}}return t.strictColumnHandling&&e.length!!e);if(s.default(r).length!==r.length){const e=a.default(r),t=Object.keys(e).filter(t=>e[t].length>1);throw new Error(`Duplicate headers found ${JSON.stringify(t)}`)}this.headers=e,this.receivedHeaders=!0,this.headersLength=(null===(t=this.headers)||void 0===t?void 0:t.length)||0}}},{"lodash.groupby":27,"lodash.isfunction":30,"lodash.isundefined":32,"lodash.uniq":33}],23:[function(e,t,r){"use strict";var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(r,"__esModule",{value:!0}),r.RowTransformerValidator=void 0;const i=n(e("lodash.isfunction")),o=e("../types");class s{constructor(){this._rowTransform=null,this._rowValidator=null}static createTransform(e){return o.isSyncTransform(e)?(t,r)=>{let n=null;try{n=e(t)}catch(e){return r(e)}return r(null,n)}:e}static createValidator(e){return o.isSyncValidate(e)?(t,r)=>{r(null,{row:t,isValid:e(t)})}:(t,r)=>{e(t,(e,n,i)=>e?r(e):r(null,n?{row:t,isValid:n,reason:i}:{row:t,isValid:!1,reason:i}))}}set rowTransform(e){if(!i.default(e))throw new TypeError("The transform should be a function");this._rowTransform=s.createTransform(e)}set rowValidator(e){if(!i.default(e))throw new TypeError("The validate should be a function");this._rowValidator=s.createValidator(e)}transformAndValidate(e,t){return this.callTransformer(e,(e,r)=>e?t(e):r?this.callValidator(r,(e,n)=>e?t(e):n&&!n.isValid?t(null,{row:r,isValid:!1,reason:n.reason}):t(null,{row:r,isValid:!0})):t(null,{row:null,isValid:!0}))}callTransformer(e,t){return this._rowTransform?this._rowTransform(e,t):t(null,e)}callValidator(e,t){return this._rowValidator?this._rowValidator(e,t):t(null,{row:e,isValid:!0})}}r.RowTransformerValidator=s},{"../types":25,"lodash.isfunction":30}],24:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.HeaderTransformer=r.RowTransformerValidator=void 0;var n=e("./RowTransformerValidator");Object.defineProperty(r,"RowTransformerValidator",{enumerable:!0,get:function(){return n.RowTransformerValidator}});var i=e("./HeaderTransformer");Object.defineProperty(r,"HeaderTransformer",{enumerable:!0,get:function(){return i.HeaderTransformer}})},{"./HeaderTransformer":22,"./RowTransformerValidator":23}],25:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.isSyncValidate=r.isSyncTransform=void 0,r.isSyncTransform=(e=>1===e.length),r.isSyncValidate=(e=>1===e.length)},{}],26:[function(e,t,r){(function(e){var r=1/0,n="[object Symbol]",i=/[\\^$.*+?()[\]{}|]/g,o=RegExp(i.source),s="object"==typeof e&&e&&e.Object===Object&&e,a="object"==typeof self&&self&&self.Object===Object&&self,u=s||a||Function("return this")(),f=Object.prototype.toString,l=u.Symbol,c=l?l.prototype:void 0,h=c?c.toString:void 0;function d(e){if("string"==typeof e)return e;if(function(e){return"symbol"==typeof e||function(e){return!!e&&"object"==typeof e}(e)&&f.call(e)==n}(e))return h?h.call(e):"";var t=e+"";return"0"==t&&1/e==-r?"-0":t}t.exports=function(e){var t;return(e=null==(t=e)?"":d(t))&&o.test(e)?e.replace(i,"\\$&"):e}}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{}],27:[function(e,t,r){(function(e){var n=200,i="Expected a function",o="__lodash_hash_undefined__",s=1,a=2,u=1/0,f=9007199254740991,l="[object Arguments]",c="[object Array]",h="[object Boolean]",d="[object Date]",p="[object Error]",y="[object Function]",m="[object GeneratorFunction]",g="[object Map]",b="[object Number]",v="[object Object]",w="[object RegExp]",_="[object Set]",j="[object String]",T="[object Symbol]",O="[object ArrayBuffer]",S="[object DataView]",C=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,k=/^\w*$/,E=/^\./,P=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,x=/\\(\\)?/g,R=/^\[object .+?Constructor\]$/,A=/^(?:0|[1-9]\d*)$/,M={};M["[object Float32Array]"]=M["[object Float64Array]"]=M["[object Int8Array]"]=M["[object Int16Array]"]=M["[object Int32Array]"]=M["[object Uint8Array]"]=M["[object Uint8ClampedArray]"]=M["[object Uint16Array]"]=M["[object Uint32Array]"]=!0,M[l]=M[c]=M[O]=M[h]=M[S]=M[d]=M[p]=M[y]=M[g]=M[b]=M[v]=M[w]=M[_]=M[j]=M["[object WeakMap]"]=!1;var F="object"==typeof e&&e&&e.Object===Object&&e,L="object"==typeof self&&self&&self.Object===Object&&self,B=F||L||Function("return this")(),U="object"==typeof r&&r&&!r.nodeType&&r,D=U&&"object"==typeof t&&t&&!t.nodeType&&t,N=D&&D.exports===U&&F.process,I=function(){try{return N&&N.binding("util")}catch(e){}}(),H=I&&I.isTypedArray;function q(e,t,r,n){for(var i=-1,o=e?e.length:0;++i-1},Se.prototype.set=function(e,t){var r=this.__data__,n=xe(r,e);return n<0?r.push([e,t]):r[n][1]=t,this},Ce.prototype.clear=function(){this.__data__={hash:new Oe,map:new(ce||Se),string:new Oe}},Ce.prototype.delete=function(e){return ze(this,e).delete(e)},Ce.prototype.get=function(e){return ze(this,e).get(e)},Ce.prototype.has=function(e){return ze(this,e).has(e)},Ce.prototype.set=function(e,t){return ze(this,e).set(e,t),this},ke.prototype.add=ke.prototype.push=function(e){return this.__data__.set(e,o),this},ke.prototype.has=function(e){return this.__data__.has(e)},Ee.prototype.clear=function(){this.__data__=new Se},Ee.prototype.delete=function(e){return this.__data__.delete(e)},Ee.prototype.get=function(e){return this.__data__.get(e)},Ee.prototype.has=function(e){return this.__data__.has(e)},Ee.prototype.set=function(e,t){var r=this.__data__;if(r instanceof Se){var i=r.__data__;if(!ce||i.lengthf))return!1;var c=o.get(e);if(c&&o.get(t))return c==t;var h=-1,d=!0,p=i&s?new ke:void 0;for(o.set(e,t),o.set(t,e);++h-1&&e%1==0&&e-1&&e%1==0&&e<=f}function lt(e){var t=typeof e;return!!e&&("object"==t||"function"==t)}function ct(e){return!!e&&"object"==typeof e}function ht(e){return"symbol"==typeof e||ct(e)&&ne.call(e)==T}var dt=H?function(e){return function(t){return e(t)}}(H):function(e){return ct(e)&&ft(e.length)&&!!M[ne.call(e)]};function pt(e){return at(e)?Pe(e):He(e)}function yt(e){return e}t.exports=rt}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{}],28:[function(e,t,r){var n="[object Boolean]",i=Object.prototype.toString;t.exports=function(e){return!0===e||!1===e||function(e){return!!e&&"object"==typeof e}(e)&&i.call(e)==n}},{}],29:[function(e,t,r){(function(e){var n=200,i="__lodash_hash_undefined__",o=1,s=2,a=9007199254740991,u="[object Arguments]",f="[object Array]",l="[object AsyncFunction]",c="[object Boolean]",h="[object Date]",d="[object Error]",p="[object Function]",y="[object GeneratorFunction]",m="[object Map]",g="[object Number]",b="[object Null]",v="[object Object]",w="[object Proxy]",_="[object RegExp]",j="[object Set]",T="[object String]",O="[object Symbol]",S="[object Undefined]",C="[object ArrayBuffer]",k="[object DataView]",E=/^\[object .+?Constructor\]$/,P=/^(?:0|[1-9]\d*)$/,x={};x["[object Float32Array]"]=x["[object Float64Array]"]=x["[object Int8Array]"]=x["[object Int16Array]"]=x["[object Int32Array]"]=x["[object Uint8Array]"]=x["[object Uint8ClampedArray]"]=x["[object Uint16Array]"]=x["[object Uint32Array]"]=!0,x[u]=x[f]=x[C]=x[c]=x[k]=x[h]=x[d]=x[p]=x[m]=x[g]=x[v]=x[_]=x[j]=x[T]=x["[object WeakMap]"]=!1;var R="object"==typeof e&&e&&e.Object===Object&&e,A="object"==typeof self&&self&&self.Object===Object&&self,M=R||A||Function("return this")(),F="object"==typeof r&&r&&!r.nodeType&&r,L=F&&"object"==typeof t&&t&&!t.nodeType&&t,B=L&&L.exports===F,U=B&&R.process,D=function(){try{return U&&U.binding&&U.binding("util")}catch(e){}}(),N=D&&D.isTypedArray;function I(e,t){for(var r=-1,n=null==e?0:e.length;++rf))return!1;var c=a.get(e);if(c&&a.get(t))return c==t;var h=-1,d=!0,p=r&s?new Ce:void 0;for(a.set(e,t),a.set(t,e);++h-1},Oe.prototype.set=function(e,t){var r=this.__data__,n=Pe(r,e);return n<0?(++this.size,r.push([e,t])):r[n][1]=t,this},Se.prototype.clear=function(){this.size=0,this.__data__={hash:new Te,map:new(ce||Oe),string:new Te}},Se.prototype.delete=function(e){var t=Ue(this,e).delete(e);return this.size-=t?1:0,t},Se.prototype.get=function(e){return Ue(this,e).get(e)},Se.prototype.has=function(e){return Ue(this,e).has(e)},Se.prototype.set=function(e,t){var r=Ue(this,e),n=r.size;return r.set(e,t),this.size+=r.size==n?0:1,this},Ce.prototype.add=Ce.prototype.push=function(e){return this.__data__.set(e,i),this},Ce.prototype.has=function(e){return this.__data__.has(e)},ke.prototype.clear=function(){this.__data__=new Oe,this.size=0},ke.prototype.delete=function(e){var t=this.__data__,r=t.delete(e);return this.size=t.size,r},ke.prototype.get=function(e){return this.__data__.get(e)},ke.prototype.has=function(e){return this.__data__.has(e)},ke.prototype.set=function(e,t){var r=this.__data__;if(r instanceof Oe){var i=r.__data__;if(!ce||i.length-1&&e%1==0&&e-1&&e%1==0&&e<=a}function Xe(e){var t=typeof e;return null!=e&&("object"==t||"function"==t)}function Je(e){return null!=e&&"object"==typeof e}var Ye=N?function(e){return function(t){return e(t)}}(N):function(e){return Je(e)&&Ge(e.length)&&!!x[xe(e)]};function Ke(e){return null!=(t=e)&&Ge(t.length)&&!Qe(t)?Ee(e):Fe(e);var t}t.exports=function(e,t){return Ae(e,t)}}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{}],30:[function(e,t,r){(function(e){var r="[object AsyncFunction]",n="[object Function]",i="[object GeneratorFunction]",o="[object Null]",s="[object Proxy]",a="[object Undefined]",u="object"==typeof e&&e&&e.Object===Object&&e,f="object"==typeof self&&self&&self.Object===Object&&self,l=u||f||Function("return this")(),c=Object.prototype,h=c.hasOwnProperty,d=c.toString,p=l.Symbol,y=p?p.toStringTag:void 0;function m(e){return null==e?void 0===e?a:o:y&&y in Object(e)?function(e){var t=h.call(e,y),r=e[y];try{e[y]=void 0;var n=!0}catch(e){}var i=d.call(e);n&&(t?e[y]=r:delete e[y]);return i}(e):function(e){return d.call(e)}(e)}t.exports=function(e){if(!function(e){var t=typeof e;return null!=e&&("object"==t||"function"==t)}(e))return!1;var t=m(e);return t==n||t==i||t==r||t==s}}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{}],31:[function(e,t,r){t.exports=function(e){return null==e}},{}],32:[function(e,t,r){t.exports=function(e){return void 0===e}},{}],33:[function(e,t,r){(function(e){var r=200,n="__lodash_hash_undefined__",i="[object Function]",o="[object GeneratorFunction]",s=/^\[object .+?Constructor\]$/,a="object"==typeof e&&e&&e.Object===Object&&e,u="object"==typeof self&&self&&self.Object===Object&&self,f=a||u||Function("return this")();function l(e,t){return!!(e?e.length:0)&&function(e,t,r){if(t!=t)return function(e,t,r,n){var i=e.length,o=r+(n?1:-1);for(;n?o--:++o-1}function c(e,t,r){for(var n=-1,i=e?e.length:0;++n-1},x.prototype.set=function(e,t){var r=this.__data__,n=M(r,e);return n<0?r.push([e,t]):r[n][1]=t,this},R.prototype.clear=function(){this.__data__={hash:new P,map:new(C||x),string:new P}},R.prototype.delete=function(e){return B(this,e).delete(e)},R.prototype.get=function(e){return B(this,e).get(e)},R.prototype.has=function(e){return B(this,e).has(e)},R.prototype.set=function(e,t){return B(this,e).set(e,t),this},A.prototype.add=A.prototype.push=function(e){return this.__data__.set(e,n),this},A.prototype.has=function(e){return this.__data__.has(e)};var L=k&&1/p(new k([,-0]))[1]==1/0?function(e){return new k(e)}:function(){};function B(e,t){var r,n,i=e.__data__;return("string"==(n=typeof(r=t))||"number"==n||"symbol"==n||"boolean"==n?"__proto__"!==r:null===r)?i["string"==typeof t?"string":"hash"]:i.map}function U(e,t){var r=function(e,t){return null==e?void 0:e[t]}(e,t);return F(r)?r:void 0}function D(e){var t=typeof e;return!!e&&("object"==t||"function"==t)}t.exports=function(e){return e&&e.length?function(e,t,n){var i=-1,o=l,s=e.length,a=!0,u=[],f=u;if(n)a=!1,o=c;else if(s>=r){var h=t?null:L(e);if(h)return p(h);a=!1,o=d,f=new A}else f=t?[]:u;e:for(;++i0?s-4:s;for(r=0;r>16&255,u[l++]=t>>8&255,u[l++]=255&t;2===a&&(t=i[e.charCodeAt(r)]<<2|i[e.charCodeAt(r+1)]>>4,u[l++]=255&t);1===a&&(t=i[e.charCodeAt(r)]<<10|i[e.charCodeAt(r+1)]<<4|i[e.charCodeAt(r+2)]>>2,u[l++]=t>>8&255,u[l++]=255&t);return u},r.fromByteArray=function(e){for(var t,r=e.length,i=r%3,o=[],s=0,a=r-i;sa?a:s+16383));1===i?(t=e[r-1],o.push(n[t>>2]+n[t<<4&63]+"==")):2===i&&(t=(e[r-2]<<8)+e[r-1],o.push(n[t>>10]+n[t>>4&63]+n[t<<2&63]+"="));return o.join("")};for(var n=[],i=[],o="undefined"!=typeof Uint8Array?Uint8Array:Array,s="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",a=0,u=s.length;a0)throw new Error("Invalid string. Length must be a multiple of 4");var r=e.indexOf("=");return-1===r&&(r=t),[r,r===t?0:4-r%4]}function l(e,t,r){for(var i,o,s=[],a=t;a>18&63]+n[o>>12&63]+n[o>>6&63]+n[63&o]);return s.join("")}i["-".charCodeAt(0)]=62,i["_".charCodeAt(0)]=63},{}],35:[function(e,t,r){},{}],36:[function(e,t,r){arguments[4][35][0].apply(r,arguments)},{dup:35}],37:[function(e,t,r){(function(t){"use strict";var n=e("base64-js"),i=e("ieee754");r.Buffer=t,r.SlowBuffer=function(e){+e!=e&&(e=0);return t.alloc(+e)},r.INSPECT_MAX_BYTES=50;var o=2147483647;function s(e){if(e>o)throw new RangeError('The value "'+e+'" is invalid for option "size"');var r=new Uint8Array(e);return r.__proto__=t.prototype,r}function t(e,t,r){if("number"==typeof e){if("string"==typeof t)throw new TypeError('The "string" argument must be of type string. Received type number');return f(e)}return a(e,t,r)}function a(e,r,n){if("string"==typeof e)return function(e,r){"string"==typeof r&&""!==r||(r="utf8");if(!t.isEncoding(r))throw new TypeError("Unknown encoding: "+r);var n=0|h(e,r),i=s(n),o=i.write(e,r);o!==n&&(i=i.slice(0,o));return i}(e,r);if(ArrayBuffer.isView(e))return l(e);if(null==e)throw TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof e);if(N(e,ArrayBuffer)||e&&N(e.buffer,ArrayBuffer))return function(e,r,n){if(r<0||e.byteLength=o)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+o.toString(16)+" bytes");return 0|e}function h(e,r){if(t.isBuffer(e))return e.length;if(ArrayBuffer.isView(e)||N(e,ArrayBuffer))return e.byteLength;if("string"!=typeof e)throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof e);var n=e.length,i=arguments.length>2&&!0===arguments[2];if(!i&&0===n)return 0;for(var o=!1;;)switch(r){case"ascii":case"latin1":case"binary":return n;case"utf8":case"utf-8":return B(e).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*n;case"hex":return n>>>1;case"base64":return U(e).length;default:if(o)return i?-1:B(e).length;r=(""+r).toLowerCase(),o=!0}}function d(e,t,r){var n=e[t];e[t]=e[r],e[r]=n}function p(e,r,n,i,o){if(0===e.length)return-1;if("string"==typeof n?(i=n,n=0):n>2147483647?n=2147483647:n<-2147483648&&(n=-2147483648),I(n=+n)&&(n=o?0:e.length-1),n<0&&(n=e.length+n),n>=e.length){if(o)return-1;n=e.length-1}else if(n<0){if(!o)return-1;n=0}if("string"==typeof r&&(r=t.from(r,i)),t.isBuffer(r))return 0===r.length?-1:y(e,r,n,i,o);if("number"==typeof r)return r&=255,"function"==typeof Uint8Array.prototype.indexOf?o?Uint8Array.prototype.indexOf.call(e,r,n):Uint8Array.prototype.lastIndexOf.call(e,r,n):y(e,[r],n,i,o);throw new TypeError("val must be string, number or Buffer")}function y(e,t,r,n,i){var o,s=1,a=e.length,u=t.length;if(void 0!==n&&("ucs2"===(n=String(n).toLowerCase())||"ucs-2"===n||"utf16le"===n||"utf-16le"===n)){if(e.length<2||t.length<2)return-1;s=2,a/=2,u/=2,r/=2}function f(e,t){return 1===s?e[t]:e.readUInt16BE(t*s)}if(i){var l=-1;for(o=r;oa&&(r=a-u),o=r;o>=0;o--){for(var c=!0,h=0;hi&&(n=i):n=i;var o=t.length;n>o/2&&(n=o/2);for(var s=0;s>8,i=r%256,o.push(i),o.push(n);return o}(t,e.length-r),e,r,n)}function j(e,t,r){return 0===t&&r===e.length?n.fromByteArray(e):n.fromByteArray(e.slice(t,r))}function T(e,t,r){r=Math.min(e.length,r);for(var n=[],i=t;i239?4:f>223?3:f>191?2:1;if(i+c<=r)switch(c){case 1:f<128&&(l=f);break;case 2:128==(192&(o=e[i+1]))&&(u=(31&f)<<6|63&o)>127&&(l=u);break;case 3:o=e[i+1],s=e[i+2],128==(192&o)&&128==(192&s)&&(u=(15&f)<<12|(63&o)<<6|63&s)>2047&&(u<55296||u>57343)&&(l=u);break;case 4:o=e[i+1],s=e[i+2],a=e[i+3],128==(192&o)&&128==(192&s)&&128==(192&a)&&(u=(15&f)<<18|(63&o)<<12|(63&s)<<6|63&a)>65535&&u<1114112&&(l=u)}null===l?(l=65533,c=1):l>65535&&(l-=65536,n.push(l>>>10&1023|55296),l=56320|1023&l),n.push(l),i+=c}return function(e){var t=e.length;if(t<=O)return String.fromCharCode.apply(String,e);var r="",n=0;for(;nthis.length)return"";if((void 0===r||r>this.length)&&(r=this.length),r<=0)return"";if((r>>>=0)<=(t>>>=0))return"";for(e||(e="utf8");;)switch(e){case"hex":return k(this,t,r);case"utf8":case"utf-8":return T(this,t,r);case"ascii":return S(this,t,r);case"latin1":case"binary":return C(this,t,r);case"base64":return j(this,t,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return E(this,t,r);default:if(n)throw new TypeError("Unknown encoding: "+e);e=(e+"").toLowerCase(),n=!0}}.apply(this,arguments)},t.prototype.toLocaleString=t.prototype.toString,t.prototype.equals=function(e){if(!t.isBuffer(e))throw new TypeError("Argument must be a Buffer");return this===e||0===t.compare(this,e)},t.prototype.inspect=function(){var e="",t=r.INSPECT_MAX_BYTES;return e=this.toString("hex",0,t).replace(/(.{2})/g,"$1 ").trim(),this.length>t&&(e+=" ... "),""},t.prototype.compare=function(e,r,n,i,o){if(N(e,Uint8Array)&&(e=t.from(e,e.offset,e.byteLength)),!t.isBuffer(e))throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof e);if(void 0===r&&(r=0),void 0===n&&(n=e?e.length:0),void 0===i&&(i=0),void 0===o&&(o=this.length),r<0||n>e.length||i<0||o>this.length)throw new RangeError("out of range index");if(i>=o&&r>=n)return 0;if(i>=o)return-1;if(r>=n)return 1;if(this===e)return 0;for(var s=(o>>>=0)-(i>>>=0),a=(n>>>=0)-(r>>>=0),u=Math.min(s,a),f=this.slice(i,o),l=e.slice(r,n),c=0;c>>=0,isFinite(r)?(r>>>=0,void 0===n&&(n="utf8")):(n=r,r=void 0)}var i=this.length-t;if((void 0===r||r>i)&&(r=i),e.length>0&&(r<0||t<0)||t>this.length)throw new RangeError("Attempt to write outside buffer bounds");n||(n="utf8");for(var o=!1;;)switch(n){case"hex":return m(this,e,t,r);case"utf8":case"utf-8":return g(this,e,t,r);case"ascii":return b(this,e,t,r);case"latin1":case"binary":return v(this,e,t,r);case"base64":return w(this,e,t,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return _(this,e,t,r);default:if(o)throw new TypeError("Unknown encoding: "+n);n=(""+n).toLowerCase(),o=!0}},t.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};var O=4096;function S(e,t,r){var n="";r=Math.min(e.length,r);for(var i=t;in)&&(r=n);for(var i="",o=t;or)throw new RangeError("Trying to access beyond buffer length")}function x(e,r,n,i,o,s){if(!t.isBuffer(e))throw new TypeError('"buffer" argument must be a Buffer instance');if(r>o||re.length)throw new RangeError("Index out of range")}function R(e,t,r,n,i,o){if(r+n>e.length)throw new RangeError("Index out of range");if(r<0)throw new RangeError("Index out of range")}function A(e,t,r,n,o){return t=+t,r>>>=0,o||R(e,0,r,4),i.write(e,t,r,n,23,4),r+4}function M(e,t,r,n,o){return t=+t,r>>>=0,o||R(e,0,r,8),i.write(e,t,r,n,52,8),r+8}t.prototype.slice=function(e,r){var n=this.length;(e=~~e)<0?(e+=n)<0&&(e=0):e>n&&(e=n),(r=void 0===r?n:~~r)<0?(r+=n)<0&&(r=0):r>n&&(r=n),r>>=0,t>>>=0,r||P(e,t,this.length);for(var n=this[e],i=1,o=0;++o>>=0,t>>>=0,r||P(e,t,this.length);for(var n=this[e+--t],i=1;t>0&&(i*=256);)n+=this[e+--t]*i;return n},t.prototype.readUInt8=function(e,t){return e>>>=0,t||P(e,1,this.length),this[e]},t.prototype.readUInt16LE=function(e,t){return e>>>=0,t||P(e,2,this.length),this[e]|this[e+1]<<8},t.prototype.readUInt16BE=function(e,t){return e>>>=0,t||P(e,2,this.length),this[e]<<8|this[e+1]},t.prototype.readUInt32LE=function(e,t){return e>>>=0,t||P(e,4,this.length),(this[e]|this[e+1]<<8|this[e+2]<<16)+16777216*this[e+3]},t.prototype.readUInt32BE=function(e,t){return e>>>=0,t||P(e,4,this.length),16777216*this[e]+(this[e+1]<<16|this[e+2]<<8|this[e+3])},t.prototype.readIntLE=function(e,t,r){e>>>=0,t>>>=0,r||P(e,t,this.length);for(var n=this[e],i=1,o=0;++o=(i*=128)&&(n-=Math.pow(2,8*t)),n},t.prototype.readIntBE=function(e,t,r){e>>>=0,t>>>=0,r||P(e,t,this.length);for(var n=t,i=1,o=this[e+--n];n>0&&(i*=256);)o+=this[e+--n]*i;return o>=(i*=128)&&(o-=Math.pow(2,8*t)),o},t.prototype.readInt8=function(e,t){return e>>>=0,t||P(e,1,this.length),128&this[e]?-1*(255-this[e]+1):this[e]},t.prototype.readInt16LE=function(e,t){e>>>=0,t||P(e,2,this.length);var r=this[e]|this[e+1]<<8;return 32768&r?4294901760|r:r},t.prototype.readInt16BE=function(e,t){e>>>=0,t||P(e,2,this.length);var r=this[e+1]|this[e]<<8;return 32768&r?4294901760|r:r},t.prototype.readInt32LE=function(e,t){return e>>>=0,t||P(e,4,this.length),this[e]|this[e+1]<<8|this[e+2]<<16|this[e+3]<<24},t.prototype.readInt32BE=function(e,t){return e>>>=0,t||P(e,4,this.length),this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]},t.prototype.readFloatLE=function(e,t){return e>>>=0,t||P(e,4,this.length),i.read(this,e,!0,23,4)},t.prototype.readFloatBE=function(e,t){return e>>>=0,t||P(e,4,this.length),i.read(this,e,!1,23,4)},t.prototype.readDoubleLE=function(e,t){return e>>>=0,t||P(e,8,this.length),i.read(this,e,!0,52,8)},t.prototype.readDoubleBE=function(e,t){return e>>>=0,t||P(e,8,this.length),i.read(this,e,!1,52,8)},t.prototype.writeUIntLE=function(e,t,r,n){(e=+e,t>>>=0,r>>>=0,n)||x(this,e,t,r,Math.pow(2,8*r)-1,0);var i=1,o=0;for(this[t]=255&e;++o>>=0,r>>>=0,n)||x(this,e,t,r,Math.pow(2,8*r)-1,0);var i=r-1,o=1;for(this[t+i]=255&e;--i>=0&&(o*=256);)this[t+i]=e/o&255;return t+r},t.prototype.writeUInt8=function(e,t,r){return e=+e,t>>>=0,r||x(this,e,t,1,255,0),this[t]=255&e,t+1},t.prototype.writeUInt16LE=function(e,t,r){return e=+e,t>>>=0,r||x(this,e,t,2,65535,0),this[t]=255&e,this[t+1]=e>>>8,t+2},t.prototype.writeUInt16BE=function(e,t,r){return e=+e,t>>>=0,r||x(this,e,t,2,65535,0),this[t]=e>>>8,this[t+1]=255&e,t+2},t.prototype.writeUInt32LE=function(e,t,r){return e=+e,t>>>=0,r||x(this,e,t,4,4294967295,0),this[t+3]=e>>>24,this[t+2]=e>>>16,this[t+1]=e>>>8,this[t]=255&e,t+4},t.prototype.writeUInt32BE=function(e,t,r){return e=+e,t>>>=0,r||x(this,e,t,4,4294967295,0),this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e,t+4},t.prototype.writeIntLE=function(e,t,r,n){if(e=+e,t>>>=0,!n){var i=Math.pow(2,8*r-1);x(this,e,t,r,i-1,-i)}var o=0,s=1,a=0;for(this[t]=255&e;++o>0)-a&255;return t+r},t.prototype.writeIntBE=function(e,t,r,n){if(e=+e,t>>>=0,!n){var i=Math.pow(2,8*r-1);x(this,e,t,r,i-1,-i)}var o=r-1,s=1,a=0;for(this[t+o]=255&e;--o>=0&&(s*=256);)e<0&&0===a&&0!==this[t+o+1]&&(a=1),this[t+o]=(e/s>>0)-a&255;return t+r},t.prototype.writeInt8=function(e,t,r){return e=+e,t>>>=0,r||x(this,e,t,1,127,-128),e<0&&(e=255+e+1),this[t]=255&e,t+1},t.prototype.writeInt16LE=function(e,t,r){return e=+e,t>>>=0,r||x(this,e,t,2,32767,-32768),this[t]=255&e,this[t+1]=e>>>8,t+2},t.prototype.writeInt16BE=function(e,t,r){return e=+e,t>>>=0,r||x(this,e,t,2,32767,-32768),this[t]=e>>>8,this[t+1]=255&e,t+2},t.prototype.writeInt32LE=function(e,t,r){return e=+e,t>>>=0,r||x(this,e,t,4,2147483647,-2147483648),this[t]=255&e,this[t+1]=e>>>8,this[t+2]=e>>>16,this[t+3]=e>>>24,t+4},t.prototype.writeInt32BE=function(e,t,r){return e=+e,t>>>=0,r||x(this,e,t,4,2147483647,-2147483648),e<0&&(e=4294967295+e+1),this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e,t+4},t.prototype.writeFloatLE=function(e,t,r){return A(this,e,t,!0,r)},t.prototype.writeFloatBE=function(e,t,r){return A(this,e,t,!1,r)},t.prototype.writeDoubleLE=function(e,t,r){return M(this,e,t,!0,r)},t.prototype.writeDoubleBE=function(e,t,r){return M(this,e,t,!1,r)},t.prototype.copy=function(e,r,n,i){if(!t.isBuffer(e))throw new TypeError("argument should be a Buffer");if(n||(n=0),i||0===i||(i=this.length),r>=e.length&&(r=e.length),r||(r=0),i>0&&i=this.length)throw new RangeError("Index out of range");if(i<0)throw new RangeError("sourceEnd out of bounds");i>this.length&&(i=this.length),e.length-r=0;--s)e[s+r]=this[s+n];else Uint8Array.prototype.set.call(e,this.subarray(n,i),r);return o},t.prototype.fill=function(e,r,n,i){if("string"==typeof e){if("string"==typeof r?(i=r,r=0,n=this.length):"string"==typeof n&&(i=n,n=this.length),void 0!==i&&"string"!=typeof i)throw new TypeError("encoding must be a string");if("string"==typeof i&&!t.isEncoding(i))throw new TypeError("Unknown encoding: "+i);if(1===e.length){var o=e.charCodeAt(0);("utf8"===i&&o<128||"latin1"===i)&&(e=o)}}else"number"==typeof e&&(e&=255);if(r<0||this.length>>=0,n=void 0===n?this.length:n>>>0,e||(e=0),"number"==typeof e)for(s=r;s55295&&r<57344){if(!i){if(r>56319){(t-=3)>-1&&o.push(239,191,189);continue}if(s+1===n){(t-=3)>-1&&o.push(239,191,189);continue}i=r;continue}if(r<56320){(t-=3)>-1&&o.push(239,191,189),i=r;continue}r=65536+(i-55296<<10|r-56320)}else i&&(t-=3)>-1&&o.push(239,191,189);if(i=null,r<128){if((t-=1)<0)break;o.push(r)}else if(r<2048){if((t-=2)<0)break;o.push(r>>6|192,63&r|128)}else if(r<65536){if((t-=3)<0)break;o.push(r>>12|224,r>>6&63|128,63&r|128)}else{if(!(r<1114112))throw new Error("Invalid code point");if((t-=4)<0)break;o.push(r>>18|240,r>>12&63|128,r>>6&63|128,63&r|128)}}return o}function U(e){return n.toByteArray(function(e){if((e=(e=e.split("=")[0]).trim().replace(F,"")).length<2)return"";for(;e.length%4!=0;)e+="=";return e}(e))}function D(e,t,r,n){for(var i=0;i=t.length||i>=e.length);++i)t[i+r]=e[i];return i}function N(e,t){return e instanceof t||null!=e&&null!=e.constructor&&null!=e.constructor.name&&e.constructor.name===t.name}function I(e){return e!=e}}).call(this,e("buffer").Buffer)},{"base64-js":34,buffer:37,ieee754:40}],38:[function(e,t,r){(function(e){function t(e){return Object.prototype.toString.call(e)}r.isArray=function(e){return Array.isArray?Array.isArray(e):"[object Array]"===t(e)},r.isBoolean=function(e){return"boolean"==typeof e},r.isNull=function(e){return null===e},r.isNullOrUndefined=function(e){return null==e},r.isNumber=function(e){return"number"==typeof e},r.isString=function(e){return"string"==typeof e},r.isSymbol=function(e){return"symbol"==typeof e},r.isUndefined=function(e){return void 0===e},r.isRegExp=function(e){return"[object RegExp]"===t(e)},r.isObject=function(e){return"object"==typeof e&&null!==e},r.isDate=function(e){return"[object Date]"===t(e)},r.isError=function(e){return"[object Error]"===t(e)||e instanceof Error},r.isFunction=function(e){return"function"==typeof e},r.isPrimitive=function(e){return null===e||"boolean"==typeof e||"number"==typeof e||"string"==typeof e||"symbol"==typeof e||void 0===e},r.isBuffer=e.isBuffer}).call(this,{isBuffer:e("../../is-buffer/index.js")})},{"../../is-buffer/index.js":42}],39:[function(e,t,r){var n=Object.create||function(e){var t=function(){};return t.prototype=e,new t},i=Object.keys||function(e){var t=[];for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.push(r);return r},o=Function.prototype.bind||function(e){var t=this;return function(){return t.apply(e,arguments)}};function s(){this._events&&Object.prototype.hasOwnProperty.call(this,"_events")||(this._events=n(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0}t.exports=s,s.EventEmitter=s,s.prototype._events=void 0,s.prototype._maxListeners=void 0;var a,u=10;try{var f={};Object.defineProperty&&Object.defineProperty(f,"x",{value:0}),a=0===f.x}catch(e){a=!1}function l(e){return void 0===e._maxListeners?s.defaultMaxListeners:e._maxListeners}function c(e,t,r,i){var o,s,a;if("function"!=typeof r)throw new TypeError('"listener" argument must be a function');if((s=e._events)?(s.newListener&&(e.emit("newListener",t,r.listener?r.listener:r),s=e._events),a=s[t]):(s=e._events=n(null),e._eventsCount=0),a){if("function"==typeof a?a=s[t]=i?[r,a]:[a,r]:i?a.unshift(r):a.push(r),!a.warned&&(o=l(e))&&o>0&&a.length>o){a.warned=!0;var u=new Error("Possible EventEmitter memory leak detected. "+a.length+' "'+String(t)+'" listeners added. Use emitter.setMaxListeners() to increase limit.');u.name="MaxListenersExceededWarning",u.emitter=e,u.type=t,u.count=a.length,"object"==typeof console&&console.warn&&console.warn("%s: %s",u.name,u.message)}}else a=s[t]=r,++e._eventsCount;return e}function h(){if(!this.fired)switch(this.target.removeListener(this.type,this.wrapFn),this.fired=!0,arguments.length){case 0:return this.listener.call(this.target);case 1:return this.listener.call(this.target,arguments[0]);case 2:return this.listener.call(this.target,arguments[0],arguments[1]);case 3:return this.listener.call(this.target,arguments[0],arguments[1],arguments[2]);default:for(var e=new Array(arguments.length),t=0;t1&&(t=arguments[1]),t instanceof Error)throw t;var u=new Error('Unhandled "error" event. ('+t+")");throw u.context=t,u}if(!(r=s[e]))return!1;var f="function"==typeof r;switch(n=arguments.length){case 1:!function(e,t,r){if(t)e.call(r);else for(var n=e.length,i=m(e,n),o=0;o=0;s--)if(r[s]===t||r[s].listener===t){a=r[s].listener,o=s;break}if(o<0)return this;0===o?r.shift():function(e,t){for(var r=t,n=r+1,i=e.length;n=0;o--)this.removeListener(e,t[o]);return this},s.prototype.listeners=function(e){return p(this,e,!0)},s.prototype.rawListeners=function(e){return p(this,e,!1)},s.listenerCount=function(e,t){return"function"==typeof e.listenerCount?e.listenerCount(t):y.call(e,t)},s.prototype.listenerCount=y,s.prototype.eventNames=function(){return this._eventsCount>0?Reflect.ownKeys(this._events):[]}},{}],40:[function(e,t,r){r.read=function(e,t,r,n,i){var o,s,a=8*i-n-1,u=(1<>1,l=-7,c=r?i-1:0,h=r?-1:1,d=e[t+c];for(c+=h,o=d&(1<<-l)-1,d>>=-l,l+=a;l>0;o=256*o+e[t+c],c+=h,l-=8);for(s=o&(1<<-l)-1,o>>=-l,l+=n;l>0;s=256*s+e[t+c],c+=h,l-=8);if(0===o)o=1-f;else{if(o===u)return s?NaN:1/0*(d?-1:1);s+=Math.pow(2,n),o-=f}return(d?-1:1)*s*Math.pow(2,o-n)},r.write=function(e,t,r,n,i,o){var s,a,u,f=8*o-i-1,l=(1<>1,h=23===i?Math.pow(2,-24)-Math.pow(2,-77):0,d=n?0:o-1,p=n?1:-1,y=t<0||0===t&&1/t<0?1:0;for(t=Math.abs(t),isNaN(t)||t===1/0?(a=isNaN(t)?1:0,s=l):(s=Math.floor(Math.log(t)/Math.LN2),t*(u=Math.pow(2,-s))<1&&(s--,u*=2),(t+=s+c>=1?h/u:h*Math.pow(2,1-c))*u>=2&&(s++,u/=2),s+c>=l?(a=0,s=l):s+c>=1?(a=(t*u-1)*Math.pow(2,i),s+=c):(a=t*Math.pow(2,c-1)*Math.pow(2,i),s=0));i>=8;e[r+d]=255&a,d+=p,a/=256,i-=8);for(s=s<0;e[r+d]=255&s,d+=p,s/=256,f-=8);e[r+d-p]|=128*y}},{}],41:[function(e,t,r){"function"==typeof Object.create?t.exports=function(e,t){t&&(e.super_=t,e.prototype=Object.create(t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}))}:t.exports=function(e,t){if(t){e.super_=t;var r=function(){};r.prototype=t.prototype,e.prototype=new r,e.prototype.constructor=e}}},{}],42:[function(e,t,r){function n(e){return!!e.constructor&&"function"==typeof e.constructor.isBuffer&&e.constructor.isBuffer(e)}t.exports=function(e){return null!=e&&(n(e)||function(e){return"function"==typeof e.readFloatLE&&"function"==typeof e.slice&&n(e.slice(0,0))}(e)||!!e._isBuffer)}},{}],43:[function(e,t,r){var n={}.toString;t.exports=Array.isArray||function(e){return"[object Array]"==n.call(e)}},{}],44:[function(e,t,r){(function(e){"use strict";void 0===e||!e.version||0===e.version.indexOf("v0.")||0===e.version.indexOf("v1.")&&0!==e.version.indexOf("v1.8.")?t.exports={nextTick:function(t,r,n,i){if("function"!=typeof t)throw new TypeError('"callback" argument must be a function');var o,s,a=arguments.length;switch(a){case 0:case 1:return e.nextTick(t);case 2:return e.nextTick(function(){t.call(null,r)});case 3:return e.nextTick(function(){t.call(null,r,n)});case 4:return e.nextTick(function(){t.call(null,r,n,i)});default:for(o=new Array(a-1),s=0;s1)for(var r=1;r0?("string"==typeof t||s.objectMode||Object.getPrototypeOf(t)===f.prototype||(t=function(e){return f.from(e)}(t)),n?s.endEmitted?e.emit("error",new Error("stream.unshift() after end event")):_(e,s,t,!0):s.ended?e.emit("error",new Error("stream.push() after EOF")):(s.reading=!1,s.decoder&&!r?(t=s.decoder.write(t),s.objectMode||0!==t.length?_(e,s,t,!1):C(e,s)):_(e,s,t,!1))):n||(s.reading=!1));return function(e){return!e.ended&&(e.needReadable||e.lengtht.highWaterMark&&(t.highWaterMark=function(e){return e>=j?e=j:(e--,e|=e>>>1,e|=e>>>2,e|=e>>>4,e|=e>>>8,e|=e>>>16,e++),e}(e)),e<=t.length?e:t.ended?t.length:(t.needReadable=!0,0))}function O(e){var t=e._readableState;t.needReadable=!1,t.emittedReadable||(d("emitReadable",t.flowing),t.emittedReadable=!0,t.sync?i.nextTick(S,e):S(e))}function S(e){d("emit readable"),e.emit("readable"),x(e)}function C(e,t){t.readingMore||(t.readingMore=!0,i.nextTick(k,e,t))}function k(e,t){for(var r=t.length;!t.reading&&!t.flowing&&!t.ended&&t.length=t.length?(r=t.decoder?t.buffer.join(""):1===t.buffer.length?t.buffer.head.data:t.buffer.concat(t.length),t.buffer.clear()):r=function(e,t,r){var n;eo.length?o.length:e;if(s===o.length?i+=o:i+=o.slice(0,e),0===(e-=s)){s===o.length?(++n,r.next?t.head=r.next:t.head=t.tail=null):(t.head=r,r.data=o.slice(s));break}++n}return t.length-=n,i}(e,t):function(e,t){var r=f.allocUnsafe(e),n=t.head,i=1;n.data.copy(r),e-=n.data.length;for(;n=n.next;){var o=n.data,s=e>o.length?o.length:e;if(o.copy(r,r.length-e,0,s),0===(e-=s)){s===o.length?(++i,n.next?t.head=n.next:t.head=t.tail=null):(t.head=n,n.data=o.slice(s));break}++i}return t.length-=i,r}(e,t);return n}(e,t.buffer,t.decoder),r);var r}function A(e){var t=e._readableState;if(t.length>0)throw new Error('"endReadable()" called on non-empty stream');t.endEmitted||(t.ended=!0,i.nextTick(M,t,e))}function M(e,t){e.endEmitted||0!==e.length||(e.endEmitted=!0,t.readable=!1,t.emit("end"))}function F(e,t){for(var r=0,n=e.length;r=t.highWaterMark||t.ended))return d("read: emitReadable",t.length,t.ended),0===t.length&&t.ended?A(this):O(this),null;if(0===(e=T(e,t))&&t.ended)return 0===t.length&&A(this),null;var n,i=t.needReadable;return d("need readable",i),(0===t.length||t.length-e0?R(e,t):null)?(t.needReadable=!0,e=0):t.length-=e,0===t.length&&(t.ended||(t.needReadable=!0),r!==e&&t.ended&&A(this)),null!==n&&this.emit("data",n),n},v.prototype._read=function(e){this.emit("error",new Error("_read() is not implemented"))},v.prototype.pipe=function(e,t){var n=this,o=this._readableState;switch(o.pipesCount){case 0:o.pipes=e;break;case 1:o.pipes=[o.pipes,e];break;default:o.pipes.push(e)}o.pipesCount+=1,d("pipe count=%d opts=%j",o.pipesCount,t);var u=(!t||!1!==t.end)&&e!==r.stdout&&e!==r.stderr?l:v;function f(t,r){d("onunpipe"),t===n&&r&&!1===r.hasUnpiped&&(r.hasUnpiped=!0,d("cleanup"),e.removeListener("close",g),e.removeListener("finish",b),e.removeListener("drain",c),e.removeListener("error",m),e.removeListener("unpipe",f),n.removeListener("end",l),n.removeListener("end",v),n.removeListener("data",y),h=!0,!o.awaitDrain||e._writableState&&!e._writableState.needDrain||c())}function l(){d("onend"),e.end()}o.endEmitted?i.nextTick(u):n.once("end",u),e.on("unpipe",f);var c=function(e){return function(){var t=e._readableState;d("pipeOnDrain",t.awaitDrain),t.awaitDrain&&t.awaitDrain--,0===t.awaitDrain&&a(e,"data")&&(t.flowing=!0,x(e))}}(n);e.on("drain",c);var h=!1;var p=!1;function y(t){d("ondata"),p=!1,!1!==e.write(t)||p||((1===o.pipesCount&&o.pipes===e||o.pipesCount>1&&-1!==F(o.pipes,e))&&!h&&(d("false write response, pause",n._readableState.awaitDrain),n._readableState.awaitDrain++,p=!0),n.pause())}function m(t){d("onerror",t),v(),e.removeListener("error",m),0===a(e,"error")&&e.emit("error",t)}function g(){e.removeListener("finish",b),v()}function b(){d("onfinish"),e.removeListener("close",g),v()}function v(){d("unpipe"),n.unpipe(e)}return n.on("data",y),function(e,t,r){if("function"==typeof e.prependListener)return e.prependListener(t,r);e._events&&e._events[t]?s(e._events[t])?e._events[t].unshift(r):e._events[t]=[r,e._events[t]]:e.on(t,r)}(e,"error",m),e.once("close",g),e.once("finish",b),e.emit("pipe",n),o.flowing||(d("pipe resume"),n.resume()),e},v.prototype.unpipe=function(e){var t=this._readableState,r={hasUnpiped:!1};if(0===t.pipesCount)return this;if(1===t.pipesCount)return e&&e!==t.pipes?this:(e||(e=t.pipes),t.pipes=null,t.pipesCount=0,t.flowing=!1,e&&e.emit("unpipe",this,r),this);if(!e){var n=t.pipes,i=t.pipesCount;t.pipes=null,t.pipesCount=0,t.flowing=!1;for(var o=0;o-1?i:o.nextTick;b.WritableState=g;var f=e("core-util-is");f.inherits=e("inherits");var l={deprecate:e("util-deprecate")},c=e("./internal/streams/stream"),h=e("safe-buffer").Buffer,d=n.Uint8Array||function(){};var p,y=e("./internal/streams/destroy");function m(){}function g(t,r){a=a||e("./_stream_duplex"),t=t||{};var n=r instanceof a;this.objectMode=!!t.objectMode,n&&(this.objectMode=this.objectMode||!!t.writableObjectMode);var i=t.highWaterMark,f=t.writableHighWaterMark,l=this.objectMode?16:16384;this.highWaterMark=i||0===i?i:n&&(f||0===f)?f:l,this.highWaterMark=Math.floor(this.highWaterMark),this.finalCalled=!1,this.needDrain=!1,this.ending=!1,this.ended=!1,this.finished=!1,this.destroyed=!1;var c=!1===t.decodeStrings;this.decodeStrings=!c,this.defaultEncoding=t.defaultEncoding||"utf8",this.length=0,this.writing=!1,this.corked=0,this.sync=!0,this.bufferProcessing=!1,this.onwrite=function(e){!function(e,t){var r=e._writableState,n=r.sync,i=r.writecb;if(function(e){e.writing=!1,e.writecb=null,e.length-=e.writelen,e.writelen=0}(r),t)!function(e,t,r,n,i){--t.pendingcb,r?(o.nextTick(i,n),o.nextTick(O,e,t),e._writableState.errorEmitted=!0,e.emit("error",n)):(i(n),e._writableState.errorEmitted=!0,e.emit("error",n),O(e,t))}(e,r,n,t,i);else{var s=j(r);s||r.corked||r.bufferProcessing||!r.bufferedRequest||_(e,r),n?u(w,e,r,s,i):w(e,r,s,i)}}(r,e)},this.writecb=null,this.writelen=0,this.bufferedRequest=null,this.lastBufferedRequest=null,this.pendingcb=0,this.prefinished=!1,this.errorEmitted=!1,this.bufferedRequestCount=0,this.corkedRequestsFree=new s(this)}function b(t){if(a=a||e("./_stream_duplex"),!(p.call(b,this)||this instanceof a))return new b(t);this._writableState=new g(t,this),this.writable=!0,t&&("function"==typeof t.write&&(this._write=t.write),"function"==typeof t.writev&&(this._writev=t.writev),"function"==typeof t.destroy&&(this._destroy=t.destroy),"function"==typeof t.final&&(this._final=t.final)),c.call(this)}function v(e,t,r,n,i,o,s){t.writelen=n,t.writecb=s,t.writing=!0,t.sync=!0,r?e._writev(i,t.onwrite):e._write(i,o,t.onwrite),t.sync=!1}function w(e,t,r,n){r||function(e,t){0===t.length&&t.needDrain&&(t.needDrain=!1,e.emit("drain"))}(e,t),t.pendingcb--,n(),O(e,t)}function _(e,t){t.bufferProcessing=!0;var r=t.bufferedRequest;if(e._writev&&r&&r.next){var n=t.bufferedRequestCount,i=new Array(n),o=t.corkedRequestsFree;o.entry=r;for(var a=0,u=!0;r;)i[a]=r,r.isBuf||(u=!1),r=r.next,a+=1;i.allBuffers=u,v(e,t,!0,t.length,i,"",o.finish),t.pendingcb++,t.lastBufferedRequest=null,o.next?(t.corkedRequestsFree=o.next,o.next=null):t.corkedRequestsFree=new s(t),t.bufferedRequestCount=0}else{for(;r;){var f=r.chunk,l=r.encoding,c=r.callback;if(v(e,t,!1,t.objectMode?1:f.length,f,l,c),r=r.next,t.bufferedRequestCount--,t.writing)break}null===r&&(t.lastBufferedRequest=null)}t.bufferedRequest=r,t.bufferProcessing=!1}function j(e){return e.ending&&0===e.length&&null===e.bufferedRequest&&!e.finished&&!e.writing}function T(e,t){e._final(function(r){t.pendingcb--,r&&e.emit("error",r),t.prefinished=!0,e.emit("prefinish"),O(e,t)})}function O(e,t){var r=j(t);return r&&(!function(e,t){t.prefinished||t.finalCalled||("function"==typeof e._final?(t.pendingcb++,t.finalCalled=!0,o.nextTick(T,e,t)):(t.prefinished=!0,e.emit("prefinish")))}(e,t),0===t.pendingcb&&(t.finished=!0,e.emit("finish"))),r}f.inherits(b,c),g.prototype.getBuffer=function(){for(var e=this.bufferedRequest,t=[];e;)t.push(e),e=e.next;return t},function(){try{Object.defineProperty(g.prototype,"buffer",{get:l.deprecate(function(){return this.getBuffer()},"_writableState.buffer is deprecated. Use _writableState.getBuffer instead.","DEP0003")})}catch(e){}}(),"function"==typeof Symbol&&Symbol.hasInstance&&"function"==typeof Function.prototype[Symbol.hasInstance]?(p=Function.prototype[Symbol.hasInstance],Object.defineProperty(b,Symbol.hasInstance,{value:function(e){return!!p.call(this,e)||this===b&&(e&&e._writableState instanceof g)}})):p=function(e){return e instanceof this},b.prototype.pipe=function(){this.emit("error",new Error("Cannot pipe, not readable"))},b.prototype.write=function(e,t,r){var n,i=this._writableState,s=!1,a=!i.objectMode&&(n=e,h.isBuffer(n)||n instanceof d);return a&&!h.isBuffer(e)&&(e=function(e){return h.from(e)}(e)),"function"==typeof t&&(r=t,t=null),a?t="buffer":t||(t=i.defaultEncoding),"function"!=typeof r&&(r=m),i.ended?function(e,t){var r=new Error("write after end");e.emit("error",r),o.nextTick(t,r)}(this,r):(a||function(e,t,r,n){var i=!0,s=!1;return null===r?s=new TypeError("May not write null values to stream"):"string"==typeof r||void 0===r||t.objectMode||(s=new TypeError("Invalid non-string/buffer chunk")),s&&(e.emit("error",s),o.nextTick(n,s),i=!1),i}(this,i,e,r))&&(i.pendingcb++,s=function(e,t,r,n,i,o){if(!r){var s=function(e,t,r){e.objectMode||!1===e.decodeStrings||"string"!=typeof t||(t=h.from(t,r));return t}(t,n,i);n!==s&&(r=!0,i="buffer",n=s)}var a=t.objectMode?1:n.length;t.length+=a;var u=t.length-1))throw new TypeError("Unknown encoding: "+e);return this._writableState.defaultEncoding=e,this},Object.defineProperty(b.prototype,"writableHighWaterMark",{enumerable:!1,get:function(){return this._writableState.highWaterMark}}),b.prototype._write=function(e,t,r){r(new Error("_write() is not implemented"))},b.prototype._writev=null,b.prototype.end=function(e,t,r){var n=this._writableState;"function"==typeof e?(r=e,e=null,t=null):"function"==typeof t&&(r=t,t=null),null!=e&&this.write(e,t),n.corked&&(n.corked=1,this.uncork()),n.ending||n.finished||function(e,t,r){t.ending=!0,O(e,t),r&&(t.finished?o.nextTick(r):e.once("finish",r));t.ended=!0,e.writable=!1}(this,n,r)},Object.defineProperty(b.prototype,"destroyed",{get:function(){return void 0!==this._writableState&&this._writableState.destroyed},set:function(e){this._writableState&&(this._writableState.destroyed=e)}}),b.prototype.destroy=y.destroy,b.prototype._undestroy=y.undestroy,b.prototype._destroy=function(e,t){this.end(),t(e)}}).call(this,e("_process"),"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{},e("timers").setImmediate)},{"./_stream_duplex":47,"./internal/streams/destroy":53,"./internal/streams/stream":54,_process:45,"core-util-is":38,inherits:41,"process-nextick-args":44,"safe-buffer":55,timers:64,"util-deprecate":65}],52:[function(e,t,r){"use strict";var n=e("safe-buffer").Buffer,i=e("util");t.exports=function(){function e(){!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e),this.head=null,this.tail=null,this.length=0}return e.prototype.push=function(e){var t={data:e,next:null};this.length>0?this.tail.next=t:this.head=t,this.tail=t,++this.length},e.prototype.unshift=function(e){var t={data:e,next:this.head};0===this.length&&(this.tail=t),this.head=t,++this.length},e.prototype.shift=function(){if(0!==this.length){var e=this.head.data;return 1===this.length?this.head=this.tail=null:this.head=this.head.next,--this.length,e}},e.prototype.clear=function(){this.head=this.tail=null,this.length=0},e.prototype.join=function(e){if(0===this.length)return"";for(var t=this.head,r=""+t.data;t=t.next;)r+=e+t.data;return r},e.prototype.concat=function(e){if(0===this.length)return n.alloc(0);if(1===this.length)return this.head.data;for(var t,r,i,o=n.allocUnsafe(e>>>0),s=this.head,a=0;s;)t=s.data,r=o,i=a,t.copy(r,i),a+=s.data.length,s=s.next;return o},e}(),i&&i.inspect&&i.inspect.custom&&(t.exports.prototype[i.inspect.custom]=function(){var e=i.inspect({length:this.length});return this.constructor.name+" "+e})},{"safe-buffer":55,util:35}],53:[function(e,t,r){"use strict";var n=e("process-nextick-args");function i(e,t){e.emit("error",t)}t.exports={destroy:function(e,t){var r=this,o=this._readableState&&this._readableState.destroyed,s=this._writableState&&this._writableState.destroyed;return o||s?(t?t(e):!e||this._writableState&&this._writableState.errorEmitted||n.nextTick(i,this,e),this):(this._readableState&&(this._readableState.destroyed=!0),this._writableState&&(this._writableState.destroyed=!0),this._destroy(e||null,function(e){!t&&e?(n.nextTick(i,r,e),r._writableState&&(r._writableState.errorEmitted=!0)):t&&t(e)}),this)},undestroy:function(){this._readableState&&(this._readableState.destroyed=!1,this._readableState.reading=!1,this._readableState.ended=!1,this._readableState.endEmitted=!1),this._writableState&&(this._writableState.destroyed=!1,this._writableState.ended=!1,this._writableState.ending=!1,this._writableState.finished=!1,this._writableState.errorEmitted=!1)}}},{"process-nextick-args":44}],54:[function(e,t,r){t.exports=e("events").EventEmitter},{events:39}],55:[function(e,t,r){var n=e("buffer"),i=n.Buffer;function o(e,t){for(var r in e)t[r]=e[r]}function s(e,t,r){return i(e,t,r)}i.from&&i.alloc&&i.allocUnsafe&&i.allocUnsafeSlow?t.exports=n:(o(n,r),r.Buffer=s),o(i,s),s.from=function(e,t,r){if("number"==typeof e)throw new TypeError("Argument must not be a number");return i(e,t,r)},s.alloc=function(e,t,r){if("number"!=typeof e)throw new TypeError("Argument must be a number");var n=i(e);return void 0!==t?"string"==typeof r?n.fill(t,r):n.fill(t):n.fill(0),n},s.allocUnsafe=function(e){if("number"!=typeof e)throw new TypeError("Argument must be a number");return i(e)},s.allocUnsafeSlow=function(e){if("number"!=typeof e)throw new TypeError("Argument must be a number");return n.SlowBuffer(e)}},{buffer:37}],56:[function(e,t,r){"use strict";var n=e("safe-buffer").Buffer,i=n.isEncoding||function(e){switch((e=""+e)&&e.toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":case"raw":return!0;default:return!1}};function o(e){var t;switch(this.encoding=function(e){var t=function(e){if(!e)return"utf8";for(var t;;)switch(e){case"utf8":case"utf-8":return"utf8";case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return"utf16le";case"latin1":case"binary":return"latin1";case"base64":case"ascii":case"hex":return e;default:if(t)return;e=(""+e).toLowerCase(),t=!0}}(e);if("string"!=typeof t&&(n.isEncoding===i||!i(e)))throw new Error("Unknown encoding: "+e);return t||e}(e),this.encoding){case"utf16le":this.text=u,this.end=f,t=4;break;case"utf8":this.fillLast=a,t=4;break;case"base64":this.text=l,this.end=c,t=3;break;default:return this.write=h,void(this.end=d)}this.lastNeed=0,this.lastTotal=0,this.lastChar=n.allocUnsafe(t)}function s(e){return e<=127?0:e>>5==6?2:e>>4==14?3:e>>3==30?4:e>>6==2?-1:-2}function a(e){var t=this.lastTotal-this.lastNeed,r=function(e,t,r){if(128!=(192&t[0]))return e.lastNeed=0,"�";if(e.lastNeed>1&&t.length>1){if(128!=(192&t[1]))return e.lastNeed=1,"�";if(e.lastNeed>2&&t.length>2&&128!=(192&t[2]))return e.lastNeed=2,"�"}}(this,e);return void 0!==r?r:this.lastNeed<=e.length?(e.copy(this.lastChar,t,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal)):(e.copy(this.lastChar,t,0,e.length),void(this.lastNeed-=e.length))}function u(e,t){if((e.length-t)%2==0){var r=e.toString("utf16le",t);if(r){var n=r.charCodeAt(r.length-1);if(n>=55296&&n<=56319)return this.lastNeed=2,this.lastTotal=4,this.lastChar[0]=e[e.length-2],this.lastChar[1]=e[e.length-1],r.slice(0,-1)}return r}return this.lastNeed=1,this.lastTotal=2,this.lastChar[0]=e[e.length-1],e.toString("utf16le",t,e.length-1)}function f(e){var t=e&&e.length?this.write(e):"";if(this.lastNeed){var r=this.lastTotal-this.lastNeed;return t+this.lastChar.toString("utf16le",0,r)}return t}function l(e,t){var r=(e.length-t)%3;return 0===r?e.toString("base64",t):(this.lastNeed=3-r,this.lastTotal=3,1===r?this.lastChar[0]=e[e.length-1]:(this.lastChar[0]=e[e.length-2],this.lastChar[1]=e[e.length-1]),e.toString("base64",t,e.length-r))}function c(e){var t=e&&e.length?this.write(e):"";return this.lastNeed?t+this.lastChar.toString("base64",0,3-this.lastNeed):t}function h(e){return e.toString(this.encoding)}function d(e){return e&&e.length?this.write(e):""}r.StringDecoder=o,o.prototype.write=function(e){if(0===e.length)return"";var t,r;if(this.lastNeed){if(void 0===(t=this.fillLast(e)))return"";r=this.lastNeed,this.lastNeed=0}else r=0;return r=0)return i>0&&(e.lastNeed=i-1),i;if(--n=0)return i>0&&(e.lastNeed=i-2),i;if(--n=0)return i>0&&(2===i?i=0:e.lastNeed=i-3),i;return 0}(this,e,t);if(!this.lastNeed)return e.toString("utf8",t);this.lastTotal=r;var n=e.length-(r-this.lastNeed);return e.copy(this.lastChar,0,n),e.toString("utf8",t,n)},o.prototype.fillLast=function(e){if(this.lastNeed<=e.length)return e.copy(this.lastChar,this.lastTotal-this.lastNeed,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal);e.copy(this.lastChar,this.lastTotal-this.lastNeed,0,e.length),this.lastNeed-=e.length}},{"safe-buffer":55}],57:[function(e,t,r){t.exports=e("./readable").PassThrough},{"./readable":58}],58:[function(e,t,r){(r=t.exports=e("./lib/_stream_readable.js")).Stream=r,r.Readable=r,r.Writable=e("./lib/_stream_writable.js"),r.Duplex=e("./lib/_stream_duplex.js"),r.Transform=e("./lib/_stream_transform.js"),r.PassThrough=e("./lib/_stream_passthrough.js")},{"./lib/_stream_duplex.js":47,"./lib/_stream_passthrough.js":48,"./lib/_stream_readable.js":49,"./lib/_stream_transform.js":50,"./lib/_stream_writable.js":51}],59:[function(e,t,r){t.exports=e("./readable").Transform},{"./readable":58}],60:[function(e,t,r){t.exports=e("./lib/_stream_writable.js")},{"./lib/_stream_writable.js":51}],61:[function(e,t,r){var n=e("buffer"),i=n.Buffer;function o(e,t){for(var r in e)t[r]=e[r]}function s(e,t,r){return i(e,t,r)}i.from&&i.alloc&&i.allocUnsafe&&i.allocUnsafeSlow?t.exports=n:(o(n,r),r.Buffer=s),s.prototype=Object.create(i.prototype),o(i,s),s.from=function(e,t,r){if("number"==typeof e)throw new TypeError("Argument must not be a number");return i(e,t,r)},s.alloc=function(e,t,r){if("number"!=typeof e)throw new TypeError("Argument must be a number");var n=i(e);return void 0!==t?"string"==typeof r?n.fill(t,r):n.fill(t):n.fill(0),n},s.allocUnsafe=function(e){if("number"!=typeof e)throw new TypeError("Argument must be a number");return i(e)},s.allocUnsafeSlow=function(e){if("number"!=typeof e)throw new TypeError("Argument must be a number");return n.SlowBuffer(e)}},{buffer:37}],62:[function(e,t,r){t.exports=i;var n=e("events").EventEmitter;function i(){n.call(this)}e("inherits")(i,n),i.Readable=e("readable-stream/readable.js"),i.Writable=e("readable-stream/writable.js"),i.Duplex=e("readable-stream/duplex.js"),i.Transform=e("readable-stream/transform.js"),i.PassThrough=e("readable-stream/passthrough.js"),i.Stream=i,i.prototype.pipe=function(e,t){var r=this;function i(t){e.writable&&!1===e.write(t)&&r.pause&&r.pause()}function o(){r.readable&&r.resume&&r.resume()}r.on("data",i),e.on("drain",o),e._isStdio||t&&!1===t.end||(r.on("end",a),r.on("close",u));var s=!1;function a(){s||(s=!0,e.end())}function u(){s||(s=!0,"function"==typeof e.destroy&&e.destroy())}function f(e){if(l(),0===n.listenerCount(this,"error"))throw e}function l(){r.removeListener("data",i),e.removeListener("drain",o),r.removeListener("end",a),r.removeListener("close",u),r.removeListener("error",f),e.removeListener("error",f),r.removeListener("end",l),r.removeListener("close",l),e.removeListener("close",l)}return r.on("error",f),e.on("error",f),r.on("end",l),r.on("close",l),e.on("close",l),e.emit("pipe",r),e}},{events:39,inherits:41,"readable-stream/duplex.js":46,"readable-stream/passthrough.js":57,"readable-stream/readable.js":58,"readable-stream/transform.js":59,"readable-stream/writable.js":60}],63:[function(e,t,r){arguments[4][56][0].apply(r,arguments)},{dup:56,"safe-buffer":61}],64:[function(e,t,r){(function(t,n){var i=e("process/browser.js").nextTick,o=Function.prototype.apply,s=Array.prototype.slice,a={},u=0;function f(e,t){this._id=e,this._clearFn=t}r.setTimeout=function(){return new f(o.call(setTimeout,window,arguments),clearTimeout)},r.setInterval=function(){return new f(o.call(setInterval,window,arguments),clearInterval)},r.clearTimeout=r.clearInterval=function(e){e.close()},f.prototype.unref=f.prototype.ref=function(){},f.prototype.close=function(){this._clearFn.call(window,this._id)},r.enroll=function(e,t){clearTimeout(e._idleTimeoutId),e._idleTimeout=t},r.unenroll=function(e){clearTimeout(e._idleTimeoutId),e._idleTimeout=-1},r._unrefActive=r.active=function(e){clearTimeout(e._idleTimeoutId);var t=e._idleTimeout;t>=0&&(e._idleTimeoutId=setTimeout(function(){e._onTimeout&&e._onTimeout()},t))},r.setImmediate="function"==typeof t?t:function(e){var t=u++,n=!(arguments.length<2)&&s.call(arguments,1);return a[t]=!0,i(function(){a[t]&&(n?e.apply(null,n):e.call(null),r.clearImmediate(t))}),t},r.clearImmediate="function"==typeof n?n:function(e){delete a[e]}}).call(this,e("timers").setImmediate,e("timers").clearImmediate)},{"process/browser.js":45,timers:64}],65:[function(e,t,r){(function(e){function r(t){try{if(!e.localStorage)return!1}catch(e){return!1}var r=e.localStorage[t];return null!=r&&"true"===String(r).toLowerCase()}t.exports=function(e,t){if(r("noDeprecation"))return e;var n=!1;return function(){if(!n){if(r("throwDeprecation"))throw new Error(t);r("traceDeprecation")?console.trace(t):console.warn(t),n=!0}return e.apply(this,arguments)}}}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{}],66:[function(e,t,r){"function"==typeof Object.create?t.exports=function(e,t){e.super_=t,e.prototype=Object.create(t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}})}:t.exports=function(e,t){e.super_=t;var r=function(){};r.prototype=t.prototype,e.prototype=new r,e.prototype.constructor=e}},{}],67:[function(e,t,r){t.exports=function(e){return e&&"object"==typeof e&&"function"==typeof e.copy&&"function"==typeof e.fill&&"function"==typeof e.readUInt8}},{}],68:[function(e,t,r){(function(t,n){var i=/%[sdj%]/g;r.format=function(e){if(!g(e)){for(var t=[],r=0;r=o)return e;switch(e){case"%s":return String(n[r++]);case"%d":return Number(n[r++]);case"%j":try{return JSON.stringify(n[r++])}catch(e){return"[Circular]"}default:return e}}),u=n[r];r=3&&(n.depth=arguments[2]),arguments.length>=4&&(n.colors=arguments[3]),p(t)?n.showHidden=t:t&&r._extend(n,t),b(n.showHidden)&&(n.showHidden=!1),b(n.depth)&&(n.depth=2),b(n.colors)&&(n.colors=!1),b(n.customInspect)&&(n.customInspect=!0),n.colors&&(n.stylize=u),l(n,e,n.depth)}function u(e,t){var r=a.styles[t];return r?"["+a.colors[r][0]+"m"+e+"["+a.colors[r][1]+"m":e}function f(e,t){return e}function l(e,t,n){if(e.customInspect&&t&&T(t.inspect)&&t.inspect!==r.inspect&&(!t.constructor||t.constructor.prototype!==t)){var i=t.inspect(n,e);return g(i)||(i=l(e,i,n)),i}var o=function(e,t){if(b(t))return e.stylize("undefined","undefined");if(g(t)){var r="'"+JSON.stringify(t).replace(/^"|"$/g,"").replace(/'/g,"\\'").replace(/\\"/g,'"')+"'";return e.stylize(r,"string")}if(m(t))return e.stylize(""+t,"number");if(p(t))return e.stylize(""+t,"boolean");if(y(t))return e.stylize("null","null")}(e,t);if(o)return o;var s=Object.keys(t),a=function(e){var t={};return e.forEach(function(e,r){t[e]=!0}),t}(s);if(e.showHidden&&(s=Object.getOwnPropertyNames(t)),j(t)&&(s.indexOf("message")>=0||s.indexOf("description")>=0))return c(t);if(0===s.length){if(T(t)){var u=t.name?": "+t.name:"";return e.stylize("[Function"+u+"]","special")}if(v(t))return e.stylize(RegExp.prototype.toString.call(t),"regexp");if(_(t))return e.stylize(Date.prototype.toString.call(t),"date");if(j(t))return c(t)}var f,w="",O=!1,S=["{","}"];(d(t)&&(O=!0,S=["[","]"]),T(t))&&(w=" [Function"+(t.name?": "+t.name:"")+"]");return v(t)&&(w=" "+RegExp.prototype.toString.call(t)),_(t)&&(w=" "+Date.prototype.toUTCString.call(t)),j(t)&&(w=" "+c(t)),0!==s.length||O&&0!=t.length?n<0?v(t)?e.stylize(RegExp.prototype.toString.call(t),"regexp"):e.stylize("[Object]","special"):(e.seen.push(t),f=O?function(e,t,r,n,i){for(var o=[],s=0,a=t.length;s=0&&0,e+t.replace(/\u001b\[\d\d?m/g,"").length+1},0)>60)return r[0]+(""===t?"":t+"\n ")+" "+e.join(",\n ")+" "+r[1];return r[0]+t+" "+e.join(", ")+" "+r[1]}(f,w,S)):S[0]+w+S[1]}function c(e){return"["+Error.prototype.toString.call(e)+"]"}function h(e,t,r,n,i,o){var s,a,u;if((u=Object.getOwnPropertyDescriptor(t,i)||{value:t[i]}).get?a=u.set?e.stylize("[Getter/Setter]","special"):e.stylize("[Getter]","special"):u.set&&(a=e.stylize("[Setter]","special")),k(n,i)||(s="["+i+"]"),a||(e.seen.indexOf(u.value)<0?(a=y(r)?l(e,u.value,null):l(e,u.value,r-1)).indexOf("\n")>-1&&(a=o?a.split("\n").map(function(e){return" "+e}).join("\n").substr(2):"\n"+a.split("\n").map(function(e){return" "+e}).join("\n")):a=e.stylize("[Circular]","special")),b(s)){if(o&&i.match(/^\d+$/))return a;(s=JSON.stringify(""+i)).match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)?(s=s.substr(1,s.length-2),s=e.stylize(s,"name")):(s=s.replace(/'/g,"\\'").replace(/\\"/g,'"').replace(/(^"|"$)/g,"'"),s=e.stylize(s,"string"))}return s+": "+a}function d(e){return Array.isArray(e)}function p(e){return"boolean"==typeof e}function y(e){return null===e}function m(e){return"number"==typeof e}function g(e){return"string"==typeof e}function b(e){return void 0===e}function v(e){return w(e)&&"[object RegExp]"===O(e)}function w(e){return"object"==typeof e&&null!==e}function _(e){return w(e)&&"[object Date]"===O(e)}function j(e){return w(e)&&("[object Error]"===O(e)||e instanceof Error)}function T(e){return"function"==typeof e}function O(e){return Object.prototype.toString.call(e)}function S(e){return e<10?"0"+e.toString(10):e.toString(10)}r.debuglog=function(e){if(b(o)&&(o=t.env.NODE_DEBUG||""),e=e.toUpperCase(),!s[e])if(new RegExp("\\b"+e+"\\b","i").test(o)){var n=t.pid;s[e]=function(){var t=r.format.apply(r,arguments);console.error("%s %d: %s",e,n,t)}}else s[e]=function(){};return s[e]},r.inspect=a,a.colors={bold:[1,22],italic:[3,23],underline:[4,24],inverse:[7,27],white:[37,39],grey:[90,39],black:[30,39],blue:[34,39],cyan:[36,39],green:[32,39],magenta:[35,39],red:[31,39],yellow:[33,39]},a.styles={special:"cyan",number:"yellow",boolean:"yellow",undefined:"grey",null:"bold",string:"green",date:"magenta",regexp:"red"},r.isArray=d,r.isBoolean=p,r.isNull=y,r.isNullOrUndefined=function(e){return null==e},r.isNumber=m,r.isString=g,r.isSymbol=function(e){return"symbol"==typeof e},r.isUndefined=b,r.isRegExp=v,r.isObject=w,r.isDate=_,r.isError=j,r.isFunction=T,r.isPrimitive=function(e){return null===e||"boolean"==typeof e||"number"==typeof e||"string"==typeof e||"symbol"==typeof e||void 0===e},r.isBuffer=e("./support/isBuffer");var C=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function k(e,t){return Object.prototype.hasOwnProperty.call(e,t)}r.log=function(){var e,t;console.log("%s - %s",(e=new Date,t=[S(e.getHours()),S(e.getMinutes()),S(e.getSeconds())].join(":"),[e.getDate(),C[e.getMonth()],t].join(" ")),r.format.apply(r,arguments))},r.inherits=e("inherits"),r._extend=function(e,t){if(!t||!w(t))return e;for(var r=Object.keys(t),n=r.length;n--;)e[r[n]]=t[r[n]];return e}}).call(this,e("_process"),"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"./support/isBuffer":67,_process:45,inherits:66}]},{},[1])(1)}); \ No newline at end of file diff --git a/app/client/public/libraries/jsonwebtoken@8.5.1.js b/app/client/public/libraries/jsonwebtoken@8.5.1.js new file mode 100644 index 0000000000..ef575d43c5 --- /dev/null +++ b/app/client/public/libraries/jsonwebtoken@8.5.1.js @@ -0,0 +1 @@ +!function(e){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{("undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:this).jsonwebtoken=e()}}(function(){var define,module,exports;return function(){return function e(t,r,n){function i(a,s){if(!r[a]){if(!t[a]){var f="function"==typeof require&&require;if(!s&&f)return f(a,!0);if(o)return o(a,!0);var c=new Error("Cannot find module '"+a+"'");throw c.code="MODULE_NOT_FOUND",c}var u=r[a]={exports:{}};t[a][0].call(u.exports,function(e){return i(t[a][1][e]||e)},u,u.exports,e,t,r,n)}return r[a].exports}for(var o="function"==typeof require&&require,a=0;a=8.0.0")}).call(this,e("_process"))},{_process:145,semver:26}],7:[function(e,t,r){var n=e("ms");t.exports=function(e,t){var r=t||Math.floor(Date.now()/1e3);if("string"==typeof e){var i=n(e);if(void 0===i)return;return Math.floor(r+i/1e3)}return"number"==typeof e?r+e:void 0}},{ms:24}],8:[function(e,t,r){"use strict";var n=e("buffer").Buffer,i=e("buffer").SlowBuffer;function o(e,t){if(!n.isBuffer(e)||!n.isBuffer(t))return!1;if(e.length!==t.length)return!1;for(var r=0,i=0;i=o&&--n,n}t.exports={derToJose:function(e,t){e=f(e);var r=i(t),c=r+1,u=e.length,h=0;if(e[h++]!==a)throw new Error('Could not find expected "seq"');var d=e[h++];if(d===(1|o)&&(d=e[h++]),u-h-1&&e%1==0&&e-1&&e%1==0&&e<=i}(e.length)&&!function(e){var t=C(e)?M.call(e):"";return t==f||t==c}(e)}function C(e){var t=typeof e;return!!e&&("object"==t||"function"==t)}function P(e){return!!e&&"object"==typeof e}t.exports=function(e,t,r,i){var s;e=T(e)?e:(s=e)?g(s,function(e){return T(e)?j(e):B(e)}(s)):[],r=r&&!i?function(e){var t=function(e){if(!e)return 0===e?e:0;if((e=function(e){if("number"==typeof e)return e;if(function(e){return"symbol"==typeof e||P(e)&&M.call(e)==h}(e))return a;if(C(e)){var t="function"==typeof e.valueOf?e.valueOf():e;e=C(t)?t+"":t}if("string"!=typeof e)return 0===e?e:+e;e=e.replace(d,"");var r=p.test(e);return r||b.test(e)?m(e.slice(2),r?2:8):l.test(e)?a:+e}(e))===n||e===-n){var t=e<0?-1:1;return t*o}return e==e?e:0}(e),r=t%1;return t==t?r?t-r:t:0}(r):0;var f=e.length;return r<0&&(r=A(f+r,0)),function(e){return"string"==typeof e||!R(e)&&P(e)&&M.call(e)==u}(e)?r<=f&&e.indexOf(t,r)>-1:!!f&&function(e,t,r){if(t!=t)return function(e,t,r,n){for(var i=e.length,o=r+(n?1:-1);n?o--:++o-1}},{}],18:[function(e,t,r){var n="[object Boolean]",i=Object.prototype.toString;t.exports=function(e){return!0===e||!1===e||function(e){return!!e&&"object"==typeof e}(e)&&i.call(e)==n}},{}],19:[function(e,t,r){var n=1/0,i=1.7976931348623157e308,o=NaN,a="[object Symbol]",s=/^\s+|\s+$/g,f=/^[-+]0x[0-9a-f]+$/i,c=/^0b[01]+$/i,u=/^0o[0-7]+$/i,h=parseInt,d=Object.prototype.toString;function l(e){var t=typeof e;return!!e&&("object"==t||"function"==t)}t.exports=function(e){return"number"==typeof e&&e==function(e){var t=function(e){if(!e)return 0===e?e:0;if((e=function(e){if("number"==typeof e)return e;if(function(e){return"symbol"==typeof e||function(e){return!!e&&"object"==typeof e}(e)&&d.call(e)==a}(e))return o;if(l(e)){var t="function"==typeof e.valueOf?e.valueOf():e;e=l(t)?t+"":t}if("string"!=typeof e)return 0===e?e:+e;e=e.replace(s,"");var r=c.test(e);return r||u.test(e)?h(e.slice(2),r?2:8):f.test(e)?o:+e}(e))===n||e===-n){var t=e<0?-1:1;return t*i}return e==e?e:0}(e),r=t%1;return t==t?r?t-r:t:0}(e)}},{}],20:[function(e,t,r){var n="[object Number]",i=Object.prototype.toString;t.exports=function(e){return"number"==typeof e||function(e){return!!e&&"object"==typeof e}(e)&&i.call(e)==n}},{}],21:[function(e,t,r){var n="[object Object]";var i,o,a=Function.prototype,s=Object.prototype,f=a.toString,c=s.hasOwnProperty,u=f.call(Object),h=s.toString,d=(i=Object.getPrototypeOf,o=Object,function(e){return i(o(e))});t.exports=function(e){if(!function(e){return!!e&&"object"==typeof e}(e)||h.call(e)!=n||function(e){var t=!1;if(null!=e&&"function"!=typeof e.toString)try{t=!!(e+"")}catch(e){}return t}(e))return!1;var t=d(e);if(null===t)return!0;var r=c.call(t,"constructor")&&t.constructor;return"function"==typeof r&&r instanceof r&&f.call(r)==u}},{}],22:[function(e,t,r){var n="[object String]",i=Object.prototype.toString,o=Array.isArray;t.exports=function(e){return"string"==typeof e||!o(e)&&function(e){return!!e&&"object"==typeof e}(e)&&i.call(e)==n}},{}],23:[function(e,t,r){var n="Expected a function",i=1/0,o=1.7976931348623157e308,a=NaN,s="[object Symbol]",f=/^\s+|\s+$/g,c=/^[-+]0x[0-9a-f]+$/i,u=/^0b[01]+$/i,h=/^0o[0-7]+$/i,d=parseInt,l=Object.prototype.toString;function p(e,t){var r;if("function"!=typeof t)throw new TypeError(n);return e=function(e){var t=function(e){if(!e)return 0===e?e:0;if((e=function(e){if("number"==typeof e)return e;if(function(e){return"symbol"==typeof e||function(e){return!!e&&"object"==typeof e}(e)&&l.call(e)==s}(e))return a;if(b(e)){var t="function"==typeof e.valueOf?e.valueOf():e;e=b(t)?t+"":t}if("string"!=typeof e)return 0===e?e:+e;e=e.replace(f,"");var r=u.test(e);return r||h.test(e)?d(e.slice(2),r?2:8):c.test(e)?a:+e}(e))===i||e===-i){var t=e<0?-1:1;return t*o}return e==e?e:0}(e),r=t%1;return t==t?r?t-r:t:0}(e),function(){return--e>0&&(r=t.apply(this,arguments)),e<=1&&(t=void 0),r}}function b(e){var t=typeof e;return!!e&&("object"==t||"function"==t)}t.exports=function(e){return p(2,e)}},{}],24:[function(e,t,r){var n=1e3,i=60*n,o=60*i,a=24*o,s=7*a,f=365.25*a;function c(e,t,r,n){var i=t>=1.5*r;return Math.round(e/r)+" "+n+(i?"s":"")}t.exports=function(e,t){t=t||{};var r=typeof e;if("string"===r&&e.length>0)return function(e){if((e=String(e)).length>100)return;var t=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(e);if(!t)return;var r=parseFloat(t[1]);switch((t[2]||"ms").toLowerCase()){case"years":case"year":case"yrs":case"yr":case"y":return r*f;case"weeks":case"week":case"w":return r*s;case"days":case"day":case"d":return r*a;case"hours":case"hour":case"hrs":case"hr":case"h":return r*o;case"minutes":case"minute":case"mins":case"min":case"m":return r*i;case"seconds":case"second":case"secs":case"sec":case"s":return r*n;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return r;default:return}}(e);if("number"===r&&isFinite(e))return t.long?function(e){var t=Math.abs(e);if(t>=a)return c(e,t,a,"day");if(t>=o)return c(e,t,o,"hour");if(t>=i)return c(e,t,i,"minute");if(t>=n)return c(e,t,n,"second");return e+" ms"}(e):function(e){var t=Math.abs(e);if(t>=a)return Math.round(e/a)+"d";if(t>=o)return Math.round(e/o)+"h";if(t>=i)return Math.round(e/i)+"m";if(t>=n)return Math.round(e/n)+"s";return e+"ms"}(e);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(e))}},{}],25:[function(e,t,r){var n=e("buffer"),i=n.Buffer;function o(e,t){for(var r in e)t[r]=e[r]}function a(e,t,r){return i(e,t,r)}i.from&&i.alloc&&i.allocUnsafe&&i.allocUnsafeSlow?t.exports=n:(o(n,r),r.Buffer=a),a.prototype=Object.create(i.prototype),o(i,a),a.from=function(e,t,r){if("number"==typeof e)throw new TypeError("Argument must not be a number");return i(e,t,r)},a.alloc=function(e,t,r){if("number"!=typeof e)throw new TypeError("Argument must be a number");var n=i(e);return void 0!==t?"string"==typeof r?n.fill(t,r):n.fill(t):n.fill(0),n},a.allocUnsafe=function(e){if("number"!=typeof e)throw new TypeError("Argument must be a number");return i(e)},a.allocUnsafeSlow=function(e){if("number"!=typeof e)throw new TypeError("Argument must be a number");return n.SlowBuffer(e)}},{buffer:75}],26:[function(e,t,r){(function(e){var n;r=t.exports=X,n="object"==typeof e&&e.env&&e.env.NODE_DEBUG&&/\bsemver\b/i.test(e.env.NODE_DEBUG)?function(){var e=Array.prototype.slice.call(arguments,0);e.unshift("SEMVER"),console.log.apply(console,e)}:function(){},r.SEMVER_SPEC_VERSION="2.0.0";var i=256,o=Number.MAX_SAFE_INTEGER||9007199254740991,a=r.re=[],s=r.src=[],f=0,c=f++;s[c]="0|[1-9]\\d*";var u=f++;s[u]="[0-9]+";var h=f++;s[h]="\\d*[a-zA-Z-][a-zA-Z0-9-]*";var d=f++;s[d]="("+s[c]+")\\.("+s[c]+")\\.("+s[c]+")";var l=f++;s[l]="("+s[u]+")\\.("+s[u]+")\\.("+s[u]+")";var p=f++;s[p]="(?:"+s[c]+"|"+s[h]+")";var b=f++;s[b]="(?:"+s[u]+"|"+s[h]+")";var y=f++;s[y]="(?:-("+s[p]+"(?:\\."+s[p]+")*))";var m=f++;s[m]="(?:-?("+s[b]+"(?:\\."+s[b]+")*))";var v=f++;s[v]="[0-9A-Za-z-]+";var g=f++;s[g]="(?:\\+("+s[v]+"(?:\\."+s[v]+")*))";var w=f++,_="v?"+s[d]+s[y]+"?"+s[g]+"?";s[w]="^"+_+"$";var S="[v=\\s]*"+s[l]+s[m]+"?"+s[g]+"?",E=f++;s[E]="^"+S+"$";var M=f++;s[M]="((?:<|>)?=?)";var k=f++;s[k]=s[u]+"|x|X|\\*";var x=f++;s[x]=s[c]+"|x|X|\\*";var A=f++;s[A]="[v=\\s]*("+s[x]+")(?:\\.("+s[x]+")(?:\\.("+s[x]+")(?:"+s[y]+")?"+s[g]+"?)?)?";var j=f++;s[j]="[v=\\s]*("+s[k]+")(?:\\.("+s[k]+")(?:\\.("+s[k]+")(?:"+s[m]+")?"+s[g]+"?)?)?";var B=f++;s[B]="^"+s[M]+"\\s*"+s[A]+"$";var I=f++;s[I]="^"+s[M]+"\\s*"+s[j]+"$";var R=f++;s[R]="(?:^|[^\\d])(\\d{1,16})(?:\\.(\\d{1,16}))?(?:\\.(\\d{1,16}))?(?:$|[^\\d])";var T=f++;s[T]="(?:~>?)";var C=f++;s[C]="(\\s*)"+s[T]+"\\s+",a[C]=new RegExp(s[C],"g");var P=f++;s[P]="^"+s[T]+s[A]+"$";var O=f++;s[O]="^"+s[T]+s[j]+"$";var D=f++;s[D]="(?:\\^)";var N=f++;s[N]="(\\s*)"+s[D]+"\\s+",a[N]=new RegExp(s[N],"g");var L=f++;s[L]="^"+s[D]+s[A]+"$";var U=f++;s[U]="^"+s[D]+s[j]+"$";var q=f++;s[q]="^"+s[M]+"\\s*("+S+")$|^$";var z=f++;s[z]="^"+s[M]+"\\s*("+_+")$|^$";var K=f++;s[K]="(\\s*)"+s[M]+"\\s*("+S+"|"+s[A]+")",a[K]=new RegExp(s[K],"g");var F=f++;s[F]="^\\s*("+s[A]+")\\s+-\\s+("+s[A]+")\\s*$";var H=f++;s[H]="^\\s*("+s[j]+")\\s+-\\s+("+s[j]+")\\s*$";var V=f++;s[V]="(<|>)?=?\\s*\\*";for(var W=0;W<35;W++)n(W,s[W]),a[W]||(a[W]=new RegExp(s[W]));function J(e,t){if(t&&"object"==typeof t||(t={loose:!!t,includePrerelease:!1}),e instanceof X)return e;if("string"!=typeof e)return null;if(e.length>i)return null;if(!(t.loose?a[E]:a[w]).test(e))return null;try{return new X(e,t)}catch(e){return null}}function X(e,t){if(t&&"object"==typeof t||(t={loose:!!t,includePrerelease:!1}),e instanceof X){if(e.loose===t.loose)return e;e=e.version}else if("string"!=typeof e)throw new TypeError("Invalid Version: "+e);if(e.length>i)throw new TypeError("version is longer than "+i+" characters");if(!(this instanceof X))return new X(e,t);n("SemVer",e,t),this.options=t,this.loose=!!t.loose;var r=e.trim().match(t.loose?a[E]:a[w]);if(!r)throw new TypeError("Invalid Version: "+e);if(this.raw=e,this.major=+r[1],this.minor=+r[2],this.patch=+r[3],this.major>o||this.major<0)throw new TypeError("Invalid major version");if(this.minor>o||this.minor<0)throw new TypeError("Invalid minor version");if(this.patch>o||this.patch<0)throw new TypeError("Invalid patch version");r[4]?this.prerelease=r[4].split(".").map(function(e){if(/^[0-9]+$/.test(e)){var t=+e;if(t>=0&&t=0;)"number"==typeof this.prerelease[r]&&(this.prerelease[r]++,r=-2);-1===r&&this.prerelease.push(0)}t&&(this.prerelease[0]===t?isNaN(this.prerelease[1])&&(this.prerelease=[t,0]):this.prerelease=[t,0]);break;default:throw new Error("invalid increment argument: "+e)}return this.format(),this.raw=this.version,this},r.inc=function(e,t,r,n){"string"==typeof r&&(n=r,r=void 0);try{return new X(e,r).inc(t,n).version}catch(e){return null}},r.diff=function(e,t){if(ee(e,t))return null;var r=J(e),n=J(t),i="";if(r.prerelease.length||n.prerelease.length){i="pre";var o="prerelease"}for(var a in r)if(("major"===a||"minor"===a||"patch"===a)&&r[a]!==n[a])return i+a;return o},r.compareIdentifiers=G;var $=/^[0-9]+$/;function G(e,t){var r=$.test(e),n=$.test(t);return r&&n&&(e=+e,t=+t),e===t?0:r&&!n?-1:n&&!r?1:e0}function Q(e,t,r){return Z(e,t,r)<0}function ee(e,t,r){return 0===Z(e,t,r)}function te(e,t,r){return 0!==Z(e,t,r)}function re(e,t,r){return Z(e,t,r)>=0}function ne(e,t,r){return Z(e,t,r)<=0}function ie(e,t,r,n){switch(t){case"===":return"object"==typeof e&&(e=e.version),"object"==typeof r&&(r=r.version),e===r;case"!==":return"object"==typeof e&&(e=e.version),"object"==typeof r&&(r=r.version),e!==r;case"":case"=":case"==":return ee(e,r,n);case"!=":return te(e,r,n);case">":return Y(e,r,n);case">=":return re(e,r,n);case"<":return Q(e,r,n);case"<=":return ne(e,r,n);default:throw new TypeError("Invalid operator: "+t)}}function oe(e,t){if(t&&"object"==typeof t||(t={loose:!!t,includePrerelease:!1}),e instanceof oe){if(e.loose===!!t.loose)return e;e=e.value}if(!(this instanceof oe))return new oe(e,t);n("comparator",e,t),this.options=t,this.loose=!!t.loose,this.parse(e),this.semver===ae?this.value="":this.value=this.operator+this.semver.version,n("comp",this)}r.rcompareIdentifiers=function(e,t){return G(t,e)},r.major=function(e,t){return new X(e,t).major},r.minor=function(e,t){return new X(e,t).minor},r.patch=function(e,t){return new X(e,t).patch},r.compare=Z,r.compareLoose=function(e,t){return Z(e,t,!0)},r.rcompare=function(e,t,r){return Z(t,e,r)},r.sort=function(e,t){return e.sort(function(e,n){return r.compare(e,n,t)})},r.rsort=function(e,t){return e.sort(function(e,n){return r.rcompare(e,n,t)})},r.gt=Y,r.lt=Q,r.eq=ee,r.neq=te,r.gte=re,r.lte=ne,r.cmp=ie,r.Comparator=oe;var ae={};function se(e,t){if(t&&"object"==typeof t||(t={loose:!!t,includePrerelease:!1}),e instanceof se)return e.loose===!!t.loose&&e.includePrerelease===!!t.includePrerelease?e:new se(e.raw,t);if(e instanceof oe)return new se(e.value,t);if(!(this instanceof se))return new se(e,t);if(this.options=t,this.loose=!!t.loose,this.includePrerelease=!!t.includePrerelease,this.raw=e,this.set=e.split(/\s*\|\|\s*/).map(function(e){return this.parseRange(e.trim())},this).filter(function(e){return e.length}),!this.set.length)throw new TypeError("Invalid SemVer Range: "+e);this.format()}function fe(e){return!e||"x"===e.toLowerCase()||"*"===e}function ce(e,t,r,n,i,o,a,s,f,c,u,h,d){return((t=fe(r)?"":fe(n)?">="+r+".0.0":fe(i)?">="+r+"."+n+".0":">="+t)+" "+(s=fe(f)?"":fe(c)?"<"+(+f+1)+".0.0":fe(u)?"<"+f+"."+(+c+1)+".0":h?"<="+f+"."+c+"."+u+"-"+h:"<="+s)).trim()}function ue(e,t,r){for(var i=0;i0){var o=e[i].semver;if(o.major===t.major&&o.minor===t.minor&&o.patch===t.patch)return!0}return!1}return!0}function he(e,t,r){try{t=new se(t,r)}catch(e){return!1}return t.test(e)}function de(e,t,r,n){var i,o,a,s,f;switch(e=new X(e,n),t=new se(t,n),r){case">":i=Y,o=ne,a=Q,s=">",f=">=";break;case"<":i=Q,o=re,a=Y,s="<",f="<=";break;default:throw new TypeError('Must provide a hilo val of "<" or ">"')}if(he(e,t,n))return!1;for(var c=0;c=0.0.0")),h=h||e,d=d||e,i(e.semver,h.semver,n)?h=e:a(e.semver,d.semver,n)&&(d=e)}),h.operator===s||h.operator===f)return!1;if((!d.operator||d.operator===s)&&o(e,d.semver))return!1;if(d.operator===f&&a(e,d.semver))return!1}return!0}oe.prototype.parse=function(e){var t=this.options.loose?a[q]:a[z],r=e.match(t);if(!r)throw new TypeError("Invalid comparator: "+e);this.operator=r[1],"="===this.operator&&(this.operator=""),r[2]?this.semver=new X(r[2],this.options.loose):this.semver=ae},oe.prototype.toString=function(){return this.value},oe.prototype.test=function(e){return n("Comparator.test",e,this.options.loose),this.semver===ae||("string"==typeof e&&(e=new X(e,this.options)),ie(e,this.operator,this.semver,this.options))},oe.prototype.intersects=function(e,t){if(!(e instanceof oe))throw new TypeError("a Comparator is required");var r;if(t&&"object"==typeof t||(t={loose:!!t,includePrerelease:!1}),""===this.operator)return r=new se(e.value,t),he(this.value,r,t);if(""===e.operator)return r=new se(this.value,t),he(e.semver,r,t);var n=!(">="!==this.operator&&">"!==this.operator||">="!==e.operator&&">"!==e.operator),i=!("<="!==this.operator&&"<"!==this.operator||"<="!==e.operator&&"<"!==e.operator),o=this.semver.version===e.semver.version,a=!(">="!==this.operator&&"<="!==this.operator||">="!==e.operator&&"<="!==e.operator),s=ie(this.semver,"<",e.semver,t)&&(">="===this.operator||">"===this.operator)&&("<="===e.operator||"<"===e.operator),f=ie(this.semver,">",e.semver,t)&&("<="===this.operator||"<"===this.operator)&&(">="===e.operator||">"===e.operator);return n||i||o&&a||s||f},r.Range=se,se.prototype.format=function(){return this.range=this.set.map(function(e){return e.join(" ").trim()}).join("||").trim(),this.range},se.prototype.toString=function(){return this.range},se.prototype.parseRange=function(e){var t=this.options.loose;e=e.trim();var r=t?a[H]:a[F];e=e.replace(r,ce),n("hyphen replace",e),e=e.replace(a[K],"$1$2$3"),n("comparator trim",e,a[K]),e=(e=(e=e.replace(a[C],"$1~")).replace(a[N],"$1^")).split(/\s+/).join(" ");var i=t?a[q]:a[z],o=e.split(" ").map(function(e){return function(e,t){return n("comp",e,t),e=function(e,t){return e.trim().split(/\s+/).map(function(e){return function(e,t){n("caret",e,t);var r=t.loose?a[U]:a[L];return e.replace(r,function(t,r,i,o,a){var s;return n("caret",e,t,r,i,o,a),fe(r)?s="":fe(i)?s=">="+r+".0.0 <"+(+r+1)+".0.0":fe(o)?s="0"===r?">="+r+"."+i+".0 <"+r+"."+(+i+1)+".0":">="+r+"."+i+".0 <"+(+r+1)+".0.0":a?(n("replaceCaret pr",a),s="0"===r?"0"===i?">="+r+"."+i+"."+o+"-"+a+" <"+r+"."+i+"."+(+o+1):">="+r+"."+i+"."+o+"-"+a+" <"+r+"."+(+i+1)+".0":">="+r+"."+i+"."+o+"-"+a+" <"+(+r+1)+".0.0"):(n("no pr"),s="0"===r?"0"===i?">="+r+"."+i+"."+o+" <"+r+"."+i+"."+(+o+1):">="+r+"."+i+"."+o+" <"+r+"."+(+i+1)+".0":">="+r+"."+i+"."+o+" <"+(+r+1)+".0.0"),n("caret return",s),s})}(e,t)}).join(" ")}(e,t),n("caret",e),e=function(e,t){return e.trim().split(/\s+/).map(function(e){return function(e,t){var r=t.loose?a[O]:a[P];return e.replace(r,function(t,r,i,o,a){var s;return n("tilde",e,t,r,i,o,a),fe(r)?s="":fe(i)?s=">="+r+".0.0 <"+(+r+1)+".0.0":fe(o)?s=">="+r+"."+i+".0 <"+r+"."+(+i+1)+".0":a?(n("replaceTilde pr",a),s=">="+r+"."+i+"."+o+"-"+a+" <"+r+"."+(+i+1)+".0"):s=">="+r+"."+i+"."+o+" <"+r+"."+(+i+1)+".0",n("tilde return",s),s})}(e,t)}).join(" ")}(e,t),n("tildes",e),e=function(e,t){return n("replaceXRanges",e,t),e.split(/\s+/).map(function(e){return function(e,t){e=e.trim();var r=t.loose?a[I]:a[B];return e.replace(r,function(t,r,i,o,a,s){n("xRange",e,t,r,i,o,a,s);var f=fe(i),c=f||fe(o),u=c||fe(a),h=u;return"="===r&&h&&(r=""),f?t=">"===r||"<"===r?"<0.0.0":"*":r&&h?(c&&(o=0),a=0,">"===r?(r=">=",c?(i=+i+1,o=0,a=0):(o=+o+1,a=0)):"<="===r&&(r="<",c?i=+i+1:o=+o+1),t=r+i+"."+o+"."+a):c?t=">="+i+".0.0 <"+(+i+1)+".0.0":u&&(t=">="+i+"."+o+".0 <"+i+"."+(+o+1)+".0"),n("xRange return",t),t})}(e,t)}).join(" ")}(e,t),n("xrange",e),e=function(e,t){return n("replaceStars",e,t),e.trim().replace(a[V],"")}(e,t),n("stars",e),e}(e,this.options)},this).join(" ").split(/\s+/);return this.options.loose&&(o=o.filter(function(e){return!!e.match(i)})),o=o.map(function(e){return new oe(e,this.options)},this)},se.prototype.intersects=function(e,t){if(!(e instanceof se))throw new TypeError("a Range is required");return this.set.some(function(r){return r.every(function(r){return e.set.some(function(e){return e.every(function(e){return r.intersects(e,t)})})})})},r.toComparators=function(e,t){return new se(e,t).set.map(function(e){return e.map(function(e){return e.value}).join(" ").trim().split(" ")})},se.prototype.test=function(e){if(!e)return!1;"string"==typeof e&&(e=new X(e,this.options));for(var t=0;t":0===t.prerelease.length?t.patch++:t.prerelease.push(0),t.raw=t.format();case"":case">=":r&&!Y(r,t)||(r=t);break;case"<":case"<=":break;default:throw new Error("Unexpected operation: "+e.operator)}})}if(r&&e.test(r))return r;return null},r.validRange=function(e,t){try{return new se(e,t).range||"*"}catch(e){return null}},r.ltr=function(e,t,r){return de(e,t,"<",r)},r.gtr=function(e,t,r){return de(e,t,">",r)},r.outside=de,r.prerelease=function(e,t){var r=J(e,t);return r&&r.prerelease.length?r.prerelease:null},r.intersects=function(e,t,r){return e=new se(e,r),t=new se(t,r),e.intersects(t)},r.coerce=function(e){if(e instanceof X)return e;if("string"!=typeof e)return null;var t=e.match(a[R]);if(null==t)return null;return J(t[1]+"."+(t[2]||"0")+"."+(t[3]||"0"))}}).call(this,e("_process"))},{_process:145}],27:[function(e,t,r){(function(r){var n=e("./lib/timespan"),i=e("./lib/psSupported"),o=e("jws"),a=e("lodash.includes"),s=e("lodash.isboolean"),f=e("lodash.isinteger"),c=e("lodash.isnumber"),u=e("lodash.isplainobject"),h=e("lodash.isstring"),d=e("lodash.once"),l=["RS256","RS384","RS512","ES256","ES384","ES512","HS256","HS384","HS512","none"];i&&l.splice(3,0,"PS256","PS384","PS512");var p={expiresIn:{isValid:function(e){return f(e)||h(e)&&e},message:'"expiresIn" should be a number of seconds or string representing a timespan'},notBefore:{isValid:function(e){return f(e)||h(e)&&e},message:'"notBefore" should be a number of seconds or string representing a timespan'},audience:{isValid:function(e){return h(e)||Array.isArray(e)},message:'"audience" must be a string or array'},algorithm:{isValid:a.bind(null,l),message:'"algorithm" must be a valid string enum value'},header:{isValid:u,message:'"header" must be an object'},encoding:{isValid:h,message:'"encoding" must be a string'},issuer:{isValid:h,message:'"issuer" must be a string'},subject:{isValid:h,message:'"subject" must be a string'},jwtid:{isValid:h,message:'"jwtid" must be a string'},noTimestamp:{isValid:s,message:'"noTimestamp" must be a boolean'},keyid:{isValid:h,message:'"keyid" must be a string'},mutatePayload:{isValid:s,message:'"mutatePayload" must be a boolean'}},b={iat:{isValid:c,message:'"iat" should be a number of seconds'},exp:{isValid:c,message:'"exp" should be a number of seconds'},nbf:{isValid:c,message:'"nbf" should be a number of seconds'}};function y(e,t,r,n){if(!u(r))throw new Error('Expected "'+n+'" to be a plain object.');Object.keys(r).forEach(function(i){var o=e[i];if(o){if(!o.isValid(r[i]))throw new Error(o.message)}else if(!t)throw new Error('"'+i+'" is not allowed in "'+n+'"')})}var m={audience:"aud",issuer:"iss",subject:"sub",jwtid:"jti"},v=["expiresIn","notBefore","noTimestamp","audience","issuer","subject","jwtid"];t.exports=function(e,t,i,a){"function"==typeof i?(a=i,i={}):i=i||{};var s="object"==typeof e&&!r.isBuffer(e),f=Object.assign({alg:i.algorithm||"HS256",typ:s?"JWT":void 0,kid:i.keyid},i.header);function c(e){if(a)return a(e);throw e}if(!t&&"none"!==i.algorithm)return c(new Error("secretOrPrivateKey must have a value"));if(void 0===e)return c(new Error("payload is required"));if(s){try{!function(e){y(b,!0,e,"payload")}(e)}catch(e){return c(e)}i.mutatePayload||(e=Object.assign({},e))}else{var u=v.filter(function(e){return void 0!==i[e]});if(u.length>0)return c(new Error("invalid "+u.join(",")+" option for "+typeof e+" payload"))}if(void 0!==e.exp&&void 0!==i.expiresIn)return c(new Error('Bad "options.expiresIn" option the payload already has an "exp" property.'));if(void 0!==e.nbf&&void 0!==i.notBefore)return c(new Error('Bad "options.notBefore" option the payload already has an "nbf" property.'));try{!function(e){y(p,!1,e,"options")}(i)}catch(e){return c(e)}var h=e.iat||Math.floor(Date.now()/1e3);if(i.noTimestamp?delete e.iat:s&&(e.iat=h),void 0!==i.notBefore){try{e.nbf=n(i.notBefore,h)}catch(e){return c(e)}if(void 0===e.nbf)return c(new Error('"notBefore" should be a number of seconds or string representing a timespan eg: "1d", "20h", 60'))}if(void 0!==i.expiresIn&&"object"==typeof e){try{e.exp=n(i.expiresIn,h)}catch(e){return c(e)}if(void 0===e.exp)return c(new Error('"expiresIn" should be a number of seconds or string representing a timespan eg: "1d", "20h", 60'))}Object.keys(m).forEach(function(t){var r=m[t];if(void 0!==i[t]){if(void 0!==e[r])return c(new Error('Bad "options.'+t+'" option. The payload already has an "'+r+'" property.'));e[r]=i[t]}});var l=i.encoding||"utf8";if("function"!=typeof a)return o.sign({header:f,payload:e,secret:t,encoding:l});a=a&&d(a),o.createSign({header:f,privateKey:t,payload:e,encoding:l}).once("error",a).once("done",function(e){a(null,e)})}}).call(this,{isBuffer:e("../../../node_modules/is-buffer/index.js")})},{"../../../node_modules/is-buffer/index.js":128,"./lib/psSupported":6,"./lib/timespan":7,jws:12,"lodash.includes":17,"lodash.isboolean":18,"lodash.isinteger":19,"lodash.isnumber":20,"lodash.isplainobject":21,"lodash.isstring":22,"lodash.once":23}],28:[function(e,t,r){var n=e("./lib/JsonWebTokenError"),i=e("./lib/NotBeforeError"),o=e("./lib/TokenExpiredError"),a=e("./decode"),s=e("./lib/timespan"),f=e("./lib/psSupported"),c=e("jws"),u=["RS256","RS384","RS512","ES256","ES384","ES512"],h=["RS256","RS384","RS512"],d=["HS256","HS384","HS512"];f&&(u.splice(3,0,"PS256","PS384","PS512"),h.splice(3,0,"PS256","PS384","PS512")),t.exports=function(e,t,r,f){var l;if("function"!=typeof r||f||(f=r,r={}),r||(r={}),r=Object.assign({},r),l=f||function(e,t){if(e)throw e;return t},r.clockTimestamp&&"number"!=typeof r.clockTimestamp)return l(new n("clockTimestamp must be a number"));if(void 0!==r.nonce&&("string"!=typeof r.nonce||""===r.nonce.trim()))return l(new n("nonce must be a non-empty string"));var p=r.clockTimestamp||Math.floor(Date.now()/1e3);if(!e)return l(new n("jwt must be provided"));if("string"!=typeof e)return l(new n("jwt must be a string"));var b,y=e.split(".");if(3!==y.length)return l(new n("jwt malformed"));try{b=a(e,{complete:!0})}catch(e){return l(e)}if(!b)return l(new n("invalid token"));var m,v=b.header;if("function"==typeof t){if(!f)return l(new n("verify must be called asynchronous if secret or public key is provided as a callback"));m=t}else m=function(e,r){return r(null,t)};return m(v,function(t,a){if(t)return l(new n("error in secret or public key callback: "+t.message));var f,m=""!==y[2].trim();if(!m&&a)return l(new n("jwt signature is required"));if(m&&!a)return l(new n("secret or public key must be provided"));if(m||r.algorithms||(r.algorithms=["none"]),r.algorithms||(r.algorithms=~a.toString().indexOf("BEGIN CERTIFICATE")||~a.toString().indexOf("BEGIN PUBLIC KEY")?u:~a.toString().indexOf("BEGIN RSA PUBLIC KEY")?h:d),!~r.algorithms.indexOf(b.header.alg))return l(new n("invalid algorithm"));try{f=c.verify(e,b.header.alg,a)}catch(e){return l(e)}if(!f)return l(new n("invalid signature"));var g=b.payload;if(void 0!==g.nbf&&!r.ignoreNotBefore){if("number"!=typeof g.nbf)return l(new n("invalid nbf value"));if(g.nbf>p+(r.clockTolerance||0))return l(new i("jwt not active",new Date(1e3*g.nbf)))}if(void 0!==g.exp&&!r.ignoreExpiration){if("number"!=typeof g.exp)return l(new n("invalid exp value"));if(p>=g.exp+(r.clockTolerance||0))return l(new o("jwt expired",new Date(1e3*g.exp)))}if(r.audience){var w=Array.isArray(r.audience)?r.audience:[r.audience];if(!(Array.isArray(g.aud)?g.aud:[g.aud]).some(function(e){return w.some(function(t){return t instanceof RegExp?t.test(e):t===e})}))return l(new n("jwt audience invalid. expected: "+w.join(" or ")))}if(r.issuer&&("string"==typeof r.issuer&&g.iss!==r.issuer||Array.isArray(r.issuer)&&-1===r.issuer.indexOf(g.iss)))return l(new n("jwt issuer invalid. expected: "+r.issuer));if(r.subject&&g.sub!==r.subject)return l(new n("jwt subject invalid. expected: "+r.subject));if(r.jwtid&&g.jti!==r.jwtid)return l(new n("jwt jwtid invalid. expected: "+r.jwtid));if(r.nonce&&g.nonce!==r.nonce)return l(new n("jwt nonce invalid. expected: "+r.nonce));if(r.maxAge){if("number"!=typeof g.iat)return l(new n("iat required when maxAge is specified"));var _=s(r.maxAge,g.iat);if(void 0===_)return l(new n('"maxAge" should be a number of seconds or string representing a timespan eg: "1d", "20h", 60'));if(p>=_+(r.clockTolerance||0))return l(new o("maxAge exceeded",new Date(1e3*_)))}if(!0===r.complete){var S=b.signature;return l(null,{header:v,payload:g,signature:S})}return l(null,g)})}},{"./decode":1,"./lib/JsonWebTokenError":3,"./lib/NotBeforeError":4,"./lib/TokenExpiredError":5,"./lib/psSupported":6,"./lib/timespan":7,jws:12}],29:[function(e,t,r){var n=r;n.bignum=e("bn.js"),n.define=e("./asn1/api").define,n.base=e("./asn1/base"),n.constants=e("./asn1/constants"),n.decoders=e("./asn1/decoders"),n.encoders=e("./asn1/encoders")},{"./asn1/api":30,"./asn1/base":32,"./asn1/constants":36,"./asn1/decoders":38,"./asn1/encoders":41,"bn.js":44}],30:[function(e,t,r){var n=e("../asn1"),i=e("inherits");function o(e,t){this.name=e,this.body=t,this.decoders={},this.encoders={}}r.define=function(e,t){return new o(e,t)},o.prototype._createNamed=function(t){var r;try{r=e("vm").runInThisContext("(function "+this.name+"(entity) {\n this._initNamed(entity);\n})")}catch(e){r=function(e){this._initNamed(e)}}return i(r,t),r.prototype._initNamed=function(e){t.call(this,e)},new r(this)},o.prototype._getDecoder=function(e){return e=e||"der",this.decoders.hasOwnProperty(e)||(this.decoders[e]=this._createNamed(n.decoders[e])),this.decoders[e]},o.prototype.decode=function(e,t,r){return this._getDecoder(t).decode(e,r)},o.prototype._getEncoder=function(e){return e=e||"der",this.encoders.hasOwnProperty(e)||(this.encoders[e]=this._createNamed(n.encoders[e])),this.encoders[e]},o.prototype.encode=function(e,t,r){return this._getEncoder(t).encode(e,r)}},{"../asn1":29,inherits:127,vm:186}],31:[function(e,t,r){var n=e("inherits"),i=e("../base").Reporter,o=e("buffer").Buffer;function a(e,t){i.call(this,t),o.isBuffer(e)?(this.base=e,this.offset=0,this.length=e.length):this.error("Input not Buffer")}function s(e,t){if(Array.isArray(e))this.length=0,this.value=e.map(function(e){return e instanceof s||(e=new s(e,t)),this.length+=e.length,e},this);else if("number"==typeof e){if(!(0<=e&&e<=255))return t.error("non-byte EncoderBuffer value");this.value=e,this.length=1}else if("string"==typeof e)this.value=e,this.length=o.byteLength(e);else{if(!o.isBuffer(e))return t.error("Unsupported type: "+typeof e);this.value=e,this.length=e.length}}n(a,i),r.DecoderBuffer=a,a.prototype.save=function(){return{offset:this.offset,reporter:i.prototype.save.call(this)}},a.prototype.restore=function(e){var t=new a(this.base);return t.offset=e.offset,t.length=this.offset,this.offset=e.offset,i.prototype.restore.call(this,e.reporter),t},a.prototype.isEmpty=function(){return this.offset===this.length},a.prototype.readUInt8=function(e){return this.offset+1<=this.length?this.base.readUInt8(this.offset++,!0):this.error(e||"DecoderBuffer overrun")},a.prototype.skip=function(e,t){if(!(this.offset+e<=this.length))return this.error(t||"DecoderBuffer overrun");var r=new a(this.base);return r._reporterState=this._reporterState,r.offset=this.offset,r.length=this.offset+e,this.offset+=e,r},a.prototype.raw=function(e){return this.base.slice(e?e.offset:this.offset,this.length)},r.EncoderBuffer=s,s.prototype.join=function(e,t){return e||(e=new o(this.length)),t||(t=0),0===this.length?e:(Array.isArray(this.value)?this.value.forEach(function(r){r.join(e,t),t+=r.length}):("number"==typeof this.value?e[t]=this.value:"string"==typeof this.value?e.write(this.value,t):o.isBuffer(this.value)&&this.value.copy(e,t),t+=this.length),e)}},{"../base":32,buffer:75,inherits:127}],32:[function(e,t,r){var n=r;n.Reporter=e("./reporter").Reporter,n.DecoderBuffer=e("./buffer").DecoderBuffer,n.EncoderBuffer=e("./buffer").EncoderBuffer,n.Node=e("./node")},{"./buffer":31,"./node":33,"./reporter":34}],33:[function(e,t,r){var n=e("../base").Reporter,i=e("../base").EncoderBuffer,o=e("../base").DecoderBuffer,a=e("minimalistic-assert"),s=["seq","seqof","set","setof","objid","bool","gentime","utctime","null_","enum","int","objDesc","bitstr","bmpstr","charstr","genstr","graphstr","ia5str","iso646str","numstr","octstr","printstr","t61str","unistr","utf8str","videostr"],f=["key","obj","use","optional","explicit","implicit","def","choice","any","contains"].concat(s);function c(e,t){var r={};this._baseState=r,r.enc=e,r.parent=t||null,r.children=null,r.tag=null,r.args=null,r.reverseArgs=null,r.choice=null,r.optional=!1,r.any=!1,r.obj=!1,r.use=null,r.useDecoder=null,r.key=null,r.default=null,r.explicit=null,r.implicit=null,r.contains=null,r.parent||(r.children=[],this._wrap())}t.exports=c;var u=["enc","parent","children","tag","args","reverseArgs","choice","optional","any","obj","use","alteredUse","key","default","explicit","implicit","contains"];c.prototype.clone=function(){var e=this._baseState,t={};u.forEach(function(r){t[r]=e[r]});var r=new this.constructor(t.parent);return r._baseState=t,r},c.prototype._wrap=function(){var e=this._baseState;f.forEach(function(t){this[t]=function(){var r=new this.constructor(this);return e.children.push(r),r[t].apply(r,arguments)}},this)},c.prototype._init=function(e){var t=this._baseState;a(null===t.parent),e.call(this),t.children=t.children.filter(function(e){return e._baseState.parent===this},this),a.equal(t.children.length,1,"Root node can have only one child")},c.prototype._useArgs=function(e){var t=this._baseState,r=e.filter(function(e){return e instanceof this.constructor},this);e=e.filter(function(e){return!(e instanceof this.constructor)},this),0!==r.length&&(a(null===t.children),t.children=r,r.forEach(function(e){e._baseState.parent=this},this)),0!==e.length&&(a(null===t.args),t.args=e,t.reverseArgs=e.map(function(e){if("object"!=typeof e||e.constructor!==Object)return e;var t={};return Object.keys(e).forEach(function(r){r==(0|r)&&(r|=0);var n=e[r];t[n]=r}),t}))},["_peekTag","_decodeTag","_use","_decodeStr","_decodeObjid","_decodeTime","_decodeNull","_decodeInt","_decodeBool","_decodeList","_encodeComposite","_encodeStr","_encodeObjid","_encodeTime","_encodeNull","_encodeInt","_encodeBool"].forEach(function(e){c.prototype[e]=function(){var t=this._baseState;throw new Error(e+" not implemented for encoding: "+t.enc)}}),s.forEach(function(e){c.prototype[e]=function(){var t=this._baseState,r=Array.prototype.slice.call(arguments);return a(null===t.tag),t.tag=e,this._useArgs(r),this}}),c.prototype.use=function(e){a(e);var t=this._baseState;return a(null===t.use),t.use=e,this},c.prototype.optional=function(){return this._baseState.optional=!0,this},c.prototype.def=function(e){var t=this._baseState;return a(null===t.default),t.default=e,t.optional=!0,this},c.prototype.explicit=function(e){var t=this._baseState;return a(null===t.explicit&&null===t.implicit),t.explicit=e,this},c.prototype.implicit=function(e){var t=this._baseState;return a(null===t.explicit&&null===t.implicit),t.implicit=e,this},c.prototype.obj=function(){var e=this._baseState,t=Array.prototype.slice.call(arguments);return e.obj=!0,0!==t.length&&this._useArgs(t),this},c.prototype.key=function(e){var t=this._baseState;return a(null===t.key),t.key=e,this},c.prototype.any=function(){return this._baseState.any=!0,this},c.prototype.choice=function(e){var t=this._baseState;return a(null===t.choice),t.choice=e,this._useArgs(Object.keys(e).map(function(t){return e[t]})),this},c.prototype.contains=function(e){var t=this._baseState;return a(null===t.use),t.contains=e,this},c.prototype._decode=function(e,t){var r=this._baseState;if(null===r.parent)return e.wrapResult(r.children[0]._decode(e,t));var n,i=r.default,a=!0,s=null;if(null!==r.key&&(s=e.enterKey(r.key)),r.optional){var f=null;if(null!==r.explicit?f=r.explicit:null!==r.implicit?f=r.implicit:null!==r.tag&&(f=r.tag),null!==f||r.any){if(a=this._peekTag(e,f,r.any),e.isError(a))return a}else{var c=e.save();try{null===r.choice?this._decodeGeneric(r.tag,e,t):this._decodeChoice(e,t),a=!0}catch(e){a=!1}e.restore(c)}}if(r.obj&&a&&(n=e.enterObject()),a){if(null!==r.explicit){var u=this._decodeTag(e,r.explicit);if(e.isError(u))return u;e=u}var h=e.offset;if(null===r.use&&null===r.choice){if(r.any)c=e.save();var d=this._decodeTag(e,null!==r.implicit?r.implicit:r.tag,r.any);if(e.isError(d))return d;r.any?i=e.raw(c):e=d}if(t&&t.track&&null!==r.tag&&t.track(e.path(),h,e.length,"tagged"),t&&t.track&&null!==r.tag&&t.track(e.path(),e.offset,e.length,"content"),i=r.any?i:null===r.choice?this._decodeGeneric(r.tag,e,t):this._decodeChoice(e,t),e.isError(i))return i;if(r.any||null!==r.choice||null===r.children||r.children.forEach(function(r){r._decode(e,t)}),r.contains&&("octstr"===r.tag||"bitstr"===r.tag)){var l=new o(i);i=this._getUse(r.contains,e._reporterState.obj)._decode(l,t)}}return r.obj&&a&&(i=e.leaveObject(n)),null===r.key||null===i&&!0!==a?null!==s&&e.exitKey(s):e.leaveKey(s,r.key,i),i},c.prototype._decodeGeneric=function(e,t,r){var n=this._baseState;return"seq"===e||"set"===e?null:"seqof"===e||"setof"===e?this._decodeList(t,e,n.args[0],r):/str$/.test(e)?this._decodeStr(t,e,r):"objid"===e&&n.args?this._decodeObjid(t,n.args[0],n.args[1],r):"objid"===e?this._decodeObjid(t,null,null,r):"gentime"===e||"utctime"===e?this._decodeTime(t,e,r):"null_"===e?this._decodeNull(t,r):"bool"===e?this._decodeBool(t,r):"objDesc"===e?this._decodeStr(t,e,r):"int"===e||"enum"===e?this._decodeInt(t,n.args&&n.args[0],r):null!==n.use?this._getUse(n.use,t._reporterState.obj)._decode(t,r):t.error("unknown tag: "+e)},c.prototype._getUse=function(e,t){var r=this._baseState;return r.useDecoder=this._use(e,t),a(null===r.useDecoder._baseState.parent),r.useDecoder=r.useDecoder._baseState.children[0],r.implicit!==r.useDecoder._baseState.implicit&&(r.useDecoder=r.useDecoder.clone(),r.useDecoder._baseState.implicit=r.implicit),r.useDecoder},c.prototype._decodeChoice=function(e,t){var r=this._baseState,n=null,i=!1;return Object.keys(r.choice).some(function(o){var a=e.save(),s=r.choice[o];try{var f=s._decode(e,t);if(e.isError(f))return!1;n={type:o,value:f},i=!0}catch(t){return e.restore(a),!1}return!0},this),i?n:e.error("Choice not matched")},c.prototype._createEncoderBuffer=function(e){return new i(e,this.reporter)},c.prototype._encode=function(e,t,r){var n=this._baseState;if(null===n.default||n.default!==e){var i=this._encodeValue(e,t,r);if(void 0!==i&&!this._skipDefault(i,t,r))return i}},c.prototype._encodeValue=function(e,t,r){var i=this._baseState;if(null===i.parent)return i.children[0]._encode(e,t||new n);var o=null;if(this.reporter=t,i.optional&&void 0===e){if(null===i.default)return;e=i.default}var a=null,s=!1;if(i.any)o=this._createEncoderBuffer(e);else if(i.choice)o=this._encodeChoice(e,t);else if(i.contains)a=this._getUse(i.contains,r)._encode(e,t),s=!0;else if(i.children)a=i.children.map(function(r){if("null_"===r._baseState.tag)return r._encode(null,t,e);if(null===r._baseState.key)return t.error("Child should have a key");var n=t.enterKey(r._baseState.key);if("object"!=typeof e)return t.error("Child expected, but input is not object");var i=r._encode(e[r._baseState.key],t,e);return t.leaveKey(n),i},this).filter(function(e){return e}),a=this._createEncoderBuffer(a);else if("seqof"===i.tag||"setof"===i.tag){if(!i.args||1!==i.args.length)return t.error("Too many args for : "+i.tag);if(!Array.isArray(e))return t.error("seqof/setof, but data is not Array");var f=this.clone();f._baseState.implicit=null,a=this._createEncoderBuffer(e.map(function(r){var n=this._baseState;return this._getUse(n.args[0],e)._encode(r,t)},f))}else null!==i.use?o=this._getUse(i.use,r)._encode(e,t):(a=this._encodePrimitive(i.tag,e),s=!0);if(!i.any&&null===i.choice){var c=null!==i.implicit?i.implicit:i.tag,u=null===i.implicit?"universal":"context";null===c?null===i.use&&t.error("Tag could be omitted only for .use()"):null===i.use&&(o=this._encodeComposite(c,s,u,a))}return null!==i.explicit&&(o=this._encodeComposite(i.explicit,!1,"context",o)),o},c.prototype._encodeChoice=function(e,t){var r=this._baseState,n=r.choice[e.type];return n||a(!1,e.type+" not found in "+JSON.stringify(Object.keys(r.choice))),n._encode(e.value,t)},c.prototype._encodePrimitive=function(e,t){var r=this._baseState;if(/str$/.test(e))return this._encodeStr(t,e);if("objid"===e&&r.args)return this._encodeObjid(t,r.reverseArgs[0],r.args[1]);if("objid"===e)return this._encodeObjid(t,null,null);if("gentime"===e||"utctime"===e)return this._encodeTime(t,e);if("null_"===e)return this._encodeNull();if("int"===e||"enum"===e)return this._encodeInt(t,r.args&&r.reverseArgs[0]);if("bool"===e)return this._encodeBool(t);if("objDesc"===e)return this._encodeStr(t,e);throw new Error("Unsupported tag: "+e)},c.prototype._isNumstr=function(e){return/^[0-9 ]*$/.test(e)},c.prototype._isPrintstr=function(e){return/^[A-Za-z0-9 '\(\)\+,\-\.\/:=\?]*$/.test(e)}},{"../base":32,"minimalistic-assert":132}],34:[function(e,t,r){var n=e("inherits");function i(e){this._reporterState={obj:null,path:[],options:e||{},errors:[]}}function o(e,t){this.path=e,this.rethrow(t)}r.Reporter=i,i.prototype.isError=function(e){return e instanceof o},i.prototype.save=function(){var e=this._reporterState;return{obj:e.obj,pathLen:e.path.length}},i.prototype.restore=function(e){var t=this._reporterState;t.obj=e.obj,t.path=t.path.slice(0,e.pathLen)},i.prototype.enterKey=function(e){return this._reporterState.path.push(e)},i.prototype.exitKey=function(e){var t=this._reporterState;t.path=t.path.slice(0,e-1)},i.prototype.leaveKey=function(e,t,r){var n=this._reporterState;this.exitKey(e),null!==n.obj&&(n.obj[t]=r)},i.prototype.path=function(){return this._reporterState.path.join("/")},i.prototype.enterObject=function(){var e=this._reporterState,t=e.obj;return e.obj={},t},i.prototype.leaveObject=function(e){var t=this._reporterState,r=t.obj;return t.obj=e,r},i.prototype.error=function(e){var t,r=this._reporterState,n=e instanceof o;if(t=n?e:new o(r.path.map(function(e){return"["+JSON.stringify(e)+"]"}).join(""),e.message||e,e.stack),!r.options.partial)throw t;return n||r.errors.push(t),t},i.prototype.wrapResult=function(e){var t=this._reporterState;return t.options.partial?{result:this.isError(e)?null:e,errors:t.errors}:e},n(o,Error),o.prototype.rethrow=function(e){if(this.message=e+" at: "+(this.path||"(shallow)"),Error.captureStackTrace&&Error.captureStackTrace(this,o),!this.stack)try{throw new Error(this.message)}catch(e){this.stack=e.stack}return this}},{inherits:127}],35:[function(e,t,r){var n=e("../constants");r.tagClass={0:"universal",1:"application",2:"context",3:"private"},r.tagClassByName=n._reverse(r.tagClass),r.tag={0:"end",1:"bool",2:"int",3:"bitstr",4:"octstr",5:"null_",6:"objid",7:"objDesc",8:"external",9:"real",10:"enum",11:"embed",12:"utf8str",13:"relativeOid",16:"seq",17:"set",18:"numstr",19:"printstr",20:"t61str",21:"videostr",22:"ia5str",23:"utctime",24:"gentime",25:"graphstr",26:"iso646str",27:"genstr",28:"unistr",29:"charstr",30:"bmpstr"},r.tagByName=n._reverse(r.tag)},{"../constants":36}],36:[function(e,t,r){var n=r;n._reverse=function(e){var t={};return Object.keys(e).forEach(function(r){(0|r)==r&&(r|=0);var n=e[r];t[n]=r}),t},n.der=e("./der")},{"./der":35}],37:[function(e,t,r){var n=e("inherits"),i=e("../../asn1"),o=i.base,a=i.bignum,s=i.constants.der;function f(e){this.enc="der",this.name=e.name,this.entity=e,this.tree=new c,this.tree._init(e.body)}function c(e){o.Node.call(this,"der",e)}function u(e,t){var r=e.readUInt8(t);if(e.isError(r))return r;var n=s.tagClass[r>>6],i=0==(32&r);if(31==(31&r)){var o=r;for(r=0;128==(128&o);){if(o=e.readUInt8(t),e.isError(o))return o;r<<=7,r|=127&o}}else r&=31;return{cls:n,primitive:i,tag:r,tagStr:s.tag[r]}}function h(e,t,r){var n=e.readUInt8(r);if(e.isError(n))return n;if(!t&&128===n)return null;if(0==(128&n))return n;var i=127&n;if(i>4)return e.error("length octect is too long");n=0;for(var o=0;o=31)return n.error("Multi-octet tag encoding unsupported");t||(i|=32);return i|=s.tagClassByName[r||"universal"]<<6}(e,t,r,this.reporter);if(n.length<128)return(o=new i(2))[0]=a,o[1]=n.length,this._createEncoderBuffer([o,n]);for(var f=1,c=n.length;c>=256;c>>=8)f++;(o=new i(2+f))[0]=a,o[1]=128|f;c=1+f;for(var u=n.length;u>0;c--,u>>=8)o[c]=255&u;return this._createEncoderBuffer([o,n])},c.prototype._encodeStr=function(e,t){if("bitstr"===t)return this._createEncoderBuffer([0|e.unused,e.data]);if("bmpstr"===t){for(var r=new i(2*e.length),n=0;n=40)return this.reporter.error("Second objid identifier OOB");e.splice(0,2,40*e[0]+e[1])}var o=0;for(n=0;n=128;a>>=7)o++}var s=new i(o),f=s.length-1;for(n=e.length-1;n>=0;n--){a=e[n];for(s[f--]=127&a;(a>>=7)>0;)s[f--]=128|127&a}return this._createEncoderBuffer(s)},c.prototype._encodeTime=function(e,t){var r,n=new Date(e);return"gentime"===t?r=[u(n.getFullYear()),u(n.getUTCMonth()+1),u(n.getUTCDate()),u(n.getUTCHours()),u(n.getUTCMinutes()),u(n.getUTCSeconds()),"Z"].join(""):"utctime"===t?r=[u(n.getFullYear()%100),u(n.getUTCMonth()+1),u(n.getUTCDate()),u(n.getUTCHours()),u(n.getUTCMinutes()),u(n.getUTCSeconds()),"Z"].join(""):this.reporter.error("Encoding "+t+" time is not supported yet"),this._encodeStr(r,"octstr")},c.prototype._encodeNull=function(){return this._createEncoderBuffer("")},c.prototype._encodeInt=function(e,t){if("string"==typeof e){if(!t)return this.reporter.error("String int or enum given, but no values map");if(!t.hasOwnProperty(e))return this.reporter.error("Values map doesn't contain: "+JSON.stringify(e));e=t[e]}if("number"!=typeof e&&!i.isBuffer(e)){var r=e.toArray();!e.sign&&128&r[0]&&r.unshift(0),e=new i(r)}if(i.isBuffer(e)){var n=e.length;0===e.length&&n++;var o=new i(n);return e.copy(o),0===e.length&&(o[0]=0),this._createEncoderBuffer(o)}if(e<128)return this._createEncoderBuffer(e);if(e<256)return this._createEncoderBuffer([0,e]);n=1;for(var a=e;a>=256;a>>=8)n++;for(a=(o=new Array(n)).length-1;a>=0;a--)o[a]=255&e,e>>=8;return 128&o[0]&&o.unshift(0),this._createEncoderBuffer(new i(o))},c.prototype._encodeBool=function(e){return this._createEncoderBuffer(e?255:0)},c.prototype._use=function(e,t){return"function"==typeof e&&(e=e(t)),e._getEncoder("der").tree},c.prototype._skipDefault=function(e,t,r){var n,i=this._baseState;if(null===i.default)return!1;var o=e.join();if(void 0===i.defaultBuffer&&(i.defaultBuffer=this._encodeValue(i.default,t,r).join()),o.length!==i.defaultBuffer.length)return!1;for(n=0;n0?a-4:a;for(r=0;r>16&255,f[u++]=t>>8&255,f[u++]=255&t;2===s&&(t=i[e.charCodeAt(r)]<<2|i[e.charCodeAt(r+1)]>>4,f[u++]=255&t);1===s&&(t=i[e.charCodeAt(r)]<<10|i[e.charCodeAt(r+1)]<<4|i[e.charCodeAt(r+2)]>>2,f[u++]=t>>8&255,f[u++]=255&t);return f},r.fromByteArray=function(e){for(var t,r=e.length,i=r%3,o=[],a=0,s=r-i;as?s:a+16383));1===i?(t=e[r-1],o.push(n[t>>2]+n[t<<4&63]+"==")):2===i&&(t=(e[r-2]<<8)+e[r-1],o.push(n[t>>10]+n[t>>4&63]+n[t<<2&63]+"="));return o.join("")};for(var n=[],i=[],o="undefined"!=typeof Uint8Array?Uint8Array:Array,a="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",s=0,f=a.length;s0)throw new Error("Invalid string. Length must be a multiple of 4");var r=e.indexOf("=");return-1===r&&(r=t),[r,r===t?0:4-r%4]}function u(e,t,r){for(var i,o,a=[],s=t;s>18&63]+n[o>>12&63]+n[o>>6&63]+n[63&o]);return a.join("")}i["-".charCodeAt(0)]=62,i["_".charCodeAt(0)]=63},{}],44:[function(e,t,r){!function(t,r){"use strict";function n(e,t){if(!e)throw new Error(t||"Assertion failed")}function i(e,t){e.super_=t;var r=function(){};r.prototype=t.prototype,e.prototype=new r,e.prototype.constructor=e}function o(e,t,r){if(o.isBN(e))return e;this.negative=0,this.words=null,this.length=0,this.red=null,null!==e&&("le"!==t&&"be"!==t||(r=t,t=10),this._init(e||0,t||10,r||"be"))}var a;"object"==typeof t?t.exports=o:r.BN=o,o.BN=o,o.wordSize=26;try{a=e("buffer").Buffer}catch(e){}function s(e,t,r){for(var n=0,i=Math.min(e.length,r),o=t;o=49&&a<=54?a-49+10:a>=17&&a<=22?a-17+10:15&a}return n}function f(e,t,r,n){for(var i=0,o=Math.min(e.length,r),a=t;a=49?s-49+10:s>=17?s-17+10:s}return i}o.isBN=function(e){return e instanceof o||null!==e&&"object"==typeof e&&e.constructor.wordSize===o.wordSize&&Array.isArray(e.words)},o.max=function(e,t){return e.cmp(t)>0?e:t},o.min=function(e,t){return e.cmp(t)<0?e:t},o.prototype._init=function(e,t,r){if("number"==typeof e)return this._initNumber(e,t,r);if("object"==typeof e)return this._initArray(e,t,r);"hex"===t&&(t=16),n(t===(0|t)&&t>=2&&t<=36);var i=0;"-"===(e=e.toString().replace(/\s+/g,""))[0]&&i++,16===t?this._parseHex(e,i):this._parseBase(e,t,i),"-"===e[0]&&(this.negative=1),this.strip(),"le"===r&&this._initArray(this.toArray(),t,r)},o.prototype._initNumber=function(e,t,r){e<0&&(this.negative=1,e=-e),e<67108864?(this.words=[67108863&e],this.length=1):e<4503599627370496?(this.words=[67108863&e,e/67108864&67108863],this.length=2):(n(e<9007199254740992),this.words=[67108863&e,e/67108864&67108863,1],this.length=3),"le"===r&&this._initArray(this.toArray(),t,r)},o.prototype._initArray=function(e,t,r){if(n("number"==typeof e.length),e.length<=0)return this.words=[0],this.length=1,this;this.length=Math.ceil(e.length/3),this.words=new Array(this.length);for(var i=0;i=0;i-=3)a=e[i]|e[i-1]<<8|e[i-2]<<16,this.words[o]|=a<>>26-s&67108863,(s+=24)>=26&&(s-=26,o++);else if("le"===r)for(i=0,o=0;i>>26-s&67108863,(s+=24)>=26&&(s-=26,o++);return this.strip()},o.prototype._parseHex=function(e,t){this.length=Math.ceil((e.length-t)/6),this.words=new Array(this.length);for(var r=0;r=t;r-=6)i=s(e,r,r+6),this.words[n]|=i<>>26-o&4194303,(o+=24)>=26&&(o-=26,n++);r+6!==t&&(i=s(e,t,r+6),this.words[n]|=i<>>26-o&4194303),this.strip()},o.prototype._parseBase=function(e,t,r){this.words=[0],this.length=1;for(var n=0,i=1;i<=67108863;i*=t)n++;n--,i=i/t|0;for(var o=e.length-r,a=o%n,s=Math.min(o,o-a)+r,c=0,u=r;u1&&0===this.words[this.length-1];)this.length--;return this._normSign()},o.prototype._normSign=function(){return 1===this.length&&0===this.words[0]&&(this.negative=0),this},o.prototype.inspect=function(){return(this.red?""};var c=["","0","00","000","0000","00000","000000","0000000","00000000","000000000","0000000000","00000000000","000000000000","0000000000000","00000000000000","000000000000000","0000000000000000","00000000000000000","000000000000000000","0000000000000000000","00000000000000000000","000000000000000000000","0000000000000000000000","00000000000000000000000","000000000000000000000000","0000000000000000000000000"],u=[0,0,25,16,12,11,10,9,8,8,7,7,7,7,6,6,6,6,6,6,6,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5],h=[0,0,33554432,43046721,16777216,48828125,60466176,40353607,16777216,43046721,1e7,19487171,35831808,62748517,7529536,11390625,16777216,24137569,34012224,47045881,64e6,4084101,5153632,6436343,7962624,9765625,11881376,14348907,17210368,20511149,243e5,28629151,33554432,39135393,45435424,52521875,60466176];function d(e,t,r){r.negative=t.negative^e.negative;var n=e.length+t.length|0;r.length=n,n=n-1|0;var i=0|e.words[0],o=0|t.words[0],a=i*o,s=67108863&a,f=a/67108864|0;r.words[0]=s;for(var c=1;c>>26,h=67108863&f,d=Math.min(c,t.length-1),l=Math.max(0,c-e.length+1);l<=d;l++){var p=c-l|0;u+=(a=(i=0|e.words[p])*(o=0|t.words[l])+h)/67108864|0,h=67108863&a}r.words[c]=0|h,f=0|u}return 0!==f?r.words[c]=0|f:r.length--,r.strip()}o.prototype.toString=function(e,t){var r;if(t=0|t||1,16===(e=e||10)||"hex"===e){r="";for(var i=0,o=0,a=0;a>>24-i&16777215)||a!==this.length-1?c[6-f.length]+f+r:f+r,(i+=2)>=26&&(i-=26,a--)}for(0!==o&&(r=o.toString(16)+r);r.length%t!=0;)r="0"+r;return 0!==this.negative&&(r="-"+r),r}if(e===(0|e)&&e>=2&&e<=36){var d=u[e],l=h[e];r="";var p=this.clone();for(p.negative=0;!p.isZero();){var b=p.modn(l).toString(e);r=(p=p.idivn(l)).isZero()?b+r:c[d-b.length]+b+r}for(this.isZero()&&(r="0"+r);r.length%t!=0;)r="0"+r;return 0!==this.negative&&(r="-"+r),r}n(!1,"Base should be between 2 and 36")},o.prototype.toNumber=function(){var e=this.words[0];return 2===this.length?e+=67108864*this.words[1]:3===this.length&&1===this.words[2]?e+=4503599627370496+67108864*this.words[1]:this.length>2&&n(!1,"Number can only safely store up to 53 bits"),0!==this.negative?-e:e},o.prototype.toJSON=function(){return this.toString(16)},o.prototype.toBuffer=function(e,t){return n(void 0!==a),this.toArrayLike(a,e,t)},o.prototype.toArray=function(e,t){return this.toArrayLike(Array,e,t)},o.prototype.toArrayLike=function(e,t,r){var i=this.byteLength(),o=r||Math.max(1,i);n(i<=o,"byte array longer than desired length"),n(o>0,"Requested array length <= 0"),this.strip();var a,s,f="le"===t,c=new e(o),u=this.clone();if(f){for(s=0;!u.isZero();s++)a=u.andln(255),u.iushrn(8),c[s]=a;for(;s=4096&&(r+=13,t>>>=13),t>=64&&(r+=7,t>>>=7),t>=8&&(r+=4,t>>>=4),t>=2&&(r+=2,t>>>=2),r+t},o.prototype._zeroBits=function(e){if(0===e)return 26;var t=e,r=0;return 0==(8191&t)&&(r+=13,t>>>=13),0==(127&t)&&(r+=7,t>>>=7),0==(15&t)&&(r+=4,t>>>=4),0==(3&t)&&(r+=2,t>>>=2),0==(1&t)&&r++,r},o.prototype.bitLength=function(){var e=this.words[this.length-1],t=this._countBits(e);return 26*(this.length-1)+t},o.prototype.zeroBits=function(){if(this.isZero())return 0;for(var e=0,t=0;te.length?this.clone().ior(e):e.clone().ior(this)},o.prototype.uor=function(e){return this.length>e.length?this.clone().iuor(e):e.clone().iuor(this)},o.prototype.iuand=function(e){var t;t=this.length>e.length?e:this;for(var r=0;re.length?this.clone().iand(e):e.clone().iand(this)},o.prototype.uand=function(e){return this.length>e.length?this.clone().iuand(e):e.clone().iuand(this)},o.prototype.iuxor=function(e){var t,r;this.length>e.length?(t=this,r=e):(t=e,r=this);for(var n=0;ne.length?this.clone().ixor(e):e.clone().ixor(this)},o.prototype.uxor=function(e){return this.length>e.length?this.clone().iuxor(e):e.clone().iuxor(this)},o.prototype.inotn=function(e){n("number"==typeof e&&e>=0);var t=0|Math.ceil(e/26),r=e%26;this._expand(t),r>0&&t--;for(var i=0;i0&&(this.words[i]=~this.words[i]&67108863>>26-r),this.strip()},o.prototype.notn=function(e){return this.clone().inotn(e)},o.prototype.setn=function(e,t){n("number"==typeof e&&e>=0);var r=e/26|0,i=e%26;return this._expand(r+1),this.words[r]=t?this.words[r]|1<e.length?(r=this,n=e):(r=e,n=this);for(var i=0,o=0;o>>26;for(;0!==i&&o>>26;if(this.length=r.length,0!==i)this.words[this.length]=i,this.length++;else if(r!==this)for(;oe.length?this.clone().iadd(e):e.clone().iadd(this)},o.prototype.isub=function(e){if(0!==e.negative){e.negative=0;var t=this.iadd(e);return e.negative=1,t._normSign()}if(0!==this.negative)return this.negative=0,this.iadd(e),this.negative=1,this._normSign();var r,n,i=this.cmp(e);if(0===i)return this.negative=0,this.length=1,this.words[0]=0,this;i>0?(r=this,n=e):(r=e,n=this);for(var o=0,a=0;a>26,this.words[a]=67108863&t;for(;0!==o&&a>26,this.words[a]=67108863&t;if(0===o&&a>>13,l=0|a[1],p=8191&l,b=l>>>13,y=0|a[2],m=8191&y,v=y>>>13,g=0|a[3],w=8191&g,_=g>>>13,S=0|a[4],E=8191&S,M=S>>>13,k=0|a[5],x=8191&k,A=k>>>13,j=0|a[6],B=8191&j,I=j>>>13,R=0|a[7],T=8191&R,C=R>>>13,P=0|a[8],O=8191&P,D=P>>>13,N=0|a[9],L=8191&N,U=N>>>13,q=0|s[0],z=8191&q,K=q>>>13,F=0|s[1],H=8191&F,V=F>>>13,W=0|s[2],J=8191&W,X=W>>>13,$=0|s[3],G=8191&$,Z=$>>>13,Y=0|s[4],Q=8191&Y,ee=Y>>>13,te=0|s[5],re=8191&te,ne=te>>>13,ie=0|s[6],oe=8191&ie,ae=ie>>>13,se=0|s[7],fe=8191&se,ce=se>>>13,ue=0|s[8],he=8191&ue,de=ue>>>13,le=0|s[9],pe=8191&le,be=le>>>13;r.negative=e.negative^t.negative,r.length=19;var ye=(c+(n=Math.imul(h,z))|0)+((8191&(i=(i=Math.imul(h,K))+Math.imul(d,z)|0))<<13)|0;c=((o=Math.imul(d,K))+(i>>>13)|0)+(ye>>>26)|0,ye&=67108863,n=Math.imul(p,z),i=(i=Math.imul(p,K))+Math.imul(b,z)|0,o=Math.imul(b,K);var me=(c+(n=n+Math.imul(h,H)|0)|0)+((8191&(i=(i=i+Math.imul(h,V)|0)+Math.imul(d,H)|0))<<13)|0;c=((o=o+Math.imul(d,V)|0)+(i>>>13)|0)+(me>>>26)|0,me&=67108863,n=Math.imul(m,z),i=(i=Math.imul(m,K))+Math.imul(v,z)|0,o=Math.imul(v,K),n=n+Math.imul(p,H)|0,i=(i=i+Math.imul(p,V)|0)+Math.imul(b,H)|0,o=o+Math.imul(b,V)|0;var ve=(c+(n=n+Math.imul(h,J)|0)|0)+((8191&(i=(i=i+Math.imul(h,X)|0)+Math.imul(d,J)|0))<<13)|0;c=((o=o+Math.imul(d,X)|0)+(i>>>13)|0)+(ve>>>26)|0,ve&=67108863,n=Math.imul(w,z),i=(i=Math.imul(w,K))+Math.imul(_,z)|0,o=Math.imul(_,K),n=n+Math.imul(m,H)|0,i=(i=i+Math.imul(m,V)|0)+Math.imul(v,H)|0,o=o+Math.imul(v,V)|0,n=n+Math.imul(p,J)|0,i=(i=i+Math.imul(p,X)|0)+Math.imul(b,J)|0,o=o+Math.imul(b,X)|0;var ge=(c+(n=n+Math.imul(h,G)|0)|0)+((8191&(i=(i=i+Math.imul(h,Z)|0)+Math.imul(d,G)|0))<<13)|0;c=((o=o+Math.imul(d,Z)|0)+(i>>>13)|0)+(ge>>>26)|0,ge&=67108863,n=Math.imul(E,z),i=(i=Math.imul(E,K))+Math.imul(M,z)|0,o=Math.imul(M,K),n=n+Math.imul(w,H)|0,i=(i=i+Math.imul(w,V)|0)+Math.imul(_,H)|0,o=o+Math.imul(_,V)|0,n=n+Math.imul(m,J)|0,i=(i=i+Math.imul(m,X)|0)+Math.imul(v,J)|0,o=o+Math.imul(v,X)|0,n=n+Math.imul(p,G)|0,i=(i=i+Math.imul(p,Z)|0)+Math.imul(b,G)|0,o=o+Math.imul(b,Z)|0;var we=(c+(n=n+Math.imul(h,Q)|0)|0)+((8191&(i=(i=i+Math.imul(h,ee)|0)+Math.imul(d,Q)|0))<<13)|0;c=((o=o+Math.imul(d,ee)|0)+(i>>>13)|0)+(we>>>26)|0,we&=67108863,n=Math.imul(x,z),i=(i=Math.imul(x,K))+Math.imul(A,z)|0,o=Math.imul(A,K),n=n+Math.imul(E,H)|0,i=(i=i+Math.imul(E,V)|0)+Math.imul(M,H)|0,o=o+Math.imul(M,V)|0,n=n+Math.imul(w,J)|0,i=(i=i+Math.imul(w,X)|0)+Math.imul(_,J)|0,o=o+Math.imul(_,X)|0,n=n+Math.imul(m,G)|0,i=(i=i+Math.imul(m,Z)|0)+Math.imul(v,G)|0,o=o+Math.imul(v,Z)|0,n=n+Math.imul(p,Q)|0,i=(i=i+Math.imul(p,ee)|0)+Math.imul(b,Q)|0,o=o+Math.imul(b,ee)|0;var _e=(c+(n=n+Math.imul(h,re)|0)|0)+((8191&(i=(i=i+Math.imul(h,ne)|0)+Math.imul(d,re)|0))<<13)|0;c=((o=o+Math.imul(d,ne)|0)+(i>>>13)|0)+(_e>>>26)|0,_e&=67108863,n=Math.imul(B,z),i=(i=Math.imul(B,K))+Math.imul(I,z)|0,o=Math.imul(I,K),n=n+Math.imul(x,H)|0,i=(i=i+Math.imul(x,V)|0)+Math.imul(A,H)|0,o=o+Math.imul(A,V)|0,n=n+Math.imul(E,J)|0,i=(i=i+Math.imul(E,X)|0)+Math.imul(M,J)|0,o=o+Math.imul(M,X)|0,n=n+Math.imul(w,G)|0,i=(i=i+Math.imul(w,Z)|0)+Math.imul(_,G)|0,o=o+Math.imul(_,Z)|0,n=n+Math.imul(m,Q)|0,i=(i=i+Math.imul(m,ee)|0)+Math.imul(v,Q)|0,o=o+Math.imul(v,ee)|0,n=n+Math.imul(p,re)|0,i=(i=i+Math.imul(p,ne)|0)+Math.imul(b,re)|0,o=o+Math.imul(b,ne)|0;var Se=(c+(n=n+Math.imul(h,oe)|0)|0)+((8191&(i=(i=i+Math.imul(h,ae)|0)+Math.imul(d,oe)|0))<<13)|0;c=((o=o+Math.imul(d,ae)|0)+(i>>>13)|0)+(Se>>>26)|0,Se&=67108863,n=Math.imul(T,z),i=(i=Math.imul(T,K))+Math.imul(C,z)|0,o=Math.imul(C,K),n=n+Math.imul(B,H)|0,i=(i=i+Math.imul(B,V)|0)+Math.imul(I,H)|0,o=o+Math.imul(I,V)|0,n=n+Math.imul(x,J)|0,i=(i=i+Math.imul(x,X)|0)+Math.imul(A,J)|0,o=o+Math.imul(A,X)|0,n=n+Math.imul(E,G)|0,i=(i=i+Math.imul(E,Z)|0)+Math.imul(M,G)|0,o=o+Math.imul(M,Z)|0,n=n+Math.imul(w,Q)|0,i=(i=i+Math.imul(w,ee)|0)+Math.imul(_,Q)|0,o=o+Math.imul(_,ee)|0,n=n+Math.imul(m,re)|0,i=(i=i+Math.imul(m,ne)|0)+Math.imul(v,re)|0,o=o+Math.imul(v,ne)|0,n=n+Math.imul(p,oe)|0,i=(i=i+Math.imul(p,ae)|0)+Math.imul(b,oe)|0,o=o+Math.imul(b,ae)|0;var Ee=(c+(n=n+Math.imul(h,fe)|0)|0)+((8191&(i=(i=i+Math.imul(h,ce)|0)+Math.imul(d,fe)|0))<<13)|0;c=((o=o+Math.imul(d,ce)|0)+(i>>>13)|0)+(Ee>>>26)|0,Ee&=67108863,n=Math.imul(O,z),i=(i=Math.imul(O,K))+Math.imul(D,z)|0,o=Math.imul(D,K),n=n+Math.imul(T,H)|0,i=(i=i+Math.imul(T,V)|0)+Math.imul(C,H)|0,o=o+Math.imul(C,V)|0,n=n+Math.imul(B,J)|0,i=(i=i+Math.imul(B,X)|0)+Math.imul(I,J)|0,o=o+Math.imul(I,X)|0,n=n+Math.imul(x,G)|0,i=(i=i+Math.imul(x,Z)|0)+Math.imul(A,G)|0,o=o+Math.imul(A,Z)|0,n=n+Math.imul(E,Q)|0,i=(i=i+Math.imul(E,ee)|0)+Math.imul(M,Q)|0,o=o+Math.imul(M,ee)|0,n=n+Math.imul(w,re)|0,i=(i=i+Math.imul(w,ne)|0)+Math.imul(_,re)|0,o=o+Math.imul(_,ne)|0,n=n+Math.imul(m,oe)|0,i=(i=i+Math.imul(m,ae)|0)+Math.imul(v,oe)|0,o=o+Math.imul(v,ae)|0,n=n+Math.imul(p,fe)|0,i=(i=i+Math.imul(p,ce)|0)+Math.imul(b,fe)|0,o=o+Math.imul(b,ce)|0;var Me=(c+(n=n+Math.imul(h,he)|0)|0)+((8191&(i=(i=i+Math.imul(h,de)|0)+Math.imul(d,he)|0))<<13)|0;c=((o=o+Math.imul(d,de)|0)+(i>>>13)|0)+(Me>>>26)|0,Me&=67108863,n=Math.imul(L,z),i=(i=Math.imul(L,K))+Math.imul(U,z)|0,o=Math.imul(U,K),n=n+Math.imul(O,H)|0,i=(i=i+Math.imul(O,V)|0)+Math.imul(D,H)|0,o=o+Math.imul(D,V)|0,n=n+Math.imul(T,J)|0,i=(i=i+Math.imul(T,X)|0)+Math.imul(C,J)|0,o=o+Math.imul(C,X)|0,n=n+Math.imul(B,G)|0,i=(i=i+Math.imul(B,Z)|0)+Math.imul(I,G)|0,o=o+Math.imul(I,Z)|0,n=n+Math.imul(x,Q)|0,i=(i=i+Math.imul(x,ee)|0)+Math.imul(A,Q)|0,o=o+Math.imul(A,ee)|0,n=n+Math.imul(E,re)|0,i=(i=i+Math.imul(E,ne)|0)+Math.imul(M,re)|0,o=o+Math.imul(M,ne)|0,n=n+Math.imul(w,oe)|0,i=(i=i+Math.imul(w,ae)|0)+Math.imul(_,oe)|0,o=o+Math.imul(_,ae)|0,n=n+Math.imul(m,fe)|0,i=(i=i+Math.imul(m,ce)|0)+Math.imul(v,fe)|0,o=o+Math.imul(v,ce)|0,n=n+Math.imul(p,he)|0,i=(i=i+Math.imul(p,de)|0)+Math.imul(b,he)|0,o=o+Math.imul(b,de)|0;var ke=(c+(n=n+Math.imul(h,pe)|0)|0)+((8191&(i=(i=i+Math.imul(h,be)|0)+Math.imul(d,pe)|0))<<13)|0;c=((o=o+Math.imul(d,be)|0)+(i>>>13)|0)+(ke>>>26)|0,ke&=67108863,n=Math.imul(L,H),i=(i=Math.imul(L,V))+Math.imul(U,H)|0,o=Math.imul(U,V),n=n+Math.imul(O,J)|0,i=(i=i+Math.imul(O,X)|0)+Math.imul(D,J)|0,o=o+Math.imul(D,X)|0,n=n+Math.imul(T,G)|0,i=(i=i+Math.imul(T,Z)|0)+Math.imul(C,G)|0,o=o+Math.imul(C,Z)|0,n=n+Math.imul(B,Q)|0,i=(i=i+Math.imul(B,ee)|0)+Math.imul(I,Q)|0,o=o+Math.imul(I,ee)|0,n=n+Math.imul(x,re)|0,i=(i=i+Math.imul(x,ne)|0)+Math.imul(A,re)|0,o=o+Math.imul(A,ne)|0,n=n+Math.imul(E,oe)|0,i=(i=i+Math.imul(E,ae)|0)+Math.imul(M,oe)|0,o=o+Math.imul(M,ae)|0,n=n+Math.imul(w,fe)|0,i=(i=i+Math.imul(w,ce)|0)+Math.imul(_,fe)|0,o=o+Math.imul(_,ce)|0,n=n+Math.imul(m,he)|0,i=(i=i+Math.imul(m,de)|0)+Math.imul(v,he)|0,o=o+Math.imul(v,de)|0;var xe=(c+(n=n+Math.imul(p,pe)|0)|0)+((8191&(i=(i=i+Math.imul(p,be)|0)+Math.imul(b,pe)|0))<<13)|0;c=((o=o+Math.imul(b,be)|0)+(i>>>13)|0)+(xe>>>26)|0,xe&=67108863,n=Math.imul(L,J),i=(i=Math.imul(L,X))+Math.imul(U,J)|0,o=Math.imul(U,X),n=n+Math.imul(O,G)|0,i=(i=i+Math.imul(O,Z)|0)+Math.imul(D,G)|0,o=o+Math.imul(D,Z)|0,n=n+Math.imul(T,Q)|0,i=(i=i+Math.imul(T,ee)|0)+Math.imul(C,Q)|0,o=o+Math.imul(C,ee)|0,n=n+Math.imul(B,re)|0,i=(i=i+Math.imul(B,ne)|0)+Math.imul(I,re)|0,o=o+Math.imul(I,ne)|0,n=n+Math.imul(x,oe)|0,i=(i=i+Math.imul(x,ae)|0)+Math.imul(A,oe)|0,o=o+Math.imul(A,ae)|0,n=n+Math.imul(E,fe)|0,i=(i=i+Math.imul(E,ce)|0)+Math.imul(M,fe)|0,o=o+Math.imul(M,ce)|0,n=n+Math.imul(w,he)|0,i=(i=i+Math.imul(w,de)|0)+Math.imul(_,he)|0,o=o+Math.imul(_,de)|0;var Ae=(c+(n=n+Math.imul(m,pe)|0)|0)+((8191&(i=(i=i+Math.imul(m,be)|0)+Math.imul(v,pe)|0))<<13)|0;c=((o=o+Math.imul(v,be)|0)+(i>>>13)|0)+(Ae>>>26)|0,Ae&=67108863,n=Math.imul(L,G),i=(i=Math.imul(L,Z))+Math.imul(U,G)|0,o=Math.imul(U,Z),n=n+Math.imul(O,Q)|0,i=(i=i+Math.imul(O,ee)|0)+Math.imul(D,Q)|0,o=o+Math.imul(D,ee)|0,n=n+Math.imul(T,re)|0,i=(i=i+Math.imul(T,ne)|0)+Math.imul(C,re)|0,o=o+Math.imul(C,ne)|0,n=n+Math.imul(B,oe)|0,i=(i=i+Math.imul(B,ae)|0)+Math.imul(I,oe)|0,o=o+Math.imul(I,ae)|0,n=n+Math.imul(x,fe)|0,i=(i=i+Math.imul(x,ce)|0)+Math.imul(A,fe)|0,o=o+Math.imul(A,ce)|0,n=n+Math.imul(E,he)|0,i=(i=i+Math.imul(E,de)|0)+Math.imul(M,he)|0,o=o+Math.imul(M,de)|0;var je=(c+(n=n+Math.imul(w,pe)|0)|0)+((8191&(i=(i=i+Math.imul(w,be)|0)+Math.imul(_,pe)|0))<<13)|0;c=((o=o+Math.imul(_,be)|0)+(i>>>13)|0)+(je>>>26)|0,je&=67108863,n=Math.imul(L,Q),i=(i=Math.imul(L,ee))+Math.imul(U,Q)|0,o=Math.imul(U,ee),n=n+Math.imul(O,re)|0,i=(i=i+Math.imul(O,ne)|0)+Math.imul(D,re)|0,o=o+Math.imul(D,ne)|0,n=n+Math.imul(T,oe)|0,i=(i=i+Math.imul(T,ae)|0)+Math.imul(C,oe)|0,o=o+Math.imul(C,ae)|0,n=n+Math.imul(B,fe)|0,i=(i=i+Math.imul(B,ce)|0)+Math.imul(I,fe)|0,o=o+Math.imul(I,ce)|0,n=n+Math.imul(x,he)|0,i=(i=i+Math.imul(x,de)|0)+Math.imul(A,he)|0,o=o+Math.imul(A,de)|0;var Be=(c+(n=n+Math.imul(E,pe)|0)|0)+((8191&(i=(i=i+Math.imul(E,be)|0)+Math.imul(M,pe)|0))<<13)|0;c=((o=o+Math.imul(M,be)|0)+(i>>>13)|0)+(Be>>>26)|0,Be&=67108863,n=Math.imul(L,re),i=(i=Math.imul(L,ne))+Math.imul(U,re)|0,o=Math.imul(U,ne),n=n+Math.imul(O,oe)|0,i=(i=i+Math.imul(O,ae)|0)+Math.imul(D,oe)|0,o=o+Math.imul(D,ae)|0,n=n+Math.imul(T,fe)|0,i=(i=i+Math.imul(T,ce)|0)+Math.imul(C,fe)|0,o=o+Math.imul(C,ce)|0,n=n+Math.imul(B,he)|0,i=(i=i+Math.imul(B,de)|0)+Math.imul(I,he)|0,o=o+Math.imul(I,de)|0;var Ie=(c+(n=n+Math.imul(x,pe)|0)|0)+((8191&(i=(i=i+Math.imul(x,be)|0)+Math.imul(A,pe)|0))<<13)|0;c=((o=o+Math.imul(A,be)|0)+(i>>>13)|0)+(Ie>>>26)|0,Ie&=67108863,n=Math.imul(L,oe),i=(i=Math.imul(L,ae))+Math.imul(U,oe)|0,o=Math.imul(U,ae),n=n+Math.imul(O,fe)|0,i=(i=i+Math.imul(O,ce)|0)+Math.imul(D,fe)|0,o=o+Math.imul(D,ce)|0,n=n+Math.imul(T,he)|0,i=(i=i+Math.imul(T,de)|0)+Math.imul(C,he)|0,o=o+Math.imul(C,de)|0;var Re=(c+(n=n+Math.imul(B,pe)|0)|0)+((8191&(i=(i=i+Math.imul(B,be)|0)+Math.imul(I,pe)|0))<<13)|0;c=((o=o+Math.imul(I,be)|0)+(i>>>13)|0)+(Re>>>26)|0,Re&=67108863,n=Math.imul(L,fe),i=(i=Math.imul(L,ce))+Math.imul(U,fe)|0,o=Math.imul(U,ce),n=n+Math.imul(O,he)|0,i=(i=i+Math.imul(O,de)|0)+Math.imul(D,he)|0,o=o+Math.imul(D,de)|0;var Te=(c+(n=n+Math.imul(T,pe)|0)|0)+((8191&(i=(i=i+Math.imul(T,be)|0)+Math.imul(C,pe)|0))<<13)|0;c=((o=o+Math.imul(C,be)|0)+(i>>>13)|0)+(Te>>>26)|0,Te&=67108863,n=Math.imul(L,he),i=(i=Math.imul(L,de))+Math.imul(U,he)|0,o=Math.imul(U,de);var Ce=(c+(n=n+Math.imul(O,pe)|0)|0)+((8191&(i=(i=i+Math.imul(O,be)|0)+Math.imul(D,pe)|0))<<13)|0;c=((o=o+Math.imul(D,be)|0)+(i>>>13)|0)+(Ce>>>26)|0,Ce&=67108863;var Pe=(c+(n=Math.imul(L,pe))|0)+((8191&(i=(i=Math.imul(L,be))+Math.imul(U,pe)|0))<<13)|0;return c=((o=Math.imul(U,be))+(i>>>13)|0)+(Pe>>>26)|0,Pe&=67108863,f[0]=ye,f[1]=me,f[2]=ve,f[3]=ge,f[4]=we,f[5]=_e,f[6]=Se,f[7]=Ee,f[8]=Me,f[9]=ke,f[10]=xe,f[11]=Ae,f[12]=je,f[13]=Be,f[14]=Ie,f[15]=Re,f[16]=Te,f[17]=Ce,f[18]=Pe,0!==c&&(f[19]=c,r.length++),r};function p(e,t,r){return(new b).mulp(e,t,r)}function b(e,t){this.x=e,this.y=t}Math.imul||(l=d),o.prototype.mulTo=function(e,t){var r=this.length+e.length;return 10===this.length&&10===e.length?l(this,e,t):r<63?d(this,e,t):r<1024?function(e,t,r){r.negative=t.negative^e.negative,r.length=e.length+t.length;for(var n=0,i=0,o=0;o>>26)|0)>>>26,a&=67108863}r.words[o]=s,n=a,a=i}return 0!==n?r.words[o]=n:r.length--,r.strip()}(this,e,t):p(this,e,t)},b.prototype.makeRBT=function(e){for(var t=new Array(e),r=o.prototype._countBits(e)-1,n=0;n>=1;return n},b.prototype.permute=function(e,t,r,n,i,o){for(var a=0;a>>=1)i++;return 1<>>=13,r[2*a+1]=8191&o,o>>>=13;for(a=2*t;a>=26,t+=i/67108864|0,t+=o>>>26,this.words[r]=67108863&o}return 0!==t&&(this.words[r]=t,this.length++),this},o.prototype.muln=function(e){return this.clone().imuln(e)},o.prototype.sqr=function(){return this.mul(this)},o.prototype.isqr=function(){return this.imul(this.clone())},o.prototype.pow=function(e){var t=function(e){for(var t=new Array(e.bitLength()),r=0;r>>i}return t}(e);if(0===t.length)return new o(1);for(var r=this,n=0;n=0);var t,r=e%26,i=(e-r)/26,o=67108863>>>26-r<<26-r;if(0!==r){var a=0;for(t=0;t>>26-r}a&&(this.words[t]=a,this.length++)}if(0!==i){for(t=this.length-1;t>=0;t--)this.words[t+i]=this.words[t];for(t=0;t=0),i=t?(t-t%26)/26:0;var o=e%26,a=Math.min((e-o)/26,this.length),s=67108863^67108863>>>o<a)for(this.length-=a,c=0;c=0&&(0!==u||c>=i);c--){var h=0|this.words[c];this.words[c]=u<<26-o|h>>>o,u=h&s}return f&&0!==u&&(f.words[f.length++]=u),0===this.length&&(this.words[0]=0,this.length=1),this.strip()},o.prototype.ishrn=function(e,t,r){return n(0===this.negative),this.iushrn(e,t,r)},o.prototype.shln=function(e){return this.clone().ishln(e)},o.prototype.ushln=function(e){return this.clone().iushln(e)},o.prototype.shrn=function(e){return this.clone().ishrn(e)},o.prototype.ushrn=function(e){return this.clone().iushrn(e)},o.prototype.testn=function(e){n("number"==typeof e&&e>=0);var t=e%26,r=(e-t)/26,i=1<=0);var t=e%26,r=(e-t)/26;if(n(0===this.negative,"imaskn works only with positive numbers"),this.length<=r)return this;if(0!==t&&r++,this.length=Math.min(r,this.length),0!==t){var i=67108863^67108863>>>t<=67108864;t++)this.words[t]-=67108864,t===this.length-1?this.words[t+1]=1:this.words[t+1]++;return this.length=Math.max(this.length,t+1),this},o.prototype.isubn=function(e){if(n("number"==typeof e),n(e<67108864),e<0)return this.iaddn(-e);if(0!==this.negative)return this.negative=0,this.iaddn(e),this.negative=1,this;if(this.words[0]-=e,1===this.length&&this.words[0]<0)this.words[0]=-this.words[0],this.negative=1;else for(var t=0;t>26)-(f/67108864|0),this.words[i+r]=67108863&o}for(;i>26,this.words[i+r]=67108863&o;if(0===s)return this.strip();for(n(-1===s),s=0,i=0;i>26,this.words[i]=67108863&o;return this.negative=1,this.strip()},o.prototype._wordDiv=function(e,t){var r=(this.length,e.length),n=this.clone(),i=e,a=0|i.words[i.length-1];0!==(r=26-this._countBits(a))&&(i=i.ushln(r),n.iushln(r),a=0|i.words[i.length-1]);var s,f=n.length-i.length;if("mod"!==t){(s=new o(null)).length=f+1,s.words=new Array(s.length);for(var c=0;c=0;h--){var d=67108864*(0|n.words[i.length+h])+(0|n.words[i.length+h-1]);for(d=Math.min(d/a|0,67108863),n._ishlnsubmul(i,d,h);0!==n.negative;)d--,n.negative=0,n._ishlnsubmul(i,1,h),n.isZero()||(n.negative^=1);s&&(s.words[h]=d)}return s&&s.strip(),n.strip(),"div"!==t&&0!==r&&n.iushrn(r),{div:s||null,mod:n}},o.prototype.divmod=function(e,t,r){return n(!e.isZero()),this.isZero()?{div:new o(0),mod:new o(0)}:0!==this.negative&&0===e.negative?(s=this.neg().divmod(e,t),"mod"!==t&&(i=s.div.neg()),"div"!==t&&(a=s.mod.neg(),r&&0!==a.negative&&a.iadd(e)),{div:i,mod:a}):0===this.negative&&0!==e.negative?(s=this.divmod(e.neg(),t),"mod"!==t&&(i=s.div.neg()),{div:i,mod:s.mod}):0!=(this.negative&e.negative)?(s=this.neg().divmod(e.neg(),t),"div"!==t&&(a=s.mod.neg(),r&&0!==a.negative&&a.isub(e)),{div:s.div,mod:a}):e.length>this.length||this.cmp(e)<0?{div:new o(0),mod:this}:1===e.length?"div"===t?{div:this.divn(e.words[0]),mod:null}:"mod"===t?{div:null,mod:new o(this.modn(e.words[0]))}:{div:this.divn(e.words[0]),mod:new o(this.modn(e.words[0]))}:this._wordDiv(e,t);var i,a,s},o.prototype.div=function(e){return this.divmod(e,"div",!1).div},o.prototype.mod=function(e){return this.divmod(e,"mod",!1).mod},o.prototype.umod=function(e){return this.divmod(e,"mod",!0).mod},o.prototype.divRound=function(e){var t=this.divmod(e);if(t.mod.isZero())return t.div;var r=0!==t.div.negative?t.mod.isub(e):t.mod,n=e.ushrn(1),i=e.andln(1),o=r.cmp(n);return o<0||1===i&&0===o?t.div:0!==t.div.negative?t.div.isubn(1):t.div.iaddn(1)},o.prototype.modn=function(e){n(e<=67108863);for(var t=(1<<26)%e,r=0,i=this.length-1;i>=0;i--)r=(t*r+(0|this.words[i]))%e;return r},o.prototype.idivn=function(e){n(e<=67108863);for(var t=0,r=this.length-1;r>=0;r--){var i=(0|this.words[r])+67108864*t;this.words[r]=i/e|0,t=i%e}return this.strip()},o.prototype.divn=function(e){return this.clone().idivn(e)},o.prototype.egcd=function(e){n(0===e.negative),n(!e.isZero());var t=this,r=e.clone();t=0!==t.negative?t.umod(e):t.clone();for(var i=new o(1),a=new o(0),s=new o(0),f=new o(1),c=0;t.isEven()&&r.isEven();)t.iushrn(1),r.iushrn(1),++c;for(var u=r.clone(),h=t.clone();!t.isZero();){for(var d=0,l=1;0==(t.words[0]&l)&&d<26;++d,l<<=1);if(d>0)for(t.iushrn(d);d-- >0;)(i.isOdd()||a.isOdd())&&(i.iadd(u),a.isub(h)),i.iushrn(1),a.iushrn(1);for(var p=0,b=1;0==(r.words[0]&b)&&p<26;++p,b<<=1);if(p>0)for(r.iushrn(p);p-- >0;)(s.isOdd()||f.isOdd())&&(s.iadd(u),f.isub(h)),s.iushrn(1),f.iushrn(1);t.cmp(r)>=0?(t.isub(r),i.isub(s),a.isub(f)):(r.isub(t),s.isub(i),f.isub(a))}return{a:s,b:f,gcd:r.iushln(c)}},o.prototype._invmp=function(e){n(0===e.negative),n(!e.isZero());var t=this,r=e.clone();t=0!==t.negative?t.umod(e):t.clone();for(var i,a=new o(1),s=new o(0),f=r.clone();t.cmpn(1)>0&&r.cmpn(1)>0;){for(var c=0,u=1;0==(t.words[0]&u)&&c<26;++c,u<<=1);if(c>0)for(t.iushrn(c);c-- >0;)a.isOdd()&&a.iadd(f),a.iushrn(1);for(var h=0,d=1;0==(r.words[0]&d)&&h<26;++h,d<<=1);if(h>0)for(r.iushrn(h);h-- >0;)s.isOdd()&&s.iadd(f),s.iushrn(1);t.cmp(r)>=0?(t.isub(r),a.isub(s)):(r.isub(t),s.isub(a))}return(i=0===t.cmpn(1)?a:s).cmpn(0)<0&&i.iadd(e),i},o.prototype.gcd=function(e){if(this.isZero())return e.abs();if(e.isZero())return this.abs();var t=this.clone(),r=e.clone();t.negative=0,r.negative=0;for(var n=0;t.isEven()&&r.isEven();n++)t.iushrn(1),r.iushrn(1);for(;;){for(;t.isEven();)t.iushrn(1);for(;r.isEven();)r.iushrn(1);var i=t.cmp(r);if(i<0){var o=t;t=r,r=o}else if(0===i||0===r.cmpn(1))break;t.isub(r)}return r.iushln(n)},o.prototype.invm=function(e){return this.egcd(e).a.umod(e)},o.prototype.isEven=function(){return 0==(1&this.words[0])},o.prototype.isOdd=function(){return 1==(1&this.words[0])},o.prototype.andln=function(e){return this.words[0]&e},o.prototype.bincn=function(e){n("number"==typeof e);var t=e%26,r=(e-t)/26,i=1<>>26,s&=67108863,this.words[a]=s}return 0!==o&&(this.words[a]=o,this.length++),this},o.prototype.isZero=function(){return 1===this.length&&0===this.words[0]},o.prototype.cmpn=function(e){var t,r=e<0;if(0!==this.negative&&!r)return-1;if(0===this.negative&&r)return 1;if(this.strip(),this.length>1)t=1;else{r&&(e=-e),n(e<=67108863,"Number is too big");var i=0|this.words[0];t=i===e?0:ie.length)return 1;if(this.length=0;r--){var n=0|this.words[r],i=0|e.words[r];if(n!==i){ni&&(t=1);break}}return t},o.prototype.gtn=function(e){return 1===this.cmpn(e)},o.prototype.gt=function(e){return 1===this.cmp(e)},o.prototype.gten=function(e){return this.cmpn(e)>=0},o.prototype.gte=function(e){return this.cmp(e)>=0},o.prototype.ltn=function(e){return-1===this.cmpn(e)},o.prototype.lt=function(e){return-1===this.cmp(e)},o.prototype.lten=function(e){return this.cmpn(e)<=0},o.prototype.lte=function(e){return this.cmp(e)<=0},o.prototype.eqn=function(e){return 0===this.cmpn(e)},o.prototype.eq=function(e){return 0===this.cmp(e)},o.red=function(e){return new S(e)},o.prototype.toRed=function(e){return n(!this.red,"Already a number in reduction context"),n(0===this.negative,"red works only with positives"),e.convertTo(this)._forceRed(e)},o.prototype.fromRed=function(){return n(this.red,"fromRed works only with numbers in reduction context"),this.red.convertFrom(this)},o.prototype._forceRed=function(e){return this.red=e,this},o.prototype.forceRed=function(e){return n(!this.red,"Already a number in reduction context"),this._forceRed(e)},o.prototype.redAdd=function(e){return n(this.red,"redAdd works only with red numbers"),this.red.add(this,e)},o.prototype.redIAdd=function(e){return n(this.red,"redIAdd works only with red numbers"),this.red.iadd(this,e)},o.prototype.redSub=function(e){return n(this.red,"redSub works only with red numbers"),this.red.sub(this,e)},o.prototype.redISub=function(e){return n(this.red,"redISub works only with red numbers"),this.red.isub(this,e)},o.prototype.redShl=function(e){return n(this.red,"redShl works only with red numbers"),this.red.shl(this,e)},o.prototype.redMul=function(e){return n(this.red,"redMul works only with red numbers"),this.red._verify2(this,e),this.red.mul(this,e)},o.prototype.redIMul=function(e){return n(this.red,"redMul works only with red numbers"),this.red._verify2(this,e),this.red.imul(this,e)},o.prototype.redSqr=function(){return n(this.red,"redSqr works only with red numbers"),this.red._verify1(this),this.red.sqr(this)},o.prototype.redISqr=function(){return n(this.red,"redISqr works only with red numbers"),this.red._verify1(this),this.red.isqr(this)},o.prototype.redSqrt=function(){return n(this.red,"redSqrt works only with red numbers"),this.red._verify1(this),this.red.sqrt(this)},o.prototype.redInvm=function(){return n(this.red,"redInvm works only with red numbers"),this.red._verify1(this),this.red.invm(this)},o.prototype.redNeg=function(){return n(this.red,"redNeg works only with red numbers"),this.red._verify1(this),this.red.neg(this)},o.prototype.redPow=function(e){return n(this.red&&!e.red,"redPow(normalNum)"),this.red._verify1(this),this.red.pow(this,e)};var y={k256:null,p224:null,p192:null,p25519:null};function m(e,t){this.name=e,this.p=new o(t,16),this.n=this.p.bitLength(),this.k=new o(1).iushln(this.n).isub(this.p),this.tmp=this._tmp()}function v(){m.call(this,"k256","ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f")}function g(){m.call(this,"p224","ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001")}function w(){m.call(this,"p192","ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff")}function _(){m.call(this,"25519","7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed")}function S(e){if("string"==typeof e){var t=o._prime(e);this.m=t.p,this.prime=t}else n(e.gtn(1),"modulus must be greater than 1"),this.m=e,this.prime=null}function E(e){S.call(this,e),this.shift=this.m.bitLength(),this.shift%26!=0&&(this.shift+=26-this.shift%26),this.r=new o(1).iushln(this.shift),this.r2=this.imod(this.r.sqr()),this.rinv=this.r._invmp(this.m),this.minv=this.rinv.mul(this.r).isubn(1).div(this.m),this.minv=this.minv.umod(this.r),this.minv=this.r.sub(this.minv)}m.prototype._tmp=function(){var e=new o(null);return e.words=new Array(Math.ceil(this.n/13)),e},m.prototype.ireduce=function(e){var t,r=e;do{this.split(r,this.tmp),t=(r=(r=this.imulK(r)).iadd(this.tmp)).bitLength()}while(t>this.n);var n=t0?r.isub(this.p):r.strip(),r},m.prototype.split=function(e,t){e.iushrn(this.n,0,t)},m.prototype.imulK=function(e){return e.imul(this.k)},i(v,m),v.prototype.split=function(e,t){for(var r=Math.min(e.length,9),n=0;n>>22,i=o}i>>>=22,e.words[n-10]=i,0===i&&e.length>10?e.length-=10:e.length-=9},v.prototype.imulK=function(e){e.words[e.length]=0,e.words[e.length+1]=0,e.length+=2;for(var t=0,r=0;r>>=26,e.words[r]=i,t=n}return 0!==t&&(e.words[e.length++]=t),e},o._prime=function(e){if(y[e])return y[e];var t;if("k256"===e)t=new v;else if("p224"===e)t=new g;else if("p192"===e)t=new w;else{if("p25519"!==e)throw new Error("Unknown prime "+e);t=new _}return y[e]=t,t},S.prototype._verify1=function(e){n(0===e.negative,"red works only with positives"),n(e.red,"red works only with red numbers")},S.prototype._verify2=function(e,t){n(0==(e.negative|t.negative),"red works only with positives"),n(e.red&&e.red===t.red,"red works only with red numbers")},S.prototype.imod=function(e){return this.prime?this.prime.ireduce(e)._forceRed(this):e.umod(this.m)._forceRed(this)},S.prototype.neg=function(e){return e.isZero()?e.clone():this.m.sub(e)._forceRed(this)},S.prototype.add=function(e,t){this._verify2(e,t);var r=e.add(t);return r.cmp(this.m)>=0&&r.isub(this.m),r._forceRed(this)},S.prototype.iadd=function(e,t){this._verify2(e,t);var r=e.iadd(t);return r.cmp(this.m)>=0&&r.isub(this.m),r},S.prototype.sub=function(e,t){this._verify2(e,t);var r=e.sub(t);return r.cmpn(0)<0&&r.iadd(this.m),r._forceRed(this)},S.prototype.isub=function(e,t){this._verify2(e,t);var r=e.isub(t);return r.cmpn(0)<0&&r.iadd(this.m),r},S.prototype.shl=function(e,t){return this._verify1(e),this.imod(e.ushln(t))},S.prototype.imul=function(e,t){return this._verify2(e,t),this.imod(e.imul(t))},S.prototype.mul=function(e,t){return this._verify2(e,t),this.imod(e.mul(t))},S.prototype.isqr=function(e){return this.imul(e,e.clone())},S.prototype.sqr=function(e){return this.mul(e,e)},S.prototype.sqrt=function(e){if(e.isZero())return e.clone();var t=this.m.andln(3);if(n(t%2==1),3===t){var r=this.m.add(new o(1)).iushrn(2);return this.pow(e,r)}for(var i=this.m.subn(1),a=0;!i.isZero()&&0===i.andln(1);)a++,i.iushrn(1);n(!i.isZero());var s=new o(1).toRed(this),f=s.redNeg(),c=this.m.subn(1).iushrn(1),u=this.m.bitLength();for(u=new o(2*u*u).toRed(this);0!==this.pow(u,c).cmp(f);)u.redIAdd(f);for(var h=this.pow(u,i),d=this.pow(e,i.addn(1).iushrn(1)),l=this.pow(e,i),p=a;0!==l.cmp(s);){for(var b=l,y=0;0!==b.cmp(s);y++)b=b.redSqr();n(y=0;n--){for(var c=t.words[n],u=f-1;u>=0;u--){var h=c>>u&1;i!==r[0]&&(i=this.sqr(i)),0!==h||0!==a?(a<<=1,a|=h,(4===++s||0===n&&0===u)&&(i=this.mul(i,r[a]),s=0,a=0)):s=0}f=26}return i},S.prototype.convertTo=function(e){var t=e.umod(this.m);return t===e?t.clone():t},S.prototype.convertFrom=function(e){var t=e.clone();return t.red=null,t},o.mont=function(e){return new E(e)},i(E,S),E.prototype.convertTo=function(e){return this.imod(e.ushln(this.shift))},E.prototype.convertFrom=function(e){var t=this.imod(e.mul(this.rinv));return t.red=null,t},E.prototype.imul=function(e,t){if(e.isZero()||t.isZero())return e.words[0]=0,e.length=1,e;var r=e.imul(t),n=r.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),i=r.isub(n).iushrn(this.shift),o=i;return i.cmp(this.m)>=0?o=i.isub(this.m):i.cmpn(0)<0&&(o=i.iadd(this.m)),o._forceRed(this)},E.prototype.mul=function(e,t){if(e.isZero()||t.isZero())return new o(0)._forceRed(this);var r=e.mul(t),n=r.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),i=r.isub(n).iushrn(this.shift),a=i;return i.cmp(this.m)>=0?a=i.isub(this.m):i.cmpn(0)<0&&(a=i.iadd(this.m)),a._forceRed(this)},E.prototype.invm=function(e){return this.imod(e._invmp(this.m).mul(this.r2))._forceRed(this)}}(void 0===t||t,this)},{buffer:46}],45:[function(e,t,r){var n;function i(e){this.rand=e}if(t.exports=function(e){return n||(n=new i(null)),n.generate(e)},t.exports.Rand=i,i.prototype.generate=function(e){return this._rand(e)},i.prototype._rand=function(e){if(this.rand.getBytes)return this.rand.getBytes(e);for(var t=new Uint8Array(e),r=0;r>>24]^u[p>>>16&255]^h[b>>>8&255]^d[255&y]^t[m++],a=c[p>>>24]^u[b>>>16&255]^h[y>>>8&255]^d[255&l]^t[m++],s=c[b>>>24]^u[y>>>16&255]^h[l>>>8&255]^d[255&p]^t[m++],f=c[y>>>24]^u[l>>>16&255]^h[p>>>8&255]^d[255&b]^t[m++],l=o,p=a,b=s,y=f;return o=(n[l>>>24]<<24|n[p>>>16&255]<<16|n[b>>>8&255]<<8|n[255&y])^t[m++],a=(n[p>>>24]<<24|n[b>>>16&255]<<16|n[y>>>8&255]<<8|n[255&l])^t[m++],s=(n[b>>>24]<<24|n[y>>>16&255]<<16|n[l>>>8&255]<<8|n[255&p])^t[m++],f=(n[y>>>24]<<24|n[l>>>16&255]<<16|n[p>>>8&255]<<8|n[255&b])^t[m++],[o>>>=0,a>>>=0,s>>>=0,f>>>=0]}var s=[0,1,2,4,8,16,32,64,128,27,54],f=function(){for(var e=new Array(256),t=0;t<256;t++)e[t]=t<128?t<<1:t<<1^283;for(var r=[],n=[],i=[[],[],[],[]],o=[[],[],[],[]],a=0,s=0,f=0;f<256;++f){var c=s^s<<1^s<<2^s<<3^s<<4;c=c>>>8^255&c^99,r[a]=c,n[c]=a;var u=e[a],h=e[u],d=e[h],l=257*e[c]^16843008*c;i[0][a]=l<<24|l>>>8,i[1][a]=l<<16|l>>>16,i[2][a]=l<<8|l>>>24,i[3][a]=l,l=16843009*d^65537*h^257*u^16843008*a,o[0][c]=l<<24|l>>>8,o[1][c]=l<<16|l>>>16,o[2][c]=l<<8|l>>>24,o[3][c]=l,0===a?a=s=1:(a=u^e[e[e[d^u]]],s^=e[e[s]])}return{SBOX:r,INV_SBOX:n,SUB_MIX:i,INV_SUB_MIX:o}}();function c(e){this._key=i(e),this._reset()}c.blockSize=16,c.keySize=32,c.prototype.blockSize=c.blockSize,c.prototype.keySize=c.keySize,c.prototype._reset=function(){for(var e=this._key,t=e.length,r=t+6,n=4*(r+1),i=[],o=0;o>>24,a=f.SBOX[a>>>24]<<24|f.SBOX[a>>>16&255]<<16|f.SBOX[a>>>8&255]<<8|f.SBOX[255&a],a^=s[o/t|0]<<24):t>6&&o%t==4&&(a=f.SBOX[a>>>24]<<24|f.SBOX[a>>>16&255]<<16|f.SBOX[a>>>8&255]<<8|f.SBOX[255&a]),i[o]=i[o-t]^a}for(var c=[],u=0;u>>24]]^f.INV_SUB_MIX[1][f.SBOX[d>>>16&255]]^f.INV_SUB_MIX[2][f.SBOX[d>>>8&255]]^f.INV_SUB_MIX[3][f.SBOX[255&d]]}this._nRounds=r,this._keySchedule=i,this._invKeySchedule=c},c.prototype.encryptBlockRaw=function(e){return a(e=i(e),this._keySchedule,f.SUB_MIX,f.SBOX,this._nRounds)},c.prototype.encryptBlock=function(e){var t=this.encryptBlockRaw(e),r=n.allocUnsafe(16);return r.writeUInt32BE(t[0],0),r.writeUInt32BE(t[1],4),r.writeUInt32BE(t[2],8),r.writeUInt32BE(t[3],12),r},c.prototype.decryptBlock=function(e){var t=(e=i(e))[1];e[1]=e[3],e[3]=t;var r=a(e,this._invKeySchedule,f.INV_SUB_MIX,f.INV_SBOX,this._nRounds),o=n.allocUnsafe(16);return o.writeUInt32BE(r[0],0),o.writeUInt32BE(r[3],4),o.writeUInt32BE(r[2],8),o.writeUInt32BE(r[1],12),o},c.prototype.scrub=function(){o(this._keySchedule),o(this._invKeySchedule),o(this._key)},t.exports.AES=c},{"safe-buffer":170}],48:[function(e,t,r){var n=e("./aes"),i=e("safe-buffer").Buffer,o=e("cipher-base"),a=e("inherits"),s=e("./ghash"),f=e("buffer-xor"),c=e("./incr32");function u(e,t,r,a){o.call(this);var f=i.alloc(4,0);this._cipher=new n.AES(t);var u=this._cipher.encryptBlock(f);this._ghash=new s(u),r=function(e,t,r){if(12===t.length)return e._finID=i.concat([t,i.from([0,0,0,1])]),i.concat([t,i.from([0,0,0,2])]);var n=new s(r),o=t.length,a=o%16;n.update(t),a&&(a=16-a,n.update(i.alloc(a,0))),n.update(i.alloc(8,0));var f=8*o,u=i.alloc(8);u.writeUIntBE(f,0,8),n.update(u),e._finID=n.state;var h=i.from(e._finID);return c(h),h}(this,r,u),this._prev=i.from(r),this._cache=i.allocUnsafe(0),this._secCache=i.allocUnsafe(0),this._decrypt=a,this._alen=0,this._len=0,this._mode=e,this._authTag=null,this._called=!1}a(u,o),u.prototype._update=function(e){if(!this._called&&this._alen){var t=16-this._alen%16;t<16&&(t=i.alloc(t,0),this._ghash.update(t))}this._called=!0;var r=this._mode.encrypt(this,e);return this._decrypt?this._ghash.update(e):this._ghash.update(r),this._len+=e.length,r},u.prototype._final=function(){if(this._decrypt&&!this._authTag)throw new Error("Unsupported state or unable to authenticate data");var e=f(this._ghash.final(8*this._alen,8*this._len),this._cipher.encryptBlock(this._finID));if(this._decrypt&&function(e,t){var r=0;e.length!==t.length&&r++;for(var n=Math.min(e.length,t.length),i=0;i16)throw new Error("unable to decrypt data");var r=-1;for(;++r16)return t=this.cache.slice(0,16),this.cache=this.cache.slice(16),t}else if(this.cache.length>=16)return t=this.cache.slice(0,16),this.cache=this.cache.slice(16),t;return null},h.prototype.flush=function(){if(this.cache.length)return this.cache},r.createDecipher=function(e,t){var r=o[e.toLowerCase()];if(!r)throw new TypeError("invalid suite type");var n=c(t,!1,r.key,r.iv);return d(e,n.key,n.iv)},r.createDecipheriv=d},{"./aes":47,"./authCipher":48,"./modes":60,"./streamCipher":63,"cipher-base":76,evp_bytestokey:111,inherits:127,"safe-buffer":170}],51:[function(e,t,r){var n=e("./modes"),i=e("./authCipher"),o=e("safe-buffer").Buffer,a=e("./streamCipher"),s=e("cipher-base"),f=e("./aes"),c=e("evp_bytestokey");function u(e,t,r){s.call(this),this._cache=new d,this._cipher=new f.AES(t),this._prev=o.from(r),this._mode=e,this._autopadding=!0}e("inherits")(u,s),u.prototype._update=function(e){var t,r;this._cache.add(e);for(var n=[];t=this._cache.get();)r=this._mode.encrypt(this,t),n.push(r);return o.concat(n)};var h=o.alloc(16,16);function d(){this.cache=o.allocUnsafe(0)}function l(e,t,r){var s=n[e.toLowerCase()];if(!s)throw new TypeError("invalid suite type");if("string"==typeof t&&(t=o.from(t)),t.length!==s.key/8)throw new TypeError("invalid key length "+t.length);if("string"==typeof r&&(r=o.from(r)),"GCM"!==s.mode&&r.length!==s.iv)throw new TypeError("invalid iv length "+r.length);return"stream"===s.type?new a(s.module,t,r):"auth"===s.type?new i(s.module,t,r):new u(s.module,t,r)}u.prototype._final=function(){var e=this._cache.flush();if(this._autopadding)return e=this._mode.encrypt(this,e),this._cipher.scrub(),e;if(!e.equals(h))throw this._cipher.scrub(),new Error("data not multiple of block length")},u.prototype.setAutoPadding=function(e){return this._autopadding=!!e,this},d.prototype.add=function(e){this.cache=o.concat([this.cache,e])},d.prototype.get=function(){if(this.cache.length>15){var e=this.cache.slice(0,16);return this.cache=this.cache.slice(16),e}return null},d.prototype.flush=function(){for(var e=16-this.cache.length,t=o.allocUnsafe(e),r=-1;++r>>0,0),t.writeUInt32BE(e[1]>>>0,4),t.writeUInt32BE(e[2]>>>0,8),t.writeUInt32BE(e[3]>>>0,12),t}function a(e){this.h=e,this.state=n.alloc(16,0),this.cache=n.allocUnsafe(0)}a.prototype.ghash=function(e){for(var t=-1;++t0;t--)n[t]=n[t]>>>1|(1&n[t-1])<<31;n[0]=n[0]>>>1,r&&(n[0]=n[0]^225<<24)}this.state=o(i)},a.prototype.update=function(e){var t;for(this.cache=n.concat([this.cache,e]);this.cache.length>=16;)t=this.cache.slice(0,16),this.cache=this.cache.slice(16),this.ghash(t)},a.prototype.final=function(e,t){return this.cache.length&&this.ghash(n.concat([this.cache,i],16)),this.ghash(o([0,e,0,t])),this.state},t.exports=a},{"safe-buffer":170}],53:[function(e,t,r){t.exports=function(e){for(var t,r=e.length;r--;){if(255!==(t=e.readUInt8(r))){t++,e.writeUInt8(t,r);break}e.writeUInt8(0,r)}}},{}],54:[function(e,t,r){var n=e("buffer-xor");r.encrypt=function(e,t){var r=n(t,e._prev);return e._prev=e._cipher.encryptBlock(r),e._prev},r.decrypt=function(e,t){var r=e._prev;e._prev=t;var i=e._cipher.decryptBlock(t);return n(i,r)}},{"buffer-xor":74}],55:[function(e,t,r){var n=e("safe-buffer").Buffer,i=e("buffer-xor");function o(e,t,r){var o=t.length,a=i(t,e._cache);return e._cache=e._cache.slice(o),e._prev=n.concat([e._prev,r?t:a]),a}r.encrypt=function(e,t,r){for(var i,a=n.allocUnsafe(0);t.length;){if(0===e._cache.length&&(e._cache=e._cipher.encryptBlock(e._prev),e._prev=n.allocUnsafe(0)),!(e._cache.length<=t.length)){a=n.concat([a,o(e,t,r)]);break}i=e._cache.length,a=n.concat([a,o(e,t.slice(0,i),r)]),t=t.slice(i)}return a}},{"buffer-xor":74,"safe-buffer":170}],56:[function(e,t,r){var n=e("safe-buffer").Buffer;function i(e,t,r){for(var n,i,a=-1,s=0;++a<8;)n=t&1<<7-a?128:0,s+=(128&(i=e._cipher.encryptBlock(e._prev)[0]^n))>>a%8,e._prev=o(e._prev,r?n:i);return s}function o(e,t){var r=e.length,i=-1,o=n.allocUnsafe(e.length);for(e=n.concat([e,n.from([t])]);++i>7;return o}r.encrypt=function(e,t,r){for(var o=t.length,a=n.allocUnsafe(o),s=-1;++s=0||!r.umod(e.prime1)||!r.umod(e.prime2);)r=new n(i(t));return r}t.exports=o,o.getr=a}).call(this,e("buffer").Buffer)},{"bn.js":44,buffer:75,randombytes:152}],68:[function(e,t,r){t.exports=e("./browser/algorithms.json")},{"./browser/algorithms.json":69}],69:[function(e,t,r){t.exports={sha224WithRSAEncryption:{sign:"rsa",hash:"sha224",id:"302d300d06096086480165030402040500041c"},"RSA-SHA224":{sign:"ecdsa/rsa",hash:"sha224",id:"302d300d06096086480165030402040500041c"},sha256WithRSAEncryption:{sign:"rsa",hash:"sha256",id:"3031300d060960864801650304020105000420"},"RSA-SHA256":{sign:"ecdsa/rsa",hash:"sha256",id:"3031300d060960864801650304020105000420"},sha384WithRSAEncryption:{sign:"rsa",hash:"sha384",id:"3041300d060960864801650304020205000430"},"RSA-SHA384":{sign:"ecdsa/rsa",hash:"sha384",id:"3041300d060960864801650304020205000430"},sha512WithRSAEncryption:{sign:"rsa",hash:"sha512",id:"3051300d060960864801650304020305000440"},"RSA-SHA512":{sign:"ecdsa/rsa",hash:"sha512",id:"3051300d060960864801650304020305000440"},"RSA-SHA1":{sign:"rsa",hash:"sha1",id:"3021300906052b0e03021a05000414"},"ecdsa-with-SHA1":{sign:"ecdsa",hash:"sha1",id:""},sha256:{sign:"ecdsa",hash:"sha256",id:""},sha224:{sign:"ecdsa",hash:"sha224",id:""},sha384:{sign:"ecdsa",hash:"sha384",id:""},sha512:{sign:"ecdsa",hash:"sha512",id:""},"DSA-SHA":{sign:"dsa",hash:"sha1",id:""},"DSA-SHA1":{sign:"dsa",hash:"sha1",id:""},DSA:{sign:"dsa",hash:"sha1",id:""},"DSA-WITH-SHA224":{sign:"dsa",hash:"sha224",id:""},"DSA-SHA224":{sign:"dsa",hash:"sha224",id:""},"DSA-WITH-SHA256":{sign:"dsa",hash:"sha256",id:""},"DSA-SHA256":{sign:"dsa",hash:"sha256",id:""},"DSA-WITH-SHA384":{sign:"dsa",hash:"sha384",id:""},"DSA-SHA384":{sign:"dsa",hash:"sha384",id:""},"DSA-WITH-SHA512":{sign:"dsa",hash:"sha512",id:""},"DSA-SHA512":{sign:"dsa",hash:"sha512",id:""},"DSA-RIPEMD160":{sign:"dsa",hash:"rmd160",id:""},ripemd160WithRSA:{sign:"rsa",hash:"rmd160",id:"3021300906052b2403020105000414"},"RSA-RIPEMD160":{sign:"rsa",hash:"rmd160",id:"3021300906052b2403020105000414"},md5WithRSAEncryption:{sign:"rsa",hash:"md5",id:"3020300c06082a864886f70d020505000410"},"RSA-MD5":{sign:"rsa",hash:"md5",id:"3020300c06082a864886f70d020505000410"}}},{}],70:[function(e,t,r){t.exports={"1.3.132.0.10":"secp256k1","1.3.132.0.33":"p224","1.2.840.10045.3.1.1":"p192","1.2.840.10045.3.1.7":"p256","1.3.132.0.34":"p384","1.3.132.0.35":"p521"}},{}],71:[function(e,t,r){(function(r){var n=e("create-hash"),i=e("stream"),o=e("inherits"),a=e("./sign"),s=e("./verify"),f=e("./algorithms.json");function c(e){i.Writable.call(this);var t=f[e];if(!t)throw new Error("Unknown message digest");this._hashType=t.hash,this._hash=n(t.hash),this._tag=t.id,this._signType=t.sign}function u(e){i.Writable.call(this);var t=f[e];if(!t)throw new Error("Unknown message digest");this._hash=n(t.hash),this._tag=t.id,this._signType=t.sign}function h(e){return new c(e)}function d(e){return new u(e)}Object.keys(f).forEach(function(e){f[e].id=new r(f[e].id,"hex"),f[e.toLowerCase()]=f[e]}),o(c,i.Writable),c.prototype._write=function(e,t,r){this._hash.update(e),r()},c.prototype.update=function(e,t){return"string"==typeof e&&(e=new r(e,t)),this._hash.update(e),this},c.prototype.sign=function(e,t){this.end();var r=this._hash.digest(),n=a(r,e,this._hashType,this._signType,this._tag);return t?n.toString(t):n},o(u,i.Writable),u.prototype._write=function(e,t,r){this._hash.update(e),r()},u.prototype.update=function(e,t){return"string"==typeof e&&(e=new r(e,t)),this._hash.update(e),this},u.prototype.verify=function(e,t,n){"string"==typeof t&&(t=new r(t,n)),this.end();var i=this._hash.digest();return s(t,i,e,this._signType,this._tag)},t.exports={Sign:h,Verify:d,createSign:h,createVerify:d}}).call(this,e("buffer").Buffer)},{"./algorithms.json":69,"./sign":72,"./verify":73,buffer:75,"create-hash":79,inherits:127,stream:179}],72:[function(e,t,r){(function(r){var n=e("create-hmac"),i=e("browserify-rsa"),o=e("elliptic").ec,a=e("bn.js"),s=e("parse-asn1"),f=e("./curves.json");function c(e,t,i,o){if((e=new r(e.toArray())).length0&&r.ishrn(n),r}function h(e,t,i){var o,a;do{for(o=new r(0);8*o.length=t)throw new Error("invalid sig")}t.exports=function(e,t,f,c,u){var h=o(f);if("ec"===h.type){if("ecdsa"!==c&&"ecdsa/rsa"!==c)throw new Error("wrong public key type");return function(e,t,r){var n=a[r.data.algorithm.curve.join(".")];if(!n)throw new Error("unknown curve "+r.data.algorithm.curve.join("."));var o=new i(n),s=r.data.subjectPrivateKey.data;return o.verify(t,e,s)}(e,t,h)}if("dsa"===h.type){if("dsa"!==c)throw new Error("wrong public key type");return function(e,t,r){var i=r.data.p,a=r.data.q,f=r.data.g,c=r.data.pub_key,u=o.signature.decode(e,"der"),h=u.s,d=u.r;s(h,a),s(d,a);var l=n.mont(i),p=h.invm(a);return 0===f.toRed(l).redPow(new n(t).mul(p).mod(a)).fromRed().mul(c.toRed(l).redPow(d.mul(p).mod(a)).fromRed()).mod(i).mod(a).cmp(d)}(e,t,h)}if("rsa"!==c&&"ecdsa/rsa"!==c)throw new Error("wrong public key type");t=r.concat([u,t]);for(var d=h.modulus.byteLength(),l=[1],p=0;t.length+l.length+2o)throw new RangeError('The value "'+e+'" is invalid for option "size"');var r=new Uint8Array(e);return r.__proto__=t.prototype,r}function t(e,t,r){if("number"==typeof e){if("string"==typeof t)throw new TypeError('The "string" argument must be of type string. Received type number');return c(e)}return s(e,t,r)}function s(e,r,n){if("string"==typeof e)return function(e,r){"string"==typeof r&&""!==r||(r="utf8");if(!t.isEncoding(r))throw new TypeError("Unknown encoding: "+r);var n=0|d(e,r),i=a(n),o=i.write(e,r);o!==n&&(i=i.slice(0,o));return i}(e,r);if(ArrayBuffer.isView(e))return u(e);if(null==e)throw TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof e);if(U(e,ArrayBuffer)||e&&U(e.buffer,ArrayBuffer))return function(e,r,n){if(r<0||e.byteLength=o)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+o.toString(16)+" bytes");return 0|e}function d(e,r){if(t.isBuffer(e))return e.length;if(ArrayBuffer.isView(e)||U(e,ArrayBuffer))return e.byteLength;if("string"!=typeof e)throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof e);var n=e.length,i=arguments.length>2&&!0===arguments[2];if(!i&&0===n)return 0;for(var o=!1;;)switch(r){case"ascii":case"latin1":case"binary":return n;case"utf8":case"utf-8":return D(e).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*n;case"hex":return n>>>1;case"base64":return N(e).length;default:if(o)return i?-1:D(e).length;r=(""+r).toLowerCase(),o=!0}}function l(e,t,r){var n=e[t];e[t]=e[r],e[r]=n}function p(e,r,n,i,o){if(0===e.length)return-1;if("string"==typeof n?(i=n,n=0):n>2147483647?n=2147483647:n<-2147483648&&(n=-2147483648),q(n=+n)&&(n=o?0:e.length-1),n<0&&(n=e.length+n),n>=e.length){if(o)return-1;n=e.length-1}else if(n<0){if(!o)return-1;n=0}if("string"==typeof r&&(r=t.from(r,i)),t.isBuffer(r))return 0===r.length?-1:b(e,r,n,i,o);if("number"==typeof r)return r&=255,"function"==typeof Uint8Array.prototype.indexOf?o?Uint8Array.prototype.indexOf.call(e,r,n):Uint8Array.prototype.lastIndexOf.call(e,r,n):b(e,[r],n,i,o);throw new TypeError("val must be string, number or Buffer")}function b(e,t,r,n,i){var o,a=1,s=e.length,f=t.length;if(void 0!==n&&("ucs2"===(n=String(n).toLowerCase())||"ucs-2"===n||"utf16le"===n||"utf-16le"===n)){if(e.length<2||t.length<2)return-1;a=2,s/=2,f/=2,r/=2}function c(e,t){return 1===a?e[t]:e.readUInt16BE(t*a)}if(i){var u=-1;for(o=r;os&&(r=s-f),o=r;o>=0;o--){for(var h=!0,d=0;di&&(n=i):n=i;var o=t.length;n>o/2&&(n=o/2);for(var a=0;a>8,i=r%256,o.push(i),o.push(n);return o}(t,e.length-r),e,r,n)}function S(e,t,r){return 0===t&&r===e.length?n.fromByteArray(e):n.fromByteArray(e.slice(t,r))}function E(e,t,r){r=Math.min(e.length,r);for(var n=[],i=t;i239?4:c>223?3:c>191?2:1;if(i+h<=r)switch(h){case 1:c<128&&(u=c);break;case 2:128==(192&(o=e[i+1]))&&(f=(31&c)<<6|63&o)>127&&(u=f);break;case 3:o=e[i+1],a=e[i+2],128==(192&o)&&128==(192&a)&&(f=(15&c)<<12|(63&o)<<6|63&a)>2047&&(f<55296||f>57343)&&(u=f);break;case 4:o=e[i+1],a=e[i+2],s=e[i+3],128==(192&o)&&128==(192&a)&&128==(192&s)&&(f=(15&c)<<18|(63&o)<<12|(63&a)<<6|63&s)>65535&&f<1114112&&(u=f)}null===u?(u=65533,h=1):u>65535&&(u-=65536,n.push(u>>>10&1023|55296),u=56320|1023&u),n.push(u),i+=h}return function(e){var t=e.length;if(t<=M)return String.fromCharCode.apply(String,e);var r="",n=0;for(;nthis.length)return"";if((void 0===r||r>this.length)&&(r=this.length),r<=0)return"";if((r>>>=0)<=(t>>>=0))return"";for(e||(e="utf8");;)switch(e){case"hex":return A(this,t,r);case"utf8":case"utf-8":return E(this,t,r);case"ascii":return k(this,t,r);case"latin1":case"binary":return x(this,t,r);case"base64":return S(this,t,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return j(this,t,r);default:if(n)throw new TypeError("Unknown encoding: "+e);e=(e+"").toLowerCase(),n=!0}}.apply(this,arguments)},t.prototype.toLocaleString=t.prototype.toString,t.prototype.equals=function(e){if(!t.isBuffer(e))throw new TypeError("Argument must be a Buffer");return this===e||0===t.compare(this,e)},t.prototype.inspect=function(){var e="",t=r.INSPECT_MAX_BYTES;return e=this.toString("hex",0,t).replace(/(.{2})/g,"$1 ").trim(),this.length>t&&(e+=" ... "),""},t.prototype.compare=function(e,r,n,i,o){if(U(e,Uint8Array)&&(e=t.from(e,e.offset,e.byteLength)),!t.isBuffer(e))throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof e);if(void 0===r&&(r=0),void 0===n&&(n=e?e.length:0),void 0===i&&(i=0),void 0===o&&(o=this.length),r<0||n>e.length||i<0||o>this.length)throw new RangeError("out of range index");if(i>=o&&r>=n)return 0;if(i>=o)return-1;if(r>=n)return 1;if(this===e)return 0;for(var a=(o>>>=0)-(i>>>=0),s=(n>>>=0)-(r>>>=0),f=Math.min(a,s),c=this.slice(i,o),u=e.slice(r,n),h=0;h>>=0,isFinite(r)?(r>>>=0,void 0===n&&(n="utf8")):(n=r,r=void 0)}var i=this.length-t;if((void 0===r||r>i)&&(r=i),e.length>0&&(r<0||t<0)||t>this.length)throw new RangeError("Attempt to write outside buffer bounds");n||(n="utf8");for(var o=!1;;)switch(n){case"hex":return y(this,e,t,r);case"utf8":case"utf-8":return m(this,e,t,r);case"ascii":return v(this,e,t,r);case"latin1":case"binary":return g(this,e,t,r);case"base64":return w(this,e,t,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return _(this,e,t,r);default:if(o)throw new TypeError("Unknown encoding: "+n);n=(""+n).toLowerCase(),o=!0}},t.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};var M=4096;function k(e,t,r){var n="";r=Math.min(e.length,r);for(var i=t;in)&&(r=n);for(var i="",o=t;or)throw new RangeError("Trying to access beyond buffer length")}function I(e,r,n,i,o,a){if(!t.isBuffer(e))throw new TypeError('"buffer" argument must be a Buffer instance');if(r>o||re.length)throw new RangeError("Index out of range")}function R(e,t,r,n,i,o){if(r+n>e.length)throw new RangeError("Index out of range");if(r<0)throw new RangeError("Index out of range")}function T(e,t,r,n,o){return t=+t,r>>>=0,o||R(e,0,r,4),i.write(e,t,r,n,23,4),r+4}function C(e,t,r,n,o){return t=+t,r>>>=0,o||R(e,0,r,8),i.write(e,t,r,n,52,8),r+8}t.prototype.slice=function(e,r){var n=this.length;(e=~~e)<0?(e+=n)<0&&(e=0):e>n&&(e=n),(r=void 0===r?n:~~r)<0?(r+=n)<0&&(r=0):r>n&&(r=n),r>>=0,t>>>=0,r||B(e,t,this.length);for(var n=this[e],i=1,o=0;++o>>=0,t>>>=0,r||B(e,t,this.length);for(var n=this[e+--t],i=1;t>0&&(i*=256);)n+=this[e+--t]*i;return n},t.prototype.readUInt8=function(e,t){return e>>>=0,t||B(e,1,this.length),this[e]},t.prototype.readUInt16LE=function(e,t){return e>>>=0,t||B(e,2,this.length),this[e]|this[e+1]<<8},t.prototype.readUInt16BE=function(e,t){return e>>>=0,t||B(e,2,this.length),this[e]<<8|this[e+1]},t.prototype.readUInt32LE=function(e,t){return e>>>=0,t||B(e,4,this.length),(this[e]|this[e+1]<<8|this[e+2]<<16)+16777216*this[e+3]},t.prototype.readUInt32BE=function(e,t){return e>>>=0,t||B(e,4,this.length),16777216*this[e]+(this[e+1]<<16|this[e+2]<<8|this[e+3])},t.prototype.readIntLE=function(e,t,r){e>>>=0,t>>>=0,r||B(e,t,this.length);for(var n=this[e],i=1,o=0;++o=(i*=128)&&(n-=Math.pow(2,8*t)),n},t.prototype.readIntBE=function(e,t,r){e>>>=0,t>>>=0,r||B(e,t,this.length);for(var n=t,i=1,o=this[e+--n];n>0&&(i*=256);)o+=this[e+--n]*i;return o>=(i*=128)&&(o-=Math.pow(2,8*t)),o},t.prototype.readInt8=function(e,t){return e>>>=0,t||B(e,1,this.length),128&this[e]?-1*(255-this[e]+1):this[e]},t.prototype.readInt16LE=function(e,t){e>>>=0,t||B(e,2,this.length);var r=this[e]|this[e+1]<<8;return 32768&r?4294901760|r:r},t.prototype.readInt16BE=function(e,t){e>>>=0,t||B(e,2,this.length);var r=this[e+1]|this[e]<<8;return 32768&r?4294901760|r:r},t.prototype.readInt32LE=function(e,t){return e>>>=0,t||B(e,4,this.length),this[e]|this[e+1]<<8|this[e+2]<<16|this[e+3]<<24},t.prototype.readInt32BE=function(e,t){return e>>>=0,t||B(e,4,this.length),this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]},t.prototype.readFloatLE=function(e,t){return e>>>=0,t||B(e,4,this.length),i.read(this,e,!0,23,4)},t.prototype.readFloatBE=function(e,t){return e>>>=0,t||B(e,4,this.length),i.read(this,e,!1,23,4)},t.prototype.readDoubleLE=function(e,t){return e>>>=0,t||B(e,8,this.length),i.read(this,e,!0,52,8)},t.prototype.readDoubleBE=function(e,t){return e>>>=0,t||B(e,8,this.length),i.read(this,e,!1,52,8)},t.prototype.writeUIntLE=function(e,t,r,n){(e=+e,t>>>=0,r>>>=0,n)||I(this,e,t,r,Math.pow(2,8*r)-1,0);var i=1,o=0;for(this[t]=255&e;++o>>=0,r>>>=0,n)||I(this,e,t,r,Math.pow(2,8*r)-1,0);var i=r-1,o=1;for(this[t+i]=255&e;--i>=0&&(o*=256);)this[t+i]=e/o&255;return t+r},t.prototype.writeUInt8=function(e,t,r){return e=+e,t>>>=0,r||I(this,e,t,1,255,0),this[t]=255&e,t+1},t.prototype.writeUInt16LE=function(e,t,r){return e=+e,t>>>=0,r||I(this,e,t,2,65535,0),this[t]=255&e,this[t+1]=e>>>8,t+2},t.prototype.writeUInt16BE=function(e,t,r){return e=+e,t>>>=0,r||I(this,e,t,2,65535,0),this[t]=e>>>8,this[t+1]=255&e,t+2},t.prototype.writeUInt32LE=function(e,t,r){return e=+e,t>>>=0,r||I(this,e,t,4,4294967295,0),this[t+3]=e>>>24,this[t+2]=e>>>16,this[t+1]=e>>>8,this[t]=255&e,t+4},t.prototype.writeUInt32BE=function(e,t,r){return e=+e,t>>>=0,r||I(this,e,t,4,4294967295,0),this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e,t+4},t.prototype.writeIntLE=function(e,t,r,n){if(e=+e,t>>>=0,!n){var i=Math.pow(2,8*r-1);I(this,e,t,r,i-1,-i)}var o=0,a=1,s=0;for(this[t]=255&e;++o>0)-s&255;return t+r},t.prototype.writeIntBE=function(e,t,r,n){if(e=+e,t>>>=0,!n){var i=Math.pow(2,8*r-1);I(this,e,t,r,i-1,-i)}var o=r-1,a=1,s=0;for(this[t+o]=255&e;--o>=0&&(a*=256);)e<0&&0===s&&0!==this[t+o+1]&&(s=1),this[t+o]=(e/a>>0)-s&255;return t+r},t.prototype.writeInt8=function(e,t,r){return e=+e,t>>>=0,r||I(this,e,t,1,127,-128),e<0&&(e=255+e+1),this[t]=255&e,t+1},t.prototype.writeInt16LE=function(e,t,r){return e=+e,t>>>=0,r||I(this,e,t,2,32767,-32768),this[t]=255&e,this[t+1]=e>>>8,t+2},t.prototype.writeInt16BE=function(e,t,r){return e=+e,t>>>=0,r||I(this,e,t,2,32767,-32768),this[t]=e>>>8,this[t+1]=255&e,t+2},t.prototype.writeInt32LE=function(e,t,r){return e=+e,t>>>=0,r||I(this,e,t,4,2147483647,-2147483648),this[t]=255&e,this[t+1]=e>>>8,this[t+2]=e>>>16,this[t+3]=e>>>24,t+4},t.prototype.writeInt32BE=function(e,t,r){return e=+e,t>>>=0,r||I(this,e,t,4,2147483647,-2147483648),e<0&&(e=4294967295+e+1),this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e,t+4},t.prototype.writeFloatLE=function(e,t,r){return T(this,e,t,!0,r)},t.prototype.writeFloatBE=function(e,t,r){return T(this,e,t,!1,r)},t.prototype.writeDoubleLE=function(e,t,r){return C(this,e,t,!0,r)},t.prototype.writeDoubleBE=function(e,t,r){return C(this,e,t,!1,r)},t.prototype.copy=function(e,r,n,i){if(!t.isBuffer(e))throw new TypeError("argument should be a Buffer");if(n||(n=0),i||0===i||(i=this.length),r>=e.length&&(r=e.length),r||(r=0),i>0&&i=this.length)throw new RangeError("Index out of range");if(i<0)throw new RangeError("sourceEnd out of bounds");i>this.length&&(i=this.length),e.length-r=0;--a)e[a+r]=this[a+n];else Uint8Array.prototype.set.call(e,this.subarray(n,i),r);return o},t.prototype.fill=function(e,r,n,i){if("string"==typeof e){if("string"==typeof r?(i=r,r=0,n=this.length):"string"==typeof n&&(i=n,n=this.length),void 0!==i&&"string"!=typeof i)throw new TypeError("encoding must be a string");if("string"==typeof i&&!t.isEncoding(i))throw new TypeError("Unknown encoding: "+i);if(1===e.length){var o=e.charCodeAt(0);("utf8"===i&&o<128||"latin1"===i)&&(e=o)}}else"number"==typeof e&&(e&=255);if(r<0||this.length>>=0,n=void 0===n?this.length:n>>>0,e||(e=0),"number"==typeof e)for(a=r;a55295&&r<57344){if(!i){if(r>56319){(t-=3)>-1&&o.push(239,191,189);continue}if(a+1===n){(t-=3)>-1&&o.push(239,191,189);continue}i=r;continue}if(r<56320){(t-=3)>-1&&o.push(239,191,189),i=r;continue}r=65536+(i-55296<<10|r-56320)}else i&&(t-=3)>-1&&o.push(239,191,189);if(i=null,r<128){if((t-=1)<0)break;o.push(r)}else if(r<2048){if((t-=2)<0)break;o.push(r>>6|192,63&r|128)}else if(r<65536){if((t-=3)<0)break;o.push(r>>12|224,r>>6&63|128,63&r|128)}else{if(!(r<1114112))throw new Error("Invalid code point");if((t-=4)<0)break;o.push(r>>18|240,r>>12&63|128,r>>6&63|128,63&r|128)}}return o}function N(e){return n.toByteArray(function(e){if((e=(e=e.split("=")[0]).trim().replace(P,"")).length<2)return"";for(;e.length%4!=0;)e+="=";return e}(e))}function L(e,t,r,n){for(var i=0;i=t.length||i>=e.length);++i)t[i+r]=e[i];return i}function U(e,t){return e instanceof t||null!=e&&null!=e.constructor&&null!=e.constructor.name&&e.constructor.name===t.name}function q(e){return e!=e}}).call(this,e("buffer").Buffer)},{"base64-js":43,buffer:75,ieee754:126}],76:[function(e,t,r){var n=e("safe-buffer").Buffer,i=e("stream").Transform,o=e("string_decoder").StringDecoder;function a(e){i.call(this),this.hashMode="string"==typeof e,this.hashMode?this[e]=this._finalOrDigest:this.final=this._finalOrDigest,this._final&&(this.__final=this._final,this._final=null),this._decoder=null,this._encoding=null}e("inherits")(a,i),a.prototype.update=function(e,t,r){"string"==typeof e&&(e=n.from(e,t));var i=this._update(e);return this.hashMode?this:(r&&(i=this._toString(i,r)),i)},a.prototype.setAutoPadding=function(){},a.prototype.getAuthTag=function(){throw new Error("trying to get auth tag in unsupported state")},a.prototype.setAuthTag=function(){throw new Error("trying to set auth tag in unsupported state")},a.prototype.setAAD=function(){throw new Error("trying to set aad in unsupported state")},a.prototype._transform=function(e,t,r){var n;try{this.hashMode?this._update(e):this.push(this._update(e))}catch(e){n=e}finally{r(n)}},a.prototype._flush=function(e){var t;try{this.push(this.__final())}catch(e){t=e}e(t)},a.prototype._finalOrDigest=function(e){var t=this.__final()||n.alloc(0);return e&&(t=this._toString(t,e,!0)),t},a.prototype._toString=function(e,t,r){if(this._decoder||(this._decoder=new o(t),this._encoding=t),this._encoding!==t)throw new Error("can't switch encodings");var n=this._decoder.write(e);return r&&(n+=this._decoder.end()),n},t.exports=a},{inherits:127,"safe-buffer":170,stream:179,string_decoder:180}],77:[function(e,t,r){(function(e){function t(e){return Object.prototype.toString.call(e)}r.isArray=function(e){return Array.isArray?Array.isArray(e):"[object Array]"===t(e)},r.isBoolean=function(e){return"boolean"==typeof e},r.isNull=function(e){return null===e},r.isNullOrUndefined=function(e){return null==e},r.isNumber=function(e){return"number"==typeof e},r.isString=function(e){return"string"==typeof e},r.isSymbol=function(e){return"symbol"==typeof e},r.isUndefined=function(e){return void 0===e},r.isRegExp=function(e){return"[object RegExp]"===t(e)},r.isObject=function(e){return"object"==typeof e&&null!==e},r.isDate=function(e){return"[object Date]"===t(e)},r.isError=function(e){return"[object Error]"===t(e)||e instanceof Error},r.isFunction=function(e){return"function"==typeof e},r.isPrimitive=function(e){return null===e||"boolean"==typeof e||"number"==typeof e||"string"==typeof e||"symbol"==typeof e||void 0===e},r.isBuffer=e.isBuffer}).call(this,{isBuffer:e("../../is-buffer/index.js")})},{"../../is-buffer/index.js":128}],78:[function(e,t,r){(function(r){var n=e("elliptic"),i=e("bn.js");t.exports=function(e){return new a(e)};var o={secp256k1:{name:"secp256k1",byteLength:32},secp224r1:{name:"p224",byteLength:28},prime256v1:{name:"p256",byteLength:32},prime192v1:{name:"p192",byteLength:24},ed25519:{name:"ed25519",byteLength:32},secp384r1:{name:"p384",byteLength:48},secp521r1:{name:"p521",byteLength:66}};function a(e){this.curveType=o[e],this.curveType||(this.curveType={name:e}),this.curve=new n.ec(this.curveType.name),this.keys=void 0}function s(e,t,n){Array.isArray(e)||(e=e.toArray());var i=new r(e);if(n&&i.lengthr)?t=("rmd160"===e?new f:c(e)).update(t).digest():t.lengths?t=e(t):t.length0;n--)t+=this._buffer(e,t),r+=this._flushBuffer(i,r);return t+=this._buffer(e,t),i},i.prototype.final=function(e){var t,r;return e&&(t=this.update(e)),r="encrypt"===this.type?this._finalEncrypt():this._finalDecrypt(),t?t.concat(r):r},i.prototype._pad=function(e,t){if(0===t)return!1;for(;t>>1];r=a.r28shl(r,s),i=a.r28shl(i,s),a.pc2(r,i,e.keys,o)}},c.prototype._update=function(e,t,r,n){var i=this._desState,o=a.readUInt32BE(e,t),s=a.readUInt32BE(e,t+4);a.ip(o,s,i.tmp,0),o=i.tmp[0],s=i.tmp[1],"encrypt"===this.type?this._encrypt(i,o,s,i.tmp,0):this._decrypt(i,o,s,i.tmp,0),o=i.tmp[0],s=i.tmp[1],a.writeUInt32BE(r,o,n),a.writeUInt32BE(r,s,n+4)},c.prototype._pad=function(e,t){for(var r=e.length-t,n=t;n>>0,o=d}a.rip(s,o,n,i)},c.prototype._decrypt=function(e,t,r,n,i){for(var o=r,s=t,f=e.keys.length-2;f>=0;f-=2){var c=e.keys[f],u=e.keys[f+1];a.expand(o,e.tmp,0),c^=e.tmp[0],u^=e.tmp[1];var h=a.substitute(c,u),d=o;o=(s^a.permute(h))>>>0,s=d}a.rip(o,s,n,i)}},{"../des":84,inherits:127,"minimalistic-assert":132}],88:[function(e,t,r){"use strict";var n=e("minimalistic-assert"),i=e("inherits"),o=e("../des"),a=o.Cipher,s=o.DES;function f(e,t){n.equal(t.length,24,"Invalid key length");var r=t.slice(0,8),i=t.slice(8,16),o=t.slice(16,24);this.ciphers="encrypt"===e?[s.create({type:"encrypt",key:r}),s.create({type:"decrypt",key:i}),s.create({type:"encrypt",key:o})]:[s.create({type:"decrypt",key:o}),s.create({type:"encrypt",key:i}),s.create({type:"decrypt",key:r})]}function c(e){a.call(this,e);var t=new f(this.type,this.options.key);this._edeState=t}i(c,a),t.exports=c,c.create=function(e){return new c(e)},c.prototype._update=function(e,t,r,n){var i=this._edeState;i.ciphers[0]._update(e,t,r,n),i.ciphers[1]._update(r,n,r,n),i.ciphers[2]._update(r,n,r,n)},c.prototype._pad=s.prototype._pad,c.prototype._unpad=s.prototype._unpad},{"../des":84,inherits:127,"minimalistic-assert":132}],89:[function(e,t,r){"use strict";r.readUInt32BE=function(e,t){return(e[0+t]<<24|e[1+t]<<16|e[2+t]<<8|e[3+t])>>>0},r.writeUInt32BE=function(e,t,r){e[0+r]=t>>>24,e[1+r]=t>>>16&255,e[2+r]=t>>>8&255,e[3+r]=255&t},r.ip=function(e,t,r,n){for(var i=0,o=0,a=6;a>=0;a-=2){for(var s=0;s<=24;s+=8)i<<=1,i|=t>>>s+a&1;for(s=0;s<=24;s+=8)i<<=1,i|=e>>>s+a&1}for(a=6;a>=0;a-=2){for(s=1;s<=25;s+=8)o<<=1,o|=t>>>s+a&1;for(s=1;s<=25;s+=8)o<<=1,o|=e>>>s+a&1}r[n+0]=i>>>0,r[n+1]=o>>>0},r.rip=function(e,t,r,n){for(var i=0,o=0,a=0;a<4;a++)for(var s=24;s>=0;s-=8)i<<=1,i|=t>>>s+a&1,i<<=1,i|=e>>>s+a&1;for(a=4;a<8;a++)for(s=24;s>=0;s-=8)o<<=1,o|=t>>>s+a&1,o<<=1,o|=e>>>s+a&1;r[n+0]=i>>>0,r[n+1]=o>>>0},r.pc1=function(e,t,r,n){for(var i=0,o=0,a=7;a>=5;a--){for(var s=0;s<=24;s+=8)i<<=1,i|=t>>s+a&1;for(s=0;s<=24;s+=8)i<<=1,i|=e>>s+a&1}for(s=0;s<=24;s+=8)i<<=1,i|=t>>s+a&1;for(a=1;a<=3;a++){for(s=0;s<=24;s+=8)o<<=1,o|=t>>s+a&1;for(s=0;s<=24;s+=8)o<<=1,o|=e>>s+a&1}for(s=0;s<=24;s+=8)o<<=1,o|=e>>s+a&1;r[n+0]=i>>>0,r[n+1]=o>>>0},r.r28shl=function(e,t){return e<>>28-t};var n=[14,11,17,4,27,23,25,0,13,22,7,18,5,9,16,24,2,20,12,21,1,8,15,26,15,4,25,19,9,1,26,16,5,11,23,8,12,7,17,0,22,3,10,14,6,20,27,24];r.pc2=function(e,t,r,i){for(var o=0,a=0,s=n.length>>>1,f=0;f>>n[f]&1;for(f=s;f>>n[f]&1;r[i+0]=o>>>0,r[i+1]=a>>>0},r.expand=function(e,t,r){var n=0,i=0;n=(1&e)<<5|e>>>27;for(var o=23;o>=15;o-=4)n<<=6,n|=e>>>o&63;for(o=11;o>=3;o-=4)i|=e>>>o&63,i<<=6;i|=(31&e)<<1|e>>>31,t[r+0]=n>>>0,t[r+1]=i>>>0};var i=[14,0,4,15,13,7,1,4,2,14,15,2,11,13,8,1,3,10,10,6,6,12,12,11,5,9,9,5,0,3,7,8,4,15,1,12,14,8,8,2,13,4,6,9,2,1,11,7,15,5,12,11,9,3,7,14,3,10,10,0,5,6,0,13,15,3,1,13,8,4,14,7,6,15,11,2,3,8,4,14,9,12,7,0,2,1,13,10,12,6,0,9,5,11,10,5,0,13,14,8,7,10,11,1,10,3,4,15,13,4,1,2,5,11,8,6,12,7,6,12,9,0,3,5,2,14,15,9,10,13,0,7,9,0,14,9,6,3,3,4,15,6,5,10,1,2,13,8,12,5,7,14,11,12,4,11,2,15,8,1,13,1,6,10,4,13,9,0,8,6,15,9,3,8,0,7,11,4,1,15,2,14,12,3,5,11,10,5,14,2,7,12,7,13,13,8,14,11,3,5,0,6,6,15,9,0,10,3,1,4,2,7,8,2,5,12,11,1,12,10,4,14,15,9,10,3,6,15,9,0,0,6,12,10,11,1,7,13,13,8,15,9,1,4,3,5,14,11,5,12,2,7,8,2,4,14,2,14,12,11,4,2,1,12,7,4,10,7,11,13,6,1,8,5,5,0,3,15,15,10,13,3,0,9,14,8,9,6,4,11,2,8,1,12,11,7,10,1,13,14,7,2,8,13,15,6,9,15,12,0,5,9,6,10,3,4,0,5,14,3,12,10,1,15,10,4,15,2,9,7,2,12,6,9,8,5,0,6,13,1,3,13,4,14,14,0,7,11,5,3,11,8,9,4,14,3,15,2,5,12,2,9,8,5,12,15,3,10,7,11,0,14,4,1,10,7,1,6,13,0,11,8,6,13,4,13,11,0,2,11,14,7,15,4,0,9,8,1,13,10,3,14,12,3,9,5,7,12,5,2,10,15,6,8,1,6,1,6,4,11,11,13,13,8,12,1,3,4,7,10,14,7,10,9,15,5,6,0,8,15,0,14,5,2,9,3,2,12,13,1,2,15,8,13,4,8,6,10,15,3,11,7,1,4,10,12,9,5,3,6,14,11,5,0,0,14,12,9,7,2,7,2,11,1,4,14,1,7,9,4,12,10,14,8,2,13,0,15,6,12,10,9,13,0,15,3,3,5,5,6,8,11];r.substitute=function(e,t){for(var r=0,n=0;n<4;n++){r<<=4,r|=i[64*n+(e>>>18-6*n&63)]}for(n=0;n<4;n++){r<<=4,r|=i[256+64*n+(t>>>18-6*n&63)]}return r>>>0};var o=[16,25,12,11,3,20,4,15,31,17,9,6,27,14,1,22,30,24,8,18,0,5,29,23,13,19,2,26,10,21,28,7];r.permute=function(e){for(var t=0,r=0;r>>o[r]&1;return t>>>0},r.padSplit=function(e,t,r){for(var n=e.toString(2);n.lengthe;)r.ishrn(1);if(r.isEven()&&r.iadd(s),r.testn(1)||r.iadd(f),t.cmp(f)){if(!t.cmp(c))for(;r.mod(u).cmp(h);)r.iadd(l)}else for(;r.mod(o).cmp(d);)r.iadd(l);if(y(p=r.shrn(1))&&y(r)&&m(p)&&m(r)&&a.test(p)&&a.test(r))return r}}},{"bn.js":44,"miller-rabin":131,randombytes:152}],93:[function(e,t,r){t.exports={modp1:{gen:"02",prime:"ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a63a3620ffffffffffffffff"},modp2:{gen:"02",prime:"ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece65381ffffffffffffffff"},modp5:{gen:"02",prime:"ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca237327ffffffffffffffff"},modp14:{gen:"02",prime:"ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3be39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf6955817183995497cea956ae515d2261898fa051015728e5a8aacaa68ffffffffffffffff"},modp15:{gen:"02",prime:"ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3be39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf6955817183995497cea956ae515d2261898fa051015728e5a8aaac42dad33170d04507a33a85521abdf1cba64ecfb850458dbef0a8aea71575d060c7db3970f85a6e1e4c7abf5ae8cdb0933d71e8c94e04a25619dcee3d2261ad2ee6bf12ffa06d98a0864d87602733ec86a64521f2b18177b200cbbe117577a615d6c770988c0bad946e208e24fa074e5ab3143db5bfce0fd108e4b82d120a93ad2caffffffffffffffff"},modp16:{gen:"02",prime:"ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3be39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf6955817183995497cea956ae515d2261898fa051015728e5a8aaac42dad33170d04507a33a85521abdf1cba64ecfb850458dbef0a8aea71575d060c7db3970f85a6e1e4c7abf5ae8cdb0933d71e8c94e04a25619dcee3d2261ad2ee6bf12ffa06d98a0864d87602733ec86a64521f2b18177b200cbbe117577a615d6c770988c0bad946e208e24fa074e5ab3143db5bfce0fd108e4b82d120a92108011a723c12a787e6d788719a10bdba5b2699c327186af4e23c1a946834b6150bda2583e9ca2ad44ce8dbbbc2db04de8ef92e8efc141fbecaa6287c59474e6bc05d99b2964fa090c3a2233ba186515be7ed1f612970cee2d7afb81bdd762170481cd0069127d5b05aa993b4ea988d8fddc186ffb7dc90a6c08f4df435c934063199ffffffffffffffff"},modp17:{gen:"02",prime:"ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3be39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf6955817183995497cea956ae515d2261898fa051015728e5a8aaac42dad33170d04507a33a85521abdf1cba64ecfb850458dbef0a8aea71575d060c7db3970f85a6e1e4c7abf5ae8cdb0933d71e8c94e04a25619dcee3d2261ad2ee6bf12ffa06d98a0864d87602733ec86a64521f2b18177b200cbbe117577a615d6c770988c0bad946e208e24fa074e5ab3143db5bfce0fd108e4b82d120a92108011a723c12a787e6d788719a10bdba5b2699c327186af4e23c1a946834b6150bda2583e9ca2ad44ce8dbbbc2db04de8ef92e8efc141fbecaa6287c59474e6bc05d99b2964fa090c3a2233ba186515be7ed1f612970cee2d7afb81bdd762170481cd0069127d5b05aa993b4ea988d8fddc186ffb7dc90a6c08f4df435c93402849236c3fab4d27c7026c1d4dcb2602646dec9751e763dba37bdf8ff9406ad9e530ee5db382f413001aeb06a53ed9027d831179727b0865a8918da3edbebcf9b14ed44ce6cbaced4bb1bdb7f1447e6cc254b332051512bd7af426fb8f401378cd2bf5983ca01c64b92ecf032ea15d1721d03f482d7ce6e74fef6d55e702f46980c82b5a84031900b1c9e59e7c97fbec7e8f323a97a7e36cc88be0f1d45b7ff585ac54bd407b22b4154aacc8f6d7ebf48e1d814cc5ed20f8037e0a79715eef29be32806a1d58bb7c5da76f550aa3d8a1fbff0eb19ccb1a313d55cda56c9ec2ef29632387fe8d76e3c0468043e8f663f4860ee12bf2d5b0b7474d6e694f91e6dcc4024ffffffffffffffff"},modp18:{gen:"02",prime:"ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3be39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf6955817183995497cea956ae515d2261898fa051015728e5a8aaac42dad33170d04507a33a85521abdf1cba64ecfb850458dbef0a8aea71575d060c7db3970f85a6e1e4c7abf5ae8cdb0933d71e8c94e04a25619dcee3d2261ad2ee6bf12ffa06d98a0864d87602733ec86a64521f2b18177b200cbbe117577a615d6c770988c0bad946e208e24fa074e5ab3143db5bfce0fd108e4b82d120a92108011a723c12a787e6d788719a10bdba5b2699c327186af4e23c1a946834b6150bda2583e9ca2ad44ce8dbbbc2db04de8ef92e8efc141fbecaa6287c59474e6bc05d99b2964fa090c3a2233ba186515be7ed1f612970cee2d7afb81bdd762170481cd0069127d5b05aa993b4ea988d8fddc186ffb7dc90a6c08f4df435c93402849236c3fab4d27c7026c1d4dcb2602646dec9751e763dba37bdf8ff9406ad9e530ee5db382f413001aeb06a53ed9027d831179727b0865a8918da3edbebcf9b14ed44ce6cbaced4bb1bdb7f1447e6cc254b332051512bd7af426fb8f401378cd2bf5983ca01c64b92ecf032ea15d1721d03f482d7ce6e74fef6d55e702f46980c82b5a84031900b1c9e59e7c97fbec7e8f323a97a7e36cc88be0f1d45b7ff585ac54bd407b22b4154aacc8f6d7ebf48e1d814cc5ed20f8037e0a79715eef29be32806a1d58bb7c5da76f550aa3d8a1fbff0eb19ccb1a313d55cda56c9ec2ef29632387fe8d76e3c0468043e8f663f4860ee12bf2d5b0b7474d6e694f91e6dbe115974a3926f12fee5e438777cb6a932df8cd8bec4d073b931ba3bc832b68d9dd300741fa7bf8afc47ed2576f6936ba424663aab639c5ae4f5683423b4742bf1c978238f16cbe39d652de3fdb8befc848ad922222e04a4037c0713eb57a81a23f0c73473fc646cea306b4bcbc8862f8385ddfa9d4b7fa2c087e879683303ed5bdd3a062b3cf5b3a278a66d2a13f83f44f82ddf310ee074ab6a364597e899a0255dc164f31cc50846851df9ab48195ded7ea1b1d510bd7ee74d73faf36bc31ecfa268359046f4eb879f924009438b481c6cd7889a002ed5ee382bc9190da6fc026e479558e4475677e9aa9e3050e2765694dfc81f56e880b96e7160c980dd98edd3dfffffffffffffffff"}}},{}],94:[function(e,t,r){"use strict";var n=r;n.version=e("../package.json").version,n.utils=e("./elliptic/utils"),n.rand=e("brorand"),n.curve=e("./elliptic/curve"),n.curves=e("./elliptic/curves"),n.ec=e("./elliptic/ec"),n.eddsa=e("./elliptic/eddsa")},{"../package.json":109,"./elliptic/curve":97,"./elliptic/curves":100,"./elliptic/ec":101,"./elliptic/eddsa":104,"./elliptic/utils":108,brorand:45}],95:[function(e,t,r){"use strict";var n=e("bn.js"),i=e("../utils"),o=i.getNAF,a=i.getJSF,s=i.assert;function f(e,t){this.type=e,this.p=new n(t.p,16),this.red=t.prime?n.red(t.prime):n.mont(this.p),this.zero=new n(0).toRed(this.red),this.one=new n(1).toRed(this.red),this.two=new n(2).toRed(this.red),this.n=t.n&&new n(t.n,16),this.g=t.g&&this.pointFromJSON(t.g,t.gRed),this._wnafT1=new Array(4),this._wnafT2=new Array(4),this._wnafT3=new Array(4),this._wnafT4=new Array(4);var r=this.n&&this.p.div(this.n);!r||r.cmpn(100)>0?this.redN=null:(this._maxwellTrick=!0,this.redN=this.n.toRed(this.red))}function c(e,t){this.curve=e,this.type=t,this.precomputed=null}t.exports=f,f.prototype.point=function(){throw new Error("Not implemented")},f.prototype.validate=function(){throw new Error("Not implemented")},f.prototype._fixedNafMul=function(e,t){s(e.precomputed);var r=e._getDoubles(),n=o(t,1),i=(1<=f;t--)c=(c<<1)+n[t];a.push(c)}for(var u=this.jpoint(null,null,null),h=this.jpoint(null,null,null),d=i;d>0;d--){for(f=0;f=0;c--){for(t=0;c>=0&&0===a[c];c--)t++;if(c>=0&&t++,f=f.dblp(t),c<0)break;var u=a[c];s(0!==u),f="affine"===e.type?u>0?f.mixedAdd(i[u-1>>1]):f.mixedAdd(i[-u-1>>1].neg()):u>0?f.add(i[u-1>>1]):f.add(i[-u-1>>1].neg())}return"affine"===e.type?f.toP():f},f.prototype._wnafMulAdd=function(e,t,r,n,i){for(var s=this._wnafT1,f=this._wnafT2,c=this._wnafT3,u=0,h=0;h=1;h-=2){var l=h-1,p=h;if(1===s[l]&&1===s[p]){var b=[t[l],null,null,t[p]];0===t[l].y.cmp(t[p].y)?(b[1]=t[l].add(t[p]),b[2]=t[l].toJ().mixedAdd(t[p].neg())):0===t[l].y.cmp(t[p].y.redNeg())?(b[1]=t[l].toJ().mixedAdd(t[p]),b[2]=t[l].add(t[p].neg())):(b[1]=t[l].toJ().mixedAdd(t[p]),b[2]=t[l].toJ().mixedAdd(t[p].neg()));var y=[-3,-1,-5,-7,0,7,5,1,3],m=a(r[l],r[p]);u=Math.max(m[0].length,u),c[l]=new Array(u),c[p]=new Array(u);for(var v=0;v=0;h--){for(var E=0;h>=0;){var M=!0;for(v=0;v=0&&E++,_=_.dblp(E),h<0)break;for(v=0;v0?k=f[v][x-1>>1]:x<0&&(k=f[v][-x-1>>1].neg()),_="affine"===k.type?_.mixedAdd(k):_.add(k))}}for(h=0;h=Math.ceil((e.bitLength()+1)/t.step)},c.prototype._getDoubles=function(e,t){if(this.precomputed&&this.precomputed.doubles)return this.precomputed.doubles;for(var r=[this],n=this,i=0;i":""},c.prototype.isInfinity=function(){return 0===this.x.cmpn(0)&&(0===this.y.cmp(this.z)||this.zOne&&0===this.y.cmp(this.curve.c))},c.prototype._extDbl=function(){var e=this.x.redSqr(),t=this.y.redSqr(),r=this.z.redSqr();r=r.redIAdd(r);var n=this.curve._mulA(e),i=this.x.redAdd(this.y).redSqr().redISub(e).redISub(t),o=n.redAdd(t),a=o.redSub(r),s=n.redSub(t),f=i.redMul(a),c=o.redMul(s),u=i.redMul(s),h=a.redMul(o);return this.curve.point(f,c,h,u)},c.prototype._projDbl=function(){var e,t,r,n=this.x.redAdd(this.y).redSqr(),i=this.x.redSqr(),o=this.y.redSqr();if(this.curve.twisted){var a=(c=this.curve._mulA(i)).redAdd(o);if(this.zOne)e=n.redSub(i).redSub(o).redMul(a.redSub(this.curve.two)),t=a.redMul(c.redSub(o)),r=a.redSqr().redSub(a).redSub(a);else{var s=this.z.redSqr(),f=a.redSub(s).redISub(s);e=n.redSub(i).redISub(o).redMul(f),t=a.redMul(c.redSub(o)),r=a.redMul(f)}}else{var c=i.redAdd(o);s=this.curve._mulC(this.z).redSqr(),f=c.redSub(s).redSub(s);e=this.curve._mulC(n.redISub(c)).redMul(f),t=this.curve._mulC(c).redMul(i.redISub(o)),r=c.redMul(f)}return this.curve.point(e,t,r)},c.prototype.dbl=function(){return this.isInfinity()?this:this.curve.extended?this._extDbl():this._projDbl()},c.prototype._extAdd=function(e){var t=this.y.redSub(this.x).redMul(e.y.redSub(e.x)),r=this.y.redAdd(this.x).redMul(e.y.redAdd(e.x)),n=this.t.redMul(this.curve.dd).redMul(e.t),i=this.z.redMul(e.z.redAdd(e.z)),o=r.redSub(t),a=i.redSub(n),s=i.redAdd(n),f=r.redAdd(t),c=o.redMul(a),u=s.redMul(f),h=o.redMul(f),d=a.redMul(s);return this.curve.point(c,u,d,h)},c.prototype._projAdd=function(e){var t,r,n=this.z.redMul(e.z),i=n.redSqr(),o=this.x.redMul(e.x),a=this.y.redMul(e.y),s=this.curve.d.redMul(o).redMul(a),f=i.redSub(s),c=i.redAdd(s),u=this.x.redAdd(this.y).redMul(e.x.redAdd(e.y)).redISub(o).redISub(a),h=n.redMul(f).redMul(u);return this.curve.twisted?(t=n.redMul(c).redMul(a.redSub(this.curve._mulA(o))),r=f.redMul(c)):(t=n.redMul(c).redMul(a.redSub(o)),r=this.curve._mulC(f).redMul(c)),this.curve.point(h,t,r)},c.prototype.add=function(e){return this.isInfinity()?e:e.isInfinity()?this:this.curve.extended?this._extAdd(e):this._projAdd(e)},c.prototype.mul=function(e){return this._hasDoubles(e)?this.curve._fixedNafMul(this,e):this.curve._wnafMul(this,e)},c.prototype.mulAdd=function(e,t,r){return this.curve._wnafMulAdd(1,[this,t],[e,r],2,!1)},c.prototype.jmulAdd=function(e,t,r){return this.curve._wnafMulAdd(1,[this,t],[e,r],2,!0)},c.prototype.normalize=function(){if(this.zOne)return this;var e=this.z.redInvm();return this.x=this.x.redMul(e),this.y=this.y.redMul(e),this.t&&(this.t=this.t.redMul(e)),this.z=this.curve.one,this.zOne=!0,this},c.prototype.neg=function(){return this.curve.point(this.x.redNeg(),this.y,this.z,this.t&&this.t.redNeg())},c.prototype.getX=function(){return this.normalize(),this.x.fromRed()},c.prototype.getY=function(){return this.normalize(),this.y.fromRed()},c.prototype.eq=function(e){return this===e||0===this.getX().cmp(e.getX())&&0===this.getY().cmp(e.getY())},c.prototype.eqXToP=function(e){var t=e.toRed(this.curve.red).redMul(this.z);if(0===this.x.cmp(t))return!0;for(var r=e.clone(),n=this.curve.redN.redMul(this.z);;){if(r.iadd(this.curve.n),r.cmp(this.curve.p)>=0)return!1;if(t.redIAdd(n),0===this.x.cmp(t))return!0}},c.prototype.toP=c.prototype.normalize,c.prototype.mixedAdd=c.prototype.add},{"../utils":108,"./base":95,"bn.js":44,inherits:127}],97:[function(e,t,r){"use strict";var n=r;n.base=e("./base"),n.short=e("./short"),n.mont=e("./mont"),n.edwards=e("./edwards")},{"./base":95,"./edwards":96,"./mont":98,"./short":99}],98:[function(e,t,r){"use strict";var n=e("bn.js"),i=e("inherits"),o=e("./base"),a=e("../utils");function s(e){o.call(this,"mont",e),this.a=new n(e.a,16).toRed(this.red),this.b=new n(e.b,16).toRed(this.red),this.i4=new n(4).toRed(this.red).redInvm(),this.two=new n(2).toRed(this.red),this.a24=this.i4.redMul(this.a.redAdd(this.two))}function f(e,t,r){o.BasePoint.call(this,e,"projective"),null===t&&null===r?(this.x=this.curve.one,this.z=this.curve.zero):(this.x=new n(t,16),this.z=new n(r,16),this.x.red||(this.x=this.x.toRed(this.curve.red)),this.z.red||(this.z=this.z.toRed(this.curve.red)))}i(s,o),t.exports=s,s.prototype.validate=function(e){var t=e.normalize().x,r=t.redSqr(),n=r.redMul(t).redAdd(r.redMul(this.a)).redAdd(t);return 0===n.redSqrt().redSqr().cmp(n)},i(f,o.BasePoint),s.prototype.decodePoint=function(e,t){return this.point(a.toArray(e,t),1)},s.prototype.point=function(e,t){return new f(this,e,t)},s.prototype.pointFromJSON=function(e){return f.fromJSON(this,e)},f.prototype.precompute=function(){},f.prototype._encode=function(){return this.getX().toArray("be",this.curve.p.byteLength())},f.fromJSON=function(e,t){return new f(e,t[0],t[1]||e.one)},f.prototype.inspect=function(){return this.isInfinity()?"":""},f.prototype.isInfinity=function(){return 0===this.z.cmpn(0)},f.prototype.dbl=function(){var e=this.x.redAdd(this.z).redSqr(),t=this.x.redSub(this.z).redSqr(),r=e.redSub(t),n=e.redMul(t),i=r.redMul(t.redAdd(this.curve.a24.redMul(r)));return this.curve.point(n,i)},f.prototype.add=function(){throw new Error("Not supported on Montgomery curve")},f.prototype.diffAdd=function(e,t){var r=this.x.redAdd(this.z),n=this.x.redSub(this.z),i=e.x.redAdd(e.z),o=e.x.redSub(e.z).redMul(r),a=i.redMul(n),s=t.z.redMul(o.redAdd(a).redSqr()),f=t.x.redMul(o.redISub(a).redSqr());return this.curve.point(s,f)},f.prototype.mul=function(e){for(var t=e.clone(),r=this,n=this.curve.point(null,null),i=[];0!==t.cmpn(0);t.iushrn(1))i.push(t.andln(1));for(var o=i.length-1;o>=0;o--)0===i[o]?(r=r.diffAdd(n,this),n=n.dbl()):(n=r.diffAdd(n,this),r=r.dbl());return n},f.prototype.mulAdd=function(){throw new Error("Not supported on Montgomery curve")},f.prototype.jumlAdd=function(){throw new Error("Not supported on Montgomery curve")},f.prototype.eq=function(e){return 0===this.getX().cmp(e.getX())},f.prototype.normalize=function(){return this.x=this.x.redMul(this.z.redInvm()),this.z=this.curve.one,this},f.prototype.getX=function(){return this.normalize(),this.x.fromRed()}},{"../utils":108,"./base":95,"bn.js":44,inherits:127}],99:[function(e,t,r){"use strict";var n=e("../utils"),i=e("bn.js"),o=e("inherits"),a=e("./base"),s=n.assert;function f(e){a.call(this,"short",e),this.a=new i(e.a,16).toRed(this.red),this.b=new i(e.b,16).toRed(this.red),this.tinv=this.two.redInvm(),this.zeroA=0===this.a.fromRed().cmpn(0),this.threeA=0===this.a.fromRed().sub(this.p).cmpn(-3),this.endo=this._getEndomorphism(e),this._endoWnafT1=new Array(4),this._endoWnafT2=new Array(4)}function c(e,t,r,n){a.BasePoint.call(this,e,"affine"),null===t&&null===r?(this.x=null,this.y=null,this.inf=!0):(this.x=new i(t,16),this.y=new i(r,16),n&&(this.x.forceRed(this.curve.red),this.y.forceRed(this.curve.red)),this.x.red||(this.x=this.x.toRed(this.curve.red)),this.y.red||(this.y=this.y.toRed(this.curve.red)),this.inf=!1)}function u(e,t,r,n){a.BasePoint.call(this,e,"jacobian"),null===t&&null===r&&null===n?(this.x=this.curve.one,this.y=this.curve.one,this.z=new i(0)):(this.x=new i(t,16),this.y=new i(r,16),this.z=new i(n,16)),this.x.red||(this.x=this.x.toRed(this.curve.red)),this.y.red||(this.y=this.y.toRed(this.curve.red)),this.z.red||(this.z=this.z.toRed(this.curve.red)),this.zOne=this.z===this.curve.one}o(f,a),t.exports=f,f.prototype._getEndomorphism=function(e){if(this.zeroA&&this.g&&this.n&&1===this.p.modn(3)){var t,r;if(e.beta)t=new i(e.beta,16).toRed(this.red);else{var n=this._getEndoRoots(this.p);t=(t=n[0].cmp(n[1])<0?n[0]:n[1]).toRed(this.red)}if(e.lambda)r=new i(e.lambda,16);else{var o=this._getEndoRoots(this.n);0===this.g.mul(o[0]).x.cmp(this.g.x.redMul(t))?r=o[0]:(r=o[1],s(0===this.g.mul(r).x.cmp(this.g.x.redMul(t))))}return{beta:t,lambda:r,basis:e.basis?e.basis.map(function(e){return{a:new i(e.a,16),b:new i(e.b,16)}}):this._getEndoBasis(r)}}},f.prototype._getEndoRoots=function(e){var t=e===this.p?this.red:i.mont(e),r=new i(2).toRed(t).redInvm(),n=r.redNeg(),o=new i(3).toRed(t).redNeg().redSqrt().redMul(r);return[n.redAdd(o).fromRed(),n.redSub(o).fromRed()]},f.prototype._getEndoBasis=function(e){for(var t,r,n,o,a,s,f,c,u,h=this.n.ushrn(Math.floor(this.n.bitLength()/2)),d=e,l=this.n.clone(),p=new i(1),b=new i(0),y=new i(0),m=new i(1),v=0;0!==d.cmpn(0);){var g=l.div(d);c=l.sub(g.mul(d)),u=y.sub(g.mul(p));var w=m.sub(g.mul(b));if(!n&&c.cmp(h)<0)t=f.neg(),r=p,n=c.neg(),o=u;else if(n&&2==++v)break;f=c,l=d,d=c,y=p,p=u,m=b,b=w}a=c.neg(),s=u;var _=n.sqr().add(o.sqr());return a.sqr().add(s.sqr()).cmp(_)>=0&&(a=t,s=r),n.negative&&(n=n.neg(),o=o.neg()),a.negative&&(a=a.neg(),s=s.neg()),[{a:n,b:o},{a:a,b:s}]},f.prototype._endoSplit=function(e){var t=this.endo.basis,r=t[0],n=t[1],i=n.b.mul(e).divRound(this.n),o=r.b.neg().mul(e).divRound(this.n),a=i.mul(r.a),s=o.mul(n.a),f=i.mul(r.b),c=o.mul(n.b);return{k1:e.sub(a).sub(s),k2:f.add(c).neg()}},f.prototype.pointFromX=function(e,t){(e=new i(e,16)).red||(e=e.toRed(this.red));var r=e.redSqr().redMul(e).redIAdd(e.redMul(this.a)).redIAdd(this.b),n=r.redSqrt();if(0!==n.redSqr().redSub(r).cmp(this.zero))throw new Error("invalid point");var o=n.fromRed().isOdd();return(t&&!o||!t&&o)&&(n=n.redNeg()),this.point(e,n)},f.prototype.validate=function(e){if(e.inf)return!0;var t=e.x,r=e.y,n=this.a.redMul(t),i=t.redSqr().redMul(t).redIAdd(n).redIAdd(this.b);return 0===r.redSqr().redISub(i).cmpn(0)},f.prototype._endoWnafMulAdd=function(e,t,r){for(var n=this._endoWnafT1,i=this._endoWnafT2,o=0;o":""},c.prototype.isInfinity=function(){return this.inf},c.prototype.add=function(e){if(this.inf)return e;if(e.inf)return this;if(this.eq(e))return this.dbl();if(this.neg().eq(e))return this.curve.point(null,null);if(0===this.x.cmp(e.x))return this.curve.point(null,null);var t=this.y.redSub(e.y);0!==t.cmpn(0)&&(t=t.redMul(this.x.redSub(e.x).redInvm()));var r=t.redSqr().redISub(this.x).redISub(e.x),n=t.redMul(this.x.redSub(r)).redISub(this.y);return this.curve.point(r,n)},c.prototype.dbl=function(){if(this.inf)return this;var e=this.y.redAdd(this.y);if(0===e.cmpn(0))return this.curve.point(null,null);var t=this.curve.a,r=this.x.redSqr(),n=e.redInvm(),i=r.redAdd(r).redIAdd(r).redIAdd(t).redMul(n),o=i.redSqr().redISub(this.x.redAdd(this.x)),a=i.redMul(this.x.redSub(o)).redISub(this.y);return this.curve.point(o,a)},c.prototype.getX=function(){return this.x.fromRed()},c.prototype.getY=function(){return this.y.fromRed()},c.prototype.mul=function(e){return e=new i(e,16),this._hasDoubles(e)?this.curve._fixedNafMul(this,e):this.curve.endo?this.curve._endoWnafMulAdd([this],[e]):this.curve._wnafMul(this,e)},c.prototype.mulAdd=function(e,t,r){var n=[this,t],i=[e,r];return this.curve.endo?this.curve._endoWnafMulAdd(n,i):this.curve._wnafMulAdd(1,n,i,2)},c.prototype.jmulAdd=function(e,t,r){var n=[this,t],i=[e,r];return this.curve.endo?this.curve._endoWnafMulAdd(n,i,!0):this.curve._wnafMulAdd(1,n,i,2,!0)},c.prototype.eq=function(e){return this===e||this.inf===e.inf&&(this.inf||0===this.x.cmp(e.x)&&0===this.y.cmp(e.y))},c.prototype.neg=function(e){if(this.inf)return this;var t=this.curve.point(this.x,this.y.redNeg());if(e&&this.precomputed){var r=this.precomputed,n=function(e){return e.neg()};t.precomputed={naf:r.naf&&{wnd:r.naf.wnd,points:r.naf.points.map(n)},doubles:r.doubles&&{step:r.doubles.step,points:r.doubles.points.map(n)}}}return t},c.prototype.toJ=function(){return this.inf?this.curve.jpoint(null,null,null):this.curve.jpoint(this.x,this.y,this.curve.one)},o(u,a.BasePoint),f.prototype.jpoint=function(e,t,r){return new u(this,e,t,r)},u.prototype.toP=function(){if(this.isInfinity())return this.curve.point(null,null);var e=this.z.redInvm(),t=e.redSqr(),r=this.x.redMul(t),n=this.y.redMul(t).redMul(e);return this.curve.point(r,n)},u.prototype.neg=function(){return this.curve.jpoint(this.x,this.y.redNeg(),this.z)},u.prototype.add=function(e){if(this.isInfinity())return e;if(e.isInfinity())return this;var t=e.z.redSqr(),r=this.z.redSqr(),n=this.x.redMul(t),i=e.x.redMul(r),o=this.y.redMul(t.redMul(e.z)),a=e.y.redMul(r.redMul(this.z)),s=n.redSub(i),f=o.redSub(a);if(0===s.cmpn(0))return 0!==f.cmpn(0)?this.curve.jpoint(null,null,null):this.dbl();var c=s.redSqr(),u=c.redMul(s),h=n.redMul(c),d=f.redSqr().redIAdd(u).redISub(h).redISub(h),l=f.redMul(h.redISub(d)).redISub(o.redMul(u)),p=this.z.redMul(e.z).redMul(s);return this.curve.jpoint(d,l,p)},u.prototype.mixedAdd=function(e){if(this.isInfinity())return e.toJ();if(e.isInfinity())return this;var t=this.z.redSqr(),r=this.x,n=e.x.redMul(t),i=this.y,o=e.y.redMul(t).redMul(this.z),a=r.redSub(n),s=i.redSub(o);if(0===a.cmpn(0))return 0!==s.cmpn(0)?this.curve.jpoint(null,null,null):this.dbl();var f=a.redSqr(),c=f.redMul(a),u=r.redMul(f),h=s.redSqr().redIAdd(c).redISub(u).redISub(u),d=s.redMul(u.redISub(h)).redISub(i.redMul(c)),l=this.z.redMul(a);return this.curve.jpoint(h,d,l)},u.prototype.dblp=function(e){if(0===e)return this;if(this.isInfinity())return this;if(!e)return this.dbl();if(this.curve.zeroA||this.curve.threeA){for(var t=this,r=0;r=0)return!1;if(r.redIAdd(i),0===this.x.cmp(r))return!0}},u.prototype.inspect=function(){return this.isInfinity()?"":""},u.prototype.isInfinity=function(){return 0===this.z.cmpn(0)}},{"../utils":108,"./base":95,"bn.js":44,inherits:127}],100:[function(e,t,r){"use strict";var n,i=r,o=e("hash.js"),a=e("./curve"),s=e("./utils").assert;function f(e){"short"===e.type?this.curve=new a.short(e):"edwards"===e.type?this.curve=new a.edwards(e):this.curve=new a.mont(e),this.g=this.curve.g,this.n=this.curve.n,this.hash=e.hash,s(this.g.validate(),"Invalid curve"),s(this.g.mul(this.n).isInfinity(),"Invalid curve, G*N != O")}function c(e,t){Object.defineProperty(i,e,{configurable:!0,enumerable:!0,get:function(){var r=new f(t);return Object.defineProperty(i,e,{configurable:!0,enumerable:!0,value:r}),r}})}i.PresetCurve=f,c("p192",{type:"short",prime:"p192",p:"ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff",a:"ffffffff ffffffff ffffffff fffffffe ffffffff fffffffc",b:"64210519 e59c80e7 0fa7e9ab 72243049 feb8deec c146b9b1",n:"ffffffff ffffffff ffffffff 99def836 146bc9b1 b4d22831",hash:o.sha256,gRed:!1,g:["188da80e b03090f6 7cbf20eb 43a18800 f4ff0afd 82ff1012","07192b95 ffc8da78 631011ed 6b24cdd5 73f977a1 1e794811"]}),c("p224",{type:"short",prime:"p224",p:"ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001",a:"ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff fffffffe",b:"b4050a85 0c04b3ab f5413256 5044b0b7 d7bfd8ba 270b3943 2355ffb4",n:"ffffffff ffffffff ffffffff ffff16a2 e0b8f03e 13dd2945 5c5c2a3d",hash:o.sha256,gRed:!1,g:["b70e0cbd 6bb4bf7f 321390b9 4a03c1d3 56c21122 343280d6 115c1d21","bd376388 b5f723fb 4c22dfe6 cd4375a0 5a074764 44d58199 85007e34"]}),c("p256",{type:"short",prime:null,p:"ffffffff 00000001 00000000 00000000 00000000 ffffffff ffffffff ffffffff",a:"ffffffff 00000001 00000000 00000000 00000000 ffffffff ffffffff fffffffc",b:"5ac635d8 aa3a93e7 b3ebbd55 769886bc 651d06b0 cc53b0f6 3bce3c3e 27d2604b",n:"ffffffff 00000000 ffffffff ffffffff bce6faad a7179e84 f3b9cac2 fc632551",hash:o.sha256,gRed:!1,g:["6b17d1f2 e12c4247 f8bce6e5 63a440f2 77037d81 2deb33a0 f4a13945 d898c296","4fe342e2 fe1a7f9b 8ee7eb4a 7c0f9e16 2bce3357 6b315ece cbb64068 37bf51f5"]}),c("p384",{type:"short",prime:null,p:"ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe ffffffff 00000000 00000000 ffffffff",a:"ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe ffffffff 00000000 00000000 fffffffc",b:"b3312fa7 e23ee7e4 988e056b e3f82d19 181d9c6e fe814112 0314088f 5013875a c656398d 8a2ed19d 2a85c8ed d3ec2aef",n:"ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff c7634d81 f4372ddf 581a0db2 48b0a77a ecec196a ccc52973",hash:o.sha384,gRed:!1,g:["aa87ca22 be8b0537 8eb1c71e f320ad74 6e1d3b62 8ba79b98 59f741e0 82542a38 5502f25d bf55296c 3a545e38 72760ab7","3617de4a 96262c6f 5d9e98bf 9292dc29 f8f41dbd 289a147c e9da3113 b5f0b8c0 0a60b1ce 1d7e819d 7a431d7c 90ea0e5f"]}),c("p521",{type:"short",prime:null,p:"000001ff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff",a:"000001ff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffc",b:"00000051 953eb961 8e1c9a1f 929a21a0 b68540ee a2da725b 99b315f3 b8b48991 8ef109e1 56193951 ec7e937b 1652c0bd 3bb1bf07 3573df88 3d2c34f1 ef451fd4 6b503f00",n:"000001ff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffa 51868783 bf2f966b 7fcc0148 f709a5d0 3bb5c9b8 899c47ae bb6fb71e 91386409",hash:o.sha512,gRed:!1,g:["000000c6 858e06b7 0404e9cd 9e3ecb66 2395b442 9c648139 053fb521 f828af60 6b4d3dba a14b5e77 efe75928 fe1dc127 a2ffa8de 3348b3c1 856a429b f97e7e31 c2e5bd66","00000118 39296a78 9a3bc004 5c8a5fb4 2c7d1bd9 98f54449 579b4468 17afbd17 273e662c 97ee7299 5ef42640 c550b901 3fad0761 353c7086 a272c240 88be9476 9fd16650"]}),c("curve25519",{type:"mont",prime:"p25519",p:"7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed",a:"76d06",b:"1",n:"1000000000000000 0000000000000000 14def9dea2f79cd6 5812631a5cf5d3ed",hash:o.sha256,gRed:!1,g:["9"]}),c("ed25519",{type:"edwards",prime:"p25519",p:"7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed",a:"-1",c:"1",d:"52036cee2b6ffe73 8cc740797779e898 00700a4d4141d8ab 75eb4dca135978a3",n:"1000000000000000 0000000000000000 14def9dea2f79cd6 5812631a5cf5d3ed",hash:o.sha256,gRed:!1,g:["216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a","6666666666666666666666666666666666666666666666666666666666666658"]});try{n=e("./precomputed/secp256k1")}catch(e){n=void 0}c("secp256k1",{type:"short",prime:"k256",p:"ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f",a:"0",b:"7",n:"ffffffff ffffffff ffffffff fffffffe baaedce6 af48a03b bfd25e8c d0364141",h:"1",hash:o.sha256,beta:"7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee",lambda:"5363ad4cc05c30e0a5261c028812645a122e22ea20816678df02967c1b23bd72",basis:[{a:"3086d221a7d46bcde86c90e49284eb15",b:"-e4437ed6010e88286f547fa90abfe4c3"},{a:"114ca50f7a8e2f3f657c1108d9d44cfd8",b:"3086d221a7d46bcde86c90e49284eb15"}],gRed:!1,g:["79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798","483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8",n]})},{"./curve":97,"./precomputed/secp256k1":107,"./utils":108,"hash.js":113}],101:[function(e,t,r){"use strict";var n=e("bn.js"),i=e("hmac-drbg"),o=e("../utils"),a=e("../curves"),s=e("brorand"),f=o.assert,c=e("./key"),u=e("./signature");function h(e){if(!(this instanceof h))return new h(e);"string"==typeof e&&(f(a.hasOwnProperty(e),"Unknown curve "+e),e=a[e]),e instanceof a.PresetCurve&&(e={curve:e}),this.curve=e.curve.curve,this.n=this.curve.n,this.nh=this.n.ushrn(1),this.g=this.curve.g,this.g=e.curve.g,this.g.precompute(e.curve.n.bitLength()+1),this.hash=e.hash||e.curve.hash}t.exports=h,h.prototype.keyPair=function(e){return new c(this,e)},h.prototype.keyFromPrivate=function(e,t){return c.fromPrivate(this,e,t)},h.prototype.keyFromPublic=function(e,t){return c.fromPublic(this,e,t)},h.prototype.genKeyPair=function(e){e||(e={});for(var t=new i({hash:this.hash,pers:e.pers,persEnc:e.persEnc||"utf8",entropy:e.entropy||s(this.hash.hmacStrength),entropyEnc:e.entropy&&e.entropyEnc||"utf8",nonce:this.n.toArray()}),r=this.n.byteLength(),o=this.n.sub(new n(2));;){var a=new n(t.generate(r));if(!(a.cmp(o)>0))return a.iaddn(1),this.keyFromPrivate(a)}},h.prototype._truncateToN=function(e,t){var r=8*e.byteLength()-this.n.bitLength();return r>0&&(e=e.ushrn(r)),!t&&e.cmp(this.n)>=0?e.sub(this.n):e},h.prototype.sign=function(e,t,r,o){"object"==typeof r&&(o=r,r=null),o||(o={}),t=this.keyFromPrivate(t,r),e=this._truncateToN(new n(e,16));for(var a=this.n.byteLength(),s=t.getPrivate().toArray("be",a),f=e.toArray("be",a),c=new i({hash:this.hash,entropy:s,nonce:f,pers:o.pers,persEnc:o.persEnc||"utf8"}),h=this.n.sub(new n(1)),d=0;;d++){var l=o.k?o.k(d):new n(c.generate(this.n.byteLength()));if(!((l=this._truncateToN(l,!0)).cmpn(1)<=0||l.cmp(h)>=0)){var p=this.g.mul(l);if(!p.isInfinity()){var b=p.getX(),y=b.umod(this.n);if(0!==y.cmpn(0)){var m=l.invm(this.n).mul(y.mul(t.getPrivate()).iadd(e));if(0!==(m=m.umod(this.n)).cmpn(0)){var v=(p.getY().isOdd()?1:0)|(0!==b.cmp(y)?2:0);return o.canonical&&m.cmp(this.nh)>0&&(m=this.n.sub(m),v^=1),new u({r:y,s:m,recoveryParam:v})}}}}}},h.prototype.verify=function(e,t,r,i){e=this._truncateToN(new n(e,16)),r=this.keyFromPublic(r,i);var o=(t=new u(t,"hex")).r,a=t.s;if(o.cmpn(1)<0||o.cmp(this.n)>=0)return!1;if(a.cmpn(1)<0||a.cmp(this.n)>=0)return!1;var s,f=a.invm(this.n),c=f.mul(e).umod(this.n),h=f.mul(o).umod(this.n);return this.curve._maxwellTrick?!(s=this.g.jmulAdd(c,r.getPublic(),h)).isInfinity()&&s.eqXToP(o):!(s=this.g.mulAdd(c,r.getPublic(),h)).isInfinity()&&0===s.getX().umod(this.n).cmp(o)},h.prototype.recoverPubKey=function(e,t,r,i){f((3&r)===r,"The recovery param is more than two bits"),t=new u(t,i);var o=this.n,a=new n(e),s=t.r,c=t.s,h=1&r,d=r>>1;if(s.cmp(this.curve.p.umod(this.curve.n))>=0&&d)throw new Error("Unable to find sencond key candinate");s=d?this.curve.pointFromX(s.add(this.curve.n),h):this.curve.pointFromX(s,h);var l=t.r.invm(o),p=o.sub(a).mul(l).umod(o),b=c.mul(l).umod(o);return this.g.mulAdd(p,s,b)},h.prototype.getKeyRecoveryParam=function(e,t,r,n){if(null!==(t=new u(t,n)).recoveryParam)return t.recoveryParam;for(var i=0;i<4;i++){var o;try{o=this.recoverPubKey(e,t,i)}catch(e){continue}if(o.eq(r))return i}throw new Error("Unable to find valid recovery factor")}},{"../curves":100,"../utils":108,"./key":102,"./signature":103,"bn.js":44,brorand:45,"hmac-drbg":125}],102:[function(e,t,r){"use strict";var n=e("bn.js"),i=e("../utils").assert;function o(e,t){this.ec=e,this.priv=null,this.pub=null,t.priv&&this._importPrivate(t.priv,t.privEnc),t.pub&&this._importPublic(t.pub,t.pubEnc)}t.exports=o,o.fromPublic=function(e,t,r){return t instanceof o?t:new o(e,{pub:t,pubEnc:r})},o.fromPrivate=function(e,t,r){return t instanceof o?t:new o(e,{priv:t,privEnc:r})},o.prototype.validate=function(){var e=this.getPublic();return e.isInfinity()?{result:!1,reason:"Invalid public key"}:e.validate()?e.mul(this.ec.curve.n).isInfinity()?{result:!0,reason:null}:{result:!1,reason:"Public key * N != O"}:{result:!1,reason:"Public key is not a point"}},o.prototype.getPublic=function(e,t){return"string"==typeof e&&(t=e,e=null),this.pub||(this.pub=this.ec.g.mul(this.priv)),t?this.pub.encode(t,e):this.pub},o.prototype.getPrivate=function(e){return"hex"===e?this.priv.toString(16,2):this.priv},o.prototype._importPrivate=function(e,t){this.priv=new n(e,t||16),this.priv=this.priv.umod(this.ec.curve.n)},o.prototype._importPublic=function(e,t){if(e.x||e.y)return"mont"===this.ec.curve.type?i(e.x,"Need x coordinate"):"short"!==this.ec.curve.type&&"edwards"!==this.ec.curve.type||i(e.x&&e.y,"Need both x and y coordinate"),void(this.pub=this.ec.curve.point(e.x,e.y));this.pub=this.ec.curve.decodePoint(e,t)},o.prototype.derive=function(e){return e.mul(this.priv).getX()},o.prototype.sign=function(e,t,r){return this.ec.sign(e,this,t,r)},o.prototype.verify=function(e,t){return this.ec.verify(e,t,this)},o.prototype.inspect=function(){return""}},{"../utils":108,"bn.js":44}],103:[function(e,t,r){"use strict";var n=e("bn.js"),i=e("../utils"),o=i.assert;function a(e,t){if(e instanceof a)return e;this._importDER(e,t)||(o(e.r&&e.s,"Signature without r or s"),this.r=new n(e.r,16),this.s=new n(e.s,16),void 0===e.recoveryParam?this.recoveryParam=null:this.recoveryParam=e.recoveryParam)}function s(){this.place=0}function f(e,t){var r=e[t.place++];if(!(128&r))return r;for(var n=15&r,i=0,o=0,a=t.place;o>>3);for(e.push(128|r);--r;)e.push(t>>>(r<<3)&255);e.push(t)}}t.exports=a,a.prototype._importDER=function(e,t){e=i.toArray(e,t);var r=new s;if(48!==e[r.place++])return!1;if(f(e,r)+r.place!==e.length)return!1;if(2!==e[r.place++])return!1;var o=f(e,r),a=e.slice(r.place,o+r.place);if(r.place+=o,2!==e[r.place++])return!1;var c=f(e,r);if(e.length!==c+r.place)return!1;var u=e.slice(r.place,c+r.place);return 0===a[0]&&128&a[1]&&(a=a.slice(1)),0===u[0]&&128&u[1]&&(u=u.slice(1)),this.r=new n(a),this.s=new n(u),this.recoveryParam=null,!0},a.prototype.toDER=function(e){var t=this.r.toArray(),r=this.s.toArray();for(128&t[0]&&(t=[0].concat(t)),128&r[0]&&(r=[0].concat(r)),t=c(t),r=c(r);!(r[0]||128&r[1]);)r=r.slice(1);var n=[2];u(n,t.length),(n=n.concat(t)).push(2),u(n,r.length);var o=n.concat(r),a=[48];return u(a,o.length),a=a.concat(o),i.encode(a,e)}},{"../utils":108,"bn.js":44}],104:[function(e,t,r){"use strict";var n=e("hash.js"),i=e("../curves"),o=e("../utils"),a=o.assert,s=o.parseBytes,f=e("./key"),c=e("./signature");function u(e){if(a("ed25519"===e,"only tested with ed25519 so far"),!(this instanceof u))return new u(e);e=i[e].curve;this.curve=e,this.g=e.g,this.g.precompute(e.n.bitLength()+1),this.pointClass=e.point().constructor,this.encodingLength=Math.ceil(e.n.bitLength()/8),this.hash=n.sha512}t.exports=u,u.prototype.sign=function(e,t){e=s(e);var r=this.keyFromSecret(t),n=this.hashInt(r.messagePrefix(),e),i=this.g.mul(n),o=this.encodePoint(i),a=this.hashInt(o,r.pubBytes(),e).mul(r.priv()),f=n.add(a).umod(this.curve.n);return this.makeSignature({R:i,S:f,Rencoded:o})},u.prototype.verify=function(e,t,r){e=s(e),t=this.makeSignature(t);var n=this.keyFromPublic(r),i=this.hashInt(t.Rencoded(),n.pubBytes(),e),o=this.g.mul(t.S());return t.R().add(n.pub().mul(i)).eq(o)},u.prototype.hashInt=function(){for(var e=this.hash(),t=0;t=0;){var o;if(i.isOdd()){var a=i.andln(n-1);o=a>(n>>1)-1?(n>>1)-a:a,i.isubn(o)}else o=0;r.push(o);for(var s=0!==i.cmpn(0)&&0===i.andln(n-1)?t+1:1,f=1;f0||t.cmpn(-i)>0;){var o,a,s,f=e.andln(3)+n&3,c=t.andln(3)+i&3;3===f&&(f=-1),3===c&&(c=-1),o=0==(1&f)?0:3!=(s=e.andln(7)+n&7)&&5!==s||2!==c?f:-f,r[0].push(o),a=0==(1&c)?0:3!=(s=t.andln(7)+i&7)&&5!==s||2!==f?c:-c,r[1].push(a),2*n===o+1&&(n=1-n),2*i===a+1&&(i=1-i),e.iushrn(1),t.iushrn(1)}return r},n.cachedProperty=function(e,t,r){var n="_"+t;e.prototype[t]=function(){return void 0!==this[n]?this[n]:this[n]=r.call(this)}},n.parseBytes=function(e){return"string"==typeof e?n.toArray(e,"hex"):e},n.intFromLE=function(e){return new i(e,"hex","le")}},{"bn.js":44,"minimalistic-assert":132,"minimalistic-crypto-utils":133}],109:[function(e,t,r){t.exports={name:"elliptic",version:"6.5.0",description:"EC cryptography",main:"lib/elliptic.js",files:["lib"],scripts:{jscs:"jscs benchmarks/*.js lib/*.js lib/**/*.js lib/**/**/*.js test/index.js",jshint:"jscs benchmarks/*.js lib/*.js lib/**/*.js lib/**/**/*.js test/index.js",lint:"npm run jscs && npm run jshint",unit:"istanbul test _mocha --reporter=spec test/index.js",test:"npm run lint && npm run unit",version:"grunt dist && git add dist/"},repository:{type:"git",url:"git@github.com:indutny/elliptic"},keywords:["EC","Elliptic","curve","Cryptography"],author:"Fedor Indutny ",license:"MIT",bugs:{url:"https://github.com/indutny/elliptic/issues"},homepage:"https://github.com/indutny/elliptic",devDependencies:{brfs:"^1.4.3",coveralls:"^2.11.3",grunt:"^0.4.5","grunt-browserify":"^5.0.0","grunt-cli":"^1.2.0","grunt-contrib-connect":"^1.0.0","grunt-contrib-copy":"^1.0.0","grunt-contrib-uglify":"^1.0.1","grunt-mocha-istanbul":"^3.0.1","grunt-saucelabs":"^8.6.2",istanbul:"^0.4.2",jscs:"^2.9.0",jshint:"^2.6.0",mocha:"^2.1.0"},dependencies:{"bn.js":"^4.4.0",brorand:"^1.0.1","hash.js":"^1.0.0","hmac-drbg":"^1.0.0",inherits:"^2.0.1","minimalistic-assert":"^1.0.0","minimalistic-crypto-utils":"^1.0.0"}}},{}],110:[function(e,t,r){var n=Object.create||function(e){var t=function(){};return t.prototype=e,new t},i=Object.keys||function(e){var t=[];for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.push(r);return r},o=Function.prototype.bind||function(e){var t=this;return function(){return t.apply(e,arguments)}};function a(){this._events&&Object.prototype.hasOwnProperty.call(this,"_events")||(this._events=n(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0}t.exports=a,a.EventEmitter=a,a.prototype._events=void 0,a.prototype._maxListeners=void 0;var s,f=10;try{var c={};Object.defineProperty&&Object.defineProperty(c,"x",{value:0}),s=0===c.x}catch(e){s=!1}function u(e){return void 0===e._maxListeners?a.defaultMaxListeners:e._maxListeners}function h(e,t,r,i){var o,a,s;if("function"!=typeof r)throw new TypeError('"listener" argument must be a function');if((a=e._events)?(a.newListener&&(e.emit("newListener",t,r.listener?r.listener:r),a=e._events),s=a[t]):(a=e._events=n(null),e._eventsCount=0),s){if("function"==typeof s?s=a[t]=i?[r,s]:[s,r]:i?s.unshift(r):s.push(r),!s.warned&&(o=u(e))&&o>0&&s.length>o){s.warned=!0;var f=new Error("Possible EventEmitter memory leak detected. "+s.length+' "'+String(t)+'" listeners added. Use emitter.setMaxListeners() to increase limit.');f.name="MaxListenersExceededWarning",f.emitter=e,f.type=t,f.count=s.length,"object"==typeof console&&console.warn&&console.warn("%s: %s",f.name,f.message)}}else s=a[t]=r,++e._eventsCount;return e}function d(){if(!this.fired)switch(this.target.removeListener(this.type,this.wrapFn),this.fired=!0,arguments.length){case 0:return this.listener.call(this.target);case 1:return this.listener.call(this.target,arguments[0]);case 2:return this.listener.call(this.target,arguments[0],arguments[1]);case 3:return this.listener.call(this.target,arguments[0],arguments[1],arguments[2]);default:for(var e=new Array(arguments.length),t=0;t1&&(t=arguments[1]),t instanceof Error)throw t;var f=new Error('Unhandled "error" event. ('+t+")");throw f.context=t,f}if(!(r=a[e]))return!1;var c="function"==typeof r;switch(n=arguments.length){case 1:!function(e,t,r){if(t)e.call(r);else for(var n=e.length,i=y(e,n),o=0;o=0;a--)if(r[a]===t||r[a].listener===t){s=r[a].listener,o=a;break}if(o<0)return this;0===o?r.shift():function(e,t){for(var r=t,n=r+1,i=e.length;n=0;o--)this.removeListener(e,t[o]);return this},a.prototype.listeners=function(e){return p(this,e,!0)},a.prototype.rawListeners=function(e){return p(this,e,!1)},a.listenerCount=function(e,t){return"function"==typeof e.listenerCount?e.listenerCount(t):b.call(e,t)},a.prototype.listenerCount=b,a.prototype.eventNames=function(){return this._eventsCount>0?Reflect.ownKeys(this._events):[]}},{}],111:[function(e,t,r){var n=e("safe-buffer").Buffer,i=e("md5.js");t.exports=function(e,t,r,o){if(n.isBuffer(e)||(e=n.from(e,"binary")),t&&(n.isBuffer(t)||(t=n.from(t,"binary")),8!==t.length))throw new RangeError("salt should be Buffer with 8 byte length");for(var a=r/8,s=n.alloc(a),f=n.alloc(o||0),c=n.alloc(0);a>0||o>0;){var u=new i;u.update(c),u.update(e),t&&u.update(t),c=u.digest();var h=0;if(a>0){var d=s.length-a;h=Math.min(a,c.length),c.copy(s,d,0,h),a-=h}if(h0){var l=f.length-o,p=Math.min(o,c.length-h);c.copy(f,l,h,h+p),o-=p}}return c.fill(0),{key:s,iv:f}}},{"md5.js":130,"safe-buffer":170}],112:[function(e,t,r){"use strict";var n=e("safe-buffer").Buffer,i=e("stream").Transform;function o(e){i.call(this),this._block=n.allocUnsafe(e),this._blockSize=e,this._blockOffset=0,this._length=[0,0,0,0],this._finalized=!1}e("inherits")(o,i),o.prototype._transform=function(e,t,r){var n=null;try{this.update(e,t)}catch(e){n=e}r(n)},o.prototype._flush=function(e){var t=null;try{this.push(this.digest())}catch(e){t=e}e(t)},o.prototype.update=function(e,t){if(function(e,t){if(!n.isBuffer(e)&&"string"!=typeof e)throw new TypeError(t+" must be a string or a buffer")}(e,"Data"),this._finalized)throw new Error("Digest already called");n.isBuffer(e)||(e=n.from(e,t));for(var r=this._block,i=0;this._blockOffset+e.length-i>=this._blockSize;){for(var o=this._blockOffset;o0;++a)this._length[a]+=s,(s=this._length[a]/4294967296|0)>0&&(this._length[a]-=4294967296*s);return this},o.prototype._update=function(){throw new Error("_update is not implemented")},o.prototype.digest=function(e){if(this._finalized)throw new Error("Digest already called");this._finalized=!0;var t=this._digest();void 0!==e&&(t=t.toString(e)),this._block.fill(0),this._blockOffset=0;for(var r=0;r<4;++r)this._length[r]=0;return t},o.prototype._digest=function(){throw new Error("_digest is not implemented")},t.exports=o},{inherits:127,"safe-buffer":170,stream:179}],113:[function(e,t,r){var n=r;n.utils=e("./hash/utils"),n.common=e("./hash/common"),n.sha=e("./hash/sha"),n.ripemd=e("./hash/ripemd"),n.hmac=e("./hash/hmac"),n.sha1=n.sha.sha1,n.sha256=n.sha.sha256,n.sha224=n.sha.sha224,n.sha384=n.sha.sha384,n.sha512=n.sha.sha512,n.ripemd160=n.ripemd.ripemd160},{"./hash/common":114,"./hash/hmac":115,"./hash/ripemd":116,"./hash/sha":117,"./hash/utils":124}],114:[function(e,t,r){"use strict";var n=e("./utils"),i=e("minimalistic-assert");function o(){this.pending=null,this.pendingTotal=0,this.blockSize=this.constructor.blockSize,this.outSize=this.constructor.outSize,this.hmacStrength=this.constructor.hmacStrength,this.padLength=this.constructor.padLength/8,this.endian="big",this._delta8=this.blockSize/8,this._delta32=this.blockSize/32}r.BlockHash=o,o.prototype.update=function(e,t){if(e=n.toArray(e,t),this.pending?this.pending=this.pending.concat(e):this.pending=e,this.pendingTotal+=e.length,this.pending.length>=this._delta8){var r=(e=this.pending).length%this._delta8;this.pending=e.slice(e.length-r,e.length),0===this.pending.length&&(this.pending=null),e=n.join32(e,0,e.length-r,this.endian);for(var i=0;i>>24&255,n[i++]=e>>>16&255,n[i++]=e>>>8&255,n[i++]=255&e}else for(n[i++]=255&e,n[i++]=e>>>8&255,n[i++]=e>>>16&255,n[i++]=e>>>24&255,n[i++]=0,n[i++]=0,n[i++]=0,n[i++]=0,o=8;othis.blockSize&&(e=(new this.Hash).update(e).digest()),i(e.length<=this.blockSize);for(var t=e.length;t>>3},r.g1_256=function(e){return n(e,17)^n(e,19)^e>>>10}},{"../utils":124}],124:[function(e,t,r){"use strict";var n=e("minimalistic-assert"),i=e("inherits");function o(e,t){return 55296==(64512&e.charCodeAt(t))&&(!(t<0||t+1>=e.length)&&56320==(64512&e.charCodeAt(t+1)))}function a(e){return(e>>>24|e>>>8&65280|e<<8&16711680|(255&e)<<24)>>>0}function s(e){return 1===e.length?"0"+e:e}function f(e){return 7===e.length?"0"+e:6===e.length?"00"+e:5===e.length?"000"+e:4===e.length?"0000"+e:3===e.length?"00000"+e:2===e.length?"000000"+e:1===e.length?"0000000"+e:e}r.inherits=i,r.toArray=function(e,t){if(Array.isArray(e))return e.slice();if(!e)return[];var r=[];if("string"==typeof e)if(t){if("hex"===t)for((e=e.replace(/[^a-z0-9]+/gi,"")).length%2!=0&&(e="0"+e),i=0;i>6|192,r[n++]=63&a|128):o(e,i)?(a=65536+((1023&a)<<10)+(1023&e.charCodeAt(++i)),r[n++]=a>>18|240,r[n++]=a>>12&63|128,r[n++]=a>>6&63|128,r[n++]=63&a|128):(r[n++]=a>>12|224,r[n++]=a>>6&63|128,r[n++]=63&a|128)}else for(i=0;i>>0}return a},r.split32=function(e,t){for(var r=new Array(4*e.length),n=0,i=0;n>>24,r[i+1]=o>>>16&255,r[i+2]=o>>>8&255,r[i+3]=255&o):(r[i+3]=o>>>24,r[i+2]=o>>>16&255,r[i+1]=o>>>8&255,r[i]=255&o)}return r},r.rotr32=function(e,t){return e>>>t|e<<32-t},r.rotl32=function(e,t){return e<>>32-t},r.sum32=function(e,t){return e+t>>>0},r.sum32_3=function(e,t,r){return e+t+r>>>0},r.sum32_4=function(e,t,r,n){return e+t+r+n>>>0},r.sum32_5=function(e,t,r,n,i){return e+t+r+n+i>>>0},r.sum64=function(e,t,r,n){var i=e[t],o=n+e[t+1]>>>0,a=(o>>0,e[t+1]=o},r.sum64_hi=function(e,t,r,n){return(t+n>>>0>>0},r.sum64_lo=function(e,t,r,n){return t+n>>>0},r.sum64_4_hi=function(e,t,r,n,i,o,a,s){var f=0,c=t;return f+=(c=c+n>>>0)>>0)>>0)>>0},r.sum64_4_lo=function(e,t,r,n,i,o,a,s){return t+n+o+s>>>0},r.sum64_5_hi=function(e,t,r,n,i,o,a,s,f,c){var u=0,h=t;return u+=(h=h+n>>>0)>>0)>>0)>>0)>>0},r.sum64_5_lo=function(e,t,r,n,i,o,a,s,f,c){return t+n+o+s+c>>>0},r.rotr64_hi=function(e,t,r){return(t<<32-r|e>>>r)>>>0},r.rotr64_lo=function(e,t,r){return(e<<32-r|t>>>r)>>>0},r.shr64_hi=function(e,t,r){return e>>>r},r.shr64_lo=function(e,t,r){return(e<<32-r|t>>>r)>>>0}},{inherits:127,"minimalistic-assert":132}],125:[function(e,t,r){"use strict";var n=e("hash.js"),i=e("minimalistic-crypto-utils"),o=e("minimalistic-assert");function a(e){if(!(this instanceof a))return new a(e);this.hash=e.hash,this.predResist=!!e.predResist,this.outLen=this.hash.outSize,this.minEntropy=e.minEntropy||this.hash.hmacStrength,this._reseed=null,this.reseedInterval=null,this.K=null,this.V=null;var t=i.toArray(e.entropy,e.entropyEnc||"hex"),r=i.toArray(e.nonce,e.nonceEnc||"hex"),n=i.toArray(e.pers,e.persEnc||"hex");o(t.length>=this.minEntropy/8,"Not enough entropy. Minimum is: "+this.minEntropy+" bits"),this._init(t,r,n)}t.exports=a,a.prototype._init=function(e,t,r){var n=e.concat(t).concat(r);this.K=new Array(this.outLen/8),this.V=new Array(this.outLen/8);for(var i=0;i=this.minEntropy/8,"Not enough entropy. Minimum is: "+this.minEntropy+" bits"),this._update(e.concat(r||[])),this._reseed=1},a.prototype.generate=function(e,t,r,n){if(this._reseed>this.reseedInterval)throw new Error("Reseed is required");"string"!=typeof t&&(n=r,r=t,t=null),r&&(r=i.toArray(r,n||"hex"),this._update(r));for(var o=[];o.length>1,u=-7,h=r?i-1:0,d=r?-1:1,l=e[t+h];for(h+=d,o=l&(1<<-u)-1,l>>=-u,u+=s;u>0;o=256*o+e[t+h],h+=d,u-=8);for(a=o&(1<<-u)-1,o>>=-u,u+=n;u>0;a=256*a+e[t+h],h+=d,u-=8);if(0===o)o=1-c;else{if(o===f)return a?NaN:1/0*(l?-1:1);a+=Math.pow(2,n),o-=c}return(l?-1:1)*a*Math.pow(2,o-n)},r.write=function(e,t,r,n,i,o){var a,s,f,c=8*o-i-1,u=(1<>1,d=23===i?Math.pow(2,-24)-Math.pow(2,-77):0,l=n?0:o-1,p=n?1:-1,b=t<0||0===t&&1/t<0?1:0;for(t=Math.abs(t),isNaN(t)||t===1/0?(s=isNaN(t)?1:0,a=u):(a=Math.floor(Math.log(t)/Math.LN2),t*(f=Math.pow(2,-a))<1&&(a--,f*=2),(t+=a+h>=1?d/f:d*Math.pow(2,1-h))*f>=2&&(a++,f/=2),a+h>=u?(s=0,a=u):a+h>=1?(s=(t*f-1)*Math.pow(2,i),a+=h):(s=t*Math.pow(2,h-1)*Math.pow(2,i),a=0));i>=8;e[r+l]=255&s,l+=p,s/=256,i-=8);for(a=a<0;e[r+l]=255&a,l+=p,a/=256,c-=8);e[r+l-p]|=128*b}},{}],127:[function(e,t,r){"function"==typeof Object.create?t.exports=function(e,t){t&&(e.super_=t,e.prototype=Object.create(t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}))}:t.exports=function(e,t){if(t){e.super_=t;var r=function(){};r.prototype=t.prototype,e.prototype=new r,e.prototype.constructor=e}}},{}],128:[function(e,t,r){function n(e){return!!e.constructor&&"function"==typeof e.constructor.isBuffer&&e.constructor.isBuffer(e)}t.exports=function(e){return null!=e&&(n(e)||function(e){return"function"==typeof e.readFloatLE&&"function"==typeof e.slice&&n(e.slice(0,0))}(e)||!!e._isBuffer)}},{}],129:[function(e,t,r){var n={}.toString;t.exports=Array.isArray||function(e){return"[object Array]"==n.call(e)}},{}],130:[function(e,t,r){"use strict";var n=e("inherits"),i=e("hash-base"),o=e("safe-buffer").Buffer,a=new Array(16);function s(){i.call(this,64),this._a=1732584193,this._b=4023233417,this._c=2562383102,this._d=271733878}function f(e,t){return e<>>32-t}function c(e,t,r,n,i,o,a){return f(e+(t&r|~t&n)+i+o|0,a)+t|0}function u(e,t,r,n,i,o,a){return f(e+(t&n|r&~n)+i+o|0,a)+t|0}function h(e,t,r,n,i,o,a){return f(e+(t^r^n)+i+o|0,a)+t|0}function d(e,t,r,n,i,o,a){return f(e+(r^(t|~n))+i+o|0,a)+t|0}n(s,i),s.prototype._update=function(){for(var e=a,t=0;t<16;++t)e[t]=this._block.readInt32LE(4*t);var r=this._a,n=this._b,i=this._c,o=this._d;r=c(r,n,i,o,e[0],3614090360,7),o=c(o,r,n,i,e[1],3905402710,12),i=c(i,o,r,n,e[2],606105819,17),n=c(n,i,o,r,e[3],3250441966,22),r=c(r,n,i,o,e[4],4118548399,7),o=c(o,r,n,i,e[5],1200080426,12),i=c(i,o,r,n,e[6],2821735955,17),n=c(n,i,o,r,e[7],4249261313,22),r=c(r,n,i,o,e[8],1770035416,7),o=c(o,r,n,i,e[9],2336552879,12),i=c(i,o,r,n,e[10],4294925233,17),n=c(n,i,o,r,e[11],2304563134,22),r=c(r,n,i,o,e[12],1804603682,7),o=c(o,r,n,i,e[13],4254626195,12),i=c(i,o,r,n,e[14],2792965006,17),r=u(r,n=c(n,i,o,r,e[15],1236535329,22),i,o,e[1],4129170786,5),o=u(o,r,n,i,e[6],3225465664,9),i=u(i,o,r,n,e[11],643717713,14),n=u(n,i,o,r,e[0],3921069994,20),r=u(r,n,i,o,e[5],3593408605,5),o=u(o,r,n,i,e[10],38016083,9),i=u(i,o,r,n,e[15],3634488961,14),n=u(n,i,o,r,e[4],3889429448,20),r=u(r,n,i,o,e[9],568446438,5),o=u(o,r,n,i,e[14],3275163606,9),i=u(i,o,r,n,e[3],4107603335,14),n=u(n,i,o,r,e[8],1163531501,20),r=u(r,n,i,o,e[13],2850285829,5),o=u(o,r,n,i,e[2],4243563512,9),i=u(i,o,r,n,e[7],1735328473,14),r=h(r,n=u(n,i,o,r,e[12],2368359562,20),i,o,e[5],4294588738,4),o=h(o,r,n,i,e[8],2272392833,11),i=h(i,o,r,n,e[11],1839030562,16),n=h(n,i,o,r,e[14],4259657740,23),r=h(r,n,i,o,e[1],2763975236,4),o=h(o,r,n,i,e[4],1272893353,11),i=h(i,o,r,n,e[7],4139469664,16),n=h(n,i,o,r,e[10],3200236656,23),r=h(r,n,i,o,e[13],681279174,4),o=h(o,r,n,i,e[0],3936430074,11),i=h(i,o,r,n,e[3],3572445317,16),n=h(n,i,o,r,e[6],76029189,23),r=h(r,n,i,o,e[9],3654602809,4),o=h(o,r,n,i,e[12],3873151461,11),i=h(i,o,r,n,e[15],530742520,16),r=d(r,n=h(n,i,o,r,e[2],3299628645,23),i,o,e[0],4096336452,6),o=d(o,r,n,i,e[7],1126891415,10),i=d(i,o,r,n,e[14],2878612391,15),n=d(n,i,o,r,e[5],4237533241,21),r=d(r,n,i,o,e[12],1700485571,6),o=d(o,r,n,i,e[3],2399980690,10),i=d(i,o,r,n,e[10],4293915773,15),n=d(n,i,o,r,e[1],2240044497,21),r=d(r,n,i,o,e[8],1873313359,6),o=d(o,r,n,i,e[15],4264355552,10),i=d(i,o,r,n,e[6],2734768916,15),n=d(n,i,o,r,e[13],1309151649,21),r=d(r,n,i,o,e[4],4149444226,6),o=d(o,r,n,i,e[11],3174756917,10),i=d(i,o,r,n,e[2],718787259,15),n=d(n,i,o,r,e[9],3951481745,21),this._a=this._a+r|0,this._b=this._b+n|0,this._c=this._c+i|0,this._d=this._d+o|0},s.prototype._digest=function(){this._block[this._blockOffset++]=128,this._blockOffset>56&&(this._block.fill(0,this._blockOffset,64),this._update(),this._blockOffset=0),this._block.fill(0,this._blockOffset,56),this._block.writeUInt32LE(this._length[0],56),this._block.writeUInt32LE(this._length[1],60),this._update();var e=o.allocUnsafe(16);return e.writeInt32LE(this._a,0),e.writeInt32LE(this._b,4),e.writeInt32LE(this._c,8),e.writeInt32LE(this._d,12),e},t.exports=s},{"hash-base":112,inherits:127,"safe-buffer":170}],131:[function(e,t,r){var n=e("bn.js"),i=e("brorand");function o(e){this.rand=e||new i.Rand}t.exports=o,o.create=function(e){return new o(e)},o.prototype._randbelow=function(e){var t=e.bitLength(),r=Math.ceil(t/8);do{var i=new n(this.rand.generate(r))}while(i.cmp(e)>=0);return i},o.prototype._randrange=function(e,t){var r=t.sub(e);return e.add(this._randbelow(r))},o.prototype.test=function(e,t,r){var i=e.bitLength(),o=n.mont(e),a=new n(1).toRed(o);t||(t=Math.max(1,i/48|0));for(var s=e.subn(1),f=0;!s.testn(f);f++);for(var c=e.shrn(f),u=s.toRed(o);t>0;t--){var h=this._randrange(new n(2),s);r&&r(h);var d=h.toRed(o).redPow(c);if(0!==d.cmp(a)&&0!==d.cmp(u)){for(var l=1;l0;t--){var u=this._randrange(new n(2),a),h=e.gcd(u);if(0!==h.cmpn(1))return h;var d=u.toRed(i).redPow(f);if(0!==d.cmp(o)&&0!==d.cmp(c)){for(var l=1;l>8,a=255&i;o?r.push(o,a):r.push(a)}return r},n.zero2=i,n.toHex=o,n.encode=function(e,t){return"hex"===t?o(e):e}},{}],134:[function(e,t,r){t.exports={"2.16.840.1.101.3.4.1.1":"aes-128-ecb","2.16.840.1.101.3.4.1.2":"aes-128-cbc","2.16.840.1.101.3.4.1.3":"aes-128-ofb","2.16.840.1.101.3.4.1.4":"aes-128-cfb","2.16.840.1.101.3.4.1.21":"aes-192-ecb","2.16.840.1.101.3.4.1.22":"aes-192-cbc","2.16.840.1.101.3.4.1.23":"aes-192-ofb","2.16.840.1.101.3.4.1.24":"aes-192-cfb","2.16.840.1.101.3.4.1.41":"aes-256-ecb","2.16.840.1.101.3.4.1.42":"aes-256-cbc","2.16.840.1.101.3.4.1.43":"aes-256-ofb","2.16.840.1.101.3.4.1.44":"aes-256-cfb"}},{}],135:[function(e,t,r){"use strict";var n=e("asn1.js");r.certificate=e("./certificate");var i=n.define("RSAPrivateKey",function(){this.seq().obj(this.key("version").int(),this.key("modulus").int(),this.key("publicExponent").int(),this.key("privateExponent").int(),this.key("prime1").int(),this.key("prime2").int(),this.key("exponent1").int(),this.key("exponent2").int(),this.key("coefficient").int())});r.RSAPrivateKey=i;var o=n.define("RSAPublicKey",function(){this.seq().obj(this.key("modulus").int(),this.key("publicExponent").int())});r.RSAPublicKey=o;var a=n.define("SubjectPublicKeyInfo",function(){this.seq().obj(this.key("algorithm").use(s),this.key("subjectPublicKey").bitstr())});r.PublicKey=a;var s=n.define("AlgorithmIdentifier",function(){this.seq().obj(this.key("algorithm").objid(),this.key("none").null_().optional(),this.key("curve").objid().optional(),this.key("params").seq().obj(this.key("p").int(),this.key("q").int(),this.key("g").int()).optional())}),f=n.define("PrivateKeyInfo",function(){this.seq().obj(this.key("version").int(),this.key("algorithm").use(s),this.key("subjectPrivateKey").octstr())});r.PrivateKey=f;var c=n.define("EncryptedPrivateKeyInfo",function(){this.seq().obj(this.key("algorithm").seq().obj(this.key("id").objid(),this.key("decrypt").seq().obj(this.key("kde").seq().obj(this.key("id").objid(),this.key("kdeparams").seq().obj(this.key("salt").octstr(),this.key("iters").int())),this.key("cipher").seq().obj(this.key("algo").objid(),this.key("iv").octstr()))),this.key("subjectPrivateKey").octstr())});r.EncryptedPrivateKey=c;var u=n.define("DSAPrivateKey",function(){this.seq().obj(this.key("version").int(),this.key("p").int(),this.key("q").int(),this.key("g").int(),this.key("pub_key").int(),this.key("priv_key").int())});r.DSAPrivateKey=u,r.DSAparam=n.define("DSAparam",function(){this.int()});var h=n.define("ECPrivateKey",function(){this.seq().obj(this.key("version").int(),this.key("privateKey").octstr(),this.key("parameters").optional().explicit(0).use(d),this.key("publicKey").optional().explicit(1).bitstr())});r.ECPrivateKey=h;var d=n.define("ECParameters",function(){this.choice({namedCurve:this.objid()})});r.signature=n.define("signature",function(){this.seq().obj(this.key("r").int(),this.key("s").int())})},{"./certificate":136,"asn1.js":29}],136:[function(e,t,r){"use strict";var n=e("asn1.js"),i=n.define("Time",function(){this.choice({utcTime:this.utctime(),generalTime:this.gentime()})}),o=n.define("AttributeTypeValue",function(){this.seq().obj(this.key("type").objid(),this.key("value").any())}),a=n.define("AlgorithmIdentifier",function(){this.seq().obj(this.key("algorithm").objid(),this.key("parameters").optional(),this.key("curve").objid().optional())}),s=n.define("SubjectPublicKeyInfo",function(){this.seq().obj(this.key("algorithm").use(a),this.key("subjectPublicKey").bitstr())}),f=n.define("RelativeDistinguishedName",function(){this.setof(o)}),c=n.define("RDNSequence",function(){this.seqof(f)}),u=n.define("Name",function(){this.choice({rdnSequence:this.use(c)})}),h=n.define("Validity",function(){this.seq().obj(this.key("notBefore").use(i),this.key("notAfter").use(i))}),d=n.define("Extension",function(){this.seq().obj(this.key("extnID").objid(),this.key("critical").bool().def(!1),this.key("extnValue").octstr())}),l=n.define("TBSCertificate",function(){this.seq().obj(this.key("version").explicit(0).int().optional(),this.key("serialNumber").int(),this.key("signature").use(a),this.key("issuer").use(u),this.key("validity").use(h),this.key("subject").use(u),this.key("subjectPublicKeyInfo").use(s),this.key("issuerUniqueID").implicit(1).bitstr().optional(),this.key("subjectUniqueID").implicit(2).bitstr().optional(),this.key("extensions").explicit(3).seqof(d).optional())}),p=n.define("X509Certificate",function(){this.seq().obj(this.key("tbsCertificate").use(l),this.key("signatureAlgorithm").use(a),this.key("signatureValue").bitstr())});t.exports=p},{"asn1.js":29}],137:[function(e,t,r){var n=/Proc-Type: 4,ENCRYPTED[\n\r]+DEK-Info: AES-((?:128)|(?:192)|(?:256))-CBC,([0-9A-H]+)[\n\r]+([0-9A-z\n\r\+\/\=]+)[\n\r]+/m,i=/^-----BEGIN ((?:.*? KEY)|CERTIFICATE)-----/m,o=/^-----BEGIN ((?:.*? KEY)|CERTIFICATE)-----([0-9A-z\n\r\+\/\=]+)-----END \1-----$/m,a=e("evp_bytestokey"),s=e("browserify-aes"),f=e("safe-buffer").Buffer;t.exports=function(e,t){var r,c=e.toString(),u=c.match(n);if(u){var h="aes"+u[1],d=f.from(u[2],"hex"),l=f.from(u[3].replace(/[\r\n]/g,""),"base64"),p=a(t,d.slice(0,8),parseInt(u[1],10)).key,b=[],y=s.createDecipheriv(h,p,d);b.push(y.update(l)),b.push(y.final()),r=f.concat(b)}else{var m=c.match(o);r=new f(m[2].replace(/[\r\n]/g,""),"base64")}return{tag:c.match(i)[1],data:r}}},{"browserify-aes":49,evp_bytestokey:111,"safe-buffer":170}],138:[function(e,t,r){var n=e("./asn1"),i=e("./aesid.json"),o=e("./fixProc"),a=e("browserify-aes"),s=e("pbkdf2"),f=e("safe-buffer").Buffer;function c(e){var t;"object"!=typeof e||f.isBuffer(e)||(t=e.passphrase,e=e.key),"string"==typeof e&&(e=f.from(e));var r,c,u=o(e,t),h=u.tag,d=u.data;switch(h){case"CERTIFICATE":c=n.certificate.decode(d,"der").tbsCertificate.subjectPublicKeyInfo;case"PUBLIC KEY":switch(c||(c=n.PublicKey.decode(d,"der")),r=c.algorithm.algorithm.join(".")){case"1.2.840.113549.1.1.1":return n.RSAPublicKey.decode(c.subjectPublicKey.data,"der");case"1.2.840.10045.2.1":return c.subjectPrivateKey=c.subjectPublicKey,{type:"ec",data:c};case"1.2.840.10040.4.1":return c.algorithm.params.pub_key=n.DSAparam.decode(c.subjectPublicKey.data,"der"),{type:"dsa",data:c.algorithm.params};default:throw new Error("unknown key id "+r)}throw new Error("unknown key type "+h);case"ENCRYPTED PRIVATE KEY":d=function(e,t){var r=e.algorithm.decrypt.kde.kdeparams.salt,n=parseInt(e.algorithm.decrypt.kde.kdeparams.iters.toString(),10),o=i[e.algorithm.decrypt.cipher.algo.join(".")],c=e.algorithm.decrypt.cipher.iv,u=e.subjectPrivateKey,h=parseInt(o.split("-")[1],10)/8,d=s.pbkdf2Sync(t,r,n,h,"sha1"),l=a.createDecipheriv(o,d,c),p=[];return p.push(l.update(u)),p.push(l.final()),f.concat(p)}(d=n.EncryptedPrivateKey.decode(d,"der"),t);case"PRIVATE KEY":switch(r=(c=n.PrivateKey.decode(d,"der")).algorithm.algorithm.join(".")){case"1.2.840.113549.1.1.1":return n.RSAPrivateKey.decode(c.subjectPrivateKey,"der");case"1.2.840.10045.2.1":return{curve:c.algorithm.curve,privateKey:n.ECPrivateKey.decode(c.subjectPrivateKey,"der").privateKey};case"1.2.840.10040.4.1":return c.algorithm.params.priv_key=n.DSAparam.decode(c.subjectPrivateKey,"der"),{type:"dsa",params:c.algorithm.params};default:throw new Error("unknown key id "+r)}throw new Error("unknown key type "+h);case"RSA PUBLIC KEY":return n.RSAPublicKey.decode(d,"der");case"RSA PRIVATE KEY":return n.RSAPrivateKey.decode(d,"der");case"DSA PRIVATE KEY":return{type:"dsa",params:n.DSAPrivateKey.decode(d,"der")};case"EC PRIVATE KEY":return{curve:(d=n.ECPrivateKey.decode(d,"der")).parameters.value,privateKey:d.privateKey};default:throw new Error("unknown key type "+h)}}t.exports=c,c.signature=n.signature},{"./aesid.json":134,"./asn1":135,"./fixProc":137,"browserify-aes":49,pbkdf2:139,"safe-buffer":170}],139:[function(e,t,r){r.pbkdf2=e("./lib/async"),r.pbkdf2Sync=e("./lib/sync")},{"./lib/async":140,"./lib/sync":143}],140:[function(e,t,r){(function(r,n){var i,o=e("./precondition"),a=e("./default-encoding"),s=e("./sync"),f=e("safe-buffer").Buffer,c=n.crypto&&n.crypto.subtle,u={sha:"SHA-1","sha-1":"SHA-1",sha1:"SHA-1",sha256:"SHA-256","sha-256":"SHA-256",sha384:"SHA-384","sha-384":"SHA-384","sha-512":"SHA-512",sha512:"SHA-512"},h=[];function d(e,t,r,n,i){return c.importKey("raw",e,{name:"PBKDF2"},!1,["deriveBits"]).then(function(e){return c.deriveBits({name:"PBKDF2",salt:t,iterations:r,hash:{name:i}},e,n<<3)}).then(function(e){return f.from(e)})}t.exports=function(e,t,l,p,b,y){"function"==typeof b&&(y=b,b=void 0);var m=u[(b=b||"sha1").toLowerCase()];if(!m||"function"!=typeof n.Promise)return r.nextTick(function(){var r;try{r=s(e,t,l,p,b)}catch(e){return y(e)}y(null,r)});if(o(e,t,l,p),"function"!=typeof y)throw new Error("No callback provided to pbkdf2");f.isBuffer(e)||(e=f.from(e,a)),f.isBuffer(t)||(t=f.from(t,a)),function(e,t){e.then(function(e){r.nextTick(function(){t(null,e)})},function(e){r.nextTick(function(){t(e)})})}(function(e){if(n.process&&!n.process.browser)return Promise.resolve(!1);if(!c||!c.importKey||!c.deriveBits)return Promise.resolve(!1);if(void 0!==h[e])return h[e];var t=d(i=i||f.alloc(8),i,10,128,e).then(function(){return!0}).catch(function(){return!1});return h[e]=t,t}(m).then(function(r){return r?d(e,t,l,p,m):s(e,t,l,p,b)}),y)}}).call(this,e("_process"),"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"./default-encoding":141,"./precondition":142,"./sync":143,_process:145,"safe-buffer":170}],141:[function(e,t,r){(function(e){var r;e.browser?r="utf-8":r=parseInt(e.version.split(".")[0].slice(1),10)>=6?"utf-8":"binary";t.exports=r}).call(this,e("_process"))},{_process:145}],142:[function(e,t,r){(function(e){var r=Math.pow(2,30)-1;function n(t,r){if("string"!=typeof t&&!e.isBuffer(t))throw new TypeError(r+" must be a buffer or string")}t.exports=function(e,t,i,o){if(n(e,"Password"),n(t,"Salt"),"number"!=typeof i)throw new TypeError("Iterations not a number");if(i<0)throw new TypeError("Bad iterations");if("number"!=typeof o)throw new TypeError("Key length not a number");if(o<0||o>r||o!=o)throw new TypeError("Bad key length")}}).call(this,{isBuffer:e("../../is-buffer/index.js")})},{"../../is-buffer/index.js":128}],143:[function(e,t,r){var n=e("create-hash/md5"),i=e("ripemd160"),o=e("sha.js"),a=e("./precondition"),s=e("./default-encoding"),f=e("safe-buffer").Buffer,c=f.alloc(128),u={md5:16,sha1:20,sha224:28,sha256:32,sha384:48,sha512:64,rmd160:20,ripemd160:20};function h(e,t,r){var a=function(e){return"rmd160"===e||"ripemd160"===e?function(e){return(new i).update(e).digest()}:"md5"===e?n:function(t){return o(e).update(t).digest()}}(e),s="sha512"===e||"sha384"===e?128:64;t.length>s?t=a(t):t.length1)for(var r=1;rp||new a(t).cmp(l.modulus)>=0)throw new Error("decryption error");d=r?c(new a(t),l):s(t,l);var b=u.alloc(p-d.length);if(d=u.concat([b,d],p),4===h)return function(e,t){var r=e.modulus.byteLength(),n=f("sha1").update(u.alloc(0)).digest(),a=n.length;if(0!==t[0])throw new Error("decryption error");var s=t.slice(1,a+1),c=t.slice(a+1),h=o(s,i(c,a)),d=o(c,i(h,r-a-1));if(function(e,t){e=u.from(e),t=u.from(t);var r=0,n=e.length;e.length!==t.length&&(r++,n=Math.min(e.length,t.length));var i=-1;for(;++i=t.length){o++;break}var a=t.slice(2,i-1);("0002"!==n.toString("hex")&&!r||"0001"!==n.toString("hex")&&r)&&o++;a.length<8&&o++;if(o)throw new Error("decryption error");return t.slice(i)}(0,d,r);if(3===h)return d;throw new Error("unknown padding")}},{"./mgf":147,"./withPublic":150,"./xor":151,"bn.js":44,"browserify-rsa":67,"create-hash":79,"parse-asn1":138,"safe-buffer":170}],149:[function(e,t,r){var n=e("parse-asn1"),i=e("randombytes"),o=e("create-hash"),a=e("./mgf"),s=e("./xor"),f=e("bn.js"),c=e("./withPublic"),u=e("browserify-rsa"),h=e("safe-buffer").Buffer;t.exports=function(e,t,r){var d;d=e.padding?e.padding:r?1:4;var l,p=n(e);if(4===d)l=function(e,t){var r=e.modulus.byteLength(),n=t.length,c=o("sha1").update(h.alloc(0)).digest(),u=c.length,d=2*u;if(n>r-d-2)throw new Error("message too long");var l=h.alloc(r-n-d-2),p=r-u-1,b=i(u),y=s(h.concat([c,l,h.alloc(1,1),t],p),a(b,p)),m=s(b,a(y,u));return new f(h.concat([h.alloc(1),m,y],r))}(p,t);else if(1===d)l=function(e,t,r){var n,o=t.length,a=e.modulus.byteLength();if(o>a-11)throw new Error("message too long");n=r?h.alloc(a-o-3,255):function(e){var t,r=h.allocUnsafe(e),n=0,o=i(2*e),a=0;for(;n=0)throw new Error("data too long for modulus")}return r?u(l,p):c(l,p)}},{"./mgf":147,"./withPublic":150,"./xor":151,"bn.js":44,"browserify-rsa":67,"create-hash":79,"parse-asn1":138,randombytes:152,"safe-buffer":170}],150:[function(e,t,r){var n=e("bn.js"),i=e("safe-buffer").Buffer;t.exports=function(e,t){return i.from(e.toRed(n.mont(t.modulus)).redPow(new n(t.publicExponent)).fromRed().toArray())}},{"bn.js":44,"safe-buffer":170}],151:[function(e,t,r){t.exports=function(e,t){for(var r=e.length,n=-1;++no)throw new RangeError("requested too many random bytes");var n=a.allocUnsafe(e);if(e>0)if(e>i)for(var f=0;fu||e<0)throw new TypeError("offset must be a uint32");if(e>f||e>t)throw new RangeError("offset out of range")}function d(e,t,r){if("number"!=typeof e||e!=e)throw new TypeError("size must be a number");if(e>u||e<0)throw new TypeError("size must be a uint32");if(e+t>r||e>f)throw new RangeError("buffer too small")}function l(e,r,n,i){if(t.browser){var o=e.buffer,s=new Uint8Array(o,r,n);return c.getRandomValues(s),i?void t.nextTick(function(){i(null,e)}):e}if(!i)return a(n).copy(e,r),e;a(n,function(t,n){if(t)return i(t);n.copy(e,r),i(null,e)})}c&&c.getRandomValues||!t.browser?(r.randomFill=function(e,t,r,i){if(!(s.isBuffer(e)||e instanceof n.Uint8Array))throw new TypeError('"buf" argument must be a Buffer or Uint8Array');if("function"==typeof t)i=t,t=0,r=e.length;else if("function"==typeof r)i=r,r=e.length-t;else if("function"!=typeof i)throw new TypeError('"cb" argument must be a function');return h(t,e.length),d(r,t,e.length),l(e,t,r,i)},r.randomFillSync=function(e,t,r){void 0===t&&(t=0);if(!(s.isBuffer(e)||e instanceof n.Uint8Array))throw new TypeError('"buf" argument must be a Buffer or Uint8Array');h(t,e.length),void 0===r&&(r=e.length-t);return d(r,t,e.length),l(e,t,r)}):(r.randomFill=i,r.randomFillSync=i)}).call(this,e("_process"),"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{_process:145,randombytes:152,"safe-buffer":170}],154:[function(e,t,r){t.exports=e("./lib/_stream_duplex.js")},{"./lib/_stream_duplex.js":155}],155:[function(e,t,r){"use strict";var n=e("process-nextick-args"),i=Object.keys||function(e){var t=[];for(var r in e)t.push(r);return t};t.exports=h;var o=e("core-util-is");o.inherits=e("inherits");var a=e("./_stream_readable"),s=e("./_stream_writable");o.inherits(h,a);for(var f=i(s.prototype),c=0;c0?("string"==typeof t||a.objectMode||Object.getPrototypeOf(t)===c.prototype||(t=function(e){return c.from(e)}(t)),n?a.endEmitted?e.emit("error",new Error("stream.unshift() after end event")):_(e,a,t,!0):a.ended?e.emit("error",new Error("stream.push() after EOF")):(a.reading=!1,a.decoder&&!r?(t=a.decoder.write(t),a.objectMode||0!==t.length?_(e,a,t,!1):x(e,a)):_(e,a,t,!1))):n||(a.reading=!1));return function(e){return!e.ended&&(e.needReadable||e.lengtht.highWaterMark&&(t.highWaterMark=function(e){return e>=S?e=S:(e--,e|=e>>>1,e|=e>>>2,e|=e>>>4,e|=e>>>8,e|=e>>>16,e++),e}(e)),e<=t.length?e:t.ended?t.length:(t.needReadable=!0,0))}function M(e){var t=e._readableState;t.needReadable=!1,t.emittedReadable||(l("emitReadable",t.flowing),t.emittedReadable=!0,t.sync?i.nextTick(k,e):k(e))}function k(e){l("emit readable"),e.emit("readable"),I(e)}function x(e,t){t.readingMore||(t.readingMore=!0,i.nextTick(A,e,t))}function A(e,t){for(var r=t.length;!t.reading&&!t.flowing&&!t.ended&&t.length=t.length?(r=t.decoder?t.buffer.join(""):1===t.buffer.length?t.buffer.head.data:t.buffer.concat(t.length),t.buffer.clear()):r=function(e,t,r){var n;eo.length?o.length:e;if(a===o.length?i+=o:i+=o.slice(0,e),0===(e-=a)){a===o.length?(++n,r.next?t.head=r.next:t.head=t.tail=null):(t.head=r,r.data=o.slice(a));break}++n}return t.length-=n,i}(e,t):function(e,t){var r=c.allocUnsafe(e),n=t.head,i=1;n.data.copy(r),e-=n.data.length;for(;n=n.next;){var o=n.data,a=e>o.length?o.length:e;if(o.copy(r,r.length-e,0,a),0===(e-=a)){a===o.length?(++i,n.next?t.head=n.next:t.head=t.tail=null):(t.head=n,n.data=o.slice(a));break}++i}return t.length-=i,r}(e,t);return n}(e,t.buffer,t.decoder),r);var r}function T(e){var t=e._readableState;if(t.length>0)throw new Error('"endReadable()" called on non-empty stream');t.endEmitted||(t.ended=!0,i.nextTick(C,t,e))}function C(e,t){e.endEmitted||0!==e.length||(e.endEmitted=!0,t.readable=!1,t.emit("end"))}function P(e,t){for(var r=0,n=e.length;r=t.highWaterMark||t.ended))return l("read: emitReadable",t.length,t.ended),0===t.length&&t.ended?T(this):M(this),null;if(0===(e=E(e,t))&&t.ended)return 0===t.length&&T(this),null;var n,i=t.needReadable;return l("need readable",i),(0===t.length||t.length-e0?R(e,t):null)?(t.needReadable=!0,e=0):t.length-=e,0===t.length&&(t.ended||(t.needReadable=!0),r!==e&&t.ended&&T(this)),null!==n&&this.emit("data",n),n},g.prototype._read=function(e){this.emit("error",new Error("_read() is not implemented"))},g.prototype.pipe=function(e,t){var n=this,o=this._readableState;switch(o.pipesCount){case 0:o.pipes=e;break;case 1:o.pipes=[o.pipes,e];break;default:o.pipes.push(e)}o.pipesCount+=1,l("pipe count=%d opts=%j",o.pipesCount,t);var f=(!t||!1!==t.end)&&e!==r.stdout&&e!==r.stderr?u:g;function c(t,r){l("onunpipe"),t===n&&r&&!1===r.hasUnpiped&&(r.hasUnpiped=!0,l("cleanup"),e.removeListener("close",m),e.removeListener("finish",v),e.removeListener("drain",h),e.removeListener("error",y),e.removeListener("unpipe",c),n.removeListener("end",u),n.removeListener("end",g),n.removeListener("data",b),d=!0,!o.awaitDrain||e._writableState&&!e._writableState.needDrain||h())}function u(){l("onend"),e.end()}o.endEmitted?i.nextTick(f):n.once("end",f),e.on("unpipe",c);var h=function(e){return function(){var t=e._readableState;l("pipeOnDrain",t.awaitDrain),t.awaitDrain&&t.awaitDrain--,0===t.awaitDrain&&s(e,"data")&&(t.flowing=!0,I(e))}}(n);e.on("drain",h);var d=!1;var p=!1;function b(t){l("ondata"),p=!1,!1!==e.write(t)||p||((1===o.pipesCount&&o.pipes===e||o.pipesCount>1&&-1!==P(o.pipes,e))&&!d&&(l("false write response, pause",n._readableState.awaitDrain),n._readableState.awaitDrain++,p=!0),n.pause())}function y(t){l("onerror",t),g(),e.removeListener("error",y),0===s(e,"error")&&e.emit("error",t)}function m(){e.removeListener("finish",v),g()}function v(){l("onfinish"),e.removeListener("close",m),g()}function g(){l("unpipe"),n.unpipe(e)}return n.on("data",b),function(e,t,r){if("function"==typeof e.prependListener)return e.prependListener(t,r);e._events&&e._events[t]?a(e._events[t])?e._events[t].unshift(r):e._events[t]=[r,e._events[t]]:e.on(t,r)}(e,"error",y),e.once("close",m),e.once("finish",v),e.emit("pipe",n),o.flowing||(l("pipe resume"),n.resume()),e},g.prototype.unpipe=function(e){var t=this._readableState,r={hasUnpiped:!1};if(0===t.pipesCount)return this;if(1===t.pipesCount)return e&&e!==t.pipes?this:(e||(e=t.pipes),t.pipes=null,t.pipesCount=0,t.flowing=!1,e&&e.emit("unpipe",this,r),this);if(!e){var n=t.pipes,i=t.pipesCount;t.pipes=null,t.pipesCount=0,t.flowing=!1;for(var o=0;o-1?i:o.nextTick;v.WritableState=m;var c=e("core-util-is");c.inherits=e("inherits");var u={deprecate:e("util-deprecate")},h=e("./internal/streams/stream"),d=e("safe-buffer").Buffer,l=n.Uint8Array||function(){};var p,b=e("./internal/streams/destroy");function y(){}function m(t,r){s=s||e("./_stream_duplex"),t=t||{};var n=r instanceof s;this.objectMode=!!t.objectMode,n&&(this.objectMode=this.objectMode||!!t.writableObjectMode);var i=t.highWaterMark,c=t.writableHighWaterMark,u=this.objectMode?16:16384;this.highWaterMark=i||0===i?i:n&&(c||0===c)?c:u,this.highWaterMark=Math.floor(this.highWaterMark),this.finalCalled=!1,this.needDrain=!1,this.ending=!1,this.ended=!1,this.finished=!1,this.destroyed=!1;var h=!1===t.decodeStrings;this.decodeStrings=!h,this.defaultEncoding=t.defaultEncoding||"utf8",this.length=0,this.writing=!1,this.corked=0,this.sync=!0,this.bufferProcessing=!1,this.onwrite=function(e){!function(e,t){var r=e._writableState,n=r.sync,i=r.writecb;if(function(e){e.writing=!1,e.writecb=null,e.length-=e.writelen,e.writelen=0}(r),t)!function(e,t,r,n,i){--t.pendingcb,r?(o.nextTick(i,n),o.nextTick(M,e,t),e._writableState.errorEmitted=!0,e.emit("error",n)):(i(n),e._writableState.errorEmitted=!0,e.emit("error",n),M(e,t))}(e,r,n,t,i);else{var a=S(r);a||r.corked||r.bufferProcessing||!r.bufferedRequest||_(e,r),n?f(w,e,r,a,i):w(e,r,a,i)}}(r,e)},this.writecb=null,this.writelen=0,this.bufferedRequest=null,this.lastBufferedRequest=null,this.pendingcb=0,this.prefinished=!1,this.errorEmitted=!1,this.bufferedRequestCount=0,this.corkedRequestsFree=new a(this)}function v(t){if(s=s||e("./_stream_duplex"),!(p.call(v,this)||this instanceof s))return new v(t);this._writableState=new m(t,this),this.writable=!0,t&&("function"==typeof t.write&&(this._write=t.write),"function"==typeof t.writev&&(this._writev=t.writev),"function"==typeof t.destroy&&(this._destroy=t.destroy),"function"==typeof t.final&&(this._final=t.final)),h.call(this)}function g(e,t,r,n,i,o,a){t.writelen=n,t.writecb=a,t.writing=!0,t.sync=!0,r?e._writev(i,t.onwrite):e._write(i,o,t.onwrite),t.sync=!1}function w(e,t,r,n){r||function(e,t){0===t.length&&t.needDrain&&(t.needDrain=!1,e.emit("drain"))}(e,t),t.pendingcb--,n(),M(e,t)}function _(e,t){t.bufferProcessing=!0;var r=t.bufferedRequest;if(e._writev&&r&&r.next){var n=t.bufferedRequestCount,i=new Array(n),o=t.corkedRequestsFree;o.entry=r;for(var s=0,f=!0;r;)i[s]=r,r.isBuf||(f=!1),r=r.next,s+=1;i.allBuffers=f,g(e,t,!0,t.length,i,"",o.finish),t.pendingcb++,t.lastBufferedRequest=null,o.next?(t.corkedRequestsFree=o.next,o.next=null):t.corkedRequestsFree=new a(t),t.bufferedRequestCount=0}else{for(;r;){var c=r.chunk,u=r.encoding,h=r.callback;if(g(e,t,!1,t.objectMode?1:c.length,c,u,h),r=r.next,t.bufferedRequestCount--,t.writing)break}null===r&&(t.lastBufferedRequest=null)}t.bufferedRequest=r,t.bufferProcessing=!1}function S(e){return e.ending&&0===e.length&&null===e.bufferedRequest&&!e.finished&&!e.writing}function E(e,t){e._final(function(r){t.pendingcb--,r&&e.emit("error",r),t.prefinished=!0,e.emit("prefinish"),M(e,t)})}function M(e,t){var r=S(t);return r&&(!function(e,t){t.prefinished||t.finalCalled||("function"==typeof e._final?(t.pendingcb++,t.finalCalled=!0,o.nextTick(E,e,t)):(t.prefinished=!0,e.emit("prefinish")))}(e,t),0===t.pendingcb&&(t.finished=!0,e.emit("finish"))),r}c.inherits(v,h),m.prototype.getBuffer=function(){for(var e=this.bufferedRequest,t=[];e;)t.push(e),e=e.next;return t},function(){try{Object.defineProperty(m.prototype,"buffer",{get:u.deprecate(function(){return this.getBuffer()},"_writableState.buffer is deprecated. Use _writableState.getBuffer instead.","DEP0003")})}catch(e){}}(),"function"==typeof Symbol&&Symbol.hasInstance&&"function"==typeof Function.prototype[Symbol.hasInstance]?(p=Function.prototype[Symbol.hasInstance],Object.defineProperty(v,Symbol.hasInstance,{value:function(e){return!!p.call(this,e)||this===v&&(e&&e._writableState instanceof m)}})):p=function(e){return e instanceof this},v.prototype.pipe=function(){this.emit("error",new Error("Cannot pipe, not readable"))},v.prototype.write=function(e,t,r){var n,i=this._writableState,a=!1,s=!i.objectMode&&(n=e,d.isBuffer(n)||n instanceof l);return s&&!d.isBuffer(e)&&(e=function(e){return d.from(e)}(e)),"function"==typeof t&&(r=t,t=null),s?t="buffer":t||(t=i.defaultEncoding),"function"!=typeof r&&(r=y),i.ended?function(e,t){var r=new Error("write after end");e.emit("error",r),o.nextTick(t,r)}(this,r):(s||function(e,t,r,n){var i=!0,a=!1;return null===r?a=new TypeError("May not write null values to stream"):"string"==typeof r||void 0===r||t.objectMode||(a=new TypeError("Invalid non-string/buffer chunk")),a&&(e.emit("error",a),o.nextTick(n,a),i=!1),i}(this,i,e,r))&&(i.pendingcb++,a=function(e,t,r,n,i,o){if(!r){var a=function(e,t,r){e.objectMode||!1===e.decodeStrings||"string"!=typeof t||(t=d.from(t,r));return t}(t,n,i);n!==a&&(r=!0,i="buffer",n=a)}var s=t.objectMode?1:n.length;t.length+=s;var f=t.length-1))throw new TypeError("Unknown encoding: "+e);return this._writableState.defaultEncoding=e,this},Object.defineProperty(v.prototype,"writableHighWaterMark",{enumerable:!1,get:function(){return this._writableState.highWaterMark}}),v.prototype._write=function(e,t,r){r(new Error("_write() is not implemented"))},v.prototype._writev=null,v.prototype.end=function(e,t,r){var n=this._writableState;"function"==typeof e?(r=e,e=null,t=null):"function"==typeof t&&(r=t,t=null),null!=e&&this.write(e,t),n.corked&&(n.corked=1,this.uncork()),n.ending||n.finished||function(e,t,r){t.ending=!0,M(e,t),r&&(t.finished?o.nextTick(r):e.once("finish",r));t.ended=!0,e.writable=!1}(this,n,r)},Object.defineProperty(v.prototype,"destroyed",{get:function(){return void 0!==this._writableState&&this._writableState.destroyed},set:function(e){this._writableState&&(this._writableState.destroyed=e)}}),v.prototype.destroy=b.destroy,v.prototype._undestroy=b.undestroy,v.prototype._destroy=function(e,t){this.end(),t(e)}}).call(this,e("_process"),"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{},e("timers").setImmediate)},{"./_stream_duplex":155,"./internal/streams/destroy":161,"./internal/streams/stream":162,_process:145,"core-util-is":77,inherits:127,"process-nextick-args":144,"safe-buffer":163,timers:181,"util-deprecate":182}],160:[function(e,t,r){"use strict";var n=e("safe-buffer").Buffer,i=e("util");t.exports=function(){function e(){!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e),this.head=null,this.tail=null,this.length=0}return e.prototype.push=function(e){var t={data:e,next:null};this.length>0?this.tail.next=t:this.head=t,this.tail=t,++this.length},e.prototype.unshift=function(e){var t={data:e,next:this.head};0===this.length&&(this.tail=t),this.head=t,++this.length},e.prototype.shift=function(){if(0!==this.length){var e=this.head.data;return 1===this.length?this.head=this.tail=null:this.head=this.head.next,--this.length,e}},e.prototype.clear=function(){this.head=this.tail=null,this.length=0},e.prototype.join=function(e){if(0===this.length)return"";for(var t=this.head,r=""+t.data;t=t.next;)r+=e+t.data;return r},e.prototype.concat=function(e){if(0===this.length)return n.alloc(0);if(1===this.length)return this.head.data;for(var t,r,i,o=n.allocUnsafe(e>>>0),a=this.head,s=0;a;)t=a.data,r=o,i=s,t.copy(r,i),s+=a.data.length,a=a.next;return o},e}(),i&&i.inspect&&i.inspect.custom&&(t.exports.prototype[i.inspect.custom]=function(){var e=i.inspect({length:this.length});return this.constructor.name+" "+e})},{"safe-buffer":163,util:46}],161:[function(e,t,r){"use strict";var n=e("process-nextick-args");function i(e,t){e.emit("error",t)}t.exports={destroy:function(e,t){var r=this,o=this._readableState&&this._readableState.destroyed,a=this._writableState&&this._writableState.destroyed;return o||a?(t?t(e):!e||this._writableState&&this._writableState.errorEmitted||n.nextTick(i,this,e),this):(this._readableState&&(this._readableState.destroyed=!0),this._writableState&&(this._writableState.destroyed=!0),this._destroy(e||null,function(e){!t&&e?(n.nextTick(i,r,e),r._writableState&&(r._writableState.errorEmitted=!0)):t&&t(e)}),this)},undestroy:function(){this._readableState&&(this._readableState.destroyed=!1,this._readableState.reading=!1,this._readableState.ended=!1,this._readableState.endEmitted=!1),this._writableState&&(this._writableState.destroyed=!1,this._writableState.ended=!1,this._writableState.ending=!1,this._writableState.finished=!1,this._writableState.errorEmitted=!1)}}},{"process-nextick-args":144}],162:[function(e,t,r){t.exports=e("events").EventEmitter},{events:110}],163:[function(e,t,r){var n=e("buffer"),i=n.Buffer;function o(e,t){for(var r in e)t[r]=e[r]}function a(e,t,r){return i(e,t,r)}i.from&&i.alloc&&i.allocUnsafe&&i.allocUnsafeSlow?t.exports=n:(o(n,r),r.Buffer=a),o(i,a),a.from=function(e,t,r){if("number"==typeof e)throw new TypeError("Argument must not be a number");return i(e,t,r)},a.alloc=function(e,t,r){if("number"!=typeof e)throw new TypeError("Argument must be a number");var n=i(e);return void 0!==t?"string"==typeof r?n.fill(t,r):n.fill(t):n.fill(0),n},a.allocUnsafe=function(e){if("number"!=typeof e)throw new TypeError("Argument must be a number");return i(e)},a.allocUnsafeSlow=function(e){if("number"!=typeof e)throw new TypeError("Argument must be a number");return n.SlowBuffer(e)}},{buffer:75}],164:[function(e,t,r){"use strict";var n=e("safe-buffer").Buffer,i=n.isEncoding||function(e){switch((e=""+e)&&e.toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":case"raw":return!0;default:return!1}};function o(e){var t;switch(this.encoding=function(e){var t=function(e){if(!e)return"utf8";for(var t;;)switch(e){case"utf8":case"utf-8":return"utf8";case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return"utf16le";case"latin1":case"binary":return"latin1";case"base64":case"ascii":case"hex":return e;default:if(t)return;e=(""+e).toLowerCase(),t=!0}}(e);if("string"!=typeof t&&(n.isEncoding===i||!i(e)))throw new Error("Unknown encoding: "+e);return t||e}(e),this.encoding){case"utf16le":this.text=f,this.end=c,t=4;break;case"utf8":this.fillLast=s,t=4;break;case"base64":this.text=u,this.end=h,t=3;break;default:return this.write=d,void(this.end=l)}this.lastNeed=0,this.lastTotal=0,this.lastChar=n.allocUnsafe(t)}function a(e){return e<=127?0:e>>5==6?2:e>>4==14?3:e>>3==30?4:e>>6==2?-1:-2}function s(e){var t=this.lastTotal-this.lastNeed,r=function(e,t,r){if(128!=(192&t[0]))return e.lastNeed=0,"�";if(e.lastNeed>1&&t.length>1){if(128!=(192&t[1]))return e.lastNeed=1,"�";if(e.lastNeed>2&&t.length>2&&128!=(192&t[2]))return e.lastNeed=2,"�"}}(this,e);return void 0!==r?r:this.lastNeed<=e.length?(e.copy(this.lastChar,t,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal)):(e.copy(this.lastChar,t,0,e.length),void(this.lastNeed-=e.length))}function f(e,t){if((e.length-t)%2==0){var r=e.toString("utf16le",t);if(r){var n=r.charCodeAt(r.length-1);if(n>=55296&&n<=56319)return this.lastNeed=2,this.lastTotal=4,this.lastChar[0]=e[e.length-2],this.lastChar[1]=e[e.length-1],r.slice(0,-1)}return r}return this.lastNeed=1,this.lastTotal=2,this.lastChar[0]=e[e.length-1],e.toString("utf16le",t,e.length-1)}function c(e){var t=e&&e.length?this.write(e):"";if(this.lastNeed){var r=this.lastTotal-this.lastNeed;return t+this.lastChar.toString("utf16le",0,r)}return t}function u(e,t){var r=(e.length-t)%3;return 0===r?e.toString("base64",t):(this.lastNeed=3-r,this.lastTotal=3,1===r?this.lastChar[0]=e[e.length-1]:(this.lastChar[0]=e[e.length-2],this.lastChar[1]=e[e.length-1]),e.toString("base64",t,e.length-r))}function h(e){var t=e&&e.length?this.write(e):"";return this.lastNeed?t+this.lastChar.toString("base64",0,3-this.lastNeed):t}function d(e){return e.toString(this.encoding)}function l(e){return e&&e.length?this.write(e):""}r.StringDecoder=o,o.prototype.write=function(e){if(0===e.length)return"";var t,r;if(this.lastNeed){if(void 0===(t=this.fillLast(e)))return"";r=this.lastNeed,this.lastNeed=0}else r=0;return r=0)return i>0&&(e.lastNeed=i-1),i;if(--n=0)return i>0&&(e.lastNeed=i-2),i;if(--n=0)return i>0&&(2===i?i=0:e.lastNeed=i-3),i;return 0}(this,e,t);if(!this.lastNeed)return e.toString("utf8",t);this.lastTotal=r;var n=e.length-(r-this.lastNeed);return e.copy(this.lastChar,0,n),e.toString("utf8",t,n)},o.prototype.fillLast=function(e){if(this.lastNeed<=e.length)return e.copy(this.lastChar,this.lastTotal-this.lastNeed,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal);e.copy(this.lastChar,this.lastTotal-this.lastNeed,0,e.length),this.lastNeed-=e.length}},{"safe-buffer":163}],165:[function(e,t,r){t.exports=e("./readable").PassThrough},{"./readable":166}],166:[function(e,t,r){(r=t.exports=e("./lib/_stream_readable.js")).Stream=r,r.Readable=r,r.Writable=e("./lib/_stream_writable.js"),r.Duplex=e("./lib/_stream_duplex.js"),r.Transform=e("./lib/_stream_transform.js"),r.PassThrough=e("./lib/_stream_passthrough.js")},{"./lib/_stream_duplex.js":155,"./lib/_stream_passthrough.js":156,"./lib/_stream_readable.js":157,"./lib/_stream_transform.js":158,"./lib/_stream_writable.js":159}],167:[function(e,t,r){t.exports=e("./readable").Transform},{"./readable":166}],168:[function(e,t,r){t.exports=e("./lib/_stream_writable.js")},{"./lib/_stream_writable.js":159}],169:[function(e,t,r){"use strict";var n=e("buffer").Buffer,i=e("inherits"),o=e("hash-base"),a=new Array(16),s=[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,7,4,13,1,10,6,15,3,12,0,9,5,2,14,11,8,3,10,14,4,9,15,8,1,2,7,0,6,13,11,5,12,1,9,11,10,0,8,12,4,13,3,7,15,14,5,6,2,4,0,5,9,7,12,2,10,14,1,3,8,11,6,15,13],f=[5,14,7,0,9,2,11,4,13,6,15,8,1,10,3,12,6,11,3,7,0,13,5,10,14,15,8,12,4,9,1,2,15,5,1,3,7,14,6,9,11,8,12,2,10,0,4,13,8,6,4,1,3,11,15,0,5,12,2,13,9,7,10,14,12,15,10,4,1,5,8,7,6,2,13,14,0,3,9,11],c=[11,14,15,12,5,8,7,9,11,13,14,15,6,7,9,8,7,6,8,13,11,9,7,15,7,12,15,9,11,7,13,12,11,13,6,7,14,9,13,15,14,8,13,6,5,12,7,5,11,12,14,15,14,15,9,8,9,14,5,6,8,6,5,12,9,15,5,11,6,8,13,12,5,12,13,14,11,8,5,6],u=[8,9,9,11,13,15,15,5,7,7,8,11,14,14,12,6,9,13,15,7,12,8,9,11,7,7,12,7,6,15,13,11,9,7,15,11,8,6,6,14,12,13,5,14,13,13,7,5,15,5,8,11,14,14,6,14,6,9,12,9,12,5,15,8,8,5,12,9,12,5,14,6,8,13,6,5,15,13,11,11],h=[0,1518500249,1859775393,2400959708,2840853838],d=[1352829926,1548603684,1836072691,2053994217,0];function l(){o.call(this,64),this._a=1732584193,this._b=4023233417,this._c=2562383102,this._d=271733878,this._e=3285377520}function p(e,t){return e<>>32-t}function b(e,t,r,n,i,o,a,s){return p(e+(t^r^n)+o+a|0,s)+i|0}function y(e,t,r,n,i,o,a,s){return p(e+(t&r|~t&n)+o+a|0,s)+i|0}function m(e,t,r,n,i,o,a,s){return p(e+((t|~r)^n)+o+a|0,s)+i|0}function v(e,t,r,n,i,o,a,s){return p(e+(t&n|r&~n)+o+a|0,s)+i|0}function g(e,t,r,n,i,o,a,s){return p(e+(t^(r|~n))+o+a|0,s)+i|0}i(l,o),l.prototype._update=function(){for(var e=a,t=0;t<16;++t)e[t]=this._block.readInt32LE(4*t);for(var r=0|this._a,n=0|this._b,i=0|this._c,o=0|this._d,l=0|this._e,w=0|this._a,_=0|this._b,S=0|this._c,E=0|this._d,M=0|this._e,k=0;k<80;k+=1){var x,A;k<16?(x=b(r,n,i,o,l,e[s[k]],h[0],c[k]),A=g(w,_,S,E,M,e[f[k]],d[0],u[k])):k<32?(x=y(r,n,i,o,l,e[s[k]],h[1],c[k]),A=v(w,_,S,E,M,e[f[k]],d[1],u[k])):k<48?(x=m(r,n,i,o,l,e[s[k]],h[2],c[k]),A=m(w,_,S,E,M,e[f[k]],d[2],u[k])):k<64?(x=v(r,n,i,o,l,e[s[k]],h[3],c[k]),A=y(w,_,S,E,M,e[f[k]],d[3],u[k])):(x=g(r,n,i,o,l,e[s[k]],h[4],c[k]),A=b(w,_,S,E,M,e[f[k]],d[4],u[k])),r=l,l=o,o=p(i,10),i=n,n=x,w=M,M=E,E=p(S,10),S=_,_=A}var j=this._b+i+E|0;this._b=this._c+o+M|0,this._c=this._d+l+w|0,this._d=this._e+r+_|0,this._e=this._a+n+S|0,this._a=j},l.prototype._digest=function(){this._block[this._blockOffset++]=128,this._blockOffset>56&&(this._block.fill(0,this._blockOffset,64),this._update(),this._blockOffset=0),this._block.fill(0,this._blockOffset,56),this._block.writeUInt32LE(this._length[0],56),this._block.writeUInt32LE(this._length[1],60),this._update();var e=n.alloc?n.alloc(20):new n(20);return e.writeInt32LE(this._a,0),e.writeInt32LE(this._b,4),e.writeInt32LE(this._c,8),e.writeInt32LE(this._d,12),e.writeInt32LE(this._e,16),e},t.exports=l},{buffer:75,"hash-base":112,inherits:127}],170:[function(e,t,r){var n=e("buffer"),i=n.Buffer;function o(e,t){for(var r in e)t[r]=e[r]}function a(e,t,r){return i(e,t,r)}i.from&&i.alloc&&i.allocUnsafe&&i.allocUnsafeSlow?t.exports=n:(o(n,r),r.Buffer=a),a.prototype=Object.create(i.prototype),o(i,a),a.from=function(e,t,r){if("number"==typeof e)throw new TypeError("Argument must not be a number");return i(e,t,r)},a.alloc=function(e,t,r){if("number"!=typeof e)throw new TypeError("Argument must be a number");var n=i(e);return void 0!==t?"string"==typeof r?n.fill(t,r):n.fill(t):n.fill(0),n},a.allocUnsafe=function(e){if("number"!=typeof e)throw new TypeError("Argument must be a number");return i(e)},a.allocUnsafeSlow=function(e){if("number"!=typeof e)throw new TypeError("Argument must be a number");return n.SlowBuffer(e)}},{buffer:75}],171:[function(e,t,r){var n=e("safe-buffer").Buffer;function i(e,t){this._block=n.alloc(e),this._finalSize=t,this._blockSize=e,this._len=0}i.prototype.update=function(e,t){"string"==typeof e&&(t=t||"utf8",e=n.from(e,t));for(var r=this._block,i=this._blockSize,o=e.length,a=this._len,s=0;s=this._finalSize&&(this._update(this._block),this._block.fill(0));var r=8*this._len;if(r<=4294967295)this._block.writeUInt32BE(r,this._blockSize-4);else{var n=(4294967295&r)>>>0,i=(r-n)/4294967296;this._block.writeUInt32BE(i,this._blockSize-8),this._block.writeUInt32BE(n,this._blockSize-4)}this._update(this._block);var o=this._hash();return e?o.toString(e):o},i.prototype._update=function(){throw new Error("_update must be implemented by subclass")},t.exports=i},{"safe-buffer":170}],172:[function(e,t,r){(r=t.exports=function(e){e=e.toLowerCase();var t=r[e];if(!t)throw new Error(e+" is not supported (we accept pull requests)");return new t}).sha=e("./sha"),r.sha1=e("./sha1"),r.sha224=e("./sha224"),r.sha256=e("./sha256"),r.sha384=e("./sha384"),r.sha512=e("./sha512")},{"./sha":173,"./sha1":174,"./sha224":175,"./sha256":176,"./sha384":177,"./sha512":178}],173:[function(e,t,r){var n=e("inherits"),i=e("./hash"),o=e("safe-buffer").Buffer,a=[1518500249,1859775393,-1894007588,-899497514],s=new Array(80);function f(){this.init(),this._w=s,i.call(this,64,56)}function c(e){return e<<30|e>>>2}function u(e,t,r,n){return 0===e?t&r|~t&n:2===e?t&r|t&n|r&n:t^r^n}n(f,i),f.prototype.init=function(){return this._a=1732584193,this._b=4023233417,this._c=2562383102,this._d=271733878,this._e=3285377520,this},f.prototype._update=function(e){for(var t,r=this._w,n=0|this._a,i=0|this._b,o=0|this._c,s=0|this._d,f=0|this._e,h=0;h<16;++h)r[h]=e.readInt32BE(4*h);for(;h<80;++h)r[h]=r[h-3]^r[h-8]^r[h-14]^r[h-16];for(var d=0;d<80;++d){var l=~~(d/20),p=0|((t=n)<<5|t>>>27)+u(l,i,o,s)+f+r[d]+a[l];f=s,s=o,o=c(i),i=n,n=p}this._a=n+this._a|0,this._b=i+this._b|0,this._c=o+this._c|0,this._d=s+this._d|0,this._e=f+this._e|0},f.prototype._hash=function(){var e=o.allocUnsafe(20);return e.writeInt32BE(0|this._a,0),e.writeInt32BE(0|this._b,4),e.writeInt32BE(0|this._c,8),e.writeInt32BE(0|this._d,12),e.writeInt32BE(0|this._e,16),e},t.exports=f},{"./hash":171,inherits:127,"safe-buffer":170}],174:[function(e,t,r){var n=e("inherits"),i=e("./hash"),o=e("safe-buffer").Buffer,a=[1518500249,1859775393,-1894007588,-899497514],s=new Array(80);function f(){this.init(),this._w=s,i.call(this,64,56)}function c(e){return e<<5|e>>>27}function u(e){return e<<30|e>>>2}function h(e,t,r,n){return 0===e?t&r|~t&n:2===e?t&r|t&n|r&n:t^r^n}n(f,i),f.prototype.init=function(){return this._a=1732584193,this._b=4023233417,this._c=2562383102,this._d=271733878,this._e=3285377520,this},f.prototype._update=function(e){for(var t,r=this._w,n=0|this._a,i=0|this._b,o=0|this._c,s=0|this._d,f=0|this._e,d=0;d<16;++d)r[d]=e.readInt32BE(4*d);for(;d<80;++d)r[d]=(t=r[d-3]^r[d-8]^r[d-14]^r[d-16])<<1|t>>>31;for(var l=0;l<80;++l){var p=~~(l/20),b=c(n)+h(p,i,o,s)+f+r[l]+a[p]|0;f=s,s=o,o=u(i),i=n,n=b}this._a=n+this._a|0,this._b=i+this._b|0,this._c=o+this._c|0,this._d=s+this._d|0,this._e=f+this._e|0},f.prototype._hash=function(){var e=o.allocUnsafe(20);return e.writeInt32BE(0|this._a,0),e.writeInt32BE(0|this._b,4),e.writeInt32BE(0|this._c,8),e.writeInt32BE(0|this._d,12),e.writeInt32BE(0|this._e,16),e},t.exports=f},{"./hash":171,inherits:127,"safe-buffer":170}],175:[function(e,t,r){var n=e("inherits"),i=e("./sha256"),o=e("./hash"),a=e("safe-buffer").Buffer,s=new Array(64);function f(){this.init(),this._w=s,o.call(this,64,56)}n(f,i),f.prototype.init=function(){return this._a=3238371032,this._b=914150663,this._c=812702999,this._d=4144912697,this._e=4290775857,this._f=1750603025,this._g=1694076839,this._h=3204075428,this},f.prototype._hash=function(){var e=a.allocUnsafe(28);return e.writeInt32BE(this._a,0),e.writeInt32BE(this._b,4),e.writeInt32BE(this._c,8),e.writeInt32BE(this._d,12),e.writeInt32BE(this._e,16),e.writeInt32BE(this._f,20),e.writeInt32BE(this._g,24),e},t.exports=f},{"./hash":171,"./sha256":176,inherits:127,"safe-buffer":170}],176:[function(e,t,r){var n=e("inherits"),i=e("./hash"),o=e("safe-buffer").Buffer,a=[1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298],s=new Array(64);function f(){this.init(),this._w=s,i.call(this,64,56)}function c(e,t,r){return r^e&(t^r)}function u(e,t,r){return e&t|r&(e|t)}function h(e){return(e>>>2|e<<30)^(e>>>13|e<<19)^(e>>>22|e<<10)}function d(e){return(e>>>6|e<<26)^(e>>>11|e<<21)^(e>>>25|e<<7)}function l(e){return(e>>>7|e<<25)^(e>>>18|e<<14)^e>>>3}n(f,i),f.prototype.init=function(){return this._a=1779033703,this._b=3144134277,this._c=1013904242,this._d=2773480762,this._e=1359893119,this._f=2600822924,this._g=528734635,this._h=1541459225,this},f.prototype._update=function(e){for(var t,r=this._w,n=0|this._a,i=0|this._b,o=0|this._c,s=0|this._d,f=0|this._e,p=0|this._f,b=0|this._g,y=0|this._h,m=0;m<16;++m)r[m]=e.readInt32BE(4*m);for(;m<64;++m)r[m]=0|(((t=r[m-2])>>>17|t<<15)^(t>>>19|t<<13)^t>>>10)+r[m-7]+l(r[m-15])+r[m-16];for(var v=0;v<64;++v){var g=y+d(f)+c(f,p,b)+a[v]+r[v]|0,w=h(n)+u(n,i,o)|0;y=b,b=p,p=f,f=s+g|0,s=o,o=i,i=n,n=g+w|0}this._a=n+this._a|0,this._b=i+this._b|0,this._c=o+this._c|0,this._d=s+this._d|0,this._e=f+this._e|0,this._f=p+this._f|0,this._g=b+this._g|0,this._h=y+this._h|0},f.prototype._hash=function(){var e=o.allocUnsafe(32);return e.writeInt32BE(this._a,0),e.writeInt32BE(this._b,4),e.writeInt32BE(this._c,8),e.writeInt32BE(this._d,12),e.writeInt32BE(this._e,16),e.writeInt32BE(this._f,20),e.writeInt32BE(this._g,24),e.writeInt32BE(this._h,28),e},t.exports=f},{"./hash":171,inherits:127,"safe-buffer":170}],177:[function(e,t,r){var n=e("inherits"),i=e("./sha512"),o=e("./hash"),a=e("safe-buffer").Buffer,s=new Array(160);function f(){this.init(),this._w=s,o.call(this,128,112)}n(f,i),f.prototype.init=function(){return this._ah=3418070365,this._bh=1654270250,this._ch=2438529370,this._dh=355462360,this._eh=1731405415,this._fh=2394180231,this._gh=3675008525,this._hh=1203062813,this._al=3238371032,this._bl=914150663,this._cl=812702999,this._dl=4144912697,this._el=4290775857,this._fl=1750603025,this._gl=1694076839,this._hl=3204075428,this},f.prototype._hash=function(){var e=a.allocUnsafe(48);function t(t,r,n){e.writeInt32BE(t,n),e.writeInt32BE(r,n+4)}return t(this._ah,this._al,0),t(this._bh,this._bl,8),t(this._ch,this._cl,16),t(this._dh,this._dl,24),t(this._eh,this._el,32),t(this._fh,this._fl,40),e},t.exports=f},{"./hash":171,"./sha512":178,inherits:127,"safe-buffer":170}],178:[function(e,t,r){var n=e("inherits"),i=e("./hash"),o=e("safe-buffer").Buffer,a=[1116352408,3609767458,1899447441,602891725,3049323471,3964484399,3921009573,2173295548,961987163,4081628472,1508970993,3053834265,2453635748,2937671579,2870763221,3664609560,3624381080,2734883394,310598401,1164996542,607225278,1323610764,1426881987,3590304994,1925078388,4068182383,2162078206,991336113,2614888103,633803317,3248222580,3479774868,3835390401,2666613458,4022224774,944711139,264347078,2341262773,604807628,2007800933,770255983,1495990901,1249150122,1856431235,1555081692,3175218132,1996064986,2198950837,2554220882,3999719339,2821834349,766784016,2952996808,2566594879,3210313671,3203337956,3336571891,1034457026,3584528711,2466948901,113926993,3758326383,338241895,168717936,666307205,1188179964,773529912,1546045734,1294757372,1522805485,1396182291,2643833823,1695183700,2343527390,1986661051,1014477480,2177026350,1206759142,2456956037,344077627,2730485921,1290863460,2820302411,3158454273,3259730800,3505952657,3345764771,106217008,3516065817,3606008344,3600352804,1432725776,4094571909,1467031594,275423344,851169720,430227734,3100823752,506948616,1363258195,659060556,3750685593,883997877,3785050280,958139571,3318307427,1322822218,3812723403,1537002063,2003034995,1747873779,3602036899,1955562222,1575990012,2024104815,1125592928,2227730452,2716904306,2361852424,442776044,2428436474,593698344,2756734187,3733110249,3204031479,2999351573,3329325298,3815920427,3391569614,3928383900,3515267271,566280711,3940187606,3454069534,4118630271,4000239992,116418474,1914138554,174292421,2731055270,289380356,3203993006,460393269,320620315,685471733,587496836,852142971,1086792851,1017036298,365543100,1126000580,2618297676,1288033470,3409855158,1501505948,4234509866,1607167915,987167468,1816402316,1246189591],s=new Array(160);function f(){this.init(),this._w=s,i.call(this,128,112)}function c(e,t,r){return r^e&(t^r)}function u(e,t,r){return e&t|r&(e|t)}function h(e,t){return(e>>>28|t<<4)^(t>>>2|e<<30)^(t>>>7|e<<25)}function d(e,t){return(e>>>14|t<<18)^(e>>>18|t<<14)^(t>>>9|e<<23)}function l(e,t){return(e>>>1|t<<31)^(e>>>8|t<<24)^e>>>7}function p(e,t){return(e>>>1|t<<31)^(e>>>8|t<<24)^(e>>>7|t<<25)}function b(e,t){return(e>>>19|t<<13)^(t>>>29|e<<3)^e>>>6}function y(e,t){return(e>>>19|t<<13)^(t>>>29|e<<3)^(e>>>6|t<<26)}function m(e,t){return e>>>0>>0?1:0}n(f,i),f.prototype.init=function(){return this._ah=1779033703,this._bh=3144134277,this._ch=1013904242,this._dh=2773480762,this._eh=1359893119,this._fh=2600822924,this._gh=528734635,this._hh=1541459225,this._al=4089235720,this._bl=2227873595,this._cl=4271175723,this._dl=1595750129,this._el=2917565137,this._fl=725511199,this._gl=4215389547,this._hl=327033209,this},f.prototype._update=function(e){for(var t=this._w,r=0|this._ah,n=0|this._bh,i=0|this._ch,o=0|this._dh,s=0|this._eh,f=0|this._fh,v=0|this._gh,g=0|this._hh,w=0|this._al,_=0|this._bl,S=0|this._cl,E=0|this._dl,M=0|this._el,k=0|this._fl,x=0|this._gl,A=0|this._hl,j=0;j<32;j+=2)t[j]=e.readInt32BE(4*j),t[j+1]=e.readInt32BE(4*j+4);for(;j<160;j+=2){var B=t[j-30],I=t[j-30+1],R=l(B,I),T=p(I,B),C=b(B=t[j-4],I=t[j-4+1]),P=y(I,B),O=t[j-14],D=t[j-14+1],N=t[j-32],L=t[j-32+1],U=T+D|0,q=R+O+m(U,T)|0;q=(q=q+C+m(U=U+P|0,P)|0)+N+m(U=U+L|0,L)|0,t[j]=q,t[j+1]=U}for(var z=0;z<160;z+=2){q=t[z],U=t[z+1];var K=u(r,n,i),F=u(w,_,S),H=h(r,w),V=h(w,r),W=d(s,M),J=d(M,s),X=a[z],$=a[z+1],G=c(s,f,v),Z=c(M,k,x),Y=A+J|0,Q=g+W+m(Y,A)|0;Q=(Q=(Q=Q+G+m(Y=Y+Z|0,Z)|0)+X+m(Y=Y+$|0,$)|0)+q+m(Y=Y+U|0,U)|0;var ee=V+F|0,te=H+K+m(ee,V)|0;g=v,A=x,v=f,x=k,f=s,k=M,s=o+Q+m(M=E+Y|0,E)|0,o=i,E=S,i=n,S=_,n=r,_=w,r=Q+te+m(w=Y+ee|0,Y)|0}this._al=this._al+w|0,this._bl=this._bl+_|0,this._cl=this._cl+S|0,this._dl=this._dl+E|0,this._el=this._el+M|0,this._fl=this._fl+k|0,this._gl=this._gl+x|0,this._hl=this._hl+A|0,this._ah=this._ah+r+m(this._al,w)|0,this._bh=this._bh+n+m(this._bl,_)|0,this._ch=this._ch+i+m(this._cl,S)|0,this._dh=this._dh+o+m(this._dl,E)|0,this._eh=this._eh+s+m(this._el,M)|0,this._fh=this._fh+f+m(this._fl,k)|0,this._gh=this._gh+v+m(this._gl,x)|0,this._hh=this._hh+g+m(this._hl,A)|0},f.prototype._hash=function(){var e=o.allocUnsafe(64);function t(t,r,n){e.writeInt32BE(t,n),e.writeInt32BE(r,n+4)}return t(this._ah,this._al,0),t(this._bh,this._bl,8),t(this._ch,this._cl,16),t(this._dh,this._dl,24),t(this._eh,this._el,32),t(this._fh,this._fl,40),t(this._gh,this._gl,48),t(this._hh,this._hl,56),e},t.exports=f},{"./hash":171,inherits:127,"safe-buffer":170}],179:[function(e,t,r){t.exports=i;var n=e("events").EventEmitter;function i(){n.call(this)}e("inherits")(i,n),i.Readable=e("readable-stream/readable.js"),i.Writable=e("readable-stream/writable.js"),i.Duplex=e("readable-stream/duplex.js"),i.Transform=e("readable-stream/transform.js"),i.PassThrough=e("readable-stream/passthrough.js"),i.Stream=i,i.prototype.pipe=function(e,t){var r=this;function i(t){e.writable&&!1===e.write(t)&&r.pause&&r.pause()}function o(){r.readable&&r.resume&&r.resume()}r.on("data",i),e.on("drain",o),e._isStdio||t&&!1===t.end||(r.on("end",s),r.on("close",f));var a=!1;function s(){a||(a=!0,e.end())}function f(){a||(a=!0,"function"==typeof e.destroy&&e.destroy())}function c(e){if(u(),0===n.listenerCount(this,"error"))throw e}function u(){r.removeListener("data",i),e.removeListener("drain",o),r.removeListener("end",s),r.removeListener("close",f),r.removeListener("error",c),e.removeListener("error",c),r.removeListener("end",u),r.removeListener("close",u),e.removeListener("close",u)}return r.on("error",c),e.on("error",c),r.on("end",u),r.on("close",u),e.on("close",u),e.emit("pipe",r),e}},{events:110,inherits:127,"readable-stream/duplex.js":154,"readable-stream/passthrough.js":165,"readable-stream/readable.js":166,"readable-stream/transform.js":167,"readable-stream/writable.js":168}],180:[function(e,t,r){arguments[4][164][0].apply(r,arguments)},{dup:164,"safe-buffer":170}],181:[function(e,t,r){(function(t,n){var i=e("process/browser.js").nextTick,o=Function.prototype.apply,a=Array.prototype.slice,s={},f=0;function c(e,t){this._id=e,this._clearFn=t}r.setTimeout=function(){return new c(o.call(setTimeout,window,arguments),clearTimeout)},r.setInterval=function(){return new c(o.call(setInterval,window,arguments),clearInterval)},r.clearTimeout=r.clearInterval=function(e){e.close()},c.prototype.unref=c.prototype.ref=function(){},c.prototype.close=function(){this._clearFn.call(window,this._id)},r.enroll=function(e,t){clearTimeout(e._idleTimeoutId),e._idleTimeout=t},r.unenroll=function(e){clearTimeout(e._idleTimeoutId),e._idleTimeout=-1},r._unrefActive=r.active=function(e){clearTimeout(e._idleTimeoutId);var t=e._idleTimeout;t>=0&&(e._idleTimeoutId=setTimeout(function(){e._onTimeout&&e._onTimeout()},t))},r.setImmediate="function"==typeof t?t:function(e){var t=f++,n=!(arguments.length<2)&&a.call(arguments,1);return s[t]=!0,i(function(){s[t]&&(n?e.apply(null,n):e.call(null),r.clearImmediate(t))}),t},r.clearImmediate="function"==typeof n?n:function(e){delete s[e]}}).call(this,e("timers").setImmediate,e("timers").clearImmediate)},{"process/browser.js":145,timers:181}],182:[function(e,t,r){(function(e){function r(t){try{if(!e.localStorage)return!1}catch(e){return!1}var r=e.localStorage[t];return null!=r&&"true"===String(r).toLowerCase()}t.exports=function(e,t){if(r("noDeprecation"))return e;var n=!1;return function(){if(!n){if(r("throwDeprecation"))throw new Error(t);r("traceDeprecation")?console.trace(t):console.warn(t),n=!0}return e.apply(this,arguments)}}}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{}],183:[function(e,t,r){"function"==typeof Object.create?t.exports=function(e,t){e.super_=t,e.prototype=Object.create(t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}})}:t.exports=function(e,t){e.super_=t;var r=function(){};r.prototype=t.prototype,e.prototype=new r,e.prototype.constructor=e}},{}],184:[function(e,t,r){t.exports=function(e){return e&&"object"==typeof e&&"function"==typeof e.copy&&"function"==typeof e.fill&&"function"==typeof e.readUInt8}},{}],185:[function(e,t,r){(function(t,n){var i=/%[sdj%]/g;r.format=function(e){if(!m(e)){for(var t=[],r=0;r=o)return e;switch(e){case"%s":return String(n[r++]);case"%d":return Number(n[r++]);case"%j":try{return JSON.stringify(n[r++])}catch(e){return"[Circular]"}default:return e}}),f=n[r];r=3&&(n.depth=arguments[2]),arguments.length>=4&&(n.colors=arguments[3]),p(t)?n.showHidden=t:t&&r._extend(n,t),v(n.showHidden)&&(n.showHidden=!1),v(n.depth)&&(n.depth=2),v(n.colors)&&(n.colors=!1),v(n.customInspect)&&(n.customInspect=!0),n.colors&&(n.stylize=f),u(n,e,n.depth)}function f(e,t){var r=s.styles[t];return r?"["+s.colors[r][0]+"m"+e+"["+s.colors[r][1]+"m":e}function c(e,t){return e}function u(e,t,n){if(e.customInspect&&t&&E(t.inspect)&&t.inspect!==r.inspect&&(!t.constructor||t.constructor.prototype!==t)){var i=t.inspect(n,e);return m(i)||(i=u(e,i,n)),i}var o=function(e,t){if(v(t))return e.stylize("undefined","undefined");if(m(t)){var r="'"+JSON.stringify(t).replace(/^"|"$/g,"").replace(/'/g,"\\'").replace(/\\"/g,'"')+"'";return e.stylize(r,"string")}if(y(t))return e.stylize(""+t,"number");if(p(t))return e.stylize(""+t,"boolean");if(b(t))return e.stylize("null","null")}(e,t);if(o)return o;var a=Object.keys(t),s=function(e){var t={};return e.forEach(function(e,r){t[e]=!0}),t}(a);if(e.showHidden&&(a=Object.getOwnPropertyNames(t)),S(t)&&(a.indexOf("message")>=0||a.indexOf("description")>=0))return h(t);if(0===a.length){if(E(t)){var f=t.name?": "+t.name:"";return e.stylize("[Function"+f+"]","special")}if(g(t))return e.stylize(RegExp.prototype.toString.call(t),"regexp");if(_(t))return e.stylize(Date.prototype.toString.call(t),"date");if(S(t))return h(t)}var c,w="",M=!1,k=["{","}"];(l(t)&&(M=!0,k=["[","]"]),E(t))&&(w=" [Function"+(t.name?": "+t.name:"")+"]");return g(t)&&(w=" "+RegExp.prototype.toString.call(t)),_(t)&&(w=" "+Date.prototype.toUTCString.call(t)),S(t)&&(w=" "+h(t)),0!==a.length||M&&0!=t.length?n<0?g(t)?e.stylize(RegExp.prototype.toString.call(t),"regexp"):e.stylize("[Object]","special"):(e.seen.push(t),c=M?function(e,t,r,n,i){for(var o=[],a=0,s=t.length;a=0&&0,e+t.replace(/\u001b\[\d\d?m/g,"").length+1},0)>60)return r[0]+(""===t?"":t+"\n ")+" "+e.join(",\n ")+" "+r[1];return r[0]+t+" "+e.join(", ")+" "+r[1]}(c,w,k)):k[0]+w+k[1]}function h(e){return"["+Error.prototype.toString.call(e)+"]"}function d(e,t,r,n,i,o){var a,s,f;if((f=Object.getOwnPropertyDescriptor(t,i)||{value:t[i]}).get?s=f.set?e.stylize("[Getter/Setter]","special"):e.stylize("[Getter]","special"):f.set&&(s=e.stylize("[Setter]","special")),A(n,i)||(a="["+i+"]"),s||(e.seen.indexOf(f.value)<0?(s=b(r)?u(e,f.value,null):u(e,f.value,r-1)).indexOf("\n")>-1&&(s=o?s.split("\n").map(function(e){return" "+e}).join("\n").substr(2):"\n"+s.split("\n").map(function(e){return" "+e}).join("\n")):s=e.stylize("[Circular]","special")),v(a)){if(o&&i.match(/^\d+$/))return s;(a=JSON.stringify(""+i)).match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)?(a=a.substr(1,a.length-2),a=e.stylize(a,"name")):(a=a.replace(/'/g,"\\'").replace(/\\"/g,'"').replace(/(^"|"$)/g,"'"),a=e.stylize(a,"string"))}return a+": "+s}function l(e){return Array.isArray(e)}function p(e){return"boolean"==typeof e}function b(e){return null===e}function y(e){return"number"==typeof e}function m(e){return"string"==typeof e}function v(e){return void 0===e}function g(e){return w(e)&&"[object RegExp]"===M(e)}function w(e){return"object"==typeof e&&null!==e}function _(e){return w(e)&&"[object Date]"===M(e)}function S(e){return w(e)&&("[object Error]"===M(e)||e instanceof Error)}function E(e){return"function"==typeof e}function M(e){return Object.prototype.toString.call(e)}function k(e){return e<10?"0"+e.toString(10):e.toString(10)}r.debuglog=function(e){if(v(o)&&(o=t.env.NODE_DEBUG||""),e=e.toUpperCase(),!a[e])if(new RegExp("\\b"+e+"\\b","i").test(o)){var n=t.pid;a[e]=function(){var t=r.format.apply(r,arguments);console.error("%s %d: %s",e,n,t)}}else a[e]=function(){};return a[e]},r.inspect=s,s.colors={bold:[1,22],italic:[3,23],underline:[4,24],inverse:[7,27],white:[37,39],grey:[90,39],black:[30,39],blue:[34,39],cyan:[36,39],green:[32,39],magenta:[35,39],red:[31,39],yellow:[33,39]},s.styles={special:"cyan",number:"yellow",boolean:"yellow",undefined:"grey",null:"bold",string:"green",date:"magenta",regexp:"red"},r.isArray=l,r.isBoolean=p,r.isNull=b,r.isNullOrUndefined=function(e){return null==e},r.isNumber=y,r.isString=m,r.isSymbol=function(e){return"symbol"==typeof e},r.isUndefined=v,r.isRegExp=g,r.isObject=w,r.isDate=_,r.isError=S,r.isFunction=E,r.isPrimitive=function(e){return null===e||"boolean"==typeof e||"number"==typeof e||"string"==typeof e||"symbol"==typeof e||void 0===e},r.isBuffer=e("./support/isBuffer");var x=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function A(e,t){return Object.prototype.hasOwnProperty.call(e,t)}r.log=function(){var e,t;console.log("%s - %s",(e=new Date,t=[k(e.getHours()),k(e.getMinutes()),k(e.getSeconds())].join(":"),[e.getDate(),x[e.getMonth()],t].join(" ")),r.format.apply(r,arguments))},r.inherits=e("inherits"),r._extend=function(e,t){if(!t||!w(t))return e;for(var r=Object.keys(t),n=r.length;n--;)e[r[n]]=t[r[n]];return e}}).call(this,e("_process"),"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"./support/isBuffer":184,_process:145,inherits:183}],186:[function(require,module,exports){var indexOf=function(e,t){if(e.indexOf)return e.indexOf(t);for(var r=0;r) { + return { + type: ReduxActionTypes.INSTALL_LIBRARY_INIT, + payload, + }; +} + +export function toggleInstaller(payload: boolean) { + return { + type: ReduxActionTypes.TOGGLE_INSTALLER, + payload, + }; +} + +export function uninstallLibraryInit(payload: TJSLibrary) { + return { + type: ReduxActionTypes.UNINSTALL_LIBRARY_INIT, + payload, + }; +} + +export function clearInstalls() { + return { + type: ReduxActionTypes.CLEAR_PROCESSED_INSTALLS, + }; +} diff --git a/app/client/src/api/LibraryAPI.tsx b/app/client/src/api/LibraryAPI.tsx new file mode 100644 index 0000000000..c1cdc38edc --- /dev/null +++ b/app/client/src/api/LibraryAPI.tsx @@ -0,0 +1,30 @@ +import { APP_MODE } from "entities/App"; +import { TJSLibrary } from "workers/common/JSLibrary"; +import Api from "./Api"; + +export default class LibraryApi extends Api { + static base_url = "v1/libraries"; + + static getUpdateLibraryBaseURL = (applicationId: string) => + `${LibraryApi.base_url}/${applicationId}`; + + static addLibrary( + applicationId: string, + library: Partial & { defs: string }, + ) { + const url = LibraryApi.getUpdateLibraryBaseURL(applicationId) + "/add"; + return Api.patch(url, library); + } + + static removeLibrary(applicationId: string, library: Partial) { + const url = LibraryApi.getUpdateLibraryBaseURL(applicationId) + "/remove"; + return Api.patch(url, library); + } + + static getLibraries(applicationId: string, mode: APP_MODE) { + const url = `${LibraryApi.getUpdateLibraryBaseURL(applicationId)}${ + mode === APP_MODE.PUBLISHED ? "/view" : "" + }`; + return Api.get(url); + } +} diff --git a/app/client/src/ce/constants/ReduxActionConstants.tsx b/app/client/src/ce/constants/ReduxActionConstants.tsx index 7f74f39e71..336c1a47cc 100644 --- a/app/client/src/ce/constants/ReduxActionConstants.tsx +++ b/app/client/src/ce/constants/ReduxActionConstants.tsx @@ -18,6 +18,15 @@ export const ReduxSagaChannels = { }; export const ReduxActionTypes = { + TOGGLE_INSTALLER: "TOGGLE_INSTALLER", + FETCH_JS_LIBRARIES_INIT: "FETCH_JS_LIBRARIES_INIT", + FETCH_JS_LIBRARIES_SUCCESS: "FETCH_JS_LIBRARIES_SUCCESS", + CLEAR_PROCESSED_INSTALLS: "CLEAR_PROCESSED_INSTALLS", + INSTALL_LIBRARY_INIT: "INSTALL_LIBRARY_INIT", + INSTALL_LIBRARY_START: "INSTALL_LIBRARY_START", + INSTALL_LIBRARY_SUCCESS: "INSTALL_LIBRARY_SUCCESS", + UNINSTALL_LIBRARY_INIT: "UNINSTALL_LIBRARY_INIT", + UNINSTALL_LIBRARY_SUCCESS: "UNINSTALL_LIBRARY_SUCCESS", GIT_DISCARD_CHANGES_SUCCESS: "GIT_DISCARD_CHANGES_SUCCESS", GIT_DISCARD_CHANGES: "GIT_DISCARD_CHANGES", DELETE_BRANCH_INIT: "DELETE_BRANCH_INIT", @@ -734,6 +743,8 @@ export const ReduxActionTypes = { SET_LINT_ERRORS: "SET_LINT_ERRORS", SET_AUTO_HEIGHT_WITH_LIMITS_CHANGING: "SET_AUTO_HEIGHT_WITH_LIMITS_CHANGING", PROCESS_AUTO_HEIGHT_UPDATES: "PROCESS_AUTO_HEIGHT_UPDATES", + LINT_TREE: "LINT_TREE", + UPDATE_LINT_GLOBALS: "UPDATE_LINT_GLOBALS", REMOVE_TEMP_DATASOURCE_SUCCESS: "REMOVE_TEMP_DATASOURCE_SUCCESS", SET_DATASOURCE_SAVE_ACTION_FLAG: "SET_DATASOURCE_SAVE_ACTION_FLAG", SET_DATASOURCE_SAVE_ACTION_FROM_POPUP_FLAG: @@ -909,6 +920,9 @@ export const ReduxActionErrorTypes = { GET_TEMPLATE_ERROR: "GET_TEMPLATE_ERROR", GET_TEMPLATE_FILTERS_ERROR: "GET_TEMPLATE_FILTERS_ERROR", FETCH_CURRENT_TENANT_CONFIG_ERROR: "FETCH_CURRENT_TENANT_CONFIG_ERROR", + INSTALL_LIBRARY_FAILED: "INSTALL_LIBRARY_FAILED", + UNINSTALL_LIBRARY_FAILED: "UNINSTALL_LIBRARY_FAILED", + FETCH_JS_LIBRARIES_FAILED: "FETCH_JS_LIBRARIES_FAILED", }; export const ReduxFormActionTypes = { diff --git a/app/client/src/ce/constants/messages.ts b/app/client/src/ce/constants/messages.ts index 3bbb1a066d..ee9639889f 100644 --- a/app/client/src/ce/constants/messages.ts +++ b/app/client/src/ce/constants/messages.ts @@ -1121,7 +1121,7 @@ export const API_PANE_NO_BODY = () => "This request does not have a body"; export const TABLE_WIDGET_TOTAL_RECORD_TOOLTIP = () => "It stores the total no. of rows in the table. Helps in calculating the no. of pages that further allows to enable or disable the next/previous control in pagination."; export const CREATE_DATASOURCE_TOOLTIP = () => "Add a new datasource"; -export const ADD_QUERY_JS_TOOLTIP = () => "Create New"; +export const ADD_QUERY_JS_TOOLTIP = () => "Add a new query / JS Object"; // Add datasource export const GENERATE_APPLICATION_TITLE = () => "Generate Page"; @@ -1420,6 +1420,39 @@ export const ALERT_STYLE_OPTIONS = [ { label: "Warning", value: "'warning'", id: "warning" }, ]; +export const customJSLibraryMessages = { + ADD_JS_LIBRARY: () => "Add JS Libraries", + REC_LIBRARY: () => "Recommended Libraries", + INSTALLATION_SUCCESSFUL: (accessor: string) => + `Installation Successful. You can access the library via ${accessor}`, + INSTALLATION_FAILED: () => "Installation failed", + INSTALLED_ALREADY: (accessor: string) => + `This library is installed already. You could access it via ${accessor}.`, + UNINSTALL_FAILED: (name: string) => + `Couldn't uninstall ${name}. Please try again after sometime.`, + UNINSTALL_SUCCESS: (accessor: string) => + `${accessor} is uninstalled successfully.`, + LEARN_MORE_DESC: () => "Learn more about Custom JS Libraries", + UNSUPPORTED_LIB: () => `Library is unsupported`, + UNSUPPORTED_LIB_DESC: () => + `Unfortunately, this library cannot be supported due to platform limitations. Please try installing a different library.`, + LEARN_MORE: () => `Learn more`, + REPORT_ISSUE: () => `Report issue`, + AUTOCOMPLETE_FAILED: (name: string) => + `Code completion for ${name} will not work.`, + CLIENT_LOAD_FAILED: (url: string) => `Failed to load the script at ${url}.`, + LIB_OVERRIDE_ERROR: ( + name: string, + ) => `The library ${name} is already installed. + If you are trying to install a different version, uninstall the library first.`, + DEFS_FAILED_ERROR: (name: string) => + `Failed to generate autocomplete definitions for ${name}.`, + IMPORT_URL_ERROR: (url: string) => + `The script at ${url} cannot be installed.`, + NAME_COLLISION_ERROR: (accessors: string) => + `Name collision detected: ${accessors}`, +}; + export const USAGE_AND_BILLING = { usage: () => "Usage", billing: () => "Billing", diff --git a/app/client/src/ce/reducers/index.tsx b/app/client/src/ce/reducers/index.tsx index f5afe8ae35..af76fd8caa 100644 --- a/app/client/src/ce/reducers/index.tsx +++ b/app/client/src/ce/reducers/index.tsx @@ -67,6 +67,7 @@ import tenantReducer, { } from "@appsmith/reducers/tenantReducer"; import { FocusHistoryState } from "reducers/uiReducers/focusHistoryReducer"; import { EditorContextState } from "reducers/uiReducers/editorContextReducer"; +import { LibraryState } from "reducers/uiReducers/libraryReducer"; import { AutoHeightLayoutTreeReduxState } from "reducers/entityReducers/autoHeightReducers/autoHeightLayoutTreeReducer"; import { CanvasLevelsReduxState } from "reducers/entityReducers/autoHeightReducers/canvasLevelsReducer"; import { LintErrors } from "reducers/lintingReducers/lintErrorsReducers"; @@ -129,6 +130,7 @@ export interface AppState { appSettingsPane: AppSettingsPaneReduxState; focusHistory: FocusHistoryState; editorContext: EditorContextState; + libraries: LibraryState; autoHeightUI: AutoHeightUIState; }; entities: { diff --git a/app/client/src/ce/sagas/index.tsx b/app/client/src/ce/sagas/index.tsx index 01be86d2a0..d0bb8dd798 100644 --- a/app/client/src/ce/sagas/index.tsx +++ b/app/client/src/ce/sagas/index.tsx @@ -40,8 +40,10 @@ import SuperUserSagas from "@appsmith/sagas/SuperUserSagas"; import NavigationSagas from "sagas/NavigationSagas"; import editorContextSagas from "sagas/editorContextSagas"; import PageVisibilitySaga from "sagas/PageVisibilitySagas"; +import JSLibrarySaga from "sagas/JSLibrarySaga"; import AutoHeightSagas from "sagas/autoHeightSagas"; import tenantSagas from "@appsmith/sagas/tenantSagas"; +import LintingSaga from "sagas/LintingSagas"; export const sagas = [ initSagas, @@ -88,4 +90,6 @@ export const sagas = [ PageVisibilitySaga, AutoHeightSagas, tenantSagas, + JSLibrarySaga, + LintingSaga, ]; diff --git a/app/client/src/entities/Engine/AppEditorEngine.ts b/app/client/src/entities/Engine/AppEditorEngine.ts index 60cbf3a1ae..f0232639e0 100644 --- a/app/client/src/entities/Engine/AppEditorEngine.ts +++ b/app/client/src/entities/Engine/AppEditorEngine.ts @@ -47,6 +47,10 @@ import AppEngine, { PluginFormConfigsNotFoundError, PluginsNotFoundError, } from "."; +import { fetchJSLibraries } from "actions/JSLibraryActions"; +import CodemirrorTernService from "utils/autocomplete/CodemirrorTernService"; +import { selectFeatureFlags } from "selectors/usersSelectors"; +import FeatureFlags from "entities/FeatureFlags"; export default class AppEditorEngine extends AppEngine { constructor(mode: APP_MODE) { @@ -71,6 +75,7 @@ export default class AppEditorEngine extends AppEngine { public *setupEngine(payload: AppEnginePayload): any { yield* super.setupEngine.call(this, payload); yield put(resetEditorSuccess()); + CodemirrorTernService.resetServer(); } public startPerformanceTracking() { @@ -113,6 +118,12 @@ export default class AppEditorEngine extends AppEngine { ReduxActionErrorTypes.FETCH_PAGE_ERROR, ]; + const featureFlags: FeatureFlags = yield select(selectFeatureFlags); + if (featureFlags.CUSTOM_JS_LIBRARY) { + initActionsCalls.push(fetchJSLibraries(applicationId)); + successActionEffects.push(ReduxActionTypes.FETCH_JS_LIBRARIES_SUCCESS); + } + const allActionCalls: boolean = yield call( failFastApiCalls, initActionsCalls, diff --git a/app/client/src/entities/Engine/AppViewerEngine.ts b/app/client/src/entities/Engine/AppViewerEngine.ts index 9c5f73c8b8..6f729c84a5 100644 --- a/app/client/src/entities/Engine/AppViewerEngine.ts +++ b/app/client/src/entities/Engine/AppViewerEngine.ts @@ -17,12 +17,15 @@ import { ReduxActionTypes, } from "@appsmith/constants/ReduxActionConstants"; import { APP_MODE } from "entities/App"; -import { call, put } from "redux-saga/effects"; +import { call, put, select } from "redux-saga/effects"; import { failFastApiCalls } from "sagas/InitSagas"; import PerformanceTracker, { PerformanceTransactionName, } from "utils/PerformanceTracker"; import AppEngine, { ActionsNotFoundError, AppEnginePayload } from "."; +import { fetchJSLibraries } from "actions/JSLibraryActions"; +import FeatureFlags from "entities/FeatureFlags"; +import { selectFeatureFlags } from "selectors/usersSelectors"; export default class AppViewerEngine extends AppEngine { constructor(mode: APP_MODE) { @@ -67,28 +70,42 @@ export default class AppViewerEngine extends AppEngine { } *loadAppEntities(toLoadPageId: string, applicationId: string): any { + const initActionsCalls: any = [ + fetchActionsForView({ applicationId }), + fetchJSCollectionsForView({ applicationId }), + fetchSelectedAppThemeAction(applicationId), + fetchAppThemesAction(applicationId), + fetchPublishedPage(toLoadPageId, true, true), + ]; + + const successActionEffects = [ + ReduxActionTypes.FETCH_ACTIONS_VIEW_MODE_SUCCESS, + ReduxActionTypes.FETCH_JS_ACTIONS_VIEW_MODE_SUCCESS, + ReduxActionTypes.FETCH_APP_THEMES_SUCCESS, + ReduxActionTypes.FETCH_SELECTED_APP_THEME_SUCCESS, + fetchPublishedPageSuccess().type, + ]; + const failureActionEffects = [ + ReduxActionErrorTypes.FETCH_ACTIONS_VIEW_MODE_ERROR, + ReduxActionErrorTypes.FETCH_JS_ACTIONS_VIEW_MODE_ERROR, + ReduxActionErrorTypes.FETCH_APP_THEMES_ERROR, + ReduxActionErrorTypes.FETCH_SELECTED_APP_THEME_ERROR, + ReduxActionErrorTypes.FETCH_PUBLISHED_PAGE_ERROR, + ]; + + const featureFlags: FeatureFlags = yield select(selectFeatureFlags); + if (featureFlags.CUSTOM_JS_LIBRARY) { + initActionsCalls.push(fetchJSLibraries(applicationId)); + successActionEffects.push(ReduxActionTypes.FETCH_JS_LIBRARIES_SUCCESS); + failureActionEffects.push( + ReduxActionErrorTypes.FETCH_JS_LIBRARIES_FAILED, + ); + } + const resultOfPrimaryCalls: boolean = yield failFastApiCalls( - [ - fetchActionsForView({ applicationId }), - fetchJSCollectionsForView({ applicationId }), - fetchSelectedAppThemeAction(applicationId), - fetchAppThemesAction(applicationId), - fetchPublishedPage(toLoadPageId, true, true), - ], - [ - ReduxActionTypes.FETCH_ACTIONS_VIEW_MODE_SUCCESS, - ReduxActionTypes.FETCH_JS_ACTIONS_VIEW_MODE_SUCCESS, - ReduxActionTypes.FETCH_APP_THEMES_SUCCESS, - ReduxActionTypes.FETCH_SELECTED_APP_THEME_SUCCESS, - fetchPublishedPageSuccess().type, - ], - [ - ReduxActionErrorTypes.FETCH_ACTIONS_VIEW_MODE_ERROR, - ReduxActionErrorTypes.FETCH_JS_ACTIONS_VIEW_MODE_ERROR, - ReduxActionErrorTypes.FETCH_APP_THEMES_ERROR, - ReduxActionErrorTypes.FETCH_SELECTED_APP_THEME_ERROR, - ReduxActionErrorTypes.FETCH_PUBLISHED_PAGE_ERROR, - ], + initActionsCalls, + successActionEffects, + failureActionEffects, ); if (!resultOfPrimaryCalls) diff --git a/app/client/src/entities/FeatureFlags.ts b/app/client/src/entities/FeatureFlags.ts index 1e30b11f2f..5e06f81d39 100644 --- a/app/client/src/entities/FeatureFlags.ts +++ b/app/client/src/entities/FeatureFlags.ts @@ -8,6 +8,7 @@ type FeatureFlags = { CONTEXT_SWITCHING?: boolean; USAGE?: boolean; DATASOURCE_ENVIRONMENTS?: boolean; + CUSTOM_JS_LIBRARY?: boolean; }; export default FeatureFlags; diff --git a/app/client/src/pages/Editor/Explorer/EntityExplorer.tsx b/app/client/src/pages/Editor/Explorer/EntityExplorer.tsx index 923bd37dd7..39ddc559a5 100644 --- a/app/client/src/pages/Editor/Explorer/EntityExplorer.tsx +++ b/app/client/src/pages/Editor/Explorer/EntityExplorer.tsx @@ -9,7 +9,7 @@ import styled from "styled-components"; import Divider from "components/editorComponents/Divider"; import Search from "./ExplorerSearch"; import { NonIdealState, Classes } from "@blueprintjs/core"; -import JSDependencies from "./JSDependencies"; +import JSDependencies from "./Libraries"; import PerformanceTracker, { PerformanceTransactionName, } from "utils/PerformanceTracker"; diff --git a/app/client/src/pages/Editor/Explorer/Files/Submenu.tsx b/app/client/src/pages/Editor/Explorer/Files/Submenu.tsx index 1ad9923ef5..2adf8c2d39 100644 --- a/app/client/src/pages/Editor/Explorer/Files/Submenu.tsx +++ b/app/client/src/pages/Editor/Explorer/Files/Submenu.tsx @@ -26,7 +26,7 @@ import { TOOLTIP_HOVER_ON_DELAY } from "constants/AppConstants"; import { EntityClassNames } from "../Entity"; import { TooltipComponent } from "design-system"; import { - ADD_QUERY_JS_BUTTON, + ADD_QUERY_JS_TOOLTIP, createMessage, } from "@appsmith/constants/messages"; import { useCloseMenuOnScroll } from "../hooks"; @@ -223,7 +223,7 @@ export default function ExplorerSubMenu({ className={EntityClassNames.TOOLTIP} content={ <> - {createMessage(ADD_QUERY_JS_BUTTON)} ( + {createMessage(ADD_QUERY_JS_TOOLTIP)} ( {comboHelpText[SEARCH_CATEGORY_ID.ACTION_OPERATION]}) } diff --git a/app/client/src/pages/Editor/Explorer/JSDependencies.tsx b/app/client/src/pages/Editor/Explorer/JSDependencies.tsx deleted file mode 100644 index 824346d971..0000000000 --- a/app/client/src/pages/Editor/Explorer/JSDependencies.tsx +++ /dev/null @@ -1,133 +0,0 @@ -import React, { useState } from "react"; -import styled from "styled-components"; -import { AppIcon as Icon, Size, TooltipComponent } from "design-system"; -import { Colors } from "constants/Colors"; -import { BindingText } from "pages/Editor/APIEditor/CommonEditorForm"; -import { extraLibraries } from "utils/DynamicBindingUtils"; -import CollapseToggle from "./Entity/CollapseToggle"; -import Collapse from "./Entity/Collapse"; - -const Wrapper = styled.div` - font-size: 14px; -`; -const ListItem = styled.li` - list-style: none; - color: ${Colors.GREY_8}; - height: 36px; - display: flex; - align-items: center; - justify-content: space-between; - cursor: pointer; - padding: 0 12px 0 20px; - position: relative; - &:hover { - background: ${Colors.ALABASTER_ALT}; - - & .t--open-new-tab { - display: block; - } - - & .t--package-version { - display: none; - } - } - - & .t--open-new-tab { - position: absolute; - right: 8px; - display: none; - } - - & .t--package-version { - display: block; - } -`; -const Name = styled.span``; -const Version = styled.span``; -const Title = styled.div` - display: grid; - grid-template-columns: 20px auto 20px; - cursor: pointer; - height: 32px; - align-items: center; - padding-right: 4px; - padding-left: 0.25rem; - font-size: 14px; - &:hover { - background: ${Colors.ALABASTER_ALT}; - } - & .t--help-icon { - svg { - position: relative; - } - } - span { - color: ${Colors.GREY_800}; - } -`; - -function JSDependencies() { - const [isOpen, setIsOpen] = useState(false); - const openDocs = (name: string, url: string) => () => window.open(url, name); - const dependencyList = extraLibraries.map((lib) => { - return ( - - {lib.displayName} - {lib.version} - - - ); - }); - - const toggleDependencies = React.useCallback( - () => setIsOpen((open) => !open), - [], - ); - const showDocs = React.useCallback((e: any) => { - window.open( - "https://docs.appsmith.com/v/v1.2.1/core-concepts/writing-code/ext-libraries", - "appsmith-docs:working-with-js-libraries", - ); - e.stopPropagation(); - e.preventDefault(); - }, []); - - const TooltipContent = ( -
- Access these JS libraries to transform data within - {`{{ }}`} - . Try - {`{{ _.add(1,1) }}`} -
- ); - return ( - - - <CollapseToggle - className={""} - disabled={false} - isOpen={isOpen} - isVisible={!!dependencyList} - onClick={toggleDependencies} - /> - <span className="ml-1 font-medium">Dependencies</span> - <TooltipComponent content={TooltipContent} hoverOpenDelay={200}> - <Icon - className="t--help-icon" - name="help" - onClick={showDocs} - size={Size.xxs} - /> - </TooltipComponent> - - - {dependencyList} - - - ); -} - -export default React.memo(JSDependencies); diff --git a/app/client/src/pages/Editor/Explorer/Libraries/Installer.tsx b/app/client/src/pages/Editor/Explorer/Libraries/Installer.tsx new file mode 100644 index 0000000000..caf9a70e2b --- /dev/null +++ b/app/client/src/pages/Editor/Explorer/Libraries/Installer.tsx @@ -0,0 +1,538 @@ +import React, { + useCallback, + useEffect, + useMemo, + useRef, + useState, +} from "react"; +import styled from "styled-components"; +import { + Button, + Category, + FormGroup, + Icon, + IconSize, + Size, + Spinner, + Text, + TextInput, + TextType, + Toaster, + Variant, +} from "design-system"; +import { + createMessage, + customJSLibraryMessages, +} from "@appsmith/constants/messages"; +import ProfileImage from "pages/common/ProfileImage"; +import { Colors } from "constants/Colors"; +import { useDispatch, useSelector } from "react-redux"; +import { + selectInstallationStatus, + selectInstalledLibraries, + selectIsInstallerOpen, + selectIsLibraryInstalled, + selectQueuedLibraries, + selectStatusForURL, +} from "selectors/entitiesSelector"; +import SaveSuccessIcon from "remixicon-react/CheckboxCircleFillIcon"; +import { InstallState } from "reducers/uiReducers/libraryReducer"; +import recommendedLibraries from "pages/Editor/Explorer/Libraries/recommendedLibraries"; +import { AppState } from "@appsmith/reducers"; +import { + clearInstalls, + installLibraryInit, + toggleInstaller, +} from "actions/JSLibraryActions"; +import classNames from "classnames"; +import { TJSLibrary } from "workers/common/JSLibrary"; +import AnalyticsUtil from "utils/AnalyticsUtil"; + +const openDoc = (e: React.MouseEvent, url: string) => { + e.preventDefault(); + e.stopPropagation(); + window.open(url, "_blank"); +}; + +const Wrapper = styled.div<{ left: number }>` + display: flex; + height: auto; + width: 400px; + max-height: 80vh; + flex-direction: column; + padding: 0 24px 4px; + position: absolute; + background: white; + z-index: 25; + left: ${(props) => props.left}px; + bottom: 15px; + .installation-header { + padding: 20px 0 0; + display: flex; + flex-direction: row; + justify-content: space-between; + margin-bottom: 12px; + } + .search-area { + margin-bottom: 16px; + .left-icon { + margin-left: 14px; + .cs-icon { + margin-right: 0; + } + } + .bp3-form-group { + margin: 0; + .remixicon-icon { + cursor: initial; + } + } + .bp3-label { + font-size: 12px; + } + display: flex; + flex-direction: column; + .search-bar { + margin-bottom: 8px; + } + } + .search-body { + display: flex; + flex-direction: column; + .search-CTA { + margin-bottom: 16px; + display: flex; + flex-direction: column; + } + .search-results { + .library-card { + gap: 8px; + padding: 8px 0; + display: flex; + flex-direction: column; + gap: 0.5rem; + border-bottom: 1px solid var(--appsmith-color-black-100); + .description { + overflow: hidden; + text-overflow: ellipsis; + display: -webkit-box; + -webkit-line-clamp: 2; + font-size: 12px; + line-clamp: 2; + font-weight: 400; + -webkit-box-orient: vertical; + } + img { + cursor: initial; + } + } + .library-card.no-border { + border-bottom: none; + } + } + } +`; + +const InstallationProgressWrapper = styled.div<{ addBorder: boolean }>` + border-top: ${(props) => + props.addBorder ? `1px solid var(--appsmith-color-black-300)` : "none"}; + display: flex; + flex-direction: column; + background: var(--appsmith-color-black-50); + text-overflow: ellipsis; + padding: 8px 8px 12px; + .install-url { + text-overflow: ellipsis; + display: -webkit-box; + -webkit-line-clamp: 2; + line-clamp: 2; + -webkit-box-orient: vertical; + overflow: hidden; + word-break: break-all; + } + .error-card { + display: flex; + padding: 10px; + flex-direction: row; + background: #ffe9e9; + .unsupported { + line-height: 17px; + .header { + font-size: 13px; + font-weight: 600; + color: #393939; + } + .body { + font-size: 12px; + font-weight: 400; + } + } + } +`; + +const StatusIconWrapper = styled.div<{ + addHoverState: boolean; +}>` + display: flex; + align-items: center; + justify-content: center; + width: 24px; + height: 24px; + cursor: initial; + .failed { + svg { + cursor: initial; + } + }} + ${(props) => + props.addHoverState + ? ` + &:hover { + cursor: pointer; + background: ${Colors.SHARK2} !important; + svg { + path { + fill: ${Colors.WHITE} !important; + } + } + } + ` + : "svg { cursor: initial }"} +`; + +function isValidJSFileURL(url: string) { + const JS_FILE_REGEX = /^https?:\/\/.*\.js$/; + return JS_FILE_REGEX.test(url); +} + +function StatusIcon(props: { + status: InstallState; + isInstalled?: boolean; + action?: any; +}) { + const { action, isInstalled = false, status } = props; + const actionProps = useMemo(() => (action ? { onClick: action } : {}), [ + action, + ]); + if (status === InstallState.Success || isInstalled) + return ( + + + + ); + if (status === InstallState.Failed) + return ( + + + + ); + if (status === InstallState.Queued) + return ( + + + + ); + return ( + + + + ); +} + +function ProgressTracker({ + isFirst, + isLast, + status, + url, +}: { + isFirst: boolean; + isLast: boolean; + status: InstallState; + url: string; +}) { + return ( + + {[InstallState.Queued, InstallState.Installing].includes(status) && ( +
Installing...
+ )} +
+
+
{url}
+
+ +
+
+ {status === InstallState.Failed && ( +
+ +
+
+ {createMessage(customJSLibraryMessages.UNSUPPORTED_LIB)} +
+
+ {createMessage(customJSLibraryMessages.UNSUPPORTED_LIB_DESC)} +
+ +
+
+ )} +
+
+ ); +} + +function InstallationProgress() { + const installStatusMap = useSelector(selectInstallationStatus); + const urls = Object.keys(installStatusMap).filter( + (url) => !recommendedLibraries.find((lib) => lib.url === url), + ); + if (urls.length === 0) return null; + return ( +
+ {urls.reverse().map((url, idx) => ( + + ))} +
+ ); +} + +const EXT_LINK = { + learnMore: + "https://docs.appsmith.com/core-concepts/writing-code/ext-libraries", + reportIssue: "https://github.com/appsmithorg/appsmith/issues/19037", + jsDelivr: "https://www.jsdelivr.com/", +}; + +export function Installer(props: { left: number }) { + const { left } = props; + const [URL, setURL] = useState(""); + const [isValid, setIsValid] = useState(true); + const dispatch = useDispatch(); + const installedLibraries = useSelector(selectInstalledLibraries); + const queuedLibraries = useSelector(selectQueuedLibraries); + const isOpen = useSelector(selectIsInstallerOpen); + const installerRef = useRef(null); + + const closeInstaller = useCallback(() => { + dispatch(clearInstalls()); + dispatch(toggleInstaller(false)); + }, []); + + const handleOutsideClick = useCallback((e: MouseEvent) => { + const paths = e.composedPath(); + if ( + installerRef && + installerRef.current && + !paths?.includes(installerRef.current) + ) + closeInstaller(); + }, []); + + useEffect(() => { + document.addEventListener("mousedown", handleOutsideClick); + return () => { + document.removeEventListener("mousedown", handleOutsideClick); + }; + }, [isOpen]); + + const updateURL = useCallback((value: string) => { + setURL(value); + }, []); + + const validate = useCallback((text) => { + const isValid = !text || isValidJSFileURL(text); + setIsValid(isValid); + return { + isValid, + message: isValid ? "" : "Please enter a valid URL", + }; + }, []); + + useEffect(() => { + URL && + AnalyticsUtil.logEvent("EDIT_LIBRARY_URL", { url: URL, valid: isValid }); + }, [URL, isValid]); + + const installLibrary = useCallback( + (lib?: Partial) => { + const url = lib?.url || URL; + const isQueued = queuedLibraries.find((libURL) => libURL === url); + if (isQueued) return; + + const libInstalled = installedLibraries.find((lib) => lib.url === url); + if (libInstalled) { + Toaster.show({ + text: createMessage( + customJSLibraryMessages.INSTALLED_ALREADY, + libInstalled.accessor, + ), + variant: Variant.info, + }); + return; + } + dispatch( + installLibraryInit({ + url, + name: lib?.name, + }), + ); + }, + [URL, installedLibraries, queuedLibraries], + ); + + return !isOpen ? null : ( + +
+ + {createMessage(customJSLibraryMessages.ADD_JS_LIBRARY)} + + +
+
+
+ + + +
+
+
+
+ + Explore libraries on{" "} + openDoc(e, EXT_LINK.jsDelivr)} + > + jsDelivr + + {". "} + {createMessage(customJSLibraryMessages.LEARN_MORE_DESC)}{" "} + openDoc(e, EXT_LINK.learnMore)} + > + here + + {"."} + +
+ +
+ + {createMessage(customJSLibraryMessages.REC_LIBRARY)} + +
+
+ {recommendedLibraries.map((lib, idx) => ( + installLibrary(lib)} + /> + ))} +
+
+
+ ); +} + +function LibraryCard({ + isLastCard, + lib, + onClick, +}: { + lib: typeof recommendedLibraries[0]; + onClick: (url: string) => void; + isLastCard: boolean; +}) { + const status = useSelector(selectStatusForURL(lib.url)); + const isInstalled = useSelector((state: AppState) => + selectIsLibraryInstalled(state, lib.url), + ); + return ( +
+
+
+ + {lib.name} + + openDoc(e, lib.docsURL)} + > + + +
+
+ +
+
+
{lib.description}
+
+ + {lib.author} +
+
+ ); +} diff --git a/app/client/src/pages/Editor/Explorer/Libraries/__tests__/Installer.test.tsx b/app/client/src/pages/Editor/Explorer/Libraries/__tests__/Installer.test.tsx new file mode 100644 index 0000000000..57da1c65f0 --- /dev/null +++ b/app/client/src/pages/Editor/Explorer/Libraries/__tests__/Installer.test.tsx @@ -0,0 +1,152 @@ +import React from "react"; +import { render, screen, fireEvent, cleanup } from "@testing-library/react"; +import "@testing-library/jest-dom/extend-expect"; +import { Provider } from "react-redux"; +import store from "store"; +import { ThemeProvider } from "styled-components"; +import { lightTheme } from "selectors/themeSelectors"; +import { ReduxActionTypes } from "@appsmith/constants/ReduxActionConstants"; +import { Installer } from "pages/Editor/Explorer/Libraries/Installer"; + +export const fetchApplicationMockResponse = { + responseMeta: { + status: 200, + success: true, + }, + data: { + application: { + id: "605c435a91dea93f0eaf91b8", + name: "My Application", + slug: "my-application", + workspaceId: "", + evaluationVersion: 1, + appIsExample: false, + gitApplicationMetadata: undefined, + applicationVersion: 2, + }, + pages: [ + { + id: "605c435a91dea93f0eaf91ba", + name: "Page1", + isDefault: true, + slug: "page-1", + }, + { + id: "605c435a91dea93f0eaf91bc", + name: "Page2", + isDefault: false, + slug: "page-2", + }, + ], + workspaceId: "", + }, +}; + +describe("Contains all UI tests for JS libraries", () => { + store.dispatch({ + type: ReduxActionTypes.TOGGLE_INSTALLER, + payload: true, + }); + afterEach(cleanup); + + it("Headers should exist", () => { + render( + + + + + , + ); + expect(screen.getByText("Add JS Libraries")).toBeDefined(); + expect(screen.getByText("Recommended Libraries")).toBeDefined(); + expect(screen.getByTestId("library-url")).toBeDefined(); + expect(screen.getByTestId("install-library-btn")).toBeDisabled(); + }); + + it("Validates URL", () => { + render( + + + + + , + ); + const input = screen.getByTestId("library-url"); + fireEvent.change(input, { target: { value: "https://valid.com/file.js" } }); + expect(screen.getByTestId("install-library-btn")).toBeEnabled(); + expect(screen.queryByText("Please enter a valid URL")).toBeNull(); + fireEvent.change(input, { target: { value: "23" } }); + expect(screen.queryByText("Please enter a valid URL")).toBeDefined(); + expect(screen.getByTestId("install-library-btn")).toBeDisabled(); + }); + + it("Renders progress bar", () => { + render( + + + + + , + ); + store.dispatch({ + type: ReduxActionTypes.FETCH_APPLICATION_SUCCESS, + payload: { + ...fetchApplicationMockResponse.data.application, + pages: fetchApplicationMockResponse.data.pages, + }, + }); + const input = screen.getByTestId("library-url"); + fireEvent.change(input, { + target: { + value: + "https://cdnjs.cloudflare.com/ajax/libs/dayjs/1.11.6/dayjs.min.js", + }, + }); + const installButton = screen.getByTestId("install-library-btn"); + expect(installButton).toBeDefined(); + fireEvent.click(installButton); + + expect( + screen.queryByText( + `Installing library for ${fetchApplicationMockResponse.data.application.name}`, + ), + ).toBeDefined(); + }); + + it("Progress bar should disappear once the installation succeeds or fails", () => { + render( + + + + + , + ); + store.dispatch({ + type: ReduxActionTypes.INSTALL_LIBRARY_INIT, + payload: + "https://cdnjs.cloudflare.com/ajax/libs/dayjs/1.11.6/dayjs.min.js", + }); + + expect( + screen.queryByText( + `Installing library for ${fetchApplicationMockResponse.data.application.name}`, + ), + ).toBeDefined(); + + store.dispatch({ + type: ReduxActionTypes.INSTALL_LIBRARY_SUCCESS, + payload: { + name: "dayjs", + version: "1.11.6", + accessor: ["dayjs"], + url: "https://cdnjs.cloudflare.com/ajax/libs/dayjs/1.11.6/dayjs.min.js", + }, + }); + + expect( + screen.queryByText( + `Installing library for ${fetchApplicationMockResponse.data.application.name}`, + ), + ).toBeNull(); + }); +}); diff --git a/app/client/src/pages/Editor/Explorer/Libraries/index.tsx b/app/client/src/pages/Editor/Explorer/Libraries/index.tsx new file mode 100644 index 0000000000..6bd206110c --- /dev/null +++ b/app/client/src/pages/Editor/Explorer/Libraries/index.tsx @@ -0,0 +1,338 @@ +import React, { MutableRefObject, useCallback, useRef } from "react"; +import styled from "styled-components"; +import { + Icon, + IconSize, + Spinner, + Toaster, + TooltipComponent, + Variant, +} from "design-system"; +import { Colors } from "constants/Colors"; +import Entity, { EntityClassNames } from "../Entity"; +import { + createMessage, + customJSLibraryMessages, +} from "@appsmith/constants/messages"; +import { useDispatch, useSelector } from "react-redux"; +import { + selectInstallationStatus, + selectIsInstallerOpen, + selectLibrariesForExplorer, +} from "selectors/entitiesSelector"; +import { InstallState } from "reducers/uiReducers/libraryReducer"; +import { Collapse } from "@blueprintjs/core"; +import { ReactComponent as CopyIcon } from "assets/icons/menu/copy-snippet.svg"; +import useClipboard from "utils/hooks/useClipboard"; +import { + toggleInstaller, + uninstallLibraryInit, +} from "actions/JSLibraryActions"; +import EntityAddButton from "../Entity/AddButton"; +import { TOOLTIP_HOVER_ON_DELAY } from "constants/AppConstants"; +import { TJSLibrary } from "workers/common/JSLibrary"; +import { getPagePermissions } from "selectors/editorSelectors"; +import { hasCreateActionPermission } from "@appsmith/utils/permissionHelpers"; +import { selectFeatureFlags } from "selectors/usersSelectors"; +import recommendedLibraries from "./recommendedLibraries"; + +const docsURLMap = recommendedLibraries.reduce((acc, lib) => { + acc[lib.url] = lib.docsURL; + return acc; +}, {} as Record); + +const Library = styled.li` + list-style: none; + flex-direction: column; + color: ${Colors.GRAY_700}; + font-weight: 400; + display: flex; + justify-content: space-between; + cursor: pointer; + position: relative; + line-height: 17px; + padding-left: 8px; + + > div:first-child { + height: 36px; + } + + .share { + display: none; + width: 30px; + height: 36px; + background: transparent; + margin-left: 8px; + flex-shrink: 0; + } + + &:hover { + background: ${Colors.SEA_SHELL}; + + & .t--open-new-tab { + display: block; + } + + & .delete, + .share { + display: flex; + align-items: center; + justify-content: center; + background: transparent; + &:hover { + background: black; + .uninstall-library, + .open-link { + color: white; + svg > path { + fill: white; + } + } + } + } + } + + .loading { + display: none; + width: 30px; + height: 36px; + background: transparent; + flex-shrink: 0; + display: flex; + align-items: center; + justify-content: center; + } + + & .t--open-new-tab { + position: absolute; + right: 8px; + display: none; + } + + .delete { + display: none; + width: 30px; + height: 36px; + background: transparent; + flex-shrink: 0; + } + + & .t--package-version { + display: block; + font-size: 12px; + height: 16px; + } + .open-collapse { + transform: rotate(90deg); + } + + .content { + font-size: 12px; + font-weight: 400; + padding: 4px 8px; + color: ${Colors.GRAY_700}; + display: flex; + align-items: center; + gap: 4px; + width: 100%; + overflow: hidden; + .accessor { + padding-left: 8px; + flex-grow: 1; + outline: 1px solid #b3b3b3 !important; + font-size: 12px; + font-family: monospace; + background: white; + display: flex; + height: 25px; + width: calc(100% - 80px); + justify-content: space-between; + align-items: center; + color: ${Colors.ENTERPRISE_DARK}; + > div { + height: 100%; + display: flex; + align-items: center; + justify-content: center; + background: transparent; + width: 25px; + &: hover { + background: ${Colors.SHARK2}; + > svg > path { + fill: ${Colors.WHITE}; + } + } + } + } + } +`; +const Name = styled.div` + display: flex; + align-items: center; + line-height: 17px; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; + word-break: break-all; +`; +const Version = styled.div<{ version?: string }>` + flex-shrink: 0; + display: ${(props) => (props.version ? "block" : "none")}; + margin: ${(props) => (props.version ? "0 8px" : "0")}; +`; + +const PrimaryCTA = function({ lib }: { lib: TJSLibrary }) { + const installationStatus = useSelector(selectInstallationStatus); + const dispatch = useDispatch(); + + const url = lib.url as string; + + const uninstallLibrary = useCallback( + (e) => { + e.stopPropagation(); + dispatch(uninstallLibraryInit(lib)); + }, + [lib], + ); + + if (installationStatus[url] === InstallState.Queued) + return ( +
+ +
+ ); + + if (url) { + //Default libraries will not have url + return ( +
+ +
+ ); + } + + return null; +}; + +function LibraryEntity({ lib }: { lib: TJSLibrary }) { + const openDocs = useCallback( + (url?: string) => (e: React.MouseEvent) => { + e?.stopPropagation(); + url && window.open(url, "_blank"); + }, + [], + ); + const propertyRef: MutableRefObject = useRef(null); + const write = useClipboard(propertyRef); + + const copyToClipboard = useCallback(() => { + write(lib.accessor[lib.accessor.length - 1]); + Toaster.show({ + text: "Copied to clipboard", + variant: Variant.success, + }); + }, [lib.accessor]); + + const [isOpen, open] = React.useState(false); + const docsURL = docsURLMap[lib.url || ""] || lib.docsURL; + return ( + +
open(!isOpen)} + > + +
+ {lib.name} + {docsURL && ( +
+ +
+ )} +
+ + {lib.version} + + +
+ +
+ Available as{" "} +
+ {lib.accessor[lib.accessor.length - 1]}{" "} +
+ +
+
+
+
+
+ ); +} + +function JSDependencies() { + const libraries = useSelector(selectLibrariesForExplorer); + const dependencyList = libraries.map((lib) => ( + + )); + const isOpen = useSelector(selectIsInstallerOpen); + const dispatch = useDispatch(); + + const pagePermissions = useSelector(getPagePermissions); + + const canCreateActions = hasCreateActionPermission(pagePermissions); + + const openInstaller = useCallback(() => { + dispatch(toggleInstaller(true)); + }, []); + + const featureFlags = useSelector(selectFeatureFlags); + + return ( + + + + } + entityId="library_section" + icon={null} + isDefaultExpanded={isOpen} + isSticky + name="Libraries" + showAddButton={canCreateActions && featureFlags?.CUSTOM_JS_LIBRARY} + step={0} + > + {dependencyList} + + ); +} + +export default React.memo(JSDependencies); diff --git a/app/client/src/pages/Editor/Explorer/Libraries/recommendedLibraries.ts b/app/client/src/pages/Editor/Explorer/Libraries/recommendedLibraries.ts new file mode 100644 index 0000000000..bb742098ee --- /dev/null +++ b/app/client/src/pages/Editor/Explorer/Libraries/recommendedLibraries.ts @@ -0,0 +1,150 @@ +export default [ + { + name: "uuidjs", + url: "https://cdn.jsdelivr.net/npm/uuidjs@4.2.12/src/uuid.min.js", + description: + "UUID.js is a JavaScript/ECMAScript library to generate RFC 4122 compliant Universally Unique IDentifiers (UUIDs). This library supports both version 4 UUIDs (UUIDs from random numbers) and version 1 UUIDs (time-based UUIDs), and provides an object-oriented interface to print a generated or parsed UUID in a variety of forms.", + author: "LiosK", + docsURL: + "https://github.com/LiosK/UUID.js/#uuidjs---rfc-compliant-uuid-generator-for-javascript", + version: "4.2.12", + icon: "https://github.com/LiosK.png?s=20", + }, + { + name: "i18next", + url: "https://cdn.jsdelivr.net/npm/i18next@22.1.4/dist/umd/i18next.min.js", + description: "i18next internationalization framework", + author: "i18next", + version: "22.1.4", + icon: "https://github.com/i18next.png?s=20", + docsURL: "https://www.i18next.com/overview/getting-started", + }, + { + name: "jsonwebtoken", + description: "JSON Web Token implementation (symmetric and asymmetric)", + author: "auth0", + docsURL: "https://github.com/auth0/node-jsonwebtoken#readme", + version: "8.5.1", + url: `/libraries/jsonwebtoken@8.5.1.js`, + icon: "https://github.com/auth0.png?s=20", + }, + { + name: "@supabase/supabase-js", + description: "Isomorphic Javascript client for Supabase", + author: "supabase", + docsURL: "https://supabase.com/docs/reference/javascript", + version: "2.1.0", + url: + "https://cdn.jsdelivr.net/npm/@supabase/supabase-js@2.1.0/dist/umd/supabase.min.js", + icon: "https://github.com/supabase.png?s=20", + }, + { + name: "@segment/analytics-next", + url: + "https://cdn.jsdelivr.net/npm/@segment/analytics-next@1.46.1/dist/umd/index.js", + description: + "Analytics Next (aka Analytics 2.0) is the latest version of Segment’s JavaScript SDK - enabling you to send your data to any tool without having to learn, test, or use a new API every time.", + author: "segmentio", + docsURL: + "https://github.com/segmentio/analytics-next/tree/master/packages/browser#readme", + version: "1.46.1", + icon: "https://github.com/segmentio.png?s=20", + }, + { + name: "mixpanel-browser", + description: "The official Mixpanel JavaScript browser client library", + author: "mixpanel", + docsURL: "https://developer.mixpanel.com/docs/javascript", + version: "2.1.0", + url: `https://cdn.jsdelivr.net/npm/mixpanel-browser@2.45.0/dist/mixpanel.umd.js`, + icon: "https://github.com/mixpanel.png?s=20", + }, + { + name: "fast-csv", + description: "CSV parser and writer", + author: "C2FO", + docsURL: + "https://c2fo.github.io/fast-csv/docs/introduction/getting-started/", + version: "4.3.6", + url: `/libraries/fast-csv@4.3.6.js`, + icon: "https://github.com/C2FO.png?s=20", + }, + { + name: "ky", + description: "Tiny and elegant HTTP client based on the browser Fetch API", + author: "sindresorhus", + docsURL: "https://github.com/sindresorhus/ky#usage", + version: "0.25.0", + url: "https://www.unpkg.com/ky@0.25.0/umd.js", + icon: "https://github.com/sindresorhus.png?s=20", + }, + { + name: "jspdf", + description: "PDF Document creation from JavaScript", + author: "MrRio", + docsURL: "https://raw.githack.com/MrRio/jsPDF/master/docs/index.html", + version: "2.5.1", + url: "https://cdnjs.cloudflare.com/ajax/libs/jspdf/2.5.1/jspdf.umd.min.js", + icon: "https://github.com/MrRio.png?s=20", + }, + { + name: "@amplitude/analytics-browser", + description: "Official Amplitude SDK for Web", + author: "amplitude", + docsURL: + "https://github.com/amplitude/Amplitude-TypeScript/tree/main/packages/analytics-browser#usage", + version: "1.6.1", + url: + "https://cdn.jsdelivr.net/npm/@amplitude/analytics-browser@1.6.1/lib/scripts/amplitude-min.umd.js", + icon: "https://github.com/amplitude.png?s=20", + }, + { + name: "uzip-module", + description: "Module version of UZIP.js", + author: "greggman", + docsURL: "https://github.com/greggman/uzip-module#uzip-module", + version: "1.0.3", + url: `https://cdn.jsdelivr.net/npm/uzip-module@1.0.3/dist/uzip.js`, + icon: "https://github.com/greggman.png?s=20", + }, + { + name: "@sentry/browser", + description: "Official Sentry SDK for browsers", + author: "getsentry", + docsURL: "https://docs.sentry.io/platforms/javascript/", + version: "7.17.3", + url: "https://browser.sentry-cdn.com/7.17.3/bundle.min.js", + icon: "https://github.com/getsentry.png?s=20", + }, + { + name: "browser-image-compression", + url: + "https://cdn.jsdelivr.net/npm/browser-image-compression@2.0.0/dist/browser-image-compression.min.js", + version: "2.0.0", + author: "Donaldcwl", + docsURL: + "https://github.com/Donaldcwl/browser-image-compression/#browser-image-compression", + description: "Compress images in the browser", + icon: "https://github.com/Donaldcwl.png?s=20", + }, + { + name: "crypto-js", + url: + "https://cdnjs.cloudflare.com/ajax/libs/crypto-js/4.1.1/crypto-js.min.js", + description: "JavaScript library of crypto standards", + version: "4.1.1", + author: "brix", + docsURL: "https://github.com/brix/crypto-js/#crypto-js", + icon: "https://github.com/brix.png?s=20", + }, + { + name: "jsonpath", + url: "https://cdn.jsdelivr.net/npm/jsonpath@1.1.1/jsonpath.min.js", + description: + "Query JavaScript objects with JSONPath expressions. Robust / safe JSONPath engine for Node.js", + version: "1.1.1", + author: "dchester", + docsURL: "https://github.com/dchester/jsonpath/#jsonpath", + icon: "https://github.com/dchester.png?s=20", + }, +]; diff --git a/app/client/src/pages/Editor/GlobalHotKeys/GlobalHotKeys.tsx b/app/client/src/pages/Editor/GlobalHotKeys/GlobalHotKeys.tsx index 25a276ee58..85949e13fb 100644 --- a/app/client/src/pages/Editor/GlobalHotKeys/GlobalHotKeys.tsx +++ b/app/client/src/pages/Editor/GlobalHotKeys/GlobalHotKeys.tsx @@ -49,6 +49,7 @@ import { setExplorerPinnedAction } from "actions/explorerActions"; import { setIsGitSyncModalOpen } from "actions/gitSyncActions"; import { GitSyncModalTab } from "entities/GitSync"; import { matchBuilderPath } from "constants/routes"; +import { toggleInstaller } from "actions/JSLibraryActions"; type Props = { copySelectedWidget: () => void; @@ -77,6 +78,7 @@ type Props = { setExplorerPinnedAction: (shouldPinned: boolean) => void; showCommitModal: () => void; getMousePosition: () => { x: number; y: number }; + hideInstaller: () => void; }; @HotkeysTarget @@ -109,6 +111,7 @@ class GlobalHotKeys extends React.Component { const category = filterCategories[categoryId]; this.props.setGlobalSearchCategory(category); + this.props.hideInstaller(); AnalyticsUtil.logEvent("OPEN_OMNIBAR", { source: "HOTKEY_COMBO", category: category.title, @@ -359,6 +362,7 @@ class GlobalHotKeys extends React.Component { label="Pin/Unpin Entity Explorer" onKeyDown={() => { this.props.setExplorerPinnedAction(!this.props.isExplorerPinned); + this.props.hideInstaller(); }} /> { dispatch( setIsGitSyncModalOpen({ isOpen: true, tab: GitSyncModalTab.DEPLOY }), ), + hideInstaller: () => dispatch(toggleInstaller(false)), }; }; diff --git a/app/client/src/pages/Editor/MainContainer.tsx b/app/client/src/pages/Editor/MainContainer.tsx index dbcbefe446..202f4f2da6 100644 --- a/app/client/src/pages/Editor/MainContainer.tsx +++ b/app/client/src/pages/Editor/MainContainer.tsx @@ -17,6 +17,7 @@ import EntityExplorerSidebar from "components/editorComponents/Sidebar"; import classNames from "classnames"; import { previewModeSelector } from "selectors/editorSelectors"; import { routeChanged } from "actions/focusHistoryActions"; +import { Installer } from "pages/Editor/Explorer/Libraries/Installer"; import { getExplorerWidth } from "selectors/explorerSelector"; import { AppsmithLocationState } from "utils/history"; @@ -96,6 +97,7 @@ function MainContainer() { "transition-all transform duration-400": true, })} /> + ); } diff --git a/app/client/src/reducers/uiReducers/editorContextReducer.ts b/app/client/src/reducers/uiReducers/editorContextReducer.ts index ea70c46b88..32faa3b8c0 100644 --- a/app/client/src/reducers/uiReducers/editorContextReducer.ts +++ b/app/client/src/reducers/uiReducers/editorContextReducer.ts @@ -51,7 +51,13 @@ const initialState: EditorContextState = { explorerSwitchIndex: 0, }; -const entitySections = ["Pages", "Widgets", "Queries/JS", "Datasources"]; +const entitySections = [ + "Pages", + "Widgets", + "Queries/JS", + "Datasources", + "Libraries", +]; export const isSubEntities = (name: string): boolean => { return entitySections.indexOf(name) < 0; diff --git a/app/client/src/reducers/uiReducers/index.tsx b/app/client/src/reducers/uiReducers/index.tsx index ceb67ce055..62e73083eb 100644 --- a/app/client/src/reducers/uiReducers/index.tsx +++ b/app/client/src/reducers/uiReducers/index.tsx @@ -42,6 +42,7 @@ import mainCanvasReducer from "./mainCanvasReducer"; import focusHistoryReducer from "./focusHistoryReducer"; import { editorContextReducer } from "./editorContextReducer"; import guidedTourReducer from "./guidedTourReducer"; +import libraryReducer from "./libraryReducer"; import appSettingsPaneReducer from "./appSettingsPaneReducer"; import autoHeightUIReducer from "./autoHeightReducer"; @@ -90,6 +91,7 @@ const uiReducer = combineReducers({ appSettingsPane: appSettingsPaneReducer, focusHistory: focusHistoryReducer, editorContext: editorContextReducer, + libraries: libraryReducer, autoHeightUI: autoHeightUIReducer, }); diff --git a/app/client/src/reducers/uiReducers/libraryReducer.ts b/app/client/src/reducers/uiReducers/libraryReducer.ts new file mode 100644 index 0000000000..eb2477aec9 --- /dev/null +++ b/app/client/src/reducers/uiReducers/libraryReducer.ts @@ -0,0 +1,116 @@ +import { createImmerReducer } from "utils/ReducerUtils"; +import { + ReduxAction, + ReduxActionErrorTypes, + ReduxActionTypes, +} from "@appsmith/constants/ReduxActionConstants"; +import recommendedLibraries from "pages/Editor/Explorer/Libraries/recommendedLibraries"; +import { defaultLibraries, TJSLibrary } from "workers/common/JSLibrary"; + +export enum InstallState { + Queued, + Installing, + Failed, + Success, +} + +export type LibraryState = { + installationStatus: Record; + installedLibraries: TJSLibrary[]; + isInstallerOpen: boolean; +}; + +const initialState = { + isInstallerOpen: false, + installationStatus: {}, + installedLibraries: defaultLibraries.map((lib: TJSLibrary) => { + return { + name: lib.name, + docsURL: lib.docsURL, + version: lib.version, + accessor: lib.accessor, + }; + }), + reservedNames: [], +}; + +const jsLibraryReducer = createImmerReducer(initialState, { + [ReduxActionTypes.INSTALL_LIBRARY_INIT]: ( + state: LibraryState, + action: ReduxAction>, + ) => { + const { url } = action.payload; + state.installationStatus[url as string] = + state.installationStatus[url as string] || InstallState.Queued; + }, + [ReduxActionTypes.INSTALL_LIBRARY_START]: ( + state: LibraryState, + action: ReduxAction, + ) => { + state.installationStatus[action.payload] = InstallState.Queued; + }, + [ReduxActionTypes.INSTALL_LIBRARY_SUCCESS]: ( + state: LibraryState, + action: ReduxAction<{ + accessor: string[]; + url: string; + version: string; + }>, + ) => { + const { accessor, url, version } = action.payload; + const name = accessor[accessor.length - 1] as string; + const recommendedLibrary = recommendedLibraries.find( + (lib) => lib.url === url, + ); + state.installationStatus[url] = InstallState.Success; + state.installedLibraries.unshift({ + name: recommendedLibrary?.name || name, + docsURL: recommendedLibrary?.url || url, + version: recommendedLibrary?.version || version, + url, + accessor, + }); + }, + [ReduxActionErrorTypes.INSTALL_LIBRARY_FAILED]: ( + state: LibraryState, + action: ReduxAction<{ url: string }>, + ) => { + state.installationStatus[action.payload.url] = InstallState.Failed; + }, + [ReduxActionTypes.CLEAR_PROCESSED_INSTALLS]: (state: LibraryState) => { + for (const key in state.installationStatus) { + if ( + [InstallState.Success, InstallState.Failed].includes( + state.installationStatus[key], + ) + ) { + delete state.installationStatus[key]; + } + } + }, + [ReduxActionTypes.FETCH_JS_LIBRARIES_SUCCESS]: ( + state: LibraryState, + action: ReduxAction, + ) => { + state.installedLibraries = action.payload.concat( + initialState.installedLibraries, + ); + }, + [ReduxActionTypes.UNINSTALL_LIBRARY_SUCCESS]: ( + state: LibraryState, + action: ReduxAction, + ) => { + const uLib = action.payload; + state.installedLibraries = state.installedLibraries.filter( + (lib) => uLib.url !== lib.url, + ); + }, + [ReduxActionTypes.TOGGLE_INSTALLER]: ( + state: LibraryState, + action: ReduxAction, + ) => { + state.isInstallerOpen = action.payload; + }, +}); + +export default jsLibraryReducer; diff --git a/app/client/src/sagas/ActionExecution/DownloadActionSaga.ts b/app/client/src/sagas/ActionExecution/DownloadActionSaga.ts index 7142b9f69e..7a45941645 100644 --- a/app/client/src/sagas/ActionExecution/DownloadActionSaga.ts +++ b/app/client/src/sagas/ActionExecution/DownloadActionSaga.ts @@ -8,6 +8,20 @@ import { } from "entities/DataTree/actionTriggers"; import { ActionValidationError } from "sagas/ActionExecution/errorUtils"; import { isBase64String, isUrlString } from "./downloadActionUtils"; +import { isBlobUrl } from "utils/AppsmithUtils"; + +function downloadBlobURL(url: string, name: string) { + const ele = document.createElement("a"); + ele.href = url; + ele.download = name; + ele.style.display = "none"; + document.body.appendChild(ele); + ele.click(); + setTimeout(() => { + URL.revokeObjectURL(url); + document.body.removeChild(ele); + }); +} export default async function downloadSaga( action: DownloadActionDescription["payload"], @@ -21,6 +35,13 @@ export default async function downloadSaga( getType(name), ); } + if (isBlobUrl(data)) { + downloadBlobURL(data, name); + AppsmithConsole.info({ + text: `download('${data}', '${name}', '${type}') was triggered`, + }); + return; + } const dataType = getType(data); if (dataType === Types.ARRAY || dataType === Types.OBJECT) { const jsonString = JSON.stringify(data, null, 2); diff --git a/app/client/src/sagas/EvaluationsSaga.ts b/app/client/src/sagas/EvaluationsSaga.ts index 21a90bcd8c..78f2aac097 100644 --- a/app/client/src/sagas/EvaluationsSaga.ts +++ b/app/client/src/sagas/EvaluationsSaga.ts @@ -27,9 +27,12 @@ import WidgetFactory, { WidgetTypeConfigMap } from "utils/WidgetFactory"; import { GracefulWorkerService } from "utils/WorkerUtil"; import { EvalError, - EVAL_WORKER_ACTIONS, PropertyEvaluationErrorType, } from "utils/DynamicBindingUtils"; +import { + EVAL_WORKER_ACTIONS, + MAIN_THREAD_ACTION, +} from "workers/Evaluation/evalWorkerActions"; import log from "loglevel"; import { WidgetProps } from "widgets/BaseWidget"; import PerformanceTracker, { @@ -103,11 +106,12 @@ import { CanvasWidgetsReduxState } from "reducers/entityReducers/canvasWidgetsRe import { AppTheme } from "entities/AppTheming"; import { ActionValidationConfigMap } from "constants/PropertyControlConstants"; import { storeLogs, updateTriggerMeta } from "./DebuggerSagas"; -import { lintTreeSaga, lintWorker } from "./LintingSagas"; +import { lintWorker } from "./LintingSagas"; import { EvalTreeRequestData, EvalTreeResponseData, } from "workers/Evaluation/types"; +import { MessageType, TMessage } from "utils/MessageUtil"; const evalWorker = new GracefulWorkerService( new Worker( @@ -121,10 +125,21 @@ const evalWorker = new GracefulWorkerService( let widgetTypeConfigMap: WidgetTypeConfigMap; -function* evaluateTreeSaga( +/** + * This saga is responsible for evaluating the data tree + * @param postEvalActions + * @param shouldReplay + * @param requiresLinting + * @param forceEvaluation - if true, will re-evaluate the entire tree + * @returns + * @example + * yield call(evaluateTreeSaga, postEvalActions, shouldReplay, requiresLinting, forceEvaluation) + */ +export function* evaluateTreeSaga( postEvalActions?: Array, shouldReplay = true, requiresLinting = false, + forceEvaluation = false, ) { const allActionValidationConfig: { [actionId: string]: ActionValidationConfigMap; @@ -146,6 +161,7 @@ function* evaluateTreeSaga( shouldReplay, allActionValidationConfig, requiresLinting: isEditMode && requiresLinting, + forceEvaluation, }; const workerResponse: EvalTreeResponseData = yield call( @@ -270,8 +286,8 @@ export function* evaluateAndExecuteDynamicTrigger( ) { const unEvalTree: DataTree = yield select(getUnevaluatedDataTree); log.debug({ execute: dynamicTrigger }); - const { isFinishedChannel } = yield call( - evalWorker.duplexRequest, + const response: unknown = yield call( + evalWorker.request, EVAL_WORKER_ACTIONS.EVAL_TRIGGER, { unEvalTree, @@ -283,122 +299,90 @@ export function* evaluateAndExecuteDynamicTrigger( }, ); - let keepAlive = true; + const { logs = [], errors = [], triggers = [] } = response as any; + yield call(updateTriggerMeta, triggerMeta, dynamicTrigger); + yield call( + storeLogs, + logs, + triggerMeta.source?.name || triggerMeta.triggerPropertyName || "", + eventType === EventType.ON_JS_FUNCTION_EXECUTE + ? ENTITY_TYPE.JSACTION + : ENTITY_TYPE.WIDGET, + triggerMeta.source?.id || "", + ); - while (keepAlive) { - const { requestData } = yield take(isFinishedChannel); - log.debug({ requestData, eventType, triggerMeta, dynamicTrigger }); - - if (requestData.finished) { - keepAlive = false; - - const { result } = requestData; - yield call(updateTriggerMeta, triggerMeta, dynamicTrigger); - - // Check for any logs in the response and store them in the redux store - if ( - !!result && - result.hasOwnProperty("logs") && - !!result.logs && - result.logs.length - ) { - yield call( - storeLogs, - result.logs, - triggerMeta.source?.name || triggerMeta.triggerPropertyName || "", - eventType === EventType.ON_JS_FUNCTION_EXECUTE - ? ENTITY_TYPE.JSACTION - : ENTITY_TYPE.WIDGET, - triggerMeta.source?.id || "", - ); - } - - /* Handle errors during evaluation - * A finish event with errors means that the error was not caught by the user code. - * We raise an error telling the user that an uncaught error has occurred - * */ - if ( - !!result && - result.hasOwnProperty("errors") && - !!result.errors && - result.errors.length - ) { - if ( - result.errors[0].errorMessage !== - "UncaughtPromiseRejection: User cancelled action execution" - ) { - throw new UncaughtPromiseError(result.errors[0].errorMessage); - } - } - - // It is possible to get a few triggers here if the user - // still uses the old way of action runs and not promises. For that we - // need to manually execute these triggers outside the promise flow - const { triggers } = result; - if (triggers && triggers.length) { - log.debug({ triggers }); - yield all( - triggers.map((trigger: ActionDescription) => - call(executeActionTriggers, trigger, eventType, triggerMeta), - ), - ); - } - // Return value of a promise is returned - isFinishedChannel.close(); - return result; + yield call(evalErrorHandler, errors); + if (errors.length) { + if ( + errors[0].errorMessage !== + "UncaughtPromiseRejection: User cancelled action execution" + ) { + throw new UncaughtPromiseError(errors[0].errorMessage); } - yield call(evalErrorHandler, requestData.errors); - isFinishedChannel.close(); + } + + log.debug({ triggers }); + yield all( + triggers.map((trigger: ActionDescription) => + call(executeActionTriggers, trigger, eventType, triggerMeta), + ), + ); + + return response; +} + +export function* handleEvalWorkerRequestSaga(listenerChannel: Channel) { + while (true) { + const request: TMessage = yield take(listenerChannel); + yield spawn(handleEvalWorkerMessage, request); } } -export function* executeDynamicTriggerRequest( - mainThreadRequestChannel: Channel, -) { - while (true) { - const { mainThreadResponseChannel, requestData, requestId } = yield take( - mainThreadRequestChannel, - ); - log.debug({ requestData }); - if (requestData?.logs) { - const { eventType, triggerMeta } = requestData; +export function* handleEvalWorkerMessage(message: TMessage) { + const { body, messageType } = message; + const { data, method } = body; + switch (method) { + case MAIN_THREAD_ACTION.LINT_TREE: { + yield put({ + type: ReduxActionTypes.LINT_TREE, + payload: { + pathsToLint: data.lintOrder, + unevalTree: data.unevalTree, + }, + }); + break; + } + case MAIN_THREAD_ACTION.PROCESS_LOGS: { + const { logs = [], triggerMeta, eventType } = data; yield call( storeLogs, - requestData.logs, + logs, triggerMeta?.source?.name || triggerMeta?.triggerPropertyName || "", eventType === EventType.ON_JS_FUNCTION_EXECUTE ? ENTITY_TYPE.JSACTION : ENTITY_TYPE.WIDGET, triggerMeta?.source?.id || "", ); + break; } - if (requestData?.trigger) { - // if we have found a trigger, we need to execute it and respond back - log.debug({ trigger: requestData.trigger }); - yield spawn( + case MAIN_THREAD_ACTION.PROCESS_TRIGGER: { + const { eventType, trigger, triggerMeta } = data; + log.debug({ trigger: data.trigger }); + const result: ResponsePayload = yield call( executeTriggerRequestSaga, - requestId, - requestData, - requestData.eventType, - mainThreadResponseChannel, - requestData.triggerMeta, + trigger, + eventType, + triggerMeta, ); - } - if (requestData.type === EVAL_WORKER_ACTIONS.LINT_TREE) { - yield spawn(lintTreeSaga, { - pathsToLint: requestData.lintOrder, - unevalTree: requestData.unevalTree, - }); - } - if (requestData?.errors) { - yield call(evalErrorHandler, requestData.errors); + if (messageType === MessageType.REQUEST) + yield call(evalWorker.respond, message.messageId, result); + break; } } + yield call(evalErrorHandler, data?.errors || []); } - interface ResponsePayload { data: { - subRequestId: string; reason?: string; resolve?: unknown; }; @@ -411,17 +395,14 @@ interface ResponsePayload { * resolve or reject it with the data the execution has provided */ function* executeTriggerRequestSaga( - requestId: string, - requestData: { trigger: ActionDescription; subRequestId: string }, + trigger: ActionDescription, eventType: EventType, - responseFromExecutionChannel: Channel, triggerMeta: TriggerMeta, ) { const responsePayload: ResponsePayload = { data: { resolve: undefined, reason: undefined, - subRequestId: requestData.subRequestId, }, success: false, eventType, @@ -429,7 +410,7 @@ function* executeTriggerRequestSaga( try { responsePayload.data.resolve = yield call( executeActionTriggers, - requestData.trigger, + trigger, eventType, triggerMeta, ); @@ -442,11 +423,7 @@ function* executeTriggerRequestSaga( responsePayload.data.reason = { message: error.message }; responsePayload.success = false; } - responseFromExecutionChannel.put({ - method: EVAL_WORKER_ACTIONS.PROCESS_TRIGGER, - requestId: requestId, - ...responsePayload, - }); + return responsePayload; } export function* clearEvalCache() { @@ -497,17 +474,15 @@ export function* executeFunction( }, ); - const { logs } = response; + const { logs = [] } = response; // Check for any logs in the response and store them in the redux store - if (!!logs && logs.length > 0) { - yield call( - storeLogs, - logs, - collectionName + "." + action.name, - ENTITY_TYPE.JSACTION, - collectionId, - ); - } + yield call( + storeLogs, + logs, + collectionName + "." + action.name, + ENTITY_TYPE.JSACTION, + collectionId, + ); } const { errors, result } = response; @@ -611,16 +586,16 @@ function getPostEvalActions( return postEvalActions; } -function* evaluationChangeListenerSaga() { +function* evaluationChangeListenerSaga(): any { // Explicitly shutdown old worker if present yield all([call(evalWorker.shutdown), call(lintWorker.shutdown)]); - const [{ mainThreadRequestChannel }] = yield all([ + const [evalWorkerListenerChannel] = yield all([ call(evalWorker.start), call(lintWorker.start), ]); yield call(evalWorker.request, EVAL_WORKER_ACTIONS.SETUP); - yield spawn(executeDynamicTriggerRequest, mainThreadRequestChannel); + yield spawn(handleEvalWorkerRequestSaga, evalWorkerListenerChannel); widgetTypeConfigMap = WidgetFactory.getWidgetTypeConfigMap(); const initAction: { @@ -654,7 +629,7 @@ export function* evaluateSnippetSaga(action: any) { let { expression } = action.payload; const { dataType, isTrigger } = action.payload; if (isTrigger) { - expression = `function() { ${expression} }`; + expression = `(function() { ${expression} })()`; } const workerResponse: { errors: any; @@ -663,7 +638,6 @@ export function* evaluateSnippetSaga(action: any) { } = yield call(evalWorker.request, EVAL_WORKER_ACTIONS.EVAL_EXPRESSION, { expression, dataType, - isTrigger, }); const { errors, result, triggers } = workerResponse; if (triggers && triggers.length > 0) { @@ -830,3 +804,5 @@ export default function* evaluationSagaListeners() { } } } + +export { evalWorker as EvalWorker }; diff --git a/app/client/src/sagas/JSLibrarySaga.ts b/app/client/src/sagas/JSLibrarySaga.ts new file mode 100644 index 0000000000..75f3a24340 --- /dev/null +++ b/app/client/src/sagas/JSLibrarySaga.ts @@ -0,0 +1,405 @@ +import { ApiResponse } from "api/ApiResponses"; +import LibraryApi from "api/LibraryAPI"; +import { + createMessage, + customJSLibraryMessages, +} from "@appsmith/constants/messages"; +import { + ReduxAction, + ReduxActionErrorTypes, + ReduxActionTypes, +} from "@appsmith/constants/ReduxActionConstants"; +import { Toaster, Variant } from "design-system"; +import { + actionChannel, + ActionPattern, + all, + call, + put, + select, + take, + takeEvery, + takeLatest, +} from "redux-saga/effects"; +import { getCurrentApplicationId } from "selectors/editorSelectors"; +import CodemirrorTernService from "utils/autocomplete/CodemirrorTernService"; +import { EVAL_WORKER_ACTIONS } from "workers/Evaluation/evalWorkerActions"; +import { validateResponse } from "./ErrorSagas"; +import { evaluateTreeSaga, EvalWorker } from "./EvaluationsSaga"; +import log from "loglevel"; +import { APP_MODE } from "entities/App"; +import { getAppMode } from "selectors/applicationSelectors"; +import AnalyticsUtil from "utils/AnalyticsUtil"; +import { TJSLibrary } from "workers/common/JSLibrary"; +import { getUsedActionNames } from "selectors/actionSelectors"; +import AppsmithConsole from "utils/AppsmithConsole"; +import { selectInstalledLibraries } from "selectors/entitiesSelector"; + +export function parseErrorMessage(text: string) { + return text + .split(": ") + .slice(1) + .join(""); +} + +function* handleInstallationFailure( + url: string, + message: string, + accessor?: string[], +) { + if (accessor) { + yield call( + EvalWorker.request, + EVAL_WORKER_ACTIONS.UNINSTALL_LIBRARY, + accessor, + ); + } + + AppsmithConsole.error({ + text: `Failed to install library script at ${url}`, + }); + + Toaster.show({ + text: message || `Failed to install library script at ${url}`, + variant: Variant.danger, + }); + yield put({ + type: ReduxActionErrorTypes.INSTALL_LIBRARY_FAILED, + payload: { url, show: false }, + }); + AnalyticsUtil.logEvent("INSTALL_LIBRARY", { url, success: false }); +} + +export function* installLibrarySaga(lib: Partial) { + const { url } = lib; + + const takenNamesMap: Record = yield select( + getUsedActionNames, + "", + ); + + const installedLibraries: TJSLibrary[] = yield select( + selectInstalledLibraries, + ); + + const takenAccessors = ([] as string[]).concat( + ...installedLibraries.map((lib) => lib.accessor), + ); + + const { accessor, defs, error, success } = yield call( + EvalWorker.request, + EVAL_WORKER_ACTIONS.INSTALL_LIBRARY, + { + url, + takenNamesMap, + takenAccessors, + }, + ); + + if (!success) { + log.debug("Failed to install locally"); + yield call(handleInstallationFailure, url as string, error?.message); + return; + } + + const name: string = lib.name || accessor[accessor.length - 1]; + const applicationId: string = yield select(getCurrentApplicationId); + + const versionMatch = (url as string).match(/(?:@)(\d+\.)(\d+\.)(\d+)/); + let [version = ""] = versionMatch ? versionMatch : []; + version = version.startsWith("@") ? version.slice(1) : version; + + let stringifiedDefs = ""; + + try { + stringifiedDefs = JSON.stringify(defs); + } catch (e) { + stringifiedDefs = JSON.stringify({ + "!name": `LIB/${accessor[accessor.length - 1]}`, + }); + } + + const response: ApiResponse = yield call( + LibraryApi.addLibrary, + applicationId, + { + name, + version, + accessor, + defs: stringifiedDefs, + url, + }, + ); + + try { + const isValidResponse: boolean = yield validateResponse(response, false); + if (!isValidResponse || !response.data) { + log.debug("Install API failed"); + yield call(handleInstallationFailure, url as string, "", accessor); + return; + } + } catch (e) { + yield call( + handleInstallationFailure, + url as string, + (e as Error).message, + accessor, + ); + return; + } + + try { + CodemirrorTernService.updateDef(defs["!name"], defs); + AnalyticsUtil.logEvent("DEFINITIONS_GENERATION", { url, success: true }); + } catch (e) { + Toaster.show({ + text: createMessage(customJSLibraryMessages.AUTOCOMPLETE_FAILED, name), + variant: Variant.warning, + }); + AppsmithConsole.warning({ + text: `Failed to generate code definitions for ${name}`, + }); + AnalyticsUtil.logEvent("DEFINITIONS_GENERATION", { url, success: false }); + log.debug("Failed to update Tern defs", e); + } + + yield put({ + type: ReduxActionTypes.UPDATE_LINT_GLOBALS, + payload: { + libs: [ + { + name, + version, + url, + accessor, + }, + ], + add: true, + }, + }); + + //TODO: Check if we could avoid this. + yield call(evaluateTreeSaga, [], false, true, true); + + yield put({ + type: ReduxActionTypes.INSTALL_LIBRARY_SUCCESS, + payload: { + url, + accessor, + version, + name, + }, + }); + + Toaster.show({ + text: createMessage( + customJSLibraryMessages.INSTALLATION_SUCCESSFUL, + accessor[accessor.length - 1], + ), + variant: Variant.success, + }); + AnalyticsUtil.logEvent("INSTALL_LIBRARY", { + url, + namespace: accessor.join("."), + success: true, + }); + + AppsmithConsole.info({ + text: `${name} installed successfully`, + }); +} + +function* uninstallLibrarySaga(action: ReduxAction) { + const { accessor, name } = action.payload; + const applicationId: string = yield select(getCurrentApplicationId); + + try { + const response: ApiResponse = yield call( + LibraryApi.removeLibrary, + applicationId, + action.payload, + ); + + const isValidResponse: boolean = yield validateResponse(response); + + if (!isValidResponse) { + yield put({ + type: ReduxActionErrorTypes.UNINSTALL_LIBRARY_FAILED, + payload: accessor, + }); + AnalyticsUtil.logEvent("UNINSTALL_LIBRARY", { + url: action.payload.url, + success: false, + }); + return; + } + + yield put({ + type: ReduxActionTypes.UPDATE_LINT_GLOBALS, + payload: { + libs: [action.payload], + add: false, + }, + }); + + const { success }: { success: boolean } = yield call( + EvalWorker.request, + EVAL_WORKER_ACTIONS.UNINSTALL_LIBRARY, + accessor, + ); + if (!success) { + Toaster.show({ + text: createMessage(customJSLibraryMessages.UNINSTALL_FAILED, name), + variant: Variant.danger, + }); + } + + try { + CodemirrorTernService.removeDef(`LIB/${accessor[accessor.length - 1]}`); + } catch (e) { + log.debug(`Failed to remove definitions for ${name}`, e); + } + + yield call(evaluateTreeSaga, [], false, true, true); + + yield put({ + type: ReduxActionTypes.UNINSTALL_LIBRARY_SUCCESS, + payload: action.payload, + }); + + Toaster.show({ + text: createMessage(customJSLibraryMessages.UNINSTALL_SUCCESS, name), + variant: Variant.success, + }); + AnalyticsUtil.logEvent("UNINSTALL_LIBRARY", { + url: action.payload.url, + success: true, + }); + } catch (e) { + Toaster.show({ + text: createMessage(customJSLibraryMessages.UNINSTALL_FAILED, name), + variant: Variant.danger, + }); + AnalyticsUtil.logEvent("UNINSTALL_LIBRARY", { + url: action.payload.url, + success: false, + }); + } +} + +function* fetchJSLibraries(action: ReduxAction) { + const applicationId: string = action.payload; + const mode: APP_MODE = yield select(getAppMode); + try { + const response: ApiResponse = yield call( + LibraryApi.getLibraries, + applicationId, + mode, + ); + const isValidResponse: boolean = yield validateResponse(response); + if (!isValidResponse) return; + + const libraries = response.data as Array; + + const { + message, + success, + }: { success: boolean; message: string } = yield call( + EvalWorker.request, + EVAL_WORKER_ACTIONS.LOAD_LIBRARIES, + libraries.map((lib) => ({ + name: lib.name, + version: lib.version, + url: lib.url, + accessor: lib.accessor, + })), + ); + + if (!success) { + if (mode === APP_MODE.EDIT) { + yield put({ + type: ReduxActionTypes.FETCH_JS_LIBRARIES_SUCCESS, + payload: libraries.map((lib) => ({ + name: lib.name, + accessor: lib.accessor, + version: lib.version, + url: lib.url, + docsURL: lib.docsURL, + })), + }); + const errorMessage = parseErrorMessage(message); + Toaster.show({ + text: errorMessage, + variant: Variant.warning, + }); + } else { + yield put({ + type: ReduxActionErrorTypes.FETCH_JS_LIBRARIES_FAILED, + }); + } + return; + } + + if (mode === APP_MODE.EDIT) { + for (const lib of libraries) { + try { + const defs = JSON.parse(lib.defs); + CodemirrorTernService.updateDef(defs["!name"], defs); + } catch (e) { + Toaster.show({ + text: createMessage( + customJSLibraryMessages.AUTOCOMPLETE_FAILED, + lib.name, + ), + variant: Variant.info, + }); + } + } + yield put({ + type: ReduxActionTypes.UPDATE_LINT_GLOBALS, + payload: { + libs: libraries, + }, + }); + } + + yield put({ + type: ReduxActionTypes.FETCH_JS_LIBRARIES_SUCCESS, + payload: libraries.map((lib) => ({ + name: lib.name, + accessor: lib.accessor, + version: lib.version, + url: lib.url, + docsURL: lib.docsURL, + })), + }); + } catch (e) { + yield put({ + type: ReduxActionErrorTypes.FETCH_JS_LIBRARIES_FAILED, + }); + } +} + +function* startInstallationRequestChannel() { + const queueInstallChannel: ActionPattern = yield actionChannel([ + ReduxActionTypes.INSTALL_LIBRARY_INIT, + ]); + while (true) { + const action: ReduxAction> = yield take( + queueInstallChannel, + ); + yield put({ + type: ReduxActionTypes.INSTALL_LIBRARY_START, + payload: action.payload.url, + }); + yield call(installLibrarySaga, action.payload); + } +} + +export default function*() { + yield all([ + takeEvery(ReduxActionTypes.UNINSTALL_LIBRARY_INIT, uninstallLibrarySaga), + takeLatest(ReduxActionTypes.FETCH_JS_LIBRARIES_INIT, fetchJSLibraries), + call(startInstallationRequestChannel), + ]); +} diff --git a/app/client/src/sagas/LintingSagas.ts b/app/client/src/sagas/LintingSagas.ts index 907d671b0a..43eda49bdc 100644 --- a/app/client/src/sagas/LintingSagas.ts +++ b/app/client/src/sagas/LintingSagas.ts @@ -1,8 +1,13 @@ import { setLintingErrors } from "actions/lintingActions"; +import { + ReduxAction, + ReduxActionTypes, +} from "@appsmith/constants/ReduxActionConstants"; import { APP_MODE } from "entities/App"; -import { call, put, select } from "redux-saga/effects"; +import { call, put, select, takeEvery } from "redux-saga/effects"; import { getAppMode } from "selectors/entitiesSelector"; import { GracefulWorkerService } from "utils/WorkerUtil"; +import { TJSLibrary } from "workers/common/JSLibrary"; import { LintTreeRequest, LintTreeResponse, @@ -18,10 +23,19 @@ export const lintWorker = new GracefulWorkerService( }), ); -export function* lintTreeSaga({ - pathsToLint, - unevalTree, -}: LintTreeSagaRequestData) { +function* updateLintGlobals(action: ReduxAction) { + const appMode: APP_MODE = yield select(getAppMode); + const isEditorMode = appMode === APP_MODE.EDIT; + if (!isEditorMode) return; + yield call( + lintWorker.request, + LINT_WORKER_ACTIONS.UPDATE_LINT_GLOBALS, + action.payload, + ); +} + +export function* lintTreeSaga(action: ReduxAction) { + const { pathsToLint, unevalTree } = action.payload; // only perform lint operations in edit mode const appMode: APP_MODE = yield select(getAppMode); if (appMode !== APP_MODE.EDIT) return; @@ -40,3 +54,8 @@ export function* lintTreeSaga({ yield put(setLintingErrors(errors)); yield call(logLatestLintPropertyErrors, { errors, dataTree: unevalTree }); } + +export default function* lintTreeSagaWatcher() { + yield takeEvery(ReduxActionTypes.UPDATE_LINT_GLOBALS, updateLintGlobals); + yield takeEvery(ReduxActionTypes.LINT_TREE, lintTreeSaga); +} diff --git a/app/client/src/sagas/PageSagas.tsx b/app/client/src/sagas/PageSagas.tsx index 76989ec377..f41cdff109 100644 --- a/app/client/src/sagas/PageSagas.tsx +++ b/app/client/src/sagas/PageSagas.tsx @@ -69,13 +69,7 @@ import { } from "utils/helpers"; import { extractCurrentDSL } from "utils/WidgetPropsUtils"; import { checkIfMigrationIsNeeded } from "utils/DSLMigrations"; -import { - getAllPageIds, - getEditorConfigs, - getExistingPageNames, - getWidgets, -} from "./selectors"; -import { getDataTree } from "selectors/dataTreeSelectors"; +import { getAllPageIds, getEditorConfigs, getWidgets } from "./selectors"; import { IncorrectBindingError, validateResponse } from "./ErrorSagas"; import { ApiResponse } from "api/ApiResponses"; import { @@ -124,7 +118,6 @@ import { import WidgetFactory from "utils/WidgetFactory"; import { toggleShowDeviationDialog } from "actions/onboardingActions"; -import { DataTree } from "entities/DataTree/dataTreeFactory"; import { builderURL } from "RouteBuilder"; import { failFastApiCalls } from "./InitSagas"; import { hasManagePagePermission } from "@appsmith/utils/permissionHelpers"; @@ -133,6 +126,7 @@ import { getSelectedWidgets } from "selectors/ui"; import { checkAndLogErrorsIfCyclicDependency } from "./helper"; import { LOCAL_STORAGE_KEYS } from "utils/localStorage"; import { generateAutoHeightLayoutTreeAction } from "actions/autoHeightActions"; +import { getUsedActionNames } from "selectors/actionSelectors"; import { getPageList } from "selectors/entitiesSelector"; const WidgetTypes = WidgetFactory.widgetTypes; @@ -788,10 +782,10 @@ export function* updateWidgetNameSaga( try { const { widgetName } = yield select(getWidgetName, action.payload.id); const layoutId: string | undefined = yield select(getCurrentLayoutId); - const evalTree: DataTree = yield select(getDataTree); const pageId: string | undefined = yield select(getCurrentPageId); - const existingPageNames: Record = yield select( - getExistingPageNames, + const getUsedNames: Record = yield select( + getUsedActionNames, + "", ); // TODO(abhinav): Why do we need to jump through these hoops just to @@ -868,12 +862,7 @@ export function* updateWidgetNameSaga( } else { // check if name is not conflicting with any // existing entity/api/queries/reserved words - if ( - isNameValid(action.payload.newName, { - ...evalTree, - ...existingPageNames, - }) - ) { + if (isNameValid(action.payload.newName, getUsedNames)) { const request: UpdateWidgetNameRequest = { newName: action.payload.newName, oldName: widgetName, diff --git a/app/client/src/selectors/actionSelectors.tsx b/app/client/src/selectors/actionSelectors.tsx index 4e4d9b1e4a..3846f2c62f 100644 --- a/app/client/src/selectors/actionSelectors.tsx +++ b/app/client/src/selectors/actionSelectors.tsx @@ -2,8 +2,12 @@ import { DataTree } from "entities/DataTree/dataTreeFactory"; import { createSelector } from "reselect"; import WidgetFactory from "utils/WidgetFactory"; import { FlattenedWidgetProps } from "widgets/constants"; +import { TJSLibrary } from "workers/common/JSLibrary"; import { getDataTree } from "./dataTreeSelectors"; -import { getExistingPageNames } from "./entitiesSelector"; +import { + getExistingPageNames, + selectInstalledLibraries, +} from "./entitiesSelector"; import { getErrorForApiName, getErrorForJSObjectName, @@ -19,10 +23,12 @@ export const getUsedActionNames = createSelector( getExistingPageNames, getDataTree, getParentWidget, + selectInstalledLibraries, ( pageNames: Record, dataTree: DataTree, parentWidget: FlattenedWidgetProps | undefined, + installedLibraries: TJSLibrary[], ) => { const map: Record = {}; // The logic has been copied from Explorer/Entity/Name.tsx Component. @@ -41,6 +47,12 @@ export const getUsedActionNames = createSelector( Object.keys(dataTree).forEach((treeItem: string) => { map[treeItem] = true; }); + const libAccessors = ([] as string[]).concat( + ...installedLibraries.map((lib) => lib.accessor), + ); + for (const accessor of libAccessors) { + map[accessor] = true; + } } return map; diff --git a/app/client/src/selectors/entitiesSelector.ts b/app/client/src/selectors/entitiesSelector.ts index 5a6b45de24..d2091de81a 100644 --- a/app/client/src/selectors/entitiesSelector.ts +++ b/app/client/src/selectors/entitiesSelector.ts @@ -29,6 +29,9 @@ import { EVAL_ERROR_PATH, PropertyEvaluationErrorType, } from "utils/DynamicBindingUtils"; +import { InstallState } from "reducers/uiReducers/libraryReducer"; +import recommendedLibraries from "pages/Editor/Explorer/Libraries/recommendedLibraries"; +import { TJSLibrary } from "workers/common/JSLibrary"; export const getEntities = (state: AppState): AppState["entities"] => state.entities; @@ -848,3 +851,51 @@ export const getNumberOfEntitiesInCurrentPage = createSelector( ); }, ); + +export const selectIsInstallerOpen = (state: AppState) => + state.ui.libraries.isInstallerOpen; +export const selectInstallationStatus = (state: AppState) => + state.ui.libraries.installationStatus; +export const selectInstalledLibraries = (state: AppState) => + state.ui.libraries.installedLibraries; +export const selectStatusForURL = (url: string) => + createSelector(selectInstallationStatus, (statusMap) => { + return statusMap[url]; + }); +export const selectIsLibraryInstalled = createSelector( + [selectInstalledLibraries, (_: AppState, url: string) => url], + (installedLibraries, url) => { + return !!installedLibraries.find((lib) => lib.url === url); + }, +); + +export const selectQueuedLibraries = createSelector( + selectInstallationStatus, + (statusMap) => { + return Object.keys(statusMap).filter( + (url) => statusMap[url] === InstallState.Queued, + ); + }, +); + +export const selectLibrariesForExplorer = createSelector( + selectInstalledLibraries, + selectInstallationStatus, + (libs, libStatus) => { + const queuedInstalls = Object.keys(libStatus) + .filter((key) => libStatus[key] === InstallState.Queued) + .map((url) => { + const recommendedLibrary = recommendedLibraries.find( + (lib) => lib.url === url, + ); + return { + name: recommendedLibrary?.name || url, + docsURL: recommendedLibrary?.url || url, + version: recommendedLibrary?.version || "", + url: recommendedLibrary?.url || url, + accessor: [], + } as TJSLibrary; + }); + return [...queuedInstalls, ...libs]; + }, +); diff --git a/app/client/src/utils/AnalyticsUtil.tsx b/app/client/src/utils/AnalyticsUtil.tsx index a1ad60550b..e44e1ec391 100644 --- a/app/client/src/utils/AnalyticsUtil.tsx +++ b/app/client/src/utils/AnalyticsUtil.tsx @@ -275,7 +275,14 @@ export type EventName = | "BRANDING_PROPERTY_UPDATE" | "BRANDING_SUBMIT_CLICK" | "Cmd+Click Navigation" - | "WIDGET_PROPERTY_SEARCH"; + | "WIDGET_PROPERTY_SEARCH" + | LIBRARY_EVENTS; + +export type LIBRARY_EVENTS = + | "INSTALL_LIBRARY" + | "DEFINITIONS_GENERATION" + | "UNINSTALL_LIBRARY" + | "EDIT_LIBRARY_URL"; export type AUDIT_LOGS_EVENT_NAMES = | "AUDIT_LOGS_CLEAR_FILTERS" diff --git a/app/client/src/utils/DynamicBindingUtils.ts b/app/client/src/utils/DynamicBindingUtils.ts index 4288ae3d59..4d769e713f 100644 --- a/app/client/src/utils/DynamicBindingUtils.ts +++ b/app/client/src/utils/DynamicBindingUtils.ts @@ -1,17 +1,13 @@ -import _, { get, isString, VERSION as lodashVersion } from "lodash"; +import _, { get, isString } from "lodash"; import { DATA_BIND_REGEX } from "constants/BindingsConstants"; import { Action } from "entities/Action"; -import moment from "moment-timezone"; import { WidgetProps } from "widgets/BaseWidget"; -import parser from "fast-xml-parser"; - import { Severity } from "entities/AppsmithConsole"; import { getEntityNameAndPropertyPath, isJSAction, isTrueObject, } from "workers/Evaluation/evaluationUtils"; -import forge from "node-forge"; import { DataTreeEntity } from "entities/DataTree/dataTreeFactory"; import { getType, Types } from "./TypeHelpers"; import { ViewTypes } from "components/formControls/utils"; @@ -130,76 +126,6 @@ export type EvalError = { context?: Record; }; -export enum EVAL_WORKER_ACTIONS { - SETUP = "SETUP", - EVAL_TREE = "EVAL_TREE", - EVAL_ACTION_BINDINGS = "EVAL_ACTION_BINDINGS", - EVAL_TRIGGER = "EVAL_TRIGGER", - PROCESS_TRIGGER = "PROCESS_TRIGGER", - CLEAR_CACHE = "CLEAR_CACHE", - VALIDATE_PROPERTY = "VALIDATE_PROPERTY", - UNDO = "undo", - REDO = "redo", - EVAL_EXPRESSION = "EVAL_EXPRESSION", - UPDATE_REPLAY_OBJECT = "UPDATE_REPLAY_OBJECT", - SET_EVALUATION_VERSION = "SET_EVALUATION_VERSION", - INIT_FORM_EVAL = "INIT_FORM_EVAL", - EXECUTE_SYNC_JS = "EXECUTE_SYNC_JS", - LINT_TREE = "LINT_TREE", -} - -export type ExtraLibrary = { - version: string; - docsURL: string; - displayName: string; - accessor: string; - lib: any; -}; - -export const extraLibraries: ExtraLibrary[] = [ - { - accessor: "_", - lib: _, - version: lodashVersion, - docsURL: `https://lodash.com/docs/${lodashVersion}`, - displayName: "lodash", - }, - { - accessor: "moment", - lib: moment, - version: moment.version, - docsURL: `https://momentjs.com/docs/`, - displayName: "moment", - }, - { - accessor: "xmlParser", - lib: parser, - version: "3.17.5", - docsURL: "https://github.com/NaturalIntelligence/fast-xml-parser", - displayName: "xmlParser", - }, - { - accessor: "forge", - // We are removing some functionalities of node-forge because they wont - // work in the worker thread - lib: _.omit(forge, ["tls", "http", "xhr", "socket", "task"]), - version: "1.3.0", - docsURL: "https://github.com/digitalbazaar/forge", - displayName: "forge", - }, -]; -/** - * creates dynamic list of constants based on - * current list of extra libraries i.e lodash("_"), moment etc - * to be used in widget and entity name validations - */ -export const extraLibrariesNames = extraLibraries.reduce( - (prev: Record, curr) => { - prev[curr.accessor] = curr.accessor; - return prev; - }, - {}, -); export interface DynamicPath { key: string; value?: string; @@ -319,7 +245,6 @@ export const unsafeFunctionForEval = [ "setInterval", "clearInterval", "setImmediate", - "importScripts", "Navigator", ]; diff --git a/app/client/src/utils/MessageUtil.ts b/app/client/src/utils/MessageUtil.ts new file mode 100644 index 0000000000..2ec62575d3 --- /dev/null +++ b/app/client/src/utils/MessageUtil.ts @@ -0,0 +1,47 @@ +/** + * This file contains the utility function to send and receive messages from the worker. + * TRequestMessage is used to send a request to/from the worker. + * TResponseMessage is used to send a response to/from the worker. + * TDefaultMessage is used to send a message to/from worker. Does not expect a response. + */ + +export enum MessageType { + REQUEST = "REQUEST", + RESPONSE = "RESPONSE", + DEFAULT = "DEFAULT", +} + +type TRequestMessage = { + body: TBody; + messageId: string; + messageType: MessageType.REQUEST; +}; + +type TResponseMessage = { + body: TBody; + messageId: string; + messageType: MessageType.RESPONSE; +}; + +type TDefaultMessage = { + body: TBody; + messageType: MessageType.DEFAULT; +}; + +export type TMessage = + | TRequestMessage + | TResponseMessage + | TDefaultMessage; + +/** Avoid from using postMessage directly. + * This function should be used to send messages to the worker and back. + * Purpose: To have some standardization in the messages that are transferred. + * TODO: Add support for window postMessage options + * TODO: Add support for transferable objects. + */ +export function sendMessage( + this: Worker | typeof globalThis, + message: TMessage, +) { + this.postMessage(message); +} diff --git a/app/client/src/utils/WorkerUtil.test.ts b/app/client/src/utils/WorkerUtil.test.ts index d852a299fa..5cd61df5db 100644 --- a/app/client/src/utils/WorkerUtil.test.ts +++ b/app/client/src/utils/WorkerUtil.test.ts @@ -56,8 +56,9 @@ class MockWorkerClass implements WorkerClass { this.messages.push(message); const counter = setTimeout(() => { const response = { - requestId: message.requestId, - responseData: message.requestData, + messageId: message.messageId, + messageType: "RESPONSE", + body: { data: message.body.data }, }; this.sendEvent({ data: response }); this.responses.delete(counter); @@ -218,65 +219,4 @@ describe("GracefulWorkerService", () => { await shutdown.toPromise(); expect(await task.toPromise()).not.toEqual(message); }); - - test("duplex request starter", async () => { - const MockWorker = new MockWorkerClass(); - const w = new GracefulWorkerService(MockWorker); - await runSaga({}, w.start); - // Need this to work with eslint - if (MockWorker.instance === undefined) { - expect(MockWorker.instance).toBeDefined(); - return; - } - const requestData = { message: "Hello" }; - const method = "duplex_test"; - MockWorker.instance.postMessage = jest.fn(); - const duplexRequest = await runSaga( - {}, - w.duplexRequest, - method, - requestData, - ); - const handlers = await duplexRequest.toPromise(); - expect(handlers).toHaveProperty("isFinishedChannel"); - expect(MockWorker.instance.postMessage).toBeCalledWith({ - method, - requestData, - requestId: expect.stringContaining(method), - }); - }); - - test("duplex response channel handler", async () => { - const MockWorker = new MockWorkerClass(); - const w = new GracefulWorkerService(MockWorker); - await runSaga({}, w.start); - - // Need this to work with eslint - if (MockWorker.instance === undefined) { - expect(MockWorker.instance).toBeDefined(); - return; - } - const mainThreadResponseChannel = channel(); - const workerRequestId = "testID"; - runSaga( - {}, - // @ts-expect-error: type mismatch - w.duplexResponseHandler, - mainThreadResponseChannel, - ); - MockWorker.instance.postMessage = jest.fn(); - - let randomRequestCount = Math.floor(Math.random() * 10); - - for (randomRequestCount; randomRequestCount > 0; randomRequestCount--) { - mainThreadResponseChannel.put({ - test: randomRequestCount, - requestId: workerRequestId, - }); - expect(MockWorker.instance.postMessage).toBeCalledWith({ - test: randomRequestCount, - requestId: workerRequestId, - }); - } - }); }); diff --git a/app/client/src/utils/WorkerUtil.ts b/app/client/src/utils/WorkerUtil.ts index 122d54dc8a..14d90d1a94 100644 --- a/app/client/src/utils/WorkerUtil.ts +++ b/app/client/src/utils/WorkerUtil.ts @@ -1,8 +1,9 @@ -import { cancelled, delay, put, spawn, take } from "redux-saga/effects"; +import { cancelled, delay, put, take } from "redux-saga/effects"; import { channel, Channel, buffers } from "redux-saga"; import { uniqueId } from "lodash"; import log from "loglevel"; -// import { executeDynamicTriggerRequest } from "sagas/EvaluationsSaga"; +import { TMessage, MessageType, sendMessage } from "./MessageUtil"; + /** * Wrap a webworker to provide a synchronous request-response semantic. * @@ -30,7 +31,6 @@ import log from "loglevel"; * Note: The worker will hold ALL requests, even in case of restarts. * If we do not want that behaviour, we should create a new GracefulWorkerService. */ -// TODO: Add a compatible listener layer on the worker to complete the framework. // TODO: Extract the worker wrapper into a library to be useful to anyone with WebWorkers + redux-saga. // TODO: Add support for timeouts on requests and shutdown. // TODO: Add a readiness + liveness probes. @@ -50,24 +50,21 @@ export class GracefulWorkerService { private readonly _workerClass: Worker; - public mainThreadRequestChannel: Channel; - public mainThreadResponseChannel: Channel; + private listenerChannel: Channel>; constructor(workerClass: Worker) { this.shutdown = this.shutdown.bind(this); this.start = this.start.bind(this); - this.request = this.request.bind(this); this._broker = this._broker.bind(this); - this.duplexRequest = this.duplexRequest.bind(this); - this.duplexResponseHandler = this.duplexResponseHandler.bind(this); + this.request = this.request.bind(this); + this.respond = this.respond.bind(this); // Do not buffer messages on this channel this._readyChan = channel(buffers.none()); this._isReady = false; this._channels = new Map>(); this._workerClass = workerClass; - this.mainThreadRequestChannel = channel(); - this.mainThreadResponseChannel = channel(); + this.listenerChannel = channel(); } /** @@ -81,10 +78,7 @@ export class GracefulWorkerService { // Inform all pending requests that we're good to go! this._isReady = true; yield put(this._readyChan, true); - yield spawn(this.duplexResponseHandler, this.mainThreadResponseChannel); - return { - mainThreadRequestChannel: this.mainThreadRequestChannel, - }; + return this.listenerChannel; } /** @@ -104,8 +98,7 @@ export class GracefulWorkerService { this._Worker.removeEventListener("message", this._broker); this._Worker.terminate(); this._Worker = undefined; - this.mainThreadRequestChannel.close(); - this.mainThreadResponseChannel.close(); + this.listenerChannel.close(); } /** @@ -120,6 +113,20 @@ export class GracefulWorkerService { return false; } + *respond(messageId = "", data = {}): any { + if (!messageId) return; + yield this.ready(true); + if (!this._Worker) return; + const messageType = MessageType.RESPONSE; + sendMessage.call(this._Worker, { + body: { + data, + }, + messageId, + messageType, + }); + } + /** * Send a request to the worker for processing. * If the worker isn't ready, we wait for it to become ready. @@ -129,7 +136,7 @@ export class GracefulWorkerService { * * @returns response from the worker */ - *request(method: string, requestData = {}): any { + *request(method: string, data = {}): any { yield this.ready(true); // Impossible case, but helps avoid `?` later in code and makes it clearer. if (!this._Worker) return; @@ -137,22 +144,25 @@ export class GracefulWorkerService { /** * We create a unique channel to wait for a response of this specific request. */ - const requestId = `${method}__${uniqueId()}`; + const messageId = `${method}__${uniqueId()}`; const ch = channel(); - this._channels.set(requestId, ch); + this._channels.set(messageId, ch); const mainThreadStartTime = performance.now(); let timeTaken; try { - this._Worker.postMessage({ - method, - requestData, - requestId, + sendMessage.call(this._Worker, { + messageType: MessageType.REQUEST, + body: { + method, + data, + }, + messageId, }); // The `this._broker` method is listening to events and will pass response to us over this channel. const response = yield take(ch); timeTaken = response.timeTaken; - const { responseData } = response; + const { data: responseData } = response; return responseData; } finally { // Log perf of main thread and worker @@ -173,86 +183,23 @@ export class GracefulWorkerService { } // Cleanup ch.close(); - this._channels.delete(requestId); + this._channels.delete(messageId); } } - /** - * When there needs to be a back and forth between both the threads, - * you can use duplex request to avoid closing a channel - * */ - *duplexRequest(method: string, requestData = {}): any { - yield this.ready(false); - // Impossible case, but helps avoid `?` later in code and makes it clearer. - if (!this._Worker) return; - - /** - * We create a unique channel to wait for a response of this specific request. - */ - const workerRequestId = `${method}__${uniqueId()}`; - // The worker channel is the main channel - // where the web worker messages will get posted - const isFinishedChannel = channel(); - this._channels.set(workerRequestId, isFinishedChannel); - // And post the first message to the worker - this._Worker.postMessage({ - method, - requestData, - requestId: workerRequestId, - }); - - // Returning these channels to the main thread so that they can listen and post on it - return { - isFinishedChannel: isFinishedChannel, - }; - } - - *duplexResponseHandler(mainThreadResponseChannel: Channel) { - if (!this._Worker) return; - try { - const keepAlive = true; - while (keepAlive) { - // Wait for the main thread to respond back after a request - const response: { finished: unknown; requestId: string } = yield take( - mainThreadResponseChannel, - ); - // send response to worker - this._Worker.postMessage({ - ...response, - requestId: response.requestId, - }); - } - } catch (e) { - log.error(e); - } - } - - private _broker(event: MessageEvent) { - if (!event || !event.data) { - return; - } - const { promisified, requestId, responseData, timeTaken } = event.data; - const ch = this._channels.get(requestId); - // Channel could have been deleted if the request gets cancelled before the WebWorker can respond. - // In that case, we want to drop the request. - if (promisified) { - if (responseData.finished) { - if (ch) { - ch.put({ requestData: responseData, timeTaken, requestId }); - this._channels.delete(requestId); - } - } else { - this.mainThreadRequestChannel.put({ - requestData: responseData, - timeTaken, - requestId, - mainThreadResponseChannel: this.mainThreadResponseChannel, - }); + private _broker(event: MessageEvent>) { + if (!event || !event.data) return; + const { body, messageType } = event.data; + if (messageType === MessageType.RESPONSE) { + const { messageId } = event.data; + if (!messageId) return; + const ch = this._channels.get(messageId); + if (ch) { + ch.put(body); + this._channels.delete(messageId); } } else { - if (ch) { - ch.put({ responseData, timeTaken, requestId }); - } + this.listenerChannel.put(event.data); } } } diff --git a/app/client/src/utils/autocomplete/CodemirrorTernService.ts b/app/client/src/utils/autocomplete/CodemirrorTernService.ts index 8f4fb61051..0cc6be630d 100644 --- a/app/client/src/utils/autocomplete/CodemirrorTernService.ts +++ b/app/client/src/utils/autocomplete/CodemirrorTernService.ts @@ -1,6 +1,6 @@ /* eslint-disable @typescript-eslint/ban-ts-comment */ // Heavily inspired from https://github.com/codemirror/CodeMirror/blob/master/addon/tern/tern.js -import tern, { Server, Def } from "tern"; +import { Server, Def } from "tern"; import ecma from "constants/defs/ecmascript.json"; import lodash from "constants/defs/lodash.json"; import base64 from "constants/defs/base64-js.json"; @@ -147,13 +147,10 @@ class CodeMirrorTernService { this.server = new TernWorkerServer(this); } - resetServer() { - this.server = new tern.Server({ - async: true, - defs: DEFS, - }); + resetServer = () => { + this.server = new TernWorkerServer(this); this.docs = Object.create(null); - } + }; complete(cm: CodeMirror.Editor) { cm.showHint({ @@ -247,7 +244,7 @@ class CodeMirrorTernService { const dataType = getDataType(completion.type); if (data.guess) className += " " + cls + "guess"; let completionText = completion.name + after; - if (dataType === "FUNCTION") { + if (dataType === "FUNCTION" && !completion.origin?.startsWith("LIB/")) { completionText = completionText + "()"; } const codeMirrorCompletion: Completion = { diff --git a/app/client/src/utils/helpers.test.ts b/app/client/src/utils/helpers.test.ts index 1b6aea72fd..b3f2a8eb70 100644 --- a/app/client/src/utils/helpers.test.ts +++ b/app/client/src/utils/helpers.test.ts @@ -575,12 +575,9 @@ describe("isNameValid()", () => { it("works properly", () => { const invalidEntityNames = [ "console", - "moment", "Promise", "appsmith", "Math", - "_", - "forge", "yield", "Boolean", "ReferenceError", diff --git a/app/client/src/utils/helpers.tsx b/app/client/src/utils/helpers.tsx index e9ce4a1229..9cd7021f1a 100644 --- a/app/client/src/utils/helpers.tsx +++ b/app/client/src/utils/helpers.tsx @@ -13,7 +13,7 @@ import { get, set, isNil, has, uniq } from "lodash"; import { Workspace } from "@appsmith/constants/workspaceConstants"; import { hasCreateNewAppPermission } from "@appsmith/utils/permissionHelpers"; import moment from "moment"; -import { extraLibrariesNames, isDynamicValue } from "./DynamicBindingUtils"; +import { isDynamicValue } from "./DynamicBindingUtils"; import { ApiResponse } from "api/ApiResponses"; import { DSLWidget } from "widgets/constants"; import * as Sentry from "@sentry/react"; @@ -412,7 +412,6 @@ export const isNameValid = ( has(DATA_TREE_KEYWORDS, name) || has(DEDICATED_WORKER_GLOBAL_SCOPE_IDENTIFIERS, name) || has(APPSMITH_GLOBAL_FUNCTIONS, name) || - has(extraLibrariesNames, name) || has(invalidNames, name) ); }; diff --git a/app/client/src/workers/Evaluation/Actions.ts b/app/client/src/workers/Evaluation/Actions.ts index 66d1730766..eb80c10a21 100644 --- a/app/client/src/workers/Evaluation/Actions.ts +++ b/app/client/src/workers/Evaluation/Actions.ts @@ -300,7 +300,6 @@ export const DATA_TREE_FUNCTIONS: Record< export const enhanceDataTreeWithFunctions = ( dataTree: Readonly, - requestId = "", // Whether not to add functions like "run", "clear" to entity skipEntityFunctions = false, eventType?: EventType, @@ -324,7 +323,6 @@ export const enhanceDataTreeWithFunctions = ( pusher.bind( { TRIGGER_COLLECTOR: self.TRIGGER_COLLECTOR, - REQUEST_ID: requestId, EVENT_TYPE: eventType, }, func, @@ -339,7 +337,6 @@ export const enhanceDataTreeWithFunctions = ( pusher.bind( { TRIGGER_COLLECTOR: self.TRIGGER_COLLECTOR, - REQUEST_ID: requestId, }, funcOrFuncCreator, ), @@ -367,7 +364,6 @@ export const enhanceDataTreeWithFunctions = ( export const pusher = function( this: { TRIGGER_COLLECTOR: ActionDescription[]; - REQUEST_ID: string; EVENT_TYPE?: EventType; }, action: ActionDispatcherWithExecutionType, @@ -383,6 +379,6 @@ export const pusher = function( if (executionType && executionType === ExecutionType.TRIGGER) { this.TRIGGER_COLLECTOR.push(actionPayload); } else { - return promisifyAction(this.REQUEST_ID, actionPayload, this.EVENT_TYPE); + return promisifyAction(actionPayload, this.EVENT_TYPE); } }; diff --git a/app/client/src/workers/Evaluation/PromisifyAction.ts b/app/client/src/workers/Evaluation/PromisifyAction.ts index 1a3e5bf6e0..3127547837 100644 --- a/app/client/src/workers/Evaluation/PromisifyAction.ts +++ b/app/client/src/workers/Evaluation/PromisifyAction.ts @@ -1,4 +1,4 @@ -import { createGlobalData, EvalResult } from "workers/Evaluation/evaluate"; +import { createGlobalData } from "workers/Evaluation/evaluate"; const ctx: Worker = self as any; /* @@ -8,17 +8,14 @@ const ctx: Worker = self as any; * * needs a REQUEST_ID to be passed in to know which request is going on right now */ -import { EVAL_WORKER_ACTIONS } from "utils/DynamicBindingUtils"; -import { - ActionDescription, - ActionTriggerType, -} from "entities/DataTree/actionTriggers"; +import { ActionDescription } from "entities/DataTree/actionTriggers"; import _ from "lodash"; import { EventType } from "constants/AppsmithActionConstants/ActionConstants"; -import { dataTreeEvaluator } from "workers/Evaluation/evaluation.worker"; +import { dataTreeEvaluator } from "./handlers/evalTree"; +import { TMessage, sendMessage, MessageType } from "utils/MessageUtil"; +import { MAIN_THREAD_ACTION } from "./evalWorkerActions"; export const promisifyAction = ( - workerRequestId: string, actionDescription: ActionDescription, eventType?: EventType, ) => { @@ -31,34 +28,32 @@ export const promisifyAction = ( self.IS_ASYNC = true; throw new Error("Async function called in a sync field"); } - const workerRequestIdCopy = workerRequestId.concat(""); return new Promise((resolve, reject) => { // We create a new sub request id for each request going on so that we can resolve the correct one later on - const subRequestId = _.uniqueId(`${workerRequestIdCopy}_`); + const messageId = _.uniqueId(`${actionDescription.type}_`); // send an execution request to the main thread - const responseData = { + const data = { trigger: actionDescription, - errors: [], - subRequestId, eventType, }; - ctx.postMessage({ - type: EVAL_WORKER_ACTIONS.PROCESS_TRIGGER, - responseData, - requestId: workerRequestIdCopy, - promisified: true, + sendMessage.call(ctx, { + messageId, + messageType: MessageType.REQUEST, + body: { + method: MAIN_THREAD_ACTION.PROCESS_TRIGGER, + data, + }, }); - const processResponse = function(event: MessageEvent) { - const { data, eventType, method, requestId, success } = event.data; + const processResponse = function(event: MessageEvent>) { + const { messageType } = event.data; + if (messageType !== MessageType.RESPONSE) return; + const { body, messageId: resMessageId } = event.data; + const { data: messageData } = body; + const { data, eventType, success } = messageData; // This listener will get all the messages that come to the worker // we need to find the correct one pertaining to this promise - if ( - method === EVAL_WORKER_ACTIONS.PROCESS_TRIGGER && - requestId === workerRequestIdCopy && - subRequestId === event.data.data.subRequestId - ) { + if (resMessageId === messageId && messageType === MessageType.RESPONSE) { // If we get a response for this same promise we will resolve or reject it - // We could not find a data tree evaluator, // maybe the page changed, or we have a cyclical dependency if (!dataTreeEvaluator) { @@ -71,7 +66,6 @@ export const promisifyAction = ( resolvedFunctions: dataTreeEvaluator.resolvedFunctions, isTriggerBased: true, context: { - requestId: workerRequestId, eventType, }, }); @@ -94,31 +88,3 @@ export const promisifyAction = ( ctx.addEventListener("message", processResponse); }); }; -// To indicate the main thread that the processing of the trigger is done -// we send a finished message -export const completePromise = (requestId: string, result: EvalResult) => { - ctx.postMessage({ - type: EVAL_WORKER_ACTIONS.PROCESS_TRIGGER, - responseData: { - finished: true, - result, - }, - requestId, - promisified: true, - }); -}; - -export const confirmationPromise = function( - requestId: string, - func: any, - name: string, - ...args: any[] -) { - const payload: ActionDescription = { - type: ActionTriggerType.CONFIRMATION_MODAL, - payload: { - funName: name, - }, - }; - return promisifyAction(requestId, payload).then(() => func(...args)); -}; diff --git a/app/client/src/workers/Evaluation/SetupDOM.ts b/app/client/src/workers/Evaluation/SetupDOM.ts new file mode 100644 index 0000000000..41852b9812 --- /dev/null +++ b/app/client/src/workers/Evaluation/SetupDOM.ts @@ -0,0 +1,16 @@ +//@ts-expect-error no types. +import * as documentMock from "linkedom/worker"; + +export const DOM_APIS = Object.keys(documentMock).reduce((acc, key) => { + acc[key] = true; + return acc; +}, {} as Record); + +export default function() { + for (const [key, value] of Object.entries(documentMock)) { + //@ts-expect-error no types + self[key] = value; + } + const dom = documentMock.parseHTML(``); + self.document = dom.window.document; +} diff --git a/app/client/src/workers/Evaluation/TimeoutOverride.ts b/app/client/src/workers/Evaluation/TimeoutOverride.ts index 3d5c9f2d3c..ce5d4e53ea 100644 --- a/app/client/src/workers/Evaluation/TimeoutOverride.ts +++ b/app/client/src/workers/Evaluation/TimeoutOverride.ts @@ -1,5 +1,5 @@ import { createGlobalData } from "./evaluate"; -import { dataTreeEvaluator } from "./evaluation.worker"; +import { dataTreeEvaluator } from "./handlers/evalTree"; export const _internalSetTimeout = self.setTimeout; export const _internalClearTimeout = self.clearTimeout; diff --git a/app/client/src/workers/Evaluation/UserLog.ts b/app/client/src/workers/Evaluation/UserLog.ts index db6a972c02..a37cb98ece 100644 --- a/app/client/src/workers/Evaluation/UserLog.ts +++ b/app/client/src/workers/Evaluation/UserLog.ts @@ -4,6 +4,8 @@ import { LogObject, Methods, Severity } from "entities/AppsmithConsole"; import { klona } from "klona/lite"; import moment from "moment"; import { TriggerMeta } from "sagas/ActionExecution/ActionExecutionSagas"; +import { sendMessage, MessageType } from "utils/MessageUtil"; +import { MAIN_THREAD_ACTION } from "./evalWorkerActions"; import { _internalClearTimeout, _internalSetTimeout } from "./TimeoutOverride"; class UserLog { @@ -11,13 +13,11 @@ class UserLog { private logs: LogObject[] = []; private flushLogTimerId: number | undefined; private requestInfo: { - requestId?: string; eventType?: EventType; triggerMeta?: TriggerMeta; } | null = null; public setCurrentRequestInfo(requestInfo: { - requestId?: string; eventType?: EventType; triggerMeta?: TriggerMeta; }) { @@ -28,14 +28,16 @@ class UserLog { if (this.flushLogTimerId) _internalClearTimeout(this.flushLogTimerId); this.flushLogTimerId = _internalSetTimeout(() => { const logs = this.flushLogs(); - self.postMessage({ - promisified: true, - responseData: { - logs, - eventType: this.requestInfo?.eventType, - triggerMeta: this.requestInfo?.triggerMeta, + sendMessage.call(self, { + messageType: MessageType.DEFAULT, + body: { + data: { + logs, + eventType: this.requestInfo?.eventType, + triggerMeta: this.requestInfo?.triggerMeta, + }, + method: MAIN_THREAD_ACTION.PROCESS_LOGS, }, - requestId: this.requestInfo?.requestId, }); }, this.flushLogsTimerDelay); } diff --git a/app/client/src/workers/Evaluation/__tests__/Actions.test.ts b/app/client/src/workers/Evaluation/__tests__/Actions.test.ts index 33a1b6817e..f48059cbd9 100644 --- a/app/client/src/workers/Evaluation/__tests__/Actions.test.ts +++ b/app/client/src/workers/Evaluation/__tests__/Actions.test.ts @@ -2,6 +2,7 @@ import { DataTree, ENTITY_TYPE } from "entities/DataTree/dataTreeFactory"; import { PluginType } from "entities/Action"; import { createGlobalData } from "workers/Evaluation/evaluate"; import uniqueId from "lodash/uniqueId"; +import { MessageType } from "utils/MessageUtil"; jest.mock("lodash/uniqueId"); describe("Add functions", () => { @@ -39,6 +40,12 @@ describe("Add functions", () => { }, }); + const messageCreator = (type: string, body: unknown) => ({ + messageId: expect.stringContaining(type), + messageType: MessageType.REQUEST, + body, + }); + beforeEach(() => { workerEventMock.mockReset(); self.postMessage = workerEventMock; @@ -119,43 +126,39 @@ describe("Add functions", () => { expect( dataTreeWithFunctions.action1.run(null, null, actionParams), ).resolves.toBe({ a: "b" }); - expect(workerEventMock).lastCalledWith({ - type: "PROCESS_TRIGGER", - requestId: "EVAL_TRIGGER", - promisified: true, - responseData: { - errors: [], - subRequestId: expect.stringContaining("EVAL_TRIGGER_"), - trigger: { - type: "RUN_PLUGIN_ACTION", - payload: { - actionId: "123", - params: { param1: "value1" }, + expect(workerEventMock).lastCalledWith( + messageCreator("RUN_PLUGIN_ACTION", { + data: { + trigger: { + type: "RUN_PLUGIN_ACTION", + payload: { + actionId: "123", + params: { param1: "value1" }, + }, }, }, - }, - }); + method: "PROCESS_TRIGGER", + }), + ); // Old syntax works with undefined values is treated as new syntax expect( dataTreeWithFunctions.action1.run(undefined, undefined, actionParams), ).resolves.toBe({ a: "b" }); - expect(workerEventMock).lastCalledWith({ - type: "PROCESS_TRIGGER", - requestId: "EVAL_TRIGGER", - promisified: true, - responseData: { - errors: [], - subRequestId: expect.stringContaining("EVAL_TRIGGER_"), - trigger: { - type: "RUN_PLUGIN_ACTION", - payload: { - actionId: "123", - params: { param1: "value1" }, + expect(workerEventMock).lastCalledWith( + messageCreator("RUN_PLUGIN_ACTION", { + data: { + trigger: { + type: "RUN_PLUGIN_ACTION", + payload: { + actionId: "123", + params: { param1: "value1" }, + }, }, }, - }, - }); + method: "PROCESS_TRIGGER", + }), + ); // new syntax works expect( @@ -164,60 +167,55 @@ describe("Add functions", () => { .then(onSuccess) .catch(onError), ).resolves.toBe({ a: "b" }); - expect(workerEventMock).lastCalledWith({ - type: "PROCESS_TRIGGER", - requestId: "EVAL_TRIGGER", - promisified: true, - responseData: { - errors: [], - subRequestId: expect.stringContaining("EVAL_TRIGGER_"), - trigger: { - type: "RUN_PLUGIN_ACTION", - payload: { - actionId: "123", - params: { param1: "value1" }, + expect(workerEventMock).lastCalledWith( + messageCreator("RUN_PLUGIN_ACTION", { + data: { + trigger: { + type: "RUN_PLUGIN_ACTION", + payload: { + actionId: "123", + params: { param1: "value1" }, + }, }, }, - }, - }); + method: "PROCESS_TRIGGER", + }), + ); // New syntax without params expect(dataTreeWithFunctions.action1.run()).resolves.toBe({ a: "b" }); - expect(workerEventMock).lastCalledWith({ - type: "PROCESS_TRIGGER", - requestId: "EVAL_TRIGGER", - promisified: true, - responseData: { - errors: [], - subRequestId: expect.stringContaining("EVAL_TRIGGER_"), - trigger: { - type: "RUN_PLUGIN_ACTION", - payload: { - actionId: "123", - params: {}, + expect(workerEventMock).lastCalledWith( + messageCreator("RUN_PLUGIN_ACTION", { + data: { + trigger: { + type: "RUN_PLUGIN_ACTION", + payload: { + actionId: "123", + params: {}, + }, }, }, - }, - }); + method: "PROCESS_TRIGGER", + }), + ); }); it("action.clear works", () => { expect(dataTreeWithFunctions.action1.clear()).resolves.toBe({}); - expect(workerEventMock).lastCalledWith({ - type: "PROCESS_TRIGGER", - requestId: "EVAL_TRIGGER", - promisified: true, - responseData: { - errors: [], - subRequestId: expect.stringContaining("EVAL_TRIGGER_"), - trigger: { - type: "CLEAR_PLUGIN_ACTION", - payload: { - actionId: "123", + expect(workerEventMock).lastCalledWith( + messageCreator("CLEAR_PLUGIN_ACTION", { + data: { + trigger: { + type: "CLEAR_PLUGIN_ACTION", + payload: { + actionId: "123", + }, }, + eventType: undefined, }, - }, - }); + method: "PROCESS_TRIGGER", + }), + ); }); it("navigateTo works", () => { @@ -228,87 +226,82 @@ describe("Add functions", () => { expect( dataTreeWithFunctions.navigateTo(pageNameOrUrl, params, target), ).resolves.toBe({}); - - expect(workerEventMock).lastCalledWith({ - type: "PROCESS_TRIGGER", - requestId: "EVAL_TRIGGER", - promisified: true, - responseData: { - errors: [], - subRequestId: expect.stringContaining("EVAL_TRIGGER_"), - trigger: { - type: "NAVIGATE_TO", - payload: { - pageNameOrUrl, - params, - target, + expect(workerEventMock).lastCalledWith( + messageCreator("NAVIGATE_TO", { + data: { + trigger: { + type: "NAVIGATE_TO", + payload: { + pageNameOrUrl, + params, + target, + }, }, + eventType: undefined, }, - }, - }); + method: "PROCESS_TRIGGER", + }), + ); }); it("showAlert works", () => { const message = "Alert message"; const style = "info"; expect(dataTreeWithFunctions.showAlert(message, style)).resolves.toBe({}); - expect(workerEventMock).lastCalledWith({ - type: "PROCESS_TRIGGER", - requestId: "EVAL_TRIGGER", - promisified: true, - responseData: { - errors: [], - subRequestId: expect.stringContaining("EVAL_TRIGGER_"), - trigger: { - type: "SHOW_ALERT", - payload: { - message, - style, + expect(workerEventMock).lastCalledWith( + messageCreator("SHOW_ALERT", { + data: { + trigger: { + type: "SHOW_ALERT", + payload: { + message, + style, + }, }, + eventType: undefined, }, - }, - }); + method: "PROCESS_TRIGGER", + }), + ); }); it("showModal works", () => { const modalName = "Modal 1"; expect(dataTreeWithFunctions.showModal(modalName)).resolves.toBe({}); - expect(workerEventMock).lastCalledWith({ - type: "PROCESS_TRIGGER", - requestId: "EVAL_TRIGGER", - promisified: true, - responseData: { - errors: [], - subRequestId: expect.stringContaining("EVAL_TRIGGER_"), - trigger: { - type: "SHOW_MODAL_BY_NAME", - payload: { - modalName, + expect(workerEventMock).lastCalledWith( + messageCreator("SHOW_MODAL_BY_NAME", { + data: { + trigger: { + type: "SHOW_MODAL_BY_NAME", + payload: { + modalName, + }, }, + eventType: undefined, }, - }, - }); + method: "PROCESS_TRIGGER", + }), + ); }); it("closeModal works", () => { const modalName = "Modal 1"; expect(dataTreeWithFunctions.closeModal(modalName)).resolves.toBe({}); - expect(workerEventMock).lastCalledWith({ - type: "PROCESS_TRIGGER", - requestId: "EVAL_TRIGGER", - promisified: true, - responseData: { - errors: [], - subRequestId: expect.stringContaining("EVAL_TRIGGER_"), - trigger: { - type: "CLOSE_MODAL", - payload: { - modalName, + expect(workerEventMock).lastCalledWith( + messageCreator("CLOSE_MODAL", { + data: { + trigger: { + type: "CLOSE_MODAL", + payload: { + modalName, + }, }, + eventType: undefined, }, - }, - }); + method: "PROCESS_TRIGGER", + }), + ); }); it("storeValue works", () => { @@ -323,62 +316,58 @@ describe("Add functions", () => { expect(dataTreeWithFunctions.storeValue(key, value, persist)).resolves.toBe( {}, ); - expect(workerEventMock).lastCalledWith({ - type: "PROCESS_TRIGGER", - requestId: "EVAL_TRIGGER", - promisified: true, - responseData: { - errors: [], - subRequestId: expect.stringContaining("EVAL_TRIGGER_"), - trigger: { - type: "STORE_VALUE", - payload: { - key, - value, - persist, - uniqueActionRequestId, + expect(workerEventMock).lastCalledWith( + messageCreator("STORE_VALUE", { + data: { + trigger: { + type: "STORE_VALUE", + payload: { + key, + value, + persist, + uniqueActionRequestId, + }, }, + eventType: undefined, }, - }, - }); + method: "PROCESS_TRIGGER", + }), + ); }); it("removeValue works", () => { const key = "some"; - expect(dataTreeWithFunctions.removeValue(key)).resolves.toBe({}); - expect(workerEventMock).lastCalledWith({ - type: "PROCESS_TRIGGER", - requestId: "EVAL_TRIGGER", - promisified: true, - responseData: { - errors: [], - subRequestId: expect.stringContaining("EVAL_TRIGGER_"), - trigger: { - type: "REMOVE_VALUE", - payload: { - key, + expect(workerEventMock).lastCalledWith( + messageCreator("REMOVE_VALUE", { + data: { + trigger: { + type: "REMOVE_VALUE", + payload: { + key, + }, }, + eventType: undefined, }, - }, - }); + method: "PROCESS_TRIGGER", + }), + ); }); it("clearStore works", () => { expect(dataTreeWithFunctions.clearStore()).resolves.toBe({}); - expect(workerEventMock).lastCalledWith({ - type: "PROCESS_TRIGGER", - requestId: "EVAL_TRIGGER", - promisified: true, - responseData: { - errors: [], - subRequestId: expect.stringContaining("EVAL_TRIGGER_"), - trigger: { - type: "CLEAR_STORE", - payload: null, + expect(workerEventMock).lastCalledWith( + messageCreator("CLEAR_STORE", { + data: { + trigger: { + type: "CLEAR_STORE", + payload: null, + }, + eventType: undefined, }, - }, - }); + method: "PROCESS_TRIGGER", + }), + ); }); it("download works", () => { @@ -387,44 +376,42 @@ describe("Add functions", () => { const type = "text"; expect(dataTreeWithFunctions.download(data, name, type)).resolves.toBe({}); - expect(workerEventMock).lastCalledWith({ - type: "PROCESS_TRIGGER", - requestId: "EVAL_TRIGGER", - promisified: true, - responseData: { - errors: [], - subRequestId: expect.stringContaining("EVAL_TRIGGER_"), - trigger: { - type: "DOWNLOAD", - payload: { - data, - name, - type, + expect(workerEventMock).lastCalledWith( + messageCreator("DOWNLOAD", { + data: { + trigger: { + type: "DOWNLOAD", + payload: { + data, + name, + type, + }, }, + eventType: undefined, }, - }, - }); + method: "PROCESS_TRIGGER", + }), + ); }); it("copyToClipboard works", () => { const data = "file"; expect(dataTreeWithFunctions.copyToClipboard(data)).resolves.toBe({}); - expect(workerEventMock).lastCalledWith({ - type: "PROCESS_TRIGGER", - requestId: "EVAL_TRIGGER", - promisified: true, - responseData: { - errors: [], - subRequestId: expect.stringContaining("EVAL_TRIGGER_"), - trigger: { - type: "COPY_TO_CLIPBOARD", - payload: { - data, - options: { debug: undefined, format: undefined }, + expect(workerEventMock).lastCalledWith( + messageCreator("COPY_TO_CLIPBOARD", { + data: { + trigger: { + type: "COPY_TO_CLIPBOARD", + payload: { + data, + options: { debug: undefined, format: undefined }, + }, }, + eventType: undefined, }, - }, - }); + method: "PROCESS_TRIGGER", + }), + ); }); it("resetWidget works", () => { @@ -434,22 +421,21 @@ describe("Add functions", () => { expect( dataTreeWithFunctions.resetWidget(widgetName, resetChildren), ).resolves.toBe({}); - expect(workerEventMock).lastCalledWith({ - type: "PROCESS_TRIGGER", - requestId: "EVAL_TRIGGER", - promisified: true, - responseData: { - errors: [], - subRequestId: expect.stringContaining("EVAL_TRIGGER_"), - trigger: { - type: "RESET_WIDGET_META_RECURSIVE_BY_NAME", - payload: { - widgetName, - resetChildren, + expect(workerEventMock).lastCalledWith( + messageCreator("RESET_WIDGET_META_RECURSIVE_BY_NAME", { + data: { + trigger: { + type: "RESET_WIDGET_META_RECURSIVE_BY_NAME", + payload: { + widgetName, + resetChildren, + }, }, + eventType: undefined, }, - }, - }); + method: "PROCESS_TRIGGER", + }), + ); }); it("setInterval works", () => { diff --git a/app/client/src/workers/Evaluation/__tests__/PromisifyAction.test.ts b/app/client/src/workers/Evaluation/__tests__/PromisifyAction.test.ts index 0101522e4c..e703e825bd 100644 --- a/app/client/src/workers/Evaluation/__tests__/PromisifyAction.test.ts +++ b/app/client/src/workers/Evaluation/__tests__/PromisifyAction.test.ts @@ -1,6 +1,7 @@ import { createGlobalData } from "workers/Evaluation/evaluate"; import _ from "lodash"; -jest.mock("../evaluation.worker.ts", () => { +import { MessageType } from "utils/MessageUtil"; +jest.mock("../handlers/evalTree", () => { return { dataTreeEvaluator: { evalTree: {}, @@ -19,6 +20,12 @@ describe("promise execution", () => { context: { requestId }, }); + const requestMessageCreator = (type: string, body: unknown) => ({ + messageId: expect.stringContaining(`${type}_`), + messageType: MessageType.REQUEST, + body, + }); + beforeEach(() => { self.ALLOW_ASYNC = true; self.postMessage = postMessageMock; @@ -36,21 +43,20 @@ describe("promise execution", () => { }); it("sends an event from the worker", () => { dataTreeWithFunctions.showAlert("test alert", "info"); - expect(postMessageMock).toBeCalledWith({ - requestId, - type: "PROCESS_TRIGGER", - promisified: true, - responseData: expect.objectContaining({ - subRequestId: expect.stringContaining(`${requestId}_`), - trigger: { - type: "SHOW_ALERT", - payload: { - message: "test alert", - style: "info", + expect(postMessageMock).toBeCalledWith( + requestMessageCreator("SHOW_ALERT", { + data: { + trigger: { + type: "SHOW_ALERT", + payload: { + message: "test alert", + style: "info", + }, }, }, + method: "PROCESS_TRIGGER", }), - }); + ); }); it("returns a promise that resolves", async () => { postMessageMock.mockReset(); @@ -59,15 +65,23 @@ describe("promise execution", () => { "info", ); const requestArgs = postMessageMock.mock.calls[0][0]; - const subRequestId = requestArgs.responseData.subRequestId; + console.log(requestArgs); + const messageId = requestArgs.messageId; self.dispatchEvent( new MessageEvent("message", { data: { - data: { resolve: ["123"], subRequestId }, - method: "PROCESS_TRIGGER", - requestId, - success: true, + messageId, + messageType: MessageType.RESPONSE, + body: { + data: { + data: { resolve: ["123"] }, + method: "PROCESS_TRIGGER", + requestId, + success: true, + }, + method: "PROCESS_TRIGGER", + }, }, }), ); @@ -82,14 +96,15 @@ describe("promise execution", () => { "info", ); const requestArgs = postMessageMock.mock.calls[0][0]; - const subRequestId = requestArgs.responseData.subRequestId; self.dispatchEvent( new MessageEvent("message", { data: { - data: { reason: "testing", subRequestId }, - method: "PROCESS_TRIGGER", - requestId, - success: false, + messageId: requestArgs.messageId, + messageType: MessageType.RESPONSE, + body: { + data: { data: { reason: "testing" }, success: false }, + method: "PROCESS_TRIGGER", + }, }, }), ); @@ -104,20 +119,22 @@ describe("promise execution", () => { ); const requestArgs = postMessageMock.mock.calls[0][0]; - const correctSubRequestId = requestArgs.responseData.subRequestId; - const differentSubRequestId = "wrongRequestId"; + const correctId = requestArgs.messageId; self.dispatchEvent( new MessageEvent("message", { data: { - data: { - resolve: ["wrongRequest"], - subRequestId: differentSubRequestId, + messageId: "wrongMessageId", + messageType: MessageType.RESPONSE, + body: { + data: { + data: { + resolve: ["wrongRequest"], + }, + success: true, + }, + method: "PROCESS_TRIGGER", }, - method: "PROCESS_TRIGGER", - requestId, - success: true, - promisified: true, }, }), ); @@ -125,10 +142,17 @@ describe("promise execution", () => { self.dispatchEvent( new MessageEvent("message", { data: { - data: { resolve: ["testing"], subRequestId: correctSubRequestId }, - method: "PROCESS_TRIGGER", - requestId, - success: true, + messageId: correctId, + messageType: MessageType.RESPONSE, + body: { + data: { + data: { + resolve: ["testing"], + }, + success: true, + }, + method: "PROCESS_TRIGGER", + }, }, }), ); @@ -143,19 +167,22 @@ describe("promise execution", () => { ); const requestArgs = postMessageMock.mock.calls[0][0]; - const subRequestId = requestArgs.responseData.subRequestId; + const messageId = requestArgs.messageId; self.dispatchEvent( new MessageEvent("message", { data: { - data: { - resolve: ["testing"], - subRequestId, + messageId, + messageType: MessageType.RESPONSE, + body: { + data: { + data: { + resolve: ["testing"], + }, + success: true, + }, + method: "PROCESS_TRIGGER", }, - method: "PROCESS_TRIGGER", - requestId, - success: true, - promisified: true, }, }), ); @@ -163,11 +190,12 @@ describe("promise execution", () => { self.dispatchEvent( new MessageEvent("message", { data: { - data: { resolve: ["wrongRequest"], subRequestId }, - method: "PROCESS_TRIGGER", - requestId, - success: false, - promisified: true, + messageId, + messageType: MessageType.RESPONSE, + body: { + data: { data: { resolve: ["wrongRequest"] }, success: true }, + method: "PROCESS_TRIGGER", + }, }, }), ); diff --git a/app/client/src/workers/Evaluation/__tests__/evaluate.test.ts b/app/client/src/workers/Evaluation/__tests__/evaluate.test.ts index 753c9bbf8d..0f9d4ede14 100644 --- a/app/client/src/workers/Evaluation/__tests__/evaluate.test.ts +++ b/app/client/src/workers/Evaluation/__tests__/evaluate.test.ts @@ -1,5 +1,4 @@ import evaluate, { - setupEvaluationEnvironment, evaluateAsync, isFunctionAsync, } from "workers/Evaluation/evaluate"; @@ -9,6 +8,7 @@ import { ENTITY_TYPE, } from "entities/DataTree/dataTreeFactory"; import { RenderModes } from "constants/WidgetConstants"; +import setupEvalEnv from "../handlers/setupEvalEnv"; describe("evaluateSync", () => { const widget: DataTreeWidget = { @@ -40,7 +40,7 @@ describe("evaluateSync", () => { Input1: widget, }; beforeAll(() => { - setupEvaluationEnvironment(); + setupEvalEnv(); }); it("unescapes string before evaluation", () => { const js = '\\"Hello!\\"'; @@ -192,45 +192,32 @@ describe("evaluateAsync", () => { it("runs and completes", async () => { const js = "(() => new Promise((resolve) => { resolve(123) }))()"; self.postMessage = jest.fn(); - await evaluateAsync(js, {}, "TEST_REQUEST", {}); - expect(self.postMessage).toBeCalledWith({ - requestId: "TEST_REQUEST", - promisified: true, - responseData: { - finished: true, - result: { errors: [], logs: [], result: 123, triggers: [] }, - }, - type: "PROCESS_TRIGGER", + const response = await evaluateAsync(js, {}, {}, {}); + expect(response).toStrictEqual({ + errors: [], + logs: [], + result: 123, + triggers: [], }); }); it("runs and returns errors", async () => { jest.restoreAllMocks(); const js = "(() => new Promise((resolve) => { randomKeyword }))()"; self.postMessage = jest.fn(); - await evaluateAsync(js, {}, "TEST_REQUEST_1", {}); - expect(self.postMessage).toBeCalledWith({ - requestId: "TEST_REQUEST_1", - promisified: true, - responseData: { - finished: true, - result: { - errors: [ - { - errorMessage: expect.stringContaining( - "randomKeyword is not defined", - ), - errorType: "PARSE", - originalBinding: expect.stringContaining("Promise"), - raw: expect.stringContaining("Promise"), - severity: "error", - }, - ], - triggers: [], - result: undefined, - logs: [], + const result = await evaluateAsync(js, {}, {}, {}); + expect(result).toStrictEqual({ + errors: [ + { + errorMessage: expect.stringContaining("randomKeyword is not defined"), + errorType: "PARSE", + originalBinding: expect.stringContaining("Promise"), + raw: expect.stringContaining("Promise"), + severity: "error", }, - }, - type: "PROCESS_TRIGGER", + ], + triggers: [], + result: undefined, + logs: [], }); }); }); diff --git a/app/client/src/workers/Evaluation/timeout.test.ts b/app/client/src/workers/Evaluation/__tests__/timeout.test.ts similarity index 96% rename from app/client/src/workers/Evaluation/timeout.test.ts rename to app/client/src/workers/Evaluation/__tests__/timeout.test.ts index 69e813576e..57901760ee 100644 --- a/app/client/src/workers/Evaluation/timeout.test.ts +++ b/app/client/src/workers/Evaluation/__tests__/timeout.test.ts @@ -1,8 +1,8 @@ import { PluginType } from "entities/Action"; import { DataTree, ENTITY_TYPE } from "entities/DataTree/dataTreeFactory"; -import { createGlobalData } from "./evaluate"; -import "./TimeoutOverride"; -import overrideTimeout from "./TimeoutOverride"; +import { createGlobalData } from "../evaluate"; +import "../TimeoutOverride"; +import overrideTimeout from "../TimeoutOverride"; describe("Expects appsmith setTimeout to pass the following criteria", () => { overrideTimeout(); diff --git a/app/client/src/workers/Evaluation/evalWorkerActions.ts b/app/client/src/workers/Evaluation/evalWorkerActions.ts new file mode 100644 index 0000000000..3cd1aafc2a --- /dev/null +++ b/app/client/src/workers/Evaluation/evalWorkerActions.ts @@ -0,0 +1,33 @@ +export enum EVAL_WORKER_SYNC_ACTION { + SETUP = "SETUP", + EVAL_TREE = "EVAL_TREE", + EVAL_ACTION_BINDINGS = "EVAL_ACTION_BINDINGS", + CLEAR_CACHE = "CLEAR_CACHE", + VALIDATE_PROPERTY = "VALIDATE_PROPERTY", + UNDO = "undo", + REDO = "redo", + UPDATE_REPLAY_OBJECT = "UPDATE_REPLAY_OBJECT", + SET_EVALUATION_VERSION = "SET_EVALUATION_VERSION", + INIT_FORM_EVAL = "INIT_FORM_EVAL", + EXECUTE_SYNC_JS = "EXECUTE_SYNC_JS", + INSTALL_LIBRARY = "INSTALL_LIBRARY", + UNINSTALL_LIBRARY = "UNINSTALL_LIBRARY", + LOAD_LIBRARIES = "LOAD_LIBRARIES", + LINT_TREE = "LINT_TREE", +} + +export enum EVAL_WORKER_ASYNC_ACTION { + EVAL_TRIGGER = "EVAL_TRIGGER", + EVAL_EXPRESSION = "EVAL_EXPRESSION", +} + +export const EVAL_WORKER_ACTIONS = { + ...EVAL_WORKER_SYNC_ACTION, + ...EVAL_WORKER_ASYNC_ACTION, +}; + +export const MAIN_THREAD_ACTION = { + PROCESS_TRIGGER: "PROCESS_TRIGGER", + PROCESS_LOGS: "PROCESS_LOGS", + LINT_TREE: "LINT_TREE", +}; diff --git a/app/client/src/workers/Evaluation/evaluate.ts b/app/client/src/workers/Evaluation/evaluate.ts index 272b4bbbb1..affc355bb4 100644 --- a/app/client/src/workers/Evaluation/evaluate.ts +++ b/app/client/src/workers/Evaluation/evaluate.ts @@ -2,22 +2,19 @@ import { DataTree } from "entities/DataTree/dataTreeFactory"; import { EvaluationError, - extraLibraries, PropertyEvaluationErrorType, - unsafeFunctionForEval, } from "utils/DynamicBindingUtils"; import unescapeJS from "unescape-js"; import { LogObject, Severity } from "entities/AppsmithConsole"; import { enhanceDataTreeWithFunctions } from "./Actions"; import { isEmpty } from "lodash"; -import { completePromise } from "workers/Evaluation/PromisifyAction"; import { ActionDescription } from "entities/DataTree/actionTriggers"; import userLogs from "./UserLog"; import { EventType } from "constants/AppsmithActionConstants/ActionConstants"; -import overrideTimeout from "./TimeoutOverride"; import { TriggerMeta } from "sagas/ActionExecution/ActionExecutionSagas"; -import interceptAndOverrideHttpRequest from "./HTTPRequestOverride"; import indirectEval from "./indirectEval"; +import { DOM_APIS } from "./SetupDOM"; +import { JSLibraries, libraryReservedIdentifiers } from "../common/JSLibrary"; export type EvalResult = { result: any; @@ -75,11 +72,19 @@ const topLevelWorkerAPIs = Object.keys(self).reduce((acc, key: string) => { function resetWorkerGlobalScope() { for (const key of Object.keys(self)) { - if (topLevelWorkerAPIs[key]) continue; - if (key === "evaluationVersion") continue; - if (extraLibraries.find((lib) => lib.accessor === key)) continue; - // @ts-expect-error: Types are not available - delete self[key]; + if (topLevelWorkerAPIs[key] || DOM_APIS[key]) continue; + //TODO: Remove this once we have a better way to handle this + if (["evaluationVersion", "window", "document", "location"].includes(key)) + continue; + if (JSLibraries.find((lib) => lib.accessor.includes(key))) continue; + if (libraryReservedIdentifiers[key]) continue; + try { + // @ts-expect-error: Types are not available + delete self[key]; + } catch (e) { + // @ts-expect-error: Types are not available + self[key] = undefined; + } } } @@ -98,6 +103,8 @@ export const getScriptType = ( return scriptType; }; +export const additionalLibrariesNames: string[] = []; + export const getScriptToEval = ( userScript: string, type: EvaluationScriptType, @@ -107,25 +114,7 @@ export const getScriptToEval = ( return `${buffer[0]}${userScript}${buffer[1]}`; }; -export function setupEvaluationEnvironment() { - ///// Adding extra libraries separately - extraLibraries.forEach((library) => { - // @ts-expect-error: Types are not available - self[library.accessor] = library.lib; - }); - - ///// Remove all unsafe functions - unsafeFunctionForEval.forEach((func) => { - // @ts-expect-error: Types are not available - self[func] = undefined; - }); - userLogs.overrideConsoleAPI(); - overrideTimeout(); - interceptAndOverrideHttpRequest(); -} - const beginsWithLineBreakRegex = /^\s+|\s+$/; - export interface createGlobalDataArgs { dataTree: DataTree; resolvedFunctions: Record; @@ -165,7 +154,6 @@ export const createGlobalData = (args: createGlobalDataArgs) => { //// Add internal functions to dataTree; const dataTreeWithFunctions = enhanceDataTreeWithFunctions( dataTree, - context?.requestId, skipEntityFunctions, context?.eventType, ); @@ -322,7 +310,6 @@ export default function evaluateSync( export async function evaluateAsync( userScript: string, dataTree: DataTree, - requestId: string, resolvedFunctions: Record, context?: EvaluateContext, evalArguments?: Array, @@ -335,7 +322,6 @@ export async function evaluateAsync( /**** Setting the eval context ****/ userLogs.resetLogs(); userLogs.setCurrentRequestInfo({ - requestId, eventType: context?.eventType, triggerMeta: context?.triggerMeta, }); @@ -343,7 +329,7 @@ export async function evaluateAsync( dataTree, resolvedFunctions, isTriggerBased: true, - context: { ...context, requestId }, + context, evalArguments, }); const { script } = getUserScriptToEvaluate(userScript, true, evalArguments); @@ -375,21 +361,12 @@ export async function evaluateAsync( // Adding this extra try catch because there are cases when logs have child objects // like functions or promises that cause issue in complete promise action, thus // leading the app into a bad state. - try { - completePromise(requestId, { - result, - errors, - logs, - triggers: Array.from(self.TRIGGER_COLLECTOR), - }); - } catch (error) { - completePromise(requestId, { - result, - errors, - logs: [userLogs.parseLogs("log", ["failed to parse logs"])], - triggers: Array.from(self.TRIGGER_COLLECTOR), - }); - } + return { + result, + errors, + logs, + triggers: Array.from(self.TRIGGER_COLLECTOR), + }; } })(); } @@ -419,21 +396,7 @@ export function isFunctionAsync( const dataTreeKey = GLOBAL_DATA[datum]; if (dataTreeKey) { const data = dataTreeKey[key]?.data; - //do not remove, we will be investigating this - // const isAsync = dataTreeKey.meta[key]?.isAsync || false; - // const confirmBeforeExecute = - // dataTreeKey.meta[key]?.confirmBeforeExecute || false; dataTreeKey[key] = resolvedObject[key]; - // if (isAsync && confirmBeforeExecute) { - // dataTreeKey[key] = confirmationPromise.bind( - // {}, - // "", - // resolvedObject[key], - // key, - // ); - // } else { - // dataTreeKey[key] = resolvedObject[key]; - // } if (!!data) { dataTreeKey[key].data = data; } diff --git a/app/client/src/workers/Evaluation/evaluation.worker.ts b/app/client/src/workers/Evaluation/evaluation.worker.ts index 8db4cc011f..9d4006cfbf 100644 --- a/app/client/src/workers/Evaluation/evaluation.worker.ts +++ b/app/client/src/workers/Evaluation/evaluation.worker.ts @@ -1,427 +1,72 @@ // Workers do not have access to log.error /* eslint-disable no-console */ -import { DataTree } from "entities/DataTree/dataTreeFactory"; -import { - DependencyMap, - EVAL_WORKER_ACTIONS, - EvalError, - EvalErrorTypes, -} from "utils/DynamicBindingUtils"; -import { - CrashingError, - DataTreeDiff, - getSafeToRenderDataTree, - removeFunctions, -} from "./evaluationUtils"; -import DataTreeEvaluator from "workers/common/DataTreeEvaluator"; -import ReplayEntity from "entities/Replay"; -import ReplayCanvas from "entities/Replay/ReplayEntity/ReplayCanvas"; -import ReplayEditor from "entities/Replay/ReplayEntity/ReplayEditor"; -import { isEmpty } from "lodash"; -import { UserLogObject } from "entities/AppsmithConsole"; import { WorkerErrorTypes } from "workers/common/types"; -import { - EvalTreeRequestData, - EvalTreeResponseData, - EvalWorkerRequest, - EvalWorkerResponse, -} from "./types"; -import { EvalMetaUpdates } from "workers/common/DataTreeEvaluator/types"; -import { setFormEvaluationSaga } from "workers/Evaluation/formEval"; -import evaluate, { - evaluateAsync, - setupEvaluationEnvironment, -} from "./evaluate"; -import { JSUpdate } from "utils/JSPaneUtils"; -import { validateWidgetProperty } from "workers/common/DataTreeEvaluator/validationUtils"; -import { initiateLinting } from "workers/Linting/utils"; -import { - createUnEvalTreeForEval, - makeEntityConfigsAsObjProperties, -} from "./dataTreeUtils"; - -const CANVAS = "canvas"; - -export let dataTreeEvaluator: DataTreeEvaluator | undefined; - -let replayMap: Record>; +import { EvalWorkerASyncRequest, EvalWorkerSyncRequest } from "./types"; +import { syncHandlerMap, asyncHandlerMap } from "./handlers"; +import { TMessage, sendMessage, MessageType } from "utils/MessageUtil"; //TODO: Create a more complete RPC setup in the subtree-eval branch. -function messageEventListener(fn: typeof eventRequestHandler) { - return (e: MessageEvent) => { - const startTime = performance.now(); - const { method, requestData, requestId } = e.data; - if (method) { - const responseData = fn({ method, requestData, requestId }); - if (responseData) { - const endTime = performance.now(); - try { - self.postMessage({ - requestId, - responseData, - timeTaken: (endTime - startTime).toFixed(2), - }); - } catch (e) { - console.error(e); - // we dont want to log dataTree because it is huge. - // eslint-disable-next-line @typescript-eslint/no-unused-vars - const { dataTree, ...rest } = requestData; - self.postMessage({ - requestId, - responseData: { - errors: [ - { - type: WorkerErrorTypes.CLONE_ERROR, - message: (e as Error)?.message, - context: JSON.stringify(rest), - }, - ], - }, - timeTaken: (endTime - startTime).toFixed(2), - }); - } - } - } - }; +function syncRequestMessageListener( + e: MessageEvent>, +) { + const { messageType } = e.data; + if (messageType !== MessageType.REQUEST) return; + const startTime = performance.now(); + const { body, messageId } = e.data; + const { method } = body; + if (!method) return; + const messageHandler = syncHandlerMap[method]; + if (typeof messageHandler !== "function") return; + const responseData = messageHandler(body); + if (!responseData) return; + const endTime = performance.now(); + respond(messageId, responseData, endTime - startTime); } -function eventRequestHandler({ - method, - requestData, - requestId, -}: EvalWorkerRequest): EvalWorkerResponse { - switch (method) { - case EVAL_WORKER_ACTIONS.SETUP: { - setupEvaluationEnvironment(); - return true; - } - case EVAL_WORKER_ACTIONS.EVAL_ACTION_BINDINGS: { - const { bindings, executionParams } = requestData; - if (!dataTreeEvaluator) { - return { values: undefined, errors: [] }; - } +async function asyncRequestMessageListener( + e: MessageEvent>, +) { + const { messageType } = e.data; + if (messageType !== MessageType.REQUEST) return; + const start = performance.now(); + const { body, messageId } = e.data; + const { method } = body; + if (!method) return; + const messageHandler = asyncHandlerMap[method]; + if (typeof messageHandler !== "function") return; + const data = await messageHandler(body); + if (!data) return; + const end = performance.now(); + respond(messageId, data, end - start); +} - const values = dataTreeEvaluator.evaluateActionBindings( - bindings, - executionParams, - ); - - const cleanValues = removeFunctions(values); - - const errors = dataTreeEvaluator.errors; - dataTreeEvaluator.clearErrors(); - return { values: cleanValues, errors }; - } - case EVAL_WORKER_ACTIONS.EVAL_TRIGGER: { - const { - callbackData, - dynamicTrigger, - eventType, - globalContext, - triggerMeta, - unEvalTree: __unEvalTree__, - } = requestData; - if (!dataTreeEvaluator) { - return { triggers: [], errors: [] }; - } - - const unEvalTree = createUnEvalTreeForEval(__unEvalTree__); - - const { - evalOrder, - nonDynamicFieldValidationOrder, - } = dataTreeEvaluator.setupUpdateTree(unEvalTree); - dataTreeEvaluator.evalAndValidateSubTree( - evalOrder, - nonDynamicFieldValidationOrder, - ); - const evalTree = dataTreeEvaluator.evalTree; - const resolvedFunctions = dataTreeEvaluator.resolvedFunctions; - - dataTreeEvaluator.evaluateTriggers( - dynamicTrigger, - evalTree, - requestId, - resolvedFunctions, - callbackData, - { - globalContext, - eventType, - triggerMeta, +function respond(messageId: string, data: unknown, timeTaken: number) { + try { + sendMessage.call(self, { + messageId, + messageType: MessageType.RESPONSE, + body: { data, timeTaken }, + }); + } catch (e) { + console.error(e); + sendMessage.call(self, { + messageId, + messageType: MessageType.RESPONSE, + body: { + timeTaken: timeTaken.toFixed(2), + data: { + errors: [ + { + type: WorkerErrorTypes.CLONE_ERROR, + message: (e as Error)?.message, + context: JSON.stringify(data), + }, + ], }, - ); - - break; - } - case EVAL_WORKER_ACTIONS.PROCESS_TRIGGER: - case EVAL_WORKER_ACTIONS.LINT_TREE: - /** - * These actions will not be processed here. They will be handled in the eval trigger sub steps - * @link promisifyAction - **/ - break; - case EVAL_WORKER_ACTIONS.CLEAR_CACHE: { - dataTreeEvaluator = undefined; - return true; - } - case EVAL_WORKER_ACTIONS.VALIDATE_PROPERTY: { - const { property, props, validation, value } = requestData; - return removeFunctions( - validateWidgetProperty(validation, value, props, property), - ); - } - case EVAL_WORKER_ACTIONS.UNDO: { - const { entityId } = requestData; - if (!replayMap[entityId || CANVAS]) return; - const replayResult = replayMap[entityId || CANVAS].replay("UNDO"); - replayMap[entityId || CANVAS].clearLogs(); - return replayResult; - } - case EVAL_WORKER_ACTIONS.REDO: { - const { entityId } = requestData; - if (!replayMap[entityId ?? CANVAS]) return; - const replayResult = replayMap[entityId ?? CANVAS].replay("REDO"); - replayMap[entityId ?? CANVAS].clearLogs(); - return replayResult; - } - case EVAL_WORKER_ACTIONS.EXECUTE_SYNC_JS: { - const { functionCall } = requestData; - - if (!dataTreeEvaluator) { - return true; - } - const evalTree = dataTreeEvaluator.evalTree; - const resolvedFunctions = dataTreeEvaluator.resolvedFunctions; - const { errors, logs, result } = evaluate( - functionCall, - evalTree, - resolvedFunctions, - false, - undefined, - ); - return { errors, logs, result }; - } - case EVAL_WORKER_ACTIONS.EVAL_EXPRESSION: - const { expression, isTrigger } = requestData; - const evalTree = dataTreeEvaluator?.evalTree; - if (!evalTree) return {}; - // TODO find a way to do this for snippets - return isTrigger - ? evaluateAsync(expression, evalTree, "SNIPPET", {}) - : evaluate(expression, evalTree, {}, false); - case EVAL_WORKER_ACTIONS.UPDATE_REPLAY_OBJECT: - const { entity, entityId, entityType } = requestData; - const replayObject = replayMap[entityId]; - if (replayObject) { - replayObject.update(entity); - } else { - replayMap[entityId] = new ReplayEditor(entity, entityType); - } - break; - case EVAL_WORKER_ACTIONS.SET_EVALUATION_VERSION: - const { version } = requestData; - self.evaluationVersion = version || 1; - break; - case EVAL_WORKER_ACTIONS.INIT_FORM_EVAL: - const { currentEvalState, payload, type } = requestData; - const response = setFormEvaluationSaga(type, payload, currentEvalState); - return response; - case EVAL_WORKER_ACTIONS.EVAL_TREE: { - let evalOrder: string[] = []; - let lintOrder: string[] = []; - let jsUpdates: Record = {}; - let unEvalUpdates: DataTreeDiff[] = []; - let nonDynamicFieldValidationOrder: string[] = []; - let isCreateFirstTree = false; - let dataTree: DataTree = {}; - let errors: EvalError[] = []; - let logs: any[] = []; - let userLogs: UserLogObject[] = []; - let dependencies: DependencyMap = {}; - let evalMetaUpdates: EvalMetaUpdates = []; - - const { - allActionValidationConfig, - requiresLinting, - shouldReplay, - theme, - unevalTree: __unevalTree__, - widgets, - widgetTypeConfigMap, - } = requestData as EvalTreeRequestData; - - const unevalTree = createUnEvalTreeForEval(__unevalTree__); - - try { - if (!dataTreeEvaluator) { - isCreateFirstTree = true; - replayMap = replayMap || {}; - replayMap[CANVAS] = new ReplayCanvas({ widgets, theme }); - dataTreeEvaluator = new DataTreeEvaluator( - widgetTypeConfigMap, - allActionValidationConfig, - ); - - const setupFirstTreeResponse = dataTreeEvaluator.setupFirstTree( - unevalTree, - ); - evalOrder = setupFirstTreeResponse.evalOrder; - lintOrder = setupFirstTreeResponse.lintOrder; - jsUpdates = setupFirstTreeResponse.jsUpdates; - - initiateLinting( - lintOrder, - makeEntityConfigsAsObjProperties(dataTreeEvaluator.oldUnEvalTree, { - sanitizeDataTree: false, - }), - requiresLinting, - ); - - const dataTreeResponse = dataTreeEvaluator.evalAndValidateFirstTree(); - dataTree = makeEntityConfigsAsObjProperties( - dataTreeResponse.evalTree, - { - evalProps: dataTreeEvaluator.evalProps, - }, - ); - } else if (dataTreeEvaluator.hasCyclicalDependency) { - if (dataTreeEvaluator && !isEmpty(allActionValidationConfig)) { - //allActionValidationConfigs may not be set in dataTreeEvaluatior. Therefore, set it explicitly via setter method - dataTreeEvaluator.setAllActionValidationConfig( - allActionValidationConfig, - ); - } - if (shouldReplay) { - replayMap[CANVAS]?.update({ widgets, theme }); - } - dataTreeEvaluator = new DataTreeEvaluator( - widgetTypeConfigMap, - allActionValidationConfig, - ); - if (dataTreeEvaluator && !isEmpty(allActionValidationConfig)) { - dataTreeEvaluator.setAllActionValidationConfig( - allActionValidationConfig, - ); - } - const setupFirstTreeResponse = dataTreeEvaluator.setupFirstTree( - unevalTree, - ); - isCreateFirstTree = true; - evalOrder = setupFirstTreeResponse.evalOrder; - lintOrder = setupFirstTreeResponse.lintOrder; - jsUpdates = setupFirstTreeResponse.jsUpdates; - - initiateLinting( - lintOrder, - makeEntityConfigsAsObjProperties(dataTreeEvaluator.oldUnEvalTree, { - sanitizeDataTree: false, - }), - requiresLinting, - ); - - const dataTreeResponse = dataTreeEvaluator.evalAndValidateFirstTree(); - dataTree = makeEntityConfigsAsObjProperties( - dataTreeResponse.evalTree, - { - evalProps: dataTreeEvaluator.evalProps, - }, - ); - } else { - if (dataTreeEvaluator && !isEmpty(allActionValidationConfig)) { - dataTreeEvaluator.setAllActionValidationConfig( - allActionValidationConfig, - ); - } - isCreateFirstTree = false; - if (shouldReplay) { - replayMap[CANVAS]?.update({ widgets, theme }); - } - const setupUpdateTreeResponse = dataTreeEvaluator.setupUpdateTree( - unevalTree, - ); - evalOrder = setupUpdateTreeResponse.evalOrder; - lintOrder = setupUpdateTreeResponse.lintOrder; - jsUpdates = setupUpdateTreeResponse.jsUpdates; - unEvalUpdates = setupUpdateTreeResponse.unEvalUpdates; - - initiateLinting( - lintOrder, - makeEntityConfigsAsObjProperties(dataTreeEvaluator.oldUnEvalTree, { - sanitizeDataTree: false, - }), - requiresLinting, - ); - nonDynamicFieldValidationOrder = - setupUpdateTreeResponse.nonDynamicFieldValidationOrder; - const updateResponse = dataTreeEvaluator.evalAndValidateSubTree( - evalOrder, - nonDynamicFieldValidationOrder, - ); - dataTree = makeEntityConfigsAsObjProperties( - dataTreeEvaluator.evalTree, - { - evalProps: dataTreeEvaluator.evalProps, - }, - ); - evalMetaUpdates = JSON.parse( - JSON.stringify(updateResponse.evalMetaUpdates), - ); - } - dataTreeEvaluator = dataTreeEvaluator as DataTreeEvaluator; - dependencies = dataTreeEvaluator.inverseDependencyMap; - errors = dataTreeEvaluator.errors; - dataTreeEvaluator.clearErrors(); - logs = dataTreeEvaluator.logs; - userLogs = dataTreeEvaluator.userLogs; - if (shouldReplay) { - if (replayMap[CANVAS]?.logs) - logs = logs.concat(replayMap[CANVAS]?.logs); - replayMap[CANVAS]?.clearLogs(); - } - - dataTreeEvaluator.clearLogs(); - } catch (error) { - if (dataTreeEvaluator !== undefined) { - errors = dataTreeEvaluator.errors; - logs = dataTreeEvaluator.logs; - userLogs = dataTreeEvaluator.userLogs; - } - if (!(error instanceof CrashingError)) { - errors.push({ - type: EvalErrorTypes.UNKNOWN_ERROR, - message: (error as Error).message, - }); - console.error(error); - } - - dataTree = getSafeToRenderDataTree( - makeEntityConfigsAsObjProperties(unevalTree, { - sanitizeDataTree: false, - evalProps: dataTreeEvaluator?.evalProps, - }), - widgetTypeConfigMap, - ); - - unEvalUpdates = []; - } - - return { - dataTree, - dependencies, - errors, - evalMetaUpdates, - evaluationOrder: evalOrder, - jsUpdates, - logs, - userLogs, - unEvalUpdates, - isCreateFirstTree, - } as EvalTreeResponseData; - } - default: { - console.error("Action not registered on evalWorker", method); - } + }, + }); } } -self.onmessage = messageEventListener(eventRequestHandler); +self.addEventListener("message", syncRequestMessageListener); +self.addEventListener("message", asyncRequestMessageListener); diff --git a/app/client/src/workers/Evaluation/handlers/__tests__/jsLibrary.test.ts b/app/client/src/workers/Evaluation/handlers/__tests__/jsLibrary.test.ts new file mode 100644 index 0000000000..83261e16d7 --- /dev/null +++ b/app/client/src/workers/Evaluation/handlers/__tests__/jsLibrary.test.ts @@ -0,0 +1,94 @@ +import { installLibrary, uninstallLibrary } from "../jsLibrary"; +import { EVAL_WORKER_SYNC_ACTION } from "workers/Evaluation/evalWorkerActions"; +import * as mod from "../../../common/JSLibrary/ternDefinitionGenerator"; + +jest.mock("../../../common/JSLibrary/ternDefinitionGenerator"); + +describe("Tests to assert install/uninstall flows", function() { + beforeAll(() => { + self.importScripts = jest.fn(() => { + //@ts-expect-error importScripts is not defined in the test environment + self.lodash = {}; + }); + + const mockTernDefsGenerator = jest.fn(() => ({})); + + jest.mock("../../../common/JSLibrary/ternDefinitionGenerator.ts", () => { + return { + makeTernDefs: mockTernDefsGenerator, + }; + }); + }); + + it("should install a library", function() { + const res = installLibrary({ + data: { + url: + "https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.21/lodash.min.js", + takenAccessors: [], + takenNamesMap: {}, + }, + method: EVAL_WORKER_SYNC_ACTION.INSTALL_LIBRARY, + }); + // + expect(self.importScripts).toHaveBeenCalled(); + expect(mod.makeTernDefs).toHaveBeenCalledWith({}); + + expect(res).toEqual({ + success: true, + defs: { + "!name": "LIB/lodash", + lodash: undefined, + }, + accessor: ["lodash"], + }); + }); + + it("Reinstalling a different version of the same installed library should fail", function() { + const res = installLibrary({ + data: { + url: + "https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.16.0/lodash.min.js", + takenAccessors: ["lodash"], + takenNamesMap: {}, + }, + method: EVAL_WORKER_SYNC_ACTION.INSTALL_LIBRARY, + }); + expect(res).toEqual({ + success: false, + defs: {}, + error: expect.any(Error), + }); + }); + + it("Detects name space collision where there is another entity(api, widget or query) with the same name", function() { + //@ts-expect-error ignore + delete self.lodash; + const res = installLibrary({ + data: { + url: + "https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.16.0/lodash.min.js", + takenAccessors: [], + takenNamesMap: { lodash: true }, + }, + method: EVAL_WORKER_SYNC_ACTION.INSTALL_LIBRARY, + }); + expect(res).toEqual({ + success: false, + defs: {}, + error: expect.any(Error), + }); + }); + + it("Removes or set the accessors to undefined on the global object on uninstallation", function() { + //@ts-expect-error ignore + self.lodash = {}; + const res = uninstallLibrary({ + data: ["lodash"], + method: EVAL_WORKER_SYNC_ACTION.UNINSTALL_LIBRARY, + }); + expect(res).toEqual({ success: true }); + //@ts-expect-error ignore + expect(self.lodash).toBeUndefined(); + }); +}); diff --git a/app/client/src/workers/Evaluation/handlers/evalActionBindings.ts b/app/client/src/workers/Evaluation/handlers/evalActionBindings.ts new file mode 100644 index 0000000000..bb2aa7c1f7 --- /dev/null +++ b/app/client/src/workers/Evaluation/handlers/evalActionBindings.ts @@ -0,0 +1,22 @@ +import { dataTreeEvaluator } from "./evalTree"; +import { removeFunctions } from "../evaluationUtils"; +import { EvalWorkerSyncRequest } from "../types"; + +export default function(request: EvalWorkerSyncRequest) { + const { data } = request; + const { bindings, executionParams } = data; + if (!dataTreeEvaluator) { + return { values: undefined, errors: [] }; + } + + const values = dataTreeEvaluator.evaluateActionBindings( + bindings, + executionParams, + ); + + const cleanValues = removeFunctions(values); + + const errors = dataTreeEvaluator.errors; + dataTreeEvaluator.clearErrors(); + return { values: cleanValues, errors }; +} diff --git a/app/client/src/workers/Evaluation/handlers/evalExpression.ts b/app/client/src/workers/Evaluation/handlers/evalExpression.ts new file mode 100644 index 0000000000..541f042431 --- /dev/null +++ b/app/client/src/workers/Evaluation/handlers/evalExpression.ts @@ -0,0 +1,12 @@ +import { evaluateAsync } from "../evaluate"; +import { EvalWorkerASyncRequest } from "../types"; +import { dataTreeEvaluator } from "./evalTree"; + +export default function(request: EvalWorkerASyncRequest) { + const { data } = request; + const { expression } = data; + const evalTree = dataTreeEvaluator?.evalTree; + const resolvedFunctions = dataTreeEvaluator?.resolvedFunctions || {}; + if (!evalTree) return {}; + return evaluateAsync(expression, evalTree, resolvedFunctions, {}); +} diff --git a/app/client/src/workers/Evaluation/handlers/evalTree.ts b/app/client/src/workers/Evaluation/handlers/evalTree.ts new file mode 100644 index 0000000000..75a53c0525 --- /dev/null +++ b/app/client/src/workers/Evaluation/handlers/evalTree.ts @@ -0,0 +1,220 @@ +import { UserLogObject } from "entities/AppsmithConsole"; +import { DataTree } from "entities/DataTree/dataTreeFactory"; +import ReplayEntity from "entities/Replay"; +import ReplayCanvas from "entities/Replay/ReplayEntity/ReplayCanvas"; +import { isEmpty } from "lodash"; +import { + DependencyMap, + EvalError, + EvalErrorTypes, +} from "utils/DynamicBindingUtils"; +import { JSUpdate } from "utils/JSPaneUtils"; +import DataTreeEvaluator from "workers/common/DataTreeEvaluator"; +import { EvalMetaUpdates } from "workers/common/DataTreeEvaluator/types"; +import { initiateLinting } from "workers/Linting/utils"; +import { + createUnEvalTreeForEval, + makeEntityConfigsAsObjProperties, +} from "../dataTreeUtils"; +import { + CrashingError, + DataTreeDiff, + getSafeToRenderDataTree, +} from "../evaluationUtils"; +import { + EvalTreeRequestData, + EvalTreeResponseData, + EvalWorkerSyncRequest, +} from "../types"; +export let replayMap: Record>; +export let dataTreeEvaluator: DataTreeEvaluator | undefined; +export const CANVAS = "canvas"; + +export default function(request: EvalWorkerSyncRequest) { + const { data } = request; + let evalOrder: string[] = []; + let lintOrder: string[] = []; + let jsUpdates: Record = {}; + let unEvalUpdates: DataTreeDiff[] = []; + let nonDynamicFieldValidationOrder: string[] = []; + let isCreateFirstTree = false; + let dataTree: DataTree = {}; + let errors: EvalError[] = []; + let logs: any[] = []; + let userLogs: UserLogObject[] = []; + let dependencies: DependencyMap = {}; + let evalMetaUpdates: EvalMetaUpdates = []; + + const { + allActionValidationConfig, + forceEvaluation, + requiresLinting, + shouldReplay, + theme, + unevalTree: __unevalTree__, + widgets, + widgetTypeConfigMap, + } = data as EvalTreeRequestData; + + const unevalTree = createUnEvalTreeForEval(__unevalTree__); + + try { + if (!dataTreeEvaluator) { + isCreateFirstTree = true; + replayMap = replayMap || {}; + replayMap[CANVAS] = new ReplayCanvas({ widgets, theme }); + dataTreeEvaluator = new DataTreeEvaluator( + widgetTypeConfigMap, + allActionValidationConfig, + ); + const setupFirstTreeResponse = dataTreeEvaluator.setupFirstTree( + unevalTree, + ); + evalOrder = setupFirstTreeResponse.evalOrder; + lintOrder = setupFirstTreeResponse.lintOrder; + jsUpdates = setupFirstTreeResponse.jsUpdates; + + initiateLinting( + lintOrder, + makeEntityConfigsAsObjProperties(dataTreeEvaluator.oldUnEvalTree, { + sanitizeDataTree: false, + }), + requiresLinting, + ); + + const dataTreeResponse = dataTreeEvaluator.evalAndValidateFirstTree(); + dataTree = makeEntityConfigsAsObjProperties(dataTreeResponse.evalTree, { + evalProps: dataTreeEvaluator.evalProps, + }); + } else if (dataTreeEvaluator.hasCyclicalDependency || forceEvaluation) { + if (dataTreeEvaluator && !isEmpty(allActionValidationConfig)) { + //allActionValidationConfigs may not be set in dataTreeEvaluatior. Therefore, set it explicitly via setter method + dataTreeEvaluator.setAllActionValidationConfig( + allActionValidationConfig, + ); + } + if (shouldReplay) { + replayMap[CANVAS]?.update({ widgets, theme }); + } + dataTreeEvaluator = new DataTreeEvaluator( + widgetTypeConfigMap, + allActionValidationConfig, + ); + if (dataTreeEvaluator && !isEmpty(allActionValidationConfig)) { + dataTreeEvaluator.setAllActionValidationConfig( + allActionValidationConfig, + ); + } + const setupFirstTreeResponse = dataTreeEvaluator.setupFirstTree( + unevalTree, + ); + isCreateFirstTree = true; + evalOrder = setupFirstTreeResponse.evalOrder; + lintOrder = setupFirstTreeResponse.lintOrder; + jsUpdates = setupFirstTreeResponse.jsUpdates; + + initiateLinting( + lintOrder, + makeEntityConfigsAsObjProperties(dataTreeEvaluator.oldUnEvalTree, { + sanitizeDataTree: false, + }), + requiresLinting, + ); + + const dataTreeResponse = dataTreeEvaluator.evalAndValidateFirstTree(); + dataTree = makeEntityConfigsAsObjProperties(dataTreeResponse.evalTree, { + evalProps: dataTreeEvaluator.evalProps, + }); + } else { + if (dataTreeEvaluator && !isEmpty(allActionValidationConfig)) { + dataTreeEvaluator.setAllActionValidationConfig( + allActionValidationConfig, + ); + } + isCreateFirstTree = false; + if (shouldReplay) { + replayMap[CANVAS]?.update({ widgets, theme }); + } + const setupUpdateTreeResponse = dataTreeEvaluator.setupUpdateTree( + unevalTree, + ); + evalOrder = setupUpdateTreeResponse.evalOrder; + lintOrder = setupUpdateTreeResponse.lintOrder; + jsUpdates = setupUpdateTreeResponse.jsUpdates; + unEvalUpdates = setupUpdateTreeResponse.unEvalUpdates; + + initiateLinting( + lintOrder, + makeEntityConfigsAsObjProperties(dataTreeEvaluator.oldUnEvalTree, { + sanitizeDataTree: false, + }), + requiresLinting, + ); + + nonDynamicFieldValidationOrder = + setupUpdateTreeResponse.nonDynamicFieldValidationOrder; + const updateResponse = dataTreeEvaluator.evalAndValidateSubTree( + evalOrder, + nonDynamicFieldValidationOrder, + ); + dataTree = makeEntityConfigsAsObjProperties(dataTreeEvaluator.evalTree, { + evalProps: dataTreeEvaluator.evalProps, + }); + evalMetaUpdates = JSON.parse( + JSON.stringify(updateResponse.evalMetaUpdates), + ); + } + dataTreeEvaluator = dataTreeEvaluator as DataTreeEvaluator; + dependencies = dataTreeEvaluator.inverseDependencyMap; + errors = dataTreeEvaluator.errors; + dataTreeEvaluator.clearErrors(); + logs = dataTreeEvaluator.logs; + userLogs = dataTreeEvaluator.userLogs; + if (shouldReplay) { + if (replayMap[CANVAS]?.logs) logs = logs.concat(replayMap[CANVAS]?.logs); + replayMap[CANVAS]?.clearLogs(); + } + + dataTreeEvaluator.clearLogs(); + } catch (error) { + if (dataTreeEvaluator !== undefined) { + errors = dataTreeEvaluator.errors; + logs = dataTreeEvaluator.logs; + userLogs = dataTreeEvaluator.userLogs; + } + if (!(error instanceof CrashingError)) { + errors.push({ + type: EvalErrorTypes.UNKNOWN_ERROR, + message: (error as Error).message, + }); + // eslint-disable-next-line + console.error(error); + } + dataTree = getSafeToRenderDataTree( + makeEntityConfigsAsObjProperties(unevalTree, { + sanitizeDataTree: false, + evalProps: dataTreeEvaluator?.evalProps, + }), + widgetTypeConfigMap, + ); + unEvalUpdates = []; + } + + return { + dataTree, + dependencies, + errors, + evalMetaUpdates, + evaluationOrder: evalOrder, + jsUpdates, + logs, + userLogs, + unEvalUpdates, + isCreateFirstTree, + } as EvalTreeResponseData; +} + +export function clearCache() { + dataTreeEvaluator = undefined; + return true; +} diff --git a/app/client/src/workers/Evaluation/handlers/evalTrigger.ts b/app/client/src/workers/Evaluation/handlers/evalTrigger.ts new file mode 100644 index 0000000000..72316c83e9 --- /dev/null +++ b/app/client/src/workers/Evaluation/handlers/evalTrigger.ts @@ -0,0 +1,41 @@ +import { dataTreeEvaluator } from "./evalTree"; +import { EvalWorkerASyncRequest } from "../types"; +import { createUnEvalTreeForEval } from "../dataTreeUtils"; + +export default async function(request: EvalWorkerASyncRequest) { + const { data } = request; + const { + callbackData, + dynamicTrigger, + eventType, + globalContext, + triggerMeta, + unEvalTree: __unEvalTree__, + } = data; + if (!dataTreeEvaluator) { + return { triggers: [], errors: [] }; + } + const unEvalTree = createUnEvalTreeForEval(__unEvalTree__); + const { + evalOrder, + nonDynamicFieldValidationOrder, + } = dataTreeEvaluator.setupUpdateTree(unEvalTree); + dataTreeEvaluator.evalAndValidateSubTree( + evalOrder, + nonDynamicFieldValidationOrder, + ); + const evalTree = dataTreeEvaluator.evalTree; + const resolvedFunctions = dataTreeEvaluator.resolvedFunctions; + + return dataTreeEvaluator.evaluateTriggers( + dynamicTrigger, + evalTree, + resolvedFunctions, + callbackData, + { + globalContext, + eventType, + triggerMeta, + }, + ); +} diff --git a/app/client/src/workers/Evaluation/handlers/executeSyncJS.ts b/app/client/src/workers/Evaluation/handlers/executeSyncJS.ts new file mode 100644 index 0000000000..6819f6db37 --- /dev/null +++ b/app/client/src/workers/Evaluation/handlers/executeSyncJS.ts @@ -0,0 +1,21 @@ +import evaluateSync from "../evaluate"; +import { dataTreeEvaluator } from "./evalTree"; +import { EvalWorkerSyncRequest } from "../types"; + +export default function(request: EvalWorkerSyncRequest) { + const { data } = request; + const { functionCall } = data; + + if (!dataTreeEvaluator) { + return true; + } + const evalTree = dataTreeEvaluator.evalTree; + const resolvedFunctions = dataTreeEvaluator.resolvedFunctions; + return evaluateSync( + functionCall, + evalTree, + resolvedFunctions, + false, + undefined, + ); +} diff --git a/app/client/src/workers/Evaluation/handlers/index.ts b/app/client/src/workers/Evaluation/handlers/index.ts new file mode 100644 index 0000000000..9e9cd0543b --- /dev/null +++ b/app/client/src/workers/Evaluation/handlers/index.ts @@ -0,0 +1,50 @@ +import noop from "lodash/noop"; +import { + EVAL_WORKER_ACTIONS, + EVAL_WORKER_ASYNC_ACTION, + EVAL_WORKER_SYNC_ACTION, +} from "workers/Evaluation/evalWorkerActions"; +import { EvalWorkerSyncRequest, EvalWorkerASyncRequest } from "../types"; +import evalActionBindings from "./evalActionBindings"; +import evalExpression from "./evalExpression"; +import evalTree, { clearCache } from "./evalTree"; +import evalTrigger from "./evalTrigger"; +import executeSyncJS from "./executeSyncJS"; +import initFormEval from "./initFormEval"; +import { installLibrary, loadLibraries, uninstallLibrary } from "./jsLibrary"; +import { redo, undo, updateReplayObject } from "./replay"; +import setupEvaluationEnvironment, { + setEvaluationVersion, +} from "./setupEvalEnv"; +import validateProperty from "./validateProperty"; + +const syncHandlerMap: Record< + EVAL_WORKER_SYNC_ACTION, + (req: EvalWorkerSyncRequest) => any +> = { + [EVAL_WORKER_ACTIONS.EVAL_ACTION_BINDINGS]: evalActionBindings, + [EVAL_WORKER_ACTIONS.EVAL_TREE]: evalTree, + [EVAL_WORKER_ACTIONS.EXECUTE_SYNC_JS]: executeSyncJS, + [EVAL_WORKER_ACTIONS.UNDO]: undo, + [EVAL_WORKER_ACTIONS.REDO]: redo, + [EVAL_WORKER_ACTIONS.UPDATE_REPLAY_OBJECT]: updateReplayObject, + [EVAL_WORKER_ACTIONS.VALIDATE_PROPERTY]: validateProperty, + [EVAL_WORKER_ACTIONS.INSTALL_LIBRARY]: installLibrary, + [EVAL_WORKER_ACTIONS.UNINSTALL_LIBRARY]: uninstallLibrary, + [EVAL_WORKER_ACTIONS.LOAD_LIBRARIES]: loadLibraries, + [EVAL_WORKER_ACTIONS.LINT_TREE]: noop, + [EVAL_WORKER_ACTIONS.SETUP]: setupEvaluationEnvironment, + [EVAL_WORKER_ACTIONS.CLEAR_CACHE]: clearCache, + [EVAL_WORKER_ACTIONS.SET_EVALUATION_VERSION]: setEvaluationVersion, + [EVAL_WORKER_ACTIONS.INIT_FORM_EVAL]: initFormEval, +}; + +const asyncHandlerMap: Record< + EVAL_WORKER_ASYNC_ACTION, + (req: EvalWorkerASyncRequest) => any +> = { + [EVAL_WORKER_ACTIONS.EVAL_TRIGGER]: evalTrigger, + [EVAL_WORKER_ACTIONS.EVAL_EXPRESSION]: evalExpression, +}; + +export { syncHandlerMap, asyncHandlerMap }; diff --git a/app/client/src/workers/Evaluation/handlers/initFormEval.ts b/app/client/src/workers/Evaluation/handlers/initFormEval.ts new file mode 100644 index 0000000000..15406b0563 --- /dev/null +++ b/app/client/src/workers/Evaluation/handlers/initFormEval.ts @@ -0,0 +1,9 @@ +import { setFormEvaluationSaga } from "../formEval"; +import { EvalWorkerSyncRequest } from "../types"; + +export default function(request: EvalWorkerSyncRequest) { + const { data } = request; + const { currentEvalState, payload, type } = data; + const response = setFormEvaluationSaga(type, payload, currentEvalState); + return response; +} diff --git a/app/client/src/workers/Evaluation/handlers/jsLibrary.ts b/app/client/src/workers/Evaluation/handlers/jsLibrary.ts new file mode 100644 index 0000000000..90d65773c2 --- /dev/null +++ b/app/client/src/workers/Evaluation/handlers/jsLibrary.ts @@ -0,0 +1,202 @@ +import { + createMessage, + customJSLibraryMessages, +} from "@appsmith/constants/messages"; +import difference from "lodash/difference"; +import { Def } from "tern"; +import { + JSLibraries, + libraryReservedIdentifiers, +} from "../../common/JSLibrary"; +import { makeTernDefs } from "../../common/JSLibrary/ternDefinitionGenerator"; +import { EvalWorkerSyncRequest } from "../types"; + +enum LibraryInstallError { + NameCollisionError, + ImportError, + TernDefinitionError, + LibraryOverrideError, +} + +class NameCollisionError extends Error { + code = LibraryInstallError.NameCollisionError; + constructor(accessors: string) { + super( + createMessage(customJSLibraryMessages.NAME_COLLISION_ERROR, accessors), + ); + this.name = "NameCollisionError"; + } +} + +class ImportError extends Error { + code = LibraryInstallError.ImportError; + constructor(url: string) { + super(createMessage(customJSLibraryMessages.IMPORT_URL_ERROR, url)); + this.name = "ImportError"; + } +} + +class TernDefinitionError extends Error { + code = LibraryInstallError.TernDefinitionError; + constructor(name: string) { + super(createMessage(customJSLibraryMessages.DEFS_FAILED_ERROR, name)); + this.name = "TernDefinitionError"; + } +} + +class LibraryOverrideError extends Error { + code = LibraryInstallError.LibraryOverrideError; + data: any; + constructor(name: string, data: any) { + super(createMessage(customJSLibraryMessages.LIB_OVERRIDE_ERROR, name)); + this.name = "LibraryOverrideError"; + this.data = data; + } +} + +export function installLibrary(request: EvalWorkerSyncRequest) { + const { data } = request; + const { takenAccessors, takenNamesMap, url } = data; + const defs: Def = {}; + try { + const currentEnvKeys = Object.keys(self); + + //@ts-expect-error Find libraries that were uninstalled. + const unsetKeys = currentEnvKeys.filter((key) => self[key] === undefined); + + const existingLibraries: Record = {}; + + for (const acc of takenAccessors) { + existingLibraries[acc] = self[acc]; + } + + try { + self.importScripts(url); + } catch (e) { + throw new ImportError(url); + } + + // Find keys add that were installed to the global scope. + const accessor = difference(Object.keys(self), currentEnvKeys) as Array< + string + >; + + checkForNameCollision(accessor, takenNamesMap); + + checkIfUninstalledEarlier(accessor, unsetKeys); + + checkForOverrides(url, accessor, takenAccessors, existingLibraries); + + if (accessor.length === 0) return { status: false, defs, accessor }; + + //Reserves accessor names. + const name = accessor[accessor.length - 1]; + + defs["!name"] = `LIB/${name}`; + try { + for (const key of accessor) { + //@ts-expect-error no types + defs[key] = makeTernDefs(self[key]); + } + } catch (e) { + for (const acc of accessor) { + //@ts-expect-error no types + self[acc] = undefined; + } + throw new TernDefinitionError( + `Failed to generate autocomplete definitions: ${name}`, + ); + } + + //Reserve accessor names. + for (const acc of accessor) { + libraryReservedIdentifiers[acc] = true; + } + + return { success: true, defs, accessor }; + } catch (error) { + return { success: false, defs, error }; + } +} + +export function uninstallLibrary(request: EvalWorkerSyncRequest) { + const { data } = request; + const accessor = data; + try { + for (const key of accessor) { + try { + delete self[key]; + } catch (e) { + //@ts-expect-error ignore + self[key] = undefined; + } + delete libraryReservedIdentifiers[key]; + } + return { success: true }; + } catch (e) { + return { success: false }; + } +} + +export function loadLibraries(request: EvalWorkerSyncRequest) { + //Add types + const { data } = request; + const urls = data.map((lib: any) => lib.url); + const keysBefore = Object.keys(self); + let message = ""; + + try { + self.importScripts(...urls); + } catch (e) { + message = (e as Error).message; + } + const keysAfter = Object.keys(self); + const newKeys = difference(keysAfter, keysBefore); + for (const key of newKeys) { + libraryReservedIdentifiers[key] = true; + } + JSLibraries.push(...data); + return { success: !message, message }; +} + +function checkForNameCollision( + accessor: string[], + takenNamesMap: Record, +) { + const collidingNames = accessor.filter((key: string) => takenNamesMap[key]); + if (collidingNames.length) { + for (const acc of accessor) { + //@ts-expect-error no types + self[acc] = undefined; + } + throw new NameCollisionError(collidingNames.join(", ")); + } +} + +function checkIfUninstalledEarlier(accessor: string[], unsetKeys: string[]) { + if (accessor.length > 0) return; + for (const key of unsetKeys) { + //@ts-expect-error no types + if (!self[key]) continue; + accessor.push(key); + } +} + +function checkForOverrides( + url: string, + accessor: string[], + takenAccessors: string[], + existingLibraries: Record, +) { + if (accessor.length > 0) return; + const overriddenAccessors: Array = []; + for (const acc of takenAccessors) { + //@ts-expect-error no types + if (existingLibraries[acc] === self[acc]) continue; + //@ts-expect-error no types + self[acc] = existingLibraries[acc]; + overriddenAccessors.push(acc); + } + if (overriddenAccessors.length === 0) return; + throw new LibraryOverrideError(url, overriddenAccessors); +} diff --git a/app/client/src/workers/Evaluation/handlers/replay.ts b/app/client/src/workers/Evaluation/handlers/replay.ts new file mode 100644 index 0000000000..f143b260f8 --- /dev/null +++ b/app/client/src/workers/Evaluation/handlers/replay.ts @@ -0,0 +1,33 @@ +import ReplayEditor from "entities/Replay/ReplayEntity/ReplayEditor"; +import { EvalWorkerSyncRequest } from "../types"; +import { CANVAS, replayMap } from "./evalTree"; + +export function undo(request: EvalWorkerSyncRequest) { + const { data } = request; + const { entityId } = data; + if (!replayMap[entityId || CANVAS]) return; + const replayResult = replayMap[entityId || CANVAS].replay("UNDO"); + replayMap[entityId || CANVAS].clearLogs(); + return replayResult; +} + +export function redo(request: EvalWorkerSyncRequest) { + const { data } = request; + const { entityId } = data; + if (!replayMap[entityId ?? CANVAS]) return; + const replayResult = replayMap[entityId ?? CANVAS].replay("REDO"); + replayMap[entityId ?? CANVAS].clearLogs(); + return replayResult; +} + +export function updateReplayObject(request: EvalWorkerSyncRequest) { + const { data } = request; + const { entity, entityId, entityType } = data; + const replayObject = replayMap[entityId]; + if (replayObject) { + replayObject.update(entity); + } else { + replayMap[entityId] = new ReplayEditor(entity, entityType); + } + return true; +} diff --git a/app/client/src/workers/Evaluation/handlers/setupEvalEnv.ts b/app/client/src/workers/Evaluation/handlers/setupEvalEnv.ts new file mode 100644 index 0000000000..41a65722a6 --- /dev/null +++ b/app/client/src/workers/Evaluation/handlers/setupEvalEnv.ts @@ -0,0 +1,37 @@ +import { unsafeFunctionForEval } from "utils/DynamicBindingUtils"; +import interceptAndOverrideHttpRequest from "../HTTPRequestOverride"; +import { resetJSLibraries } from "../../common/JSLibrary"; +import setupDOM from "../SetupDOM"; +import overrideTimeout from "../TimeoutOverride"; +import { EvalWorkerSyncRequest } from "../types"; +import userLogs from "../UserLog"; + +export default function() { + const libraries = resetJSLibraries(); + ///// Adding extra libraries separately + libraries.forEach((library) => { + // @ts-expect-error: Types are not available + self[library.accessor] = library.lib; + }); + + ///// Remove all unsafe functions + unsafeFunctionForEval.forEach((func) => { + // @ts-expect-error: Types are not available + self[func] = undefined; + }); + self.window = self; + userLogs.overrideConsoleAPI(); + overrideTimeout(); + interceptAndOverrideHttpRequest(); + setupDOM(); + return true; +} + +export function setEvaluationVersion(request: EvalWorkerSyncRequest) { + const { data } = request; + const { version } = data; + self.evaluationVersion = version || 1; + // TODO: Move this to setup + resetJSLibraries(); + return true; +} diff --git a/app/client/src/workers/Evaluation/handlers/validateProperty.ts b/app/client/src/workers/Evaluation/handlers/validateProperty.ts new file mode 100644 index 0000000000..b6d66318d8 --- /dev/null +++ b/app/client/src/workers/Evaluation/handlers/validateProperty.ts @@ -0,0 +1,11 @@ +import { validateWidgetProperty } from "workers/common/DataTreeEvaluator/validationUtils"; +import { removeFunctions } from "../evaluationUtils"; +import { EvalWorkerSyncRequest } from "../types"; + +export default function(request: EvalWorkerSyncRequest) { + const { data } = request; + const { property, props, validation, value } = data; + return removeFunctions( + validateWidgetProperty(validation, value, props, property), + ); +} diff --git a/app/client/src/workers/Evaluation/types.ts b/app/client/src/workers/Evaluation/types.ts index 027e673f5e..13b869505d 100644 --- a/app/client/src/workers/Evaluation/types.ts +++ b/app/client/src/workers/Evaluation/types.ts @@ -4,18 +4,22 @@ import { AppTheme } from "entities/AppTheming"; import { DataTree, UnEvalTree } from "entities/DataTree/dataTreeFactory"; import { CanvasWidgetsReduxState } from "reducers/entityReducers/canvasWidgetsReducer"; +import { DependencyMap, EvalError } from "utils/DynamicBindingUtils"; import { - DependencyMap, - EvalError, - EVAL_WORKER_ACTIONS, -} from "utils/DynamicBindingUtils"; + EVAL_WORKER_ASYNC_ACTION, + EVAL_WORKER_SYNC_ACTION, +} from "workers/Evaluation/evalWorkerActions"; import { JSUpdate } from "utils/JSPaneUtils"; import { WidgetTypeConfigMap } from "utils/WidgetFactory"; import { EvalMetaUpdates } from "workers/common/DataTreeEvaluator/types"; import { WorkerRequest } from "workers/common/types"; import { DataTreeDiff } from "./evaluationUtils"; -export type EvalWorkerRequest = WorkerRequest; +export type EvalWorkerSyncRequest = WorkerRequest; +export type EvalWorkerASyncRequest = WorkerRequest< + any, + EVAL_WORKER_ASYNC_ACTION +>; export type EvalWorkerResponse = EvalTreeResponseData | boolean | unknown; export interface EvalTreeRequestData { @@ -28,6 +32,7 @@ export interface EvalTreeRequestData { [actionId: string]: ActionValidationConfigMap; }; requiresLinting: boolean; + forceEvaluation: boolean; } export interface EvalTreeResponseData { dataTree: DataTree; diff --git a/app/client/src/workers/Linting/lint.worker.ts b/app/client/src/workers/Linting/lint.worker.ts index d529788f30..ed0d5814e8 100644 --- a/app/client/src/workers/Linting/lint.worker.ts +++ b/app/client/src/workers/Linting/lint.worker.ts @@ -1,4 +1,6 @@ +import { isEqual } from "lodash"; import { WorkerErrorTypes } from "workers/common/types"; +import { JSLibraries, resetJSLibraries } from "workers/common/JSLibrary"; import { LintWorkerRequest, LintTreeResponse, @@ -6,37 +8,47 @@ import { LintTreeRequest, } from "./types"; import { getlintErrorsFromTree } from "./utils"; +import { TMessage, MessageType, sendMessage } from "utils/MessageUtil"; function messageEventListener(fn: typeof eventRequestHandler) { - return (event: MessageEvent) => { - const { method, requestId } = event.data; + return (event: MessageEvent>) => { + const { messageType } = event.data; + if (messageType !== MessageType.REQUEST) return; + const { body, messageId } = event.data; + const { data, method } = body; if (!method) return; const startTime = performance.now(); - const responseData = fn(event.data); + const responseData = fn({ method, requestData: data }); const endTime = performance.now(); if (!responseData) return; try { - self.postMessage({ - requestId, - responseData, - timeTaken: (endTime - startTime).toFixed(2), + sendMessage.call(self, { + messageId, + messageType: MessageType.RESPONSE, + body: { + data: responseData, + timeTaken: (endTime - startTime).toFixed(2), + }, }); } catch (e) { // eslint-disable-next-line no-console console.error(e); - self.postMessage({ - requestId, - responseData: { - errors: [ - { - type: WorkerErrorTypes.CLONE_ERROR, - message: (e as Error)?.message, - }, - ], + sendMessage.call(self, { + messageId, + messageType: MessageType.RESPONSE, + body: { + data: { + errors: [ + { + type: WorkerErrorTypes.CLONE_ERROR, + message: (e as Error)?.message, + }, + ], + }, + timeTaken: (endTime - startTime).toFixed(2), }, - timeTaken: (endTime - startTime).toFixed(2), }); } }; @@ -45,7 +57,10 @@ function messageEventListener(fn: typeof eventRequestHandler) { function eventRequestHandler({ method, requestData, -}: LintWorkerRequest): LintTreeResponse | unknown { +}: { + method: LINT_WORKER_ACTIONS; + requestData: any; +}): LintTreeResponse | unknown { switch (method) { case LINT_WORKER_ACTIONS.LINT_TREE: { const lintTreeResponse: LintTreeResponse = { errors: {} }; @@ -56,7 +71,24 @@ function eventRequestHandler({ } catch (e) {} return lintTreeResponse; } - + case LINT_WORKER_ACTIONS.UPDATE_LINT_GLOBALS: { + const { add, libs } = requestData; + if (add) { + JSLibraries.push(...libs); + } else if (add === false) { + for (const lib of libs) { + const idx = JSLibraries.findIndex((l) => + isEqual(l.accessor.sort(), lib.accessor.sort()), + ); + if (idx === -1) return; + JSLibraries.splice(idx, 1); + } + } else { + resetJSLibraries(); + JSLibraries.push(...libs); + } + return true; + } default: { // eslint-disable-next-line no-console console.error("Action not registered on lintWorker ", method); diff --git a/app/client/src/workers/Linting/types.ts b/app/client/src/workers/Linting/types.ts index f8c1dcb141..4a7b070d6d 100644 --- a/app/client/src/workers/Linting/types.ts +++ b/app/client/src/workers/Linting/types.ts @@ -4,6 +4,7 @@ import { WorkerRequest } from "workers/common/types"; export enum LINT_WORKER_ACTIONS { LINT_TREE = "LINT_TREE", + UPDATE_LINT_GLOBALS = "UPDATE_LINT_GLOBALS", } export interface LintTreeResponse { diff --git a/app/client/src/workers/Linting/utils.ts b/app/client/src/workers/Linting/utils.ts index d780446cc6..9bd0be7294 100644 --- a/app/client/src/workers/Linting/utils.ts +++ b/app/client/src/workers/Linting/utils.ts @@ -2,13 +2,12 @@ import { DataTree, DataTreeEntity } from "entities/DataTree/dataTreeFactory"; import { Position } from "codemirror"; import { - EVAL_WORKER_ACTIONS, - extraLibraries, isDynamicValue, isPathADynamicBinding, LintError, PropertyEvaluationErrorType, } from "utils/DynamicBindingUtils"; +import { MAIN_THREAD_ACTION } from "workers/Evaluation/evalWorkerActions"; import { JSHINT as jshint, LintError as JSHintError, @@ -52,6 +51,8 @@ import { } from "workers/Evaluation/evaluationUtils"; import { LintErrors } from "reducers/lintingReducers/lintErrorsReducers"; import { Severity } from "entities/AppsmithConsole"; +import { JSLibraries } from "workers/common/JSLibrary"; +import { MessageType, sendMessage } from "utils/MessageUtil"; export function getlintErrorsFromTree( pathsToLint: string[], @@ -302,7 +303,11 @@ export function getLintingErrors( globalData[dataKey] = true; } // Jshint shouldn't throw errors for additional libraries - extraLibraries.forEach((lib) => (globalData[lib.accessor] = true)); + const libAccessors = ([] as string[]).concat( + ...JSLibraries.map((lib) => lib.accessor), + ); + libAccessors.forEach((accessor) => (globalData[accessor] = true)); + // JSHint shouldn't throw errors for supported web apis Object.keys(SUPPORTED_WEB_APIS).forEach( (apiName) => (globalData[apiName] = true), @@ -464,12 +469,15 @@ export function initiateLinting( requiresLinting: boolean, ) { if (!requiresLinting) return; - postMessage({ - promisified: true, - responseData: { - lintOrder, - unevalTree, - type: EVAL_WORKER_ACTIONS.LINT_TREE, + sendMessage.call(self, { + messageId: "", + messageType: MessageType.REQUEST, + body: { + data: { + lintOrder, + unevalTree, + }, + method: MAIN_THREAD_ACTION.LINT_TREE, }, }); } diff --git a/app/client/src/workers/Tern/tern.worker.ts b/app/client/src/workers/Tern/tern.worker.ts index df88766508..5068eef3fc 100644 --- a/app/client/src/workers/Tern/tern.worker.ts +++ b/app/client/src/workers/Tern/tern.worker.ts @@ -38,7 +38,6 @@ function getFile(file: string, c: CallbackFn) { } function startServer(defs: Def[], plugins = {}, scripts?: string[]) { - //@ts-expect-error test if (scripts) self.importScripts.apply(null, scripts); server = new tern.Server({ diff --git a/app/client/src/workers/common/DataTreeEvaluator/index.ts b/app/client/src/workers/common/DataTreeEvaluator/index.ts index 93dd628246..3a2e8a1817 100644 --- a/app/client/src/workers/common/DataTreeEvaluator/index.ts +++ b/app/client/src/workers/common/DataTreeEvaluator/index.ts @@ -1013,7 +1013,6 @@ export default class DataTreeEvaluator { async evaluateTriggers( userScript: string, dataTree: DataTree, - requestId: string, resolvedFunctions: Record, callbackData: Array, context?: EvaluateContext, @@ -1022,7 +1021,6 @@ export default class DataTreeEvaluator { return evaluateAsync( jsSnippets[0] || userScript, dataTree, - requestId, resolvedFunctions, context, callbackData, diff --git a/app/client/src/workers/common/DependencyMap/utils.ts b/app/client/src/workers/common/DependencyMap/utils.ts index c54090892f..041f9d3824 100644 --- a/app/client/src/workers/common/DependencyMap/utils.ts +++ b/app/client/src/workers/common/DependencyMap/utils.ts @@ -5,7 +5,6 @@ import { EvalError, DependencyMap, getDynamicBindings, - extraLibrariesNames, getEntityDynamicBindingPathList, } from "utils/DynamicBindingUtils"; import { extractIdentifierInfoFromCode } from "@shared/ast"; @@ -26,6 +25,7 @@ import { JAVASCRIPT_KEYWORDS, } from "constants/WidgetValidation"; import { APPSMITH_GLOBAL_FUNCTIONS } from "components/editorComponents/ActionCreator/constants"; +import { libraryReservedIdentifiers } from "workers/common/JSLibrary"; /** This function extracts validReferences and invalidReferences from a binding {{}} * @param script @@ -45,7 +45,7 @@ export const extractInfoFromBinding = ( const { references } = extractIdentifierInfoFromCode( script, self.evaluationVersion, - invalidEntityIdentifiers, + { ...invalidEntityIdentifiers, ...libraryReservedIdentifiers }, ); return extractInfoFromReferences(references, allPaths); }; @@ -207,7 +207,6 @@ const invalidEntityIdentifiers: Record = { ...JAVASCRIPT_KEYWORDS, ...APPSMITH_GLOBAL_FUNCTIONS, ...DEDICATED_WORKER_GLOBAL_SCOPE_IDENTIFIERS, - ...extraLibrariesNames, }; export function listEntityDependencies( diff --git a/app/client/src/workers/common/JSLibrary/__tests__/ternDefinitionGenerator.test.ts b/app/client/src/workers/common/JSLibrary/__tests__/ternDefinitionGenerator.test.ts new file mode 100644 index 0000000000..1451088a8a --- /dev/null +++ b/app/client/src/workers/common/JSLibrary/__tests__/ternDefinitionGenerator.test.ts @@ -0,0 +1,62 @@ +import { makeTernDefs } from "../ternDefinitionGenerator"; + +describe("Tests tern definition generator", () => { + const obj = { + var1: "myVar1", + var2: 2, + var3: true, + var4: null, + var5: undefined, + var6: { a: 1, b: 2 }, + var7: () => { + return "there!"; + }, + var8: function() { + return "hey, "; + }, + var9: new Date(), + }; + const proto = { + sayHello() { + return "Hello"; + }, + }; + it("Correctly determines tern def types based", () => { + const expected = { + var1: { "!type": "string" }, + var2: { "!type": "number" }, + var3: { "!type": "bool" }, + var4: { "!type": "?" }, + var5: { "!type": "?" }, + var6: { a: { "!type": "number" }, b: { "!type": "number" } }, + var7: { "!type": "fn()" }, + }; + const defs = makeTernDefs(obj); + expect(defs).toMatchObject(expected); + }); + it("should look up the prototype chain on objects", () => { + Object.setPrototypeOf(obj, proto); + const expected = { + sayHello: { "!type": "fn()" }, + }; + const defs = makeTernDefs(proto); + expect(defs).toMatchObject(expected); + }); + it("should look up the prototype property on functions", () => { + obj.var8.prototype = { + sayWorld() { + return "World"; + }, + }; + const expected = { + var8: { + "!type": "fn()", + prototype: { + sayWorld: { "!type": "fn()" }, + }, + }, + }; + const defs = makeTernDefs(obj); + expect(defs).toMatchObject(expected); + }); +}); diff --git a/app/client/src/workers/common/JSLibrary/index.ts b/app/client/src/workers/common/JSLibrary/index.ts new file mode 100644 index 0000000000..21730fc836 --- /dev/null +++ b/app/client/src/workers/common/JSLibrary/index.ts @@ -0,0 +1,74 @@ +import _, { VERSION as lodashVersion } from "lodash"; +import moment from "moment-timezone"; +import parser from "fast-xml-parser"; +import forge from "node-forge"; + +export type TJSLibrary = { + version?: string; + docsURL: string; + name: string; + accessor: string[]; + lib?: any; + url?: string; +}; +export const defaultLibraries: TJSLibrary[] = [ + { + accessor: ["_"], + lib: _, + version: lodashVersion, + docsURL: `https://lodash.com/docs/${lodashVersion}`, + name: "lodash", + }, + { + accessor: ["moment"], + lib: moment, + version: moment.version, + docsURL: `https://momentjs.com/docs/`, + name: "moment", + }, + { + accessor: ["xmlParser"], + lib: parser, + version: "3.17.5", + docsURL: "https://github.com/NaturalIntelligence/fast-xml-parser", + name: "xmlParser", + }, + { + accessor: ["forge"], + // We are removing some functionalities of node-forge because they wont + // work in the worker thread + lib: _.omit(forge, ["tls", "http", "xhr", "socket", "task"]), + version: "1.3.0", + docsURL: "https://github.com/digitalbazaar/forge", + name: "forge", + }, +]; + +export const JSLibraries = [...defaultLibraries]; +export const libraryReservedIdentifiers = defaultLibraries.reduce( + (acc, lib) => { + lib.accessor.forEach((a) => (acc[a] = true)); + return acc; + }, + {} as Record, +); + +export function resetJSLibraries() { + JSLibraries.length = 0; + JSLibraries.push(...defaultLibraries); + const defaultLibraryAccessors = defaultLibraries.map( + (lib) => lib.accessor[0], + ); + for (const key of Object.keys(libraryReservedIdentifiers)) { + if (defaultLibraryAccessors.includes(key)) continue; + try { + // @ts-expect-error: Types are not available + delete self[key]; + } catch (e) { + // @ts-expect-error: Types are not available + self[key] = undefined; + } + delete libraryReservedIdentifiers[key]; + } + return JSLibraries; +} diff --git a/app/client/src/workers/common/JSLibrary/ternDefinitionGenerator.ts b/app/client/src/workers/common/JSLibrary/ternDefinitionGenerator.ts new file mode 100644 index 0000000000..8af92bf5c7 --- /dev/null +++ b/app/client/src/workers/common/JSLibrary/ternDefinitionGenerator.ts @@ -0,0 +1,84 @@ +import log from "loglevel"; +import { Def } from "tern"; + +function getTernDocType(obj: any) { + const type = typeof obj; + switch (type) { + case "string": + return "string"; + case "number": + return "number"; + case "boolean": + return "bool"; + case "undefined": + return "?"; + case "function": + return "fn()"; + default: + return "?"; + } +} + +const ignoredKeys = [ + "constructor", + "WINDOW", + "window", + "self", + "arguments", + "caller", + "length", + "name", +]; + +export function makeTernDefs(obj: any) { + const defs: Def = {}; + const cachedDefs: any = []; + const visitedReferences: any = []; + const MAX_ITERATIONS = 5000; + let iteration_count = 1; + const baseObjPrototype = Object.getPrototypeOf({}); + + const queue = [[obj, defs]]; + + try { + while (queue.length && iteration_count < MAX_ITERATIONS) { + const [src, target] = queue.shift() as any; + if (visitedReferences.includes(src)) { + target["!type"] = cachedDefs[visitedReferences.indexOf(src)]["!type"]; + continue; + } + const type = typeof src; + if (!src || (type !== "object" && type !== "function")) { + target["!type"] = getTernDocType(src); + continue; + } else if (type === "function") { + target["!type"] = "fn()"; + } + queue.push( + ...Object.getOwnPropertyNames(src) + .filter((key) => !ignoredKeys.includes(key)) + .map((key) => { + target[key] = {}; + return [src[key], target[key]]; + }), + ); + if (type === "object") { + const prototype = Object.getPrototypeOf(src); + if (prototype !== baseObjPrototype) { + queue.push( + ...Object.getOwnPropertyNames(prototype) + .filter((key) => !ignoredKeys.includes(key)) + .map((key) => { + target[key] = {}; + return [src[key], target[key]]; + }), + ); + } + } + iteration_count++; + } + } catch (e) { + log.debug("Unknown depth", e); + } + return defs; +} diff --git a/app/client/src/workers/common/types.ts b/app/client/src/workers/common/types.ts index 226e53f712..f30aee8f8e 100644 --- a/app/client/src/workers/common/types.ts +++ b/app/client/src/workers/common/types.ts @@ -9,6 +9,5 @@ export enum WorkerErrorTypes { export interface WorkerRequest { method: TActions; - requestData: TData; - requestId: string; + data: TData; } diff --git a/app/client/test/sagas.ts b/app/client/test/sagas.ts index f2d75d1447..29fec1d9c3 100644 --- a/app/client/test/sagas.ts +++ b/app/client/test/sagas.ts @@ -28,6 +28,8 @@ import { watchJSActionSagas } from "sagas/JSActionSagas"; import selectionCanvasSagas from "../src/sagas/CanvasSagas/SelectionCanvasSagas"; import draggingCanvasSagas from "../src/sagas/CanvasSagas/DraggingCanvasSagas"; import formEvaluationChangeListener from "../src/sagas/FormEvaluationSaga"; +import LintingSaga from "../src/sagas/LintingSagas"; +import JSLibrarySaga from "../src/sagas/JSLibrarySaga"; export const sagasToRunForTests = [ initSagas, @@ -60,4 +62,6 @@ export const sagasToRunForTests = [ watchJSActionSagas, selectionCanvasSagas, draggingCanvasSagas, + LintingSaga, + JSLibrarySaga, ]; diff --git a/app/client/tsconfig.json b/app/client/tsconfig.json index b82548fed9..31eaa71b6c 100644 --- a/app/client/tsconfig.json +++ b/app/client/tsconfig.json @@ -2,7 +2,7 @@ "extends": "./tsconfig.path.json", "compilerOptions": { "target": "ES6", - "lib": ["DOM", "ES6", "DOM.Iterable", "ScriptHost", "ES2016.Array.Include", "es2020.string", "esnext"], + "lib": ["DOM", "ES6", "DOM.Iterable", "ScriptHost", "ES2016.Array.Include", "es2020.string", "esnext", "WebWorker"], "strict": true, "outDir": "./out/js/src", "allowJs": true, diff --git a/app/client/yarn.lock b/app/client/yarn.lock index 027d7b1dbf..1ccb6759bd 100644 --- a/app/client/yarn.lock +++ b/app/client/yarn.lock @@ -5767,7 +5767,7 @@ css-select-base-adapter@^0.1.1: version "0.1.1" resolved "https://registry.npmjs.org/css-select-base-adapter/-/css-select-base-adapter-0.1.1.tgz" -css-select@4.1.3, css-select@^2.0.0, css-select@^4.1.3: +css-select@4.1.3, css-select@^2.0.0, css-select@^4.1.3, css-select@^5.1.0: version "4.1.3" resolved "https://registry.yarnpkg.com/css-select/-/css-select-4.1.3.tgz#a70440f70317f2669118ad74ff105e65849c7067" integrity sha512-gT3wBNd9Nj49rAbmtFHj1cljIAOLYSX1nZ8CB7TBO3INYckygm5B7LISU/szY//YmdiSLbJvDLOx9VnMVpMBxA== @@ -5904,6 +5904,11 @@ cssom@^0.4.4: version "0.4.4" resolved "https://registry.npmjs.org/cssom/-/cssom-0.4.4.tgz" +cssom@^0.5.0: + version "0.5.0" + resolved "https://registry.yarnpkg.com/cssom/-/cssom-0.5.0.tgz#d254fa92cd8b6fbd83811b9fbaed34663cc17c36" + integrity sha512-iKuQcq+NdHqlAcwUY0o/HL69XQrUaQdMjmStJ8JFmUaiiQErlhrmuigkg/CU4E2J0IyUKUrMAgl36TvN67MqTw== + cssom@~0.3.6: version "0.3.8" resolved "https://registry.npmjs.org/cssom/-/cssom-0.3.8.tgz" @@ -6365,6 +6370,15 @@ dom-serializer@^1.0.1: domhandler "^4.2.0" entities "^2.0.0" +dom-serializer@^2.0.0: + version "2.0.0" + resolved "https://registry.yarnpkg.com/dom-serializer/-/dom-serializer-2.0.0.tgz#e41b802e1eedf9f6cae183ce5e622d789d7d8e53" + integrity sha512-wIkAryiqt/nV5EQKqQpo3SToSOV9J0DnbJqwK7Wv/Trc92zIAYZ4FlMu+JPFW1DfGFt81ZTCGgDEabffXeLyJg== + dependencies: + domelementtype "^2.3.0" + domhandler "^5.0.2" + entities "^4.2.0" + dom4@^2.1.5: version "2.1.5" resolved "https://registry.npmjs.org/dom4/-/dom4-2.1.5.tgz" @@ -6377,7 +6391,7 @@ domelementtype@^2.0.1: version "2.0.2" resolved "https://registry.npmjs.org/domelementtype/-/domelementtype-2.0.2.tgz" -domelementtype@^2.2.0: +domelementtype@^2.2.0, domelementtype@^2.3.0: version "2.3.0" resolved "https://registry.npmjs.org/domelementtype/-/domelementtype-2.3.0.tgz" integrity sha512-OLETBj6w0OsagBwdXnPdN0cnMfF9opN69co+7ZrbfPGrdpPVNBUj02spi6B1N7wChLQiPn4CSH/zJvXw56gmHw== @@ -6401,6 +6415,13 @@ domhandler@^4.0.0, domhandler@^4.2.0: dependencies: domelementtype "^2.2.0" +domhandler@^5.0.1, domhandler@^5.0.2: + version "5.0.3" + resolved "https://registry.yarnpkg.com/domhandler/-/domhandler-5.0.3.tgz#cc385f7f751f1d1fc650c21374804254538c7d31" + integrity sha512-cgwlv/1iFQiFnU96XXgROh8xTeetsnJiDsTc7TYCLFd9+/WNkIqPTxiM/8pSd8VIrhXGTf1Ny1q1hquVqDJB5w== + dependencies: + domelementtype "^2.3.0" + domutils@1.5: version "1.5.1" resolved "https://registry.npmjs.org/domutils/-/domutils-1.5.1.tgz" @@ -6417,6 +6438,15 @@ domutils@^2.5.2, domutils@^2.6.0: domelementtype "^2.2.0" domhandler "^4.2.0" +domutils@^3.0.1: + version "3.0.1" + resolved "https://registry.yarnpkg.com/domutils/-/domutils-3.0.1.tgz#696b3875238338cb186b6c0612bd4901c89a4f1c" + integrity sha512-z08c1l761iKhDFtfXO04C7kTdPBLi41zwOZl00WS8b5eiaebNpY00HKbztwBq+e3vyqWNwWF3mP9YLUeqIrF+Q== + dependencies: + dom-serializer "^2.0.0" + domelementtype "^2.3.0" + domhandler "^5.0.1" + dot-case@^3.0.4: version "3.0.4" resolved "https://registry.npmjs.org/dot-case/-/dot-case-3.0.4.tgz" @@ -6611,6 +6641,11 @@ entities@^2.0.0: version "2.0.3" resolved "https://registry.npmjs.org/entities/-/entities-2.0.3.tgz" +entities@^4.2.0, entities@^4.3.0: + version "4.4.0" + resolved "https://registry.yarnpkg.com/entities/-/entities-4.4.0.tgz#97bdaba170339446495e653cfd2db78962900174" + integrity sha512-oYp7156SP8LkeGD0GF85ad1X9Ai79WtRsZ2gxJqtBuzH+98YUV6jkHEKlZkMbcrjJjIVJNIDP/3WL9wQkoPbWA== + errno@^0.1.3: version "0.1.7" resolved "https://registry.npmjs.org/errno/-/errno-0.1.7.tgz" @@ -8255,6 +8290,11 @@ html-escaper@^2.0.0: version "2.0.2" resolved "https://registry.npmjs.org/html-escaper/-/html-escaper-2.0.2.tgz" +html-escaper@^3.0.3: + version "3.0.3" + resolved "https://registry.yarnpkg.com/html-escaper/-/html-escaper-3.0.3.tgz#4d336674652beb1dcbc29ef6b6ba7f6be6fdfed6" + integrity sha512-RuMffC89BOWQoY0WKGpIhn5gX3iI54O6nRA0yC124NYVtzjmFWBIiFd8M0x+ZdX0P9R4lADg1mgP8C7PxGOWuQ== + html-minifier-terser@^6.0.2: version "6.1.0" resolved "https://registry.npmjs.org/html-minifier-terser/-/html-minifier-terser-6.1.0.tgz" @@ -8299,6 +8339,16 @@ htmlparser2@^6.1.0: domutils "^2.5.2" entities "^2.0.0" +htmlparser2@^8.0.1: + version "8.0.1" + resolved "https://registry.yarnpkg.com/htmlparser2/-/htmlparser2-8.0.1.tgz#abaa985474fcefe269bc761a779b544d7196d010" + integrity sha512-4lVbmc1diZC7GUJQtRQ5yBAeUCL1exyMwmForWkRLnwyzWBFxN633SALPMGYaWZvKe9j1pRZJpauvmxENSp/EA== + dependencies: + domelementtype "^2.3.0" + domhandler "^5.0.2" + domutils "^3.0.1" + entities "^4.3.0" + http-deceiver@^1.2.7: version "1.2.7" resolved "https://registry.npmjs.org/http-deceiver/-/http-deceiver-1.2.7.tgz" @@ -9860,6 +9910,17 @@ lines-and-columns@^1.1.6: version "1.1.6" resolved "https://registry.npmjs.org/lines-and-columns/-/lines-and-columns-1.1.6.tgz" +linkedom@^0.14.20: + version "0.14.20" + resolved "https://registry.yarnpkg.com/linkedom/-/linkedom-0.14.20.tgz#4dd4418941507326ef7cc325e8e049853481dbb9" + integrity sha512-H7BX22kn4Ul4Mfr5/Jz039TgfsYce/YCvQ6272LEIlIJ1sYmU3R6yFNSYZU6iDX2aoF76wX+qjcSZEaLwumcAw== + dependencies: + css-select "^5.1.0" + cssom "^0.5.0" + html-escaper "^3.0.3" + htmlparser2 "^8.0.1" + uhyphen "^0.1.0" + lint-staged@^13.0.3: version "13.0.3" resolved "https://registry.yarnpkg.com/lint-staged/-/lint-staged-13.0.3.tgz#d7cdf03a3830b327a2b63c6aec953d71d9dc48c6" @@ -14806,6 +14867,11 @@ uglify-js@^3.1.4: version "3.13.4" resolved "https://registry.yarnpkg.com/uglify-js/-/uglify-js-3.13.4.tgz#592588bb9f47ae03b24916e2471218d914955574" +uhyphen@^0.1.0: + version "0.1.0" + resolved "https://registry.yarnpkg.com/uhyphen/-/uhyphen-0.1.0.tgz#3cc22afa790daa802b9f6789f3583108d5b4a08c" + integrity sha512-o0QVGuFg24FK765Qdd5kk0zU/U4dEsCtN/GSiwNI9i8xsSVtjIAOdTaVhLwZ1nrbWxFVMxNDDl+9fednsOMsBw== + unbox-primitive@^1.0.2: version "1.0.2" resolved "https://registry.yarnpkg.com/unbox-primitive/-/unbox-primitive-1.0.2.tgz#29032021057d5e6cdbd08c5129c226dff8ed6f9e" diff --git a/contributions/CustomJsLibrary.md b/contributions/CustomJsLibrary.md index 313ed1e527..07c7d6e579 100644 --- a/contributions/CustomJsLibrary.md +++ b/contributions/CustomJsLibrary.md @@ -5,14 +5,14 @@ $ cd app/client $ yarn install myLibrary ``` -2. In the file `app/client/src/utils/DynamicBindingUtils.ts` find the const `extraLibraries` and add details about your library in the codebase +2. In the file `app/client/src/worker/common/JSLibrary/index.ts` find the const `defaultLibraries` and add details about your library in the codebase ``` import myLibrary from "myLibrary"; ... ... -const extraLibraries = [ +const defaultLibraries = [ ... { accessor: "myLibrary",// The namespace for access