diff --git a/.gitignore b/.gitignore
index 3a342fd7..9dca76e1 100644
--- a/.gitignore
+++ b/.gitignore
@@ -1,6 +1,5 @@
npm-debug.log
*.log
-/plugins/vorlon/**/*.css
tsconfig.json
/Plugins/obj
**/node_modules
@@ -8,11 +7,11 @@ sync.bat
*.suo
/.vs/
bin/
-GLE id�es.txt
+**/control.css
sync.bat
-Plugins/Vorlon/plugins/remoteDebugging.zip
.settings/launch.json
*.dat
Server/public/stylesheets/style.css
-vorlon
/Server/public/stylesheets/style.css
+/DeploymentTools/deployment-package.zip
+DeploymentTools/deployment-package.zip
\ No newline at end of file
diff --git a/.vscode/launch.json b/.vscode/launch.json
index ee84dc00..08c4a076 100644
--- a/.vscode/launch.json
+++ b/.vscode/launch.json
@@ -19,9 +19,11 @@
// Workspace relative or absolute path to the runtime executable to be used. Default is the runtime executable on the PATH.
"runtimeExecutable": null,
// Optional arguments passed to the runtime executable.
- "runtimeArgs": ["--nolazy"],
+ "runtimeArgs": [
+ "--nolazy"
+ ],
// Environment variables passed to the program.
- "env": { },
+ "env": {},
// Use JavaScript source maps (if they exist).
"sourceMaps": false,
// If JavaScript source maps are enabled, the generated code is expected in this directory.
@@ -35,6 +37,58 @@
// Port to attach to.
"port": 5858,
"sourceMaps": false
+ },
+ {
+ // not working since latest vs code and electron versions :-(
+ "name": "Launch desktop App",
+ "type": "node",
+ "program": "desktop/app/background.js",
+ "stopOnEntry": false,
+ "args": [
+ "--dev"
+ ],
+ "cwd": ".",
+ "runtimeExecutable": "desktop/node_modules/electron-prebuilt/dist/electron.exe",
+ "env": {}
+ },
+ {
+ // not working since latest vs code and electron versions :-(
+ "name": "Launch node.js sample",
+ "type": "node",
+ "program": "client samples/nodejs/app.js",
+ "stopOnEntry": false,
+ "args": [
+ "--nolazy"
+ ],
+ "cwd": ".",
+ "runtimeExecutable": null,
+ "env": {}
+ },
+ {
+ // Name of configuration; appears in the launch configuration drop down menu.
+ "name": "Launch w/TypeScript",
+ // Type of configuration. Possible values: "node", "mono".
+ "type": "node",
+ // Workspace relative or absolute path to the program.
+ "program": "Server/server.ts",
+ // Automatically stop program after launch.
+ "stopOnEntry": false,
+ // Command line arguments passed to the program.
+ "args": [],
+ // Workspace relative or absolute path to the working directory of the program being debugged. Default is the current workspace.
+ "cwd": ".",
+ // Workspace relative or absolute path to the runtime executable to be used. Default is the runtime executable on the PATH.
+ "runtimeExecutable": null,
+ // Optional arguments passed to the runtime executable.
+ "runtimeArgs": [
+ "--nolazy"
+ ],
+ // Environment variables passed to the program.
+ "env": {},
+ // Use JavaScript source maps (if they exist).
+ "sourceMaps": true,
+ // If JavaScript source maps are enabled, the generated code is expected in this directory.
+ "outDir": null
}
]
-}
+}
\ No newline at end of file
diff --git a/.vscode/tasks.json b/.vscode/tasks.json
new file mode 100644
index 00000000..802a46dd
--- /dev/null
+++ b/.vscode/tasks.json
@@ -0,0 +1,20 @@
+// Available variables which can be used inside of strings.
+// ${workspaceRoot}: the root folder of the team
+// ${file}: the current opened file
+// ${fileBasename}: the current opened file's basename
+// ${fileDirname}: the current opened file's dirname
+// ${fileExtname}: the current opened file's extension
+// ${cwd}: the current working directory of the spawned process
+
+{
+ "version": "0.1.0",
+ "command": "gulp",
+ "isShellCommand": true,
+ "tasks": [
+ {
+ "taskName": "default",
+ "isBuildCommand": true,
+ "showOutput": "always"
+ }
+ ]
+}
diff --git a/DeploymentTools/Dockerfile b/DeploymentTools/Dockerfile
new file mode 100644
index 00000000..516b130b
--- /dev/null
+++ b/DeploymentTools/Dockerfile
@@ -0,0 +1,29 @@
+# use the node argon image as base
+FROM node:argon
+
+# Set the Vorlon.JS Docker Image maintainer
+MAINTAINER Julien Corioland (Microsoft, DX)
+
+# update apt get and install unzip
+RUN apt-get -qq update && apt-get -qqy install unzip
+
+# Create the application directory
+RUN mkdir -p /usr/src/vorlonjs
+
+# Set app root as working directory
+WORKDIR /usr/src/vorlonjs
+
+# Send the app content to the container
+COPY deployment-package.zip /usr/src/vorlonjs
+
+# Extract the archive
+RUN unzip deployment-package.zip -d /usr/src/vorlonjs
+
+# Remove the archive
+RUN rm deployment-package.zip
+
+# Expose port 1337
+EXPOSE 1337
+
+# Run Vorlon.JS
+CMD ["npm", "start"]
\ No newline at end of file
diff --git a/DeploymentTools/build-docker-image.cmd b/DeploymentTools/build-docker-image.cmd
new file mode 100644
index 00000000..0930d409
--- /dev/null
+++ b/DeploymentTools/build-docker-image.cmd
@@ -0,0 +1,28 @@
+@ECHO OFF
+
+IF "%1"=="" GOTO :usage
+IF "%2"=="" GOTO :usage
+IF "%3"=="" GOTO :usage
+IF "%4"=="" GOTO :usage
+IF "%5"=="" GOTO :usage
+
+@ECHO "SET DOCKER_HOST TO %1"
+SET DOCKER_HOST=%1
+
+@ECHO "BUILD DOCKER IMAGE"
+docker --tls --tlscacert="%2\ca.pem" --tlscert="%2\cert.pem" --tlskey="%2\key.pem" build -t jcorioland/vorlonjs:0.2 .
+
+@ECHO "LOG INTO DOCKER HUB"
+docker --tls --tlscacert="%2\ca.pem" --tlscert="%2\cert.pem" --tlskey="%2\key.pem" login --username="%3" --password="%4" --email="%5" https://index.docker.io/v1/
+
+@ECHO "PUSH IMAGE INTO DOCKER HUB"
+docker --tls --tlscacert="%2\ca.pem" --tlscert="%2\cert.pem" --tlskey="%2\key.pem" push jcorioland/vorlonjs:0.2
+
+@ECHO "LOG OUT FROM DOCKER HUB"
+docker --tls --tlscacert="%2\ca.pem" --tlscert="%2\cert.pem" --tlskey="%2\key.pem" logout
+
+GOTO :eof
+
+:usage
+@ECHO Usage: %0 ^ ^ ^ ^
+EXIT /B 1
\ No newline at end of file
diff --git a/DeploymentTools/deployment-template.json b/DeploymentTools/deployment-template.json
new file mode 100644
index 00000000..ffd2b94d
--- /dev/null
+++ b/DeploymentTools/deployment-template.json
@@ -0,0 +1,286 @@
+{
+ "$schema": "http://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json#",
+ "contentVersion": "1.0.0.0",
+ "parameters": {
+ "hostingPlanName": {
+ "type": "string",
+ "minLength": 1
+ },
+ "siteName": {
+ "type": "string",
+ "minLength": 1
+ },
+ "sku": {
+ "type": "string",
+ "allowedValues": [
+ "Free",
+ "Shared",
+ "Basic",
+ "Standard",
+ "Premium"
+ ],
+ "defaultValue": "Free"
+ },
+ "workerSize": {
+ "type": "string",
+ "allowedValues": [
+ "0",
+ "1",
+ "2"
+ ],
+ "defaultValue": "0"
+ }
+ },
+ "resources": [
+ {
+ "apiVersion": "2014-06-01",
+ "name": "[parameters('hostingPlanName')]",
+ "type": "Microsoft.Web/serverfarms",
+ "location": "[resourceGroup().location]",
+ "tags": {
+ "displayName": "HostingPlan"
+ },
+ "properties": {
+ "name": "[parameters('hostingPlanName')]",
+ "sku": "[parameters('sku')]",
+ "workerSize": "[parameters('workerSize')]",
+ "numberOfWorkers": 1
+ }
+ },
+ {
+ "apiVersion": "2014-06-01",
+ "name": "[parameters('siteName')]",
+ "type": "Microsoft.Web/sites",
+ "location": "[resourceGroup().location]",
+ "tags": {
+ "[concat('hidden-related:', resourceGroup().id, '/providers/Microsoft.Web/serverfarms/', parameters('hostingPlanName'))]": "Resource",
+ "displayName": "Website"
+ },
+ "dependsOn": [
+ "[concat('Microsoft.Web/serverfarms/', parameters('hostingPlanName'))]"
+ ],
+ "properties": {
+ "name": "[parameters('siteName')]",
+ "serverFarm": "[parameters('hostingPlanName')]"
+ }
+ },
+ {
+ "apiVersion": "2014-04-01",
+ "name": "[concat(parameters('hostingPlanName'), '-', resourceGroup().name)]",
+ "type": "Microsoft.Insights/autoscalesettings",
+ "location": "East US",
+ "tags": {
+ "[concat('hidden-link:', resourceGroup().id, '/providers/Microsoft.Web/serverfarms/', parameters('hostingPlanName'))]": "Resource",
+ "displayName": "AutoScaleSettings"
+ },
+ "dependsOn": [
+ "[concat('Microsoft.Web/serverfarms/', parameters('hostingPlanName'))]"
+ ],
+ "properties": {
+ "profiles": [
+ {
+ "name": "Default",
+ "capacity": {
+ "minimum": 1,
+ "maximum": 2,
+ "default": 1
+ },
+ "rules": [
+ {
+ "metricTrigger": {
+ "metricName": "CpuPercentage",
+ "metricResourceUri": "[concat(resourceGroup().id, '/providers/Microsoft.Web/serverfarms/', parameters('hostingPlanName'))]",
+ "timeGrain": "PT1M",
+ "statistic": "Average",
+ "timeWindow": "PT10M",
+ "timeAggregation": "Average",
+ "operator": "GreaterThan",
+ "threshold": 80.0
+ },
+ "scaleAction": {
+ "direction": "Increase",
+ "type": "ChangeCount",
+ "value": 1,
+ "cooldown": "PT10M"
+ }
+ },
+ {
+ "metricTrigger": {
+ "metricName": "CpuPercentage",
+ "metricResourceUri": "[concat(resourceGroup().id, '/providers/Microsoft.Web/serverfarms/', parameters('hostingPlanName'))]",
+ "timeGrain": "PT1M",
+ "statistic": "Average",
+ "timeWindow": "PT1H",
+ "timeAggregation": "Average",
+ "operator": "LessThan",
+ "threshold": 60.0
+ },
+ "scaleAction": {
+ "direction": "Decrease",
+ "type": "ChangeCount",
+ "value": 1,
+ "cooldown": "PT1H"
+ }
+ }
+ ]
+ }
+ ],
+ "enabled": false,
+ "name": "[concat(parameters('hostingPlanName'), '-', resourceGroup().name)]",
+ "targetResourceUri": "[concat(resourceGroup().id, '/providers/Microsoft.Web/serverfarms/', parameters('hostingPlanName'))]"
+ }
+ },
+ {
+ "apiVersion": "2014-04-01",
+ "name": "[concat('ServerErrors ', parameters('siteName'))]",
+ "type": "Microsoft.Insights/alertrules",
+ "location": "East US",
+ "dependsOn": [
+ "[concat('Microsoft.Web/sites/', parameters('siteName'))]"
+ ],
+ "tags": {
+ "[concat('hidden-link:', resourceGroup().id, '/providers/Microsoft.Web/sites/', parameters('siteName'))]": "Resource",
+ "displayName": "ServerErrorsAlertRule"
+ },
+ "properties": {
+ "name": "[concat('ServerErrors ', parameters('siteName'))]",
+ "description": "[concat(parameters('siteName'), ' has some server errors, status code 5xx.')]",
+ "isEnabled": false,
+ "condition": {
+ "odata.type": "Microsoft.Azure.Management.Insights.Models.ThresholdRuleCondition",
+ "dataSource": {
+ "odata.type": "Microsoft.Azure.Management.Insights.Models.RuleMetricDataSource",
+ "resourceUri": "[concat(resourceGroup().id, '/providers/Microsoft.Web/sites/', parameters('siteName'))]",
+ "metricName": "Http5xx"
+ },
+ "operator": "GreaterThan",
+ "threshold": 0.0,
+ "windowSize": "PT5M"
+ },
+ "action": {
+ "odata.type": "Microsoft.Azure.Management.Insights.Models.RuleEmailAction",
+ "sendToServiceOwners": true,
+ "customEmails": []
+ }
+ }
+ },
+ {
+ "apiVersion": "2014-04-01",
+ "name": "[concat('ForbiddenRequests ', parameters('siteName'))]",
+ "type": "Microsoft.Insights/alertrules",
+ "location": "East US",
+ "dependsOn": [
+ "[concat('Microsoft.Web/sites/', parameters('siteName'))]"
+ ],
+ "tags": {
+ "[concat('hidden-link:', resourceGroup().id, '/providers/Microsoft.Web/sites/', parameters('siteName'))]": "Resource",
+ "displayName": "ForbiddenRequestsAlertRule"
+ },
+ "properties": {
+ "name": "[concat('ForbiddenRequests ', parameters('siteName'))]",
+ "description": "[concat(parameters('siteName'), ' has some requests that are forbidden, status code 403.')]",
+ "isEnabled": false,
+ "condition": {
+ "odata.type": "Microsoft.Azure.Management.Insights.Models.ThresholdRuleCondition",
+ "dataSource": {
+ "odata.type": "Microsoft.Azure.Management.Insights.Models.RuleMetricDataSource",
+ "resourceUri": "[concat(resourceGroup().id, '/providers/Microsoft.Web/sites/', parameters('siteName'))]",
+ "metricName": "Http403"
+ },
+ "operator": "GreaterThan",
+ "threshold": 0,
+ "windowSize": "PT5M"
+ },
+ "action": {
+ "odata.type": "Microsoft.Azure.Management.Insights.Models.RuleEmailAction",
+ "sendToServiceOwners": true,
+ "customEmails": []
+ }
+ }
+ },
+ {
+ "apiVersion": "2014-04-01",
+ "name": "[concat('CPUHigh ', parameters('hostingPlanName'))]",
+ "type": "Microsoft.Insights/alertrules",
+ "location": "East US",
+ "dependsOn": [
+ "[concat('Microsoft.Web/serverfarms/', parameters('hostingPlanName'))]"
+ ],
+ "tags": {
+ "[concat('hidden-link:', resourceGroup().id, '/providers/Microsoft.Web/serverfarms/', parameters('hostingPlanName'))]": "Resource",
+ "displayName": "CPUHighAlertRule"
+ },
+ "properties": {
+ "name": "[concat('CPUHigh ', parameters('hostingPlanName'))]",
+ "description": "[concat('The average CPU is high across all the instances of ', parameters('hostingPlanName'))]",
+ "isEnabled": false,
+ "condition": {
+ "odata.type": "Microsoft.Azure.Management.Insights.Models.ThresholdRuleCondition",
+ "dataSource": {
+ "odata.type": "Microsoft.Azure.Management.Insights.Models.RuleMetricDataSource",
+ "resourceUri": "[concat(resourceGroup().id, '/providers/Microsoft.Web/serverfarms/', parameters('hostingPlanName'))]",
+ "metricName": "CpuPercentage"
+ },
+ "operator": "GreaterThan",
+ "threshold": 90,
+ "windowSize": "PT15M"
+ },
+ "action": {
+ "odata.type": "Microsoft.Azure.Management.Insights.Models.RuleEmailAction",
+ "sendToServiceOwners": true,
+ "customEmails": []
+ }
+ }
+ },
+ {
+ "apiVersion": "2014-04-01",
+ "name": "[concat('LongHttpQueue ', parameters('hostingPlanName'))]",
+ "type": "Microsoft.Insights/alertrules",
+ "location": "East US",
+ "dependsOn": [
+ "[concat('Microsoft.Web/serverfarms/', parameters('hostingPlanName'))]"
+ ],
+ "tags": {
+ "[concat('hidden-link:', resourceGroup().id, '/providers/Microsoft.Web/serverfarms/', parameters('hostingPlanName'))]": "Resource",
+ "displayName": "LongHttpQueueAlertRule"
+ },
+ "properties": {
+ "name": "[concat('LongHttpQueue ', parameters('hostingPlanName'))]",
+ "description": "[concat('The HTTP queue for the instances of ', parameters('hostingPlanName'), ' has a large number of pending requests.')]",
+ "isEnabled": false,
+ "condition": {
+ "odata.type": "Microsoft.Azure.Management.Insights.Models.ThresholdRuleCondition",
+ "dataSource": {
+ "odata.type": "Microsoft.Azure.Management.Insights.Models.RuleMetricDataSource",
+ "resourceUri": "[concat(resourceGroup().id, '/providers/Microsoft.Web/serverfarms/', parameters('hostingPlanName'))]",
+ "metricName": "HttpQueueLength"
+ },
+ "operator": "GreaterThan",
+ "threshold": 100.0,
+ "windowSize": "PT5M"
+ },
+ "action": {
+ "odata.type": "Microsoft.Azure.Management.Insights.Models.RuleEmailAction",
+ "sendToServiceOwners": true,
+ "customEmails": []
+ }
+ }
+ },
+ {
+ "apiVersion": "2014-04-01",
+ "name": "[parameters('siteName')]",
+ "type": "Microsoft.Insights/components",
+ "location": "Central US",
+ "dependsOn": [
+ "[concat('Microsoft.Web/sites/', parameters('siteName'))]"
+ ],
+ "tags": {
+ "[concat('hidden-link:', resourceGroup().id, '/providers/Microsoft.Web/sites/', parameters('siteName'))]": "Resource",
+ "displayName": "AppInsightsComponent"
+ },
+ "properties": {
+ "applicationId": "[parameters('siteName')]"
+ }
+ }
+ ]
+}
diff --git a/DeploymentTools/dev-deployment-template-parameters.json b/DeploymentTools/dev-deployment-template-parameters.json
new file mode 100644
index 00000000..18dfa12f
--- /dev/null
+++ b/DeploymentTools/dev-deployment-template-parameters.json
@@ -0,0 +1,18 @@
+{
+ "$schema": "http://schema.management.azure.com/schemas/2015-01-01/deploymentParameters.json#",
+ "contentVersion": "1.0.0.0",
+ "parameters": {
+ "siteName": {
+ "value": "vorlonjs-dev"
+ },
+ "hostingPlanName": {
+ "value": "vorlonjs-dev-hp"
+ },
+ "sku" :{
+ "value" : "Basic"
+ },
+ "workerSize" : {
+ "value" : "0"
+ }
+ }
+}
\ No newline at end of file
diff --git a/DeploymentTools/post-deployment-template.json b/DeploymentTools/post-deployment-template.json
new file mode 100644
index 00000000..cb2a7122
--- /dev/null
+++ b/DeploymentTools/post-deployment-template.json
@@ -0,0 +1,65 @@
+{
+ "$schema": "http://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json#",
+ "contentVersion": "1.0.0.0",
+ "parameters": {
+ "hostingPlanName": {
+ "type": "string",
+ "minLength": 1
+ },
+ "siteName": {
+ "type": "string",
+ "minLength": 1
+ },
+ "sku": {
+ "type": "string",
+ "allowedValues": [
+ "Free",
+ "Shared",
+ "Basic",
+ "Standard",
+ "Premium"
+ ],
+ "defaultValue": "Free"
+ },
+ "workerSize": {
+ "type": "string",
+ "allowedValues": [
+ "0",
+ "1",
+ "2"
+ ],
+ "defaultValue": "0"
+ }
+ },
+ "resources": [
+ {
+ "apiVersion": "2014-06-01",
+ "name": "[parameters('siteName')]",
+ "type": "Microsoft.Web/sites",
+ "location": "[resourceGroup().location]",
+ "properties": {
+ "name": "[parameters('siteName')]"
+ },
+ "resources": [
+ {
+ "apiVersion": "2014-06-01",
+ "type": "config",
+ "name": "web",
+ "dependsOn": [
+ "[resourceId('Microsoft.Web/Sites', parameters('siteName'))]"
+ ],
+ "properties": {
+ "webSocketsEnabled": true,
+ "virtualApplications": [
+ {
+ "virtualPath": "/",
+ "physicalPath": "site\\wwwroot\\Server",
+ "preloadEnabled": true,
+ "virtualDirectories": null
+ }]
+ }
+ }
+ ]
+ }
+ ]
+}
diff --git a/DeploymentTools/preprod-deployment-template-parameters.json b/DeploymentTools/preprod-deployment-template-parameters.json
new file mode 100644
index 00000000..aebf284b
--- /dev/null
+++ b/DeploymentTools/preprod-deployment-template-parameters.json
@@ -0,0 +1,18 @@
+{
+ "$schema": "http://schema.management.azure.com/schemas/2015-01-01/deploymentParameters.json#",
+ "contentVersion": "1.0.0.0",
+ "parameters": {
+ "siteName": {
+ "value": "vorlonjs-preprod"
+ },
+ "hostingPlanName": {
+ "value": "vorlonjs-preprod-hp"
+ },
+ "sku" :{
+ "value" : "Basic"
+ },
+ "workerSize" : {
+ "value" : "0"
+ }
+ }
+}
\ No newline at end of file
diff --git a/DeploymentTools/production-deployment-template-parameters.json b/DeploymentTools/production-deployment-template-parameters.json
new file mode 100644
index 00000000..afbfc7d0
--- /dev/null
+++ b/DeploymentTools/production-deployment-template-parameters.json
@@ -0,0 +1,21 @@
+{
+ "$schema": "http://schema.management.azure.com/schemas/2015-01-01/deploymentParameters.json#",
+ "contentVersion": "1.0.0.0",
+ "parameters": {
+ "siteName": {
+ "value": "vorlonjs-production"
+ },
+ "hostingPlanName": {
+ "value": "vorlonjs-production-hp"
+ },
+ "slotName":{
+ "value": "staging"
+ },
+ "sku" :{
+ "value" : "Standard"
+ },
+ "workerSize" : {
+ "value" : "0"
+ }
+ }
+}
\ No newline at end of file
diff --git a/DeploymentTools/production-deployment-template.json b/DeploymentTools/production-deployment-template.json
new file mode 100644
index 00000000..a7fa47ec
--- /dev/null
+++ b/DeploymentTools/production-deployment-template.json
@@ -0,0 +1,323 @@
+{
+ "$schema": "http://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json#",
+ "contentVersion": "1.0.0.0",
+ "parameters": {
+ "hostingPlanName": {
+ "type": "string",
+ "minLength": 1
+ },
+ "siteName": {
+ "type": "string",
+ "minLength": 1
+ },
+ "slotName": {
+ "type": "string",
+ "minLength": 1
+ },
+ "sku": {
+ "type": "string",
+ "allowedValues": [
+ "Free",
+ "Shared",
+ "Basic",
+ "Standard",
+ "Premium"
+ ],
+ "defaultValue": "Free"
+ },
+ "workerSize": {
+ "type": "string",
+ "allowedValues": [
+ "0",
+ "1",
+ "2"
+ ],
+ "defaultValue": "0"
+ }
+ },
+ "resources": [
+ {
+ "apiVersion": "2014-06-01",
+ "name": "[parameters('hostingPlanName')]",
+ "type": "Microsoft.Web/serverfarms",
+ "location": "[resourceGroup().location]",
+ "tags": {
+ "displayName": "HostingPlan"
+ },
+ "properties": {
+ "name": "[parameters('hostingPlanName')]",
+ "sku": "[parameters('sku')]",
+ "workerSize": "[parameters('workerSize')]",
+ "numberOfWorkers": 1
+ }
+ },
+ {
+ "apiVersion": "2014-06-01",
+ "name": "[parameters('siteName')]",
+ "type": "Microsoft.Web/sites",
+ "location": "[resourceGroup().location]",
+ "tags": {
+ "[concat('hidden-related:', resourceGroup().id, '/providers/Microsoft.Web/serverfarms/', parameters('hostingPlanName'))]": "Resource",
+ "displayName": "Website"
+ },
+ "dependsOn": [
+ "[concat('Microsoft.Web/serverfarms/', parameters('hostingPlanName'))]"
+ ],
+ "properties": {
+ "name": "[parameters('siteName')]",
+ "serverFarm": "[parameters('hostingPlanName')]"
+ },
+ "resources": [
+ {
+ "apiVersion": "2014-06-01",
+ "type": "slots",
+ "name" : "[parameters('slotName')]",
+ "location": "[resourceGroup().location]",
+ "dependsOn": [
+ "[resourceId('Microsoft.Web/Sites', parameters('siteName'))]"
+ ],
+ "properties": {
+ "name":"[concat(parameters('siteName'), '(', parameters('slotName'), ')')]"
+ },
+ "resources": [
+ {
+ "apiVersion": "2014-06-01",
+ "type": "config",
+ "name": "web",
+ "dependsOn": [
+ "[resourceId('Microsoft.Web/Sites/slots', parameters('siteName'), parameters('slotName'))]"
+ ],
+ "properties": {
+ "webSocketsEnabled": true,
+ "virtualApplications": [
+ {
+ "virtualPath": "/",
+ "physicalPath": "site\\wwwroot",
+ "preloadEnabled": false,
+ "virtualDirectories": null
+ }]
+ }
+ }
+ ]
+ }]
+ },
+ {
+ "apiVersion": "2014-04-01",
+ "name": "[concat(parameters('hostingPlanName'), '-', resourceGroup().name)]",
+ "type": "Microsoft.Insights/autoscalesettings",
+ "location": "East US",
+ "tags": {
+ "[concat('hidden-link:', resourceGroup().id, '/providers/Microsoft.Web/serverfarms/', parameters('hostingPlanName'))]": "Resource",
+ "displayName": "AutoScaleSettings"
+ },
+ "dependsOn": [
+ "[concat('Microsoft.Web/serverfarms/', parameters('hostingPlanName'))]"
+ ],
+ "properties": {
+ "profiles": [
+ {
+ "name": "Default",
+ "capacity": {
+ "minimum": 1,
+ "maximum": 2,
+ "default": 1
+ },
+ "rules": [
+ {
+ "metricTrigger": {
+ "metricName": "CpuPercentage",
+ "metricResourceUri": "[concat(resourceGroup().id, '/providers/Microsoft.Web/serverfarms/', parameters('hostingPlanName'))]",
+ "timeGrain": "PT1M",
+ "statistic": "Average",
+ "timeWindow": "PT10M",
+ "timeAggregation": "Average",
+ "operator": "GreaterThan",
+ "threshold": 80.0
+ },
+ "scaleAction": {
+ "direction": "Increase",
+ "type": "ChangeCount",
+ "value": 1,
+ "cooldown": "PT10M"
+ }
+ },
+ {
+ "metricTrigger": {
+ "metricName": "CpuPercentage",
+ "metricResourceUri": "[concat(resourceGroup().id, '/providers/Microsoft.Web/serverfarms/', parameters('hostingPlanName'))]",
+ "timeGrain": "PT1M",
+ "statistic": "Average",
+ "timeWindow": "PT1H",
+ "timeAggregation": "Average",
+ "operator": "LessThan",
+ "threshold": 60.0
+ },
+ "scaleAction": {
+ "direction": "Decrease",
+ "type": "ChangeCount",
+ "value": 1,
+ "cooldown": "PT1H"
+ }
+ }
+ ]
+ }
+ ],
+ "enabled": false,
+ "name": "[concat(parameters('hostingPlanName'), '-', resourceGroup().name)]",
+ "targetResourceUri": "[concat(resourceGroup().id, '/providers/Microsoft.Web/serverfarms/', parameters('hostingPlanName'))]"
+ }
+ },
+ {
+ "apiVersion": "2014-04-01",
+ "name": "[concat('ServerErrors ', parameters('siteName'))]",
+ "type": "Microsoft.Insights/alertrules",
+ "location": "East US",
+ "dependsOn": [
+ "[concat('Microsoft.Web/sites/', parameters('siteName'))]"
+ ],
+ "tags": {
+ "[concat('hidden-link:', resourceGroup().id, '/providers/Microsoft.Web/sites/', parameters('siteName'))]": "Resource",
+ "displayName": "ServerErrorsAlertRule"
+ },
+ "properties": {
+ "name": "[concat('ServerErrors ', parameters('siteName'))]",
+ "description": "[concat(parameters('siteName'), ' has some server errors, status code 5xx.')]",
+ "isEnabled": false,
+ "condition": {
+ "odata.type": "Microsoft.Azure.Management.Insights.Models.ThresholdRuleCondition",
+ "dataSource": {
+ "odata.type": "Microsoft.Azure.Management.Insights.Models.RuleMetricDataSource",
+ "resourceUri": "[concat(resourceGroup().id, '/providers/Microsoft.Web/sites/', parameters('siteName'))]",
+ "metricName": "Http5xx"
+ },
+ "operator": "GreaterThan",
+ "threshold": 0.0,
+ "windowSize": "PT5M"
+ },
+ "action": {
+ "odata.type": "Microsoft.Azure.Management.Insights.Models.RuleEmailAction",
+ "sendToServiceOwners": true,
+ "customEmails": []
+ }
+ }
+ },
+ {
+ "apiVersion": "2014-04-01",
+ "name": "[concat('ForbiddenRequests ', parameters('siteName'))]",
+ "type": "Microsoft.Insights/alertrules",
+ "location": "East US",
+ "dependsOn": [
+ "[concat('Microsoft.Web/sites/', parameters('siteName'))]"
+ ],
+ "tags": {
+ "[concat('hidden-link:', resourceGroup().id, '/providers/Microsoft.Web/sites/', parameters('siteName'))]": "Resource",
+ "displayName": "ForbiddenRequestsAlertRule"
+ },
+ "properties": {
+ "name": "[concat('ForbiddenRequests ', parameters('siteName'))]",
+ "description": "[concat(parameters('siteName'), ' has some requests that are forbidden, status code 403.')]",
+ "isEnabled": false,
+ "condition": {
+ "odata.type": "Microsoft.Azure.Management.Insights.Models.ThresholdRuleCondition",
+ "dataSource": {
+ "odata.type": "Microsoft.Azure.Management.Insights.Models.RuleMetricDataSource",
+ "resourceUri": "[concat(resourceGroup().id, '/providers/Microsoft.Web/sites/', parameters('siteName'))]",
+ "metricName": "Http403"
+ },
+ "operator": "GreaterThan",
+ "threshold": 0,
+ "windowSize": "PT5M"
+ },
+ "action": {
+ "odata.type": "Microsoft.Azure.Management.Insights.Models.RuleEmailAction",
+ "sendToServiceOwners": true,
+ "customEmails": []
+ }
+ }
+ },
+ {
+ "apiVersion": "2014-04-01",
+ "name": "[concat('CPUHigh ', parameters('hostingPlanName'))]",
+ "type": "Microsoft.Insights/alertrules",
+ "location": "East US",
+ "dependsOn": [
+ "[concat('Microsoft.Web/serverfarms/', parameters('hostingPlanName'))]"
+ ],
+ "tags": {
+ "[concat('hidden-link:', resourceGroup().id, '/providers/Microsoft.Web/serverfarms/', parameters('hostingPlanName'))]": "Resource",
+ "displayName": "CPUHighAlertRule"
+ },
+ "properties": {
+ "name": "[concat('CPUHigh ', parameters('hostingPlanName'))]",
+ "description": "[concat('The average CPU is high across all the instances of ', parameters('hostingPlanName'))]",
+ "isEnabled": false,
+ "condition": {
+ "odata.type": "Microsoft.Azure.Management.Insights.Models.ThresholdRuleCondition",
+ "dataSource": {
+ "odata.type": "Microsoft.Azure.Management.Insights.Models.RuleMetricDataSource",
+ "resourceUri": "[concat(resourceGroup().id, '/providers/Microsoft.Web/serverfarms/', parameters('hostingPlanName'))]",
+ "metricName": "CpuPercentage"
+ },
+ "operator": "GreaterThan",
+ "threshold": 90,
+ "windowSize": "PT15M"
+ },
+ "action": {
+ "odata.type": "Microsoft.Azure.Management.Insights.Models.RuleEmailAction",
+ "sendToServiceOwners": true,
+ "customEmails": []
+ }
+ }
+ },
+ {
+ "apiVersion": "2014-04-01",
+ "name": "[concat('LongHttpQueue ', parameters('hostingPlanName'))]",
+ "type": "Microsoft.Insights/alertrules",
+ "location": "East US",
+ "dependsOn": [
+ "[concat('Microsoft.Web/serverfarms/', parameters('hostingPlanName'))]"
+ ],
+ "tags": {
+ "[concat('hidden-link:', resourceGroup().id, '/providers/Microsoft.Web/serverfarms/', parameters('hostingPlanName'))]": "Resource",
+ "displayName": "LongHttpQueueAlertRule"
+ },
+ "properties": {
+ "name": "[concat('LongHttpQueue ', parameters('hostingPlanName'))]",
+ "description": "[concat('The HTTP queue for the instances of ', parameters('hostingPlanName'), ' has a large number of pending requests.')]",
+ "isEnabled": false,
+ "condition": {
+ "odata.type": "Microsoft.Azure.Management.Insights.Models.ThresholdRuleCondition",
+ "dataSource": {
+ "odata.type": "Microsoft.Azure.Management.Insights.Models.RuleMetricDataSource",
+ "resourceUri": "[concat(resourceGroup().id, '/providers/Microsoft.Web/serverfarms/', parameters('hostingPlanName'))]",
+ "metricName": "HttpQueueLength"
+ },
+ "operator": "GreaterThan",
+ "threshold": 100.0,
+ "windowSize": "PT5M"
+ },
+ "action": {
+ "odata.type": "Microsoft.Azure.Management.Insights.Models.RuleEmailAction",
+ "sendToServiceOwners": true,
+ "customEmails": []
+ }
+ }
+ },
+ {
+ "apiVersion": "2014-04-01",
+ "name": "[parameters('siteName')]",
+ "type": "Microsoft.Insights/components",
+ "location": "Central US",
+ "dependsOn": [
+ "[concat('Microsoft.Web/sites/', parameters('siteName'))]"
+ ],
+ "tags": {
+ "[concat('hidden-link:', resourceGroup().id, '/providers/Microsoft.Web/sites/', parameters('siteName'))]": "Resource",
+ "displayName": "AppInsightsComponent"
+ },
+ "properties": {
+ "applicationId": "[parameters('siteName')]"
+ }
+ }
+ ]
+}
diff --git a/DeploymentTools/production-post-deployment-template.json b/DeploymentTools/production-post-deployment-template.json
new file mode 100644
index 00000000..b867d5e5
--- /dev/null
+++ b/DeploymentTools/production-post-deployment-template.json
@@ -0,0 +1,100 @@
+{
+ "$schema": "http://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json#",
+ "contentVersion": "1.0.0.0",
+ "parameters": {
+ "hostingPlanName": {
+ "type": "string",
+ "minLength": 1
+ },
+ "siteName": {
+ "type": "string",
+ "minLength": 1
+ },
+ "slotName": {
+ "type": "string",
+ "minLength": 1
+ },
+ "sku": {
+ "type": "string",
+ "allowedValues": [
+ "Free",
+ "Shared",
+ "Basic",
+ "Standard",
+ "Premium"
+ ],
+ "defaultValue": "Free"
+ },
+ "workerSize": {
+ "type": "string",
+ "allowedValues": [
+ "0",
+ "1",
+ "2"
+ ],
+ "defaultValue": "0"
+ }
+ },
+ "resources": [
+ {
+ "apiVersion": "2014-06-01",
+ "name": "[parameters('siteName')]",
+ "type": "Microsoft.Web/sites",
+ "location": "[resourceGroup().location]",
+ "properties": {
+ "name": "[parameters('siteName')]"
+ },
+ "resources": [
+ {
+ "apiVersion": "2014-06-01",
+ "type": "config",
+ "name": "web",
+ "dependsOn": [
+ "[resourceId('Microsoft.Web/Sites', parameters('siteName'))]"
+ ],
+ "properties": {
+ "webSocketsEnabled": true,
+ "virtualApplications": [
+ {
+ "virtualPath": "/",
+ "physicalPath": "site\\wwwroot\\Server",
+ "preloadEnabled": false,
+ "virtualDirectories": null
+ }]
+ }
+ },
+ {
+ "apiVersion": "2014-06-01",
+ "type": "slots",
+ "name" : "[parameters('slotName')]",
+ "location": "[resourceGroup().location]",
+ "dependsOn": [
+ "[resourceId('Microsoft.Web/Sites', parameters('siteName'))]"
+ ],
+ "properties": {
+ "name":"[concat(parameters('siteName'), '(', parameters('slotName'), ')')]"
+ },
+ "resources": [
+ {
+ "apiVersion": "2014-06-01",
+ "type": "config",
+ "name": "web",
+ "dependsOn": [
+ "[resourceId('Microsoft.Web/Sites/slots', parameters('siteName'), parameters('slotName'))]"
+ ],
+ "properties": {
+ "webSocketsEnabled": true,
+ "virtualApplications": [
+ {
+ "virtualPath": "/",
+ "physicalPath": "site\\wwwroot\\Server",
+ "preloadEnabled": false,
+ "virtualDirectories": null
+ }]
+ }
+ }
+ ]
+ }
+ ]
+ }]
+}
diff --git a/DeploymentTools/production-preview-slot-deletion.ps1 b/DeploymentTools/production-preview-slot-deletion.ps1
new file mode 100644
index 00000000..588a5214
--- /dev/null
+++ b/DeploymentTools/production-preview-slot-deletion.ps1
@@ -0,0 +1 @@
+Remove-AzureWebsite -Name vorlonjs-production -Slot staging -Force -ErrorAction SilentlyContinu
\ No newline at end of file
diff --git a/Plugins/Vorlon/plugins/babylonInspector/control.css b/Plugins/Vorlon/plugins/babylonInspector/control.css
new file mode 100644
index 00000000..3c16e074
--- /dev/null
+++ b/Plugins/Vorlon/plugins/babylonInspector/control.css
@@ -0,0 +1,124 @@
+#babylonInspector-displayer {
+ position: absolute;
+ display: none;
+ left: 300px;
+ top: 100px;
+ width: 300px;
+ height: 300px;
+}
+
+.tree-node {
+ margin-left: 20px;
+}
+
+.tree-node-button {
+ display: inline-block;
+ cursor: pointer;
+ width: 16px;
+ height: 16px;
+}
+
+.tree-node-content {
+ display: inline-block;
+ margin-left: 5px;
+ margin-right: 5px;
+}
+
+.tree-node-features {
+ display: inline-block;
+ margin-left: 15px;
+}
+
+.tree-node-features * {
+ display: inline-block;
+ margin-left: 15px;
+}
+
+.tree-node-hidden {
+ display: none;
+}
+
+.tree-node-type-icon {
+ display: inline-block;
+ width: 16px;
+ height: 16px;
+}
+
+.tree-node-type-icon-mesh {
+ background-image: url("img/mesh.png");
+}
+
+.tree-node-type-icon-light {
+ background-image: url("img/light.png");
+}
+
+.tree-node-type-icon-camera {
+ background-image: url("img/camera.png");
+}
+
+.tree-node-type-icon-skeleton {
+ background-image: url("img/skeleton.png");
+}
+
+.tree-node-features-element {
+ display: inline-block;
+}
+
+.tree-node-color-sample {
+ width: 12px;
+ height: 12px;
+ margin-left: 5px;
+ border: 1px solid;
+}
+
+.tree-node-texture-thumbnail {
+ width: 20px;
+ height: 20px;
+}
+
+.tree-node-texture-view {
+ width: 300px;
+ height: 300px;
+}
+
+.tree-node-animation-button {
+ width: 16px;
+ height: 16px;
+ background-repeat: no-repeat;
+ background-position: center;
+}
+
+.tree-node-animation-button-play {
+ background-image: url("img/play.png");
+}
+
+.tree-node-animation-button-pause {
+ background-image: url("img/pause.png");
+}
+
+.tree-node-animation-button-stop {
+ background-image: url("img/stop.png");
+}
+
+.tree-node-animation-button-stop-pressed {
+ background-image: url("img/stop_pressed.png");
+}
+
+.tree-node-spot-mesh-button {
+ width: 16px;
+ height: 16px;
+ background-repeat: no-repeat;
+ background-position: center;
+}
+
+.tree-node-spot-mesh-button-on {
+ background-image: url("img/spot_on.png");
+}
+
+.tree-node-spot-mesh-button-off {
+ background-image: url("img/spot_off.png");
+}
+
+.clickable {
+ cursor: pointer;
+}
\ No newline at end of file
diff --git a/Plugins/Vorlon/plugins/babylonInspector/control.html b/Plugins/Vorlon/plugins/babylonInspector/control.html
index 93d13be6..bdd01665 100644
--- a/Plugins/Vorlon/plugins/babylonInspector/control.html
+++ b/Plugins/Vorlon/plugins/babylonInspector/control.html
@@ -1,5 +1,4 @@
\ No newline at end of file
+
diff --git a/Plugins/Vorlon/plugins/babylonInspector/vorlon.babylonInspector.client.ts b/Plugins/Vorlon/plugins/babylonInspector/vorlon.babylonInspector.client.ts
index 9ce2e67e..a680d912 100644
--- a/Plugins/Vorlon/plugins/babylonInspector/vorlon.babylonInspector.client.ts
+++ b/Plugins/Vorlon/plugins/babylonInspector/vorlon.babylonInspector.client.ts
@@ -763,12 +763,14 @@ module VORLON {
* as the user switches between clients on the dashboard.
*/
public refresh(): void {
- if (this.engine) {
- this._sendScenesData();
- } else {
- this.engine = this._getBabylonEngine();
- this.scenes = this.engine.scenes;
- this._sendScenesData();
+ if(typeof BABYLON !== 'undefined'){
+ if (this.engine) {
+ this._sendScenesData();
+ } else {
+ this.engine = this._getBabylonEngine();
+ this.scenes = this.engine.scenes;
+ this._sendScenesData();
+ }
}
}
@@ -776,18 +778,17 @@ module VORLON {
* Start the clientside code : initilization etc
*/
public startClientSide(): void {
- if(!BABYLON.Engine.isSupported()) {
+ if(typeof BABYLON !== 'undefined' && !BABYLON.Engine.isSupported()) {
//error
} else {
+ //document.addEventListener("DOMContentLoaded", () => {
+ this.engine = this._getBabylonEngine();
+ if (this.engine) {
+ this.scenes = this.engine.scenes;
+ this.refresh();
+ }
+ //});
}
-
- //document.addEventListener("DOMContentLoaded", () => {
- this.engine = this._getBabylonEngine();
- if (this.engine) {
- this.scenes = this.engine.scenes;
- this.refresh();
- }
- //});
}
/**
@@ -837,10 +838,13 @@ module VORLON {
* @private
*/
private _findMesh(meshName : string, sceneID : string) {
- var id : number = +sceneID;
- var scene = this.engine.scenes[id];
- var mesh = scene.getMeshByName(meshName);
- return mesh;
+ if(typeof BABYLON !== 'undefined'){
+ var id : number = +sceneID;
+ var scene = this.engine.scenes[id];
+ var mesh = scene.getMeshByName(meshName);
+ return mesh;
+ }
+ return null;
}
/**
@@ -848,7 +852,7 @@ module VORLON {
* @private
*/
private _sendScenesData() {
- if (this.scenes) {
+ if (typeof BABYLON !== 'undefined' && this.scenes) {
var scenesData = this._dataGenerator.generateScenesData(this.scenes);
this.sendToDashboard({
messageType: 'SCENES_DATA',
@@ -864,7 +868,7 @@ module VORLON {
*/
private _getBabylonEngine() {
for (var member in window) {
- if (window[member] instanceof BABYLON.Engine) {
+ if (typeof BABYLON !== 'undefined' && window[member] instanceof BABYLON.Engine) {
return window[member];
}
}
diff --git a/Plugins/Vorlon/plugins/babylonInspector/vorlon.babylonInspector.dashboard.ts b/Plugins/Vorlon/plugins/babylonInspector/vorlon.babylonInspector.dashboard.ts
index aa3537cf..86101043 100644
--- a/Plugins/Vorlon/plugins/babylonInspector/vorlon.babylonInspector.dashboard.ts
+++ b/Plugins/Vorlon/plugins/babylonInspector/vorlon.babylonInspector.dashboard.ts
@@ -221,8 +221,10 @@ module VORLON {
private _createColorSample(colorHex) {
var colorSample = document.createElement('div');
colorSample.className = "tree-node-color-sample";
- colorSample.style.backgroundColor = colorHex;
- colorSample.style.borderColor = this._isClearColor(colorHex) ? '#000000' : '#ffffff';
+ if (colorHex) {
+ colorSample.style.backgroundColor = colorHex;
+ colorSample.style.borderColor = this._isClearColor(colorHex) ? '#000000' : '#ffffff';
+ }
return colorSample;
}
diff --git a/Plugins/Vorlon/plugins/domExplorer/control.less b/Plugins/Vorlon/plugins/domExplorer/control.less
index 7b0a705d..9e8e3f5f 100644
--- a/Plugins/Vorlon/plugins/domExplorer/control.less
+++ b/Plugins/Vorlon/plugins/domExplorer/control.less
@@ -20,9 +20,7 @@
height: 100%;
overflow: hidden !important;
}
-
-
-
+
.panel-left,
.panel-right {
height: 100%;
@@ -532,16 +530,27 @@
.nodeAttribute {
padding-left: 0.5em;
- color: @quotesColor;
-
+ color: @quotesColor;
+
span.attr-name {
color: @attributeNameColor;
}
-
+
+ span.link-hovered{
+ text-decoration: underline;
+ }
+
span.attr-value {
- color: @attributeValueColor;
+ color: @attributeValueColor;
}
}
+
+ .colored-square{
+ display: inline-flex;
+ height: 10px;
+ width: 10px;
+ border: 1px #000 solid;
+ }
.styleLabel, .attributeName {
display: inline-block;
@@ -614,13 +623,14 @@ body .b-m-mpanel {
cursor: pointer;
border: none;
}
+
/*.ui-state-hover, .ui-widget-content .ui-state-hover, .ui-widget-header .ui-state-hover, .ui-state-focus, .ui-widget-content .ui-state-focus, .ui-widget-header .ui-state-focus {
background: #CCC;
}
-
-
+
.ui-menu-item {
padding: 10px;
font-size: 10pt;
}*/
}
+
\ No newline at end of file
diff --git a/Plugins/Vorlon/plugins/domExplorer/vorlon.domExplorer.dashboard.ts b/Plugins/Vorlon/plugins/domExplorer/vorlon.domExplorer.dashboard.ts
index f3799601..d9d7de8f 100644
--- a/Plugins/Vorlon/plugins/domExplorer/vorlon.domExplorer.dashboard.ts
+++ b/Plugins/Vorlon/plugins/domExplorer/vorlon.domExplorer.dashboard.ts
@@ -410,7 +410,7 @@
},
nodeStyle(data: any){
console.log("dashboard receive node style", data);
- var plugin = this;
+ var plugin = this;
plugin.setNodeStyle(data.internalID, data.styles);
}
}
@@ -820,13 +820,15 @@
$('.b-m-mpanel').remove();
$("#" + parentElementId).contextmenu(option);
}
+
nodeValue.addEventListener("contextmenu",() => {
if (nodeValue.contentEditable != "true" && nodeName.contentEditable != "true")
menu.bind(this)("value");
});
- nodeValue.addEventListener("click",() => {
- this.parent.plugin.makeEditable(nodeValue);
- });
+ nodeValue.addEventListener("click",(e) => {
+ if(!this.uriCheck("click", nodeValue, e))
+ this.parent.plugin.makeEditable(nodeValue);
+ });
nodeName.addEventListener("click",() => {
this.parent.plugin.makeEditable(nodeName);
});
@@ -834,8 +836,8 @@
if (nodeValue.contentEditable != "true" && nodeName.contentEditable != "true")
menu.bind(this)("name");
});
- nodeValue.addEventListener("blur",() => {
- sendTextToClient.bind(this)(nodeName.innerHTML, nodeValue.innerHTML, nodeValue);
+ nodeValue.addEventListener("blur",() => {
+ sendTextToClient.bind(this)(nodeName.innerHTML, nodeValue.innerHTML, nodeValue);
});
nodeName.addEventListener("blur",() => {
sendTextToClient.bind(this)(nodeName.innerHTML, nodeValue.innerHTML, nodeName);
@@ -851,8 +853,32 @@
evt.preventDefault();
sendTextToClient.bind(this)(nodeName.innerHTML, nodeValue.innerHTML, nodeValue);
}
+ });
+ nodeValue.addEventListener("mousemove",(e) => {
+ this.uriCheck("mousemove", nodeValue, e);
});
+ nodeValue.addEventListener("mouseout",(e) => {
+ $(nodeValue).removeClass("link-hovered");
+ });
}
+
+ uriCheck(triggerType: string, node, e) {
+ if (e != null && e.ctrlKey) {
+ var urlPattern = /(\w+):\/*([^\/]+)([a-z0-9\-@\^=%&;\/~\+]*)[\?]?([^ \#]*)#?([^ \#]*)/i;
+ if (urlPattern.test(node.innerText)) {
+ switch(triggerType){
+ case "click": open(node.innerText);
+ case "mousemove": $(node).addClass("link-hovered");
+ default: return true;
+ }
+ return true;
+ }
+ }
+ else{
+ $(node).removeClass("link-hovered");
+ }
+ return false;
+ }
render() {
var node = new FluentDOM("SPAN", "nodeAttribute", this.parent.headerAttributes);
@@ -899,6 +925,9 @@
for (var index = 0; index < styles.length; index++) {
var style = styles[index];
var splits = style.split(":");
+ // ensure that urls are not malformed after the split.
+ if(splits[2] !== undefined && splits[2].indexOf('//') > -1)
+ splits[1] += ":" + splits[2];
this.styles.push(new DomExplorerPropertyEditorItem(this, splits[0], splits[1], this.internalId));
}
// Append add style button
@@ -907,8 +936,7 @@
this.plugin.styleView.appendChild(e.target);
});
}
- }
-
+ }
}
export class DomExplorerPropertyEditorItem {
@@ -920,17 +948,24 @@
this.name = name;
this.value = value;
if (generate)
- this._generateStyle(name, value, internalId, editableLabel);
+ this._generateStyle(name, value, internalId, editableLabel);
}
private _generateStyle(property: string, value: string, internalId: string, editableLabel = false): void {
+ console.debug(property + value);
var wrap = document.createElement("div");
wrap.className = 'styleWrap';
var label = document.createElement("div");
label.innerHTML = property;
label.className = "styleLabel";
- label.contentEditable = "false";
+ label.contentEditable = "false";
var valueElement = this._generateClickableValue(label, value, internalId);
- wrap.appendChild(label);
+ wrap.appendChild(label);
+ if(property.indexOf("color") != -1){
+ var square = document.createElement("span");
+ square.className = "colored-square";
+ square.style.backgroundColor = value;
+ wrap.appendChild(square);
+ }
wrap.appendChild(valueElement);
this.parent.plugin.styleView.appendChild(wrap);
@@ -1000,7 +1035,6 @@
});
return valueElement;
}
-
}
export interface LayoutStyle {
diff --git a/Plugins/Vorlon/plugins/interactiveConsole/vorlon.interactiveConsole.client.ts b/Plugins/Vorlon/plugins/interactiveConsole/vorlon.interactiveConsole.client.ts
index 7e9c857b..102f252c 100644
--- a/Plugins/Vorlon/plugins/interactiveConsole/vorlon.interactiveConsole.client.ts
+++ b/Plugins/Vorlon/plugins/interactiveConsole/vorlon.interactiveConsole.client.ts
@@ -107,9 +107,12 @@
for (var i = 0, l = messages.length; i < l; i++) {
var msg = messages[i];
if (typeof msg === 'string' || typeof msg === 'number') {
- resmessages.push(msg);
+ resmessages.push(msg);
} else {
- if (msg == window || msg == document) {
+ if (!Tools.IsWindowAvailable){
+ resmessages.push(this.inspect(msg, msg, 0));
+ }
+ else if(msg == window || msg == document) {
resmessages.push('VORLON : object cannot be inspected, too big...');
} else {
resmessages.push(this.inspect(msg, msg, 0));
@@ -168,13 +171,14 @@
public startClientSide(): void {
this._cache = [];
this._pendingEntries = [];
+ var console = Tools.IsWindowAvailable ? window.console : global.console;
// Overrides clear, log, error and warn
- this._hooks.clear = Tools.Hook(window.console, "clear",(): void => {
+ this._hooks.clear = Tools.Hook(console, "clear",(): void => {
this.clearClientConsole();
});
- this._hooks.dir = Tools.Hook(window.console, "dir",(message: any): void => {
+ this._hooks.dir = Tools.Hook(console, "dir",(message: any): void => {
var data = {
messages: this.getMessages(message),
type: "dir"
@@ -183,7 +187,7 @@
this.addEntry(data);
});
- this._hooks.log = Tools.Hook(window.console, "log", (message: any): void => {
+ this._hooks.log = Tools.Hook(console, "log", (message: any): void => {
var data = {
messages: this.getMessages(message),
type: "log"
@@ -192,7 +196,7 @@
this.addEntry(data);
});
- this._hooks.debug = Tools.Hook(window.console, "debug", (message: any): void => {
+ this._hooks.debug = Tools.Hook(console, "debug", (message: any): void => {
var data = {
messages: this.getMessages(message),
type: "debug"
@@ -201,7 +205,7 @@
this.addEntry(data);
});
- this._hooks.info = Tools.Hook(window.console, "info",(message: any): void => {
+ this._hooks.info = Tools.Hook(console, "info",(message: any): void => {
var data = {
messages: this.getMessages(message),
type: "info"
@@ -210,7 +214,7 @@
this.addEntry(data);
});
- this._hooks.warn = Tools.Hook(window.console, "warn",(message: any): void => {
+ this._hooks.warn = Tools.Hook(console, "warn",(message: any): void => {
var data = {
messages: this.getMessages(message),
type: "warn"
@@ -219,7 +223,7 @@
this.addEntry(data);
});
- this._hooks.error = Tools.Hook(window.console, "error",(message: any): void => {
+ this._hooks.error = Tools.Hook(console, "error",(message: any): void => {
var data = {
messages: this.getMessages(message),
type: "error"
@@ -244,13 +248,15 @@
return error;
});
- window.addEventListener('error', (err) => {
-
- if (err && (err).error) {
- //this.addEntry({ messages: [err.error.message], type: "exception" });
- this.addEntry({ messages: [(err).error.stack], type: "exception" });
- }
- });
+ if (Tools.IsWindowAvailable) {
+ window.addEventListener('error', (err) => {
+
+ if (err && (err).error) {
+ //this.addEntry({ messages: [err.error.message], type: "exception" });
+ this.addEntry({ messages: [(err).error.stack], type: "exception" });
+ }
+ });
+ }
}
public clearClientConsole() {
diff --git a/Plugins/Vorlon/plugins/networkMonitor/vorlon.networkMonitor.client.ts b/Plugins/Vorlon/plugins/networkMonitor/vorlon.networkMonitor.client.ts
index b30f3039..0df6764f 100644
--- a/Plugins/Vorlon/plugins/networkMonitor/vorlon.networkMonitor.client.ts
+++ b/Plugins/Vorlon/plugins/networkMonitor/vorlon.networkMonitor.client.ts
@@ -14,30 +14,31 @@
public sendClientData(): void {
this.trace("network monitor sending data ")
- var entries = window.performance.getEntries();
- //console.log(entries);
-
this.performanceItems = [];
- for (var i = 0; i < entries.length; i++) {
- this.performanceItems.push({
- name: entries[i].name,
- type: entries[i].initiatorType,
- startTime: entries[i].startTime,
- duration: entries[i].duration,
- redirectStart: entries[i].redirectStart,
- redirectDuration: entries[i].redirectEnd - entries[i].redirectStart,
- dnsStart: entries[i].domainLookupStart,
- dnsDuration: entries[i].domainLookupEnd - entries[i].domainLookupStart,
- tcpStart: entries[i].connectStart,
- tcpDuration: entries[i].connectEnd - entries[i].connectStart, // TODO
- requestStart: entries[i].requestStart,
- requestDuration: entries[i].responseStart - entries[i].requestStart,
- responseStart: entries[i].responseStart,
- responseDuration: (entries[i].responseStart == 0 ? 0 : entries[i].responseEnd - entries[i].responseStart)
- });
+
+ if (window.performance) {
+ var entries = window.performance.getEntries();
+
+ for (var i = 0; i < entries.length; i++) {
+ this.performanceItems.push({
+ name: entries[i].name,
+ type: entries[i].initiatorType,
+ startTime: entries[i].startTime,
+ duration: entries[i].duration,
+ redirectStart: entries[i].redirectStart,
+ redirectDuration: entries[i].redirectEnd - entries[i].redirectStart,
+ dnsStart: entries[i].domainLookupStart,
+ dnsDuration: entries[i].domainLookupEnd - entries[i].domainLookupStart,
+ tcpStart: entries[i].connectStart,
+ tcpDuration: entries[i].connectEnd - entries[i].connectStart, // TODO
+ requestStart: entries[i].requestStart,
+ requestDuration: entries[i].responseStart - entries[i].requestStart,
+ responseStart: entries[i].responseStart,
+ responseDuration: (entries[i].responseStart == 0 ? 0 : entries[i].responseEnd - entries[i].responseStart)
+ });
+ }
}
- //console.log(this.performanceItems);
var message: any = {};
message.entries = this.performanceItems;
this.sendCommandToDashboard("performanceItems", message);
diff --git a/Plugins/Vorlon/plugins/objectExplorer/vorlon.objectExplorer.client.ts b/Plugins/Vorlon/plugins/objectExplorer/vorlon.objectExplorer.client.ts
index e69d3b9b..74f8f8f7 100644
--- a/Plugins/Vorlon/plugins/objectExplorer/vorlon.objectExplorer.client.ts
+++ b/Plugins/Vorlon/plugins/objectExplorer/vorlon.objectExplorer.client.ts
@@ -14,7 +14,7 @@
private STRIP_COMMENTS = /((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg;
private ARGUMENT_NAMES = /([^\s,]+)/g;
- private rootProperty = 'window';
+ private rootProperty = Tools.IsWindowAvailable ? 'window' : "global";
private getFunctionArgumentNames(func) {
var result = [];
@@ -154,7 +154,7 @@
}
private _getProperty(propertyPath: string): ObjExplorerObjDescriptor {
- var selectedObj = window;
+ var selectedObj = Tools.IsWindowAvailable ? window : global;
var tokens = [this.rootProperty];
this.trace("getting obj at " + propertyPath);
diff --git a/Plugins/Vorlon/plugins/objectExplorer/vorlon.objectExplorer.dashboard.ts b/Plugins/Vorlon/plugins/objectExplorer/vorlon.objectExplorer.dashboard.ts
index 997a25a7..67de5be5 100644
--- a/Plugins/Vorlon/plugins/objectExplorer/vorlon.objectExplorer.dashboard.ts
+++ b/Plugins/Vorlon/plugins/objectExplorer/vorlon.objectExplorer.dashboard.ts
@@ -177,7 +177,7 @@
var elt = new FluentDOM('DIV', 'objdescriptor', parent);
this.element = elt.element;
this.isRoot = isRoot;
- this.element.__vorlon = this;
+ (this.element).__vorlon = this;
this.item = item;
this.plugin = plugin;
this.childs = [];
@@ -198,7 +198,7 @@
public dispose() {
this.clear();
- this.element.__vorlon = null;
+ (this.element).__vorlon = null;
this.plugin = null;
this.element = null;
this.item = null;
@@ -380,7 +380,7 @@
btn.text("-");
var elt = this.element.element.querySelector(".expand-content > .objdescriptor");
if (elt) {
- var ctrl = elt.__vorlon;
+ var ctrl = (elt).__vorlon;
if (ctrl) {
setTimeout(() => {
ctrl.getContent();
diff --git a/Plugins/Vorlon/plugins/unitTestRunner/qunit.js b/Plugins/Vorlon/plugins/unitTestRunner/qunit.js
index 317ec406..f51204cb 100644
--- a/Plugins/Vorlon/plugins/unitTestRunner/qunit.js
+++ b/Plugins/Vorlon/plugins/unitTestRunner/qunit.js
@@ -1,102 +1,248 @@
/*!
- * QUnit 1.18.1-pre
+ * QUnit 1.20.0
* http://qunitjs.com/
*
* Copyright jQuery Foundation and other contributors
* Released under the MIT license
* http://jquery.org/license
*
- * Date: 2015-06-18T11:09Z
+ * Date: 2015-10-27T17:53Z
*/
-(function( window ) {
+(function( global ) {
-var QUnit,
- config,
- onErrorFnPrev,
- loggingCallbacks = {},
- fileName = ( sourceFromStacktrace( 0 ) || "" ).replace( /(:\d+)+\)?/, "" ).replace( /.+\//, "" ),
- toString = Object.prototype.toString,
- hasOwn = Object.prototype.hasOwnProperty,
- // Keep a local reference to Date (GH-283)
- Date = window.Date,
- now = Date.now || function() {
- return new Date().getTime();
- },
- globalStartCalled = false,
- runStarted = false,
- setTimeout = window.setTimeout,
- clearTimeout = window.clearTimeout,
- defined = {
- document: window.document !== undefined,
- setTimeout: window.setTimeout !== undefined,
- sessionStorage: (function() {
- var x = "qunit-test-string";
- try {
- sessionStorage.setItem( x, x );
- sessionStorage.removeItem( x );
- return true;
- } catch ( e ) {
- return false;
+var QUnit = {};
+
+var Date = global.Date;
+var now = Date.now || function() {
+ return new Date().getTime();
+};
+
+var setTimeout = global.setTimeout;
+var clearTimeout = global.clearTimeout;
+
+// Store a local window from the global to allow direct references.
+var window = global.window;
+
+var defined = {
+ document: window && window.document !== undefined,
+ setTimeout: setTimeout !== undefined,
+ sessionStorage: (function() {
+ var x = "qunit-test-string";
+ try {
+ sessionStorage.setItem( x, x );
+ sessionStorage.removeItem( x );
+ return true;
+ } catch ( e ) {
+ return false;
+ }
+ }() )
+};
+
+var fileName = ( sourceFromStacktrace( 0 ) || "" ).replace( /(:\d+)+\)?/, "" ).replace( /.+\//, "" );
+var globalStartCalled = false;
+var runStarted = false;
+
+var toString = Object.prototype.toString,
+ hasOwn = Object.prototype.hasOwnProperty;
+
+// returns a new Array with the elements that are in a but not in b
+function diff( a, b ) {
+ var i, j,
+ result = a.slice();
+
+ for ( i = 0; i < result.length; i++ ) {
+ for ( j = 0; j < b.length; j++ ) {
+ if ( result[ i ] === b[ j ] ) {
+ result.splice( i, 1 );
+ i--;
+ break;
}
- }())
- },
- /**
- * Provides a normalized error string, correcting an issue
- * with IE 7 (and prior) where Error.prototype.toString is
- * not properly implemented
- *
- * Based on http://es5.github.com/#x15.11.4.4
- *
- * @param {String|Error} error
- * @return {String} error message
- */
- errorString = function( error ) {
- var name, message,
- errorString = error.toString();
- if ( errorString.substring( 0, 7 ) === "[object" ) {
- name = error.name ? error.name.toString() : "Error";
- message = error.message ? error.message.toString() : "";
- if ( name && message ) {
- return name + ": " + message;
- } else if ( name ) {
- return name;
- } else if ( message ) {
- return message;
+ }
+ }
+ return result;
+}
+
+// from jquery.js
+function inArray( elem, array ) {
+ if ( array.indexOf ) {
+ return array.indexOf( elem );
+ }
+
+ for ( var i = 0, length = array.length; i < length; i++ ) {
+ if ( array[ i ] === elem ) {
+ return i;
+ }
+ }
+
+ return -1;
+}
+
+/**
+ * Makes a clone of an object using only Array or Object as base,
+ * and copies over the own enumerable properties.
+ *
+ * @param {Object} obj
+ * @return {Object} New object with only the own properties (recursively).
+ */
+function objectValues ( obj ) {
+ var key, val,
+ vals = QUnit.is( "array", obj ) ? [] : {};
+ for ( key in obj ) {
+ if ( hasOwn.call( obj, key ) ) {
+ val = obj[ key ];
+ vals[ key ] = val === Object( val ) ? objectValues( val ) : val;
+ }
+ }
+ return vals;
+}
+
+function extend( a, b, undefOnly ) {
+ for ( var prop in b ) {
+ if ( hasOwn.call( b, prop ) ) {
+
+ // Avoid "Member not found" error in IE8 caused by messing with window.constructor
+ // This block runs on every environment, so `global` is being used instead of `window`
+ // to avoid errors on node.
+ if ( prop !== "constructor" || a !== global ) {
+ if ( b[ prop ] === undefined ) {
+ delete a[ prop ];
+ } else if ( !( undefOnly && typeof a[ prop ] !== "undefined" ) ) {
+ a[ prop ] = b[ prop ];
+ }
+ }
+ }
+ }
+
+ return a;
+}
+
+function objectType( obj ) {
+ if ( typeof obj === "undefined" ) {
+ return "undefined";
+ }
+
+ // Consider: typeof null === object
+ if ( obj === null ) {
+ return "null";
+ }
+
+ var match = toString.call( obj ).match( /^\[object\s(.*)\]$/ ),
+ type = match && match[ 1 ];
+
+ switch ( type ) {
+ case "Number":
+ if ( isNaN( obj ) ) {
+ return "nan";
+ }
+ return "number";
+ case "String":
+ case "Boolean":
+ case "Array":
+ case "Set":
+ case "Map":
+ case "Date":
+ case "RegExp":
+ case "Function":
+ case "Symbol":
+ return type.toLowerCase();
+ }
+ if ( typeof obj === "object" ) {
+ return "object";
+ }
+}
+
+// Safe object type checking
+function is( type, obj ) {
+ return QUnit.objectType( obj ) === type;
+}
+
+var getUrlParams = function() {
+ var i, current;
+ var urlParams = {};
+ var location = window.location;
+ var params = location.search.slice( 1 ).split( "&" );
+ var length = params.length;
+
+ if ( params[ 0 ] ) {
+ for ( i = 0; i < length; i++ ) {
+ current = params[ i ].split( "=" );
+ current[ 0 ] = decodeURIComponent( current[ 0 ] );
+
+ // allow just a key to turn on a flag, e.g., test.html?noglobals
+ current[ 1 ] = current[ 1 ] ? decodeURIComponent( current[ 1 ] ) : true;
+ if ( urlParams[ current[ 0 ] ] ) {
+ urlParams[ current[ 0 ] ] = [].concat( urlParams[ current[ 0 ] ], current[ 1 ] );
} else {
- return "Error";
+ urlParams[ current[ 0 ] ] = current[ 1 ];
}
- } else {
- return errorString;
}
- },
- /**
- * Makes a clone of an object using only Array or Object as base,
- * and copies over the own enumerable properties.
- *
- * @param {Object} obj
- * @return {Object} New object with only the own properties (recursively).
- */
- objectValues = function( obj ) {
- var key, val,
- vals = QUnit.is( "array", obj ) ? [] : {};
- for ( key in obj ) {
- if ( hasOwn.call( obj, key ) ) {
- val = obj[ key ];
- vals[ key ] = val === Object( val ) ? objectValues( val ) : val;
+ }
+
+ return urlParams;
+};
+
+// Doesn't support IE6 to IE9, it will return undefined on these browsers
+// See also https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Error/Stack
+function extractStacktrace( e, offset ) {
+ offset = offset === undefined ? 4 : offset;
+
+ var stack, include, i;
+
+ if ( e.stack ) {
+ stack = e.stack.split( "\n" );
+ if ( /^error$/i.test( stack[ 0 ] ) ) {
+ stack.shift();
+ }
+ if ( fileName ) {
+ include = [];
+ for ( i = offset; i < stack.length; i++ ) {
+ if ( stack[ i ].indexOf( fileName ) !== -1 ) {
+ break;
+ }
+ include.push( stack[ i ] );
+ }
+ if ( include.length ) {
+ return include.join( "\n" );
}
}
- return vals;
- };
+ return stack[ offset ];
+
+ // Support: Safari <=6 only
+ } else if ( e.sourceURL ) {
+
+ // exclude useless self-reference for generated Error objects
+ if ( /qunit.js$/.test( e.sourceURL ) ) {
+ return;
+ }
+
+ // for actual exceptions, this is useful
+ return e.sourceURL + ":" + e.line;
+ }
+}
+
+function sourceFromStacktrace( offset ) {
+ var error = new Error();
+
+ // Support: Safari <=7 only, IE <=10 - 11 only
+ // Not all browsers generate the `stack` property for `new Error()`, see also #636
+ if ( !error.stack ) {
+ try {
+ throw error;
+ } catch ( err ) {
+ error = err;
+ }
+ }
-QUnit = {};
+ return extractStacktrace( error, offset );
+}
/**
* Config object: Maintain internal state
* Later exposed as QUnit.config
* `config` initialized at top of scope
*/
-config = {
+var config = {
// The queue of tests to run
queue: [],
@@ -110,15 +256,19 @@ config = {
// by default, modify document.title when suite is done
altertitle: true,
+ // HTML Reporter: collapse every test except the first failing test
+ // If false, all failing tests will be expanded
+ collapse: true,
+
// by default, scroll to top of the page when suite is done
scrolltop: true,
- // when enabled, all tests must call expect()
- requireExpects: false,
-
// depth up-to which object will be dumped
maxDepth: 5,
+ // when enabled, all tests must call expect()
+ requireExpects: false,
+
// add checkboxes that are persisted in the query-string
// when enabled, the id is set to `true` as a `QUnit.config` property
urlConfig: [
@@ -131,7 +281,7 @@ config = {
id: "noglobals",
label: "Check for Globals",
tooltip: "Enabling this will test if any test introduces new properties on the " +
- "`window` object. Stored as query-strings."
+ "global object (`window` in Browsers). Stored as query-strings."
},
{
id: "notrycatch",
@@ -144,6 +294,9 @@ config = {
// Set of all modules.
modules: [],
+ // Stack of nested modules
+ moduleStack: [],
+
// The first unnamed module
currentModule: {
name: "",
@@ -153,128 +306,230 @@ config = {
callbacks: {}
};
+var urlParams = defined.document ? getUrlParams() : {};
+
// Push a loose unnamed module to the modules collection
config.modules.push( config.currentModule );
-// Initialize more QUnit.config and QUnit.urlParams
-(function() {
- var i, current,
- location = window.location || { search: "", protocol: "file:" },
- params = location.search.slice( 1 ).split( "&" ),
- length = params.length,
- urlParams = {};
+if ( urlParams.filter === true ) {
+ delete urlParams.filter;
+}
- if ( params[ 0 ] ) {
- for ( i = 0; i < length; i++ ) {
- current = params[ i ].split( "=" );
- current[ 0 ] = decodeURIComponent( current[ 0 ] );
+// String search anywhere in moduleName+testName
+config.filter = urlParams.filter;
- // allow just a key to turn on a flag, e.g., test.html?noglobals
- current[ 1 ] = current[ 1 ] ? decodeURIComponent( current[ 1 ] ) : true;
- if ( urlParams[ current[ 0 ] ] ) {
- urlParams[ current[ 0 ] ] = [].concat( urlParams[ current[ 0 ] ], current[ 1 ] );
- } else {
- urlParams[ current[ 0 ] ] = current[ 1 ];
- }
- }
+config.testId = [];
+if ( urlParams.testId ) {
+ // Ensure that urlParams.testId is an array
+ urlParams.testId = decodeURIComponent( urlParams.testId ).split( "," );
+ for (var i = 0; i < urlParams.testId.length; i++ ) {
+ config.testId.push( urlParams.testId[ i ] );
}
+}
- if ( urlParams.filter === true ) {
- delete urlParams.filter;
- }
+var loggingCallbacks = {};
- QUnit.urlParams = urlParams;
+// Register logging callbacks
+function registerLoggingCallbacks( obj ) {
+ var i, l, key,
+ callbackNames = [ "begin", "done", "log", "testStart", "testDone",
+ "moduleStart", "moduleDone" ];
- // String search anywhere in moduleName+testName
- config.filter = urlParams.filter;
+ function registerLoggingCallback( key ) {
+ var loggingCallback = function( callback ) {
+ if ( objectType( callback ) !== "function" ) {
+ throw new Error(
+ "QUnit logging methods require a callback function as their first parameters."
+ );
+ }
- if ( urlParams.maxDepth ) {
- config.maxDepth = parseInt( urlParams.maxDepth, 10 ) === -1 ?
- Number.POSITIVE_INFINITY :
- urlParams.maxDepth;
- }
+ config.callbacks[ key ].push( callback );
+ };
- config.testId = [];
- if ( urlParams.testId ) {
+ // DEPRECATED: This will be removed on QUnit 2.0.0+
+ // Stores the registered functions allowing restoring
+ // at verifyLoggingCallbacks() if modified
+ loggingCallbacks[ key ] = loggingCallback;
- // Ensure that urlParams.testId is an array
- urlParams.testId = decodeURIComponent( urlParams.testId ).split( "," );
- for ( i = 0; i < urlParams.testId.length; i++ ) {
- config.testId.push( urlParams.testId[ i ] );
- }
+ return loggingCallback;
}
- // Figure out if we're running the tests from a server or not
- QUnit.isLocal = location.protocol === "file:";
-
- // Expose the current QUnit version
- QUnit.version = "1.18.1-pre";
-}());
-
-// Root QUnit object.
-// `QUnit` initialized at top of scope
-extend( QUnit, {
-
- // call on start of module test to prepend name to all tests
- module: function( name, testEnvironment ) {
- var currentModule = {
- name: name,
- testEnvironment: testEnvironment,
- tests: []
- };
+ for ( i = 0, l = callbackNames.length; i < l; i++ ) {
+ key = callbackNames[ i ];
- // DEPRECATED: handles setup/teardown functions,
- // beforeEach and afterEach should be used instead
- if ( testEnvironment && testEnvironment.setup ) {
- testEnvironment.beforeEach = testEnvironment.setup;
- delete testEnvironment.setup;
- }
- if ( testEnvironment && testEnvironment.teardown ) {
- testEnvironment.afterEach = testEnvironment.teardown;
- delete testEnvironment.teardown;
+ // Initialize key collection of logging callback
+ if ( objectType( config.callbacks[ key ] ) === "undefined" ) {
+ config.callbacks[ key ] = [];
}
- config.modules.push( currentModule );
- config.currentModule = currentModule;
- },
+ obj[ key ] = registerLoggingCallback( key );
+ }
+}
- // DEPRECATED: QUnit.asyncTest() will be removed in QUnit 2.0.
- asyncTest: function( testName, expected, callback ) {
- if ( arguments.length === 2 ) {
- callback = expected;
- expected = null;
- }
+function runLoggingCallbacks( key, args ) {
+ var i, l, callbacks;
- QUnit.test( testName, expected, callback, true );
- },
+ callbacks = config.callbacks[ key ];
+ for ( i = 0, l = callbacks.length; i < l; i++ ) {
+ callbacks[ i ]( args );
+ }
+}
- test: function( testName, expected, callback, async ) {
- var test;
+// DEPRECATED: This will be removed on 2.0.0+
+// This function verifies if the loggingCallbacks were modified by the user
+// If so, it will restore it, assign the given callback and print a console warning
+function verifyLoggingCallbacks() {
+ var loggingCallback, userCallback;
- if ( arguments.length === 2 ) {
- callback = expected;
- expected = null;
- }
+ for ( loggingCallback in loggingCallbacks ) {
+ if ( QUnit[ loggingCallback ] !== loggingCallbacks[ loggingCallback ] ) {
- test = new Test({
- testName: testName,
- expected: expected,
- async: async,
- callback: callback
- });
+ userCallback = QUnit[ loggingCallback ];
- test.queue();
- },
+ // Restore the callback function
+ QUnit[ loggingCallback ] = loggingCallbacks[ loggingCallback ];
- skip: function( testName ) {
- var test = new Test({
- testName: testName,
- skip: true
- });
+ // Assign the deprecated given callback
+ QUnit[ loggingCallback ]( userCallback );
+
+ if ( global.console && global.console.warn ) {
+ global.console.warn(
+ "QUnit." + loggingCallback + " was replaced with a new value.\n" +
+ "Please, check out the documentation on how to apply logging callbacks.\n" +
+ "Reference: http://api.qunitjs.com/category/callbacks/"
+ );
+ }
+ }
+ }
+}
+
+( function() {
+ if ( !defined.document ) {
+ return;
+ }
+
+ // `onErrorFnPrev` initialized at top of scope
+ // Preserve other handlers
+ var onErrorFnPrev = window.onerror;
+
+ // Cover uncaught exceptions
+ // Returning true will suppress the default browser handler,
+ // returning false will let it run.
+ window.onerror = function( error, filePath, linerNr ) {
+ var ret = false;
+ if ( onErrorFnPrev ) {
+ ret = onErrorFnPrev( error, filePath, linerNr );
+ }
+
+ // Treat return value as window.onerror itself does,
+ // Only do our handling if not suppressed.
+ if ( ret !== true ) {
+ if ( QUnit.config.current ) {
+ if ( QUnit.config.current.ignoreGlobalErrors ) {
+ return true;
+ }
+ QUnit.pushFailure( error, filePath + ":" + linerNr );
+ } else {
+ QUnit.test( "global failure", extend(function() {
+ QUnit.pushFailure( error, filePath + ":" + linerNr );
+ }, { validTest: true } ) );
+ }
+ return false;
+ }
+
+ return ret;
+ };
+} )();
+
+QUnit.urlParams = urlParams;
+
+// Figure out if we're running the tests from a server or not
+QUnit.isLocal = !( defined.document && window.location.protocol !== "file:" );
+
+// Expose the current QUnit version
+QUnit.version = "1.20.0";
+
+extend( QUnit, {
+
+ // call on start of module test to prepend name to all tests
+ module: function( name, testEnvironment, executeNow ) {
+ var module, moduleFns;
+ var currentModule = config.currentModule;
+
+ if ( arguments.length === 2 ) {
+ if ( testEnvironment instanceof Function ) {
+ executeNow = testEnvironment;
+ testEnvironment = undefined;
+ }
+ }
+
+ // DEPRECATED: handles setup/teardown functions,
+ // beforeEach and afterEach should be used instead
+ if ( testEnvironment && testEnvironment.setup ) {
+ testEnvironment.beforeEach = testEnvironment.setup;
+ delete testEnvironment.setup;
+ }
+ if ( testEnvironment && testEnvironment.teardown ) {
+ testEnvironment.afterEach = testEnvironment.teardown;
+ delete testEnvironment.teardown;
+ }
+
+ module = createModule();
+
+ moduleFns = {
+ beforeEach: setHook( module, "beforeEach" ),
+ afterEach: setHook( module, "afterEach" )
+ };
+
+ if ( executeNow instanceof Function ) {
+ config.moduleStack.push( module );
+ setCurrentModule( module );
+ executeNow.call( module.testEnvironment, moduleFns );
+ config.moduleStack.pop();
+ module = module.parentModule || currentModule;
+ }
+
+ setCurrentModule( module );
+
+ function createModule() {
+ var parentModule = config.moduleStack.length ?
+ config.moduleStack.slice( -1 )[ 0 ] : null;
+ var moduleName = parentModule !== null ?
+ [ parentModule.name, name ].join( " > " ) : name;
+ var module = {
+ name: moduleName,
+ parentModule: parentModule,
+ tests: []
+ };
+
+ var env = {};
+ if ( parentModule ) {
+ extend( env, parentModule.testEnvironment );
+ delete env.beforeEach;
+ delete env.afterEach;
+ }
+ extend( env, testEnvironment );
+ module.testEnvironment = env;
+
+ config.modules.push( module );
+ return module;
+ }
+
+ function setCurrentModule( module ) {
+ config.currentModule = module;
+ }
- test.queue();
},
+ // DEPRECATED: QUnit.asyncTest() will be removed in QUnit 2.0.
+ asyncTest: asyncTest,
+
+ test: test,
+
+ skip: skip,
+
+ only: only,
+
// DEPRECATED: The functionality of QUnit.start() will be altered in QUnit 2.0.
// In QUnit 2.0, invoking it will ONLY affect the `QUnit.config.autostart` blocking behavior.
start: function( count ) {
@@ -301,6 +556,17 @@ extend( QUnit, {
// If a test is running, adjust its semaphore
config.current.semaphore -= count || 1;
+ // If semaphore is non-numeric, throw error
+ if ( isNaN( config.current.semaphore ) ) {
+ config.current.semaphore = 0;
+
+ QUnit.pushFailure(
+ "Called start() with a non-numeric decrement.",
+ sourceFromStacktrace( 2 )
+ );
+ return;
+ }
+
// Don't start until equal number of stop-calls
if ( config.current.semaphore > 0 ) {
return;
@@ -337,43 +603,9 @@ extend( QUnit, {
config: config,
- // Safe object type checking
- is: function( type, obj ) {
- return QUnit.objectType( obj ) === type;
- },
-
- objectType: function( obj ) {
- if ( typeof obj === "undefined" ) {
- return "undefined";
- }
-
- // Consider: typeof null === object
- if ( obj === null ) {
- return "null";
- }
-
- var match = toString.call( obj ).match( /^\[object\s(.*)\]$/ ),
- type = match && match[ 1 ] || "";
+ is: is,
- switch ( type ) {
- case "Number":
- if ( isNaN( obj ) ) {
- return "nan";
- }
- return "number";
- case "String":
- case "Boolean":
- case "Array":
- case "Date":
- case "RegExp":
- case "Function":
- return type.toLowerCase();
- }
- if ( typeof obj === "object" ) {
- return "object";
- }
- return undefined;
- },
+ objectType: objectType,
extend: extend,
@@ -403,199 +635,7 @@ extend( QUnit, {
}
});
-// Register logging callbacks
-(function() {
- var i, l, key,
- callbacks = [ "begin", "done", "log", "testStart", "testDone",
- "moduleStart", "moduleDone" ];
-
- function registerLoggingCallback( key ) {
- var loggingCallback = function( callback ) {
- if ( QUnit.objectType( callback ) !== "function" ) {
- throw new Error(
- "QUnit logging methods require a callback function as their first parameters."
- );
- }
-
- config.callbacks[ key ].push( callback );
- };
-
- // DEPRECATED: This will be removed on QUnit 2.0.0+
- // Stores the registered functions allowing restoring
- // at verifyLoggingCallbacks() if modified
- loggingCallbacks[ key ] = loggingCallback;
-
- return loggingCallback;
- }
-
- for ( i = 0, l = callbacks.length; i < l; i++ ) {
- key = callbacks[ i ];
-
- // Initialize key collection of logging callback
- if ( QUnit.objectType( config.callbacks[ key ] ) === "undefined" ) {
- config.callbacks[ key ] = [];
- }
-
- QUnit[ key ] = registerLoggingCallback( key );
- }
-})();
-
-// `onErrorFnPrev` initialized at top of scope
-// Preserve other handlers
-onErrorFnPrev = window.onerror;
-
-// Cover uncaught exceptions
-// Returning true will suppress the default browser handler,
-// returning false will let it run.
-window.onerror = function( error, filePath, linerNr ) {
- var ret = false;
- if ( onErrorFnPrev ) {
- ret = onErrorFnPrev( error, filePath, linerNr );
- }
-
- // Treat return value as window.onerror itself does,
- // Only do our handling if not suppressed.
- if ( ret !== true ) {
- if ( QUnit.config.current ) {
- if ( QUnit.config.current.ignoreGlobalErrors ) {
- return true;
- }
- QUnit.pushFailure( error, filePath + ":" + linerNr );
- } else {
- QUnit.test( "global failure", extend(function() {
- QUnit.pushFailure( error, filePath + ":" + linerNr );
- }, { validTest: true } ) );
- }
- return false;
- }
-
- return ret;
-};
-
-function done() {
- var runtime, passed;
-
- config.autorun = true;
-
- // Log the last module results
- if ( config.previousModule ) {
- runLoggingCallbacks( "moduleDone", {
- name: config.previousModule.name,
- tests: config.previousModule.tests,
- failed: config.moduleStats.bad,
- passed: config.moduleStats.all - config.moduleStats.bad,
- total: config.moduleStats.all,
- runtime: now() - config.moduleStats.started
- });
- }
- delete config.previousModule;
-
- runtime = now() - config.started;
- passed = config.stats.all - config.stats.bad;
-
- runLoggingCallbacks( "done", {
- failed: config.stats.bad,
- passed: passed,
- total: config.stats.all,
- runtime: runtime
- });
-}
-
-// Doesn't support IE6 to IE9, it will return undefined on these browsers
-// See also https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Error/Stack
-function extractStacktrace( e, offset ) {
- offset = offset === undefined ? 4 : offset;
-
- var stack, include, i;
-
- if ( e.stack ) {
- stack = e.stack.split( "\n" );
- if ( /^error$/i.test( stack[ 0 ] ) ) {
- stack.shift();
- }
- if ( fileName ) {
- include = [];
- for ( i = offset; i < stack.length; i++ ) {
- if ( stack[ i ].indexOf( fileName ) !== -1 ) {
- break;
- }
- include.push( stack[ i ] );
- }
- if ( include.length ) {
- return include.join( "\n" );
- }
- }
- return stack[ offset ];
-
- // Support: Safari <=6 only
- } else if ( e.sourceURL ) {
-
- // exclude useless self-reference for generated Error objects
- if ( /qunit.js$/.test( e.sourceURL ) ) {
- return;
- }
-
- // for actual exceptions, this is useful
- return e.sourceURL + ":" + e.line;
- }
-}
-
-function sourceFromStacktrace( offset ) {
- var error = new Error();
-
- // Support: Safari <=7 only, IE <=10 - 11 only
- // Not all browsers generate the `stack` property for `new Error()`, see also #636
- if ( !error.stack ) {
- try {
- throw error;
- } catch ( err ) {
- error = err;
- }
- }
-
- return extractStacktrace( error, offset );
-}
-
-function synchronize( callback, last ) {
- if ( QUnit.objectType( callback ) === "array" ) {
- while ( callback.length ) {
- synchronize( callback.shift() );
- }
- return;
- }
- config.queue.push( callback );
-
- if ( config.autorun && !config.blocking ) {
- process( last );
- }
-}
-
-function process( last ) {
- function next() {
- process( last );
- }
- var start = now();
- config.depth = ( config.depth || 0 ) + 1;
-
- while ( config.queue.length && !config.blocking ) {
- if ( !defined.setTimeout || config.updateRate <= 0 ||
- ( ( now() - start ) < config.updateRate ) ) {
- if ( config.current ) {
-
- // Reset async tracking for each phase of the Test lifecycle
- config.current.usedAsync = false;
- }
- config.queue.shift()();
- } else {
- setTimeout( next, 13 );
- break;
- }
- }
- config.depth--;
- if ( last && !config.blocking && !config.queue.length && config.depth === 0 ) {
- done();
- }
-}
+registerLoggingCallbacks( QUnit );
function begin() {
var i, l,
@@ -633,23 +673,30 @@ function begin() {
process( true );
}
-function resumeProcessing() {
- runStarted = true;
+function process( last ) {
+ function next() {
+ process( last );
+ }
+ var start = now();
+ config.depth = ( config.depth || 0 ) + 1;
- // A slight delay to allow this iteration of the event loop to finish (more assertions, etc.)
- if ( defined.setTimeout ) {
- setTimeout(function() {
- if ( config.current && config.current.semaphore > 0 ) {
- return;
- }
- if ( config.timeout ) {
- clearTimeout( config.timeout );
- }
+ while ( config.queue.length && !config.blocking ) {
+ if ( !defined.setTimeout || config.updateRate <= 0 ||
+ ( ( now() - start ) < config.updateRate ) ) {
+ if ( config.current ) {
- begin();
- }, 13 );
- } else {
- begin();
+ // Reset async tracking for each phase of the Test lifecycle
+ config.current.usedAsync = false;
+ }
+ config.queue.shift()();
+ } else {
+ setTimeout( next, 13 );
+ break;
+ }
+ }
+ config.depth--;
+ if ( last && !config.blocking && !config.queue.length && config.depth === 0 ) {
+ done();
}
}
@@ -670,127 +717,67 @@ function pauseProcessing() {
}
}
-function saveGlobal() {
- config.pollution = [];
-
- if ( config.noglobals ) {
- for ( var key in window ) {
- if ( hasOwn.call( window, key ) ) {
- // in Opera sometimes DOM element ids show up here, ignore them
- if ( /^qunit-test-output/.test( key ) ) {
- continue;
- }
- config.pollution.push( key );
- }
- }
- }
-}
-
-function checkPollution() {
- var newGlobals,
- deletedGlobals,
- old = config.pollution;
-
- saveGlobal();
-
- newGlobals = diff( config.pollution, old );
- if ( newGlobals.length > 0 ) {
- QUnit.pushFailure( "Introduced global variable(s): " + newGlobals.join( ", " ) );
- }
-
- deletedGlobals = diff( old, config.pollution );
- if ( deletedGlobals.length > 0 ) {
- QUnit.pushFailure( "Deleted global variable(s): " + deletedGlobals.join( ", " ) );
- }
-}
-
-// returns a new Array with the elements that are in a but not in b
-function diff( a, b ) {
- var i, j,
- result = a.slice();
+function resumeProcessing() {
+ runStarted = true;
- for ( i = 0; i < result.length; i++ ) {
- for ( j = 0; j < b.length; j++ ) {
- if ( result[ i ] === b[ j ] ) {
- result.splice( i, 1 );
- i--;
- break;
+ // A slight delay to allow this iteration of the event loop to finish (more assertions, etc.)
+ if ( defined.setTimeout ) {
+ setTimeout(function() {
+ if ( config.current && config.current.semaphore > 0 ) {
+ return;
}
- }
- }
- return result;
-}
-
-function extend( a, b, undefOnly ) {
- for ( var prop in b ) {
- if ( hasOwn.call( b, prop ) ) {
-
- // Avoid "Member not found" error in IE8 caused by messing with window.constructor
- if ( !( prop === "constructor" && a === window ) ) {
- if ( b[ prop ] === undefined ) {
- delete a[ prop ];
- } else if ( !( undefOnly && typeof a[ prop ] !== "undefined" ) ) {
- a[ prop ] = b[ prop ];
- }
+ if ( config.timeout ) {
+ clearTimeout( config.timeout );
}
- }
- }
-
- return a;
-}
-
-function runLoggingCallbacks( key, args ) {
- var i, l, callbacks;
-
- callbacks = config.callbacks[ key ];
- for ( i = 0, l = callbacks.length; i < l; i++ ) {
- callbacks[ i ]( args );
- }
-}
-// DEPRECATED: This will be removed on 2.0.0+
-// This function verifies if the loggingCallbacks were modified by the user
-// If so, it will restore it, assign the given callback and print a console warning
-function verifyLoggingCallbacks() {
- var loggingCallback, userCallback;
-
- for ( loggingCallback in loggingCallbacks ) {
- if ( QUnit[ loggingCallback ] !== loggingCallbacks[ loggingCallback ] ) {
-
- userCallback = QUnit[ loggingCallback ];
-
- // Restore the callback function
- QUnit[ loggingCallback ] = loggingCallbacks[ loggingCallback ];
-
- // Assign the deprecated given callback
- QUnit[ loggingCallback ]( userCallback );
-
- if ( window.console && window.console.warn ) {
- window.console.warn(
- "QUnit." + loggingCallback + " was replaced with a new value.\n" +
- "Please, check out the documentation on how to apply logging callbacks.\n" +
- "Reference: http://api.qunitjs.com/category/callbacks/"
- );
- }
- }
+ begin();
+ }, 13 );
+ } else {
+ begin();
}
}
-// from jquery.js
-function inArray( elem, array ) {
- if ( array.indexOf ) {
- return array.indexOf( elem );
+function done() {
+ var runtime, passed;
+
+ config.autorun = true;
+
+ // Log the last module results
+ if ( config.previousModule ) {
+ runLoggingCallbacks( "moduleDone", {
+ name: config.previousModule.name,
+ tests: config.previousModule.tests,
+ failed: config.moduleStats.bad,
+ passed: config.moduleStats.all - config.moduleStats.bad,
+ total: config.moduleStats.all,
+ runtime: now() - config.moduleStats.started
+ });
}
+ delete config.previousModule;
- for ( var i = 0, length = array.length; i < length; i++ ) {
- if ( array[ i ] === elem ) {
- return i;
- }
+ runtime = now() - config.started;
+ passed = config.stats.all - config.stats.bad;
+
+ runLoggingCallbacks( "done", {
+ failed: config.stats.bad,
+ passed: passed,
+ total: config.stats.all,
+ runtime: runtime
+ });
+}
+
+function setHook( module, hookName ) {
+ if ( module.testEnvironment === undefined ) {
+ module.testEnvironment = {};
}
- return -1;
+ return function( callback ) {
+ module.testEnvironment[ hookName ] = callback;
+ };
}
+var focused = false;
+
function Test( settings ) {
var i, l;
@@ -863,9 +850,11 @@ Test.prototype = {
config.current = this;
+ if ( this.module.testEnvironment ) {
+ delete this.module.testEnvironment.beforeEach;
+ delete this.module.testEnvironment.afterEach;
+ }
this.testEnvironment = extend( {}, this.module.testEnvironment );
- delete this.testEnvironment.beforeEach;
- delete this.testEnvironment.afterEach;
this.started = now();
runLoggingCallbacks( "testStart", {
@@ -891,14 +880,12 @@ Test.prototype = {
this.callbackStarted = now();
if ( config.notrycatch ) {
- promise = this.callback.call( this.testEnvironment, this.assert );
- this.resolvePromise( promise );
+ runTest( this );
return;
}
try {
- promise = this.callback.call( this.testEnvironment, this.assert );
- this.resolvePromise( promise );
+ runTest( this );
} catch ( e ) {
this.pushFailure( "Died on test #" + ( this.assertions.length + 1 ) + " " +
this.stack + ": " + ( e.message || e ), extractStacktrace( e, 0 ) );
@@ -911,6 +898,11 @@ Test.prototype = {
QUnit.start();
}
}
+
+ function runTest( test ) {
+ promise = test.callback.call( test.testEnvironment, test.assert );
+ test.resolvePromise( promise );
+ }
},
after: function() {
@@ -923,16 +915,19 @@ Test.prototype = {
return function runHook() {
config.current = test;
if ( config.notrycatch ) {
- promise = hook.call( test.testEnvironment, test.assert );
- test.resolvePromise( promise, hookName );
+ callHook();
return;
}
try {
- promise = hook.call( test.testEnvironment, test.assert );
- test.resolvePromise( promise, hookName );
+ callHook();
} catch ( error ) {
test.pushFailure( hookName + " failed on " + test.testName + ": " +
- ( error.message || error ), extractStacktrace( error, 0 ) );
+ ( error.message || error ), extractStacktrace( error, 0 ) );
+ }
+
+ function callHook() {
+ promise = hook.call( test.testEnvironment, test.assert );
+ test.resolvePromise( promise, hookName );
}
};
},
@@ -941,16 +936,20 @@ Test.prototype = {
hooks: function( handler ) {
var hooks = [];
- // Hooks are ignored on skipped tests
- if ( this.skip ) {
- return hooks;
+ function processHooks( test, module ) {
+ if ( module.parentModule ) {
+ processHooks( test, module.parentModule );
+ }
+ if ( module.testEnvironment &&
+ QUnit.objectType( module.testEnvironment[ handler ] ) === "function" ) {
+ hooks.push( test.queueHook( module.testEnvironment[ handler ], handler ) );
+ }
}
- if ( this.module.testEnvironment &&
- QUnit.objectType( this.module.testEnvironment[ handler ] ) === "function" ) {
- hooks.push( this.queueHook( this.module.testEnvironment[ handler ], handler ) );
+ // Hooks are ignored on skipped tests
+ if ( !this.skip ) {
+ processHooks( this, this.module );
}
-
return hooks;
},
@@ -1011,7 +1010,7 @@ Test.prototype = {
},
queue: function() {
- var bad,
+ var priority,
test = this;
if ( !this.valid() ) {
@@ -1027,7 +1026,6 @@ Test.prototype = {
},
test.hooks( "beforeEach" ),
-
function() {
test.run();
},
@@ -1043,16 +1041,11 @@ Test.prototype = {
]);
}
- // `bad` initialized at top of scope
- // defer when previous test run passed, if storage is available
- bad = QUnit.config.reorder && defined.sessionStorage &&
+ // Prioritize previously failed tests, detected from sessionStorage
+ priority = QUnit.config.reorder && defined.sessionStorage &&
+sessionStorage.getItem( "qunit-test-" + this.module.name + "-" + this.testName );
- if ( bad ) {
- run();
- } else {
- synchronize( run, true );
- }
+ return synchronize( run, priority );
},
push: function( result, actual, expected, message, negative ) {
@@ -1086,7 +1079,7 @@ Test.prototype = {
},
pushFailure: function( message, source, actual ) {
- if ( !this instanceof Test ) {
+ if ( !( this instanceof Test ) ) {
throw new Error( "pushFailure() assertion outside test context, was " +
sourceFromStacktrace( 2 ) );
}
@@ -1122,7 +1115,7 @@ Test.prototype = {
QUnit.stop();
then.call(
promise,
- QUnit.start,
+ function() { QUnit.start(); },
function( error ) {
message = "Promise rejected " +
( !phase ? "during" : phase.replace( /Each$/, "" ) ) +
@@ -1146,6 +1139,17 @@ Test.prototype = {
module = QUnit.urlParams.module && QUnit.urlParams.module.toLowerCase(),
fullName = ( this.module.name + ": " + this.testName ).toLowerCase();
+ function testInModuleChain( testModule ) {
+ var testModuleName = testModule.name ? testModule.name.toLowerCase() : null;
+ if ( testModuleName === module ) {
+ return true;
+ } else if ( testModule.parentModule ) {
+ return testInModuleChain( testModule.parentModule );
+ } else {
+ return false;
+ }
+ }
+
// Internally-generated tests are always valid
if ( this.callback && this.callback.validTest ) {
return true;
@@ -1155,7 +1159,7 @@ Test.prototype = {
return false;
}
- if ( module && ( !this.module.name || this.module.name.toLowerCase() !== module ) ) {
+ if ( module && !testInModuleChain( this.module ) ) {
return false;
}
@@ -1176,7 +1180,6 @@ Test.prototype = {
// Otherwise, do the opposite
return !include;
}
-
};
// Resets the test setup. Useful for tests that modify the DOM.
@@ -1189,7 +1192,7 @@ QUnit.reset = function() {
// Return on non-browser environments
// This is necessary to not break on node tests
- if ( typeof window === "undefined" ) {
+ if ( !defined.document ) {
return;
}
@@ -1237,6 +1240,145 @@ function generateHash( module, testName ) {
return hex.slice( -8 );
}
+function synchronize( callback, priority ) {
+ var last = !priority;
+
+ if ( QUnit.objectType( callback ) === "array" ) {
+ while ( callback.length ) {
+ synchronize( callback.shift() );
+ }
+ return;
+ }
+
+ if ( priority ) {
+ priorityFill( callback );
+ } else {
+ config.queue.push( callback );
+ }
+
+ if ( config.autorun && !config.blocking ) {
+ process( last );
+ }
+}
+
+// Place previously failed tests on a queue priority line, respecting the order they get assigned.
+function priorityFill( callback ) {
+ var queue, prioritizedQueue;
+
+ queue = config.queue.slice( priorityFill.pos );
+ prioritizedQueue = config.queue.slice( 0, -config.queue.length + priorityFill.pos );
+
+ queue.unshift( callback );
+ queue.unshift.apply( queue, prioritizedQueue );
+
+ config.queue = queue;
+
+ priorityFill.pos += 1;
+}
+priorityFill.pos = 0;
+
+function saveGlobal() {
+ config.pollution = [];
+
+ if ( config.noglobals ) {
+ for ( var key in global ) {
+ if ( hasOwn.call( global, key ) ) {
+
+ // in Opera sometimes DOM element ids show up here, ignore them
+ if ( /^qunit-test-output/.test( key ) ) {
+ continue;
+ }
+ config.pollution.push( key );
+ }
+ }
+ }
+}
+
+function checkPollution() {
+ var newGlobals,
+ deletedGlobals,
+ old = config.pollution;
+
+ saveGlobal();
+
+ newGlobals = diff( config.pollution, old );
+ if ( newGlobals.length > 0 ) {
+ QUnit.pushFailure( "Introduced global variable(s): " + newGlobals.join( ", " ) );
+ }
+
+ deletedGlobals = diff( old, config.pollution );
+ if ( deletedGlobals.length > 0 ) {
+ QUnit.pushFailure( "Deleted global variable(s): " + deletedGlobals.join( ", " ) );
+ }
+}
+
+// Will be exposed as QUnit.asyncTest
+function asyncTest( testName, expected, callback ) {
+ if ( arguments.length === 2 ) {
+ callback = expected;
+ expected = null;
+ }
+
+ QUnit.test( testName, expected, callback, true );
+}
+
+// Will be exposed as QUnit.test
+function test( testName, expected, callback, async ) {
+ if ( focused ) { return; }
+
+ var newTest;
+
+ if ( arguments.length === 2 ) {
+ callback = expected;
+ expected = null;
+ }
+
+ newTest = new Test({
+ testName: testName,
+ expected: expected,
+ async: async,
+ callback: callback
+ });
+
+ newTest.queue();
+}
+
+// Will be exposed as QUnit.skip
+function skip( testName ) {
+ if ( focused ) { return; }
+
+ var test = new Test({
+ testName: testName,
+ skip: true
+ });
+
+ test.queue();
+}
+
+// Will be exposed as QUnit.only
+function only( testName, expected, callback, async ) {
+ var newTest;
+
+ if ( focused ) { return; }
+
+ QUnit.config.queue.length = 0;
+ focused = true;
+
+ if ( arguments.length === 2 ) {
+ callback = expected;
+ expected = null;
+ }
+
+ newTest = new Test({
+ testName: testName,
+ expected: expected,
+ async: async,
+ callback: callback
+ });
+
+ newTest.queue();
+}
+
function Assert( testContext ) {
this.test = testContext;
}
@@ -1254,25 +1396,36 @@ QUnit.assert = Assert.prototype = {
}
},
- // Increment this Test's semaphore counter, then return a single-use function that
+ // Increment this Test's semaphore counter, then return a function that
// decrements that counter a maximum of once.
- async: function() {
+ async: function( count ) {
var test = this.test,
- popped = false;
+ popped = false,
+ acceptCallCount = count;
+
+ if ( typeof acceptCallCount === "undefined" ) {
+ acceptCallCount = 1;
+ }
test.semaphore += 1;
test.usedAsync = true;
pauseProcessing();
return function done() {
- if ( !popped ) {
- test.semaphore -= 1;
- popped = true;
- resumeProcessing();
- } else {
- test.pushFailure( "Called the callback returned from `assert.async` more than once",
+
+ if ( popped ) {
+ test.pushFailure( "Too many calls to the `assert.async` callback",
sourceFromStacktrace( 2 ) );
+ return;
}
+ acceptCallCount -= 1;
+ if ( acceptCallCount > 0 ) {
+ return;
+ }
+
+ test.semaphore -= 1;
+ popped = true;
+ resumeProcessing();
};
},
@@ -1410,229 +1563,305 @@ QUnit.assert = Assert.prototype = {
}
};
-// Provide an alternative to assert.throws(), for enviroments that consider throws a reserved word
+// Provide an alternative to assert.throws(), for environments that consider throws a reserved word
// Known to us are: Closure Compiler, Narwhal
(function() {
/*jshint sub:true */
Assert.prototype.raises = Assert.prototype[ "throws" ];
}());
+function errorString( error ) {
+ var name, message,
+ resultErrorString = error.toString();
+ if ( resultErrorString.substring( 0, 7 ) === "[object" ) {
+ name = error.name ? error.name.toString() : "Error";
+ message = error.message ? error.message.toString() : "";
+ if ( name && message ) {
+ return name + ": " + message;
+ } else if ( name ) {
+ return name;
+ } else if ( message ) {
+ return message;
+ } else {
+ return "Error";
+ }
+ } else {
+ return resultErrorString;
+ }
+}
+
// Test for equality any JavaScript type.
// Author: Philippe Rathé
QUnit.equiv = (function() {
- // Call the o related callback with the given arguments.
- function bindCallbacks( o, callbacks, args ) {
- var prop = QUnit.objectType( o );
- if ( prop ) {
- if ( QUnit.objectType( callbacks[ prop ] ) === "function" ) {
- return callbacks[ prop ].apply( callbacks, args );
- } else {
- return callbacks[ prop ]; // or undefined
- }
- }
- }
+ // Stack to decide between skip/abort functions
+ var callers = [];
+
+ // Stack to avoiding loops from circular referencing
+ var parents = [];
+ var parentsB = [];
+
+ function useStrictEquality( b, a ) {
- // the real equiv function
- var innerEquiv,
+ /*jshint eqeqeq:false */
+ if ( b instanceof a.constructor || a instanceof b.constructor ) {
- // stack to decide between skip/abort functions
- callers = [],
+ // To catch short annotation VS 'new' annotation of a declaration. e.g.:
+ // `var i = 1;`
+ // `var j = new Number(1);`
+ return a == b;
+ } else {
+ return a === b;
+ }
+ }
- // stack to avoiding loops from circular referencing
- parents = [],
- parentsB = [],
+ function compareConstructors( a, b ) {
+ var getProto = Object.getPrototypeOf || function( obj ) {
- getProto = Object.getPrototypeOf || function( obj ) {
- /* jshint camelcase: false, proto: true */
+ /*jshint proto: true */
return obj.__proto__;
- },
- callbacks = (function() {
+ };
+ var protoA = getProto( a );
+ var protoB = getProto( b );
- // for string, boolean, number and null
- function useStrictEquality( b, a ) {
+ // Comparing constructors is more strict than using `instanceof`
+ if ( a.constructor === b.constructor ) {
+ return true;
+ }
- /*jshint eqeqeq:false */
- if ( b instanceof a.constructor || a instanceof b.constructor ) {
+ // Ref #851
+ // If the obj prototype descends from a null constructor, treat it
+ // as a null prototype.
+ if ( protoA && protoA.constructor === null ) {
+ protoA = null;
+ }
+ if ( protoB && protoB.constructor === null ) {
+ protoB = null;
+ }
- // to catch short annotation VS 'new' annotation of a
- // declaration
- // e.g. var i = 1;
- // var j = new Number(1);
- return a == b;
- } else {
- return a === b;
- }
- }
+ // Allow objects with no prototype to be equivalent to
+ // objects with Object as their constructor.
+ if ( ( protoA === null && protoB === Object.prototype ) ||
+ ( protoB === null && protoA === Object.prototype ) ) {
+ return true;
+ }
- return {
- "string": useStrictEquality,
- "boolean": useStrictEquality,
- "number": useStrictEquality,
- "null": useStrictEquality,
- "undefined": useStrictEquality,
+ return false;
+ }
- "nan": function( b ) {
- return isNaN( b );
- },
+ var callbacks = {
+ "string": useStrictEquality,
+ "boolean": useStrictEquality,
+ "number": useStrictEquality,
+ "null": useStrictEquality,
+ "undefined": useStrictEquality,
+ "symbol": useStrictEquality,
- "date": function( b, a ) {
- return QUnit.objectType( b ) === "date" && a.valueOf() === b.valueOf();
- },
+ "nan": function( b ) {
+ return isNaN( b );
+ },
- "regexp": function( b, a ) {
- return QUnit.objectType( b ) === "regexp" &&
+ "date": function( b, a ) {
+ return QUnit.objectType( b ) === "date" && a.valueOf() === b.valueOf();
+ },
- // the regex itself
- a.source === b.source &&
+ "regexp": function( b, a ) {
+ return QUnit.objectType( b ) === "regexp" &&
- // and its modifiers
- a.global === b.global &&
+ // The regex itself
+ a.source === b.source &&
- // (gmi) ...
- a.ignoreCase === b.ignoreCase &&
- a.multiline === b.multiline &&
- a.sticky === b.sticky;
- },
+ // And its modifiers
+ a.global === b.global &&
- // - skip when the property is a method of an instance (OOP)
- // - abort otherwise,
- // initial === would have catch identical references anyway
- "function": function() {
- var caller = callers[ callers.length - 1 ];
- return caller !== Object && typeof caller !== "undefined";
- },
+ // (gmi) ...
+ a.ignoreCase === b.ignoreCase &&
+ a.multiline === b.multiline &&
+ a.sticky === b.sticky;
+ },
- "array": function( b, a ) {
- var i, j, len, loop, aCircular, bCircular;
+ // - skip when the property is a method of an instance (OOP)
+ // - abort otherwise,
+ // initial === would have catch identical references anyway
+ "function": function() {
+ var caller = callers[ callers.length - 1 ];
+ return caller !== Object && typeof caller !== "undefined";
+ },
- // b could be an object literal here
- if ( QUnit.objectType( b ) !== "array" ) {
- return false;
- }
+ "array": function( b, a ) {
+ var i, j, len, loop, aCircular, bCircular;
- len = a.length;
- if ( len !== b.length ) {
- // safe and faster
- return false;
- }
+ // b could be an object literal here
+ if ( QUnit.objectType( b ) !== "array" ) {
+ return false;
+ }
- // track reference to avoid circular references
- parents.push( a );
- parentsB.push( b );
- for ( i = 0; i < len; i++ ) {
- loop = false;
- for ( j = 0; j < parents.length; j++ ) {
- aCircular = parents[ j ] === a[ i ];
- bCircular = parentsB[ j ] === b[ i ];
- if ( aCircular || bCircular ) {
- if ( a[ i ] === b[ i ] || aCircular && bCircular ) {
- loop = true;
- } else {
- parents.pop();
- parentsB.pop();
- return false;
- }
- }
- }
- if ( !loop && !innerEquiv( a[ i ], b[ i ] ) ) {
+ len = a.length;
+ if ( len !== b.length ) {
+ // safe and faster
+ return false;
+ }
+
+ // Track reference to avoid circular references
+ parents.push( a );
+ parentsB.push( b );
+ for ( i = 0; i < len; i++ ) {
+ loop = false;
+ for ( j = 0; j < parents.length; j++ ) {
+ aCircular = parents[ j ] === a[ i ];
+ bCircular = parentsB[ j ] === b[ i ];
+ if ( aCircular || bCircular ) {
+ if ( a[ i ] === b[ i ] || aCircular && bCircular ) {
+ loop = true;
+ } else {
parents.pop();
parentsB.pop();
return false;
}
}
+ }
+ if ( !loop && !innerEquiv( a[ i ], b[ i ] ) ) {
parents.pop();
parentsB.pop();
- return true;
- },
+ return false;
+ }
+ }
+ parents.pop();
+ parentsB.pop();
+ return true;
+ },
+
+ "set": function( b, a ) {
+ var aArray, bArray;
- "object": function( b, a ) {
+ // `b` could be any object here
+ if ( QUnit.objectType( b ) !== "set" ) {
+ return false;
+ }
- /*jshint forin:false */
- var i, j, loop, aCircular, bCircular,
- // Default to true
- eq = true,
- aProperties = [],
- bProperties = [];
+ aArray = [];
+ a.forEach( function( v ) {
+ aArray.push( v );
+ });
+ bArray = [];
+ b.forEach( function( v ) {
+ bArray.push( v );
+ });
- // comparing constructors is more strict than using
- // instanceof
- if ( a.constructor !== b.constructor ) {
+ return innerEquiv( bArray, aArray );
+ },
- // Allow objects with no prototype to be equivalent to
- // objects with Object as their constructor.
- if ( !( ( getProto( a ) === null && getProto( b ) === Object.prototype ) ||
- ( getProto( b ) === null && getProto( a ) === Object.prototype ) ) ) {
- return false;
- }
- }
+ "map": function( b, a ) {
+ var aArray, bArray;
- // stack constructor before traversing properties
- callers.push( a.constructor );
-
- // track reference to avoid circular references
- parents.push( a );
- parentsB.push( b );
-
- // be strict: don't ensure hasOwnProperty and go deep
- for ( i in a ) {
- loop = false;
- for ( j = 0; j < parents.length; j++ ) {
- aCircular = parents[ j ] === a[ i ];
- bCircular = parentsB[ j ] === b[ i ];
- if ( aCircular || bCircular ) {
- if ( a[ i ] === b[ i ] || aCircular && bCircular ) {
- loop = true;
- } else {
- eq = false;
- break;
- }
- }
- }
- aProperties.push( i );
- if ( !loop && !innerEquiv( a[ i ], b[ i ] ) ) {
+ // `b` could be any object here
+ if ( QUnit.objectType( b ) !== "map" ) {
+ return false;
+ }
+
+ aArray = [];
+ a.forEach( function( v, k ) {
+ aArray.push( [ k, v ] );
+ });
+ bArray = [];
+ b.forEach( function( v, k ) {
+ bArray.push( [ k, v ] );
+ });
+
+ return innerEquiv( bArray, aArray );
+ },
+
+ "object": function( b, a ) {
+ var i, j, loop, aCircular, bCircular;
+
+ // Default to true
+ var eq = true;
+ var aProperties = [];
+ var bProperties = [];
+
+ if ( compareConstructors( a, b ) === false ) {
+ return false;
+ }
+
+ // Stack constructor before traversing properties
+ callers.push( a.constructor );
+
+ // Track reference to avoid circular references
+ parents.push( a );
+ parentsB.push( b );
+
+ // Be strict: don't ensure hasOwnProperty and go deep
+ for ( i in a ) {
+ loop = false;
+ for ( j = 0; j < parents.length; j++ ) {
+ aCircular = parents[ j ] === a[ i ];
+ bCircular = parentsB[ j ] === b[ i ];
+ if ( aCircular || bCircular ) {
+ if ( a[ i ] === b[ i ] || aCircular && bCircular ) {
+ loop = true;
+ } else {
eq = false;
break;
}
}
+ }
+ aProperties.push( i );
+ if ( !loop && !innerEquiv( a[ i ], b[ i ] ) ) {
+ eq = false;
+ break;
+ }
+ }
- parents.pop();
- parentsB.pop();
- callers.pop(); // unstack, we are done
+ parents.pop();
+ parentsB.pop();
- for ( i in b ) {
- bProperties.push( i ); // collect b's properties
- }
+ // Unstack, we are done
+ callers.pop();
- // Ensures identical properties name
- return eq && innerEquiv( aProperties.sort(), bProperties.sort() );
- }
- };
- }());
+ for ( i in b ) {
+
+ // Collect b's properties
+ bProperties.push( i );
+ }
- innerEquiv = function() { // can take multiple arguments
+ // Ensures identical properties name
+ return eq && innerEquiv( aProperties.sort(), bProperties.sort() );
+ }
+ };
+
+ function typeEquiv( a, b ) {
+ var prop = QUnit.objectType( a );
+ return callbacks[ prop ]( b, a );
+ }
+
+ // The real equiv function
+ function innerEquiv() {
var args = [].slice.apply( arguments );
if ( args.length < 2 ) {
- return true; // end transition
+
+ // End transition
+ return true;
}
return ( (function( a, b ) {
if ( a === b ) {
- return true; // catch the most you can
+
+ // Catch the most you can
+ return true;
} else if ( a === null || b === null || typeof a === "undefined" ||
typeof b === "undefined" ||
QUnit.objectType( a ) !== QUnit.objectType( b ) ) {
- // don't lose time with error prone cases
+ // Don't lose time with error prone cases
return false;
} else {
- return bindCallbacks( a, callbacks, [ b, a ] );
+ return typeEquiv( a, b );
}
- // apply transition with (1..n) arguments
+ // Apply transition with (1..n) arguments
}( args[ 0 ], args[ 1 ] ) ) &&
innerEquiv.apply( this, args.splice( 1, args.length - 1 ) ) );
- };
+ }
return innerEquiv;
}());
@@ -1902,7 +2131,7 @@ QUnit.dump = (function() {
QUnit.jsDump = QUnit.dump;
// For browser, export only select globals
-if ( typeof window !== "undefined" ) {
+if ( defined.document ) {
// Deprecated
// Extend assert methods to QUnit and Global scope through Backwards compatibility
@@ -1941,7 +2170,8 @@ if ( typeof window !== "undefined" ) {
"notDeepEqual",
"strictEqual",
"notStrictEqual",
- "throws"
+ "throws",
+ "raises"
];
for ( i = 0, l = keys.length; i < l; i++ ) {
@@ -1966,19 +2196,12 @@ if ( typeof exports !== "undefined" && exports ) {
}
if ( typeof define === "function" && define.amd ) {
- define( function() {
+ define('QUnit', function() {
return QUnit;
} );
QUnit.config.autostart = false;
}
-// Get a reference to the global object, like window in browsers
-}( (function() {
- return this;
-})() ));
-
-/*istanbul ignore next */
-// jscs:disable maximumLineLength
/*
* This file is a modified version of google-diff-match-patch's JavaScript implementation
* (https://code.google.com/p/google-diff-match-patch/source/browse/trunk/javascript/diff_match_patch_uncompressed.js),
@@ -2006,1067 +2229,1103 @@ if ( typeof define === "function" && define.amd ) {
*
* Usage: QUnit.diff(expected, actual)
*
- * QUnit.diff( "the quick brown fox jumped over", "the quick fox jumps over" ) === "the quick brown fox jumps ed} Array of diff tuples.
- */
- DiffMatchPatch.prototype.DiffMain = function( text1, text2, optChecklines, optDeadline ) {
- var deadline, checklines, commonlength,
+ /**
+ * Find the differences between two texts. Simplifies the problem by stripping
+ * any common prefix or suffix off the texts before diffing.
+ * @param {string} text1 Old string to be diffed.
+ * @param {string} text2 New string to be diffed.
+ * @param {boolean=} optChecklines Optional speedup flag. If present and false,
+ * then don't run a line-level diff first to identify the changed areas.
+ * Defaults to true, which does a faster, slightly less optimal diff.
+ * @return {!Array.} Array of diff tuples.
+ */
+ DiffMatchPatch.prototype.DiffMain = function( text1, text2, optChecklines ) {
+ var deadline, checklines, commonlength,
commonprefix, commonsuffix, diffs;
- // Set a deadline by which time the diff must be complete.
- if ( typeof optDeadline === "undefined" ) {
- if ( this.DiffTimeout <= 0 ) {
- optDeadline = Number.MAX_VALUE;
- } else {
- optDeadline = ( new Date() ).getTime() + this.DiffTimeout * 1000;
- }
- }
- deadline = optDeadline;
-
- // Check for null inputs.
- if ( text1 === null || text2 === null ) {
- throw new Error( "Null input. (DiffMain)" );
- }
-
- // Check for equality (speedup).
- if ( text1 === text2 ) {
- if ( text1 ) {
- return [
- [ DIFF_EQUAL, text1 ]
- ];
- }
- return [];
- }
-
- if ( typeof optChecklines === "undefined" ) {
- optChecklines = true;
- }
-
- checklines = optChecklines;
-
- // Trim off common prefix (speedup).
- commonlength = this.diffCommonPrefix( text1, text2 );
- commonprefix = text1.substring( 0, commonlength );
- text1 = text1.substring( commonlength );
- text2 = text2.substring( commonlength );
-
- // Trim off common suffix (speedup).
- /////////
- commonlength = this.diffCommonSuffix( text1, text2 );
- commonsuffix = text1.substring( text1.length - commonlength );
- text1 = text1.substring( 0, text1.length - commonlength );
- text2 = text2.substring( 0, text2.length - commonlength );
-
- // Compute the diff on the middle block.
- diffs = this.diffCompute( text1, text2, checklines, deadline );
-
- // Restore the prefix and suffix.
- if ( commonprefix ) {
- diffs.unshift( [ DIFF_EQUAL, commonprefix ] );
- }
- if ( commonsuffix ) {
- diffs.push( [ DIFF_EQUAL, commonsuffix ] );
- }
- this.diffCleanupMerge( diffs );
- return diffs;
- };
-
- /**
- * Reduce the number of edits by eliminating operationally trivial equalities.
- * @param {!Array.} diffs Array of diff tuples.
- */
- DiffMatchPatch.prototype.diffCleanupEfficiency = function( diffs ) {
- var changes, equalities, equalitiesLength, lastequality,
+
+ // The diff must be complete in up to 1 second.
+ deadline = ( new Date() ).getTime() + 1000;
+
+ // Check for null inputs.
+ if ( text1 === null || text2 === null ) {
+ throw new Error( "Null input. (DiffMain)" );
+ }
+
+ // Check for equality (speedup).
+ if ( text1 === text2 ) {
+ if ( text1 ) {
+ return [
+ [ DIFF_EQUAL, text1 ]
+ ];
+ }
+ return [];
+ }
+
+ if ( typeof optChecklines === "undefined" ) {
+ optChecklines = true;
+ }
+
+ checklines = optChecklines;
+
+ // Trim off common prefix (speedup).
+ commonlength = this.diffCommonPrefix( text1, text2 );
+ commonprefix = text1.substring( 0, commonlength );
+ text1 = text1.substring( commonlength );
+ text2 = text2.substring( commonlength );
+
+ // Trim off common suffix (speedup).
+ commonlength = this.diffCommonSuffix( text1, text2 );
+ commonsuffix = text1.substring( text1.length - commonlength );
+ text1 = text1.substring( 0, text1.length - commonlength );
+ text2 = text2.substring( 0, text2.length - commonlength );
+
+ // Compute the diff on the middle block.
+ diffs = this.diffCompute( text1, text2, checklines, deadline );
+
+ // Restore the prefix and suffix.
+ if ( commonprefix ) {
+ diffs.unshift( [ DIFF_EQUAL, commonprefix ] );
+ }
+ if ( commonsuffix ) {
+ diffs.push( [ DIFF_EQUAL, commonsuffix ] );
+ }
+ this.diffCleanupMerge( diffs );
+ return diffs;
+ };
+
+ /**
+ * Reduce the number of edits by eliminating operationally trivial equalities.
+ * @param {!Array.} diffs Array of diff tuples.
+ */
+ DiffMatchPatch.prototype.diffCleanupEfficiency = function( diffs ) {
+ var changes, equalities, equalitiesLength, lastequality,
pointer, preIns, preDel, postIns, postDel;
- changes = false;
- equalities = []; // Stack of indices where equalities are found.
- equalitiesLength = 0; // Keeping our own length var is faster in JS.
- /** @type {?string} */
- lastequality = null;
- // Always equal to diffs[equalities[equalitiesLength - 1]][1]
- pointer = 0; // Index of current position.
- // Is there an insertion operation before the last equality.
- preIns = false;
- // Is there a deletion operation before the last equality.
- preDel = false;
- // Is there an insertion operation after the last equality.
- postIns = false;
- // Is there a deletion operation after the last equality.
- postDel = false;
- while ( pointer < diffs.length ) {
- if ( diffs[ pointer ][ 0 ] === DIFF_EQUAL ) { // Equality found.
- if ( diffs[ pointer ][ 1 ].length < this.DiffEditCost && ( postIns || postDel ) ) {
- // Candidate found.
- equalities[ equalitiesLength++ ] = pointer;
- preIns = postIns;
- preDel = postDel;
- lastequality = diffs[ pointer ][ 1 ];
- } else {
- // Not a candidate, and can never become one.
- equalitiesLength = 0;
- lastequality = null;
- }
- postIns = postDel = false;
- } else { // An insertion or deletion.
- if ( diffs[ pointer ][ 0 ] === DIFF_DELETE ) {
- postDel = true;
- } else {
- postIns = true;
- }
- /*
- * Five types to be split:
- * A BXYC D
- * A XC D
- * A BXC
- * AXC D
- * A BXC
- */
- if ( lastequality && ( ( preIns && preDel && postIns && postDel ) ||
- ( ( lastequality.length < this.DiffEditCost / 2 ) &&
- ( preIns + preDel + postIns + postDel ) === 3 ) ) ) {
- // Duplicate record.
- diffs.splice( equalities[equalitiesLength - 1], 0, [ DIFF_DELETE, lastequality ] );
- // Change second copy to insert.
- diffs[ equalities[ equalitiesLength - 1 ] + 1 ][ 0 ] = DIFF_INSERT;
- equalitiesLength--; // Throw away the equality we just deleted;
- lastequality = null;
- if (preIns && preDel) {
- // No changes made which could affect previous entry, keep going.
- postIns = postDel = true;
- equalitiesLength = 0;
- } else {
- equalitiesLength--; // Throw away the previous equality.
- pointer = equalitiesLength > 0 ? equalities[ equalitiesLength - 1 ] : -1;
- postIns = postDel = false;
- }
- changes = true;
- }
- }
- pointer++;
- }
-
- if ( changes ) {
- this.diffCleanupMerge( diffs );
- }
- };
-
- /**
- * Convert a diff array into a pretty HTML report.
- * @param {!Array.} diffs Array of diff tuples.
- * @param {integer} string to be beautified.
- * @return {string} HTML representation.
- */
- DiffMatchPatch.prototype.diffPrettyHtml = function( diffs ) {
- var op, data, x, html = [];
- for ( x = 0; x < diffs.length; x++ ) {
- op = diffs[x][0]; // Operation (insert, delete, equal)
- data = diffs[x][1]; // Text of change.
- switch ( op ) {
- case DIFF_INSERT:
- html[x] = "" + data + " ";
- break;
- case DIFF_DELETE:
- html[x] = "" + data + "";
- break;
- case DIFF_EQUAL:
- html[x] = "" + data + " ";
- break;
- }
- }
- return html.join("");
- };
-
- /**
- * Determine the common prefix of two strings.
- * @param {string} text1 First string.
- * @param {string} text2 Second string.
- * @return {number} The number of characters common to the start of each
- * string.
- */
- DiffMatchPatch.prototype.diffCommonPrefix = function( text1, text2 ) {
- var pointermid, pointermax, pointermin, pointerstart;
- // Quick check for common null cases.
- if ( !text1 || !text2 || text1.charAt(0) !== text2.charAt(0) ) {
- return 0;
- }
- // Binary search.
- // Performance analysis: http://neil.fraser.name/news/2007/10/09/
- pointermin = 0;
- pointermax = Math.min( text1.length, text2.length );
- pointermid = pointermax;
- pointerstart = 0;
- while ( pointermin < pointermid ) {
- if ( text1.substring( pointerstart, pointermid ) === text2.substring( pointerstart, pointermid ) ) {
- pointermin = pointermid;
- pointerstart = pointermin;
- } else {
- pointermax = pointermid;
- }
- pointermid = Math.floor( ( pointermax - pointermin ) / 2 + pointermin );
- }
- return pointermid;
- };
-
- /**
- * Determine the common suffix of two strings.
- * @param {string} text1 First string.
- * @param {string} text2 Second string.
- * @return {number} The number of characters common to the end of each string.
- */
- DiffMatchPatch.prototype.diffCommonSuffix = function( text1, text2 ) {
- var pointermid, pointermax, pointermin, pointerend;
- // Quick check for common null cases.
- if (!text1 || !text2 || text1.charAt(text1.length - 1) !== text2.charAt(text2.length - 1)) {
- return 0;
- }
- // Binary search.
- // Performance analysis: http://neil.fraser.name/news/2007/10/09/
- pointermin = 0;
- pointermax = Math.min(text1.length, text2.length);
- pointermid = pointermax;
- pointerend = 0;
- while ( pointermin < pointermid ) {
- if (text1.substring( text1.length - pointermid, text1.length - pointerend ) ===
- text2.substring( text2.length - pointermid, text2.length - pointerend ) ) {
- pointermin = pointermid;
- pointerend = pointermin;
- } else {
- pointermax = pointermid;
- }
- pointermid = Math.floor( ( pointermax - pointermin ) / 2 + pointermin );
- }
- return pointermid;
- };
-
- /**
- * Find the differences between two texts. Assumes that the texts do not
- * have any common prefix or suffix.
- * @param {string} text1 Old string to be diffed.
- * @param {string} text2 New string to be diffed.
- * @param {boolean} checklines Speedup flag. If false, then don't run a
- * line-level diff first to identify the changed areas.
- * If true, then run a faster, slightly less optimal diff.
- * @param {number} deadline Time when the diff should be complete by.
- * @return {!Array.} Array of diff tuples.
- * @private
- */
- DiffMatchPatch.prototype.diffCompute = function( text1, text2, checklines, deadline ) {
- var diffs, longtext, shorttext, i, hm,
+ changes = false;
+ equalities = []; // Stack of indices where equalities are found.
+ equalitiesLength = 0; // Keeping our own length var is faster in JS.
+ /** @type {?string} */
+ lastequality = null;
+ // Always equal to diffs[equalities[equalitiesLength - 1]][1]
+ pointer = 0; // Index of current position.
+ // Is there an insertion operation before the last equality.
+ preIns = false;
+ // Is there a deletion operation before the last equality.
+ preDel = false;
+ // Is there an insertion operation after the last equality.
+ postIns = false;
+ // Is there a deletion operation after the last equality.
+ postDel = false;
+ while ( pointer < diffs.length ) {
+
+ // Equality found.
+ if ( diffs[ pointer ][ 0 ] === DIFF_EQUAL ) {
+ if ( diffs[ pointer ][ 1 ].length < 4 && ( postIns || postDel ) ) {
+
+ // Candidate found.
+ equalities[ equalitiesLength++ ] = pointer;
+ preIns = postIns;
+ preDel = postDel;
+ lastequality = diffs[ pointer ][ 1 ];
+ } else {
+
+ // Not a candidate, and can never become one.
+ equalitiesLength = 0;
+ lastequality = null;
+ }
+ postIns = postDel = false;
+
+ // An insertion or deletion.
+ } else {
+
+ if ( diffs[ pointer ][ 0 ] === DIFF_DELETE ) {
+ postDel = true;
+ } else {
+ postIns = true;
+ }
+
+ /*
+ * Five types to be split:
+ * A BXYC D
+ * A XC D
+ * A BXC
+ * AXC D
+ * A BXC
+ */
+ if ( lastequality && ( ( preIns && preDel && postIns && postDel ) ||
+ ( ( lastequality.length < 2 ) &&
+ ( preIns + preDel + postIns + postDel ) === 3 ) ) ) {
+
+ // Duplicate record.
+ diffs.splice(
+ equalities[ equalitiesLength - 1 ],
+ 0,
+ [ DIFF_DELETE, lastequality ]
+ );
+
+ // Change second copy to insert.
+ diffs[ equalities[ equalitiesLength - 1 ] + 1 ][ 0 ] = DIFF_INSERT;
+ equalitiesLength--; // Throw away the equality we just deleted;
+ lastequality = null;
+ if ( preIns && preDel ) {
+ // No changes made which could affect previous entry, keep going.
+ postIns = postDel = true;
+ equalitiesLength = 0;
+ } else {
+ equalitiesLength--; // Throw away the previous equality.
+ pointer = equalitiesLength > 0 ? equalities[ equalitiesLength - 1 ] : -1;
+ postIns = postDel = false;
+ }
+ changes = true;
+ }
+ }
+ pointer++;
+ }
+
+ if ( changes ) {
+ this.diffCleanupMerge( diffs );
+ }
+ };
+
+ /**
+ * Convert a diff array into a pretty HTML report.
+ * @param {!Array.} diffs Array of diff tuples.
+ * @param {integer} string to be beautified.
+ * @return {string} HTML representation.
+ */
+ DiffMatchPatch.prototype.diffPrettyHtml = function( diffs ) {
+ var op, data, x,
+ html = [];
+ for ( x = 0; x < diffs.length; x++ ) {
+ op = diffs[ x ][ 0 ]; // Operation (insert, delete, equal)
+ data = diffs[ x ][ 1 ]; // Text of change.
+ switch ( op ) {
+ case DIFF_INSERT:
+ html[ x ] = "" + data + " ";
+ break;
+ case DIFF_DELETE:
+ html[ x ] = "" + data + "";
+ break;
+ case DIFF_EQUAL:
+ html[ x ] = "" + data + " ";
+ break;
+ }
+ }
+ return html.join( "" );
+ };
+
+ /**
+ * Determine the common prefix of two strings.
+ * @param {string} text1 First string.
+ * @param {string} text2 Second string.
+ * @return {number} The number of characters common to the start of each
+ * string.
+ */
+ DiffMatchPatch.prototype.diffCommonPrefix = function( text1, text2 ) {
+ var pointermid, pointermax, pointermin, pointerstart;
+ // Quick check for common null cases.
+ if ( !text1 || !text2 || text1.charAt( 0 ) !== text2.charAt( 0 ) ) {
+ return 0;
+ }
+ // Binary search.
+ // Performance analysis: http://neil.fraser.name/news/2007/10/09/
+ pointermin = 0;
+ pointermax = Math.min( text1.length, text2.length );
+ pointermid = pointermax;
+ pointerstart = 0;
+ while ( pointermin < pointermid ) {
+ if ( text1.substring( pointerstart, pointermid ) ===
+ text2.substring( pointerstart, pointermid ) ) {
+ pointermin = pointermid;
+ pointerstart = pointermin;
+ } else {
+ pointermax = pointermid;
+ }
+ pointermid = Math.floor( ( pointermax - pointermin ) / 2 + pointermin );
+ }
+ return pointermid;
+ };
+
+ /**
+ * Determine the common suffix of two strings.
+ * @param {string} text1 First string.
+ * @param {string} text2 Second string.
+ * @return {number} The number of characters common to the end of each string.
+ */
+ DiffMatchPatch.prototype.diffCommonSuffix = function( text1, text2 ) {
+ var pointermid, pointermax, pointermin, pointerend;
+ // Quick check for common null cases.
+ if ( !text1 ||
+ !text2 ||
+ text1.charAt( text1.length - 1 ) !== text2.charAt( text2.length - 1 ) ) {
+ return 0;
+ }
+ // Binary search.
+ // Performance analysis: http://neil.fraser.name/news/2007/10/09/
+ pointermin = 0;
+ pointermax = Math.min( text1.length, text2.length );
+ pointermid = pointermax;
+ pointerend = 0;
+ while ( pointermin < pointermid ) {
+ if ( text1.substring( text1.length - pointermid, text1.length - pointerend ) ===
+ text2.substring( text2.length - pointermid, text2.length - pointerend ) ) {
+ pointermin = pointermid;
+ pointerend = pointermin;
+ } else {
+ pointermax = pointermid;
+ }
+ pointermid = Math.floor( ( pointermax - pointermin ) / 2 + pointermin );
+ }
+ return pointermid;
+ };
+
+ /**
+ * Find the differences between two texts. Assumes that the texts do not
+ * have any common prefix or suffix.
+ * @param {string} text1 Old string to be diffed.
+ * @param {string} text2 New string to be diffed.
+ * @param {boolean} checklines Speedup flag. If false, then don't run a
+ * line-level diff first to identify the changed areas.
+ * If true, then run a faster, slightly less optimal diff.
+ * @param {number} deadline Time when the diff should be complete by.
+ * @return {!Array.} Array of diff tuples.
+ * @private
+ */
+ DiffMatchPatch.prototype.diffCompute = function( text1, text2, checklines, deadline ) {
+ var diffs, longtext, shorttext, i, hm,
text1A, text2A, text1B, text2B,
midCommon, diffsA, diffsB;
- if ( !text1 ) {
- // Just add some text (speedup).
- return [
- [ DIFF_INSERT, text2 ]
- ];
- }
-
- if (!text2) {
- // Just delete some text (speedup).
- return [
- [ DIFF_DELETE, text1 ]
- ];
- }
-
- longtext = text1.length > text2.length ? text1 : text2;
- shorttext = text1.length > text2.length ? text2 : text1;
- i = longtext.indexOf( shorttext );
- if ( i !== -1 ) {
- // Shorter text is inside the longer text (speedup).
- diffs = [
- [ DIFF_INSERT, longtext.substring( 0, i ) ],
- [ DIFF_EQUAL, shorttext ],
- [ DIFF_INSERT, longtext.substring( i + shorttext.length ) ]
- ];
- // Swap insertions for deletions if diff is reversed.
- if ( text1.length > text2.length ) {
- diffs[0][0] = diffs[2][0] = DIFF_DELETE;
- }
- return diffs;
- }
-
- if ( shorttext.length === 1 ) {
- // Single character string.
- // After the previous speedup, the character can't be an equality.
- return [
- [ DIFF_DELETE, text1 ],
- [ DIFF_INSERT, text2 ]
- ];
- }
-
- // Check to see if the problem can be split in two.
- hm = this.diffHalfMatch(text1, text2);
- if (hm) {
- // A half-match was found, sort out the return data.
- text1A = hm[0];
- text1B = hm[1];
- text2A = hm[2];
- text2B = hm[3];
- midCommon = hm[4];
- // Send both pairs off for separate processing.
- diffsA = this.DiffMain(text1A, text2A, checklines, deadline);
- diffsB = this.DiffMain(text1B, text2B, checklines, deadline);
- // Merge the results.
- return diffsA.concat([
- [ DIFF_EQUAL, midCommon ]
- ], diffsB);
- }
-
- if (checklines && text1.length > 100 && text2.length > 100) {
- return this.diffLineMode(text1, text2, deadline);
- }
-
- return this.diffBisect(text1, text2, deadline);
- };
-
- /**
- * Do the two texts share a substring which is at least half the length of the
- * longer text?
- * This speedup can produce non-minimal diffs.
- * @param {string} text1 First string.
- * @param {string} text2 Second string.
- * @return {Array.} Five element Array, containing the prefix of
- * text1, the suffix of text1, the prefix of text2, the suffix of
- * text2 and the common middle. Or null if there was no match.
- * @private
- */
- DiffMatchPatch.prototype.diffHalfMatch = function(text1, text2) {
- var longtext, shorttext, dmp,
+ if ( !text1 ) {
+ // Just add some text (speedup).
+ return [
+ [ DIFF_INSERT, text2 ]
+ ];
+ }
+
+ if ( !text2 ) {
+ // Just delete some text (speedup).
+ return [
+ [ DIFF_DELETE, text1 ]
+ ];
+ }
+
+ longtext = text1.length > text2.length ? text1 : text2;
+ shorttext = text1.length > text2.length ? text2 : text1;
+ i = longtext.indexOf( shorttext );
+ if ( i !== -1 ) {
+ // Shorter text is inside the longer text (speedup).
+ diffs = [
+ [ DIFF_INSERT, longtext.substring( 0, i ) ],
+ [ DIFF_EQUAL, shorttext ],
+ [ DIFF_INSERT, longtext.substring( i + shorttext.length ) ]
+ ];
+ // Swap insertions for deletions if diff is reversed.
+ if ( text1.length > text2.length ) {
+ diffs[ 0 ][ 0 ] = diffs[ 2 ][ 0 ] = DIFF_DELETE;
+ }
+ return diffs;
+ }
+
+ if ( shorttext.length === 1 ) {
+ // Single character string.
+ // After the previous speedup, the character can't be an equality.
+ return [
+ [ DIFF_DELETE, text1 ],
+ [ DIFF_INSERT, text2 ]
+ ];
+ }
+
+ // Check to see if the problem can be split in two.
+ hm = this.diffHalfMatch( text1, text2 );
+ if ( hm ) {
+ // A half-match was found, sort out the return data.
+ text1A = hm[ 0 ];
+ text1B = hm[ 1 ];
+ text2A = hm[ 2 ];
+ text2B = hm[ 3 ];
+ midCommon = hm[ 4 ];
+ // Send both pairs off for separate processing.
+ diffsA = this.DiffMain( text1A, text2A, checklines, deadline );
+ diffsB = this.DiffMain( text1B, text2B, checklines, deadline );
+ // Merge the results.
+ return diffsA.concat( [
+ [ DIFF_EQUAL, midCommon ]
+ ], diffsB );
+ }
+
+ if ( checklines && text1.length > 100 && text2.length > 100 ) {
+ return this.diffLineMode( text1, text2, deadline );
+ }
+
+ return this.diffBisect( text1, text2, deadline );
+ };
+
+ /**
+ * Do the two texts share a substring which is at least half the length of the
+ * longer text?
+ * This speedup can produce non-minimal diffs.
+ * @param {string} text1 First string.
+ * @param {string} text2 Second string.
+ * @return {Array.} Five element Array, containing the prefix of
+ * text1, the suffix of text1, the prefix of text2, the suffix of
+ * text2 and the common middle. Or null if there was no match.
+ * @private
+ */
+ DiffMatchPatch.prototype.diffHalfMatch = function( text1, text2 ) {
+ var longtext, shorttext, dmp,
text1A, text2B, text2A, text1B, midCommon,
hm1, hm2, hm;
- if (this.DiffTimeout <= 0) {
- // Don't risk returning a non-optimal diff if we have unlimited time.
- return null;
- }
- longtext = text1.length > text2.length ? text1 : text2;
- shorttext = text1.length > text2.length ? text2 : text1;
- if (longtext.length < 4 || shorttext.length * 2 < longtext.length) {
- return null; // Pointless.
- }
- dmp = this; // 'this' becomes 'window' in a closure.
-
- /**
- * Does a substring of shorttext exist within longtext such that the substring
- * is at least half the length of longtext?
- * Closure, but does not reference any external variables.
- * @param {string} longtext Longer string.
- * @param {string} shorttext Shorter string.
- * @param {number} i Start index of quarter length substring within longtext.
- * @return {Array.} Five element Array, containing the prefix of
- * longtext, the suffix of longtext, the prefix of shorttext, the suffix
- * of shorttext and the common middle. Or null if there was no match.
- * @private
- */
- function diffHalfMatchI(longtext, shorttext, i) {
- var seed, j, bestCommon, prefixLength, suffixLength,
+
+ longtext = text1.length > text2.length ? text1 : text2;
+ shorttext = text1.length > text2.length ? text2 : text1;
+ if ( longtext.length < 4 || shorttext.length * 2 < longtext.length ) {
+ return null; // Pointless.
+ }
+ dmp = this; // 'this' becomes 'window' in a closure.
+
+ /**
+ * Does a substring of shorttext exist within longtext such that the substring
+ * is at least half the length of longtext?
+ * Closure, but does not reference any external variables.
+ * @param {string} longtext Longer string.
+ * @param {string} shorttext Shorter string.
+ * @param {number} i Start index of quarter length substring within longtext.
+ * @return {Array.} Five element Array, containing the prefix of
+ * longtext, the suffix of longtext, the prefix of shorttext, the suffix
+ * of shorttext and the common middle. Or null if there was no match.
+ * @private
+ */
+ function diffHalfMatchI( longtext, shorttext, i ) {
+ var seed, j, bestCommon, prefixLength, suffixLength,
bestLongtextA, bestLongtextB, bestShorttextA, bestShorttextB;
- // Start with a 1/4 length substring at position i as a seed.
- seed = longtext.substring(i, i + Math.floor(longtext.length / 4));
- j = -1;
- bestCommon = "";
- while ((j = shorttext.indexOf(seed, j + 1)) !== -1) {
- prefixLength = dmp.diffCommonPrefix(longtext.substring(i),
- shorttext.substring(j));
- suffixLength = dmp.diffCommonSuffix(longtext.substring(0, i),
- shorttext.substring(0, j));
- if (bestCommon.length < suffixLength + prefixLength) {
- bestCommon = shorttext.substring(j - suffixLength, j) +
- shorttext.substring(j, j + prefixLength);
- bestLongtextA = longtext.substring(0, i - suffixLength);
- bestLongtextB = longtext.substring(i + prefixLength);
- bestShorttextA = shorttext.substring(0, j - suffixLength);
- bestShorttextB = shorttext.substring(j + prefixLength);
- }
- }
- if (bestCommon.length * 2 >= longtext.length) {
- return [ bestLongtextA, bestLongtextB,
- bestShorttextA, bestShorttextB, bestCommon
- ];
- } else {
- return null;
- }
- }
-
- // First check if the second quarter is the seed for a half-match.
- hm1 = diffHalfMatchI(longtext, shorttext,
- Math.ceil(longtext.length / 4));
- // Check again based on the third quarter.
- hm2 = diffHalfMatchI(longtext, shorttext,
- Math.ceil(longtext.length / 2));
- if (!hm1 && !hm2) {
- return null;
- } else if (!hm2) {
- hm = hm1;
- } else if (!hm1) {
- hm = hm2;
- } else {
- // Both matched. Select the longest.
- hm = hm1[4].length > hm2[4].length ? hm1 : hm2;
- }
-
- // A half-match was found, sort out the return data.
- text1A, text1B, text2A, text2B;
- if (text1.length > text2.length) {
- text1A = hm[0];
- text1B = hm[1];
- text2A = hm[2];
- text2B = hm[3];
- } else {
- text2A = hm[0];
- text2B = hm[1];
- text1A = hm[2];
- text1B = hm[3];
- }
- midCommon = hm[4];
- return [ text1A, text1B, text2A, text2B, midCommon ];
- };
-
- /**
- * Do a quick line-level diff on both strings, then rediff the parts for
- * greater accuracy.
- * This speedup can produce non-minimal diffs.
- * @param {string} text1 Old string to be diffed.
- * @param {string} text2 New string to be diffed.
- * @param {number} deadline Time when the diff should be complete by.
- * @return {!Array.} Array of diff tuples.
- * @private
- */
- DiffMatchPatch.prototype.diffLineMode = function(text1, text2, deadline) {
- var a, diffs, linearray, pointer, countInsert,
+ // Start with a 1/4 length substring at position i as a seed.
+ seed = longtext.substring( i, i + Math.floor( longtext.length / 4 ) );
+ j = -1;
+ bestCommon = "";
+ while ( ( j = shorttext.indexOf( seed, j + 1 ) ) !== -1 ) {
+ prefixLength = dmp.diffCommonPrefix( longtext.substring( i ),
+ shorttext.substring( j ) );
+ suffixLength = dmp.diffCommonSuffix( longtext.substring( 0, i ),
+ shorttext.substring( 0, j ) );
+ if ( bestCommon.length < suffixLength + prefixLength ) {
+ bestCommon = shorttext.substring( j - suffixLength, j ) +
+ shorttext.substring( j, j + prefixLength );
+ bestLongtextA = longtext.substring( 0, i - suffixLength );
+ bestLongtextB = longtext.substring( i + prefixLength );
+ bestShorttextA = shorttext.substring( 0, j - suffixLength );
+ bestShorttextB = shorttext.substring( j + prefixLength );
+ }
+ }
+ if ( bestCommon.length * 2 >= longtext.length ) {
+ return [ bestLongtextA, bestLongtextB,
+ bestShorttextA, bestShorttextB, bestCommon
+ ];
+ } else {
+ return null;
+ }
+ }
+
+ // First check if the second quarter is the seed for a half-match.
+ hm1 = diffHalfMatchI( longtext, shorttext,
+ Math.ceil( longtext.length / 4 ) );
+ // Check again based on the third quarter.
+ hm2 = diffHalfMatchI( longtext, shorttext,
+ Math.ceil( longtext.length / 2 ) );
+ if ( !hm1 && !hm2 ) {
+ return null;
+ } else if ( !hm2 ) {
+ hm = hm1;
+ } else if ( !hm1 ) {
+ hm = hm2;
+ } else {
+ // Both matched. Select the longest.
+ hm = hm1[ 4 ].length > hm2[ 4 ].length ? hm1 : hm2;
+ }
+
+ // A half-match was found, sort out the return data.
+ text1A, text1B, text2A, text2B;
+ if ( text1.length > text2.length ) {
+ text1A = hm[ 0 ];
+ text1B = hm[ 1 ];
+ text2A = hm[ 2 ];
+ text2B = hm[ 3 ];
+ } else {
+ text2A = hm[ 0 ];
+ text2B = hm[ 1 ];
+ text1A = hm[ 2 ];
+ text1B = hm[ 3 ];
+ }
+ midCommon = hm[ 4 ];
+ return [ text1A, text1B, text2A, text2B, midCommon ];
+ };
+
+ /**
+ * Do a quick line-level diff on both strings, then rediff the parts for
+ * greater accuracy.
+ * This speedup can produce non-minimal diffs.
+ * @param {string} text1 Old string to be diffed.
+ * @param {string} text2 New string to be diffed.
+ * @param {number} deadline Time when the diff should be complete by.
+ * @return {!Array.} Array of diff tuples.
+ * @private
+ */
+ DiffMatchPatch.prototype.diffLineMode = function( text1, text2, deadline ) {
+ var a, diffs, linearray, pointer, countInsert,
countDelete, textInsert, textDelete, j;
- // Scan the text on a line-by-line basis first.
- a = this.diffLinesToChars(text1, text2);
- text1 = a.chars1;
- text2 = a.chars2;
- linearray = a.lineArray;
-
- diffs = this.DiffMain(text1, text2, false, deadline);
-
- // Convert the diff back to original text.
- this.diffCharsToLines(diffs, linearray);
- // Eliminate freak matches (e.g. blank lines)
- this.diffCleanupSemantic(diffs);
-
- // Rediff any replacement blocks, this time character-by-character.
- // Add a dummy entry at the end.
- diffs.push( [ DIFF_EQUAL, "" ] );
- pointer = 0;
- countDelete = 0;
- countInsert = 0;
- textDelete = "";
- textInsert = "";
- while (pointer < diffs.length) {
- switch ( diffs[pointer][0] ) {
- case DIFF_INSERT:
- countInsert++;
- textInsert += diffs[pointer][1];
- break;
- case DIFF_DELETE:
- countDelete++;
- textDelete += diffs[pointer][1];
- break;
- case DIFF_EQUAL:
- // Upon reaching an equality, check for prior redundancies.
- if (countDelete >= 1 && countInsert >= 1) {
- // Delete the offending records and add the merged ones.
- diffs.splice(pointer - countDelete - countInsert,
- countDelete + countInsert);
- pointer = pointer - countDelete - countInsert;
- a = this.DiffMain(textDelete, textInsert, false, deadline);
- for (j = a.length - 1; j >= 0; j--) {
- diffs.splice( pointer, 0, a[j] );
- }
- pointer = pointer + a.length;
- }
- countInsert = 0;
- countDelete = 0;
- textDelete = "";
- textInsert = "";
- break;
- }
- pointer++;
- }
- diffs.pop(); // Remove the dummy entry at the end.
-
- return diffs;
- };
-
- /**
- * Find the 'middle snake' of a diff, split the problem in two
- * and return the recursively constructed diff.
- * See Myers 1986 paper: An O(ND) Difference Algorithm and Its Variations.
- * @param {string} text1 Old string to be diffed.
- * @param {string} text2 New string to be diffed.
- * @param {number} deadline Time at which to bail if not yet complete.
- * @return {!Array.} Array of diff tuples.
- * @private
- */
- DiffMatchPatch.prototype.diffBisect = function(text1, text2, deadline) {
- var text1Length, text2Length, maxD, vOffset, vLength,
+ // Scan the text on a line-by-line basis first.
+ a = this.diffLinesToChars( text1, text2 );
+ text1 = a.chars1;
+ text2 = a.chars2;
+ linearray = a.lineArray;
+
+ diffs = this.DiffMain( text1, text2, false, deadline );
+
+ // Convert the diff back to original text.
+ this.diffCharsToLines( diffs, linearray );
+ // Eliminate freak matches (e.g. blank lines)
+ this.diffCleanupSemantic( diffs );
+
+ // Rediff any replacement blocks, this time character-by-character.
+ // Add a dummy entry at the end.
+ diffs.push( [ DIFF_EQUAL, "" ] );
+ pointer = 0;
+ countDelete = 0;
+ countInsert = 0;
+ textDelete = "";
+ textInsert = "";
+ while ( pointer < diffs.length ) {
+ switch ( diffs[ pointer ][ 0 ] ) {
+ case DIFF_INSERT:
+ countInsert++;
+ textInsert += diffs[ pointer ][ 1 ];
+ break;
+ case DIFF_DELETE:
+ countDelete++;
+ textDelete += diffs[ pointer ][ 1 ];
+ break;
+ case DIFF_EQUAL:
+ // Upon reaching an equality, check for prior redundancies.
+ if ( countDelete >= 1 && countInsert >= 1 ) {
+ // Delete the offending records and add the merged ones.
+ diffs.splice( pointer - countDelete - countInsert,
+ countDelete + countInsert );
+ pointer = pointer - countDelete - countInsert;
+ a = this.DiffMain( textDelete, textInsert, false, deadline );
+ for ( j = a.length - 1; j >= 0; j-- ) {
+ diffs.splice( pointer, 0, a[ j ] );
+ }
+ pointer = pointer + a.length;
+ }
+ countInsert = 0;
+ countDelete = 0;
+ textDelete = "";
+ textInsert = "";
+ break;
+ }
+ pointer++;
+ }
+ diffs.pop(); // Remove the dummy entry at the end.
+
+ return diffs;
+ };
+
+ /**
+ * Find the 'middle snake' of a diff, split the problem in two
+ * and return the recursively constructed diff.
+ * See Myers 1986 paper: An O(ND) Difference Algorithm and Its Variations.
+ * @param {string} text1 Old string to be diffed.
+ * @param {string} text2 New string to be diffed.
+ * @param {number} deadline Time at which to bail if not yet complete.
+ * @return {!Array.} Array of diff tuples.
+ * @private
+ */
+ DiffMatchPatch.prototype.diffBisect = function( text1, text2, deadline ) {
+ var text1Length, text2Length, maxD, vOffset, vLength,
v1, v2, x, delta, front, k1start, k1end, k2start,
k2end, k2Offset, k1Offset, x1, x2, y1, y2, d, k1, k2;
- // Cache the text lengths to prevent multiple calls.
- text1Length = text1.length;
- text2Length = text2.length;
- maxD = Math.ceil((text1Length + text2Length) / 2);
- vOffset = maxD;
- vLength = 2 * maxD;
- v1 = new Array(vLength);
- v2 = new Array(vLength);
- // Setting all elements to -1 is faster in Chrome & Firefox than mixing
- // integers and undefined.
- for (x = 0; x < vLength; x++) {
- v1[x] = -1;
- v2[x] = -1;
- }
- v1[vOffset + 1] = 0;
- v2[vOffset + 1] = 0;
- delta = text1Length - text2Length;
- // If the total number of characters is odd, then the front path will collide
- // with the reverse path.
- front = (delta % 2 !== 0);
- // Offsets for start and end of k loop.
- // Prevents mapping of space beyond the grid.
- k1start = 0;
- k1end = 0;
- k2start = 0;
- k2end = 0;
- for (d = 0; d < maxD; d++) {
- // Bail out if deadline is reached.
- if ((new Date()).getTime() > deadline) {
- break;
- }
-
- // Walk the front path one step.
- for (k1 = -d + k1start; k1 <= d - k1end; k1 += 2) {
- k1Offset = vOffset + k1;
- if ( k1 === -d || ( k1 !== d && v1[ k1Offset - 1 ] < v1[ k1Offset + 1 ] ) ) {
- x1 = v1[k1Offset + 1];
- } else {
- x1 = v1[k1Offset - 1] + 1;
- }
- y1 = x1 - k1;
- while (x1 < text1Length && y1 < text2Length &&
- text1.charAt(x1) === text2.charAt(y1)) {
- x1++;
- y1++;
- }
- v1[k1Offset] = x1;
- if (x1 > text1Length) {
- // Ran off the right of the graph.
- k1end += 2;
- } else if (y1 > text2Length) {
- // Ran off the bottom of the graph.
- k1start += 2;
- } else if (front) {
- k2Offset = vOffset + delta - k1;
- if (k2Offset >= 0 && k2Offset < vLength && v2[k2Offset] !== -1) {
- // Mirror x2 onto top-left coordinate system.
- x2 = text1Length - v2[k2Offset];
- if (x1 >= x2) {
- // Overlap detected.
- return this.diffBisectSplit(text1, text2, x1, y1, deadline);
- }
- }
- }
- }
-
- // Walk the reverse path one step.
- for (k2 = -d + k2start; k2 <= d - k2end; k2 += 2) {
- k2Offset = vOffset + k2;
- if ( k2 === -d || (k2 !== d && v2[ k2Offset - 1 ] < v2[ k2Offset + 1 ] ) ) {
- x2 = v2[k2Offset + 1];
- } else {
- x2 = v2[k2Offset - 1] + 1;
- }
- y2 = x2 - k2;
- while (x2 < text1Length && y2 < text2Length &&
- text1.charAt(text1Length - x2 - 1) ===
- text2.charAt(text2Length - y2 - 1)) {
- x2++;
- y2++;
- }
- v2[k2Offset] = x2;
- if (x2 > text1Length) {
- // Ran off the left of the graph.
- k2end += 2;
- } else if (y2 > text2Length) {
- // Ran off the top of the graph.
- k2start += 2;
- } else if (!front) {
- k1Offset = vOffset + delta - k2;
- if (k1Offset >= 0 && k1Offset < vLength && v1[k1Offset] !== -1) {
- x1 = v1[k1Offset];
- y1 = vOffset + x1 - k1Offset;
- // Mirror x2 onto top-left coordinate system.
- x2 = text1Length - x2;
- if (x1 >= x2) {
- // Overlap detected.
- return this.diffBisectSplit(text1, text2, x1, y1, deadline);
- }
- }
- }
- }
- }
- // Diff took too long and hit the deadline or
- // number of diffs equals number of characters, no commonality at all.
- return [
- [ DIFF_DELETE, text1 ],
- [ DIFF_INSERT, text2 ]
- ];
- };
-
- /**
- * Given the location of the 'middle snake', split the diff in two parts
- * and recurse.
- * @param {string} text1 Old string to be diffed.
- * @param {string} text2 New string to be diffed.
- * @param {number} x Index of split point in text1.
- * @param {number} y Index of split point in text2.
- * @param {number} deadline Time at which to bail if not yet complete.
- * @return {!Array.} Array of diff tuples.
- * @private
- */
- DiffMatchPatch.prototype.diffBisectSplit = function( text1, text2, x, y, deadline ) {
- var text1a, text1b, text2a, text2b, diffs, diffsb;
- text1a = text1.substring(0, x);
- text2a = text2.substring(0, y);
- text1b = text1.substring(x);
- text2b = text2.substring(y);
-
- // Compute both diffs serially.
- diffs = this.DiffMain(text1a, text2a, false, deadline);
- diffsb = this.DiffMain(text1b, text2b, false, deadline);
-
- return diffs.concat(diffsb);
- };
-
- /**
- * Reduce the number of edits by eliminating semantically trivial equalities.
- * @param {!Array.} diffs Array of diff tuples.
- */
- DiffMatchPatch.prototype.diffCleanupSemantic = function(diffs) {
- var changes, equalities, equalitiesLength, lastequality,
+ // Cache the text lengths to prevent multiple calls.
+ text1Length = text1.length;
+ text2Length = text2.length;
+ maxD = Math.ceil( ( text1Length + text2Length ) / 2 );
+ vOffset = maxD;
+ vLength = 2 * maxD;
+ v1 = new Array( vLength );
+ v2 = new Array( vLength );
+ // Setting all elements to -1 is faster in Chrome & Firefox than mixing
+ // integers and undefined.
+ for ( x = 0; x < vLength; x++ ) {
+ v1[ x ] = -1;
+ v2[ x ] = -1;
+ }
+ v1[ vOffset + 1 ] = 0;
+ v2[ vOffset + 1 ] = 0;
+ delta = text1Length - text2Length;
+ // If the total number of characters is odd, then the front path will collide
+ // with the reverse path.
+ front = ( delta % 2 !== 0 );
+ // Offsets for start and end of k loop.
+ // Prevents mapping of space beyond the grid.
+ k1start = 0;
+ k1end = 0;
+ k2start = 0;
+ k2end = 0;
+ for ( d = 0; d < maxD; d++ ) {
+ // Bail out if deadline is reached.
+ if ( ( new Date() ).getTime() > deadline ) {
+ break;
+ }
+
+ // Walk the front path one step.
+ for ( k1 = -d + k1start; k1 <= d - k1end; k1 += 2 ) {
+ k1Offset = vOffset + k1;
+ if ( k1 === -d || ( k1 !== d && v1[ k1Offset - 1 ] < v1[ k1Offset + 1 ] ) ) {
+ x1 = v1[ k1Offset + 1 ];
+ } else {
+ x1 = v1[ k1Offset - 1 ] + 1;
+ }
+ y1 = x1 - k1;
+ while ( x1 < text1Length && y1 < text2Length &&
+ text1.charAt( x1 ) === text2.charAt( y1 ) ) {
+ x1++;
+ y1++;
+ }
+ v1[ k1Offset ] = x1;
+ if ( x1 > text1Length ) {
+ // Ran off the right of the graph.
+ k1end += 2;
+ } else if ( y1 > text2Length ) {
+ // Ran off the bottom of the graph.
+ k1start += 2;
+ } else if ( front ) {
+ k2Offset = vOffset + delta - k1;
+ if ( k2Offset >= 0 && k2Offset < vLength && v2[ k2Offset ] !== -1 ) {
+ // Mirror x2 onto top-left coordinate system.
+ x2 = text1Length - v2[ k2Offset ];
+ if ( x1 >= x2 ) {
+ // Overlap detected.
+ return this.diffBisectSplit( text1, text2, x1, y1, deadline );
+ }
+ }
+ }
+ }
+
+ // Walk the reverse path one step.
+ for ( k2 = -d + k2start; k2 <= d - k2end; k2 += 2 ) {
+ k2Offset = vOffset + k2;
+ if ( k2 === -d || ( k2 !== d && v2[ k2Offset - 1 ] < v2[ k2Offset + 1 ] ) ) {
+ x2 = v2[ k2Offset + 1 ];
+ } else {
+ x2 = v2[ k2Offset - 1 ] + 1;
+ }
+ y2 = x2 - k2;
+ while ( x2 < text1Length && y2 < text2Length &&
+ text1.charAt( text1Length - x2 - 1 ) ===
+ text2.charAt( text2Length - y2 - 1 ) ) {
+ x2++;
+ y2++;
+ }
+ v2[ k2Offset ] = x2;
+ if ( x2 > text1Length ) {
+ // Ran off the left of the graph.
+ k2end += 2;
+ } else if ( y2 > text2Length ) {
+ // Ran off the top of the graph.
+ k2start += 2;
+ } else if ( !front ) {
+ k1Offset = vOffset + delta - k2;
+ if ( k1Offset >= 0 && k1Offset < vLength && v1[ k1Offset ] !== -1 ) {
+ x1 = v1[ k1Offset ];
+ y1 = vOffset + x1 - k1Offset;
+ // Mirror x2 onto top-left coordinate system.
+ x2 = text1Length - x2;
+ if ( x1 >= x2 ) {
+ // Overlap detected.
+ return this.diffBisectSplit( text1, text2, x1, y1, deadline );
+ }
+ }
+ }
+ }
+ }
+ // Diff took too long and hit the deadline or
+ // number of diffs equals number of characters, no commonality at all.
+ return [
+ [ DIFF_DELETE, text1 ],
+ [ DIFF_INSERT, text2 ]
+ ];
+ };
+
+ /**
+ * Given the location of the 'middle snake', split the diff in two parts
+ * and recurse.
+ * @param {string} text1 Old string to be diffed.
+ * @param {string} text2 New string to be diffed.
+ * @param {number} x Index of split point in text1.
+ * @param {number} y Index of split point in text2.
+ * @param {number} deadline Time at which to bail if not yet complete.
+ * @return {!Array.} Array of diff tuples.
+ * @private
+ */
+ DiffMatchPatch.prototype.diffBisectSplit = function( text1, text2, x, y, deadline ) {
+ var text1a, text1b, text2a, text2b, diffs, diffsb;
+ text1a = text1.substring( 0, x );
+ text2a = text2.substring( 0, y );
+ text1b = text1.substring( x );
+ text2b = text2.substring( y );
+
+ // Compute both diffs serially.
+ diffs = this.DiffMain( text1a, text2a, false, deadline );
+ diffsb = this.DiffMain( text1b, text2b, false, deadline );
+
+ return diffs.concat( diffsb );
+ };
+
+ /**
+ * Reduce the number of edits by eliminating semantically trivial equalities.
+ * @param {!Array.} diffs Array of diff tuples.
+ */
+ DiffMatchPatch.prototype.diffCleanupSemantic = function( diffs ) {
+ var changes, equalities, equalitiesLength, lastequality,
pointer, lengthInsertions2, lengthDeletions2, lengthInsertions1,
lengthDeletions1, deletion, insertion, overlapLength1, overlapLength2;
- changes = false;
- equalities = []; // Stack of indices where equalities are found.
- equalitiesLength = 0; // Keeping our own length var is faster in JS.
- /** @type {?string} */
- lastequality = null;
- // Always equal to diffs[equalities[equalitiesLength - 1]][1]
- pointer = 0; // Index of current position.
- // Number of characters that changed prior to the equality.
- lengthInsertions1 = 0;
- lengthDeletions1 = 0;
- // Number of characters that changed after the equality.
- lengthInsertions2 = 0;
- lengthDeletions2 = 0;
- while (pointer < diffs.length) {
- if (diffs[pointer][0] === DIFF_EQUAL) { // Equality found.
- equalities[equalitiesLength++] = pointer;
- lengthInsertions1 = lengthInsertions2;
- lengthDeletions1 = lengthDeletions2;
- lengthInsertions2 = 0;
- lengthDeletions2 = 0;
- lastequality = diffs[pointer][1];
- } else { // An insertion or deletion.
- if (diffs[pointer][0] === DIFF_INSERT) {
- lengthInsertions2 += diffs[pointer][1].length;
- } else {
- lengthDeletions2 += diffs[pointer][1].length;
- }
- // Eliminate an equality that is smaller or equal to the edits on both
- // sides of it.
- if (lastequality && (lastequality.length <=
- Math.max(lengthInsertions1, lengthDeletions1)) &&
- (lastequality.length <= Math.max(lengthInsertions2,
- lengthDeletions2))) {
- // Duplicate record.
- diffs.splice( equalities[ equalitiesLength - 1 ], 0, [ DIFF_DELETE, lastequality ] );
- // Change second copy to insert.
- diffs[equalities[equalitiesLength - 1] + 1][0] = DIFF_INSERT;
- // Throw away the equality we just deleted.
- equalitiesLength--;
- // Throw away the previous equality (it needs to be reevaluated).
- equalitiesLength--;
- pointer = equalitiesLength > 0 ? equalities[equalitiesLength - 1] : -1;
- lengthInsertions1 = 0; // Reset the counters.
- lengthDeletions1 = 0;
- lengthInsertions2 = 0;
- lengthDeletions2 = 0;
- lastequality = null;
- changes = true;
- }
- }
- pointer++;
- }
-
- // Normalize the diff.
- if (changes) {
- this.diffCleanupMerge(diffs);
- }
-
- // Find any overlaps between deletions and insertions.
- // e.g: abcxxxxxxdef
- // -> abcxxxdef
- // e.g: xxxabcdefxxx
- // -> def xxxabc
- // Only extract an overlap if it is as big as the edit ahead or behind it.
- pointer = 1;
- while (pointer < diffs.length) {
- if (diffs[pointer - 1][0] === DIFF_DELETE &&
- diffs[pointer][0] === DIFF_INSERT) {
- deletion = diffs[pointer - 1][1];
- insertion = diffs[pointer][1];
- overlapLength1 = this.diffCommonOverlap(deletion, insertion);
- overlapLength2 = this.diffCommonOverlap(insertion, deletion);
- if (overlapLength1 >= overlapLength2) {
- if (overlapLength1 >= deletion.length / 2 ||
- overlapLength1 >= insertion.length / 2) {
- // Overlap found. Insert an equality and trim the surrounding edits.
- diffs.splice( pointer, 0, [ DIFF_EQUAL, insertion.substring( 0, overlapLength1 ) ] );
- diffs[pointer - 1][1] =
- deletion.substring(0, deletion.length - overlapLength1);
- diffs[pointer + 1][1] = insertion.substring(overlapLength1);
- pointer++;
- }
- } else {
- if (overlapLength2 >= deletion.length / 2 ||
- overlapLength2 >= insertion.length / 2) {
- // Reverse overlap found.
- // Insert an equality and swap and trim the surrounding edits.
- diffs.splice( pointer, 0, [ DIFF_EQUAL, deletion.substring( 0, overlapLength2 ) ] );
- diffs[pointer - 1][0] = DIFF_INSERT;
- diffs[pointer - 1][1] =
- insertion.substring(0, insertion.length - overlapLength2);
- diffs[pointer + 1][0] = DIFF_DELETE;
- diffs[pointer + 1][1] =
- deletion.substring(overlapLength2);
- pointer++;
- }
- }
- pointer++;
- }
- pointer++;
- }
- };
-
- /**
- * Determine if the suffix of one string is the prefix of another.
- * @param {string} text1 First string.
- * @param {string} text2 Second string.
- * @return {number} The number of characters common to the end of the first
- * string and the start of the second string.
- * @private
- */
- DiffMatchPatch.prototype.diffCommonOverlap = function(text1, text2) {
- var text1Length, text2Length, textLength,
+ changes = false;
+ equalities = []; // Stack of indices where equalities are found.
+ equalitiesLength = 0; // Keeping our own length var is faster in JS.
+ /** @type {?string} */
+ lastequality = null;
+ // Always equal to diffs[equalities[equalitiesLength - 1]][1]
+ pointer = 0; // Index of current position.
+ // Number of characters that changed prior to the equality.
+ lengthInsertions1 = 0;
+ lengthDeletions1 = 0;
+ // Number of characters that changed after the equality.
+ lengthInsertions2 = 0;
+ lengthDeletions2 = 0;
+ while ( pointer < diffs.length ) {
+ if ( diffs[ pointer ][ 0 ] === DIFF_EQUAL ) { // Equality found.
+ equalities[ equalitiesLength++ ] = pointer;
+ lengthInsertions1 = lengthInsertions2;
+ lengthDeletions1 = lengthDeletions2;
+ lengthInsertions2 = 0;
+ lengthDeletions2 = 0;
+ lastequality = diffs[ pointer ][ 1 ];
+ } else { // An insertion or deletion.
+ if ( diffs[ pointer ][ 0 ] === DIFF_INSERT ) {
+ lengthInsertions2 += diffs[ pointer ][ 1 ].length;
+ } else {
+ lengthDeletions2 += diffs[ pointer ][ 1 ].length;
+ }
+ // Eliminate an equality that is smaller or equal to the edits on both
+ // sides of it.
+ if ( lastequality && ( lastequality.length <=
+ Math.max( lengthInsertions1, lengthDeletions1 ) ) &&
+ ( lastequality.length <= Math.max( lengthInsertions2,
+ lengthDeletions2 ) ) ) {
+
+ // Duplicate record.
+ diffs.splice(
+ equalities[ equalitiesLength - 1 ],
+ 0,
+ [ DIFF_DELETE, lastequality ]
+ );
+
+ // Change second copy to insert.
+ diffs[ equalities[ equalitiesLength - 1 ] + 1 ][ 0 ] = DIFF_INSERT;
+
+ // Throw away the equality we just deleted.
+ equalitiesLength--;
+
+ // Throw away the previous equality (it needs to be reevaluated).
+ equalitiesLength--;
+ pointer = equalitiesLength > 0 ? equalities[ equalitiesLength - 1 ] : -1;
+
+ // Reset the counters.
+ lengthInsertions1 = 0;
+ lengthDeletions1 = 0;
+ lengthInsertions2 = 0;
+ lengthDeletions2 = 0;
+ lastequality = null;
+ changes = true;
+ }
+ }
+ pointer++;
+ }
+
+ // Normalize the diff.
+ if ( changes ) {
+ this.diffCleanupMerge( diffs );
+ }
+
+ // Find any overlaps between deletions and insertions.
+ // e.g: abcxxxxxxdef
+ // -> abcxxxdef
+ // e.g: xxxabcdefxxx
+ // -> def xxxabc
+ // Only extract an overlap if it is as big as the edit ahead or behind it.
+ pointer = 1;
+ while ( pointer < diffs.length ) {
+ if ( diffs[ pointer - 1 ][ 0 ] === DIFF_DELETE &&
+ diffs[ pointer ][ 0 ] === DIFF_INSERT ) {
+ deletion = diffs[ pointer - 1 ][ 1 ];
+ insertion = diffs[ pointer ][ 1 ];
+ overlapLength1 = this.diffCommonOverlap( deletion, insertion );
+ overlapLength2 = this.diffCommonOverlap( insertion, deletion );
+ if ( overlapLength1 >= overlapLength2 ) {
+ if ( overlapLength1 >= deletion.length / 2 ||
+ overlapLength1 >= insertion.length / 2 ) {
+ // Overlap found. Insert an equality and trim the surrounding edits.
+ diffs.splice(
+ pointer,
+ 0,
+ [ DIFF_EQUAL, insertion.substring( 0, overlapLength1 ) ]
+ );
+ diffs[ pointer - 1 ][ 1 ] =
+ deletion.substring( 0, deletion.length - overlapLength1 );
+ diffs[ pointer + 1 ][ 1 ] = insertion.substring( overlapLength1 );
+ pointer++;
+ }
+ } else {
+ if ( overlapLength2 >= deletion.length / 2 ||
+ overlapLength2 >= insertion.length / 2 ) {
+
+ // Reverse overlap found.
+ // Insert an equality and swap and trim the surrounding edits.
+ diffs.splice(
+ pointer,
+ 0,
+ [ DIFF_EQUAL, deletion.substring( 0, overlapLength2 ) ]
+ );
+
+ diffs[ pointer - 1 ][ 0 ] = DIFF_INSERT;
+ diffs[ pointer - 1 ][ 1 ] =
+ insertion.substring( 0, insertion.length - overlapLength2 );
+ diffs[ pointer + 1 ][ 0 ] = DIFF_DELETE;
+ diffs[ pointer + 1 ][ 1 ] =
+ deletion.substring( overlapLength2 );
+ pointer++;
+ }
+ }
+ pointer++;
+ }
+ pointer++;
+ }
+ };
+
+ /**
+ * Determine if the suffix of one string is the prefix of another.
+ * @param {string} text1 First string.
+ * @param {string} text2 Second string.
+ * @return {number} The number of characters common to the end of the first
+ * string and the start of the second string.
+ * @private
+ */
+ DiffMatchPatch.prototype.diffCommonOverlap = function( text1, text2 ) {
+ var text1Length, text2Length, textLength,
best, length, pattern, found;
- // Cache the text lengths to prevent multiple calls.
- text1Length = text1.length;
- text2Length = text2.length;
- // Eliminate the null case.
- if (text1Length === 0 || text2Length === 0) {
- return 0;
- }
- // Truncate the longer string.
- if (text1Length > text2Length) {
- text1 = text1.substring(text1Length - text2Length);
- } else if (text1Length < text2Length) {
- text2 = text2.substring(0, text1Length);
- }
- textLength = Math.min(text1Length, text2Length);
- // Quick check for the worst case.
- if (text1 === text2) {
- return textLength;
- }
-
- // Start by looking for a single character match
- // and increase length until no match is found.
- // Performance analysis: http://neil.fraser.name/news/2010/11/04/
- best = 0;
- length = 1;
- while (true) {
- pattern = text1.substring(textLength - length);
- found = text2.indexOf(pattern);
- if (found === -1) {
- return best;
- }
- length += found;
- if (found === 0 || text1.substring(textLength - length) ===
- text2.substring(0, length)) {
- best = length;
- length++;
- }
- }
- };
-
- /**
- * Split two texts into an array of strings. Reduce the texts to a string of
- * hashes where each Unicode character represents one line.
- * @param {string} text1 First string.
- * @param {string} text2 Second string.
- * @return {{chars1: string, chars2: string, lineArray: !Array.}}
- * An object containing the encoded text1, the encoded text2 and
- * the array of unique strings.
- * The zeroth element of the array of unique strings is intentionally blank.
- * @private
- */
- DiffMatchPatch.prototype.diffLinesToChars = function(text1, text2) {
- var lineArray, lineHash, chars1, chars2;
- lineArray = []; // e.g. lineArray[4] === 'Hello\n'
- lineHash = {}; // e.g. lineHash['Hello\n'] === 4
-
- // '\x00' is a valid character, but various debuggers don't like it.
- // So we'll insert a junk entry to avoid generating a null character.
- lineArray[0] = "";
-
- /**
- * Split a text into an array of strings. Reduce the texts to a string of
- * hashes where each Unicode character represents one line.
- * Modifies linearray and linehash through being a closure.
- * @param {string} text String to encode.
- * @return {string} Encoded string.
- * @private
- */
- function diffLinesToCharsMunge(text) {
- var chars, lineStart, lineEnd, lineArrayLength, line;
- chars = "";
- // Walk the text, pulling out a substring for each line.
- // text.split('\n') would would temporarily double our memory footprint.
- // Modifying text would create many large strings to garbage collect.
- lineStart = 0;
- lineEnd = -1;
- // Keeping our own length variable is faster than looking it up.
- lineArrayLength = lineArray.length;
- while (lineEnd < text.length - 1) {
- lineEnd = text.indexOf("\n", lineStart);
- if (lineEnd === -1) {
- lineEnd = text.length - 1;
- }
- line = text.substring(lineStart, lineEnd + 1);
- lineStart = lineEnd + 1;
-
- if (lineHash.hasOwnProperty ? lineHash.hasOwnProperty(line) :
- (lineHash[line] !== undefined)) {
- chars += String.fromCharCode( lineHash[ line ] );
- } else {
- chars += String.fromCharCode(lineArrayLength);
- lineHash[line] = lineArrayLength;
- lineArray[lineArrayLength++] = line;
- }
- }
- return chars;
- }
-
- chars1 = diffLinesToCharsMunge(text1);
- chars2 = diffLinesToCharsMunge(text2);
- return {
- chars1: chars1,
- chars2: chars2,
- lineArray: lineArray
- };
- };
-
- /**
- * Rehydrate the text in a diff from a string of line hashes to real lines of
- * text.
- * @param {!Array.} diffs Array of diff tuples.
- * @param {!Array.} lineArray Array of unique strings.
- * @private
- */
- DiffMatchPatch.prototype.diffCharsToLines = function( diffs, lineArray ) {
- var x, chars, text, y;
- for ( x = 0; x < diffs.length; x++ ) {
- chars = diffs[x][1];
- text = [];
- for ( y = 0; y < chars.length; y++ ) {
- text[y] = lineArray[chars.charCodeAt(y)];
- }
- diffs[x][1] = text.join("");
- }
- };
-
- /**
- * Reorder and merge like edit sections. Merge equalities.
- * Any edit section can move as long as it doesn't cross an equality.
- * @param {!Array.} diffs Array of diff tuples.
- */
- DiffMatchPatch.prototype.diffCleanupMerge = function(diffs) {
- var pointer, countDelete, countInsert, textInsert, textDelete,
- commonlength, changes;
- diffs.push( [ DIFF_EQUAL, "" ] ); // Add a dummy entry at the end.
- pointer = 0;
- countDelete = 0;
- countInsert = 0;
- textDelete = "";
- textInsert = "";
- commonlength;
- while (pointer < diffs.length) {
- switch ( diffs[ pointer ][ 0 ] ) {
- case DIFF_INSERT:
- countInsert++;
- textInsert += diffs[pointer][1];
- pointer++;
- break;
- case DIFF_DELETE:
- countDelete++;
- textDelete += diffs[pointer][1];
- pointer++;
- break;
- case DIFF_EQUAL:
- // Upon reaching an equality, check for prior redundancies.
- if (countDelete + countInsert > 1) {
- if (countDelete !== 0 && countInsert !== 0) {
- // Factor out any common prefixies.
- commonlength = this.diffCommonPrefix(textInsert, textDelete);
- if (commonlength !== 0) {
- if ((pointer - countDelete - countInsert) > 0 &&
- diffs[pointer - countDelete - countInsert - 1][0] ===
- DIFF_EQUAL) {
- diffs[pointer - countDelete - countInsert - 1][1] +=
- textInsert.substring(0, commonlength);
- } else {
- diffs.splice( 0, 0, [ DIFF_EQUAL,
- textInsert.substring( 0, commonlength )
- ] );
- pointer++;
- }
- textInsert = textInsert.substring(commonlength);
- textDelete = textDelete.substring(commonlength);
- }
- // Factor out any common suffixies.
- commonlength = this.diffCommonSuffix(textInsert, textDelete);
- if (commonlength !== 0) {
- diffs[pointer][1] = textInsert.substring(textInsert.length -
- commonlength) + diffs[pointer][1];
- textInsert = textInsert.substring(0, textInsert.length -
- commonlength);
- textDelete = textDelete.substring(0, textDelete.length -
- commonlength);
- }
- }
- // Delete the offending records and add the merged ones.
- if (countDelete === 0) {
- diffs.splice( pointer - countInsert,
- countDelete + countInsert, [ DIFF_INSERT, textInsert ] );
- } else if (countInsert === 0) {
- diffs.splice( pointer - countDelete,
- countDelete + countInsert, [ DIFF_DELETE, textDelete ] );
- } else {
- diffs.splice( pointer - countDelete - countInsert,
- countDelete + countInsert, [ DIFF_DELETE, textDelete ], [ DIFF_INSERT, textInsert ] );
- }
- pointer = pointer - countDelete - countInsert +
- (countDelete ? 1 : 0) + (countInsert ? 1 : 0) + 1;
- } else if (pointer !== 0 && diffs[pointer - 1][0] === DIFF_EQUAL) {
- // Merge this equality with the previous one.
- diffs[pointer - 1][1] += diffs[pointer][1];
- diffs.splice(pointer, 1);
- } else {
- pointer++;
- }
- countInsert = 0;
- countDelete = 0;
- textDelete = "";
- textInsert = "";
- break;
- }
- }
- if (diffs[diffs.length - 1][1] === "") {
- diffs.pop(); // Remove the dummy entry at the end.
- }
-
- // Second pass: look for single edits surrounded on both sides by equalities
- // which can be shifted sideways to eliminate an equality.
- // e.g: ABA C -> AB AC
- changes = false;
- pointer = 1;
- // Intentionally ignore the first and last element (don't need checking).
- while (pointer < diffs.length - 1) {
- if (diffs[pointer - 1][0] === DIFF_EQUAL &&
- diffs[pointer + 1][0] === DIFF_EQUAL) {
- // This is a single edit surrounded by equalities.
- if ( diffs[ pointer ][ 1 ].substring( diffs[ pointer ][ 1 ].length -
- diffs[ pointer - 1 ][ 1 ].length ) === diffs[ pointer - 1 ][ 1 ] ) {
- // Shift the edit over the previous equality.
- diffs[pointer][1] = diffs[pointer - 1][1] +
- diffs[pointer][1].substring(0, diffs[pointer][1].length -
- diffs[pointer - 1][1].length);
- diffs[pointer + 1][1] = diffs[pointer - 1][1] + diffs[pointer + 1][1];
- diffs.splice(pointer - 1, 1);
- changes = true;
- } else if ( diffs[ pointer ][ 1 ].substring( 0, diffs[ pointer + 1 ][ 1 ].length ) ===
- diffs[ pointer + 1 ][ 1 ] ) {
- // Shift the edit over the next equality.
- diffs[pointer - 1][1] += diffs[pointer + 1][1];
- diffs[pointer][1] =
- diffs[pointer][1].substring(diffs[pointer + 1][1].length) +
- diffs[pointer + 1][1];
- diffs.splice(pointer + 1, 1);
- changes = true;
- }
- }
- pointer++;
- }
- // If shifts were made, the diff needs reordering and another shift sweep.
- if (changes) {
- this.diffCleanupMerge(diffs);
- }
- };
-
- return function(o, n) {
+ // Cache the text lengths to prevent multiple calls.
+ text1Length = text1.length;
+ text2Length = text2.length;
+ // Eliminate the null case.
+ if ( text1Length === 0 || text2Length === 0 ) {
+ return 0;
+ }
+ // Truncate the longer string.
+ if ( text1Length > text2Length ) {
+ text1 = text1.substring( text1Length - text2Length );
+ } else if ( text1Length < text2Length ) {
+ text2 = text2.substring( 0, text1Length );
+ }
+ textLength = Math.min( text1Length, text2Length );
+ // Quick check for the worst case.
+ if ( text1 === text2 ) {
+ return textLength;
+ }
+
+ // Start by looking for a single character match
+ // and increase length until no match is found.
+ // Performance analysis: http://neil.fraser.name/news/2010/11/04/
+ best = 0;
+ length = 1;
+ while ( true ) {
+ pattern = text1.substring( textLength - length );
+ found = text2.indexOf( pattern );
+ if ( found === -1 ) {
+ return best;
+ }
+ length += found;
+ if ( found === 0 || text1.substring( textLength - length ) ===
+ text2.substring( 0, length ) ) {
+ best = length;
+ length++;
+ }
+ }
+ };
+
+ /**
+ * Split two texts into an array of strings. Reduce the texts to a string of
+ * hashes where each Unicode character represents one line.
+ * @param {string} text1 First string.
+ * @param {string} text2 Second string.
+ * @return {{chars1: string, chars2: string, lineArray: !Array.}}
+ * An object containing the encoded text1, the encoded text2 and
+ * the array of unique strings.
+ * The zeroth element of the array of unique strings is intentionally blank.
+ * @private
+ */
+ DiffMatchPatch.prototype.diffLinesToChars = function( text1, text2 ) {
+ var lineArray, lineHash, chars1, chars2;
+ lineArray = []; // e.g. lineArray[4] === 'Hello\n'
+ lineHash = {}; // e.g. lineHash['Hello\n'] === 4
+
+ // '\x00' is a valid character, but various debuggers don't like it.
+ // So we'll insert a junk entry to avoid generating a null character.
+ lineArray[ 0 ] = "";
+
+ /**
+ * Split a text into an array of strings. Reduce the texts to a string of
+ * hashes where each Unicode character represents one line.
+ * Modifies linearray and linehash through being a closure.
+ * @param {string} text String to encode.
+ * @return {string} Encoded string.
+ * @private
+ */
+ function diffLinesToCharsMunge( text ) {
+ var chars, lineStart, lineEnd, lineArrayLength, line;
+ chars = "";
+ // Walk the text, pulling out a substring for each line.
+ // text.split('\n') would would temporarily double our memory footprint.
+ // Modifying text would create many large strings to garbage collect.
+ lineStart = 0;
+ lineEnd = -1;
+ // Keeping our own length variable is faster than looking it up.
+ lineArrayLength = lineArray.length;
+ while ( lineEnd < text.length - 1 ) {
+ lineEnd = text.indexOf( "\n", lineStart );
+ if ( lineEnd === -1 ) {
+ lineEnd = text.length - 1;
+ }
+ line = text.substring( lineStart, lineEnd + 1 );
+ lineStart = lineEnd + 1;
+
+ if ( lineHash.hasOwnProperty ? lineHash.hasOwnProperty( line ) :
+ ( lineHash[ line ] !== undefined ) ) {
+ chars += String.fromCharCode( lineHash[ line ] );
+ } else {
+ chars += String.fromCharCode( lineArrayLength );
+ lineHash[ line ] = lineArrayLength;
+ lineArray[ lineArrayLength++ ] = line;
+ }
+ }
+ return chars;
+ }
+
+ chars1 = diffLinesToCharsMunge( text1 );
+ chars2 = diffLinesToCharsMunge( text2 );
+ return {
+ chars1: chars1,
+ chars2: chars2,
+ lineArray: lineArray
+ };
+ };
+
+ /**
+ * Rehydrate the text in a diff from a string of line hashes to real lines of
+ * text.
+ * @param {!Array.} diffs Array of diff tuples.
+ * @param {!Array.} lineArray Array of unique strings.
+ * @private
+ */
+ DiffMatchPatch.prototype.diffCharsToLines = function( diffs, lineArray ) {
+ var x, chars, text, y;
+ for ( x = 0; x < diffs.length; x++ ) {
+ chars = diffs[ x ][ 1 ];
+ text = [];
+ for ( y = 0; y < chars.length; y++ ) {
+ text[ y ] = lineArray[ chars.charCodeAt( y ) ];
+ }
+ diffs[ x ][ 1 ] = text.join( "" );
+ }
+ };
+
+ /**
+ * Reorder and merge like edit sections. Merge equalities.
+ * Any edit section can move as long as it doesn't cross an equality.
+ * @param {!Array.} diffs Array of diff tuples.
+ */
+ DiffMatchPatch.prototype.diffCleanupMerge = function( diffs ) {
+ var pointer, countDelete, countInsert, textInsert, textDelete,
+ commonlength, changes, diffPointer, position;
+ diffs.push( [ DIFF_EQUAL, "" ] ); // Add a dummy entry at the end.
+ pointer = 0;
+ countDelete = 0;
+ countInsert = 0;
+ textDelete = "";
+ textInsert = "";
+ commonlength;
+ while ( pointer < diffs.length ) {
+ switch ( diffs[ pointer ][ 0 ] ) {
+ case DIFF_INSERT:
+ countInsert++;
+ textInsert += diffs[ pointer ][ 1 ];
+ pointer++;
+ break;
+ case DIFF_DELETE:
+ countDelete++;
+ textDelete += diffs[ pointer ][ 1 ];
+ pointer++;
+ break;
+ case DIFF_EQUAL:
+ // Upon reaching an equality, check for prior redundancies.
+ if ( countDelete + countInsert > 1 ) {
+ if ( countDelete !== 0 && countInsert !== 0 ) {
+ // Factor out any common prefixies.
+ commonlength = this.diffCommonPrefix( textInsert, textDelete );
+ if ( commonlength !== 0 ) {
+ if ( ( pointer - countDelete - countInsert ) > 0 &&
+ diffs[ pointer - countDelete - countInsert - 1 ][ 0 ] ===
+ DIFF_EQUAL ) {
+ diffs[ pointer - countDelete - countInsert - 1 ][ 1 ] +=
+ textInsert.substring( 0, commonlength );
+ } else {
+ diffs.splice( 0, 0, [ DIFF_EQUAL,
+ textInsert.substring( 0, commonlength )
+ ] );
+ pointer++;
+ }
+ textInsert = textInsert.substring( commonlength );
+ textDelete = textDelete.substring( commonlength );
+ }
+ // Factor out any common suffixies.
+ commonlength = this.diffCommonSuffix( textInsert, textDelete );
+ if ( commonlength !== 0 ) {
+ diffs[ pointer ][ 1 ] = textInsert.substring( textInsert.length -
+ commonlength ) + diffs[ pointer ][ 1 ];
+ textInsert = textInsert.substring( 0, textInsert.length -
+ commonlength );
+ textDelete = textDelete.substring( 0, textDelete.length -
+ commonlength );
+ }
+ }
+ // Delete the offending records and add the merged ones.
+ if ( countDelete === 0 ) {
+ diffs.splice( pointer - countInsert,
+ countDelete + countInsert, [ DIFF_INSERT, textInsert ] );
+ } else if ( countInsert === 0 ) {
+ diffs.splice( pointer - countDelete,
+ countDelete + countInsert, [ DIFF_DELETE, textDelete ] );
+ } else {
+ diffs.splice(
+ pointer - countDelete - countInsert,
+ countDelete + countInsert,
+ [ DIFF_DELETE, textDelete ], [ DIFF_INSERT, textInsert ]
+ );
+ }
+ pointer = pointer - countDelete - countInsert +
+ ( countDelete ? 1 : 0 ) + ( countInsert ? 1 : 0 ) + 1;
+ } else if ( pointer !== 0 && diffs[ pointer - 1 ][ 0 ] === DIFF_EQUAL ) {
+
+ // Merge this equality with the previous one.
+ diffs[ pointer - 1 ][ 1 ] += diffs[ pointer ][ 1 ];
+ diffs.splice( pointer, 1 );
+ } else {
+ pointer++;
+ }
+ countInsert = 0;
+ countDelete = 0;
+ textDelete = "";
+ textInsert = "";
+ break;
+ }
+ }
+ if ( diffs[ diffs.length - 1 ][ 1 ] === "" ) {
+ diffs.pop(); // Remove the dummy entry at the end.
+ }
+
+ // Second pass: look for single edits surrounded on both sides by equalities
+ // which can be shifted sideways to eliminate an equality.
+ // e.g: ABA C -> AB AC
+ changes = false;
+ pointer = 1;
+
+ // Intentionally ignore the first and last element (don't need checking).
+ while ( pointer < diffs.length - 1 ) {
+ if ( diffs[ pointer - 1 ][ 0 ] === DIFF_EQUAL &&
+ diffs[ pointer + 1 ][ 0 ] === DIFF_EQUAL ) {
+
+ diffPointer = diffs[ pointer ][ 1 ];
+ position = diffPointer.substring(
+ diffPointer.length - diffs[ pointer - 1 ][ 1 ].length
+ );
+
+ // This is a single edit surrounded by equalities.
+ if ( position === diffs[ pointer - 1 ][ 1 ] ) {
+
+ // Shift the edit over the previous equality.
+ diffs[ pointer ][ 1 ] = diffs[ pointer - 1 ][ 1 ] +
+ diffs[ pointer ][ 1 ].substring( 0, diffs[ pointer ][ 1 ].length -
+ diffs[ pointer - 1 ][ 1 ].length );
+ diffs[ pointer + 1 ][ 1 ] =
+ diffs[ pointer - 1 ][ 1 ] + diffs[ pointer + 1 ][ 1 ];
+ diffs.splice( pointer - 1, 1 );
+ changes = true;
+ } else if ( diffPointer.substring( 0, diffs[ pointer + 1 ][ 1 ].length ) ===
+ diffs[ pointer + 1 ][ 1 ] ) {
+
+ // Shift the edit over the next equality.
+ diffs[ pointer - 1 ][ 1 ] += diffs[ pointer + 1 ][ 1 ];
+ diffs[ pointer ][ 1 ] =
+ diffs[ pointer ][ 1 ].substring( diffs[ pointer + 1 ][ 1 ].length ) +
+ diffs[ pointer + 1 ][ 1 ];
+ diffs.splice( pointer + 1, 1 );
+ changes = true;
+ }
+ }
+ pointer++;
+ }
+ // If shifts were made, the diff needs reordering and another shift sweep.
+ if ( changes ) {
+ this.diffCleanupMerge( diffs );
+ }
+ };
+
+ return function( o, n ) {
var diff, output, text;
- diff = new DiffMatchPatch();
- output = diff.DiffMain(o, n);
- //console.log(output);
- diff.diffCleanupEfficiency(output);
- text = diff.diffPrettyHtml(output);
-
- return text;
- };
-}());
-// jscs:enable
+ diff = new DiffMatchPatch();
+ output = diff.DiffMain( o, n );
+ diff.diffCleanupEfficiency( output );
+ text = diff.diffPrettyHtml( output );
+
+ return text;
+ };
+}() );
+
+// Get a reference to the global object, like window in browsers
+}( (function() {
+ return this;
+})() ));
(function() {
+// Don't load the HTML Reporter on non-Browser environments
+if ( typeof window === "undefined" || !window.document ) {
+ return;
+}
+
// Deprecated QUnit.init - Ref #530
// Re-initialize the configuration options
QUnit.init = function() {
@@ -3124,12 +3383,8 @@ QUnit.init = function() {
}
};
-// Don't load the HTML Reporter on non-Browser environments
-if ( typeof window === "undefined" ) {
- return;
-}
-
var config = QUnit.config,
+ collapseNext = false,
hasOwn = Object.prototype.hasOwnProperty,
defined = {
document: window.document !== undefined,
@@ -3526,6 +3781,17 @@ function storeFixture() {
}
}
+function appendFilteredTest() {
+ var testId = QUnit.config.testId;
+ if ( !testId || testId.length <= 0 ) {
+ return "";
+ }
+ return "";
+}
+
function appendUserAgent() {
var userAgent = id( "qunit-userAgent" );
@@ -3533,7 +3799,7 @@ function appendUserAgent() {
userAgent.innerHTML = "";
userAgent.appendChild(
document.createTextNode(
- "QUnit " + QUnit.version + "; " + navigator.userAgent
+ "QUnit " + QUnit.version + "; " + navigator.userAgent
)
);
}
@@ -3597,6 +3863,7 @@ QUnit.begin(function( details ) {
"" +
" " +
"
" +
+ appendFilteredTest() +
" " +
" ";
}
@@ -3813,6 +4080,16 @@ QUnit.testDone(function( details ) {
}
if ( bad === 0 ) {
+
+ // Collapse the passing tests
+ addClass( assertList, "qunit-collapsed" );
+ } else if ( bad && config.collapse && !collapseNext ) {
+
+ // Skip collapsing the first failing test
+ collapseNext = true;
+ } else {
+
+ // Collapse remaining tests
addClass( assertList, "qunit-collapsed" );
}
@@ -3879,3 +4156,4 @@ if ( defined.document ) {
}
})();
+
diff --git a/Plugins/Vorlon/plugins/unitTestRunner/vorlon.unitTestRunner.interfaces.ts b/Plugins/Vorlon/plugins/unitTestRunner/vorlon.unitTestRunner.interfaces.ts
deleted file mode 100644
index 97191ee8..00000000
--- a/Plugins/Vorlon/plugins/unitTestRunner/vorlon.unitTestRunner.interfaces.ts
+++ /dev/null
@@ -1,6 +0,0 @@
-module VORLON {
- //export class KeyValue {
- // public key: string;
- // public value: string;
- //}
-}
\ No newline at end of file
diff --git a/Plugins/Vorlon/plugins/vorlontheme.css b/Plugins/Vorlon/plugins/vorlontheme.css
new file mode 100644
index 00000000..e69de29b
diff --git a/Plugins/Vorlon/plugins/webstandards/axe.min.js b/Plugins/Vorlon/plugins/webstandards/axe.min.js
new file mode 100644
index 00000000..8090eaee
--- /dev/null
+++ b/Plugins/Vorlon/plugins/webstandards/axe.min.js
@@ -0,0 +1,15 @@
+/*! aXe v1.1.1
+ * Copyright (c) 2015 Deque Systems, Inc.
+ *
+ * Your use of this Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/.
+ *
+ * This entire copyright notice must appear in every copy of this file you
+ * distribute or in any file that contains substantial portions of this source
+ * code.
+ */
+!function(a,b){function c(a){"use strict";var b,d,e=a;if(null!==a&&"object"==typeof a)if(Array.isArray(a))for(e=[],b=0,d=a.length;d>b;b++)e[b]=c(a[b]);else{e={};for(b in a)e[b]=c(a[b])}return e}function d(a){"use strict";var b=a||{};return b.rules=b.rules||[],b.tools=b.tools||[],b.checks=b.checks||[],b.data=b.data||{checks:{},rules:{}},b}function e(a,b,c){"use strict";var d,e;for(d=0,e=a.length;e>d;d++)b[c](a[d])}function f(a){"use strict";a=d(a),S.commons=R=a.commons,this.reporter=a.reporter,this.rules=[],this.tools={},this.checks={},e(a.rules,this,"addRule"),e(a.tools,this,"addTool"),e(a.checks,this,"addCheck"),this.data=a.data||{checks:{},rules:{}},H(a.style)}function g(a){"use strict";this.id=a.id,this.data=null,this.relatedNodes=[],this.result=null}function h(a){"use strict";this.id=a.id,this.options=a.options,this.selector=a.selector,this.evaluate=a.evaluate,a.after&&(this.after=a.after),a.matches&&(this.matches=a.matches),this.enabled=a.hasOwnProperty("enabled")?a.enabled:!0}function i(a,b){"use strict";if(!T.isHidden(b)){var c=T.findBy(a,"node",b);c||a.push({node:b,include:[],exclude:[]})}}function j(a,c,d){"use strict";a.frames=a.frames||[];var e,f,g=b.querySelectorAll(d.shift());a:for(var h=0,i=g.length;i>h;h++){f=g[h];for(var j=0,k=a.frames.length;k>j;j++)if(a.frames[j].node===f){a.frames[j][c].push(d);break a}e={node:f,include:[],exclude:[]},d&&e[c].push(d),a.frames.push(e)}}function k(a){"use strict";if(a&&"object"==typeof a||a instanceof NodeList){if(a instanceof Node)return{include:[a],exclude:[]};if(a.hasOwnProperty("include")||a.hasOwnProperty("exclude"))return{include:a.include||[b],exclude:a.exclude||[]};if(a.length===+a.length)return{include:a,exclude:[]}}return"string"==typeof a?{include:[a],exclude:[]}:{include:[b],exclude:[]}}function l(a,c){"use strict";for(var d,e=[],f=0,g=a[c].length;g>f;f++){if(d=a[c][f],"string"==typeof d){e=e.concat(T.toArray(b.querySelectorAll(d)));break}d&&d.length?d.length>1?j(a,c,d):e=e.concat(T.toArray(b.querySelectorAll(d[0]))):e.push(d)}return e.filter(function(a){return a})}function m(a){"use strict";var c=this;this.frames=[],this.initiator=a&&"boolean"==typeof a.initiator?a.initiator:!0,this.page=!1,a=k(a),this.exclude=a.exclude,this.include=a.include,this.include=l(this,"include"),this.exclude=l(this,"exclude"),T.select("frame, iframe",this).forEach(function(a){M(a,c)&&i(c.frames,a)}),1===this.include.length&&this.include[0]===b&&(this.page=!0)}function n(a){"use strict";this.id=a.id,this.result=S.constants.result.NA,this.pageLevel=a.pageLevel,this.impact=null,this.nodes=[]}function o(a,b){"use strict";this._audit=b,this.id=a.id,this.selector=a.selector||"*",this.excludeHidden="boolean"==typeof a.excludeHidden?a.excludeHidden:!0,this.enabled="boolean"==typeof a.enabled?a.enabled:!0,this.pageLevel="boolean"==typeof a.pageLevel?a.pageLevel:!1,this.any=a.any||[],this.all=a.all||[],this.none=a.none||[],this.tags=a.tags||[],a.matches&&(this.matches=a.matches)}function p(a){"use strict";return T.getAllChecks(a).map(function(b){var c=a._audit.checks[b.id||b];return"function"==typeof c.after?c:null}).filter(Boolean)}function q(a,b){"use strict";var c=[];return a.forEach(function(a){var d=T.getAllChecks(a);d.forEach(function(a){a.id===b&&c.push(a)})}),c}function r(a){"use strict";return a.filter(function(a){return a.filtered!==!0})}function s(a){"use strict";var b=["any","all","none"],c=a.nodes.filter(function(a){var c=0;return b.forEach(function(b){a[b]=r(a[b]),c+=a[b].length}),c>0});return a.pageLevel&&c.length&&(c=[c.reduce(function(a,c){return a?(b.forEach(function(b){a[b].push.apply(a[b],c[b])}),a):void 0})]),c}function t(a){"use strict";a.source=a.source||{},this.id=a.id,this.options=a.options,this._run=a.source.run,this._cleanup=a.source.cleanup,this.active=!1}function u(a){"use strict";if(!S._audit)throw new Error("No audit configured");var c=T.queue();Object.keys(S._audit.tools).forEach(function(a){var b=S._audit.tools[a];b.active&&c.defer(function(a){b.cleanup(a)})}),T.toArray(b.querySelectorAll("frame, iframe")).forEach(function(a){c.defer(function(b){return T.sendCommandToFrame(a,{command:"cleanup-tool"},b)})}),c.then(a)}function v(a,c){"use strict";var d=a&&a.context||{};d.include&&!d.include.length&&(d.include=[b]);var e=a&&a.options||{};switch(a.command){case"rules":return x(d,e,c);case"run-tool":return y(a.parameter,a.selectorArray,e,c);case"cleanup-tool":return u(c)}}function w(a){"use strict";return"string"==typeof a&&W[a]?W[a]:"function"==typeof a?a:V}function x(a,b,c){"use strict";a=new m(a);var d=T.queue(),e=S._audit;a.frames.length&&d.defer(function(c){T.collectResultsFromFrames(a,b,"rules",null,c)}),d.defer(function(c){e.run(a,b,c)}),d.then(function(d){var f=T.mergeResults(d.map(function(a){return{results:a}}));a.initiator&&(f=e.after(f,b),f=f.map(T.finalizeRuleResult)),c(f)})}function y(a,c,d,e){"use strict";if(!S._audit)throw new Error("No audit configured");if(c.length>1){var f=b.querySelector(c.shift());return T.sendCommandToFrame(f,{options:d,command:"run-tool",parameter:a,selectorArray:c},e)}var g=b.querySelector(c.shift());S._audit.tools[a].run(g,d,e)}function z(a,b){"use strict";if(b=b||300,a.length>b){var c=a.indexOf(">");a=a.substring(0,c+1)}return a}function A(a){"use strict";var b=a.outerHTML;return b||"function"!=typeof XMLSerializer||(b=(new XMLSerializer).serializeToString(a)),z(b||"")}function B(a,b){"use strict";b=b||{},this.selector=b.selector||[T.getSelector(a)],this.source=void 0!==b.source?b.source:A(a),this.element=a}function C(a,b){"use strict";Object.keys(S.constants.raisedMetadata).forEach(function(c){var d=S.constants.raisedMetadata[c],e=b.reduce(function(a,b){var e=d.indexOf(b[c]);return e>a?e:a},-1);d[e]&&(a[c]=d[e])})}function D(a){"use strict";var b=a.any.length||a.all.length||a.none.length;return b?S.constants.result.FAIL:S.constants.result.PASS}function E(a){"use strict";function b(a){return T.extendBlacklist({},a,["result"])}var c=T.extendBlacklist({violations:[],passes:[]},a,["nodes"]);return a.nodes.forEach(function(a){var d=T.getFailingChecks(a),e=D(d);return e===S.constants.result.FAIL?(C(a,T.getAllChecks(d)),a.any=d.any.map(b),a.all=d.all.map(b),a.none=d.none.map(b),void c.violations.push(a)):(a.any=a.any.filter(function(a){return a.result}).map(b),a.all=a.all.map(b),a.none=a.none.map(b),void c.passes.push(a))}),C(c,c.violations),c.result=c.violations.length?S.constants.result.FAIL:c.passes.length?S.constants.result.PASS:c.result,c}function F(a){"use strict";for(var b=1,c=a.nodeName;a=a.previousElementSibling;)a.nodeName===c&&b++;return b}function G(a,b){"use strict";var c,d,e=a.parentNode.children;if(!e)return!1;var f=e.length;for(c=0;f>c;c++)if(d=e[c],d!==a&&T.matchesSelector(d,b))return!0;return!1}function H(a){"use strict";if(X&&X.parentNode&&(X.parentNode.removeChild(X),X=null),a){var c=b.head||b.getElementsByTagName("head")[0];return X=b.createElement("style"),X.type="text/css",void 0===X.styleSheet?X.appendChild(b.createTextNode(a)):X.styleSheet.cssText=a,c.appendChild(X),X}}function I(a,b,c){"use strict";a.forEach(function(a){a.node.selector.unshift(c),a.node=new T.DqElement(b,a.node);var d=T.getAllChecks(a);d.length&&d.forEach(function(a){a.relatedNodes.forEach(function(a){a.selector.unshift(c),a=new T.DqElement(b,a)})})})}function J(a,b){"use strict";for(var c,d,e=b[0].node,f=0,g=a.length;g>f;f++)if(d=a[f].node,c=T.nodeSorter(d.element,e.element),c>0||0===c&&e.selector.lengthd;d++)-1===a.indexOf(b[d])&&M(b[d],c)&&a.push(b[d])}var O,P=function(){"use strict";function a(a){var b,c,d=a.Element.prototype,e=["matches","matchesSelector","mozMatchesSelector","webkitMatchesSelector","msMatchesSelector"],f=e.length;for(b=0;f>b;b++)if(c=e[b],d[c])return c}var b;return function(c,d){return b&&c[b]||(b=a(c.ownerDocument.defaultView)),c[b](d)}}(),Q=function(a){"use strict";for(var b,c=String(a),d=c.length,e=-1,f="",g=c.charCodeAt(0);++e=1&&31>=b||b>=127&&159>=b||0==e&&b>=48&&57>=b||1==e&&b>=48&&57>=b&&45==g?"\\"+b.toString(16)+" ":(1!=e||45!=b||45!=g)&&(b>=128||45==b||95==b||b>=48&&57>=b||b>=65&&90>=b||b>=97&&122>=b)?c.charAt(e):"\\"+c.charAt(e)}return f};!function(a){function b(a,b,c){var d=b&&c||0,e=0;for(b=b||[],a.toLowerCase().replace(/[0-9a-f]{2}/g,function(a){16>e&&(b[d+e++]=l[a])});16>e;)b[d+e++]=0;return b}function c(a,b){var c=b||0,d=k;return d[a[c++]]+d[a[c++]]+d[a[c++]]+d[a[c++]]+"-"+d[a[c++]]+d[a[c++]]+"-"+d[a[c++]]+d[a[c++]]+"-"+d[a[c++]]+d[a[c++]]+"-"+d[a[c++]]+d[a[c++]]+d[a[c++]]+d[a[c++]]+d[a[c++]]+d[a[c++]]}function d(a,b,d){var e=b&&d||0,f=b||[];a=a||{};var g=null!=a.clockseq?a.clockseq:p,h=null!=a.msecs?a.msecs:(new Date).getTime(),i=null!=a.nsecs?a.nsecs:r+1,j=h-q+(i-r)/1e4;if(0>j&&null==a.clockseq&&(g=g+1&16383),(0>j||h>q)&&null==a.nsecs&&(i=0),i>=1e4)throw new Error("uuid.v1(): Can't create more than 10M uuids/sec");q=h,r=i,p=g,h+=122192928e5;var k=(1e4*(268435455&h)+i)%4294967296;f[e++]=k>>>24&255,f[e++]=k>>>16&255,f[e++]=k>>>8&255,f[e++]=255&k;var l=h/4294967296*1e4&268435455;f[e++]=l>>>8&255,f[e++]=255&l,f[e++]=l>>>24&15|16,f[e++]=l>>>16&255,f[e++]=g>>>8|128,f[e++]=255&g;for(var m=a.node||o,n=0;6>n;n++)f[e+n]=m[n];return b?b:c(f)}function e(a,b,d){var e=b&&d||0;"string"==typeof a&&(b="binary"==a?new j(16):null,a=null),a=a||{};var g=a.random||(a.rng||f)();if(g[6]=15&g[6]|64,g[8]=63&g[8]|128,b)for(var h=0;16>h;h++)b[e+h]=g[h];return b||c(g)}var f,g=a.crypto||a.msCrypto;if(!f&&g&&g.getRandomValues){var h=new Uint8Array(16);f=function(){return g.getRandomValues(h),h}}if(!f){var i=new Array(16);f=function(){for(var a,b=0;16>b;b++)0===(3&b)&&(a=4294967296*Math.random()),i[b]=a>>>((3&b)<<3)&255;return i}}for(var j="function"==typeof a.Buffer?a.Buffer:Array,k=[],l={},m=0;256>m;m++)k[m]=(m+256).toString(16).substr(1),l[k[m]]=m;var n=f(),o=[1|n[0],n[1],n[2],n[3],n[4],n[5]],p=16383&(n[6]<<8|n[7]),q=0,r=0;O=e,O.v1=d,O.v4=e,O.parse=b,O.unparse=c,O.BufferClass=j}(a);var R,S={},T=S.utils={};T.matchesSelector=P,T.escapeSelector=Q,T.clone=c;var U={};f.prototype.addRule=function(a){"use strict";a.metadata&&(this.data.rules[a.id]=a.metadata);for(var b,c=0,d=this.rules.length;d>c;c++)if(b=this.rules[c],b.id===a.id)return void(this.rules[c]=new o(a,this));this.rules.push(new o(a,this))},f.prototype.addTool=function(a){"use strict";this.tools[a.id]=new t(a)},f.prototype.addCheck=function(a){"use strict";a.metadata&&(this.data.checks[a.id]=a.metadata),this.checks[a.id]=new h(a)},f.prototype.run=function(a,b,c){"use strict";var d=T.queue();this.rules.forEach(function(c){T.ruleShouldRun(c,a,b)&&d.defer(function(d){c.run(a,b,d)})}),d.then(c)},f.prototype.after=function(a,b){"use strict";var c=this.rules;return a.map(function(a){var d=T.findBy(c,"id",a.id);return d.after(a,b)})},h.prototype.matches=function(a){"use strict";return!this.selector||T.matchesSelector(a,this.selector)?!0:!1},h.prototype.run=function(a,b,c){"use strict";b=b||{};var d=b.hasOwnProperty("enabled")?b.enabled:this.enabled,e=b.options||this.options;if(d&&this.matches(a)){var f,h=new g(this),i=T.checkHelper(h,c);try{f=this.evaluate.call(i,a,e)}catch(j){return S.log(j.message,j.stack),void c(null)}i.isAsync||(h.result=f,setTimeout(function(){c(h)},0))}else c(null)},o.prototype.matches=function(){"use strict";return!0},o.prototype.gather=function(a){"use strict";var b=T.select(this.selector,a);return this.excludeHidden?b.filter(function(a){return!T.isHidden(a)}):b},o.prototype.runChecks=function(a,b,c,d){"use strict";var e=this,f=T.queue();this[a].forEach(function(a){var d=e._audit.checks[a.id||a],g=T.getCheckOption(d,e.id,c);f.defer(function(a){d.run(b,g,a)})}),f.then(function(b){b=b.filter(function(a){return a}),d({type:a,results:b})})},o.prototype.run=function(a,b,c){"use strict";var d,e=this.gather(a),f=T.queue(),g=this;d=new n(this),e.forEach(function(a){g.matches(a)&&f.defer(function(c){var e=T.queue();e.defer(function(c){g.runChecks("any",a,b,c)}),e.defer(function(c){g.runChecks("all",a,b,c)}),e.defer(function(c){g.runChecks("none",a,b,c)}),e.then(function(b){if(b.length){var e=!1,f={node:new T.DqElement(a)};b.forEach(function(a){var b=a.results.filter(function(a){return a});f[a.type]=b,b.length&&(e=!0)}),e&&d.nodes.push(f)}c()})})}),f.then(function(){c(d)})},o.prototype.after=function(a,b){"use strict";var c=p(this),d=this.id;return c.forEach(function(c){var e=q(a.nodes,c.id),f=T.getCheckOption(c,d,b),g=c.after(e,f);e.forEach(function(a){-1===g.indexOf(a)&&(a.filtered=!0)})}),a.nodes=s(a),a},t.prototype.run=function(a,b,c){"use strict";b="undefined"==typeof b?this.options:b,this.active=!0,this._run(a,b,c)},t.prototype.cleanup=function(a){"use strict";this.active=!1,this._cleanup(a)},S.constants={},S.constants.result={PASS:"PASS",FAIL:"FAIL",NA:"NA"},S.constants.raisedMetadata={impact:["minor","moderate","serious","critical"]},S.version="dev",a.axe=S,S.log=function(){"use strict";"object"==typeof console&&console.log&&Function.prototype.apply.call(console.log,console,arguments)},S.cleanup=u,S.configure=function(a){"use strict";var b=S._audit;if(!b)throw new Error("No audit configured");a.reporter&&("function"==typeof a.reporter||W[a.reporter])&&(b.reporter=a.reporter),a.checks&&a.checks.forEach(function(a){b.addCheck(a)}),a.rules&&a.rules.forEach(function(a){b.addRule(a)}),a.tools&&a.tools.forEach(function(a){b.addTool(a)})},S.getRules=function(a){"use strict";a=a||[];var b=a.length?S._audit.rules.filter(function(b){return!!a.filter(function(a){return-1!==b.tags.indexOf(a)}).length}):S._audit.rules,c=S._audit.data.rules||{};return b.map(function(a){var b=c[a.id]||{};return{ruleId:a.id,description:b.description,help:b.help,helpUrl:b.helpUrl,tags:a.tags}})},S._load=function(a){"use strict";T.respondable.subscribe("axe.ping",function(a,b){b({axe:!0})}),T.respondable.subscribe("axe.start",v),S._audit=new f(a)};var V,W={};S.reporter=function(a,b,c){"use strict";W[a]=b,c&&(V=b)},S.a11yCheck=function(a,b,c){"use strict";"function"==typeof b&&(c=b,b={}),b&&"object"==typeof b||(b={});var d=S._audit;if(!d)throw new Error("No audit configured");var e=w(b.reporter||d.reporter);x(a,b,function(a){e(a,c)})},S.tool=y,U.failureSummary=function(a){"use strict";var b={};return b.none=a.none.concat(a.all),b.any=a.any,Object.keys(b).map(function(a){return b[a].length?S._audit.data.failureSummaries[a].failureMessage(b[a].map(function(a){return a.message||""})):void 0}).filter(function(a){return void 0!==a}).join("\n\n")},U.formatCheck=function(a){"use strict";return{id:a.id,impact:a.impact,message:a.message,data:a.data,relatedNodes:a.relatedNodes.map(U.formatNode)}},U.formatChecks=function(a,b){"use strict";return a.any=b.any.map(U.formatCheck),a.all=b.all.map(U.formatCheck),a.none=b.none.map(U.formatCheck),a},U.formatNode=function(a){"use strict";return{target:a?a.selector:null,html:a?a.source:null}},U.formatRuleResult=function(a){"use strict";return{id:a.id,description:a.description,help:a.help,helpUrl:a.helpUrl||null,impact:null,tags:a.tags,nodes:[]}},U.splitResultsWithChecks=function(a){"use strict";return U.splitResults(a,U.formatChecks)},U.splitResults=function(b,c){"use strict";var d=[],e=[];return b.forEach(function(a){function b(b){var d=b.result||a.result,e=U.formatNode(b.node);return e.impact=b.impact||null,c(e,b,d)}var f,g=U.formatRuleResult(a);f=T.clone(g),f.impact=a.impact||null,f.nodes=a.violations.map(b),g.nodes=a.passes.map(b),f.nodes.length&&d.push(f),g.nodes.length&&e.push(g)}),{violations:d,passes:e,url:a.location.href,timestamp:new Date}},S.reporter("na",function(a,b){"use strict";var c=a.filter(function(a){return 0===a.violations.length&&0===a.passes.length}).map(U.formatRuleResult),d=U.splitResultsWithChecks(a);b({violations:d.violations,passes:d.passes,notApplicable:c,timestamp:d.timestamp,url:d.url})}),S.reporter("no-passes",function(a,b){"use strict";var c=U.splitResultsWithChecks(a);b({violations:c.violations,timestamp:c.timestamp,url:c.url})}),S.reporter("raw",function(a,b){"use strict";b(a)}),S.reporter("v1",function(a,b){"use strict";var c=U.splitResults(a,function(a,b,c){return c===S.constants.result.FAIL&&(a.failureSummary=U.failureSummary(b)),a});b({violations:c.violations,passes:c.passes,timestamp:c.timestamp,url:c.url})}),S.reporter("v2",function(a,b){"use strict";var c=U.splitResultsWithChecks(a);b({violations:c.violations,passes:c.passes,timestamp:c.timestamp,url:c.url})},!0),T.checkHelper=function(a,b){"use strict";return{isAsync:!1,async:function(){return this.isAsync=!0,function(c){a.value=c,b(a)}},data:function(b){a.data=b},relatedNodes:function(b){b=b instanceof Node?[b]:T.toArray(b),a.relatedNodes=b.map(function(a){return new T.DqElement(a)})}}},T.sendCommandToFrame=function(a,b,c){"use strict";var d=a.contentWindow;if(!d)return S.log("Frame does not have a content window",a),c({});var e=setTimeout(function(){e=setTimeout(function(){S.log("No response from frame: ",a),c(null)},0)},500);T.respondable(d,"axe.ping",null,function(){clearTimeout(e),e=setTimeout(function(){S.log("Error returning results from frame: ",a),c({}),c=null},3e4),T.respondable(d,"axe.start",b,function(a){c&&(clearTimeout(e),c(a))})})},T.collectResultsFromFrames=function(a,b,c,d,e){"use strict";function f(e){var f={options:b,command:c,parameter:d,context:{initiator:!1,page:a.page,include:e.include||[],exclude:e.exclude||[]}};g.defer(function(a){var b=e.node;T.sendCommandToFrame(b,f,function(c){return c?a({results:c,frameElement:b,frame:T.getSelector(b)}):void a(null)})})}for(var g=T.queue(),h=a.frames,i=0,j=h.length;j>i;i++)f(h[i]);g.then(function(a){e(T.mergeResults(a))})},T.contains=function(a,b){"use strict";return"function"==typeof a.contains?a.contains(b):!!(16&a.compareDocumentPosition(b))},B.prototype.toJSON=function(){"use strict";return{selector:this.selector,source:this.source}},T.DqElement=B,T.extendBlacklist=function(a,b,c){"use strict";c=c||[];for(var d in b)b.hasOwnProperty(d)&&-1===c.indexOf(d)&&(a[d]=b[d]);return a},T.extendMetaData=function(a,b){"use strict";for(var c in b)if(b.hasOwnProperty(c))if("function"==typeof b[c])try{a[c]=b[c](a)}catch(d){a[c]=null}else a[c]=b[c]},T.getFailingChecks=function(a){"use strict";var b=a.any.filter(function(a){return!a.result});return{all:a.all.filter(function(a){return!a.result}),any:b.length===a.any.length?b:[],none:a.none.filter(function(a){return!!a.result})}},T.finalizeRuleResult=function(a){"use strict";return T.publishMetaData(a),E(a)},T.findBy=function(a,b,c){"use strict";a=a||[];var d,e;for(d=0,e=a.length;e>d;d++)if(a[d][b]===c)return a[d]},T.getAllChecks=function(a){"use strict";var b=[];return b.concat(a.any||[]).concat(a.all||[]).concat(a.none||[])},T.getCheckOption=function(a,b,c){"use strict";var d=((c.rules&&c.rules[b]||{}).checks||{})[a.id],e=(c.checks||{})[a.id],f=a.enabled,g=a.options;return e&&(e.hasOwnProperty("enabled")&&(f=e.enabled),e.hasOwnProperty("options")&&(g=e.options)),d&&(d.hasOwnProperty("enabled")&&(f=d.enabled),d.hasOwnProperty("options")&&(g=d.options)),{enabled:f,options:g}},T.getSelector=function(a){"use strict";function c(a){return T.escapeSelector(a)}for(var d,e=[];a.parentNode;){if(d="",a.id&&1===b.querySelectorAll("#"+T.escapeSelector(a.id)).length){e.unshift("#"+T.escapeSelector(a.id));break}if(a.className&&"string"==typeof a.className&&(d="."+a.className.trim().split(/\s+/).map(c).join("."),("."===d||G(a,d))&&(d="")),!d){if(d=T.escapeSelector(a.nodeName).toLowerCase(),"html"===d||"body"===d){e.unshift(d);break}G(a,d)&&(d+=":nth-of-type("+F(a)+")")}e.unshift(d),a=a.parentNode}return e.join(" > ")};var X;T.isHidden=function(b,c){"use strict";if(9===b.nodeType)return!1;var d=a.getComputedStyle(b,null);return d&&b.parentNode&&"none"!==d.getPropertyValue("display")&&(c||"hidden"!==d.getPropertyValue("visibility"))&&"true"!==b.getAttribute("aria-hidden")?T.isHidden(b.parentNode,!0):!0},T.mergeResults=function(a){"use strict";var b=[];return a.forEach(function(a){var c=K(a);c&&c.length&&c.forEach(function(c){c.nodes&&a.frame&&I(c.nodes,a.frameElement,a.frame);var d=T.findBy(b,"id",c.id);d?c.nodes.length&&J(d.nodes,c.nodes):b.push(c)})}),b},T.nodeSorter=function(a,b){"use strict";return a===b?0:4&a.compareDocumentPosition(b)?-1:1},T.publishMetaData=function(a){"use strict";function b(a){return function(b){var d=c[b.id]||{},e=d.messages||{},f=T.extendBlacklist({},d,["messages"]);f.message=b.result===a?e.pass:e.fail,T.extendMetaData(b,f)}}var c=S._audit.data.checks||{},d=S._audit.data.rules||{},e=T.findBy(S._audit.rules,"id",a.id)||{};a.tags=T.clone(e.tags||[]);var f=b(!0),g=b(!1);a.nodes.forEach(function(a){a.any.forEach(f),a.all.forEach(f),a.none.forEach(g)}),T.extendMetaData(a,T.clone(d[a.id]||{}))},function(){"use strict";function a(){}function b(){function b(){for(var a=e.length;a>f;f++){var b=e[f],d=b.shift();b.push(c(f)),d.apply(null,b)}}function c(a){return function(b){e[a]=b,--g||d()}}function d(){h(e)}var e=[],f=0,g=0,h=a;return{defer:function(a){e.push([a]),++g,b()},then:function(a){h=a,g||d()},abort:function(b){h=a,b(e)}}}T.queue=b}(),function(b){"use strict";function c(a){return"object"==typeof a&&"string"==typeof a.uuid&&a._respondable===!0}function d(a,b,c,d,e){var f={uuid:d,topic:b,message:c,_respondable:!0};h[d]=e,a.postMessage(JSON.stringify(f),"*")}function e(a,b,c,e){var f=O.v1();d(a,b,c,f,e)}function f(a,b){var c=b.topic,d=b.message,e=i[c];e&&e(d,g(a.source,null,b.uuid))}function g(a,b,c){return function(e,f){d(a,b,e,c,f)}}var h={},i={};e.subscribe=function(a,b){i[a]=b},a.addEventListener("message",function(a){if("string"==typeof a.data){var b;try{b=JSON.parse(a.data)}catch(d){}if(c(b)){var e=b.uuid;h[e]&&(h[e](b.message,g(a.source,b.topic,e)),h[e]=null),f(a,b)}}},!1),b.respondable=e}(T),T.ruleShouldRun=function(a,b,c){"use strict";if(a.pageLevel&&!b.page)return!1;var d=c.runOnly,e=(c.rules||{})[a.id];return d?"rule"===d.type?-1!==d.values.indexOf(a.id):!!(d.values||[]).filter(function(b){return-1!==a.tags.indexOf(b)}).length:(e&&e.hasOwnProperty("enabled")?e.enabled:a.enabled)?!0:!1},T.select=function(a,b){"use strict";for(var c,d=[],e=0,f=b.include.length;f>e;e++)c=b.include[e],c.nodeType===c.ELEMENT_NODE&&T.matchesSelector(c,a)&&N(d,[c],b),N(d,c.querySelectorAll(a),b);return d.sort(T.nodeSorter)},T.toArray=function(a){"use strict";return Array.prototype.slice.call(a)},S._load({data:{rules:{accesskeys:{description:"Ensures every accesskey attribute value is unique",help:"accesskey attribute value must be unique",helpUrl:"https://dequeuniversity.com/rules/axe/1.1/accesskeys"},"area-alt":{description:"Ensures elements of image maps have alternate text",help:"Active elements must have alternate text",helpUrl:"https://dequeuniversity.com/rules/axe/1.1/area-alt"},"aria-allowed-attr":{description:"Ensures ARIA attributes are allowed for an element's role",help:"Elements must only use allowed ARIA attributes",helpUrl:"https://dequeuniversity.com/rules/axe/1.1/aria-allowed-attr"},"aria-required-attr":{description:"Ensures elements with ARIA roles have all required ARIA attributes",help:"Required ARIA attributes must be provided",helpUrl:"https://dequeuniversity.com/rules/axe/1.1/aria-required-attr"},"aria-required-children":{description:"Ensures elements with an ARIA role that require child roles contain them",help:"Certain ARIA roles must contain particular children",helpUrl:"https://dequeuniversity.com/rules/axe/1.1/aria-required-children"},"aria-required-parent":{description:"Ensures elements with an ARIA role that require parent roles are contained by them",help:"Certain ARIA roles must be contained by particular parents",helpUrl:"https://dequeuniversity.com/rules/axe/1.1/aria-required-parent"},"aria-roles":{description:"Ensures all elements with a role attribute use a valid value",help:"ARIA roles used must conform to valid values",helpUrl:"https://dequeuniversity.com/rules/axe/1.1/aria-roles"},"aria-valid-attr-value":{description:"Ensures all ARIA attributes have valid values",help:"ARIA attributes must conform to valid values",helpUrl:"https://dequeuniversity.com/rules/axe/1.1/aria-valid-attr-value"},"aria-valid-attr":{description:"Ensures attributes that begin with aria- are valid ARIA attributes",help:"ARIA attributes must conform to valid names",helpUrl:"https://dequeuniversity.com/rules/axe/1.1/aria-valid-attr"},"audio-caption":{description:"Ensures elements have captions",help:" elements must have a captions track",helpUrl:"https://dequeuniversity.com/rules/axe/1.1/audio-caption"},blink:{description:"Ensures elements are not used",help:" elements are deprecated and must not be used",helpUrl:"https://dequeuniversity.com/rules/axe/1.1/blink"},"button-name":{description:"Ensures buttons have discernible text",help:"Buttons must have discernible text",helpUrl:"https://dequeuniversity.com/rules/axe/1.1/button-name"},bypass:{description:"Ensures each page has at least one mechanism for a user to bypass navigation and jump straight to the content",help:"Page must have means to bypass repeated blocks",helpUrl:"https://dequeuniversity.com/rules/axe/1.1/bypass"},checkboxgroup:{description:'Ensures related elements have a group and that that group designation is consistent',help:"Checkbox inputs with the same name attribute value must be part of a group",helpUrl:"https://dequeuniversity.com/rules/axe/1.1/checkboxgroup"},"color-contrast":{description:"Ensures the contrast between foreground and background colors meets WCAG 2 AA contrast ratio thresholds",help:"Elements must have sufficient color contrast",helpUrl:"https://dequeuniversity.com/rules/axe/1.1/color-contrast"},"data-table":{description:"Ensures data tables are marked up semantically and have the correct header structure",help:"Data tables should be marked up properly",helpUrl:"https://dequeuniversity.com/rules/axe/1.1/data-table"},"definition-list":{description:"Ensures elements are structured correctly",help:" elements must only directly contain properly-ordered and groups, "
if (encoding == "gzip" || encoding == "deflate") {
- console.warn("PROXY content is encoded to " + encoding);
+ this._log.debug("PROXY content is encoded to " + encoding);
var uncompress = (zlib).Gunzip();
if (encoding == "deflate")
uncompress = (zlib).Inflate();
@@ -430,7 +431,7 @@ export module VORLON {
//we must set cookie only if url was requested through Vorlon
if (req.query.vorlonproxytarget) {
- console.log("set cookie " + req.query.vorlonproxytarget);
+ _proxy._log.debug("set cookie " + req.query.vorlonproxytarget);
res.cookie(_proxy._proxyCookieName, req.query.vorlonproxytarget);
res.cookie(_proxy._proxySessionCookieName, vorlonsessionid);
}
@@ -479,7 +480,7 @@ export module VORLON {
res.header('X-VorlonProxyEncoding', encoding || "none");
//we must set cookie only if url was requested through Vorlon
if (req.query.vorlonproxytarget) {
- console.log("set cookie " + req.query.vorlonproxytarget);
+ _proxy._log.debug("set cookie " + req.query.vorlonproxytarget);
res.cookie(_proxy._proxyCookieName, req.query.vorlonproxytarget);
}
diff --git a/Server/Scripts/vorlon.server.ts b/Server/Scripts/vorlon.server.ts
index dcb5b06f..f54d86db 100644
--- a/Server/Scripts/vorlon.server.ts
+++ b/Server/Scripts/vorlon.server.ts
@@ -1,246 +1,165 @@
import redis = require("redis");
import express = require("express");
-import winston = require("winston");
import http = require("http");
import socketio = require("socket.io");
import fs = require("fs");
import path = require("path");
-var fakeredis = require("fakeredis");
-
-var winstonDisplay = require("winston-logs-display");
-import redisConfigImport = require("../config/vorlon.redisconfig");
-var redisConfig = redisConfigImport.VORLON.RedisConfig;
-import httpConfig = require("../config/vorlon.httpconfig");
-import logConfig = require("../config/vorlon.logconfig");
-import baseURLConfig = require("../config/vorlon.baseurlconfig");
//Vorlon
import iwsc = require("./vorlon.IWebServerComponent");
import tools = require("./vorlon.tools");
+import vorloncontext = require("../config/vorlon.servercontext");
export module VORLON {
export class Server implements iwsc.VORLON.IWebServerComponent {
- public sessions = new Array();
+ private _sessions: vorloncontext.VORLON.SessionManager;
public dashboards = new Array();
private _io: any;
- private _redisApi: any;
- private _log: winston.LoggerInstance;
- private http: httpConfig.VORLON.HttpConfig;
- private logConfig: logConfig.VORLON.LogConfig;
- private baseURLConfig: baseURLConfig.VORLON.BaseURLConfig;
-
- constructor() {
- this.logConfig = new logConfig.VORLON.LogConfig();
- this.baseURLConfig = new baseURLConfig.VORLON.BaseURLConfig();
-
- //LOGS
- winston.cli();
- this._log = new winston.Logger({
- levels: {
- info: 0,
- warn: 1,
- error: 2,
- verbose: 3,
- api: 4,
- dashboard: 5,
- plugin: 6
- },
- transports: [
- new winston.transports.File({ filename: this.logConfig.vorlonLogFile, level: this.logConfig.level})
- ],
- exceptionHandlers: [
- new winston.transports.File({ filename: this.logConfig.exceptionsLogFile, timestamp: true, maxsize: 1000000 })
- ],
- exitOnError: false
- });
-
- if (this.logConfig.enableConsole) {
- this._log.add(winston.transports.Console, {
- level: this.logConfig.level,
- handleExceptions: true,
- json: false,
- timestamp: function() {
- var date:Date = new Date();
- return date.getFullYear() + "-" +
- date.getMonth() + "-" +
- date.getDate() + " " +
- date.getHours() + ":" +
- date.getMinutes() + ":" +
- date.getSeconds();
- },
- colorize: true
- });
- }
-
- winston.addColors({
- info: 'green',
- warn: 'cyan',
- error: 'red',
- verbose: 'blue',
- api: 'gray',
- dashboard: 'pink',
- plugin: 'yellow'
- });
-
- this._log.cli();
-
- //Redis
- if (redisConfig.fackredis === true) {
- this._redisApi = fakeredis.createClient();
- }
- else {
- this._redisApi = redis.createClient(redisConfig._redisPort, redisConfig._redisMachine);
- this._redisApi.auth(redisConfig._redisPassword,(err) => {
- if (err) { throw err; }
- });
- }
- //SSL
- this.http = new httpConfig.VORLON.HttpConfig();
+ private _log: vorloncontext.VORLON.ILogger;
+ private httpConfig: vorloncontext.VORLON.IHttpConfig;
+ private pluginsConfig: vorloncontext.VORLON.IPluginsProvider;
+ private baseURLConfig: vorloncontext.VORLON.IBaseURLConfig;
+
+ constructor(context: vorloncontext.VORLON.IVorlonServerContext) {
+ this.baseURLConfig = context.baseURLConfig;
+ this.httpConfig = context.httpConfig;
+ this.pluginsConfig = context.plugins;
+ this._log = context.logger;
+ this._sessions = context.sessions;
+ }
+
+ public noCache(res:any){
+ //Add header no-cache
+ res.header('Cache-Control', 'private, no-cache, no-store, must-revalidate');
+ res.header('Expires', '-1');
+ res.header('Pragma', 'no-cache');
}
public addRoutes(app: express.Express, passport: any): void {
- app.get(this.baseURLConfig.baseURL + "/api/createsession",(req: any, res: any) => {
+ app.get(this.baseURLConfig.baseURL + "/api/createsession", (req: any, res: any) => {
this.json(res, this.guid());
});
- app.get(this.baseURLConfig.baseURL + "/api/reset/:idSession",(req: any, res: any) => {
- var session = this.sessions[req.params.idSession];
+ app.get(this.baseURLConfig.baseURL + "/api/reset/:idSession", (req: any, res: any) => {
+ var session = this._sessions.get(req.params.idSession);
if (session && session.connectedClients) {
for (var client in session.connectedClients) {
delete session.connectedClients[client];
}
}
- delete this.sessions[req.params.idSession];
+ this._sessions.remove(req.params.idSession);
+
+ this.noCache(res);
res.writeHead(200, {});
- res.end();
+ res.end();
});
- app.get(this.baseURLConfig.baseURL + "/api/getclients/:idSession",(req: any, res: any) => {
- var session = this.sessions[req.params.idSession];
+ app.get(this.baseURLConfig.baseURL + "/api/getclients/:idSession", (req: any, res: any) => {
+ var session = this._sessions.get(req.params.idSession);
var clients = new Array();
if (session != null) {
var nbClients = 0;
for (var client in session.connectedClients) {
var currentclient = session.connectedClients[client];
if (currentclient.opened) {
- var name = tools.VORLON.Tools.GetOperatingSystem(currentclient.ua);
clients.push(currentclient.data);
nbClients++;
}
}
- this._log.info("API : GetClients nb client " + nbClients + " in session " + req.params.idSession, { type: "API", session: req.params.idSession });
+ this._sessions.update(req.params.idSession, session);
+ this._log.debug("API : GetClients nb client " + nbClients + " in session " + req.params.idSession, { type: "API", session: req.params.idSession });
}
else {
this._log.warn("API : No client in session " + req.params.idSession, { type: "API", session: req.params.idSession });
}
- //Add header no-cache
- res.header('Cache-Control', 'private, no-cache, no-store, must-revalidate');
- res.header('Expires', '-1');
- res.header('Pragma', 'no-cache');
+
+ this.noCache(res);
this.json(res, clients);
});
- app.get(this.baseURLConfig.baseURL + "/api/range/:idsession/:idplugin/:from/:to",(req: any, res: any) => {
- this._redisApi.lrange(req.params.idsession + req.params.idplugin, req.params.from, req.params.to,(err: any, reply: any) => {
- this._log.info("API : Get Range data from : " + req.params.from + " to " + req.params.to + " = " + reply, { type: "API", session: req.params.idsession });
- this.json(res, reply);
- });
- });
-
- app.post(this.baseURLConfig.baseURL + "/api/push",(req: any, res: any) => {
- var receiveMessage = req.body;
- this._log.info("API : Receve data to log : " + JSON.stringify(req.body), { type: "API", session: receiveMessage._idsession });
- this._redisApi.rpush([receiveMessage._idsession + receiveMessage.id, receiveMessage.message], err => {
- if (err) {
- this._log.error("API : Error data log : " + err, { type: "API", session: receiveMessage._idsession });
- } else {
- this._log.info("API : Push data ok", { type: "API", session: receiveMessage._idsession });
- }
- });
- this.json(res, {});
- });
-
- app.get(this.baseURLConfig.baseURL + "/vorlon.max.js/",(req: any, res: any) => {
+ app.get(this.baseURLConfig.baseURL + "/vorlon.max.js/", (req: any, res: any) => {
res.redirect("/vorlon.max.js/default");
});
- app.get(this.baseURLConfig.baseURL + "/vorlon.max.js/:idsession",(req: any, res: any) => {
+ app.get(this.baseURLConfig.baseURL + "/vorlon.max.js/:idsession", (req: any, res: any) => {
this._sendVorlonJSFile(false, req, res);
});
- app.get(this.baseURLConfig.baseURL + "/vorlon.js",(req: any, res: any) => {
+ app.get(this.baseURLConfig.baseURL + "/vorlon.js", (req: any, res: any) => {
res.redirect(this.baseURLConfig.baseURL + "/vorlon.js/default");
});
- app.get(this.baseURLConfig.baseURL + "/vorlon.js/:idsession",(req: any, res: any) => {
+ app.get(this.baseURLConfig.baseURL + "/vorlon.js/:idsession", (req: any, res: any) => {
this._sendVorlonJSFile(true, req, res);
});
- app.get(this.baseURLConfig.baseURL + "/vorlon.max.autostartdisabled.js",(req: any, res: any) => {
+ app.get(this.baseURLConfig.baseURL + "/vorlon.max.autostartdisabled.js", (req: any, res: any) => {
this._sendVorlonJSFile(false, req, res, false);
});
- app.get(this.baseURLConfig.baseURL + "/vorlon.autostartdisabled.js",(req: any, res: any) => {
+ app.get(this.baseURLConfig.baseURL + "/vorlon.autostartdisabled.js", (req: any, res: any) => {
this._sendVorlonJSFile(true, req, res, false);
});
-
- app.get(this.baseURLConfig.baseURL + "/config.json",(req: any, res: any) => {
+
+ app.get(this.baseURLConfig.baseURL + "/getplugins/:idsession", (req: any, res: any) => {
this._sendConfigJson(req, res);
});
+
+ app.get(this.baseURLConfig.baseURL + "/vorlon.node.max.js/", (req: any, res: any) => {
+ res.redirect("/vorlon.node.max.js/default");
+ });
+
+ app.get(this.baseURLConfig.baseURL + "/vorlon.node.max.js/:idsession", (req: any, res: any) => {
+ this._sendVorlonJSFile(false, req, res, false, true);
+ });
+
+ app.get(this.baseURLConfig.baseURL + "/vorlon.node.js/", (req: any, res: any) => {
+ res.redirect("/vorlon.node.js/default");
+ });
- //DisplayLogs
- winstonDisplay(app, this._log);
+ app.get(this.baseURLConfig.baseURL + "/vorlon.node.js/:idsession", (req: any, res: any) => {
+ this._sendVorlonJSFile(true, req, res, false, true);
+ });
}
-
+
private _sendConfigJson(req: any, res: any) {
-
- fs.readFile(path.join(__dirname, "../config.json"), "utf8",(err, catalogdata) => {
+
+ var sessionid = req.params.idsession || "default";
+ this.pluginsConfig.getPluginsFor(sessionid, (err, catalog) => {
if (err) {
this._log.error("ROUTE : Error reading config.json file");
return;
}
-
- var catalog = JSON.parse(catalogdata.replace(/^\uFEFF/, ''));
-
- //remove auth data to not send username and password outside ;)
- if(catalog.activateAuth){
- delete catalog.activateAuth;
- }
- if(catalog.username){
- delete catalog.username;
- }
- if(catalog.password){
- delete catalog.password;
- }
-
- catalogdata = JSON.stringify(catalog);
+
+
+ var catalogdata = JSON.stringify(catalog);
res.header('Content-Type', 'application/json');
res.send(catalogdata);
});
}
- private _sendVorlonJSFile(ismin: boolean, req: any, res: any, autostart: boolean = true) {
- //Read Socket.io file
+ private _sendVorlonJSFile(ismin: boolean, req: any, res: any, autostart: boolean = true, nodeOnly = false) {
var javascriptFile: string;
-
- fs.readFile(path.join(__dirname, "../config.json"), "utf8",(err, catalogdata) => {
+ var sessionid = req.params.idsession || "default";
+
+ this.pluginsConfig.getPluginsFor(sessionid, (err, catalog) => {
if (err) {
- this._log.error("ROUTE : Error reading config.json");
+ this._log.error("ROUTE : Error getting plugins");
return;
}
- var configstring = catalogdata.toString().replace(/^\uFEFF/, '');
var baseUrl = this.baseURLConfig.baseURL;
- var catalog = JSON.parse(configstring);
var vorlonpluginfiles: string = "";
var javascriptFile: string = "";
-
+
javascriptFile += 'var vorlonBaseURL="' + baseUrl + '";\n';
//read the socket.io file if needed
- if (catalog.includeSocketIO) {
- javascriptFile += fs.readFileSync(path.join(__dirname, "../public/javascripts/socket.io-1.3.6.js"));
+ if (nodeOnly) {
+ javascriptFile += "var io = require('socket.io-client');\n"
+ } else if (catalog.includeSocketIO) {
+ javascriptFile += fs.readFileSync(path.join(__dirname, "../public/javascripts/socket.io-1.4.3.js"));
}
if (ismin) {
@@ -252,7 +171,10 @@ export module VORLON {
for (var pluginid = 0; pluginid < catalog.plugins.length; pluginid++) {
var plugin = catalog.plugins[pluginid];
- if (plugin && plugin.enabled){
+ if (plugin && plugin.enabled) {
+ if (nodeOnly && !plugin.nodeCompliant) {
+ continue;
+ }
//Read Vorlon.js file
if (ismin) {
vorlonpluginfiles += fs.readFileSync(path.join(__dirname, "../public/vorlon/plugins/" + plugin.foldername + "/vorlon." + plugin.foldername + ".client.min.js"));
@@ -263,11 +185,14 @@ export module VORLON {
}
}
- vorlonpluginfiles = vorlonpluginfiles.replace('"vorlon/plugins"', '"' + this.http.protocol + '://' + req.headers.host + baseUrl + '/vorlon/plugins"');
+ vorlonpluginfiles = vorlonpluginfiles.replace('"vorlon/plugins"', '"' + this.httpConfig.protocol + '://' + req.headers.host + baseUrl + '/vorlon/plugins"');
javascriptFile += "\r" + vorlonpluginfiles;
+ javascriptFile += "if (((typeof window != 'undefined' && window.module) || (typeof module != 'undefined')) && typeof module.exports != 'undefined') {\r\n";
+ javascriptFile += "module.exports = VORLON;};\r\n";
+
if (autostart) {
- javascriptFile += "\r (function() { VORLON.Core.StartClientSide('" + this.http.protocol + "://" + req.headers.host + "/', '" + req.params.idsession + "'); }());";
+ javascriptFile += "\r (function() { VORLON.Core.StartClientSide('" + this.httpConfig.protocol + "://" + req.headers.host + "/', '" + req.params.idsession + "'); }());";
}
res.header('Content-Type', 'application/javascript');
@@ -280,16 +205,6 @@ export module VORLON {
var io = socketio(httpServer);
this._io = io;
- //Redis
- var redisConfig = redisConfigImport.VORLON.RedisConfig;
- if (redisConfig.fackredis === false) {
- var pub = redis.createClient(redisConfig._redisPort, redisConfig._redisMachine);
- pub.auth(redisConfig._redisPassword);
- var sub = redis.createClient(redisConfig._redisPort, redisConfig._redisMachine);
- sub.auth(redisConfig._redisPassword);
- var socketredis = require("socket.io-redis");
- io.adapter(socketredis({ pubClient: pub, subClient: sub }));
- }
//Listen on /
io.on("connection", socket => {
this.addClient(socket);
@@ -299,8 +214,8 @@ export module VORLON {
var dashboardio = io
.of("/dashboard")
.on("connection", socket => {
- this.addDashboard(socket);
- });
+ this.addDashboard(socket);
+ });
}
public get io(): any {
@@ -327,69 +242,72 @@ export module VORLON {
res.end();
}
-
+
public addClient(socket: SocketIO.Socket): void {
- socket.on("helo",(message: string) => {
+ socket.on("helo", (message: string) => {
var receiveMessage = JSON.parse(message);
var metadata = receiveMessage.metadata;
var data = receiveMessage.data;
- var session = this.sessions[metadata.sessionId];
+ var session = this._sessions.get(metadata.sessionId);
if (session == null) {
- session = new Session();
- this.sessions[metadata.sessionId] = session;
+ session = new vorloncontext.VORLON.Session();
+ this._sessions.add(metadata.sessionId, session);
}
- var client = session.connectedClients[metadata.clientId];
+ var client = session.connectedClients[metadata.clientId];
var dashboard = this.dashboards[metadata.sessionId];
if (client == undefined) {
- var client = new Client(metadata.clientId, data.ua, socket, ++session.nbClients);
+ var client = new vorloncontext.VORLON.Client(metadata.clientId, data.ua, data.noWindow, socket, ++session.nbClients);
+ client.identity = data.identity;
session.connectedClients[metadata.clientId] = client;
- this._log.info(formatLog("PLUGIN", "Send Add Client to dashboard (" + client.displayId + ")[" + data.ua + "] socketid = " + socket.id, receiveMessage));
+ this._log.debug(formatLog("PLUGIN", "Send Add Client to dashboard (" + client.displayId + ")[" + data.ua + "] socketid = " + socket.id, receiveMessage));
if (dashboard != undefined) {
dashboard.emit("addclient", client.data);
}
- this._log.info(formatLog("PLUGIN", "New client (" + client.displayId + ")[" + data.ua + "] socketid = " + socket.id, receiveMessage));
+ this._log.debug(formatLog("PLUGIN", "New client (" + client.displayId + ")[" + data.ua + "] socketid = " + socket.id, receiveMessage));
}
else {
client.socket = socket;
client.opened = true;
+ client.identity = data.identity;
if (dashboard != undefined) {
dashboard.emit("addclient", client.data);
}
- this._log.info(formatLog("PLUGIN", "Client Reconnect (" + client.displayId + ")[" + data.ua + "] socketid=" + socket.id, receiveMessage));
+ this._log.debug(formatLog("PLUGIN", "Client Reconnect (" + client.displayId + ")[" + data.ua + "] socketid=" + socket.id, receiveMessage));
}
+ this._sessions.update(metadata.sessionId, session);
- this._log.info(formatLog("PLUGIN", "Number clients in session : " + (session.nbClients + 1), receiveMessage));
+ this._log.debug(formatLog("PLUGIN", "Number clients in session : " + (session.nbClients + 1), receiveMessage));
//If dashboard already connected to this socket send "helo" else wait
if ((metadata.clientId != "") && (metadata.clientId == session.currentClientId)) {
- this._log.info(formatLog("PLUGIN", "Send helo to client to open socket : " + metadata.clientId, receiveMessage));
+ this._log.debug(formatLog("PLUGIN", "Send helo to client to open socket : " + metadata.clientId, receiveMessage));
//socket.emit("helo", metadata.clientId);
}
else {
- this._log.info(formatLog("PLUGIN", "New client (" + client.displayId + ") wait...", receiveMessage));
+ this._log.debug(formatLog("PLUGIN", "New client (" + client.displayId + ") wait...", receiveMessage));
}
});
- socket.on("message",(message: string) => {
+ socket.on("message", (message: string) => {
//this._log.warn("CLIENT message " + message);
var receiveMessage = JSON.parse(message);
var dashboard = this.dashboards[receiveMessage.metadata.sessionId];
if (dashboard != null) {
- var session = this.sessions[receiveMessage.metadata.sessionId];
+ var session = this._sessions.get(receiveMessage.metadata.sessionId);
if (receiveMessage.metadata.clientId === "") {
//No broadcast id _clientID ===""
//this.dashboards[receiveMessage._sessionId].emit("message", message);
//***
- //this._log.info("PLUGIN : " + receiveMessage._pluginID + " message receive without clientId sent to dashboard for session id :" + receiveMessage._sessionId, { type: "PLUGIN", session: receiveMessage._sessionId });
+ //this._log.debug("PLUGIN : " + receiveMessage._pluginID + " message receive without clientId sent to dashboard for session id :" + receiveMessage._sessionId, { type: "PLUGIN", session: receiveMessage._sessionId });
}
else {
//Send message if _clientID = clientID selected by dashboard
if (session && receiveMessage.metadata.clientId === session.currentClientId) {
dashboard.emit("message", message);
- this._log.info(formatLog("PLUGIN", "PLUGIN=>DASHBOARD", receiveMessage));
+ this._log.debug(formatLog("PLUGIN", "PLUGIN=>DASHBOARD", receiveMessage));
}
else {
this._log.error(formatLog("PLUGIN", "must be disconnected", receiveMessage));
@@ -401,38 +319,40 @@ export module VORLON {
}
});
- socket.on("clientclosed",(message: string) => {
- //this._log.warn("CLIENT clientclosed " + message);
+ socket.on("clientclosed", (message: string) => {
+ this._log.warn("CLIENT clientclosed " + message);
var receiveMessage = JSON.parse(message);
- for (var session in this.sessions) {
- for (var client in this.sessions[session].connectedClients) {
- if (receiveMessage.data.socketid === this.sessions[session].connectedClients[client].socket.id) {
- this.sessions[session].connectedClients[client].opened = false;
- if (this.dashboards[session]) {
- this._log.info(formatLog("PLUGIN", "Send RemoveClient to Dashboard " + socket.id, receiveMessage));
- this.dashboards[session].emit("removeclient", this.sessions[session].connectedClients[client].data);
+ this._sessions.all().forEach((session) => {
+ for (var clientid in session.connectedClients) {
+ var client = session.connectedClients[clientid];
+ if ("/#" + receiveMessage.data.socketid === client.socket.id) {
+ client.opened = false;
+ if (this.dashboards[session.sessionId]) {
+ this._log.debug(formatLog("PLUGIN", "Send RemoveClient to Dashboard " + socket.id, receiveMessage));
+ this.dashboards[session.sessionId].emit("removeclient", client.data);
} else {
- this._log.info(formatLog("PLUGIN", "NOT sending RefreshClients, no Dashboard " + socket.id, receiveMessage));
+ this._log.debug(formatLog("PLUGIN", "NOT sending RefreshClients, no Dashboard " + socket.id, receiveMessage));
}
- this._log.info(formatLog("PLUGIN", "Client Close " + socket.id, receiveMessage));
+ this._log.debug(formatLog("PLUGIN", "Client Close " + socket.id, receiveMessage));
}
}
- }
+ this._sessions.update(session.sessionId, session);
+ });
});
}
public addDashboard(socket: SocketIO.Socket): void {
- socket.on("helo",(message: string) => {
+ socket.on("helo", (message: string) => {
//this._log.warn("DASHBOARD helo " + message);
var receiveMessage = JSON.parse(message);
var metadata = receiveMessage.metadata;
var dashboard = this.dashboards[metadata.sessionId];
if (dashboard == null) {
- this._log.info(formatLog("DASHBOARD", "New Dashboard", receiveMessage));
+ this._log.debug(formatLog("DASHBOARD", "New Dashboard", receiveMessage));
}
else {
- this._log.info(formatLog("DASHBOARD", "Reconnect", receiveMessage));
+ this._log.debug(formatLog("DASHBOARD", "Reconnect", receiveMessage));
}
this.dashboards[metadata.sessionId] = socket;
@@ -440,69 +360,75 @@ export module VORLON {
//if client listen by dashboard send helo to selected client
if (metadata.listenClientId !== "") {
- this._log.info(formatLog("DASHBOARD", "Client selected for :" + metadata.listenClientId, receiveMessage));
- var session = this.sessions[metadata.sessionId];
+ this._log.debug(formatLog("DASHBOARD", "Client selected for :" + metadata.listenClientId, receiveMessage));
+ var session = this._sessions.get(metadata.sessionId);
if (session != undefined) {
- this._log.info(formatLog("DASHBOARD", "Change currentClient " + metadata.clientId, receiveMessage));
+ this._log.debug(formatLog("DASHBOARD", "Change currentClient " + metadata.clientId, receiveMessage));
session.currentClientId = metadata.listenClientId;
for (var clientId in session.connectedClients) {
var client = session.connectedClients[clientId]
if (client.clientId === metadata.listenClientId) {
if (client.socket != null) {
- this._log.info(formatLog("DASHBOARD", "Send helo to socketid :" + client.socket.id, receiveMessage));
+ this._log.debug(formatLog("DASHBOARD", "Send helo to socketid :" + client.socket.id, receiveMessage));
client.socket.emit("helo", metadata.listenClientId);
}
}
else {
- this._log.info(formatLog("DASHBOARD", "Wait for socketid (" + client.socket.id + ")", receiveMessage));
+ this._log.debug(formatLog("DASHBOARD", "Wait for socketid (" + client.socket.id + ")", receiveMessage));
}
}
//Send Helo to DashBoard
- this._log.info(formatLog("DASHBOARD", "Send helo to Dashboard", receiveMessage));
+ this._log.debug(formatLog("DASHBOARD", "Send helo to Dashboard", receiveMessage));
socket.emit("helo", metadata.listenClientId);
}
}
else {
- this._log.info(formatLog("DASHBOARD", "No client selected for this dashboard"));
+ this._log.debug(formatLog("DASHBOARD", "No client selected for this dashboard"));
+ if (session != undefined) {
+ this._sessions.update(metadata.sessionId, session);
+ }
}
});
- socket.on("reload",(message: string) => {
+ socket.on("reload", (message: string) => {
//this._log.warn("DASHBOARD reload " + message);
var receiveMessage = JSON.parse(message);
var metadata = receiveMessage.metadata;
//if client listen by dashboard send reload to selected client
if (metadata.listenClientId !== "") {
- this._log.info(formatLog("DASHBOARD", "Client selected for :" + metadata.listenClientId, receiveMessage));
- var session = this.sessions[metadata.sessionId];
+ this._log.debug(formatLog("DASHBOARD", "Client selected for :" + metadata.listenClientId, receiveMessage));
+ var session = this._sessions.get(metadata.sessionId);
if (session != undefined) {
- this._log.info(formatLog("DASHBOARD", "Change currentClient " + metadata.clientId, receiveMessage));
+ this._log.debug(formatLog("DASHBOARD", "Change currentClient " + metadata.clientId, receiveMessage));
session.currentClientId = metadata.listenClientId;
for (var clientId in session.connectedClients) {
var client = session.connectedClients[clientId]
if (client.clientId === metadata.listenClientId) {
if (client.socket != null) {
- this._log.info(formatLog("DASHBOARD", "Send reload to socketid :" + client.socket.id, receiveMessage));
+ this._log.debug(formatLog("DASHBOARD", "Send reload to socketid :" + client.socket.id, receiveMessage));
client.socket.emit("reload", metadata.listenClientId);
-
+
}
}
else {
- this._log.info(formatLog("DASHBOARD", "Wait for socketid (" + client.socket.id + ")", receiveMessage));
+ this._log.debug(formatLog("DASHBOARD", "Wait for socketid (" + client.socket.id + ")", receiveMessage));
}
}
}
}
else {
- this._log.info(formatLog("DASHBOARD", "No client selected for this dashboard"));
+ this._log.debug(formatLog("DASHBOARD", "No client selected for this dashboard"));
+ if (session != undefined) {
+ this._sessions.update(metadata.sessionId, session);
+ }
}
});
- socket.on("protocol",(message: string) => {
+ socket.on("protocol", (message: string) => {
//this._log.warn("DASHBOARD protocol " + message);
var receiveMessage = JSON.parse(message);
var metadata = receiveMessage.metadata;
@@ -512,16 +438,16 @@ export module VORLON {
}
else {
dashboard.emit("message", message);
- this._log.info(formatLog("DASHBOARD", "Dashboard send message", receiveMessage));
+ this._log.debug(formatLog("DASHBOARD", "Dashboard send message", receiveMessage));
}
});
- socket.on("identify",(message: string) => {
+ socket.on("identify", (message: string) => {
//this._log.warn("DASHBOARD identify " + message);
var receiveMessage = JSON.parse(message);
var metadata = receiveMessage.metadata;
- this._log.info(formatLog("DASHBOARD", "Identify clients", receiveMessage));
- var session = this.sessions[metadata.sessionId];
+ this._log.debug(formatLog("DASHBOARD", "Identify clients", receiveMessage));
+ var session = this._sessions.get(metadata.sessionId);
if (session != null) {
var nbClients = 0;
@@ -529,85 +455,66 @@ export module VORLON {
var currentclient = session.connectedClients[client];
if (currentclient.opened) {
currentclient.socket.emit("identify", currentclient.displayId);
- this._log.info(formatLog("DASHBOARD", "Dashboard send identify " + currentclient.displayId + " to socketid : " + currentclient.socket.id, receiveMessage));
+ this._log.debug(formatLog("DASHBOARD", "Dashboard send identify " + currentclient.displayId + " to socketid : " + currentclient.socket.id, receiveMessage));
nbClients++;
}
}
- this._log.info(formatLog("DASHBOARD", "Send " + session.nbClients + " identify(s)", receiveMessage));
+ this._log.debug(formatLog("DASHBOARD", "Send " + session.nbClients + " identify(s)", receiveMessage));
}
else {
this._log.error(formatLog("DASHBOARD", " No client to identify...", receiveMessage));
+ if (session != undefined) {
+ this._sessions.update(metadata.sessionId, session);
+ }
}
});
- socket.on("message",(message: string) => {
+ socket.on("message", (message: string) => {
//this._log.warn("DASHBOARD message " + message);
var receiveMessage = JSON.parse(message);
var metadata = receiveMessage.metadata;
- var arrayClients = this.sessions[metadata.sessionId];
+ var arrayClients = this._sessions.get(metadata.sessionId);
if (arrayClients != null) {
for (var clientId in arrayClients.connectedClients) {
var client = arrayClients.connectedClients[clientId];
if (metadata.listenClientId === client.clientId) {
client.socket.emit("message", message);
- this._log.info(formatLog("DASHBOARD", "DASHBOARD=>PLUGIN", receiveMessage));
- //this._log.info(formatLog("DASHBOARD", "Send to client socketid : " + client.socket.id, receiveMessage));
+ this._log.debug(formatLog("DASHBOARD", "DASHBOARD=>PLUGIN", receiveMessage));
+ //this._log.debug(formatLog("DASHBOARD", "Send to client socketid : " + client.socket.id, receiveMessage));
}
}
- //this._log.info("DASHBOARD : " + metadata.sessionId + " Send " + (receiveMessage.command ? receiveMessage.command: "") + " to " + arrayClients.nbClients + " client(s)");
+ //this._log.debug("DASHBOARD : " + metadata.sessionId + " Send " + (receiveMessage.command ? receiveMessage.command: "") + " to " + arrayClients.nbClients + " client(s)");
}
else {
this._log.error(formatLog("DASHBOARD", "No client for message", receiveMessage));
+ var session = this._sessions.get(metadata.sessionId);
+ if (session != undefined) {
+ this._sessions.update(metadata.sessionId, session);
+ }
}
});
- socket.on("disconnect",(message: string) => {
+ socket.on("disconnect", (message: string) => {
//this._log.warn("DASHBOARD disconnect " + message);
//Delete dashboard session
for (var dashboard in this.dashboards) {
if (this.dashboards[dashboard].id === socket.id) {
delete this.dashboards[dashboard];
- this._log.info(formatLog("DASHBOARD", "Delete dashboard " + dashboard + " socket " + socket.id));
+ this._log.debug(formatLog("DASHBOARD", "Delete dashboard " + dashboard + " socket " + socket.id));
}
}
//Send disconnect to all client
- for (var session in this.sessions) {
- for (var client in this.sessions[session].connectedClients) {
- this.sessions[session].connectedClients[client].socket.emit("stoplisten");
+ this._sessions.all().forEach((session) => {
+ for (var client in session.connectedClients) {
+ session.connectedClients[client].socket.emit("stoplisten");
}
- }
+ });
});
}
}
- export class Session {
- public currentClientId = "";
- public nbClients = -1;
- public connectedClients = new Array();
- }
-
- export class Client {
- public clientId: string;
- public displayId: number;
- public socket: SocketIO.Socket;
- public opened: boolean;
- public ua: string;
-
- public get data(): any {
- return { "clientid": this.clientId, "displayid": this.displayId, "ua": this.ua, "name": tools.VORLON.Tools.GetOperatingSystem(this.ua) };
- }
-
- constructor(clientId: string, ua: string, socket: SocketIO.Socket, displayId: number, opened: boolean = true) {
- this.clientId = clientId;
- this.ua = ua;
- this.socket = socket;
- this.displayId = displayId;
- this.opened = opened;
- }
- }
-
export interface VorlonMessageMetadata {
pluginID: string;
side: number;
@@ -630,6 +537,7 @@ export module VORLON {
buffer.push(" ");
}
}
+
buffer.push(" : ");
if (vmessage) {
@@ -656,7 +564,7 @@ export module VORLON {
}
}
-
+
return buffer.join("");
}
diff --git a/Server/Scripts/vorlon.tools.ts b/Server/Scripts/vorlon.tools.ts
index 2951efe9..740b7b57 100644
--- a/Server/Scripts/vorlon.tools.ts
+++ b/Server/Scripts/vorlon.tools.ts
@@ -65,6 +65,11 @@
if (currentLowerUA.indexOf("firefox") >= 0) {
return "Firefox OS"; // Web is the plaform
}
+
+ // Node.js
+ if (currentLowerUA.indexOf("node.js") >= 0) {
+ return "Node.js";
+ }
return "Unknown operating system";
}
diff --git a/Server/Scripts/vorlon.webServer.ts b/Server/Scripts/vorlon.webServer.ts
index 874b6774..d2b15b06 100644
--- a/Server/Scripts/vorlon.webServer.ts
+++ b/Server/Scripts/vorlon.webServer.ts
@@ -2,12 +2,11 @@
import path = require("path");
import stylus = require("stylus");
import fs = require("fs");
-
+import http = require("http");
//Vorlon
import iwsc = require("./vorlon.IWebServerComponent");
import vauth = require("./vorlon.authentication");
-import httpConfig = require("../config/vorlon.httpconfig");
-import baseURLConfig = require("../config/vorlon.baseurlconfig");
+import vorloncontext = require("../config/vorlon.servercontext");
export module VORLON {
export class WebServer {
@@ -23,15 +22,18 @@ export module VORLON {
// private _flash = require('connect-flash');
private _components: Array;
- private http: httpConfig.VORLON.HttpConfig;
private _app: express.Express;
- private baseURLConfig: baseURLConfig.VORLON.BaseURLConfig;
+ private _log: vorloncontext.VORLON.ILogger;
+ private _httpServer : http.Server;
+ private httpConfig: vorloncontext.VORLON.IHttpConfig;
+ private baseURLConfig: vorloncontext.VORLON.IBaseURLConfig;
- constructor() {
+ constructor(context : vorloncontext.VORLON.IVorlonServerContext) {
this._app = express();
this._components = new Array();
- this.http = new httpConfig.VORLON.HttpConfig();
- this.baseURLConfig = new baseURLConfig.VORLON.BaseURLConfig();
+ this.httpConfig = context.httpConfig;
+ this.baseURLConfig = context.baseURLConfig;
+ this._log = context.logger;
}
public init(): void {
@@ -64,7 +66,7 @@ export module VORLON {
}
var _package = JSON.parse(packageData.replace(/^\uFEFF/, ''));
- console.log('Vorlon.js v' + _package.version);
+ this._log.info('Vorlon.js v' + _package.version);
});
stopExecution = true;
break;
@@ -74,11 +76,20 @@ export module VORLON {
if (stopExecution) {
return;
}
+ var cors = require("cors");
//Sets
- app.set('port', this.http.port);
+ app.set('port', this.httpConfig.port);
app.set('views', path.join(__dirname, '../views'));
app.set('view engine', 'jade');
+
+ // Cors
+ var corsOptions = {
+ allowedHeaders: "*",
+ exposedHeaders: ["X-VorlonProxyEncoding", "Content-Encoding", "Content-Length"]
+ };
+ app.use(cors(corsOptions));
+ app.options('*', cors(corsOptions));
//Uses
this._passport.use(new this._localStrategy(function(username, password, done) {
@@ -120,31 +131,32 @@ export module VORLON {
vauth.VORLON.Authentication.loadAuthConfig();
this.init();
-
- app.use((req, res, next) => {
- res.header("Access-Control-Allow-Origin", "*");
- res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
- next();
- });
+
+ // app.use((req, res, next) => {
+ // res.header("Access-Control-Allow-Origin", "*");
+ // res.header('Access-Control-Allow-Methods', 'GET,POST,PUT,HEAD,DELETE,OPTIONS');
+ // res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, X-VorlonProxyEncoding, content-encoding, content-length");
+ // next();
+ // });
- if (this.http.useSSL) {
- this.http.httpModule = this.http.httpModule.createServer(this.http.options, app).listen(app.get('port'), () => {
- console.log('Vorlon.js SERVER with SSL listening on port ' + app.get('port'));
+ if (this.httpConfig.useSSL) {
+ this._httpServer = this.httpConfig.httpModule.createServer(this.httpConfig.options, app).listen(app.get('port'), () => {
+ this._log.info('Vorlon.js SERVER with SSL listening on port ' + app.get('port'));
});
} else {
- this.http.httpModule = this.http.httpModule.createServer(app).listen(app.get('port'), () => {
- console.log('Vorlon.js SERVER listening on port ' + app.get('port'));
+ this._httpServer = this.httpConfig.httpModule.createServer(app).listen(app.get('port'), () => {
+ this._log.info('Vorlon.js SERVER listening on port ' + app.get('port'));
});
}
for (var id in this._components) {
var component = this._components[id];
- component.start(this.http.httpModule);
+ component.start(this._httpServer);
}
}
public get httpServer(){
- return this.http.httpModule;
+ return this._httpServer;
}
}
}
diff --git a/Server/Scripts/vorlon.winstonlogger.ts b/Server/Scripts/vorlon.winstonlogger.ts
new file mode 100644
index 00000000..da69c035
--- /dev/null
+++ b/Server/Scripts/vorlon.winstonlogger.ts
@@ -0,0 +1,81 @@
+import express = require("express");
+import winston = require("winston");
+import http = require("http");
+
+//Vorlon
+import iwsc = require("./vorlon.IWebServerComponent");
+import tools = require("./vorlon.tools");
+import vorloncontext = require("../config/vorlon.servercontext");
+
+var winstonDisplay = require("winston-logs-display");
+
+export module VORLON {
+ export class WinstonLogger implements iwsc.VORLON.IWebServerComponent {
+ private logConfig: vorloncontext.VORLON.ILogConfig;
+ private _log: winston.LoggerInstance;
+
+ constructor(context : vorloncontext.VORLON.IVorlonServerContext) {
+ this.logConfig = context.logConfig;
+
+ //LOGS
+ winston.cli();
+ this._log = new winston.Logger({
+ levels: {
+ info: 0,
+ warn: 1,
+ error: 2,
+ verbose: 3,
+ api: 4,
+ dashboard: 5,
+ plugin: 6
+ },
+ transports: [
+ new winston.transports.File({ filename: this.logConfig.vorlonLogFile, level: this.logConfig.level})
+ ],
+ exceptionHandlers: [
+ new winston.transports.File({ filename: this.logConfig.exceptionsLogFile, timestamp: true, maxsize: 1000000 })
+ ],
+ exitOnError: false
+ });
+ context.logger = this._log;
+
+ if (this.logConfig.enableConsole) {
+ this._log.add(winston.transports.Console, {
+ level: this.logConfig.level,
+ handleExceptions: true,
+ json: false,
+ timestamp: function() {
+ var date:Date = new Date();
+ return date.getFullYear() + "-" +
+ date.getMonth() + "-" +
+ date.getDate() + " " +
+ date.getHours() + ":" +
+ date.getMinutes() + ":" +
+ date.getSeconds();
+ },
+ colorize: true
+ });
+ }
+
+ winston.addColors({
+ info: 'green',
+ warn: 'cyan',
+ error: 'red',
+ verbose: 'blue',
+ api: 'gray',
+ dashboard: 'pink',
+ plugin: 'yellow'
+ });
+
+ this._log.cli();
+ }
+
+ public addRoutes(app: express.Express, passport: any): void {
+ //DisplayLogs
+ winstonDisplay(app, this._log);
+ }
+
+ public start(httpServer: http.Server): void {
+ }
+ }
+}
\ No newline at end of file
diff --git a/Server/Server.njsproj b/Server/Server.njsproj
index 3e014700..aa9e6d87 100644
--- a/Server/Server.njsproj
+++ b/Server/Server.njsproj
@@ -201,7 +201,7 @@
-
+
diff --git a/Server/config.json b/Server/config.json
index 1249f2ba..8d1b2bd0 100644
--- a/Server/config.json
+++ b/Server/config.json
@@ -4,29 +4,30 @@
"useSSL": false,
"SSLkey": "cert/server.key",
"SSLcert": "cert/server.crt",
- "includeSocketIO": true,
"activateAuth": false,
"username": "",
"password": "",
+
+ "port": 1337,
+ "enableWebproxy" : true,
+ "baseProxyURL": "",
+ "proxyPort" : 5050,
+ "proxyEnvPort": false,
+ "vorlonServerURL": "",
+ "vorlonProxyURL": "",
+
"plugins": [
- { "id": "CONSOLE", "name": "Interactive Console", "panel": "bottom", "foldername": "interactiveConsole", "enabled": true },
+ { "id": "CONSOLE", "name": "Interactive Console", "panel": "bottom", "foldername": "interactiveConsole", "enabled": true, "nodeCompliant": true },
{ "id": "DOM", "name": "Dom Explorer", "panel": "top", "foldername": "domExplorer", "enabled": true },
{ "id": "MODERNIZR", "name": "Modernizr", "panel": "bottom", "foldername": "modernizrReport", "enabled": true },
- { "id": "OBJEXPLORER", "name": "Obj. Explorer", "panel": "top", "foldername": "objectExplorer", "enabled": true },
- { "id": "XHRPANEL", "name": "XHR", "panel": "top", "foldername": "xhrPanel", "enabled": true },
+ { "id": "OBJEXPLORER", "name": "Obj. Explorer", "panel": "top", "foldername": "objectExplorer", "enabled": true, "nodeCompliant": true },
+ { "id": "WEBSTANDARDS", "name": "Best practices", "panel": "top", "foldername": "webstandards", "enabled": true },
+ { "id": "XHRPANEL", "name": "XHR", "panel": "top", "foldername": "xhrPanel", "enabled": true, "nodeCompliant": true },
{ "id": "NGINSPECTOR", "name": "Ng. Inspector", "panel": "top", "foldername": "ngInspector", "enabled": false },
{ "id": "NETWORK", "name": "Network Monitor", "panel": "top", "foldername": "networkMonitor", "enabled": true },
{ "id": "RESOURCES", "name": "Resources Explorer", "panel": "top", "foldername": "resourcesExplorer", "enabled": true },
{ "id": "DEVICE", "name": "My Device", "panel": "top", "foldername": "device", "enabled": true },
{ "id": "UNITTEST", "name": "Unit Test", "panel": "top", "foldername": "unitTestRunner", "enabled": true },
- { "id": "BABYLONINSPECTOR", "name": "Babylon Inspector", "panel": "top", "foldername": "babylonInspector", "enabled": false },
- { "id": "WEBSTANDARDS", "name": "Best practices", "panel": "top", "foldername": "webstandards", "enabled": true }
- ],
- "port": 1337,
- "enableWebproxy" : true,
- "baseProxyURL": "",
- "proxyPort" : 5050,
- "proxyEnvPort": false,
- "vorlonServerURL": "",
- "vorlonProxyURL": ""
+ { "id": "BABYLONINSPECTOR", "name": "Babylon Inspector", "panel": "top", "foldername": "babylonInspector", "enabled": false }
+ ]
}
diff --git a/Server/config/vorlon.logconfig.ts b/Server/config/vorlon.logconfig.ts
index 34c71829..a62840f1 100644
--- a/Server/config/vorlon.logconfig.ts
+++ b/Server/config/vorlon.logconfig.ts
@@ -21,13 +21,13 @@ export module VORLON {
this.vorlonLogFile = path.join(filePath, vorlonjsFile);
this.exceptionsLogFile = path.join(filePath, exceptionFile);
this.enableConsole = logConfig.enableConsole;
- this.level = logConfig.level ? logConfig.level : "warn";
+ this.level = logConfig.level ? logConfig.level : "info";
}
else {
this.vorlonLogFile = path.join(__dirname, "../vorlonjs.log");
this.exceptionsLogFile = path.join(__dirname, "../exceptions.log");
this.enableConsole = true;
- this.level = "warn";
+ this.level = "info";
}
}
}
diff --git a/Server/config/vorlon.pluginsconfig.ts b/Server/config/vorlon.pluginsconfig.ts
new file mode 100644
index 00000000..a8d19737
--- /dev/null
+++ b/Server/config/vorlon.pluginsconfig.ts
@@ -0,0 +1,32 @@
+import fs = require("fs");
+import path = require("path");
+import ctx = require("./vorlon.servercontext");
+
+export module VORLON {
+ export class PluginsConfig {
+
+ public constructor() {
+ }
+
+ getPluginsFor(sessionid:string, callback:(error, plugins:ctx.VORLON.ISessionPlugins) => void) {
+ var configurationFile: string = fs.readFileSync(path.join(__dirname, "../config.json"), "utf8");
+ var configurationString = configurationFile.toString().replace(/^\uFEFF/, '');
+ var configuration = JSON.parse(configurationString);
+
+ try{
+ var sessionConfig = configuration.sessions[sessionid];
+ }
+ catch(e){
+ if (!sessionConfig || !sessionConfig.plugins || !sessionConfig.plugins.length) {
+ sessionConfig = {
+ includeSocketIO: configuration.includeSocketIO || true,
+ plugins: configuration.plugins
+ };
+ }
+ }
+
+ if (callback)
+ callback(null, sessionConfig);
+ }
+ }
+}
\ No newline at end of file
diff --git a/Server/config/vorlon.redisconfig.ts b/Server/config/vorlon.redisconfig.ts
index b7c5439c..92b6d1eb 100644
--- a/Server/config/vorlon.redisconfig.ts
+++ b/Server/config/vorlon.redisconfig.ts
@@ -1,8 +1,8 @@
export module VORLON {
export class RedisConfig {
- static fackredis: boolean = true;
- static _redisPort = 6379;
- static _redisMachine = "";
- static _redisPassword = "";
+ public fackredis: boolean = true;
+ public _redisPort = 6379;
+ public _redisMachine = "";
+ public _redisPassword = "";
}
}
\ No newline at end of file
diff --git a/Server/config/vorlon.servercontext.ts b/Server/config/vorlon.servercontext.ts
new file mode 100644
index 00000000..6a6d457a
--- /dev/null
+++ b/Server/config/vorlon.servercontext.ts
@@ -0,0 +1,209 @@
+import httpConfig = require("./vorlon.httpconfig");
+import baseUrlConfig = require("./vorlon.baseurlconfig");
+import logConfig = require("./vorlon.logconfig");
+import pluginsConfig = require("./vorlon.pluginsconfig");
+import redisConfig = require("./vorlon.redisconfig");
+import tools = require("../Scripts/vorlon.tools");
+
+export module VORLON {
+ export interface IBaseURLConfig {
+ baseURL: string;
+ baseProxyURL: string;
+ }
+
+ export interface ILogger {
+ debug: (...args) => void;
+ info: (...args) => void;
+ warn: (...args) => void;
+ error: (...args) => void;
+ }
+
+ export interface IHttpConfig {
+ useSSL: boolean;
+ protocol: String;
+ options;
+ httpModule: any;
+ port: number;
+ proxyPort: number;
+ enableWebproxy: boolean;
+ vorlonServerURL: string;
+ vorlonProxyURL: string;
+ proxyEnvPort: boolean;
+ }
+
+ export interface ILogConfig {
+ vorlonLogFile: string;
+ exceptionsLogFile: string;
+ enableConsole: boolean;
+ level: string;
+ }
+
+ export interface IRedisConfig {
+ fackredis: boolean;
+ _redisPort: number;
+ _redisMachine: string;
+ _redisPassword: string;
+ }
+
+ export interface IPluginConfig {
+ id: string;
+ name: string;
+ panel: string;
+ foldername: string;
+ enabled: boolean;
+ nodeCompliant: boolean;
+ }
+
+ export interface ISessionPlugins {
+ includeSocketIO: boolean;
+ plugins: IPluginConfig[];
+ }
+
+ export interface IPluginsProvider {
+ getPluginsFor(sessionid: string, callback: (error, plugins: ISessionPlugins) => void);
+ }
+
+ export interface IVorlonServerContext {
+ baseURLConfig: IBaseURLConfig;
+ httpConfig: IHttpConfig;
+ logConfig: ILogConfig;
+ redisConfig: IRedisConfig;
+ logger: ILogger;
+ plugins: IPluginsProvider;
+ sessions: SessionManager;
+ }
+
+ export class SimpleConsoleLogger implements ILogger {
+ debug() {
+ console.log.apply(null, arguments);
+ }
+
+ info() {
+ console.info.apply(null, arguments);
+ }
+
+ warn() {
+ console.warn.apply(null, arguments);
+ }
+
+ error() {
+ console.error.apply(null, arguments);
+ }
+ }
+
+ export class SessionManager {
+ private sessions: Session[] = [];
+ public logger: ILogger;
+ public onsessionadded: (session) => void;
+ public onsessionremoved: (session) => void;
+ public onsessionupdated: (session) => void;
+
+ add(sessionId: string, session: Session) {
+ session.sessionId = sessionId;
+ this.sessions[sessionId] = session;
+ if (this.logger)
+ this.logger.debug("session " + sessionId + " added");
+
+ if (this.onsessionadded)
+ this.onsessionadded(session);
+ }
+
+ get(sessionId: string): Session {
+ return this.sessions[sessionId];
+ }
+
+ remove(sessionId: string) {
+ var session = this.sessions[sessionId];
+ if (this.logger)
+ this.logger.debug("session " + sessionId + " removed");
+
+ delete this.sessions[sessionId];
+ if (this.onsessionremoved)
+ this.onsessionremoved(session);
+ }
+
+ update(sessionId: string, session: Session) {
+ this.sessions[sessionId] = session;
+
+ if (this.logger)
+ this.logger.debug("session " + sessionId + " update");
+
+ var nbopened = 0;
+ session.connectedClients.forEach((client) => {
+ if (client.opened) {
+ nbopened++;
+ }
+ });
+
+ session.nbClients = nbopened;
+
+ if (this.onsessionupdated)
+ this.onsessionupdated(session);
+ }
+
+ all(): Session[] {
+ var items = [];
+ for (var n in this.sessions) {
+ items.push(this.sessions[n]);
+ }
+ return items;
+ }
+ }
+
+ export class Session {
+ public sessionId: string = "";
+ public currentClientId = "";
+ public nbClients = -1;
+ public connectedClients = new Array();
+ }
+
+ export class Client {
+ public clientId: string;
+ public displayId: number;
+ public socket: SocketIO.Socket;
+ public opened: boolean;
+ public ua: string;
+ public identity: string;
+ public noWindow: boolean;
+
+ public get data(): any {
+ return {
+ "clientid": this.clientId,
+ "displayid": this.displayId,
+ "ua": this.ua,
+ "identity" : this.identity,
+ "name": tools.VORLON.Tools.GetOperatingSystem(this.ua),
+ "noWindow": this.noWindow
+ };
+ }
+
+ constructor(clientId: string, ua: string, noWindow: boolean, socket: SocketIO.Socket, displayId: number, opened: boolean = true) {
+ this.clientId = clientId;
+ this.ua = ua;
+ this.socket = socket;
+ this.displayId = displayId;
+ this.opened = opened;
+ this.noWindow = noWindow;
+ }
+ }
+
+ export class DefaultContext implements IVorlonServerContext {
+ public baseURLConfig: IBaseURLConfig;
+ public httpConfig: IHttpConfig;
+ public logConfig: ILogConfig;
+ public redisConfig: IRedisConfig;
+ public logger: ILogger;
+ public sessions: SessionManager;
+ public plugins: IPluginsProvider;
+
+ constructor() {
+ this.httpConfig = new httpConfig.VORLON.HttpConfig();
+ this.baseURLConfig = new baseUrlConfig.VORLON.BaseURLConfig();
+ this.logConfig = new logConfig.VORLON.LogConfig();
+ this.redisConfig = new redisConfig.VORLON.RedisConfig();
+ this.plugins = new pluginsConfig.VORLON.PluginsConfig();
+
+ this.sessions = new SessionManager();
+ }
+ }
+}
\ No newline at end of file
diff --git a/Server/gulpfile.js b/Server/gulpfile.js
deleted file mode 100644
index 319e4e70..00000000
--- a/Server/gulpfile.js
+++ /dev/null
@@ -1,23 +0,0 @@
-var gulp = require('gulp'),
- typescript = require('gulp-typescript');
-
-gulp.task('typescript-to-js', function() {
- var tsResult = gulp.src(['./**/*.ts', '!./node_modules', '!./node_modules/**'], { base: './' })
- .pipe(typescript({ noExternalResolve: true, target: 'ES5', module: 'commonjs' }));
-
- return tsResult.js
- .pipe(gulp.dest('.'));
-});
-
-gulp.task('default', function() {
- gulp.start('typescript-to-js');
-});
-
-/**
- * Watch typescript task, will call the default typescript task if a typescript file is updated.
- */
-gulp.task('watch', function() {
- gulp.watch([
- './**/*.ts',
- ], ['default']);
-});
\ No newline at end of file
diff --git a/Server/public/javascripts/socket.io-1.3.6.js b/Server/public/javascripts/socket.io-1.3.6.js
deleted file mode 100644
index 833fe00d..00000000
--- a/Server/public/javascripts/socket.io-1.3.6.js
+++ /dev/null
@@ -1,3 +0,0 @@
-!function(e){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{var f;"undefined"!=typeof window?f=window:"undefined"!=typeof global?f=global:"undefined"!=typeof self&&(f=self),f.io=e()}}(function(){var define,module,exports;return function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);throw new Error("Cannot find module '"+o+"'")}var f=n[o]={exports:{}};t[o][0].call(f.exports,function(e){var n=t[o][1][e];return s(n?n:e)},f,f.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o0&&!this.encoding){var pack=this.packetBuffer.shift();this.packet(pack)}};Manager.prototype.cleanup=function(){var sub;while(sub=this.subs.shift())sub.destroy();this.packetBuffer=[];this.encoding=false;this.decoder.destroy()};Manager.prototype.close=Manager.prototype.disconnect=function(){this.skipReconnect=true;this.backoff.reset();this.readyState="closed";this.engine&&this.engine.close()};Manager.prototype.onclose=function(reason){debug("close");this.cleanup();this.backoff.reset();this.readyState="closed";this.emit("close",reason);if(this._reconnection&&!this.skipReconnect){this.reconnect()}};Manager.prototype.reconnect=function(){if(this.reconnecting||this.skipReconnect)return this;var self=this;if(this.backoff.attempts>=this._reconnectionAttempts){debug("reconnect failed");this.backoff.reset();this.emitAll("reconnect_failed");this.reconnecting=false}else{var delay=this.backoff.duration();debug("will wait %dms before reconnect attempt",delay);this.reconnecting=true;var timer=setTimeout(function(){if(self.skipReconnect)return;debug("attempting reconnect");self.emitAll("reconnect_attempt",self.backoff.attempts);self.emitAll("reconnecting",self.backoff.attempts);if(self.skipReconnect)return;self.open(function(err){if(err){debug("reconnect attempt error");self.reconnecting=false;self.reconnect();self.emitAll("reconnect_error",err.data)}else{debug("reconnect success");self.onreconnect()}})},delay);this.subs.push({destroy:function(){clearTimeout(timer)}})}};Manager.prototype.onreconnect=function(){var attempt=this.backoff.attempts;this.reconnecting=false;this.backoff.reset();this.updateSocketIds();this.emitAll("reconnect",attempt)}},{"./on":4,"./socket":5,"./url":6,backo2:7,"component-bind":8,"component-emitter":9,debug:10,"engine.io-client":11,indexof:42,"object-component":43,"socket.io-parser":46}],4:[function(_dereq_,module,exports){module.exports=on;function on(obj,ev,fn){obj.on(ev,fn);return{destroy:function(){obj.removeListener(ev,fn)}}}},{}],5:[function(_dereq_,module,exports){var parser=_dereq_("socket.io-parser");var Emitter=_dereq_("component-emitter");var toArray=_dereq_("to-array");var on=_dereq_("./on");var bind=_dereq_("component-bind");var debug=_dereq_("debug")("socket.io-client:socket");var hasBin=_dereq_("has-binary");module.exports=exports=Socket;var events={connect:1,connect_error:1,connect_timeout:1,disconnect:1,error:1,reconnect:1,reconnect_attempt:1,reconnect_failed:1,reconnect_error:1,reconnecting:1};var emit=Emitter.prototype.emit;function Socket(io,nsp){this.io=io;this.nsp=nsp;this.json=this;this.ids=0;this.acks={};if(this.io.autoConnect)this.open();this.receiveBuffer=[];this.sendBuffer=[];this.connected=false;this.disconnected=true}Emitter(Socket.prototype);Socket.prototype.subEvents=function(){if(this.subs)return;var io=this.io;this.subs=[on(io,"open",bind(this,"onopen")),on(io,"packet",bind(this,"onpacket")),on(io,"close",bind(this,"onclose"))]};Socket.prototype.open=Socket.prototype.connect=function(){if(this.connected)return this;this.subEvents();this.io.open();if("open"==this.io.readyState)this.onopen();return this};Socket.prototype.send=function(){var args=toArray(arguments);args.unshift("message");this.emit.apply(this,args);return this};Socket.prototype.emit=function(ev){if(events.hasOwnProperty(ev)){emit.apply(this,arguments);return this}var args=toArray(arguments);var parserType=parser.EVENT;if(hasBin(args)){parserType=parser.BINARY_EVENT}var packet={type:parserType,data:args};if("function"==typeof args[args.length-1]){debug("emitting packet with ack id %d",this.ids);this.acks[this.ids]=args.pop();packet.id=this.ids++}if(this.connected){this.packet(packet)}else{this.sendBuffer.push(packet)}return this};Socket.prototype.packet=function(packet){packet.nsp=this.nsp;this.io.packet(packet)};Socket.prototype.onopen=function(){debug("transport is open - connecting");if("/"!=this.nsp){this.packet({type:parser.CONNECT})}};Socket.prototype.onclose=function(reason){debug("close (%s)",reason);this.connected=false;this.disconnected=true;delete this.id;this.emit("disconnect",reason)};Socket.prototype.onpacket=function(packet){if(packet.nsp!=this.nsp)return;switch(packet.type){case parser.CONNECT:this.onconnect();break;case parser.EVENT:this.onevent(packet);break;case parser.BINARY_EVENT:this.onevent(packet);break;case parser.ACK:this.onack(packet);break;case parser.BINARY_ACK:this.onack(packet);break;case parser.DISCONNECT:this.ondisconnect();break;case parser.ERROR:this.emit("error",packet.data);break}};Socket.prototype.onevent=function(packet){var args=packet.data||[];debug("emitting event %j",args);if(null!=packet.id){debug("attaching ack callback to event");args.push(this.ack(packet.id))}if(this.connected){emit.apply(this,args)}else{this.receiveBuffer.push(args)}};Socket.prototype.ack=function(id){var self=this;var sent=false;return function(){if(sent)return;sent=true;var args=toArray(arguments);debug("sending ack %j",args);var type=hasBin(args)?parser.BINARY_ACK:parser.ACK;self.packet({type:type,id:id,data:args})}};Socket.prototype.onack=function(packet){debug("calling ack %s with %j",packet.id,packet.data);var fn=this.acks[packet.id];fn.apply(this,packet.data);delete this.acks[packet.id]};Socket.prototype.onconnect=function(){this.connected=true;this.disconnected=false;this.emit("connect");this.emitBuffered()};Socket.prototype.emitBuffered=function(){var i;for(i=0;i0&&opts.jitter<=1?opts.jitter:0;this.attempts=0}Backoff.prototype.duration=function(){var ms=this.ms*Math.pow(this.factor,this.attempts++);if(this.jitter){var rand=Math.random();var deviation=Math.floor(rand*this.jitter*ms);ms=(Math.floor(rand*10)&1)==0?ms-deviation:ms+deviation}return Math.min(ms,this.max)|0};Backoff.prototype.reset=function(){this.attempts=0};Backoff.prototype.setMin=function(min){this.ms=min};Backoff.prototype.setMax=function(max){this.max=max};Backoff.prototype.setJitter=function(jitter){this.jitter=jitter}},{}],8:[function(_dereq_,module,exports){var slice=[].slice;module.exports=function(obj,fn){if("string"==typeof fn)fn=obj[fn];if("function"!=typeof fn)throw new Error("bind() requires a function");var args=slice.call(arguments,2);return function(){return fn.apply(obj,args.concat(slice.call(arguments)))}}},{}],9:[function(_dereq_,module,exports){module.exports=Emitter;function Emitter(obj){if(obj)return mixin(obj)}function mixin(obj){for(var key in Emitter.prototype){obj[key]=Emitter.prototype[key]}return obj}Emitter.prototype.on=Emitter.prototype.addEventListener=function(event,fn){this._callbacks=this._callbacks||{};(this._callbacks[event]=this._callbacks[event]||[]).push(fn);return this};Emitter.prototype.once=function(event,fn){var self=this;this._callbacks=this._callbacks||{};function on(){self.off(event,on);fn.apply(this,arguments)}on.fn=fn;this.on(event,on);return this};Emitter.prototype.off=Emitter.prototype.removeListener=Emitter.prototype.removeAllListeners=Emitter.prototype.removeEventListener=function(event,fn){this._callbacks=this._callbacks||{};if(0==arguments.length){this._callbacks={};return this}var callbacks=this._callbacks[event];if(!callbacks)return this;if(1==arguments.length){delete this._callbacks[event];return this}var cb;for(var i=0;i=hour)return(ms/hour).toFixed(1)+"h";if(ms>=min)return(ms/min).toFixed(1)+"m";if(ms>=sec)return(ms/sec|0)+"s";return ms+"ms"};debug.enabled=function(name){for(var i=0,len=debug.skips.length;i';iframe=document.createElement(html)}catch(e){iframe=document.createElement("iframe");iframe.name=self.iframeId;iframe.src="javascript:0"}iframe.id=self.iframeId;self.form.appendChild(iframe);self.iframe=iframe}initIframe();data=data.replace(rEscapedNewline,"\\\n");this.area.value=data.replace(rNewline,"\\n");try{this.form.submit()}catch(e){}if(this.iframe.attachEvent){this.iframe.onreadystatechange=function(){if(self.iframe.readyState=="complete"){complete()}}}else{this.iframe.onload=complete}}}).call(this,typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"./polling":18,"component-inherit":21}],17:[function(_dereq_,module,exports){(function(global){var XMLHttpRequest=_dereq_("xmlhttprequest");var Polling=_dereq_("./polling");var Emitter=_dereq_("component-emitter");var inherit=_dereq_("component-inherit");var debug=_dereq_("debug")("engine.io-client:polling-xhr");module.exports=XHR;module.exports.Request=Request;function empty(){}function XHR(opts){Polling.call(this,opts);if(global.location){var isSSL="https:"==location.protocol;var port=location.port;if(!port){port=isSSL?443:80}this.xd=opts.hostname!=global.location.hostname||port!=opts.port;this.xs=opts.secure!=isSSL}}inherit(XHR,Polling);XHR.prototype.supportsBinary=true;XHR.prototype.request=function(opts){opts=opts||{};opts.uri=this.uri();opts.xd=this.xd;opts.xs=this.xs;opts.agent=this.agent||false;opts.supportsBinary=this.supportsBinary;opts.enablesXDR=this.enablesXDR;opts.pfx=this.pfx;opts.key=this.key;opts.passphrase=this.passphrase;opts.cert=this.cert;opts.ca=this.ca;opts.ciphers=this.ciphers;opts.rejectUnauthorized=this.rejectUnauthorized;return new Request(opts)};XHR.prototype.doWrite=function(data,fn){var isBinary=typeof data!=="string"&&data!==undefined;var req=this.request({method:"POST",data:data,isBinary:isBinary});var self=this;req.on("success",fn);req.on("error",function(err){self.onError("xhr post error",err)});this.sendXhr=req};XHR.prototype.doPoll=function(){debug("xhr poll");var req=this.request();var self=this;req.on("data",function(data){self.onData(data)});req.on("error",function(err){self.onError("xhr poll error",err)});this.pollXhr=req};function Request(opts){this.method=opts.method||"GET";this.uri=opts.uri;this.xd=!!opts.xd;this.xs=!!opts.xs;this.async=false!==opts.async;this.data=undefined!=opts.data?opts.data:null;this.agent=opts.agent;this.isBinary=opts.isBinary;this.supportsBinary=opts.supportsBinary;this.enablesXDR=opts.enablesXDR;this.pfx=opts.pfx;this.key=opts.key;this.passphrase=opts.passphrase;this.cert=opts.cert;this.ca=opts.ca;this.ciphers=opts.ciphers;this.rejectUnauthorized=opts.rejectUnauthorized;this.create()}Emitter(Request.prototype);Request.prototype.create=function(){var opts={agent:this.agent,xdomain:this.xd,xscheme:this.xs,enablesXDR:this.enablesXDR};opts.pfx=this.pfx;opts.key=this.key;opts.passphrase=this.passphrase;opts.cert=this.cert;opts.ca=this.ca;opts.ciphers=this.ciphers;opts.rejectUnauthorized=this.rejectUnauthorized;var xhr=this.xhr=new XMLHttpRequest(opts);var self=this;try{debug("xhr open %s: %s",this.method,this.uri);xhr.open(this.method,this.uri,this.async);if(this.supportsBinary){xhr.responseType="arraybuffer"}if("POST"==this.method){try{if(this.isBinary){xhr.setRequestHeader("Content-type","application/octet-stream")}else{xhr.setRequestHeader("Content-type","text/plain;charset=UTF-8")}}catch(e){}}if("withCredentials"in xhr){xhr.withCredentials=true}if(this.hasXDR()){xhr.onload=function(){self.onLoad()};xhr.onerror=function(){self.onError(xhr.responseText)}}else{xhr.onreadystatechange=function(){if(4!=xhr.readyState)return;if(200==xhr.status||1223==xhr.status){self.onLoad()}else{setTimeout(function(){self.onError(xhr.status)},0)}}}debug("xhr data %s",this.data);xhr.send(this.data)}catch(e){setTimeout(function(){self.onError(e)},0);return}if(global.document){this.index=Request.requestsCount++;Request.requests[this.index]=this}};Request.prototype.onSuccess=function(){this.emit("success");this.cleanup()};Request.prototype.onData=function(data){this.emit("data",data);this.onSuccess()};Request.prototype.onError=function(err){this.emit("error",err);this.cleanup(true)};Request.prototype.cleanup=function(fromError){if("undefined"==typeof this.xhr||null===this.xhr){return}if(this.hasXDR()){this.xhr.onload=this.xhr.onerror=empty}else{this.xhr.onreadystatechange=empty}if(fromError){try{this.xhr.abort()}catch(e){}}if(global.document){delete Request.requests[this.index]}this.xhr=null};Request.prototype.onLoad=function(){var data;try{var contentType;try{contentType=this.xhr.getResponseHeader("Content-Type").split(";")[0]}catch(e){}if(contentType==="application/octet-stream"){data=this.xhr.response}else{if(!this.supportsBinary){data=this.xhr.responseText}else{data="ok"}}}catch(e){this.onError(e)}if(null!=data){this.onData(data)}};Request.prototype.hasXDR=function(){return"undefined"!==typeof global.XDomainRequest&&!this.xs&&this.enablesXDR};Request.prototype.abort=function(){this.cleanup()};if(global.document){Request.requestsCount=0;Request.requests={};if(global.attachEvent){global.attachEvent("onunload",unloadHandler)}else if(global.addEventListener){global.addEventListener("beforeunload",unloadHandler,false)}}function unloadHandler(){for(var i in Request.requests){if(Request.requests.hasOwnProperty(i)){Request.requests[i].abort()}}}}).call(this,typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"./polling":18,"component-emitter":9,"component-inherit":21,debug:22,xmlhttprequest:20}],18:[function(_dereq_,module,exports){var Transport=_dereq_("../transport");var parseqs=_dereq_("parseqs");var parser=_dereq_("engine.io-parser");var inherit=_dereq_("component-inherit");var debug=_dereq_("debug")("engine.io-client:polling");module.exports=Polling;var hasXHR2=function(){var XMLHttpRequest=_dereq_("xmlhttprequest");var xhr=new XMLHttpRequest({xdomain:false});return null!=xhr.responseType}();function Polling(opts){var forceBase64=opts&&opts.forceBase64;if(!hasXHR2||forceBase64){this.supportsBinary=false}Transport.call(this,opts)}inherit(Polling,Transport);Polling.prototype.name="polling";Polling.prototype.doOpen=function(){this.poll()};Polling.prototype.pause=function(onPause){var pending=0;var self=this;this.readyState="pausing";function pause(){debug("paused");self.readyState="paused";onPause()}if(this.polling||!this.writable){var total=0;if(this.polling){debug("we are currently polling - waiting to pause");total++;this.once("pollComplete",function(){debug("pre-pause polling complete");--total||pause()})}if(!this.writable){debug("we are currently writing - waiting to pause");total++;this.once("drain",function(){debug("pre-pause writing complete");--total||pause()})}}else{pause()}};Polling.prototype.poll=function(){debug("polling");this.polling=true;this.doPoll();this.emit("poll")};Polling.prototype.onData=function(data){var self=this;debug("polling got data %s",data);var callback=function(packet,index,total){if("opening"==self.readyState){self.onOpen()}if("close"==packet.type){self.onClose();return false}self.onPacket(packet)};parser.decodePayload(data,this.socket.binaryType,callback);if("closed"!=this.readyState){this.polling=false;this.emit("pollComplete");if("open"==this.readyState){this.poll()}else{debug('ignoring poll - transport state "%s"',this.readyState)}}};Polling.prototype.doClose=function(){var self=this;function close(){debug("writing close packet");self.write([{type:"close"}])}if("open"==this.readyState){debug("transport open - closing");close()}else{debug("transport not open - deferring close");this.once("open",close)}};Polling.prototype.write=function(packets){var self=this;this.writable=false;var callbackfn=function(){self.writable=true;self.emit("drain")};var self=this;parser.encodePayload(packets,this.supportsBinary,function(data){self.doWrite(data,callbackfn)})};Polling.prototype.uri=function(){var query=this.query||{};var schema=this.secure?"https":"http";var port="";if(false!==this.timestampRequests){query[this.timestampParam]=+new Date+"-"+Transport.timestamps++}if(!this.supportsBinary&&!query.sid){query.b64=1}query=parseqs.encode(query);if(this.port&&("https"==schema&&this.port!=443||"http"==schema&&this.port!=80)){port=":"+this.port}if(query.length){query="?"+query}return schema+"://"+this.hostname+port+this.path+query}},{"../transport":14,"component-inherit":21,debug:22,"engine.io-parser":25,parseqs:35,xmlhttprequest:20}],19:[function(_dereq_,module,exports){var Transport=_dereq_("../transport");var parser=_dereq_("engine.io-parser");var parseqs=_dereq_("parseqs");var inherit=_dereq_("component-inherit");var debug=_dereq_("debug")("engine.io-client:websocket");var WebSocket=_dereq_("ws");module.exports=WS;function WS(opts){var forceBase64=opts&&opts.forceBase64;if(forceBase64){this.supportsBinary=false}Transport.call(this,opts)}inherit(WS,Transport);WS.prototype.name="websocket";WS.prototype.supportsBinary=true;WS.prototype.doOpen=function(){if(!this.check()){return}var self=this;var uri=this.uri();var protocols=void 0;var opts={agent:this.agent};opts.pfx=this.pfx;opts.key=this.key;opts.passphrase=this.passphrase;opts.cert=this.cert;opts.ca=this.ca;opts.ciphers=this.ciphers;opts.rejectUnauthorized=this.rejectUnauthorized;this.ws=new WebSocket(uri,protocols,opts);if(this.ws.binaryType===undefined){this.supportsBinary=false}this.ws.binaryType="arraybuffer";this.addEventListeners()};WS.prototype.addEventListeners=function(){var self=this;this.ws.onopen=function(){self.onOpen()};this.ws.onclose=function(){self.onClose()};this.ws.onmessage=function(ev){self.onData(ev.data)};this.ws.onerror=function(e){self.onError("websocket error",e)}};if("undefined"!=typeof navigator&&/iPad|iPhone|iPod/i.test(navigator.userAgent)){WS.prototype.onData=function(data){var self=this;setTimeout(function(){Transport.prototype.onData.call(self,data)},0)}}WS.prototype.write=function(packets){var self=this;this.writable=false;for(var i=0,l=packets.length;i=31}exports.formatters.j=function(v){return JSON.stringify(v)};function formatArgs(){var args=arguments;var useColors=this.useColors;args[0]=(useColors?"%c":"")+this.namespace+(useColors?" %c":" ")+args[0]+(useColors?"%c ":" ")+"+"+exports.humanize(this.diff);if(!useColors)return args;var c="color: "+this.color;args=[args[0],c,"color: inherit"].concat(Array.prototype.slice.call(args,1));var index=0;var lastC=0;args[0].replace(/%[a-z%]/g,function(match){if("%"===match)return;index++;if("%c"===match){lastC=index}});args.splice(lastC,0,c);return args}function log(){return"object"==typeof console&&"function"==typeof console.log&&Function.prototype.apply.call(console.log,console,arguments)}function save(namespaces){try{if(null==namespaces){localStorage.removeItem("debug")}else{localStorage.debug=namespaces}}catch(e){}}function load(){var r;try{r=localStorage.debug}catch(e){}return r}exports.enable(load())},{"./debug":23}],23:[function(_dereq_,module,exports){exports=module.exports=debug;exports.coerce=coerce;exports.disable=disable;exports.enable=enable;exports.enabled=enabled;exports.humanize=_dereq_("ms");exports.names=[];exports.skips=[];exports.formatters={};var prevColor=0;var prevTime;function selectColor(){return exports.colors[prevColor++%exports.colors.length]}function debug(namespace){function disabled(){}disabled.enabled=false;function enabled(){var self=enabled;var curr=+new Date;var ms=curr-(prevTime||curr);self.diff=ms;self.prev=prevTime;self.curr=curr;prevTime=curr;if(null==self.useColors)self.useColors=exports.useColors();if(null==self.color&&self.useColors)self.color=selectColor();var args=Array.prototype.slice.call(arguments);args[0]=exports.coerce(args[0]);if("string"!==typeof args[0]){args=["%o"].concat(args)}var index=0;args[0]=args[0].replace(/%([a-z%])/g,function(match,format){if(match==="%")return match;index++;var formatter=exports.formatters[format];if("function"===typeof formatter){var val=args[index];match=formatter.call(self,val);args.splice(index,1);index--}return match});if("function"===typeof exports.formatArgs){args=exports.formatArgs.apply(self,args)}var logFn=enabled.log||exports.log||console.log.bind(console);logFn.apply(self,args)}enabled.enabled=true;var fn=exports.enabled(namespace)?enabled:disabled;fn.namespace=namespace;return fn}function enable(namespaces){exports.save(namespaces);var split=(namespaces||"").split(/[\s,]+/);var len=split.length;for(var i=0;i=d)return Math.round(ms/d)+"d";if(ms>=h)return Math.round(ms/h)+"h";if(ms>=m)return Math.round(ms/m)+"m";if(ms>=s)return Math.round(ms/s)+"s";return ms+"ms"}function long(ms){return plural(ms,d,"day")||plural(ms,h,"hour")||plural(ms,m,"minute")||plural(ms,s,"second")||ms+" ms"}function plural(ms,n,name){if(ms1){return{type:packetslist[type],data:data.substring(1)}}else{return{type:packetslist[type]}}}var asArray=new Uint8Array(data);var type=asArray[0];var rest=sliceBuffer(data,1);if(Blob&&binaryType==="blob"){rest=new Blob([rest])}return{type:packetslist[type],data:rest}};exports.decodeBase64Packet=function(msg,binaryType){var type=packetslist[msg.charAt(0)];if(!global.ArrayBuffer){return{type:type,data:{base64:true,data:msg.substr(1)}}}var data=base64encoder.decode(msg.substr(1));if(binaryType==="blob"&&Blob){data=new Blob([data])}return{type:type,data:data}};exports.encodePayload=function(packets,supportsBinary,callback){if(typeof supportsBinary=="function"){callback=supportsBinary;supportsBinary=null}var isBinary=hasBinary(packets);if(supportsBinary&&isBinary){if(Blob&&!dontSendBlobs){return exports.encodePayloadAsBlob(packets,callback)}return exports.encodePayloadAsArrayBuffer(packets,callback)}if(!packets.length){return callback("0:")}function setLengthHeader(message){return message.length+":"+message}function encodeOne(packet,doneCallback){exports.encodePacket(packet,!isBinary?false:supportsBinary,true,function(message){doneCallback(null,setLengthHeader(message))})}map(packets,encodeOne,function(err,results){return callback(results.join(""))})};function map(ary,each,done){var result=new Array(ary.length);var next=after(ary.length,done);var eachWithIndex=function(i,el,cb){each(el,function(error,msg){result[i]=msg;cb(error,result)})};for(var i=0;i0){var tailArray=new Uint8Array(bufferTail);var isString=tailArray[0]===0;var msgLength="";for(var i=1;;i++){if(tailArray[i]==255)break;if(msgLength.length>310){numberTooLong=true;break}msgLength+=tailArray[i]}if(numberTooLong)return callback(err,0,1);bufferTail=sliceBuffer(bufferTail,2+msgLength.length);msgLength=parseInt(msgLength);var msg=sliceBuffer(bufferTail,0,msgLength);if(isString){try{msg=String.fromCharCode.apply(null,new Uint8Array(msg))}catch(e){var typed=new Uint8Array(msg);msg="";for(var i=0;ibytes){end=bytes}if(start>=bytes||start>=end||bytes===0){return new ArrayBuffer(0)}var abv=new Uint8Array(arraybuffer);var result=new Uint8Array(end-start);for(var i=start,ii=0;i>2];base64+=chars[(bytes[i]&3)<<4|bytes[i+1]>>4];base64+=chars[(bytes[i+1]&15)<<2|bytes[i+2]>>6];base64+=chars[bytes[i+2]&63]}if(len%3===2){base64=base64.substring(0,base64.length-1)+"="}else if(len%3===1){base64=base64.substring(0,base64.length-2)+"=="}return base64};exports.decode=function(base64){var bufferLength=base64.length*.75,len=base64.length,i,p=0,encoded1,encoded2,encoded3,encoded4;if(base64[base64.length-1]==="="){bufferLength--;if(base64[base64.length-2]==="="){bufferLength--}}var arraybuffer=new ArrayBuffer(bufferLength),bytes=new Uint8Array(arraybuffer);for(i=0;i>4;bytes[p++]=(encoded2&15)<<4|encoded3>>2;bytes[p++]=(encoded3&3)<<6|encoded4&63}return arraybuffer}})("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/")},{}],30:[function(_dereq_,module,exports){(function(global){var BlobBuilder=global.BlobBuilder||global.WebKitBlobBuilder||global.MSBlobBuilder||global.MozBlobBuilder;var blobSupported=function(){try{var b=new Blob(["hi"]);return b.size==2}catch(e){return false}}();var blobBuilderSupported=BlobBuilder&&BlobBuilder.prototype.append&&BlobBuilder.prototype.getBlob;function BlobBuilderConstructor(ary,options){options=options||{};var bb=new BlobBuilder;for(var i=0;i=55296&&value<=56319&&counter65535){value-=65536;
-output+=stringFromCharCode(value>>>10&1023|55296);value=56320|value&1023}output+=stringFromCharCode(value)}return output}function createByte(codePoint,shift){return stringFromCharCode(codePoint>>shift&63|128)}function encodeCodePoint(codePoint){if((codePoint&4294967168)==0){return stringFromCharCode(codePoint)}var symbol="";if((codePoint&4294965248)==0){symbol=stringFromCharCode(codePoint>>6&31|192)}else if((codePoint&4294901760)==0){symbol=stringFromCharCode(codePoint>>12&15|224);symbol+=createByte(codePoint,6)}else if((codePoint&4292870144)==0){symbol=stringFromCharCode(codePoint>>18&7|240);symbol+=createByte(codePoint,12);symbol+=createByte(codePoint,6)}symbol+=stringFromCharCode(codePoint&63|128);return symbol}function utf8encode(string){var codePoints=ucs2decode(string);var length=codePoints.length;var index=-1;var codePoint;var byteString="";while(++index=byteCount){throw Error("Invalid byte index")}var continuationByte=byteArray[byteIndex]&255;byteIndex++;if((continuationByte&192)==128){return continuationByte&63}throw Error("Invalid continuation byte")}function decodeSymbol(){var byte1;var byte2;var byte3;var byte4;var codePoint;if(byteIndex>byteCount){throw Error("Invalid byte index")}if(byteIndex==byteCount){return false}byte1=byteArray[byteIndex]&255;byteIndex++;if((byte1&128)==0){return byte1}if((byte1&224)==192){var byte2=readContinuationByte();codePoint=(byte1&31)<<6|byte2;if(codePoint>=128){return codePoint}else{throw Error("Invalid continuation byte")}}if((byte1&240)==224){byte2=readContinuationByte();byte3=readContinuationByte();codePoint=(byte1&15)<<12|byte2<<6|byte3;if(codePoint>=2048){return codePoint}else{throw Error("Invalid continuation byte")}}if((byte1&248)==240){byte2=readContinuationByte();byte3=readContinuationByte();byte4=readContinuationByte();codePoint=(byte1&15)<<18|byte2<<12|byte3<<6|byte4;if(codePoint>=65536&&codePoint<=1114111){return codePoint}}throw Error("Invalid UTF-8 detected")}var byteArray;var byteCount;var byteIndex;function utf8decode(byteString){byteArray=ucs2decode(byteString);byteCount=byteArray.length;byteIndex=0;var codePoints=[];var tmp;while((tmp=decodeSymbol())!==false){codePoints.push(tmp)}return ucs2encode(codePoints)}var utf8={version:"2.0.0",encode:utf8encode,decode:utf8decode};if(typeof define=="function"&&typeof define.amd=="object"&&define.amd){define(function(){return utf8})}else if(freeExports&&!freeExports.nodeType){if(freeModule){freeModule.exports=utf8}else{var object={};var hasOwnProperty=object.hasOwnProperty;for(var key in utf8){hasOwnProperty.call(utf8,key)&&(freeExports[key]=utf8[key])}}}else{root.utf8=utf8}})(this)}).call(this,typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{}],34:[function(_dereq_,module,exports){(function(global){var rvalidchars=/^[\],:{}\s]*$/;var rvalidescape=/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g;var rvalidtokens=/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g;var rvalidbraces=/(?:^|:|,)(?:\s*\[)+/g;var rtrimLeft=/^\s+/;var rtrimRight=/\s+$/;module.exports=function parsejson(data){if("string"!=typeof data||!data){return null}data=data.replace(rtrimLeft,"").replace(rtrimRight,"");if(global.JSON&&JSON.parse){return JSON.parse(data)}if(rvalidchars.test(data.replace(rvalidescape,"@").replace(rvalidtokens,"]").replace(rvalidbraces,""))){return new Function("return "+data)()}}}).call(this,typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{}],35:[function(_dereq_,module,exports){exports.encode=function(obj){var str="";for(var i in obj){if(obj.hasOwnProperty(i)){if(str.length)str+="&";str+=encodeURIComponent(i)+"="+encodeURIComponent(obj[i])}}return str};exports.decode=function(qs){var qry={};var pairs=qs.split("&");for(var i=0,l=pairs.length;i1)))/4)-floor((year-1901+month)/100)+floor((year-1601+month)/400)}}if(!(isProperty={}.hasOwnProperty)){isProperty=function(property){var members={},constructor;if((members.__proto__=null,members.__proto__={toString:1},members).toString!=getClass){isProperty=function(property){var original=this.__proto__,result=property in(this.__proto__=null,this);this.__proto__=original;return result}}else{constructor=members.constructor;isProperty=function(property){var parent=(this.constructor||constructor).prototype;return property in this&&!(property in parent&&this[property]===parent[property])}}members=null;return isProperty.call(this,property)}}var PrimitiveTypes={"boolean":1,number:1,string:1,undefined:1};var isHostType=function(object,property){var type=typeof object[property];return type=="object"?!!object[property]:!PrimitiveTypes[type]};forEach=function(object,callback){var size=0,Properties,members,property;(Properties=function(){this.valueOf=0}).prototype.valueOf=0;members=new Properties;for(property in members){if(isProperty.call(members,property)){size++}}Properties=members=null;if(!size){members=["valueOf","toString","toLocaleString","propertyIsEnumerable","isPrototypeOf","hasOwnProperty","constructor"];forEach=function(object,callback){var isFunction=getClass.call(object)==functionClass,property,length;var hasProperty=!isFunction&&typeof object.constructor!="function"&&isHostType(object,"hasOwnProperty")?object.hasOwnProperty:isProperty;for(property in object){if(!(isFunction&&property=="prototype")&&hasProperty.call(object,property)){callback(property)}}for(length=members.length;property=members[--length];hasProperty.call(object,property)&&callback(property));}}else if(size==2){forEach=function(object,callback){var members={},isFunction=getClass.call(object)==functionClass,property;for(property in object){if(!(isFunction&&property=="prototype")&&!isProperty.call(members,property)&&(members[property]=1)&&isProperty.call(object,property)){callback(property)}}}}else{forEach=function(object,callback){var isFunction=getClass.call(object)==functionClass,property,isConstructor;for(property in object){if(!(isFunction&&property=="prototype")&&isProperty.call(object,property)&&!(isConstructor=property==="constructor")){callback(property)}}if(isConstructor||isProperty.call(object,property="constructor")){callback(property)}}}return forEach(object,callback)};if(!has("json-stringify")){var Escapes={92:"\\\\",34:'\\"',8:"\\b",12:"\\f",10:"\\n",13:"\\r",9:"\\t"};var leadingZeroes="000000";var toPaddedString=function(width,value){return(leadingZeroes+(value||0)).slice(-width)};var unicodePrefix="\\u00";var quote=function(value){var result='"',index=0,length=value.length,isLarge=length>10&&charIndexBuggy,symbols;if(isLarge){symbols=value.split("")}for(;index-1/0&&value<1/0){if(getDay){date=floor(value/864e5);for(year=floor(date/365.2425)+1970-1;getDay(year+1,0)<=date;year++);for(month=floor((date-getDay(year,0))/30.42);getDay(year,month+1)<=date;month++);date=1+date-getDay(year,month);time=(value%864e5+864e5)%864e5;hours=floor(time/36e5)%24;minutes=floor(time/6e4)%60;seconds=floor(time/1e3)%60;milliseconds=time%1e3}else{year=value.getUTCFullYear();month=value.getUTCMonth();date=value.getUTCDate();hours=value.getUTCHours();minutes=value.getUTCMinutes();seconds=value.getUTCSeconds();milliseconds=value.getUTCMilliseconds()}value=(year<=0||year>=1e4?(year<0?"-":"+")+toPaddedString(6,year<0?-year:year):toPaddedString(4,year))+"-"+toPaddedString(2,month+1)+"-"+toPaddedString(2,date)+"T"+toPaddedString(2,hours)+":"+toPaddedString(2,minutes)+":"+toPaddedString(2,seconds)+"."+toPaddedString(3,milliseconds)+"Z"}else{value=null}}else if(typeof value.toJSON=="function"&&(className!=numberClass&&className!=stringClass&&className!=arrayClass||isProperty.call(value,"toJSON"))){value=value.toJSON(property)}}if(callback){value=callback.call(object,property,value)}if(value===null){return"null"}className=getClass.call(value);if(className==booleanClass){return""+value}else if(className==numberClass){return value>-1/0&&value<1/0?""+value:"null"}else if(className==stringClass){return quote(""+value)}if(typeof value=="object"){for(length=stack.length;length--;){if(stack[length]===value){throw TypeError()}}stack.push(value);results=[];prefix=indentation;indentation+=whitespace;if(className==arrayClass){for(index=0,length=value.length;index0){for(whitespace="",width>10&&(width=10);whitespace.length=48&&charCode<=57||charCode>=97&&charCode<=102||charCode>=65&&charCode<=70)){abort()}}value+=fromCharCode("0x"+source.slice(begin,Index));break;default:abort()}}else{if(charCode==34){break}charCode=source.charCodeAt(Index);begin=Index;while(charCode>=32&&charCode!=92&&charCode!=34){charCode=source.charCodeAt(++Index)}value+=source.slice(begin,Index)}}if(source.charCodeAt(Index)==34){Index++;return value}abort();default:begin=Index;if(charCode==45){isSigned=true;charCode=source.charCodeAt(++Index)}if(charCode>=48&&charCode<=57){if(charCode==48&&(charCode=source.charCodeAt(Index+1),charCode>=48&&charCode<=57)){abort()}isSigned=false;for(;Index=48&&charCode<=57);Index++);if(source.charCodeAt(Index)==46){position=++Index;for(;position=48&&charCode<=57);position++);if(position==Index){abort()}Index=position}charCode=source.charCodeAt(Index);if(charCode==101||charCode==69){charCode=source.charCodeAt(++Index);if(charCode==43||charCode==45){Index++}for(position=Index;position=48&&charCode<=57);position++);if(position==Index){abort()}Index=position}return+source.slice(begin,Index)}if(isSigned){abort()}if(source.slice(Index,Index+4)=="true"){Index+=4;return true}else if(source.slice(Index,Index+5)=="false"){Index+=5;return false}else if(source.slice(Index,Index+4)=="null"){Index+=4;return null}abort()}}return"$"};var get=function(value){var results,hasMembers;if(value=="$"){abort()}if(typeof value=="string"){if((charIndexBuggy?value.charAt(0):value[0])=="@"){return value.slice(1)}if(value=="["){results=[];for(;;hasMembers||(hasMembers=true)){value=lex();if(value=="]"){break}if(hasMembers){if(value==","){value=lex();if(value=="]"){abort()}}else{abort()}}if(value==","){abort()}results.push(get(value))}return results}else if(value=="{"){results={};for(;;hasMembers||(hasMembers=true)){value=lex();if(value=="}"){break}if(hasMembers){if(value==","){value=lex();if(value=="}"){abort()}}else{abort()}}if(value==","||typeof value!="string"||(charIndexBuggy?value.charAt(0):value[0])!="@"||lex()!=":"){abort()}results[value.slice(1)]=get(lex())}return results}abort()}return value};var update=function(source,property,callback){var element=walk(source,property,callback);if(element===undef){delete source[property]}else{source[property]=element}};var walk=function(source,property,callback){var value=source[property],length;if(typeof value=="object"&&value){if(getClass.call(value)==arrayClass){for(length=value.length;length--;){update(value,length,callback)}}else{forEach(value,function(property){update(value,property,callback)})}}return callback.call(source,property,value)};JSON3.parse=function(source,callback){var result,value;Index=0;Source=""+source;result=get(lex());if(lex()!="$"){abort()}Index=Source=null;return callback&&getClass.call(callback)==functionClass?walk((value={},value[""]=result,value),"",callback):result}}}if(isLoader){define(function(){return JSON3})}})(this)},{}],50:[function(_dereq_,module,exports){module.exports=toArray;function toArray(list,index){var array=[];index=index||0;for(var i=index||0;i0&&!this.encoding){var pack=this.packetBuffer.shift();this.packet(pack)}};Manager.prototype.cleanup=function(){debug("cleanup");var sub;while(sub=this.subs.shift())sub.destroy();this.packetBuffer=[];this.encoding=false;this.lastPing=null;this.decoder.destroy()};Manager.prototype.close=Manager.prototype.disconnect=function(){debug("disconnect");this.skipReconnect=true;this.reconnecting=false;if("opening"==this.readyState){this.cleanup()}this.backoff.reset();this.readyState="closed";if(this.engine)this.engine.close()};Manager.prototype.onclose=function(reason){debug("onclose");this.cleanup();this.backoff.reset();this.readyState="closed";this.emit("close",reason);if(this._reconnection&&!this.skipReconnect){this.reconnect()}};Manager.prototype.reconnect=function(){if(this.reconnecting||this.skipReconnect)return this;var self=this;if(this.backoff.attempts>=this._reconnectionAttempts){debug("reconnect failed");this.backoff.reset();this.emitAll("reconnect_failed");this.reconnecting=false}else{var delay=this.backoff.duration();debug("will wait %dms before reconnect attempt",delay);this.reconnecting=true;var timer=setTimeout(function(){if(self.skipReconnect)return;debug("attempting reconnect");self.emitAll("reconnect_attempt",self.backoff.attempts);self.emitAll("reconnecting",self.backoff.attempts);if(self.skipReconnect)return;self.open(function(err){if(err){debug("reconnect attempt error");self.reconnecting=false;self.reconnect();self.emitAll("reconnect_error",err.data)}else{debug("reconnect success");self.onreconnect()}})},delay);this.subs.push({destroy:function(){clearTimeout(timer)}})}};Manager.prototype.onreconnect=function(){var attempt=this.backoff.attempts;this.reconnecting=false;this.backoff.reset();this.updateSocketIds();this.emitAll("reconnect",attempt)}},{"./on":3,"./socket":4,backo2:8,"component-bind":11,"component-emitter":12,debug:14,"engine.io-client":16,indexof:33,"socket.io-parser":41}],3:[function(_dereq_,module,exports){module.exports=on;function on(obj,ev,fn){obj.on(ev,fn);return{destroy:function(){obj.removeListener(ev,fn)}}}},{}],4:[function(_dereq_,module,exports){var parser=_dereq_("socket.io-parser");var Emitter=_dereq_("component-emitter");var toArray=_dereq_("to-array");var on=_dereq_("./on");var bind=_dereq_("component-bind");var debug=_dereq_("debug")("socket.io-client:socket");var hasBin=_dereq_("has-binary");module.exports=exports=Socket;var events={connect:1,connect_error:1,connect_timeout:1,connecting:1,disconnect:1,error:1,reconnect:1,reconnect_attempt:1,reconnect_failed:1,reconnect_error:1,reconnecting:1,ping:1,pong:1};var emit=Emitter.prototype.emit;function Socket(io,nsp){this.io=io;this.nsp=nsp;this.json=this;this.ids=0;this.acks={};this.receiveBuffer=[];this.sendBuffer=[];this.connected=false;this.disconnected=true;if(this.io.autoConnect)this.open()}Emitter(Socket.prototype);Socket.prototype.subEvents=function(){if(this.subs)return;var io=this.io;this.subs=[on(io,"open",bind(this,"onopen")),on(io,"packet",bind(this,"onpacket")),on(io,"close",bind(this,"onclose"))]};Socket.prototype.open=Socket.prototype.connect=function(){if(this.connected)return this;this.subEvents();this.io.open();if("open"==this.io.readyState)this.onopen();this.emit("connecting");return this};Socket.prototype.send=function(){var args=toArray(arguments);args.unshift("message");this.emit.apply(this,args);return this};Socket.prototype.emit=function(ev){if(events.hasOwnProperty(ev)){emit.apply(this,arguments);return this}var args=toArray(arguments);var parserType=parser.EVENT;if(hasBin(args)){parserType=parser.BINARY_EVENT}var packet={type:parserType,data:args};packet.options={};packet.options.compress=!this.flags||false!==this.flags.compress;if("function"==typeof args[args.length-1]){debug("emitting packet with ack id %d",this.ids);this.acks[this.ids]=args.pop();packet.id=this.ids++}if(this.connected){this.packet(packet)}else{this.sendBuffer.push(packet)}delete this.flags;return this};Socket.prototype.packet=function(packet){packet.nsp=this.nsp;this.io.packet(packet)};Socket.prototype.onopen=function(){debug("transport is open - connecting");if("/"!=this.nsp){this.packet({type:parser.CONNECT})}};Socket.prototype.onclose=function(reason){debug("close (%s)",reason);this.connected=false;this.disconnected=true;delete this.id;this.emit("disconnect",reason)};Socket.prototype.onpacket=function(packet){if(packet.nsp!=this.nsp)return;switch(packet.type){case parser.CONNECT:this.onconnect();break;case parser.EVENT:this.onevent(packet);break;case parser.BINARY_EVENT:this.onevent(packet);break;case parser.ACK:this.onack(packet);break;case parser.BINARY_ACK:this.onack(packet);break;case parser.DISCONNECT:this.ondisconnect();break;case parser.ERROR:this.emit("error",packet.data);break}};Socket.prototype.onevent=function(packet){var args=packet.data||[];debug("emitting event %j",args);if(null!=packet.id){debug("attaching ack callback to event");args.push(this.ack(packet.id))}if(this.connected){emit.apply(this,args)}else{this.receiveBuffer.push(args)}};Socket.prototype.ack=function(id){var self=this;var sent=false;return function(){if(sent)return;sent=true;var args=toArray(arguments);debug("sending ack %j",args);var type=hasBin(args)?parser.BINARY_ACK:parser.ACK;self.packet({type:type,id:id,data:args})}};Socket.prototype.onack=function(packet){var ack=this.acks[packet.id];if("function"==typeof ack){debug("calling ack %s with %j",packet.id,packet.data);ack.apply(this,packet.data);delete this.acks[packet.id]}else{debug("bad ack %s",packet.id)}};Socket.prototype.onconnect=function(){this.connected=true;this.disconnected=false;this.emit("connect");this.emitBuffered()};Socket.prototype.emitBuffered=function(){var i;for(i=0;ibytes){end=bytes}if(start>=bytes||start>=end||bytes===0){return new ArrayBuffer(0)}var abv=new Uint8Array(arraybuffer);var result=new Uint8Array(end-start);for(var i=start,ii=0;i0&&opts.jitter<=1?opts.jitter:0;this.attempts=0}Backoff.prototype.duration=function(){var ms=this.ms*Math.pow(this.factor,this.attempts++);if(this.jitter){var rand=Math.random();var deviation=Math.floor(rand*this.jitter*ms);ms=(Math.floor(rand*10)&1)==0?ms-deviation:ms+deviation}return Math.min(ms,this.max)|0};Backoff.prototype.reset=function(){this.attempts=0};Backoff.prototype.setMin=function(min){this.ms=min};Backoff.prototype.setMax=function(max){this.max=max};Backoff.prototype.setJitter=function(jitter){this.jitter=jitter}},{}],9:[function(_dereq_,module,exports){(function(chars){"use strict";exports.encode=function(arraybuffer){var bytes=new Uint8Array(arraybuffer),i,len=bytes.buffer.byteLength,base64="";for(i=0;i>2];base64+=chars[(bytes.buffer[i]&3)<<4|bytes.buffer[i+1]>>4];base64+=chars[(bytes.buffer[i+1]&15)<<2|bytes.buffer[i+2]>>6];base64+=chars[bytes.buffer[i+2]&63]}if(len%3===2){base64=base64.substring(0,base64.length-1)+"="}else if(len%3===1){base64=base64.substring(0,base64.length-2)+"=="}return base64};exports.decode=function(base64){var bufferLength=base64.length*.75,len=base64.length,i,p=0,encoded1,encoded2,encoded3,encoded4;if(base64[base64.length-1]==="="){bufferLength--;if(base64[base64.length-2]==="="){bufferLength--}}var arraybuffer=new ArrayBuffer(bufferLength),bytes=new Uint8Array(arraybuffer);for(i=0;i>4;bytes[p++]=(encoded2&15)<<4|encoded3>>2;bytes[p++]=(encoded3&3)<<6|encoded4&63}return arraybuffer}})("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/")},{}],10:[function(_dereq_,module,exports){(function(global){var BlobBuilder=global.BlobBuilder||global.WebKitBlobBuilder||global.MSBlobBuilder||global.MozBlobBuilder;var blobSupported=function(){try{var a=new Blob(["hi"]);return a.size===2}catch(e){return false}}();var blobSupportsArrayBufferView=blobSupported&&function(){try{var b=new Blob([new Uint8Array([1,2])]);return b.size===2}catch(e){return false}}();var blobBuilderSupported=BlobBuilder&&BlobBuilder.prototype.append&&BlobBuilder.prototype.getBlob;function mapArrayBufferViews(ary){for(var i=0;i=31}exports.formatters.j=function(v){return JSON.stringify(v)};function formatArgs(){var args=arguments;var useColors=this.useColors;args[0]=(useColors?"%c":"")+this.namespace+(useColors?" %c":" ")+args[0]+(useColors?"%c ":" ")+"+"+exports.humanize(this.diff);if(!useColors)return args;var c="color: "+this.color;args=[args[0],c,"color: inherit"].concat(Array.prototype.slice.call(args,1));var index=0;var lastC=0;args[0].replace(/%[a-z%]/g,function(match){if("%%"===match)return;index++;if("%c"===match){lastC=index}});args.splice(lastC,0,c);return args}function log(){return"object"===typeof console&&console.log&&Function.prototype.apply.call(console.log,console,arguments)}function save(namespaces){try{if(null==namespaces){exports.storage.removeItem("debug")}else{exports.storage.debug=namespaces}}catch(e){}}function load(){var r;try{r=exports.storage.debug}catch(e){}return r}exports.enable(load());function localstorage(){try{return window.localStorage}catch(e){}}},{"./debug":15}],15:[function(_dereq_,module,exports){exports=module.exports=debug;exports.coerce=coerce;exports.disable=disable;exports.enable=enable;exports.enabled=enabled;exports.humanize=_dereq_("ms");exports.names=[];exports.skips=[];exports.formatters={};var prevColor=0;var prevTime;function selectColor(){return exports.colors[prevColor++%exports.colors.length]}function debug(namespace){function disabled(){}disabled.enabled=false;function enabled(){var self=enabled;var curr=+new Date;var ms=curr-(prevTime||curr);self.diff=ms;self.prev=prevTime;self.curr=curr;prevTime=curr;if(null==self.useColors)self.useColors=exports.useColors();if(null==self.color&&self.useColors)self.color=selectColor();var args=Array.prototype.slice.call(arguments);args[0]=exports.coerce(args[0]);if("string"!==typeof args[0]){args=["%o"].concat(args)}var index=0;args[0]=args[0].replace(/%([a-z%])/g,function(match,format){if(match==="%%")return match;index++;var formatter=exports.formatters[format];if("function"===typeof formatter){var val=args[index];match=formatter.call(self,val);args.splice(index,1);index--}return match});if("function"===typeof exports.formatArgs){args=exports.formatArgs.apply(self,args)}var logFn=enabled.log||exports.log||console.log.bind(console);logFn.apply(self,args)}enabled.enabled=true;var fn=exports.enabled(namespace)?enabled:disabled;fn.namespace=namespace;return fn}function enable(namespaces){exports.save(namespaces);var split=(namespaces||"").split(/[\s,]+/);var len=split.length;for(var i=0;i0){this.extraHeaders=opts.extraHeaders}}this.open()}Socket.priorWebsocketSuccess=false;Emitter(Socket.prototype);Socket.protocol=parser.protocol;Socket.Socket=Socket;Socket.Transport=_dereq_("./transport");Socket.transports=_dereq_("./transports");Socket.parser=_dereq_("engine.io-parser");Socket.prototype.createTransport=function(name){debug('creating transport "%s"',name);var query=clone(this.query);query.EIO=parser.protocol;query.transport=name;if(this.id)query.sid=this.id;var transport=new transports[name]({agent:this.agent,hostname:this.hostname,port:this.port,secure:this.secure,path:this.path,query:query,forceJSONP:this.forceJSONP,jsonp:this.jsonp,forceBase64:this.forceBase64,enablesXDR:this.enablesXDR,timestampRequests:this.timestampRequests,timestampParam:this.timestampParam,policyPort:this.policyPort,socket:this,pfx:this.pfx,key:this.key,passphrase:this.passphrase,cert:this.cert,ca:this.ca,ciphers:this.ciphers,rejectUnauthorized:this.rejectUnauthorized,perMessageDeflate:this.perMessageDeflate,extraHeaders:this.extraHeaders});return transport};function clone(obj){var o={};for(var i in obj){if(obj.hasOwnProperty(i)){o[i]=obj[i]}}return o}Socket.prototype.open=function(){var transport;if(this.rememberUpgrade&&Socket.priorWebsocketSuccess&&this.transports.indexOf("websocket")!=-1){transport="websocket"}else if(0===this.transports.length){var self=this;setTimeout(function(){self.emit("error","No transports available")},0);return}else{transport=this.transports[0]}this.readyState="opening";try{transport=this.createTransport(transport)}catch(e){this.transports.shift();this.open();return}transport.open();this.setTransport(transport)};Socket.prototype.setTransport=function(transport){debug("setting transport %s",transport.name);var self=this;if(this.transport){debug("clearing existing transport %s",this.transport.name);this.transport.removeAllListeners()}this.transport=transport;transport.on("drain",function(){self.onDrain()}).on("packet",function(packet){self.onPacket(packet)}).on("error",function(e){self.onError(e)}).on("close",function(){self.onClose("transport close")})};Socket.prototype.probe=function(name){debug('probing transport "%s"',name);var transport=this.createTransport(name,{probe:1}),failed=false,self=this;Socket.priorWebsocketSuccess=false;function onTransportOpen(){if(self.onlyBinaryUpgrades){var upgradeLosesBinary=!this.supportsBinary&&self.transport.supportsBinary;failed=failed||upgradeLosesBinary}if(failed)return;debug('probe transport "%s" opened',name);transport.send([{type:"ping",data:"probe"}]);transport.once("packet",function(msg){if(failed)return;if("pong"==msg.type&&"probe"==msg.data){debug('probe transport "%s" pong',name);self.upgrading=true;self.emit("upgrading",transport);if(!transport)return;Socket.priorWebsocketSuccess="websocket"==transport.name;debug('pausing current transport "%s"',self.transport.name);self.transport.pause(function(){if(failed)return;if("closed"==self.readyState)return;debug("changing transport and sending upgrade packet");cleanup();self.setTransport(transport);transport.send([{type:"upgrade"}]);self.emit("upgrade",transport);transport=null;self.upgrading=false;self.flush()})}else{debug('probe transport "%s" failed',name);var err=new Error("probe error");err.transport=transport.name;self.emit("upgradeError",err)}})}function freezeTransport(){if(failed)return;failed=true;cleanup();transport.close();transport=null}function onerror(err){var error=new Error("probe error: "+err);error.transport=transport.name;freezeTransport();debug('probe transport "%s" failed because of error: %s',name,err);self.emit("upgradeError",error)}function onTransportClose(){onerror("transport closed")}function onclose(){onerror("socket closed")}function onupgrade(to){if(transport&&to.name!=transport.name){debug('"%s" works - aborting "%s"',to.name,transport.name);freezeTransport()}}function cleanup(){transport.removeListener("open",onTransportOpen);transport.removeListener("error",onerror);transport.removeListener("close",onTransportClose);self.removeListener("close",onclose);self.removeListener("upgrading",onupgrade)}transport.once("open",onTransportOpen);transport.once("error",onerror);transport.once("close",onTransportClose);
+this.once("close",onclose);this.once("upgrading",onupgrade);transport.open()};Socket.prototype.onOpen=function(){debug("socket open");this.readyState="open";Socket.priorWebsocketSuccess="websocket"==this.transport.name;this.emit("open");this.flush();if("open"==this.readyState&&this.upgrade&&this.transport.pause){debug("starting upgrade probes");for(var i=0,l=this.upgrades.length;i';iframe=document.createElement(html)}catch(e){iframe=document.createElement("iframe");iframe.name=self.iframeId;iframe.src="javascript:0"}iframe.id=self.iframeId;self.form.appendChild(iframe);self.iframe=iframe}initIframe();data=data.replace(rEscapedNewline,"\\\n");this.area.value=data.replace(rNewline,"\\n");try{this.form.submit()}catch(e){}if(this.iframe.attachEvent){this.iframe.onreadystatechange=function(){if(self.iframe.readyState=="complete"){complete()}}}else{this.iframe.onload=complete}}}).call(this,typeof self!=="undefined"?self:typeof window!=="undefined"?window:typeof global!=="undefined"?global:{})},{"./polling":23,"component-inherit":13}],22:[function(_dereq_,module,exports){(function(global){var XMLHttpRequest=_dereq_("xmlhttprequest-ssl");var Polling=_dereq_("./polling");var Emitter=_dereq_("component-emitter");var inherit=_dereq_("component-inherit");var debug=_dereq_("debug")("engine.io-client:polling-xhr");module.exports=XHR;module.exports.Request=Request;function empty(){}function XHR(opts){Polling.call(this,opts);if(global.location){var isSSL="https:"==location.protocol;var port=location.port;if(!port){port=isSSL?443:80}this.xd=opts.hostname!=global.location.hostname||port!=opts.port;this.xs=opts.secure!=isSSL}else{this.extraHeaders=opts.extraHeaders}}inherit(XHR,Polling);XHR.prototype.supportsBinary=true;XHR.prototype.request=function(opts){opts=opts||{};opts.uri=this.uri();opts.xd=this.xd;opts.xs=this.xs;opts.agent=this.agent||false;opts.supportsBinary=this.supportsBinary;opts.enablesXDR=this.enablesXDR;opts.pfx=this.pfx;opts.key=this.key;opts.passphrase=this.passphrase;opts.cert=this.cert;opts.ca=this.ca;opts.ciphers=this.ciphers;opts.rejectUnauthorized=this.rejectUnauthorized;opts.extraHeaders=this.extraHeaders;return new Request(opts)};XHR.prototype.doWrite=function(data,fn){var isBinary=typeof data!=="string"&&data!==undefined;var req=this.request({method:"POST",data:data,isBinary:isBinary});var self=this;req.on("success",fn);req.on("error",function(err){self.onError("xhr post error",err)});this.sendXhr=req};XHR.prototype.doPoll=function(){debug("xhr poll");var req=this.request();var self=this;req.on("data",function(data){self.onData(data)});req.on("error",function(err){self.onError("xhr poll error",err)});this.pollXhr=req};function Request(opts){this.method=opts.method||"GET";this.uri=opts.uri;this.xd=!!opts.xd;this.xs=!!opts.xs;this.async=false!==opts.async;this.data=undefined!=opts.data?opts.data:null;this.agent=opts.agent;this.isBinary=opts.isBinary;this.supportsBinary=opts.supportsBinary;this.enablesXDR=opts.enablesXDR;this.pfx=opts.pfx;this.key=opts.key;this.passphrase=opts.passphrase;this.cert=opts.cert;this.ca=opts.ca;this.ciphers=opts.ciphers;this.rejectUnauthorized=opts.rejectUnauthorized;this.extraHeaders=opts.extraHeaders;this.create()}Emitter(Request.prototype);Request.prototype.create=function(){var opts={agent:this.agent,xdomain:this.xd,xscheme:this.xs,enablesXDR:this.enablesXDR};opts.pfx=this.pfx;opts.key=this.key;opts.passphrase=this.passphrase;opts.cert=this.cert;opts.ca=this.ca;opts.ciphers=this.ciphers;opts.rejectUnauthorized=this.rejectUnauthorized;var xhr=this.xhr=new XMLHttpRequest(opts);var self=this;try{debug("xhr open %s: %s",this.method,this.uri);xhr.open(this.method,this.uri,this.async);try{if(this.extraHeaders){xhr.setDisableHeaderCheck(true);for(var i in this.extraHeaders){if(this.extraHeaders.hasOwnProperty(i)){xhr.setRequestHeader(i,this.extraHeaders[i])}}}}catch(e){}if(this.supportsBinary){xhr.responseType="arraybuffer"}if("POST"==this.method){try{if(this.isBinary){xhr.setRequestHeader("Content-type","application/octet-stream")}else{xhr.setRequestHeader("Content-type","text/plain;charset=UTF-8")}}catch(e){}}if("withCredentials"in xhr){xhr.withCredentials=true}if(this.hasXDR()){xhr.onload=function(){self.onLoad()};xhr.onerror=function(){self.onError(xhr.responseText)}}else{xhr.onreadystatechange=function(){if(4!=xhr.readyState)return;if(200==xhr.status||1223==xhr.status){self.onLoad()}else{setTimeout(function(){self.onError(xhr.status)},0)}}}debug("xhr data %s",this.data);xhr.send(this.data)}catch(e){setTimeout(function(){self.onError(e)},0);return}if(global.document){this.index=Request.requestsCount++;Request.requests[this.index]=this}};Request.prototype.onSuccess=function(){this.emit("success");this.cleanup()};Request.prototype.onData=function(data){this.emit("data",data);this.onSuccess()};Request.prototype.onError=function(err){this.emit("error",err);this.cleanup(true)};Request.prototype.cleanup=function(fromError){if("undefined"==typeof this.xhr||null===this.xhr){return}if(this.hasXDR()){this.xhr.onload=this.xhr.onerror=empty}else{this.xhr.onreadystatechange=empty}if(fromError){try{this.xhr.abort()}catch(e){}}if(global.document){delete Request.requests[this.index]}this.xhr=null};Request.prototype.onLoad=function(){var data;try{var contentType;try{contentType=this.xhr.getResponseHeader("Content-Type").split(";")[0]}catch(e){}if(contentType==="application/octet-stream"){data=this.xhr.response}else{if(!this.supportsBinary){data=this.xhr.responseText}else{try{data=String.fromCharCode.apply(null,new Uint8Array(this.xhr.response))}catch(e){var ui8Arr=new Uint8Array(this.xhr.response);var dataArray=[];for(var idx=0,length=ui8Arr.length;idx1){return{type:packetslist[type],data:data.substring(1)}}else{return{type:packetslist[type]}}}var asArray=new Uint8Array(data);var type=asArray[0];var rest=sliceBuffer(data,1);if(Blob&&binaryType==="blob"){rest=new Blob([rest])}return{type:packetslist[type],data:rest}};exports.decodeBase64Packet=function(msg,binaryType){var type=packetslist[msg.charAt(0)];if(!global.ArrayBuffer){return{type:type,data:{base64:true,data:msg.substr(1)}}}var data=base64encoder.decode(msg.substr(1));if(binaryType==="blob"&&Blob){data=new Blob([data])}return{type:type,data:data}};exports.encodePayload=function(packets,supportsBinary,callback){if(typeof supportsBinary=="function"){callback=supportsBinary;supportsBinary=null}var isBinary=hasBinary(packets);if(supportsBinary&&isBinary){if(Blob&&!dontSendBlobs){return exports.encodePayloadAsBlob(packets,callback)}return exports.encodePayloadAsArrayBuffer(packets,callback)}if(!packets.length){return callback("0:")}function setLengthHeader(message){return message.length+":"+message}function encodeOne(packet,doneCallback){exports.encodePacket(packet,!isBinary?false:supportsBinary,true,function(message){doneCallback(null,setLengthHeader(message))})}map(packets,encodeOne,function(err,results){return callback(results.join(""))})};function map(ary,each,done){var result=new Array(ary.length);var next=after(ary.length,done);var eachWithIndex=function(i,el,cb){each(el,function(error,msg){result[i]=msg;cb(error,result)})};for(var i=0;i0){var tailArray=new Uint8Array(bufferTail);var isString=tailArray[0]===0;var msgLength="";for(var i=1;;i++){if(tailArray[i]==255)break;if(msgLength.length>310){numberTooLong=true;break}msgLength+=tailArray[i]}if(numberTooLong)return callback(err,0,1);bufferTail=sliceBuffer(bufferTail,2+msgLength.length);msgLength=parseInt(msgLength);var msg=sliceBuffer(bufferTail,0,msgLength);if(isString){try{msg=String.fromCharCode.apply(null,new Uint8Array(msg))}catch(e){var typed=new Uint8Array(msg);msg="";for(var i=0;i1)))/4)-floor((year-1901+month)/100)+floor((year-1601+month)/400)}}if(!(isProperty=objectProto.hasOwnProperty)){isProperty=function(property){var members={},constructor;if((members.__proto__=null,members.__proto__={toString:1},members).toString!=getClass){isProperty=function(property){var original=this.__proto__,result=property in(this.__proto__=null,this);this.__proto__=original;return result}}else{constructor=members.constructor;isProperty=function(property){var parent=(this.constructor||constructor).prototype;return property in this&&!(property in parent&&this[property]===parent[property])}}members=null;return isProperty.call(this,property)}}forEach=function(object,callback){var size=0,Properties,members,property;(Properties=function(){this.valueOf=0}).prototype.valueOf=0;members=new Properties;for(property in members){if(isProperty.call(members,property)){size++}}Properties=members=null;if(!size){members=["valueOf","toString","toLocaleString","propertyIsEnumerable","isPrototypeOf","hasOwnProperty","constructor"];forEach=function(object,callback){var isFunction=getClass.call(object)==functionClass,property,length;var hasProperty=!isFunction&&typeof object.constructor!="function"&&objectTypes[typeof object.hasOwnProperty]&&object.hasOwnProperty||isProperty;for(property in object){if(!(isFunction&&property=="prototype")&&hasProperty.call(object,property)){callback(property)}}for(length=members.length;property=members[--length];hasProperty.call(object,property)&&callback(property));}}else if(size==2){forEach=function(object,callback){var members={},isFunction=getClass.call(object)==functionClass,property;for(property in object){if(!(isFunction&&property=="prototype")&&!isProperty.call(members,property)&&(members[property]=1)&&isProperty.call(object,property)){callback(property)}}}}else{forEach=function(object,callback){var isFunction=getClass.call(object)==functionClass,property,isConstructor;for(property in object){if(!(isFunction&&property=="prototype")&&isProperty.call(object,property)&&!(isConstructor=property==="constructor")){callback(property)}}if(isConstructor||isProperty.call(object,property="constructor")){callback(property)}}}return forEach(object,callback)};if(!has("json-stringify")){var Escapes={92:"\\\\",34:'\\"',8:"\\b",12:"\\f",10:"\\n",13:"\\r",9:"\\t"};var leadingZeroes="000000";var toPaddedString=function(width,value){return(leadingZeroes+(value||0)).slice(-width)};var unicodePrefix="\\u00";var quote=function(value){var result='"',index=0,length=value.length,useCharIndex=!charIndexBuggy||length>10;var symbols=useCharIndex&&(charIndexBuggy?value.split(""):value);for(;index-1/0&&value<1/0){if(getDay){date=floor(value/864e5);for(year=floor(date/365.2425)+1970-1;getDay(year+1,0)<=date;year++);for(month=floor((date-getDay(year,0))/30.42);getDay(year,month+1)<=date;month++);date=1+date-getDay(year,month);time=(value%864e5+864e5)%864e5;hours=floor(time/36e5)%24;minutes=floor(time/6e4)%60;seconds=floor(time/1e3)%60;milliseconds=time%1e3}else{year=value.getUTCFullYear();month=value.getUTCMonth();date=value.getUTCDate();hours=value.getUTCHours();minutes=value.getUTCMinutes();seconds=value.getUTCSeconds();milliseconds=value.getUTCMilliseconds()}value=(year<=0||year>=1e4?(year<0?"-":"+")+toPaddedString(6,year<0?-year:year):toPaddedString(4,year))+"-"+toPaddedString(2,month+1)+"-"+toPaddedString(2,date)+"T"+toPaddedString(2,hours)+":"+toPaddedString(2,minutes)+":"+toPaddedString(2,seconds)+"."+toPaddedString(3,milliseconds)+"Z"}else{value=null}}else if(typeof value.toJSON=="function"&&(className!=numberClass&&className!=stringClass&&className!=arrayClass||isProperty.call(value,"toJSON"))){value=value.toJSON(property)}}if(callback){value=callback.call(object,property,value)}if(value===null){return"null"}className=getClass.call(value);if(className==booleanClass){return""+value}else if(className==numberClass){return value>-1/0&&value<1/0?""+value:"null"}else if(className==stringClass){return quote(""+value)}if(typeof value=="object"){for(length=stack.length;length--;){if(stack[length]===value){throw TypeError()}}stack.push(value);results=[];prefix=indentation;indentation+=whitespace;if(className==arrayClass){for(index=0,length=value.length;index0){for(whitespace="",width>10&&(width=10);whitespace.length=48&&charCode<=57||charCode>=97&&charCode<=102||charCode>=65&&charCode<=70)){abort()}}value+=fromCharCode("0x"+source.slice(begin,Index));break;default:abort()}}else{if(charCode==34){break}charCode=source.charCodeAt(Index);begin=Index;while(charCode>=32&&charCode!=92&&charCode!=34){charCode=source.charCodeAt(++Index)}value+=source.slice(begin,Index)}}if(source.charCodeAt(Index)==34){Index++;return value}abort();default:begin=Index;if(charCode==45){isSigned=true;charCode=source.charCodeAt(++Index)}if(charCode>=48&&charCode<=57){if(charCode==48&&(charCode=source.charCodeAt(Index+1),charCode>=48&&charCode<=57)){abort()}isSigned=false;for(;Index=48&&charCode<=57);Index++);if(source.charCodeAt(Index)==46){position=++Index;for(;position=48&&charCode<=57);position++);if(position==Index){abort()}Index=position}charCode=source.charCodeAt(Index);if(charCode==101||charCode==69){charCode=source.charCodeAt(++Index);if(charCode==43||charCode==45){Index++}for(position=Index;position=48&&charCode<=57);position++);if(position==Index){abort()}Index=position}return+source.slice(begin,Index)}if(isSigned){abort()}if(source.slice(Index,Index+4)=="true"){Index+=4;return true}else if(source.slice(Index,Index+5)=="false"){Index+=5;return false}else if(source.slice(Index,Index+4)=="null"){Index+=4;return null}abort()}}return"$"};var get=function(value){var results,hasMembers;if(value=="$"){abort()}if(typeof value=="string"){if((charIndexBuggy?value.charAt(0):value[0])=="@"){return value.slice(1)}if(value=="["){results=[];for(;;hasMembers||(hasMembers=true)){value=lex();if(value=="]"){break}if(hasMembers){if(value==","){value=lex();if(value=="]"){abort()}}else{abort()}}if(value==","){abort()}results.push(get(value))}return results}else if(value=="{"){results={};for(;;hasMembers||(hasMembers=true)){value=lex();if(value=="}"){break}if(hasMembers){if(value==","){value=lex();if(value=="}"){abort()}}else{abort()}}if(value==","||typeof value!="string"||(charIndexBuggy?value.charAt(0):value[0])!="@"||lex()!=":"){abort()}results[value.slice(1)]=get(lex())}return results}abort()}return value};var update=function(source,property,callback){var element=walk(source,property,callback);if(element===undef){delete source[property]}else{source[property]=element}};var walk=function(source,property,callback){var value=source[property],length;if(typeof value=="object"&&value){if(getClass.call(value)==arrayClass){for(length=value.length;length--;){update(value,length,callback)}}else{forEach(value,function(property){update(value,property,callback)})}}return callback.call(source,property,value)};exports.parse=function(source,callback){var result,value;Index=0;Source=""+source;result=get(lex());if(lex()!="$"){abort()}Index=Source=null;return callback&&getClass.call(callback)==functionClass?walk((value={},value[""]=result,value),"",callback):result}}}exports["runInContext"]=runInContext;return exports}if(freeExports&&!isLoader){runInContext(root,freeExports)}else{var nativeJSON=root.JSON,previousJSON=root["JSON3"],isRestored=false;var JSON3=runInContext(root,root["JSON3"]={noConflict:function(){if(!isRestored){isRestored=true;root.JSON=nativeJSON;root["JSON3"]=previousJSON;nativeJSON=previousJSON=null}return JSON3}});root.JSON={parse:JSON3.parse,stringify:JSON3.stringify}}if(isLoader){define(function(){return JSON3})}}).call(this)}).call(this,typeof self!=="undefined"?self:typeof window!=="undefined"?window:typeof global!=="undefined"?global:{})},{}],36:[function(_dereq_,module,exports){var s=1e3;var m=s*60;var h=m*60;var d=h*24;var y=d*365.25;module.exports=function(val,options){options=options||{};if("string"==typeof val)return parse(val);return options.long?long(val):short(val)};function parse(str){str=""+str;if(str.length>1e4)return;var match=/^((?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|years?|yrs?|y)?$/i.exec(str);if(!match)return;var n=parseFloat(match[1]);var type=(match[2]||"ms").toLowerCase();switch(type){case"years":case"year":case"yrs":case"yr":case"y":return n*y;case"days":case"day":case"d":return n*d;case"hours":case"hour":case"hrs":case"hr":case"h":return n*h;case"minutes":case"minute":case"mins":case"min":case"m":return n*m;case"seconds":case"second":case"secs":case"sec":case"s":return n*s;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return n}}function short(ms){if(ms>=d)return Math.round(ms/d)+"d";if(ms>=h)return Math.round(ms/h)+"h";if(ms>=m)return Math.round(ms/m)+"m";if(ms>=s)return Math.round(ms/s)+"s";return ms+"ms"}function long(ms){return plural(ms,d,"day")||plural(ms,h,"hour")||plural(ms,m,"minute")||plural(ms,s,"second")||ms+" ms"}function plural(ms,n,name){if(ms=55296&&value<=56319&&counter65535){value-=65536;output+=stringFromCharCode(value>>>10&1023|55296);value=56320|value&1023}output+=stringFromCharCode(value)}return output}function checkScalarValue(codePoint){if(codePoint>=55296&&codePoint<=57343){throw Error("Lone surrogate U+"+codePoint.toString(16).toUpperCase()+" is not a scalar value")}}function createByte(codePoint,shift){return stringFromCharCode(codePoint>>shift&63|128)}function encodeCodePoint(codePoint){if((codePoint&4294967168)==0){return stringFromCharCode(codePoint)}var symbol="";if((codePoint&4294965248)==0){symbol=stringFromCharCode(codePoint>>6&31|192)}else if((codePoint&4294901760)==0){checkScalarValue(codePoint);symbol=stringFromCharCode(codePoint>>12&15|224);symbol+=createByte(codePoint,6)}else if((codePoint&4292870144)==0){symbol=stringFromCharCode(codePoint>>18&7|240);symbol+=createByte(codePoint,12);symbol+=createByte(codePoint,6)}symbol+=stringFromCharCode(codePoint&63|128);return symbol}function utf8encode(string){var codePoints=ucs2decode(string);var length=codePoints.length;var index=-1;var codePoint;var byteString="";while(++index=byteCount){throw Error("Invalid byte index")}var continuationByte=byteArray[byteIndex]&255;byteIndex++;if((continuationByte&192)==128){return continuationByte&63}throw Error("Invalid continuation byte")}function decodeSymbol(){var byte1;var byte2;var byte3;var byte4;var codePoint;if(byteIndex>byteCount){throw Error("Invalid byte index")}if(byteIndex==byteCount){return false}byte1=byteArray[byteIndex]&255;byteIndex++;if((byte1&128)==0){return byte1}if((byte1&224)==192){var byte2=readContinuationByte();codePoint=(byte1&31)<<6|byte2;if(codePoint>=128){return codePoint}else{throw Error("Invalid continuation byte")}}if((byte1&240)==224){byte2=readContinuationByte();byte3=readContinuationByte();codePoint=(byte1&15)<<12|byte2<<6|byte3;if(codePoint>=2048){checkScalarValue(codePoint);return codePoint}else{throw Error("Invalid continuation byte")}}if((byte1&248)==240){byte2=readContinuationByte();byte3=readContinuationByte();byte4=readContinuationByte();codePoint=(byte1&15)<<18|byte2<<12|byte3<<6|byte4;if(codePoint>=65536&&codePoint<=1114111){return codePoint}}throw Error("Invalid UTF-8 detected")}var byteArray;var byteCount;var byteIndex;function utf8decode(byteString){byteArray=ucs2decode(byteString);byteCount=byteArray.length;byteIndex=0;var codePoints=[];var tmp;while((tmp=decodeSymbol())!==false){codePoints.push(tmp)}return ucs2encode(codePoints)}var utf8={version:"2.0.0",encode:utf8encode,decode:utf8decode};
+if(typeof define=="function"&&typeof define.amd=="object"&&define.amd){define(function(){return utf8})}else if(freeExports&&!freeExports.nodeType){if(freeModule){freeModule.exports=utf8}else{var object={};var hasOwnProperty=object.hasOwnProperty;for(var key in utf8){hasOwnProperty.call(utf8,key)&&(freeExports[key]=utf8[key])}}}else{root.utf8=utf8}})(this)}).call(this,typeof self!=="undefined"?self:typeof window!=="undefined"?window:typeof global!=="undefined"?global:{})},{}],46:[function(_dereq_,module,exports){"use strict";var alphabet="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_".split(""),length=64,map={},seed=0,i=0,prev;function encode(num){var encoded="";do{encoded=alphabet[num%length]+encoded;num=Math.floor(num/length)}while(num>0);return encoded}function decode(str){var decoded=0;for(i=0;i
-///
-///
-
-
-module VORLON {
- declare var $: any;
- declare var vorlonBaseURL: string;
-
- export class DashboardManager {
- static CatalogUrl: string;
- static ListenClientid: string;
- static DisplayingClient: boolean;
- static ListenClientDisplayid: string;
- static SessionId: string;
- static ClientList: any;
- static PluginsLoaded: boolean;
-
- constructor(sessionid: string, listenClientid: string) {
- //Dashboard session id
- DashboardManager.SessionId = sessionid;
- DashboardManager.PluginsLoaded = false;
- DashboardManager.DisplayingClient = false;
- //Client ID
- DashboardManager.ListenClientid = listenClientid;
- DashboardManager.ClientList = {};
- DashboardManager.StartListeningServer()
- DashboardManager.GetClients();
- DashboardManager.CatalogUrl = vorlonBaseURL + "/config.json";
- }
-
- public static StartListeningServer(clientid: string = ""): void{
- var getUrl = window.location;
- var baseUrl = getUrl.protocol + "//" + getUrl.host;
- Core.StopListening();
- Core.StartDashboardSide(baseUrl, DashboardManager.SessionId, clientid, DashboardManager.divMapper);
- if(!Core.Messenger.onAddClient && !Core.Messenger.onAddClient){
- Core.Messenger.onAddClient = DashboardManager.addClient;
- Core.Messenger.onRemoveClient = DashboardManager.removeClient;
- }
-
- if(clientid !== ""){
- DashboardManager.DisplayingClient = true;
- }
- else {
- DashboardManager.DisplayingClient = false;
- }
- }
-
- public static GetClients(): void {
- let xhr = new XMLHttpRequest();
-
- xhr.onreadystatechange = () => {
- if (xhr.readyState === 4) {
- if (xhr.status === 200) {
- //Init ClientList Object
- DashboardManager.ClientList = {};
- document.getElementById('test').style.visibility='hidden';
-
- //Loading client list
- var clients = JSON.parse(xhr.responseText);
-
- //Test if the client to display is in the list
- var contains = false;
- if (clients && clients.length) {
- for (var j = 0; j < clients.length; j++) {
- if (clients[j].clientid === DashboardManager.ListenClientid) {
- contains = true;
- break;
- }
- }
- }
-
- //Get the client list placeholder
- var divClientsListPane = document.getElementById("clientsListPaneContent");
-
- //Create the new empty list
- var clientlist = document.createElement("ul");
- clientlist.setAttribute("id", "clientsListPaneContentList")
- divClientsListPane.appendChild(clientlist);
-
- //Show waiting logo
- if(!contains || clients.length === 0){
- var elt = document.querySelector('.dashboard-plugins-overlay');
- VORLON.Tools.RemoveClass(elt, 'hidden');
- }
-
- for (var i = 0; i < clients.length; i++) {
- var client = clients[i];
- DashboardManager.AddClientToList(client);
- }
-
- if (contains) {
- DashboardManager.loadPlugins();
- }
- }
- }
- }
-
- xhr.open("GET", vorlonBaseURL + "/api/getclients/" + DashboardManager.SessionId);
- xhr.send();
- }
-
- public static AddClientToList(client: any){
- var clientlist = document.getElementById("clientsListPaneContentList");
-
- if (DashboardManager.ListenClientid === "") {
- DashboardManager.ListenClientid = client.clientid;
- }
-
- var pluginlistelement = document.createElement("li");
- pluginlistelement.classList.add('client');
- pluginlistelement.id = client.clientid;
- if (client.clientid === DashboardManager.ListenClientid) {
- pluginlistelement.classList.add('active');
- }
-
- var clients = clientlist.children;
-
- //remove ghosts ones
- for (var i = 0; i < clients.length; i++) {
- var currentClient = (clients[i]);
- if(DashboardManager.ClientList[currentClient.id].displayid === client.displayid){
- clientlist.removeChild(currentClient);
- i--;
- }
- }
-
- if(clients.length === 0 || DashboardManager.ClientList[(clients[clients.length - 1]).id].displayid < client.displayid){
- clientlist.appendChild(pluginlistelement);
- }
- else if(clients.length === 1){
- var firstClient = clients[clients.length - 1];
- clientlist.insertBefore(pluginlistelement, firstClient);
- }
- else{
- for (var i = 0; i < clients.length - 1; i++) {
- var currentClient = (clients[i]);
- var nextClient = (clients[i+1]);
- if(DashboardManager.ClientList[currentClient.id].displayid < client.displayid
- && DashboardManager.ClientList[nextClient.id].displayid >= client.displayid){
- clientlist.insertBefore(pluginlistelement, nextClient);
- break;
- }
- else if(i === 0){
- clientlist.insertBefore(pluginlistelement, currentClient);
- }
- }
- }
-
- var pluginlistelementa = document.createElement("a");
- pluginlistelementa.textContent = " " + client.name + " - " + client.displayid;
- pluginlistelementa.setAttribute("href", vorlonBaseURL + "/dashboard/" + DashboardManager.SessionId + "/" + client.clientid);
- pluginlistelement.appendChild(pluginlistelementa);
-
- DashboardManager.ClientList[client.clientid] = client;
- }
-
- static ClientCount(): number{
- return Object.keys(DashboardManager.ClientList).length;
- }
-
- static UpdateClientInfo(): void {
- document.querySelector('[data-hook~=session-id]').textContent = DashboardManager.SessionId;
-
- if(DashboardManager.ClientList[DashboardManager.ListenClientid] != null){
- DashboardManager.ListenClientDisplayid = DashboardManager.ClientList[DashboardManager.ListenClientid].displayid;
- }
-
- document.querySelector('[data-hook~=client-id]').textContent = DashboardManager.ListenClientDisplayid;
- }
-
- static DisplayWaitingLogo(): void{
- //Hide waiting page and let's not bounce the logo !
- var elt = document.querySelector('.dashboard-plugins-overlay');
- VORLON.Tools.RemoveClass(elt, 'hidden');
- }
-
- static DisplayBouncingLogo(): void{
- //Hide waiting page and let's not bounce the logo !
- var elt = document.querySelector('.dashboard-plugins-overlay');
- VORLON.Tools.RemoveClass(elt, 'hidden');
- elt = document.querySelector('.waitLoader');
- VORLON.Tools.RemoveClass(elt, 'hidden');
- }
-
- public static loadPlugins(): void {
- if(DashboardManager.ListenClientid === ""){
- return;
- }
-
- if(this.PluginsLoaded){
- DashboardManager.StartListeningServer(DashboardManager.ListenClientid);
- return;
- }
-
- let xhr = new XMLHttpRequest();
- let divPluginsBottom = document.getElementById("pluginsPaneBottom");
- let divPluginsTop = document.getElementById("pluginsPaneTop");
- let divPluginBottomTabs = document.getElementById("pluginsListPaneBottom");
- let divPluginTopTabs = document.getElementById("pluginsListPaneTop");
- let coreLoaded = false;
-
- //Hide waiting page and let's bounce the logo !
- DashboardManager.DisplayBouncingLogo();
-
- xhr.onreadystatechange = () => {
- if (xhr.readyState === 4) {
- if (xhr.status === 200) {
- var catalog;
- try {
- catalog = JSON.parse(xhr.responseText);
- } catch (ex) {
- throw new Error("The catalog JSON is not well-formed");
- }
-
- var pluginLoaded = 0;
- var pluginstoload = 0;
-
- //Cleaning unwanted plugins
- for(var i = 0; i < catalog.plugins.length; i++){
- if(catalog.plugins[i].enabled){
- pluginstoload ++;
- }
- }
-
- for (var i = 0; i < catalog.plugins.length; i++) {
- var plugin = catalog.plugins[i];
-
- if(!plugin.enabled){
- continue;
- }
-
- var existingLocation = document.querySelector('[data-plugin=' + plugin.id + ']');
-
- if (!existingLocation) {
- var pluginmaindiv = document.createElement('div');
- pluginmaindiv.classList.add('plugin');
- pluginmaindiv.classList.add('plugin-' + plugin.id.toLowerCase());
- pluginmaindiv.setAttribute('data-plugin', plugin.id);
-
- var plugintab = document.createElement('div');
- plugintab.classList.add('tab');
- plugintab.textContent = plugin.name;
- plugintab.setAttribute('data-plugin-target', plugin.id);
-
- if (plugin.panel === "bottom") {
- if (divPluginsBottom.children.length === 1) {
- pluginmaindiv.classList.add("active");
- }
- divPluginsBottom.appendChild(pluginmaindiv);
- divPluginBottomTabs.appendChild(plugintab);
- }
- else {
- if (divPluginsTop.children.length === 1) {
- pluginmaindiv.classList.add("active");
- }
- divPluginsTop.appendChild(pluginmaindiv);
- divPluginTopTabs.appendChild(plugintab);
- }
- }
- var pluginscript = document.createElement("script");
- pluginscript.setAttribute("src", vorlonBaseURL + "/vorlon/plugins/" + plugin.foldername + "/vorlon." + plugin.foldername + ".dashboard.min.js");
-
- pluginscript.onload = (oError) => {
- pluginLoaded++;
- if (pluginLoaded >= pluginstoload) {
- DashboardManager.StartListeningServer(DashboardManager.ListenClientid);
- coreLoaded = true;
- this.PluginsLoaded = true;
- }
- };
- document.body.appendChild(pluginscript);
- }
-
- var addPluginBtn = document.createElement('div');
- addPluginBtn.className = "tab";
- addPluginBtn.innerText = "+";
- divPluginTopTabs.appendChild(addPluginBtn);
- addPluginBtn.addEventListener('click',() => {
- window.open("http://www.vorlonjs.io/plugins", "_blank");
- });
-
- var collaspseBtn = document.createElement('div');
- collaspseBtn.className = "fa fa-expand expandBtn";
- divPluginBottomTabs.appendChild(collaspseBtn);
- collaspseBtn.addEventListener('click',() => {
- divPluginsBottom.style.height = 'calc(100% - 58px)';
- divPluginsTop.style.height = '50px';
- $('.hsplitter', divPluginsTop.parentElement).css('top', '50px');
- });
-
- var collaspseTopBtn = document.createElement('div');
- collaspseTopBtn.className = "fa fa-expand expandBtn";
- divPluginTopTabs.appendChild(collaspseTopBtn);
- collaspseTopBtn.addEventListener('click',() => {
- divPluginsBottom.style.height = '50px';
- divPluginsTop.style.height = 'calc(100% - 58px)';
- $('.hsplitter', divPluginsTop.parentElement).css('top', 'calc(100% - 58px)');
- });
-
- DashboardManager.UpdateClientInfo();
- }
- }
- }
-
- xhr.open("GET", DashboardManager.CatalogUrl);
- xhr.send();
- }
-
- public static divMapper(pluginId: string): HTMLDivElement {
- let divId = pluginId + "div";
- return (document.getElementById(divId) || document.querySelector(`[data-plugin=${pluginId}]`));
- }
-
- public identify(): void {
- Core.Messenger.sendRealtimeMessage("", { "_sessionid": DashboardManager.SessionId }, VORLON.RuntimeSide.Dashboard, "identify");
- }
-
- public static ResetDashboard(reload: boolean = true): void {
- let sessionid = DashboardManager.SessionId;
- let xhr = new XMLHttpRequest();
- xhr.onreadystatechange = () => {
- if (xhr.readyState === 4) {
- if (xhr.status === 200) {
- if (reload) {
- location.reload();
- }
- }
- }
- }
-
- xhr.open("GET", vorlonBaseURL + "/api/reset/" + sessionid);
- xhr.send();
- }
-
- public static ReloadClient(): void {
- Core.Messenger.sendRealtimeMessage("", DashboardManager.ListenClientid, VORLON.RuntimeSide.Dashboard, "reload");
- }
-
- public static addClient(client: any): void {
- DashboardManager.AddClientToList(client);
- if(!DashboardManager.DisplayingClient){
- DashboardManager.loadPlugins();
- }
- }
-
- public static removeClient(client: any): void {
- let clientInList = document.getElementById(client.clientid);
- if(clientInList){
- if(client.clientid === DashboardManager.ListenClientid){
- DashboardManager.ListenClientid = "";
- DashboardManager.StartListeningServer();
- DashboardManager.DisplayWaitingLogo();
- }
-
- clientInList.parentElement.removeChild(clientInList);
- DashboardManager.removeInClientList(client);
-
- if (DashboardManager.ClientCount() === 0) {
- DashboardManager.ResetDashboard(false);
- DashboardManager.DisplayingClient = false;
- }
- }
- }
-
- public static removeInClientList(client: any): void{
- if(DashboardManager.ClientList[client.clientid] != null){
- delete DashboardManager.ClientList[client.clientid];
- }
- }
-
- public static getSessionId(): void {
- let xhr = new XMLHttpRequest();
-
- xhr.onreadystatechange = () => {
- if (xhr.readyState === 4) {
- if (xhr.status === 200) {
- var sessionId = xhr.responseText;
- window.location.assign(vorlonBaseURL + "/dashboard/" + sessionId);
- }
- }
- }
-
- xhr.open("GET", vorlonBaseURL + "/api/createsession");
- xhr.send();
- }
- }
-}
diff --git a/Server/public/vorlon.production.ts b/Server/public/vorlon.production.ts
new file mode 100644
index 00000000..24089de4
--- /dev/null
+++ b/Server/public/vorlon.production.ts
@@ -0,0 +1,65 @@
+module VORLON {
+ export class Production{
+ public isActivated : boolean;
+
+ constructor(public vorlonServerUrl: string, public vorlonSessionId : string, public useLocalStorage?: boolean){
+ var storage = useLocalStorage ? localStorage : sessionStorage;
+ var mustActivate = storage["vorlonActivation"] === "true";
+
+ if (this.vorlonServerUrl && this.vorlonServerUrl[this.vorlonServerUrl.length-1] !== '/'){
+ this.vorlonServerUrl = this.vorlonServerUrl + "/";
+ }
+
+ if (mustActivate){
+ this.addVorlonScript();
+ }
+ }
+
+ addVorlonScript(){
+ var storage = this.useLocalStorage ? localStorage : sessionStorage;
+ storage["vorlonActivation"] = "true";
+ this.isActivated = true;
+
+ var scriptElt = document.createElement("SCRIPT");
+ scriptElt.src = this.vorlonServerUrl + "vorlon.js" + (this.vorlonSessionId ? "/" + this.vorlonSessionId : "");
+ document.head.insertBefore(scriptElt, document.head.firstChild);
+ }
+
+ setIdentity(identity){
+ var storage = this.useLocalStorage ? localStorage : sessionStorage;
+ storage["vorlonClientIdentity"] = identity;
+ var v = VORLON;
+ if (v && v.Core){
+ v.Core.sendHelo();
+ }
+ }
+
+ getIdentity(){
+ var storage = this.useLocalStorage ? localStorage : sessionStorage;
+ return storage["vorlonClientIdentity"];
+ }
+
+ activate(reload : boolean){
+ if (this.isActivated)
+ return;
+
+ if (reload){
+ var storage = this.useLocalStorage ? localStorage : sessionStorage;
+ storage["vorlonActivation"] = "true";
+ this.isActivated = true;
+ window.location.reload();
+ }else{
+ this.addVorlonScript();
+ }
+ }
+
+ deactivate(reload : boolean){
+ var storage = this.useLocalStorage ? localStorage : sessionStorage;
+ storage["vorlonActivation"] = "false";
+ this.isActivated = false;
+ if (reload){
+ window.location.reload();
+ }
+ }
+ }
+}
\ No newline at end of file
diff --git a/Server/server.ts b/Server/server.ts
index 589e2c3d..291d9cec 100644
--- a/Server/server.ts
+++ b/Server/server.ts
@@ -1,31 +1,35 @@
-import httpConfig = require("./config/vorlon.httpconfig");
+import servercontext = require("./config/vorlon.servercontext");
import vorlonServer = require("./Scripts/vorlon.server");
import vorlonDashboard = require("./Scripts/vorlon.dashboard");
import vorlonWebserver = require("./Scripts/vorlon.webServer");
import vorlonHttpProxy = require("./Scripts/vorlon.httpproxy.server");
+import winstonLogger = require("./Scripts/vorlon.winstonlogger");
+
+var context = new servercontext.VORLON.DefaultContext();
-var config = new httpConfig.VORLON.HttpConfig();
// if proxyEnvPort==true start a standalone instance of httpProxy
-if (!config.proxyEnvPort) {
+if (!context.httpConfig.proxyEnvPort) {
+ //context.logger = new servercontext.VORLON.SimpleConsoleLogger();
+ var logger = new winstonLogger.VORLON.WinstonLogger(context);
//WEBSERVER
- var webServer = new vorlonWebserver.VORLON.WebServer();
+ var webServer = new vorlonWebserver.VORLON.WebServer(context);
//DASHBOARD
- var dashboard = new vorlonDashboard.VORLON.Dashboard();
+ var dashboard = new vorlonDashboard.VORLON.Dashboard(context);
//VORLON SERVER
- var server = new vorlonServer.VORLON.Server();
+ var server = new vorlonServer.VORLON.Server(context);
//VORLON HTTPPROXY
- var HttpProxy = new vorlonHttpProxy.VORLON.HttpProxy(false);
+ var HttpProxy = new vorlonHttpProxy.VORLON.HttpProxy(context, false);
+ webServer.components.push(logger);
webServer.components.push(dashboard);
webServer.components.push(server);
webServer.components.push(HttpProxy);
webServer.start();
}
-else {
-
- var serverProxy = new vorlonHttpProxy.VORLON.HttpProxy(true);
+else {
+ var serverProxy = new vorlonHttpProxy.VORLON.HttpProxy(context, true);
serverProxy.start();
}
diff --git a/Server/views/dashboard.jade b/Server/views/dashboard.jade
index f91dffa8..f02d81b8 100644
--- a/Server/views/dashboard.jade
+++ b/Server/views/dashboard.jade
@@ -7,7 +7,7 @@ block content
include includes/dashboard-plugins
block scripts
- script(src=baseURL + '/javascripts/socket.io-1.3.6.js')
+ script(src=baseURL + '/javascripts/socket.io-1.4.3.js')
script(src=baseURL + '/javascripts/x-tag-components.js')
script(src=baseURL + '/vorlon/vorlon-noplugin.max.js')
script(src=baseURL + '/vorlon.dashboardManager.js')
@@ -16,4 +16,4 @@ block scripts
script(src=baseURL + '/javascripts/dashboard.js')
script(src=baseURL + '/javascripts/jquery-ui.js' type="text/javascript")
script(src=baseURL + '/javascripts/contextMenu.js' type="text/javascript")
- script(src=baseURL + '/javascripts/jquery.switchButton.js' type="text/javascript")
+ script(src=baseURL + '/javascripts/jquery.switchButton.js' type="text/javascript")
\ No newline at end of file
diff --git a/Server/views/getsession.jade b/Server/views/getsession.jade
index ce75a2b0..543770d2 100644
--- a/Server/views/getsession.jade
+++ b/Server/views/getsession.jade
@@ -6,5 +6,5 @@ block content
a#createSessionButton.btn.btn-default.btn-getsession(onclick='VORLON.DashboardManager.getSessionId()') Create Session
block scripts
- script(src=baseURL + '/javascripts/socket.io-1.3.6.js')
+ script(src=baseURL + '/javascripts/socket.io-1.4.3.js')
script(src=baseURL + '/vorlon.dashboardManager.js')
diff --git a/Server/views/httpproxy.jade b/Server/views/httpproxy.jade
index d8d507c1..d3d70f53 100644
--- a/Server/views/httpproxy.jade
+++ b/Server/views/httpproxy.jade
@@ -18,7 +18,6 @@ html(lang='en')
img.logo(src="/images/VorlonLogo_Smooth.svg")
div.form
div.message Vorlon proxy allows you to use Vorlon on an existing website. Just enter the website url, and click on the button. Couldn't be easier !
- div.message Please note that, for now, the proxy will not work with websites using https.
div.input
input#url(type='text', placeholder='enter website url')
div.button
diff --git a/Server/views/includes/dashboard-plugins.jade b/Server/views/includes/dashboard-plugins.jade
index 1ece35cc..4df769ff 100644
--- a/Server/views/includes/dashboard-plugins.jade
+++ b/Server/views/includes/dashboard-plugins.jade
@@ -12,6 +12,8 @@ section.dashboard-plugins-container
h4#scriptSrc <script src="http://localhost:1337/vorlon.js"></script>
h3 Once your page is loaded, the client will appear in the sidebar on the left.
h3 Click on it to start inspecting your website.
+ h3 You could also inspect existing websites using
+ a(href="/httpproxy") Vorlon proxy
br
div.waitLoader.hidden
span.fa.fa-spin.fa-spinner
diff --git a/Server/views/includes/sidebar.jade b/Server/views/includes/sidebar.jade
index cd6adebb..cbe8b56c 100644
--- a/Server/views/includes/sidebar.jade
+++ b/Server/views/includes/sidebar.jade
@@ -13,4 +13,4 @@ section.sidebar
a(onclick='VORLON.DashboardManager.ResetDashboard()').btn.btn-secondary.btn-small.btn-reset Reset Dashboard
if authenticated
a#logout(href='/logout').btn.btn-secondary.btn-small.btn-reset logout
- a(onclick='VORLON.DashboardManager.ReloadClient()')#test.btn.btn-secondary1.btn-small.btn-reset Reload Client
\ No newline at end of file
+ a(onclick='VORLON.DashboardManager.ReloadClient()')#reload.btn.btn-secondary.btn-small.btn-reset.hidden Reload Client
\ No newline at end of file
diff --git a/Tests/gulpfile.tests.js b/Tests/gulpfile.tests.js
new file mode 100644
index 00000000..4962b145
--- /dev/null
+++ b/Tests/gulpfile.tests.js
@@ -0,0 +1,10 @@
+var gulp = require('gulp'),
+ mocha = require('gulp-mocha');
+
+/**
+ * Task that runs unit test using Mocha
+ */
+gulp.task('tests', function(){
+ gulp.src('server.vorlon.tools.tests.js')
+ .pipe(mocha());
+});
\ No newline at end of file
diff --git a/Tests/server.vorlon.tools.tests.js b/Tests/server.vorlon.tools.tests.js
new file mode 100644
index 00000000..c538da63
--- /dev/null
+++ b/Tests/server.vorlon.tools.tests.js
@@ -0,0 +1,57 @@
+var assert = require('assert');
+var vorlontools = require('../Server/Scripts/vorlon.tools');
+
+describe('Server/VORLON.Tools', function() {
+ describe('GetOperatingSystem()', function () {
+ it('should return Android for android user agent', function () {
+ var ua = "Mozilla/5.0 (Linux; ; ) AppleWebKit/ (KHTML, like Gecko) Chrome/ Mobile Safari/ ";
+ var expected = "Android";
+ var actual = vorlontools.VORLON.Tools.GetOperatingSystem(ua);
+ assert.equal(actual, expected);
+ });
+ });
+});
+
+describe('Server/VORLON.Tools', function() {
+ describe('GetOperatingSystem()', function () {
+ it('should return Windows for Windows user agent', function () {
+ var ua = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.135 Safari/537.36 Edge/12.10240";
+ var expected = "Windows";
+ var actual = vorlontools.VORLON.Tools.GetOperatingSystem(ua);
+ assert.equal(actual, expected);
+ });
+ });
+});
+
+describe('Server/VORLON.Tools', function() {
+ describe('GetOperatingSystem()', function () {
+ it('should return Windows Phone for Windows Phone user agent', function () {
+ var ua = "Mozilla/5.0 (compatible; MSIE 10.0; Windows Phone 8.0; Trident/6.0; IEMobile/10.0; ARM; Touch; NOKIA; Lumia 920)";
+ var expected = "Windows Phone";
+ var actual = vorlontools.VORLON.Tools.GetOperatingSystem(ua);
+ assert.equal(actual, expected);
+ });
+ });
+});
+
+describe('Server/VORLON.Tools', function() {
+ describe('GetOperatingSystem()', function () {
+ it('should return iOS for iPad user agent', function () {
+ var ua = "Mozilla/5.0 (iPad; CPU OS 6_0 like Mac OS X) AppleWebKit/536.26 (KHTML, like Gecko) Version/6.0 Mobile/10A5355d Safari/8536.25";
+ var expected = "iOS";
+ var actual = vorlontools.VORLON.Tools.GetOperatingSystem(ua);
+ assert.equal(actual, expected);
+ });
+ });
+});
+
+describe('Server/VORLON.Tools', function() {
+ describe('GetOperatingSystem()', function () {
+ it('should return Kindle for Kindle user agent', function () {
+ var ua = "Mozilla/4.0 (compatible; Linux 2.6.10) NetFront/3.4 Kindle/1.0 (screen 600x800)";
+ var expected = "Kindle";
+ var actual = vorlontools.VORLON.Tools.GetOperatingSystem(ua);
+ assert.equal(actual, expected);
+ });
+ });
+});
\ No newline at end of file
diff --git a/VorlonNodeWrapper/README.md b/VorlonNodeWrapper/README.md
new file mode 100644
index 00000000..567089c2
--- /dev/null
+++ b/VorlonNodeWrapper/README.md
@@ -0,0 +1,42 @@
+# Vorlon.JS
+
+A new, open source, extensible, platform-agnostic tool for remotely debugging and testing your JavaScript. Powered by node.js and socket.io.
+
+Understand all about Vorlon.js in 20 minutes watching this video : https://channel9.msdn.com/Shows/codechat/046
+
+Learn more at [VorlonJS](http://vorlonjs.com).
+
+## Vorlon.JS Node.js Wrapper
+
+The current project makes it easy for you to debug Node.js processes using Vorlon.js.
+Vorlon.js was first designed to debug web client app remotely.
+As Node.js is using JavaScript as its core language, we made it possible to use some of the Vorlon.js features in the context of a Node app.
+
+## What is possible with this
+
+You can remotely debug any of your node.js apps using plugins such as Object Explorer, XHR Panel and Interactive Console.
+Note : Breakpoints and step by step debugging is not available yet
+
+Full documentation available here : http://vorlonjs.io/documentation/#debugging-nodejs-applications
+
+## How to use it
+
+First install it :
+
+```
+npm install vorlon-node-wrapper
+```
+
+Then use it in your node app :
+
+```
+var vorlonWrapper = require("vorlon-node-wrapper");
+var serverUrl = "http://localhost:1337";
+var dashboardSession = "default";
+
+//This will connect to your Vorlon.js instance (serverUrl) and download the Vorlon.node.js client file (Vorlon for node).
+vorlonWrapper.start(serverUrl, dashboardSession, false);
+
+// Your code
+// ...
+```
\ No newline at end of file
diff --git a/VorlonNodeWrapper/package.json b/VorlonNodeWrapper/package.json
new file mode 100644
index 00000000..910c5fc9
--- /dev/null
+++ b/VorlonNodeWrapper/package.json
@@ -0,0 +1,13 @@
+{
+ "name": "vorlon-node-wrapper",
+ "version": "0.0.2",
+ "description": "Wrapper for getting Vorlon.js plugin file inside a node.js application",
+ "main": "wrapper.js",
+ "author": "Vorlon Team",
+ "dependencies": {
+ "require-hook": "^0.1.2",
+ "socket.io-client": "^1.4.4",
+ "url-join": "0.0.1",
+ "xmlhttprequest": "^1.8.0"
+ }
+}
\ No newline at end of file
diff --git a/VorlonNodeWrapper/wrapper.js b/VorlonNodeWrapper/wrapper.js
new file mode 100644
index 00000000..6cd7abc1
--- /dev/null
+++ b/VorlonNodeWrapper/wrapper.js
@@ -0,0 +1,50 @@
+var urljoin = require("url-join");
+
+(function(){
+ exports.start = function(vorlonjsURL, dashboardId, async, callback){
+ if(dashboardId == undefined){
+ dashboardId = "default";
+ }
+
+ var XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest;
+ var xhr = new XMLHttpRequest();
+ var vorlonNodeUrl = urljoin(vorlonjsURL, "vorlon.node.max.js/" + dashboardId);
+
+ if (async) {
+ xhr.onload = function (){
+ try {
+ eval(xhr.responseText);
+ VORLON.Core.StartClientSide(vorlonjsURL, dashboardId);
+ if (callback) {
+ callback(true, "n/a");
+ }
+ }
+ catch(e){
+ console.log("Wrapper Vorlon.js error : " + e.message);
+ if (callback) {
+ callback(false, e.message);
+ }
+ }
+ };
+ }
+
+ xhr.open("get", vorlonNodeUrl, async);
+ xhr.send();
+
+ if (!async) {
+ try {
+ eval(xhr.responseText);
+ VORLON.Core.StartClientSide(vorlonjsURL, dashboardId);
+ if (callback) {
+ callback(true, "n/a");
+ }
+ }
+ catch(e){
+ console.log("Wrapper Vorlon.js error : " + e.message);
+ if (callback) {
+ callback(false, e.message);
+ }
+ }
+ }
+ }
+})();
\ No newline at end of file
diff --git a/client samples/nodejs/.vscode/launch.json b/client samples/nodejs/.vscode/launch.json
new file mode 100644
index 00000000..b3e1d239
--- /dev/null
+++ b/client samples/nodejs/.vscode/launch.json
@@ -0,0 +1,30 @@
+{
+ "version": "0.2.0",
+ "configurations": [
+ {
+ "name": "Launch",
+ "type": "node",
+ "request": "launch",
+ "program": "app.js",
+ "stopOnEntry": false,
+ "args": [],
+ "cwd": ".",
+ "runtimeExecutable": null,
+ "runtimeArgs": [
+ "--nolazy"
+ ],
+ "env": {
+ "NODE_ENV": "development"
+ },
+ "externalConsole": false,
+ "sourceMaps": false,
+ "outDir": null
+ },
+ {
+ "name": "Attach",
+ "type": "node",
+ "request": "attach",
+ "port": 5858
+ }
+ ]
+}
\ No newline at end of file
diff --git a/client samples/nodejs/app.js b/client samples/nodejs/app.js
new file mode 100644
index 00000000..f8bbe9db
--- /dev/null
+++ b/client samples/nodejs/app.js
@@ -0,0 +1,50 @@
+var vorlonWrapper = require("vorlon-node-wrapper");
+var serverUrl = "http://localhost:1337";
+var dashboardSession = "default";
+
+vorlonWrapper.start(serverUrl, dashboardSession, false);
+
+console.log({
+ "ok": "oui",
+ "non": "si"
+});
+
+var a = 2;
+var first = function(){
+ setTimeout(
+ function(){
+ console.log(a++);
+ second();
+ },
+ 1000
+ );
+}
+
+var second = function(){
+ setTimeout(
+ function(){
+ console.log(a++);
+ first();
+
+ if (a > 2) {
+
+ var XMLHttpRequest = require("xhr2");
+ var xhr = new XMLHttpRequest();
+ xhr.onreadystatechange = function(){
+ if (xhr.readyState === 4) {
+ if (xhr.status === 200) {
+ console.log("xhr OK");
+ }
+ }
+ }
+
+ xhr.open("GET", "http://www.google.fr");
+ xhr.send();
+ }
+ },
+ 1000
+ );
+}
+
+first();
+
diff --git a/client samples/nodejs/package.json b/client samples/nodejs/package.json
new file mode 100644
index 00000000..2b0ad1d4
--- /dev/null
+++ b/client samples/nodejs/package.json
@@ -0,0 +1,17 @@
+{
+ "name": "testvorlonjs",
+ "version": "1.0.0",
+ "description": "",
+ "main": "vorlon-allplugins.max.js",
+ "scripts": {
+ "test": "echo \"Error: no test specified\" && exit 1"
+ },
+ "author": "",
+ "license": "ISC",
+ "dependencies": {
+ "socket.io": "^1.3.7",
+ "socket.io-client": "^1.3.7",
+ "vorlon-node-wrapper": "0.0.2",
+ "xmlhttprequest": "^1.8.0"
+ }
+}
diff --git a/client samples/webpage/.gitignore b/client samples/webpage/.gitignore
new file mode 100644
index 00000000..40b878db
--- /dev/null
+++ b/client samples/webpage/.gitignore
@@ -0,0 +1 @@
+node_modules/
\ No newline at end of file
diff --git a/Plugins/samples/bestpractices.css b/client samples/webpage/bestpractices.css
similarity index 97%
rename from Plugins/samples/bestpractices.css
rename to client samples/webpage/bestpractices.css
index 2a4a8ab0..3812ca11 100644
--- a/Plugins/samples/bestpractices.css
+++ b/client samples/webpage/bestpractices.css
@@ -24,6 +24,7 @@ body {
color : white;
border : none;
padding : 0.5em 1em;
+ cursor : pointer;
}
#test {
diff --git a/Plugins/samples/bestpractices.html b/client samples/webpage/bestpractices.html
similarity index 100%
rename from Plugins/samples/bestpractices.html
rename to client samples/webpage/bestpractices.html
diff --git a/client samples/webpage/browsersync.js b/client samples/webpage/browsersync.js
new file mode 100644
index 00000000..9365ab23
--- /dev/null
+++ b/client samples/webpage/browsersync.js
@@ -0,0 +1,12 @@
+/**
+ * Require Browsersync
+ */
+var browserSync = require('browser-sync').create();
+
+/**
+ * Run Browsersync with server config
+ */
+browserSync.init({
+ server: "./",
+ files: ["./**/*.html", "./**/*.css"]
+});
\ No newline at end of file
diff --git a/client samples/webpage/how-to-use-vorlon-in-production.html b/client samples/webpage/how-to-use-vorlon-in-production.html
new file mode 100644
index 00000000..699db715
--- /dev/null
+++ b/client samples/webpage/how-to-use-vorlon-in-production.html
@@ -0,0 +1,101 @@
+
+
+
+ Vorlon.js - How to use in production
+
+
+
+
+
+
+ How to use Vorlon.JS in production
+
+
+
+ Set client identity
+
+
+ Activate VORLON
+ Deactivate VORLON
+
+
+
+ For your production environment, you may not want to have Vorlon activated for all clients. It's often best to have a silent Vorlon that you could activate when necessary. This sample page shows how you could activate a Vorlon session on demand.
+ Instead of referencing directly the client script, reference "vorlon.production.js" like this:
+
+ <script src="http://localhost:1337/vorlon.production.js"></script>
+
+ This script is very small, and you can easily add it to your project's script bundles. Now you must create an instance of Vorlon production client.
+
+ <script type="text/javascript">
+ if (VORLON && VORLON.Production){
+ var vorlonProd = new VORLON.Production("http://localhost:1337", "mysessionid");
+ }
+ </script>
+
+
+ By default, nothing will happen. You have to activate Vorlon to have all Vorlon goodness activated. By default, activation state will get persisted in session storage. It means that Vorlon activation will occur for the lifetime of the running browser. If you want state to persist, just add an extra boolean to indicate you wish to store state in localStorage. In that case, Vorlon will keep activating until you explicitely deactivate it.
+
+ <script type="text/javascript">
+ if (VORLON && VORLON.Production){
+ var vorlonProd = new VORLON.Production("http://localhost:1337", "mysessionid", true);
+ }
+ </script>
+
+
+
+ Now you just have to call "vorlonProd.activate()" or "vorlonProd.deactivate()" to turn Vorlon on or off. You can call those methods with a boolean that indicate if you want to trigger a page reload.
+ Try it for yourself by clicking the buttons above !
+
+
+
+
+
+
+
diff --git a/Plugins/samples/index.css b/client samples/webpage/index.css
similarity index 92%
rename from Plugins/samples/index.css
rename to client samples/webpage/index.css
index 1e013681..b4f82aae 100644
--- a/Plugins/samples/index.css
+++ b/client samples/webpage/index.css
@@ -26,6 +26,7 @@ body {
color : white;
border : none;
padding : 0.5em 1em;
+ cursor : pointer;
}
#test {
@@ -49,6 +50,11 @@ body {
transform : scale(1);
transition : opacity 200ms ease-out;
}
+
+ input#clientidentity{
+ width : 300px;
+ max-width: 100%;
+ }
@media screen and (min-width :1280px){
body {
diff --git a/Plugins/samples/index.html b/client samples/webpage/index.html
similarity index 96%
rename from Plugins/samples/index.html
rename to client samples/webpage/index.html
index 2337e6a9..1d24377d 100644
--- a/Plugins/samples/index.html
+++ b/client samples/webpage/index.html
@@ -73,6 +73,11 @@ unitTest
+ Wants to use Vorlon in your production environment ?
+
+ If you want to use Vorlon in production, checkout this sample .
+
+
web standards and best practices
This block is for testing several aspects of web standards and best practice checks. Open the best practices sample to check more rules
diff --git a/client samples/webpage/package.json b/client samples/webpage/package.json
new file mode 100644
index 00000000..2e50636a
--- /dev/null
+++ b/client samples/webpage/package.json
@@ -0,0 +1,14 @@
+{
+ "name": "samples",
+ "version": "1.0.0",
+ "description": "",
+ "main": "browsersync.js",
+ "scripts": {
+ "test": "echo \"Error: no test specified\" && exit 1"
+ },
+ "author": "",
+ "license": "ISC",
+ "devDependencies": {
+ "browser-sync": "^2.9.12"
+ }
+}
diff --git a/client samples/webpage/readme.md b/client samples/webpage/readme.md
new file mode 100644
index 00000000..47630800
--- /dev/null
+++ b/client samples/webpage/readme.md
@@ -0,0 +1,14 @@
+#using Vorlon with browser-sync
+You could use Vorlon with [browser-sync](http://www.browsersync.io) to debug your web pages. It will allow you to live reload or test your website on multiple devices at once.
+
+To run Vorlon sample with browser-sync, run this command in this directory :
+npm install
+
+Then start your Vorlon server, and run this command (still in this directory) :
+node browsersync
+
+It will open Vorlon's sample page with this url : [http://localhost:3000](http://localhost:3000)
+
+You can access browser-sync dashboard on this url : [http://localhost:3001](http://localhost:3001)
+
+If you want to fine tune your browser-sync instance, or use browser-sync on a running website, please refer to [their documentation](http://www.browsersync.io/docs)
\ No newline at end of file
diff --git a/Plugins/samples/ship.svg b/client samples/webpage/ship.svg
similarity index 100%
rename from Plugins/samples/ship.svg
rename to client samples/webpage/ship.svg
diff --git a/Plugins/samples/unitTestRunner.html b/client samples/webpage/unitTestRunner.html
similarity index 100%
rename from Plugins/samples/unitTestRunner.html
rename to client samples/webpage/unitTestRunner.html
diff --git a/desktop/.editorconfig b/desktop/.editorconfig
new file mode 100644
index 00000000..92926b6d
--- /dev/null
+++ b/desktop/.editorconfig
@@ -0,0 +1,16 @@
+# editorconfig.org
+root = true
+
+[*]
+indent_style = space
+indent_size = 4
+end_of_line = lf
+charset = utf-8
+trim_trailing_whitespace = true
+insert_final_newline = true
+
+[*.json]
+indent_size = 2
+
+[*.md]
+trim_trailing_whitespace = false
diff --git a/desktop/.gitattributes b/desktop/.gitattributes
new file mode 100644
index 00000000..bdb0cabc
--- /dev/null
+++ b/desktop/.gitattributes
@@ -0,0 +1,17 @@
+# Auto detect text files and perform LF normalization
+* text=auto
+
+# Custom for Visual Studio
+*.cs diff=csharp
+
+# Standard to msysgit
+*.doc diff=astextplain
+*.DOC diff=astextplain
+*.docx diff=astextplain
+*.DOCX diff=astextplain
+*.dot diff=astextplain
+*.DOT diff=astextplain
+*.pdf diff=astextplain
+*.PDF diff=astextplain
+*.rtf diff=astextplain
+*.RTF diff=astextplain
diff --git a/desktop/.gitignore b/desktop/.gitignore
new file mode 100644
index 00000000..4d216527
--- /dev/null
+++ b/desktop/.gitignore
@@ -0,0 +1,9 @@
+node_modules
+*.log
+.DS_Store
+Thumbs.db
+
+/app/spec.js
+/build/
+/releases/
+/tmp/
diff --git a/desktop/README.md b/desktop/README.md
new file mode 100644
index 00000000..cdf5a989
--- /dev/null
+++ b/desktop/README.md
@@ -0,0 +1,32 @@
+Vorlon.js desktop
+==============
+This repository is for the desktop version of Vorlon.js. Set up could take a little time so packages for desktop app are not loaded when you initialize Vorlon repository.
+The project has been initiated from [Electron boilerplate](https://github.com/szwacz/electron-boilerplate).
+
+# Quick start
+To run this from source, you will need Node.js, so just make sure you have it installed.
+
+install all required packages by running
+```
+npm install
+```
+When everything is in place, run the following command :
+```
+npm start
+```
+
+# Making a release
+
+**Note:** There are various icon and bitmap files in `resources` directory. Those are used in installers.
+
+To make ready for distribution installer use command:
+```
+npm run release
+```
+It will start the packaging process for operating system you are running this command on. Ready for distribution file will be outputted to `releases` directory.
+
+You can create Windows installer only when running on Windows, the same is true for Linux and OSX. So to generate all three installers you need all three operating systems.
+
+
+## Special precautions for Windows
+As installer [NSIS](http://nsis.sourceforge.net/Main_Page) is used. You have to install it (version 3.0), and add NSIS folder to PATH in Environment Variables, so it is reachable to scripts in this project (path should look something like `C:/Program Files (x86)/NSIS`).
diff --git a/desktop/app/.gitignore b/desktop/app/.gitignore
new file mode 100644
index 00000000..ada5b9bf
--- /dev/null
+++ b/desktop/app/.gitignore
@@ -0,0 +1,4 @@
+*.js
+*.css
+vorlon/
+node_modules/
\ No newline at end of file
diff --git a/desktop/app/assets/404.png b/desktop/app/assets/404.png
new file mode 100644
index 00000000..43164c54
Binary files /dev/null and b/desktop/app/assets/404.png differ
diff --git a/desktop/app/assets/favicon.png b/desktop/app/assets/favicon.png
new file mode 100644
index 00000000..1152ffa8
Binary files /dev/null and b/desktop/app/assets/favicon.png differ
diff --git a/desktop/app/assets/header-pixel-logo-exhaust.svg b/desktop/app/assets/header-pixel-logo-exhaust.svg
new file mode 100644
index 00000000..4e9469ed
--- /dev/null
+++ b/desktop/app/assets/header-pixel-logo-exhaust.svg
@@ -0,0 +1,30 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/desktop/app/assets/header-pixel-logo-spaceship.svg b/desktop/app/assets/header-pixel-logo-spaceship.svg
new file mode 100644
index 00000000..d9634e88
--- /dev/null
+++ b/desktop/app/assets/header-pixel-logo-spaceship.svg
@@ -0,0 +1,124 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/desktop/app/assets/header-pixel-logo-text.svg b/desktop/app/assets/header-pixel-logo-text.svg
new file mode 100644
index 00000000..0b74abd1
--- /dev/null
+++ b/desktop/app/assets/header-pixel-logo-text.svg
@@ -0,0 +1,487 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/desktop/app/assets/header-planet-large.png b/desktop/app/assets/header-planet-large.png
new file mode 100644
index 00000000..d5414d14
Binary files /dev/null and b/desktop/app/assets/header-planet-large.png differ
diff --git a/desktop/app/assets/header-planet-medium.png b/desktop/app/assets/header-planet-medium.png
new file mode 100644
index 00000000..a590b8d4
Binary files /dev/null and b/desktop/app/assets/header-planet-medium.png differ
diff --git a/desktop/app/assets/header-planet-small.png b/desktop/app/assets/header-planet-small.png
new file mode 100644
index 00000000..ebc135e5
Binary files /dev/null and b/desktop/app/assets/header-planet-small.png differ
diff --git a/desktop/app/assets/header-satellite.png b/desktop/app/assets/header-satellite.png
new file mode 100644
index 00000000..a1dfc077
Binary files /dev/null and b/desktop/app/assets/header-satellite.png differ
diff --git a/desktop/app/assets/header-stars-distant.png b/desktop/app/assets/header-stars-distant.png
new file mode 100644
index 00000000..e57283cc
Binary files /dev/null and b/desktop/app/assets/header-stars-distant.png differ
diff --git a/desktop/app/assets/header-stars.png b/desktop/app/assets/header-stars.png
new file mode 100644
index 00000000..1e352620
Binary files /dev/null and b/desktop/app/assets/header-stars.png differ
diff --git a/desktop/app/assets/header-tube-1.png b/desktop/app/assets/header-tube-1.png
new file mode 100644
index 00000000..6857f2dd
Binary files /dev/null and b/desktop/app/assets/header-tube-1.png differ
diff --git a/desktop/app/assets/header-tube-2.png b/desktop/app/assets/header-tube-2.png
new file mode 100644
index 00000000..e94ec9f2
Binary files /dev/null and b/desktop/app/assets/header-tube-2.png differ
diff --git a/desktop/app/assets/header-tube-3.png b/desktop/app/assets/header-tube-3.png
new file mode 100644
index 00000000..d57f489c
Binary files /dev/null and b/desktop/app/assets/header-tube-3.png differ
diff --git a/desktop/app/assets/header-tube-data.png b/desktop/app/assets/header-tube-data.png
new file mode 100644
index 00000000..cda872f8
Binary files /dev/null and b/desktop/app/assets/header-tube-data.png differ
diff --git a/desktop/app/assets/icon-github.svg b/desktop/app/assets/icon-github.svg
new file mode 100644
index 00000000..4da253c3
--- /dev/null
+++ b/desktop/app/assets/icon-github.svg
@@ -0,0 +1,11 @@
+
+
+
+
+
diff --git a/desktop/app/assets/icon-lightbulb.svg b/desktop/app/assets/icon-lightbulb.svg
new file mode 100644
index 00000000..78241024
--- /dev/null
+++ b/desktop/app/assets/icon-lightbulb.svg
@@ -0,0 +1,12 @@
+
+
+
+
+
+
+
+
diff --git a/desktop/app/assets/icon-plus.svg b/desktop/app/assets/icon-plus.svg
new file mode 100644
index 00000000..f95c278a
--- /dev/null
+++ b/desktop/app/assets/icon-plus.svg
@@ -0,0 +1,8 @@
+
+
+
+
+
diff --git a/desktop/app/assets/icon-tag.svg b/desktop/app/assets/icon-tag.svg
new file mode 100644
index 00000000..c692581d
--- /dev/null
+++ b/desktop/app/assets/icon-tag.svg
@@ -0,0 +1,8 @@
+
+
+
+
+
diff --git a/desktop/app/assets/icon-twitter.svg b/desktop/app/assets/icon-twitter.svg
new file mode 100644
index 00000000..34a7e1ab
--- /dev/null
+++ b/desktop/app/assets/icon-twitter.svg
@@ -0,0 +1,10 @@
+
+
+
+
+
diff --git a/desktop/app/assets/icon-up-arrow.svg b/desktop/app/assets/icon-up-arrow.svg
new file mode 100644
index 00000000..f1e8e0a8
--- /dev/null
+++ b/desktop/app/assets/icon-up-arrow.svg
@@ -0,0 +1,8 @@
+
+
+
+
+
diff --git a/desktop/app/assets/icon-x-close.svg b/desktop/app/assets/icon-x-close.svg
new file mode 100644
index 00000000..3c78fea7
--- /dev/null
+++ b/desktop/app/assets/icon-x-close.svg
@@ -0,0 +1,8 @@
+
+
+
+
+
diff --git a/desktop/app/assets/illustration-computer-devices.png b/desktop/app/assets/illustration-computer-devices.png
new file mode 100644
index 00000000..921f40f8
Binary files /dev/null and b/desktop/app/assets/illustration-computer-devices.png differ
diff --git a/desktop/app/assets/npm-logo.svg b/desktop/app/assets/npm-logo.svg
new file mode 100644
index 00000000..4330983d
--- /dev/null
+++ b/desktop/app/assets/npm-logo.svg
@@ -0,0 +1 @@
+
\ No newline at end of file
diff --git a/desktop/app/assets/npm-shield.svg b/desktop/app/assets/npm-shield.svg
new file mode 100644
index 00000000..796220f1
--- /dev/null
+++ b/desktop/app/assets/npm-shield.svg
@@ -0,0 +1 @@
+npm npm v1.0.0 v1.0.0
diff --git a/desktop/app/assets/vorlon-logo-purple.svg b/desktop/app/assets/vorlon-logo-purple.svg
new file mode 100644
index 00000000..0e00d890
--- /dev/null
+++ b/desktop/app/assets/vorlon-logo-purple.svg
@@ -0,0 +1,33 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/desktop/app/assets/vorlon-logo-white.svg b/desktop/app/assets/vorlon-logo-white.svg
new file mode 100644
index 00000000..9b1b660a
--- /dev/null
+++ b/desktop/app/assets/vorlon-logo-white.svg
@@ -0,0 +1,33 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/desktop/app/assets/vorlon-pixel-logo-large.svg b/desktop/app/assets/vorlon-pixel-logo-large.svg
new file mode 100644
index 00000000..4605c732
--- /dev/null
+++ b/desktop/app/assets/vorlon-pixel-logo-large.svg
@@ -0,0 +1,638 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/desktop/app/assets/vorlon-pixel-logo-xsmall-purple.svg b/desktop/app/assets/vorlon-pixel-logo-xsmall-purple.svg
new file mode 100644
index 00000000..cbe465bd
--- /dev/null
+++ b/desktop/app/assets/vorlon-pixel-logo-xsmall-purple.svg
@@ -0,0 +1,43 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/desktop/app/assets/vorlon-pixel-logo-xsmall-white.svg b/desktop/app/assets/vorlon-pixel-logo-xsmall-white.svg
new file mode 100644
index 00000000..629478a6
--- /dev/null
+++ b/desktop/app/assets/vorlon-pixel-logo-xsmall-white.svg
@@ -0,0 +1,42 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/desktop/app/background.ts b/desktop/app/background.ts
new file mode 100644
index 00000000..ce361b4e
--- /dev/null
+++ b/desktop/app/background.ts
@@ -0,0 +1,267 @@
+///
+///
+
+// This is main process of Electron, started as first thing when the Electron
+// app starts, and running through entire life of your application.
+
+import app = require('app');
+var ipc = require('ipc');
+
+import childProcess = require('child_process');
+var kill = require('tree-kill');
+import path = require('path');
+import http = require('http');
+
+import BrowserWindow = require('browser-window');
+var env = require('./scripts/env_config');
+var devHelper = require('./scripts/dev_helper');
+var windowStateKeeper = require('./scripts/window_state');
+
+
+import vorlonhttpConfig = require("./vorlon/config/vorlon.httpconfig");
+import vorlonServer = require("./vorlon/Scripts/vorlon.server");
+import vorlonDashboard = require("./vorlon/Scripts/vorlon.dashboard");
+import vorlonWebserver = require("./vorlon/Scripts/vorlon.webServer");
+import vorlonHttpProxy = require("./vorlon/Scripts/vorlon.httpproxy.server");
+import config = require("./vorlon.config");
+
+var mainWindow : GitHubElectron.BrowserWindow;
+var vorlonServerProcess : childProcess.ChildProcess = null;
+var dashboardWindows = {};
+var errors = [];
+var messages = [];
+var userDataPath = app.getPath('userData');
+console.log("user data path : " + userDataPath);
+
+// Preserver of the window size and position between app launches.
+var mainWindowState = windowStateKeeper('main', {
+ width: 800,
+ height: 600
+});
+
+app.on('ready', function () {
+
+ mainWindow = new BrowserWindow({
+ x: mainWindowState.x,
+ y: mainWindowState.y,
+ width: mainWindowState.width,
+ height: mainWindowState.height
+ });
+
+ if (mainWindowState.isMaximized) {
+ mainWindow.maximize();
+ }
+
+ if (env && env.name === 'test') {
+ mainWindow.loadUrl('file://' + __dirname + '/spec.html');
+ } else {
+ mainWindow.loadUrl('file://' + __dirname + '/mainpage.html');
+ }
+
+ if (!env || env.name !== 'production') {
+ devHelper.setDevMenu();
+ //mainWindow.openDevTools();
+ }
+
+ mainWindow.on('close', function () {
+ mainWindowState.saveState(mainWindow);
+ app.quit();
+ });
+
+ startVorlonProcess();
+
+ //test browser features
+ // var testWindow = new BrowserWindow({
+ // x: mainWindowState.x,
+ // y: mainWindowState.y,
+ // width: mainWindowState.width,
+ // height: mainWindowState.height
+ // });
+ // testWindow.loadUrl('http://html5test.com/');
+});
+
+app.on('window-all-closed', function () {
+ app.quit();
+});
+
+app.on('window-all-closed', function () {
+ app.quit();
+});
+
+ipc.on("opendashboard", function (event, arg) {
+ console.log("receive opendashboard for " + JSON.stringify(arg));
+ if (arg && arg.sessionid) {
+ openDashboardWindow(arg.sessionid);
+ }
+});
+
+ipc.on("startVorlon", function (event, arg) {
+ console.log("received startVorlon command");
+ startVorlonProcess();
+});
+
+ipc.on("stopVorlon", function (event, arg) {
+ console.log("received stopVorlon command");
+ stopVorlonProcess();
+});
+
+ipc.on("getVorlonStatus", function (event, arg) {
+ sendVorlonStatus(event, arg);
+});
+
+ipc.on("getVorlonSessions", function (event, arg) {
+ if (vorlonServerProcess){
+ vorlonServerProcess.send({ message: "getsessions" }, null);
+ }
+});
+
+ipc.on("updateSession", function (event, arg) {
+ console.log("received updateSession", arg);
+ var dashboardwindow = dashboardWindows[arg.sessionid];
+ if (dashboardwindow){
+ openDashboardWindow(arg.sessionid)
+ }
+});
+
+function sendVorlonStatus(event?, arg?){
+ var msg = {
+ running : vorlonServerProcess != null,
+ errors : errors,
+ messages : messages
+ };
+
+ if (event){
+ //console.log("sending status", msg);
+ event.sender.send('vorlonStatus', msg);
+ }else{
+ //console.log("sending status to mainwindow", msg);
+ mainWindow.send('vorlonStatus', msg);
+ }
+}
+
+function sendLog(logs, sender?){
+ var msg = {logs : logs};
+
+ if (sender){
+ sender.send('vorlonlog', msg);
+ }else if (mainWindow) {
+ mainWindow.send('vorlonlog', msg);
+ }
+}
+
+function openDashboardWindow(sessionid) {
+ sessionid = sessionid || 'default';
+
+ var cfg = config.getConfig(userDataPath);
+ var existing = dashboardWindows[sessionid];
+ if (existing){
+ existing.show();
+ existing.loadUrl('http://localhost:' + cfg.port + '/dashboard/' + sessionid);
+ return ;
+ }
+
+ var dashboardwdw = new BrowserWindow({
+ x: mainWindowState.x,
+ y: mainWindowState.y,
+ width: mainWindowState.width,
+ height: mainWindowState.height,
+ "node-integration": false
+ });
+
+ //dashboardwdw.openDevTools();
+ console.log("create dashboard window for " + sessionid);
+ //load empty page first to prevent bad window title
+ dashboardwdw.loadUrl('file://' + __dirname + '/emptypage.html');
+ setTimeout(function () {
+ dashboardwdw.loadUrl('http://localhost:' + cfg.port + '/dashboard/' + sessionid);
+ }, 100);
+
+ dashboardWindows[sessionid] = dashboardwdw;
+ dashboardwdw.on('close', function () {
+ dashboardWindows[sessionid] = null;
+ });
+
+ dashboardwdw.webContents.on('did-fail-load', function(event, errorCode, errorDescription, validateUrl){
+ console.log("dashboard page error " + validateUrl + " " + errorCode + " " + errorDescription);
+ dashboardwdw.loadUrl('file://' + __dirname + '/dasboardloaderrorpage.html');
+ });
+}
+
+function startVorlonProcess() {
+ if (!vorlonServerProcess) {
+ var scriptpath = path.join(__dirname, 'vorlon.js');
+ console.log("starting silent " + scriptpath);
+ var vorlon = childProcess.fork(scriptpath, [userDataPath], { silent: true });
+ //var vorlon = childProcess.spawn('node', [scriptpath], {});
+ errors = [];
+ messages = [];
+
+ vorlonServerProcess = vorlon;
+
+ vorlon.on('message', function (m) {
+ if (m.log){
+ messages.push(m.log);
+ if (m.level == "error"){
+ errors.push(m.log);
+ }
+ console.log.apply(null, m.log.args);
+ sendLog([m.log]);
+ } else if (m.session){
+ console.log("session " + m.session.action, m.session.session);
+ mainWindow.send("session." + m.session.action, m.session.session);
+ }
+ //console.log("message:", m);
+ });
+
+ vorlon.on('close', function (code, arg) {
+ console.log("VORLON CLOSED WITH CODE " + code, arg);
+ stopVorlonProcess();
+ });
+
+ sendVorlonStatus();
+
+ setTimeout(function() {
+ callVorlonServer(config.getConfig(userDataPath));
+ }, 1000);
+ }
+}
+
+function stopVorlonProcess() {
+ if (vorlonServerProcess) {
+ kill(vorlonServerProcess.pid, 'SIGKILL', function () {
+ vorlonServerProcess = null;
+ sendVorlonStatus();
+ });
+ }
+}
+
+function callVorlonServer(cfg){
+ //when application is packaged to an exe, first call to style.css sometimes hang on Windows
+ console.log("calling vorlon server on " + cfg.port);
+ var options = {
+ host: 'localhost',
+ port: cfg.port,
+ path: '/stylesheets/style.css',
+ method: 'GET'
+ };
+
+ var req = http.request(options, function(res) {
+ // console.log('STATUS: ' + res.statusCode);
+ // console.log('HEADERS: ' + JSON.stringify(res.headers));
+ // res.setEncoding('utf8');
+ res.on('data', function (chunk) {
+ console.log('server call ok');
+ });
+
+ res.on('error', function (err) {
+ console.error('server call error');
+ });
+ });
+
+ req.setTimeout(2000, function(){
+ req.abort();
+ callVorlonServer(cfg);
+ });
+
+ req.end();
+}
\ No newline at end of file
diff --git a/desktop/app/dasboardloaderrorpage.html b/desktop/app/dasboardloaderrorpage.html
new file mode 100644
index 00000000..a22e7000
--- /dev/null
+++ b/desktop/app/dasboardloaderrorpage.html
@@ -0,0 +1,15 @@
+
+
+
+
+ Vorlon.js desktop
+
+
+
+
+
+
+ ERROR loading dashboard. Check that Vorlon is running and try re-openning dashboard window.
+
+
+
diff --git a/desktop/app/dashboard.html b/desktop/app/dashboard.html
new file mode 100644
index 00000000..4547e980
--- /dev/null
+++ b/desktop/app/dashboard.html
@@ -0,0 +1,20 @@
+
+
+
+
+ Electron Boilerplate
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/desktop/app/emptypage.html b/desktop/app/emptypage.html
new file mode 100644
index 00000000..31254f15
--- /dev/null
+++ b/desktop/app/emptypage.html
@@ -0,0 +1,15 @@
+
+
+
+
+ Vorlon.js desktop
+
+
+
+
+
+
+ loading dashboard...
+
+
+
diff --git a/desktop/app/fonts/dripicons/fonts/dripicons.eot b/desktop/app/fonts/dripicons/fonts/dripicons.eot
new file mode 100644
index 00000000..449a93c9
Binary files /dev/null and b/desktop/app/fonts/dripicons/fonts/dripicons.eot differ
diff --git a/desktop/app/fonts/dripicons/fonts/dripicons.svg b/desktop/app/fonts/dripicons/fonts/dripicons.svg
new file mode 100644
index 00000000..f179fd36
--- /dev/null
+++ b/desktop/app/fonts/dripicons/fonts/dripicons.svg
@@ -0,0 +1,105 @@
+
+
+
+This SVG font generated by Fontastic.me
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/desktop/app/fonts/dripicons/fonts/dripicons.ttf b/desktop/app/fonts/dripicons/fonts/dripicons.ttf
new file mode 100644
index 00000000..6c698488
Binary files /dev/null and b/desktop/app/fonts/dripicons/fonts/dripicons.ttf differ
diff --git a/desktop/app/fonts/dripicons/fonts/dripicons.woff b/desktop/app/fonts/dripicons/fonts/dripicons.woff
new file mode 100644
index 00000000..b8c13c89
Binary files /dev/null and b/desktop/app/fonts/dripicons/fonts/dripicons.woff differ
diff --git a/desktop/app/fonts/dripicons/icons-reference.html b/desktop/app/fonts/dripicons/icons-reference.html
new file mode 100644
index 00000000..f65bd75f
--- /dev/null
+++ b/desktop/app/fonts/dripicons/icons-reference.html
@@ -0,0 +1,816 @@
+
+
+
+
+
+
+ Dripicons (Line-Icon Font) by Amit Jakhu
+
+
+
+
+
+
+
Dripicons
+
A completely free, vector line-icon font by Amit Jakhu . Version 1.0
+
Character mapping
+
+
CSS mapping
+
+
Download
+
+
+
+
\ No newline at end of file
diff --git a/desktop/app/fonts/dripicons/style.less b/desktop/app/fonts/dripicons/style.less
new file mode 100644
index 00000000..80f70561
--- /dev/null
+++ b/desktop/app/fonts/dripicons/style.less
@@ -0,0 +1,38 @@
+@import url(http://fonts.googleapis.com/css?family=Montserrat:400,700);
+ * {transition:all 0.15s;}
+ ::selection{background:#374347;color:#fff;}
+ ::-moz-selection{background:#374347;color:#fff;}
+ html,body,div,span,applet,object,iframe,h1,h2,h3,h4,h5,h6,p,blockquote,pre,a,abbr,acronym,address,big,cite,code,del,dfn,em,img,ins,kbd,q,s,samp,small,strike,strong,sub,sup,tt,var,dl,dt,dd,ol,ul,li,fieldset,form,label,legend,table,caption,tbody,tfoot,thead,tr,th,td{margin:0;padding:0;border:0;outline:0;font-weight:inherit;font-style:inherit;font-family:inherit;font-size:100%;vertical-align:baseline}
+ body{line-height:1;color:#82b4bd;background:#e3f1f3;}
+ ol,ul{list-style:none}
+ table{border-collapse:separate;border-spacing:0;vertical-align:middle}
+ caption,th,td{text-align:left;font-weight:normal;vertical-align:middle}
+ a img{border:none}
+ *{-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box}
+ body{font-family:'Montserrat','Helvetica','Arial',sans-serif;font-weight:400;}
+ .container{margin:15px auto;width:90%;max-width:1140px;}
+ h1{margin:130px 0 20px;font-weight:700;font-size:60px;line-height:66px;color:#82b4bd;text-align:center;text-transform:uppercase;letter-spacing:1px;}
+ h2{color:#b2ccd1;font-size:24px;padding:0 0 21px 5px;margin:50px 0 0 0;text-transform:uppercase;font-weight:400;text-align:center;letter-spacing:1px;}
+ .small{font-size:14px;color:#335B6D;text-align:center;}
+ .small a{color:#335B6D;}
+ .small a:hover{color:#b2ccd1}
+ .footer{font-size:12px;display:block;margin: 20px auto 80px auto;}
+ .glyphs.character-mapping{margin:0;padding:0;border:none;}
+ .glyphs.character-mapping li{margin:0;display:inline-block;width:90px;border-radius:4px;}
+ .glyphs.character-mapping .icon{margin:10px 0 10px 15px;padding:15px;position:relative;width:55px;height:55px;color:#82b4bd !important;overflow:hidden;-webkit-border-radius:3px;border-radius:3px;font-size:32px;}
+ .glyphs.character-mapping .icon svg{fill:#82b4bd}
+ .glyphs.character-mapping li:hover .icon{color:#fff !important;}
+ .glyphs.character-mapping li:hover .icon svg{fill:#fff}
+ .glyphs.character-mapping li:hover input{opacity:100;}
+ .glyphs.character-mapping li:hover{background:#374347;}
+ .glyphs.character-mapping input{opacity:0;background:#5fb6c7;color:#fff;margin:0;padding:10px 0;line-height:12px;font-size:12px;display:block;width:100%;border:none;text-align:center;outline:none;border-bottom-right-radius:3px;border-bottom-left-radius:3px;font-family:'Montserrat','Helvetica','Arial',sans-serif;font-weight:400;}
+ .glyphs.character-mapping input:focus{border:none;}
+ .glyphs.character-mapping input:hover{border:none;}
+ .glyphs.css-mapping{margin:0 0 60px 0;padding:30px 0 20px 30px;color:rgba(0,0,0,0.5);border:none;-webkit-border-radius:3px;border-radius:3px;}
+ .glyphs.css-mapping li{margin:0 30px 20px 0;padding:0;display:inline-block;overflow:hidden}
+ .glyphs.css-mapping .icon{margin:0;margin-right:10px;padding:13px;height:50px;width:50px;color:#b2ccd1 !important;overflow:hidden;float:left;font-size:24px}
+ .glyphs.css-mapping input{background:none;color:#b2ccd1;margin:0;margin-top:5px;padding:8px;line-height:14px;font-size:14px;font-family:'Montserrat','Helvetica','Arial',sans-serif;font-weight:700;display:block;width:120px;height:40px;border:none;-webkit-border-radius:5px;border-radius:5px;outline:none;float:right;}
+ .glyphs.css-mapping input:focus{border:none;}
+ .glyphs.css-mapping input:hover{}
+ .button{display:block;width:250px;margin:0 auto 40px auto;padding:30px 50px;background:#374347;color:#fff;font-weight:700;text-transform:uppercase;letter-spacing:2px;text-decoration:none;text-align:center;border-radius:4px;}
+ .button:hover{background:#fff;color:#82b4bd;}
\ No newline at end of file
diff --git a/desktop/app/fonts/dripicons/webfont.less b/desktop/app/fonts/dripicons/webfont.less
new file mode 100644
index 00000000..01b7fca8
--- /dev/null
+++ b/desktop/app/fonts/dripicons/webfont.less
@@ -0,0 +1,440 @@
+
+@charset "UTF-8";
+
+@font-face {
+ font-family: "dripicons";
+ src:url("fonts/dripicons.eot");
+ src:url("fonts/dripicons.eot?#iefix") format("embedded-opentype"),
+ url("fonts/dripicons.ttf") format("truetype"),
+ url("fonts/dripicons.svg#dripicons") format("svg"),
+ url("fonts/dripicons.woff") format("woff");
+ font-weight: normal;
+ font-style: normal;
+
+}
+
+.dripicon{
+ font-family: "dripicons";
+ font-style: normal;
+ font-weight: normal;
+ font-variant: normal;
+ text-transform: none !important;
+ speak: none;
+ display: inline-block;
+ text-decoration: none;
+ width: 1em;
+ line-height: 1em;
+ -webkit-font-smoothing: antialiased;
+}
+
+[data-dripicon]:before {
+ font-family: "dripicons";
+ content: attr(data-dripicon);
+ font-style: normal;
+ font-weight: normal;
+ font-variant: normal;
+ text-transform: none !important;
+ speak: none;
+ display: inline-block;
+ text-decoration: none;
+ width: 1em;
+ line-height: 1em;
+ -webkit-font-smoothing: antialiased;
+}
+
+[class^="dripicon-"]:before,
+[class*=" dripicon-"]:before {
+ font-family: "dripicons";
+ font-style: normal;
+ font-weight: normal;
+ font-variant: normal;
+ text-transform: none !important;
+ speak: none;
+ display: inline-block;
+ text-decoration: none;
+ width: 1em;
+ line-height: 1em;
+ -webkit-font-smoothing: antialiased;
+}
+
+
+.dripicon-align-center:before {
+ content: "\e000";
+}
+
+.dripicon-align-justify:before {
+ content: "\e001";
+}
+
+.dripicon-align-left:before {
+ content: "\e002";
+}
+
+.dripicon-align-right:before {
+ content: "\e003";
+}
+
+.dripicon-arrow-down:before {
+ content: "\e004";
+}
+
+.dripicon-arrow-left:before {
+ content: "\e005";
+}
+
+.dripicon-arrow-thin-down:before {
+ content: "\e006";
+}
+
+.dripicon-arrow-right:before {
+ content: "\e007";
+}
+
+.dripicon-arrow-thin-left:before {
+ content: "\e008";
+}
+
+.dripicon-arrow-thin-up:before {
+ content: "\e009";
+}
+
+.dripicon-arrow-up:before {
+ content: "\e010";
+}
+
+.dripicon-attachment:before {
+ content: "\e011";
+}
+
+.dripicon-arrow-thin-right:before {
+ content: "\e012";
+}
+
+.dripicon-code:before {
+ content: "\e013";
+}
+
+.dripicon-cloud:before {
+ content: "\e014";
+}
+
+.dripicon-chevron-right:before {
+ content: "\e015";
+}
+
+.dripicon-chevron-up:before {
+ content: "\e016";
+}
+
+.dripicon-chevron-down:before {
+ content: "\e017";
+}
+
+.dripicon-chevron-left:before {
+ content: "\e018";
+}
+
+.dripicon-camera:before {
+ content: "\e019";
+}
+
+.dripicon-checkmark:before {
+ content: "\e020";
+}
+
+.dripicon-calendar:before {
+ content: "\e021";
+}
+
+.dripicon-clockwise:before {
+ content: "\e022";
+}
+
+.dripicon-conversation:before {
+ content: "\e023";
+}
+
+.dripicon-direction:before {
+ content: "\e024";
+}
+
+.dripicon-cross:before {
+ content: "\e025";
+}
+
+.dripicon-graph-line:before {
+ content: "\e026";
+}
+
+.dripicon-gear:before {
+ content: "\e027";
+}
+
+.dripicon-graph-bar:before {
+ content: "\e028";
+}
+
+.dripicon-export:before {
+ content: "\e029";
+}
+
+.dripicon-feed:before {
+ content: "\e030";
+}
+
+.dripicon-folder:before {
+ content: "\e031";
+}
+
+.dripicon-forward:before {
+ content: "\e032";
+}
+
+.dripicon-folder-open:before {
+ content: "\e033";
+}
+
+.dripicon-download:before {
+ content: "\e034";
+}
+
+.dripicon-document-new:before {
+ content: "\e035";
+}
+
+.dripicon-document-edit:before {
+ content: "\e036";
+}
+
+.dripicon-document:before {
+ content: "\e037";
+}
+
+.dripicon-gaming:before {
+ content: "\e038";
+}
+
+.dripicon-graph-pie:before {
+ content: "\e039";
+}
+
+.dripicon-heart:before {
+ content: "\e040";
+}
+
+.dripicon-headset:before {
+ content: "\e041";
+}
+
+.dripicon-help:before {
+ content: "\e042";
+}
+
+.dripicon-information:before {
+ content: "\e043";
+}
+
+.dripicon-loading:before {
+ content: "\e044";
+}
+
+.dripicon-lock:before {
+ content: "\e045";
+}
+
+.dripicon-location:before {
+ content: "\e046";
+}
+
+.dripicon-lock-open:before {
+ content: "\e047";
+}
+
+.dripicon-mail:before {
+ content: "\e048";
+}
+
+.dripicon-map:before {
+ content: "\e049";
+}
+
+.dripicon-media-loop:before {
+ content: "\e050";
+}
+
+.dripicon-mobile-portrait:before {
+ content: "\e051";
+}
+
+.dripicon-mobile-landscape:before {
+ content: "\e052";
+}
+
+.dripicon-microphone:before {
+ content: "\e053";
+}
+
+.dripicon-minus:before {
+ content: "\e054";
+}
+
+.dripicon-message:before {
+ content: "\e055";
+}
+
+.dripicon-menu:before {
+ content: "\e056";
+}
+
+.dripicon-media-stop:before {
+ content: "\e057";
+}
+
+.dripicon-media-shuffle:before {
+ content: "\e058";
+}
+
+.dripicon-media-previous:before {
+ content: "\e059";
+}
+
+.dripicon-media-play:before {
+ content: "\e060";
+}
+
+.dripicon-media-next:before {
+ content: "\e061";
+}
+
+.dripicon-media-pause:before {
+ content: "\e062";
+}
+
+.dripicon-monitor:before {
+ content: "\e063";
+}
+
+.dripicon-move:before {
+ content: "\e064";
+}
+
+.dripicon-plus:before {
+ content: "\e065";
+}
+
+.dripicon-phone:before {
+ content: "\e066";
+}
+
+.dripicon-preview:before {
+ content: "\e067";
+}
+
+.dripicon-print:before {
+ content: "\e068";
+}
+
+.dripicon-media-record:before {
+ content: "\e069";
+}
+
+.dripicon-music:before {
+ content: "\e070";
+}
+
+.dripicon-home:before {
+ content: "\e071";
+}
+
+.dripicon-question:before {
+ content: "\e072";
+}
+
+.dripicon-reply:before {
+ content: "\e073";
+}
+
+.dripicon-reply-all:before {
+ content: "\e074";
+}
+
+.dripicon-return:before {
+ content: "\e075";
+}
+
+.dripicon-retweet:before {
+ content: "\e076";
+}
+
+.dripicon-search:before {
+ content: "\e077";
+}
+
+.dripicon-view-thumb:before {
+ content: "\e078";
+}
+
+.dripicon-view-list-large:before {
+ content: "\e079";
+}
+
+.dripicon-view-list:before {
+ content: "\e080";
+}
+
+.dripicon-upload:before {
+ content: "\e081";
+}
+
+.dripicon-user-group:before {
+ content: "\e082";
+}
+
+.dripicon-trash:before {
+ content: "\e083";
+}
+
+.dripicon-user:before {
+ content: "\e084";
+}
+
+.dripicon-thumbs-up:before {
+ content: "\e085";
+}
+
+.dripicon-thumbs-down:before {
+ content: "\e086";
+}
+
+.dripicon-tablet-portrait:before {
+ content: "\e087";
+}
+
+.dripicon-tablet-landscape:before {
+ content: "\e088";
+}
+
+.dripicon-tag:before {
+ content: "\e089";
+}
+
+.dripicon-star:before {
+ content: "\e090";
+}
+
+.dripicon-volume-full:before {
+ content: "\e091";
+}
+
+.dripicon-volume-off:before {
+ content: "\e092";
+}
+
+.dripicon-warning:before {
+ content: "\e093";
+}
+
+.dripicon-window:before {
+ content: "\e094";
+}
+
diff --git a/desktop/app/fonts/oswald/OFL.txt b/desktop/app/fonts/oswald/OFL.txt
new file mode 100644
index 00000000..22bdace3
--- /dev/null
+++ b/desktop/app/fonts/oswald/OFL.txt
@@ -0,0 +1,92 @@
+Copyright (c) 2011-2012, Vernon Adams (vern@newtypography.co.uk), with Reserved Font Names 'Oswald'
+This Font Software is licensed under the SIL Open Font License, Version 1.1.
+This license is copied below, and is also available with a FAQ at:
+http://scripts.sil.org/OFL
+
+
+-----------------------------------------------------------
+SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
+-----------------------------------------------------------
+
+PREAMBLE
+The goals of the Open Font License (OFL) are to stimulate worldwide
+development of collaborative font projects, to support the font creation
+efforts of academic and linguistic communities, and to provide a free and
+open framework in which fonts may be shared and improved in partnership
+with others.
+
+The OFL allows the licensed fonts to be used, studied, modified and
+redistributed freely as long as they are not sold by themselves. The
+fonts, including any derivative works, can be bundled, embedded,
+redistributed and/or sold with any software provided that any reserved
+names are not used by derivative works. The fonts and derivatives,
+however, cannot be released under any other type of license. The
+requirement for fonts to remain under this license does not apply
+to any document created using the fonts or their derivatives.
+
+DEFINITIONS
+"Font Software" refers to the set of files released by the Copyright
+Holder(s) under this license and clearly marked as such. This may
+include source files, build scripts and documentation.
+
+"Reserved Font Name" refers to any names specified as such after the
+copyright statement(s).
+
+"Original Version" refers to the collection of Font Software components as
+distributed by the Copyright Holder(s).
+
+"Modified Version" refers to any derivative made by adding to, deleting,
+or substituting -- in part or in whole -- any of the components of the
+Original Version, by changing formats or by porting the Font Software to a
+new environment.
+
+"Author" refers to any designer, engineer, programmer, technical
+writer or other person who contributed to the Font Software.
+
+PERMISSION & CONDITIONS
+Permission is hereby granted, free of charge, to any person obtaining
+a copy of the Font Software, to use, study, copy, merge, embed, modify,
+redistribute, and sell modified and unmodified copies of the Font
+Software, subject to the following conditions:
+
+1) Neither the Font Software nor any of its individual components,
+in Original or Modified Versions, may be sold by itself.
+
+2) Original or Modified Versions of the Font Software may be bundled,
+redistributed and/or sold with any software, provided that each copy
+contains the above copyright notice and this license. These can be
+included either as stand-alone text files, human-readable headers or
+in the appropriate machine-readable metadata fields within text or
+binary files as long as those fields can be easily viewed by the user.
+
+3) No Modified Version of the Font Software may use the Reserved Font
+Name(s) unless explicit written permission is granted by the corresponding
+Copyright Holder. This restriction only applies to the primary font name as
+presented to the users.
+
+4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
+Software shall not be used to promote, endorse or advertise any
+Modified Version, except to acknowledge the contribution(s) of the
+Copyright Holder(s) and the Author(s) or with their explicit written
+permission.
+
+5) The Font Software, modified or unmodified, in part or in whole,
+must be distributed entirely under this license, and must not be
+distributed under any other license. The requirement for fonts to
+remain under this license does not apply to any document created
+using the Font Software.
+
+TERMINATION
+This license becomes null and void if any of the above conditions are
+not met.
+
+DISCLAIMER
+THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
+OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
+COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
+INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
+DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
+OTHER DEALINGS IN THE FONT SOFTWARE.
diff --git a/desktop/app/fonts/oswald/Oswald-Bold.ttf b/desktop/app/fonts/oswald/Oswald-Bold.ttf
new file mode 100644
index 00000000..a77a3d0f
Binary files /dev/null and b/desktop/app/fonts/oswald/Oswald-Bold.ttf differ
diff --git a/desktop/app/fonts/oswald/Oswald-Light.ttf b/desktop/app/fonts/oswald/Oswald-Light.ttf
new file mode 100644
index 00000000..3ef58b94
Binary files /dev/null and b/desktop/app/fonts/oswald/Oswald-Light.ttf differ
diff --git a/desktop/app/fonts/oswald/Oswald-Regular.ttf b/desktop/app/fonts/oswald/Oswald-Regular.ttf
new file mode 100644
index 00000000..0798e241
Binary files /dev/null and b/desktop/app/fonts/oswald/Oswald-Regular.ttf differ
diff --git a/desktop/app/fonts/oswald/oswald.less b/desktop/app/fonts/oswald/oswald.less
new file mode 100644
index 00000000..a4a2dfac
--- /dev/null
+++ b/desktop/app/fonts/oswald/oswald.less
@@ -0,0 +1,17 @@
+@font-face {
+ font-family: Oswald;
+ font-weight: 300;
+ src: url('Oswald-Light.ttf') format('truetype');
+}
+
+@font-face {
+ font-family: Oswald;
+ font-weight: 400;
+ src: url('Oswald-Regular.ttf') format('truetype');
+}
+
+@font-face {
+ font-family: Oswald;
+ font-weight: 500;
+ src: url('Oswald-Bold.ttf') format('truetype');
+}
\ No newline at end of file
diff --git a/desktop/app/fonts/roboto/Roboto-Black.ttf b/desktop/app/fonts/roboto/Roboto-Black.ttf
new file mode 100644
index 00000000..fbde625d
Binary files /dev/null and b/desktop/app/fonts/roboto/Roboto-Black.ttf differ
diff --git a/desktop/app/fonts/roboto/Roboto-BlackItalic.ttf b/desktop/app/fonts/roboto/Roboto-BlackItalic.ttf
new file mode 100644
index 00000000..60f7782a
Binary files /dev/null and b/desktop/app/fonts/roboto/Roboto-BlackItalic.ttf differ
diff --git a/desktop/app/fonts/roboto/Roboto-Bold.ttf b/desktop/app/fonts/roboto/Roboto-Bold.ttf
new file mode 100644
index 00000000..a355c27c
Binary files /dev/null and b/desktop/app/fonts/roboto/Roboto-Bold.ttf differ
diff --git a/desktop/app/fonts/roboto/Roboto-BoldItalic.ttf b/desktop/app/fonts/roboto/Roboto-BoldItalic.ttf
new file mode 100644
index 00000000..3c9a7a37
Binary files /dev/null and b/desktop/app/fonts/roboto/Roboto-BoldItalic.ttf differ
diff --git a/desktop/app/fonts/roboto/Roboto-Italic.ttf b/desktop/app/fonts/roboto/Roboto-Italic.ttf
new file mode 100644
index 00000000..ff6046d5
Binary files /dev/null and b/desktop/app/fonts/roboto/Roboto-Italic.ttf differ
diff --git a/desktop/app/fonts/roboto/Roboto-Light.ttf b/desktop/app/fonts/roboto/Roboto-Light.ttf
new file mode 100644
index 00000000..94c6bcc6
Binary files /dev/null and b/desktop/app/fonts/roboto/Roboto-Light.ttf differ
diff --git a/desktop/app/fonts/roboto/Roboto-LightItalic.ttf b/desktop/app/fonts/roboto/Roboto-LightItalic.ttf
new file mode 100644
index 00000000..04cc0023
Binary files /dev/null and b/desktop/app/fonts/roboto/Roboto-LightItalic.ttf differ
diff --git a/desktop/app/fonts/roboto/Roboto-Medium.ttf b/desktop/app/fonts/roboto/Roboto-Medium.ttf
new file mode 100644
index 00000000..39c63d74
Binary files /dev/null and b/desktop/app/fonts/roboto/Roboto-Medium.ttf differ
diff --git a/desktop/app/fonts/roboto/Roboto-MediumItalic.ttf b/desktop/app/fonts/roboto/Roboto-MediumItalic.ttf
new file mode 100644
index 00000000..dc743f0a
Binary files /dev/null and b/desktop/app/fonts/roboto/Roboto-MediumItalic.ttf differ
diff --git a/desktop/app/fonts/roboto/Roboto-Regular.ttf b/desktop/app/fonts/roboto/Roboto-Regular.ttf
new file mode 100644
index 00000000..8c082c8d
Binary files /dev/null and b/desktop/app/fonts/roboto/Roboto-Regular.ttf differ
diff --git a/desktop/app/fonts/roboto/Roboto-Thin.ttf b/desktop/app/fonts/roboto/Roboto-Thin.ttf
new file mode 100644
index 00000000..d6955502
Binary files /dev/null and b/desktop/app/fonts/roboto/Roboto-Thin.ttf differ
diff --git a/desktop/app/fonts/roboto/Roboto-ThinItalic.ttf b/desktop/app/fonts/roboto/Roboto-ThinItalic.ttf
new file mode 100644
index 00000000..07172ff6
Binary files /dev/null and b/desktop/app/fonts/roboto/Roboto-ThinItalic.ttf differ
diff --git a/desktop/app/fonts/roboto/RobotoCondensed-Bold.ttf b/desktop/app/fonts/roboto/RobotoCondensed-Bold.ttf
new file mode 100644
index 00000000..fc28868a
Binary files /dev/null and b/desktop/app/fonts/roboto/RobotoCondensed-Bold.ttf differ
diff --git a/desktop/app/fonts/roboto/RobotoCondensed-BoldItalic.ttf b/desktop/app/fonts/roboto/RobotoCondensed-BoldItalic.ttf
new file mode 100644
index 00000000..e1a648ff
Binary files /dev/null and b/desktop/app/fonts/roboto/RobotoCondensed-BoldItalic.ttf differ
diff --git a/desktop/app/fonts/roboto/RobotoCondensed-Italic.ttf b/desktop/app/fonts/roboto/RobotoCondensed-Italic.ttf
new file mode 100644
index 00000000..97ff9f1e
Binary files /dev/null and b/desktop/app/fonts/roboto/RobotoCondensed-Italic.ttf differ
diff --git a/desktop/app/fonts/roboto/RobotoCondensed-Light.ttf b/desktop/app/fonts/roboto/RobotoCondensed-Light.ttf
new file mode 100644
index 00000000..2dae31e2
Binary files /dev/null and b/desktop/app/fonts/roboto/RobotoCondensed-Light.ttf differ
diff --git a/desktop/app/fonts/roboto/RobotoCondensed-LightItalic.ttf b/desktop/app/fonts/roboto/RobotoCondensed-LightItalic.ttf
new file mode 100644
index 00000000..da108d3a
Binary files /dev/null and b/desktop/app/fonts/roboto/RobotoCondensed-LightItalic.ttf differ
diff --git a/desktop/app/fonts/roboto/RobotoCondensed-Regular.ttf b/desktop/app/fonts/roboto/RobotoCondensed-Regular.ttf
new file mode 100644
index 00000000..c2304c14
Binary files /dev/null and b/desktop/app/fonts/roboto/RobotoCondensed-Regular.ttf differ
diff --git a/desktop/app/fonts/roboto/RobotoSlab-Bold.ttf b/desktop/app/fonts/roboto/RobotoSlab-Bold.ttf
new file mode 100644
index 00000000..df5d1df2
Binary files /dev/null and b/desktop/app/fonts/roboto/RobotoSlab-Bold.ttf differ
diff --git a/desktop/app/fonts/roboto/RobotoSlab-Light.ttf b/desktop/app/fonts/roboto/RobotoSlab-Light.ttf
new file mode 100644
index 00000000..ccb99cd0
Binary files /dev/null and b/desktop/app/fonts/roboto/RobotoSlab-Light.ttf differ
diff --git a/desktop/app/fonts/roboto/RobotoSlab-Regular.ttf b/desktop/app/fonts/roboto/RobotoSlab-Regular.ttf
new file mode 100644
index 00000000..eb52a790
Binary files /dev/null and b/desktop/app/fonts/roboto/RobotoSlab-Regular.ttf differ
diff --git a/desktop/app/fonts/roboto/RobotoSlab-Thin.ttf b/desktop/app/fonts/roboto/RobotoSlab-Thin.ttf
new file mode 100644
index 00000000..fee11da1
Binary files /dev/null and b/desktop/app/fonts/roboto/RobotoSlab-Thin.ttf differ
diff --git a/desktop/app/fonts/roboto/roboto.less b/desktop/app/fonts/roboto/roboto.less
new file mode 100644
index 00000000..5192dcf2
--- /dev/null
+++ b/desktop/app/fonts/roboto/roboto.less
@@ -0,0 +1,116 @@
+@font-face {
+ font-family: Roboto;
+ font-weight: 200;
+ src: url('Roboto-Thin.ttf') format('truetype');
+}
+@font-face {
+ font-family: Roboto;
+ font-weight: 200;
+ font-style: italic;
+ src: url('Roboto-ThinItalic.ttf') format('truetype');
+}
+@font-face {
+ font-family: Roboto;
+ font-weight: 300;
+ src: url('Roboto-Light.ttf') format('truetype');
+}
+@font-face {
+ font-family: Roboto;
+ font-weight: 300;
+ font-style: italic;
+ src: url('Roboto-LightItalic.ttf') format('truetype');
+}
+@font-face {
+ font-family: Roboto;
+ font-weight: 400;
+ src: url('Roboto-Regular.ttf') format('truetype');
+}
+@font-face {
+ font-family: Roboto;
+ font-weight: 400;
+ font-style: italic;
+ src: url('Roboto-Italic.ttf') format('truetype');
+}
+@font-face {
+ font-family: Roboto;
+ font-weight: 500;
+ src: url('Roboto-Medium.ttf') format('truetype');
+}
+@font-face {
+ font-family: Roboto;
+ font-weight: 500;
+ font-style: italic;
+ src: url('Roboto-MediumItalic.ttf') format('truetype');
+}
+@font-face {
+ font-family: Roboto;
+ font-weight: 600;
+ src: url('Roboto-Bold.ttf') format('truetype');
+}
+@font-face {
+ font-family: Roboto;
+ font-weight: 600;
+ font-style: italic;
+ src: url('Roboto-BoldItalic.ttf') format('truetype');
+}
+@font-face {
+ font-family: Roboto;
+ font-weight: 700;
+ src: url('Roboto-Black.ttf') format('truetype');
+}
+@font-face {
+ font-family: Roboto;
+ font-weight: 700;
+ font-style: italic;
+ src: url('Roboto-BlackItalic.ttf') format('truetype');
+}
+@font-face {
+ font-family: RobotoCondensed;
+ src: url('RobotoCondensed-Regular.ttf') format('truetype');
+}
+@font-face {
+ font-family: RobotoCondensed;
+ font-style: italic;
+ src: url('RobotoCondensed-RegularItalic.ttf') format('truetype');
+}
+@font-face {
+ font-family: RobotoCondensed;
+ font-weight: bold;
+ src: url('RobotoCondensed-Bold.ttf') format('truetype');
+}
+@font-face {
+ font-family: RobotoCondensed;
+ font-weight: bold;
+ font-style: italic;
+ src: url('RobotoCondensed-BoldItalic.ttf') format('truetype');
+}
+@font-face {
+ font-family: RobotoCondensed;
+ font-weight: 300;
+ src: url('RobotoCondensed-Light.ttf') format('truetype');
+}
+@font-face {
+ font-family: RobotoCondensed;
+ font-weight: 300;
+ font-style: italic;
+ src: url('RobotoCondensed-LightItalic.ttf') format('truetype');
+}
+@font-face {
+ font-family: RobotoSlab;
+ src: url('RobotoSlab-Regular.ttf') format('truetype');
+}
+@font-face {
+ font-family: RobotoSlab;
+ font-weight: bold;
+ src: url('RobotoSlab-Bold.ttf') format('truetype');
+}
+@font-face {
+ font-family: RobotoSlab;
+ font-weight: 300;
+ src: url('RobotoSlab-Light.ttf') format('truetype');
+}
+@font-face {
+ font-family: RobotoSlab;
+ font-weight: 200;
+ src: url('RobotoSlab-Thin.ttf') format('truetype');
+}
diff --git a/desktop/app/mainpage.html b/desktop/app/mainpage.html
new file mode 100644
index 00000000..c607c862
--- /dev/null
+++ b/desktop/app/mainpage.html
@@ -0,0 +1,54 @@
+
+
+
+
+
+ Vorlon.js desktop
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/desktop/app/mainpage.ts b/desktop/app/mainpage.ts
new file mode 100644
index 00000000..99d83a96
--- /dev/null
+++ b/desktop/app/mainpage.ts
@@ -0,0 +1,82 @@
+var os = require('os');
+var ipc = require('ipc');
+var $ = require('jquery');
+var app = require('remote').require('app');
+var jetpack = require('fs-jetpack').cwd(app.getAppPath());
+var shell = require('shell');
+
+import config = require("./vorlon.config");
+import {HomePanel} from './screens/home/app.home';
+import {ConsolePanel} from './screens/console/app.console';
+import {SettingsPanel} from './screens/settings/app.settings';
+import {InfoPanel} from './screens/info/app.info';
+
+var userDataPath = app.getPath('userData');
+var homepanel = null, consolepanel = null, settingspanel = null, infopanel = null;
+console.log(jetpack.read('package.json', 'json'));
+
+// window.env contains data from config/env_XXX.json file.
+var envName = "DEV";
+
+interface Window {
+ env : any;
+}
+
+var env = (window).env;
+if (env) {
+ envName = env.name;
+}
+
+document.addEventListener('DOMContentLoaded', function () {
+ var panelHome = document.getElementById("panelHome");
+ loadPanelContent("./screens/home/app.home.html", panelHome, function(){
+ console.log("panel home loaded");
+ homepanel = new HomePanel(panelHome);
+
+ }).then(function(){
+ var panelConsole = document.getElementById("panelConsole");
+ return loadPanelContent("./screens/console/app.console.html", panelConsole, function(){
+ console.log("panel console loaded");
+ consolepanel = new ConsolePanel(panelConsole);
+
+ });
+ }).then(function(){
+ ipc.send('getVorlonStatus');
+ }).then(function(){
+ var panelInfo = document.getElementById("panelInfo");
+ loadPanelContent("./screens/info/app.info.html", panelInfo, function(){
+ console.log("panel console loaded");
+ infopanel = new InfoPanel(panelInfo);
+ });
+ }).then(function(){
+ var panelConfig = document.getElementById("panelConfig");
+ return loadPanelContent("./screens/settings/app.settings.html", panelConfig, function(){
+ console.log("panel console loaded");
+ settingspanel = new SettingsPanel(panelConfig);
+ });
+ });
+
+ $("#menubar").on("click", ".icon", function(arg){
+ $("#menubar .icon.selected").removeClass("selected");
+ $(".panel.selected").removeClass("selected");
+ var panel = $(this).attr("targetpanel");
+ $(this).addClass("selected");
+ $("#"+ panel).addClass("selected");
+ });
+
+ var cfg = config.getConfig(userDataPath);
+
+ $(".vorlonscriptsample").text("http://" + os.hostname() + ":" + cfg.port + "/vorlon.js");
+});
+
+function loadPanelContent(url, panelElement, callback) {
+ return $.ajax({
+ type: "GET",
+ url: url,
+ success: function (data) {
+ //console.log(data);
+ panelElement.innerHTML = data;
+ callback(panelElement);
+ },
+ });
+}
diff --git a/desktop/app/package.json b/desktop/app/package.json
new file mode 100644
index 00000000..af1579c6
--- /dev/null
+++ b/desktop/app/package.json
@@ -0,0 +1,41 @@
+{
+ "name": "vorlon-desktop",
+ "productName": "Vorlon desktop",
+ "identifier": "com.vorlonjs.desktop",
+ "description": "VorlonJS desktop application.",
+ "version": "0.1.0",
+ "author": "",
+ "main": "background.js",
+ "config": {
+ "target": "development"
+ },
+ "dependencies": {
+ "body-parser": "^1.12.3",
+ "colors": "^1.1.2",
+ "cookie-parser": "^1.3.5",
+ "cookieparser": "^0.1.0",
+ "express": "^4.12.3",
+ "express-session": "^1.11.1",
+ "fakeredis": "^0.3.1",
+ "favicon": "0.0.2",
+ "fs-jetpack": "^0.7.0",
+ "http-proxy": "^1.11.2",
+ "jade": "^1.9.2",
+ "jquery": "^2.1.4",
+ "json": "^9.0.3",
+ "method-override": "2.3.4",
+ "multer": "^0.1.8",
+ "passport": "^0.2.1",
+ "passport-local": "^1.0.0",
+ "passport-twitter": "^1.0.3",
+ "redis": "^0.12.1",
+ "socket.io": "1.3.6",
+ "socket.io-redis": "^0.1.4",
+ "stylus": "^0.50.0",
+ "tree-kill": "^1.0.0",
+ "winston": "^1.0.1",
+ "winston-azure": "0.0.4",
+ "winston-logs-display": "^0.1.1",
+ "xmlhttprequest": "^1.7.0"
+ }
+}
diff --git a/desktop/app/screens/console/app.console.html b/desktop/app/screens/console/app.console.html
new file mode 100644
index 00000000..0c2d2d7c
--- /dev/null
+++ b/desktop/app/screens/console/app.console.html
@@ -0,0 +1,8 @@
+
+ Vorlon server console
+
+
\ No newline at end of file
diff --git a/desktop/app/screens/console/app.console.less b/desktop/app/screens/console/app.console.less
new file mode 100644
index 00000000..4e41525a
--- /dev/null
+++ b/desktop/app/screens/console/app.console.less
@@ -0,0 +1,38 @@
+@import "../../stylesheets/theme.less";
+
+#panelConsole{
+ .console-items{
+ .log{
+ padding : 5px 10px;
+ background-color: white;
+ border : 1px solid #CCC;
+ margin-bottom : 2px;
+
+ .dripicon{
+ margin-right : 10px;
+ }
+
+ &.log-debug{
+
+ }
+
+ &.log-info{
+ .dripicon{
+ color : dodgerblue;
+ }
+ }
+
+ &.log-warn{
+ .dripicon{
+ color : darkgoldenrod;
+ }
+ }
+
+ &.log-error{
+ .dripicon{
+ color : darkred;
+ }
+ }
+ }
+ }
+}
\ No newline at end of file
diff --git a/desktop/app/screens/console/app.console.ts b/desktop/app/screens/console/app.console.ts
new file mode 100644
index 00000000..1e17a27c
--- /dev/null
+++ b/desktop/app/screens/console/app.console.ts
@@ -0,0 +1,88 @@
+var os = require('os');
+var ipc = require('ipc');
+var $ = require('jquery');
+var app = require('remote').require('app');
+
+export class ConsolePanel {
+ messagescontainer: HTMLElement;
+
+ constructor(element) {
+ var panel = this;
+ this.messagescontainer = document.getElementById('vorlonmessages');
+ ipc.on("vorlonlog", function(args) {
+ if (args.logs) {
+ args.logs.forEach(function(log) {
+ panel.appendLog(log);
+ });
+ }
+ });
+
+ ipc.on("vorlonStatus", function(args) {
+ panel.messagescontainer.innerHTML = "";
+ if (args.messages) {
+ args.messages.forEach(function(log) {
+ panel.appendLog(log);
+ });
+ }
+ });
+ }
+
+ appendLog(log) {
+ if (typeof log.args == "string") {
+ this.appendLogEntry(log.level, log.args);
+ }
+ else if (log.args.length == 1) {
+ this.appendLogEntry(log.level, log.args[0]);
+ }
+ else if (log.args.length > 1) {
+ this.appendLogEntry(log.level, log.args[0]);
+ for (var i = 1, l = log.args.length; i < l; i++) {
+ this.appendLogEntry(log.level, log.args[i], true);
+ }
+ }
+ }
+
+ appendLogEntry(level, logtext, indent?) {
+ if (!logtext)
+ return;
+
+ if (!(typeof logtext == "string")) {
+ console.log(JSON.stringify(logtext));
+ return;
+ }
+
+ var e = document.createElement("DIV");
+ e.className = "log log-" + level + " " + (indent ? "indent" : "");
+ var icon = document.createElement("I");
+ icon.className = "dripicon " + classNameForLogLevel(level);
+ e.appendChild(icon);
+ var text = document.createElement("SPAN");
+ text.className = "logtext";
+ text.innerText = logtext.replace(/(?:\r\n|\r|\n)/g, ' ');
+ e.appendChild(text);
+
+ this.messagescontainer.insertBefore(e, this.messagescontainer.firstChild);
+
+ var maxentries = 500;
+ if (this.messagescontainer.children.length > maxentries){
+ for (var i=this.messagescontainer.children.length-1 ; i>maxentries; i--){
+ this.messagescontainer.removeChild(this.messagescontainer.children[i]);
+ }
+ }
+ }
+}
+
+
+
+function classNameForLogLevel(level) {
+ if (level == "debug") {
+ return "dripicon-preview";
+ }
+ else if (level == "warn") {
+ return "dripicon-warning";
+ }
+ else if (level == "error") {
+ return "dripicon-warning";
+ }
+ return "dripicon-information";
+}
diff --git a/desktop/app/screens/home/app.home.html b/desktop/app/screens/home/app.home.html
new file mode 100644
index 00000000..3023398b
--- /dev/null
+++ b/desktop/app/screens/home/app.home.html
@@ -0,0 +1,89 @@
+
+
+
+
+
+
+
+
+
+ include socket.io
+
+
+
+
+
+
+
+
+
+
+
+
Open dashboard for a specific session
+
+
+ Open dashboard session
+
+
+
+
+
Inspect existing website with Vorlon proxy
+
+
+ Open website and dashboard
+
+
+
+
+
\ No newline at end of file
diff --git a/desktop/app/screens/home/app.home.less b/desktop/app/screens/home/app.home.less
new file mode 100644
index 00000000..256d55c5
--- /dev/null
+++ b/desktop/app/screens/home/app.home.less
@@ -0,0 +1,613 @@
+@import "../../stylesheets/theme.less";
+
+#panelHome{
+ overflow: hidden;
+
+ .content{
+
+ }
+
+ .site-header {
+ height: 400px;
+ position: relative;
+ overflow: hidden;
+ background: #1f1c28;
+ background-image: url(../assets/header-stars.png),
+ url(../assets/header-stars-distant.png);
+ background-repeat: repeat;
+ background-position: center center;
+ background-size: auto 400px;
+ color: white;
+
+ .container{
+ height: 100%;
+ background-image: url(../assets/header-planet-large.png),
+ url(../assets/header-planet-medium.png),
+ url(../assets/header-planet-small.png);
+ background-repeat: no-repeat;
+ background-size: 180px auto, // planet-large
+ 90px auto, // planet-medium
+ 66px auto; // planet-small
+ background-position: right 120%, // planet-large
+ 80% 10%, // planet-medium
+ 20% 30%; // planet-small
+ }
+
+ .tube{
+ position: absolute;
+ top: 0;
+ background-repeat: no-repeat;
+ z-index: 4;
+
+ .data{
+ width: 20px;
+ height: 20px;
+ background: url(../assets/header-tube-data.png);
+ background-size: contain;
+ border-radius: 50%;
+ position: absolute;
+ top: -20px;
+ opacity: .5;
+ }
+ }
+ .tube-left{
+ width: 150px;
+ height: 400px;
+ left: 10%;
+ background-image: url(../assets/header-tube-3.png);
+ background-size: auto 400px;
+
+ .data{
+ animation: data1 8s 2s linear infinite;
+ }
+ }
+
+ .tube-top{
+ width: 280px;
+ height: 200px;
+ left: 26%;
+ background-image: url(../assets/header-tube-2.png);
+ background-size: 280px auto;
+ background-position: left -8%;
+
+ .data{
+ animation: data2 8s 6s linear infinite;
+ }
+ }
+
+ .tube-right{
+ width: 400px;
+ height: 400px;
+ right: 5%;
+ background-image: url(../assets/header-tube-1.png);
+ background-size: auto 400px;
+ background-position: right center;
+
+ .data {
+ animation: data3 8s 4s linear infinite;
+ }
+ }
+
+ .satellite {
+ width: 92px;
+ height: 92px;
+ position: absolute;
+ left: 10%;
+ bottom: 10%;
+ background: url(../assets/header-satellite.png) no-repeat center center;
+ background-size: contain;
+ z-index: 3;
+ }
+
+ .logo {
+ width: 395px;
+ height: 110px;
+ margin: 0 auto;
+ position: absolute;
+ top: 37%;
+ left: 50%;
+ transform: translateX(-50%);
+ z-index: 10;
+ background: url(../assets/header-pixel-logo-text.svg) no-repeat center center;
+ background-size: contain;
+ text-indent: -9999em;
+
+ .legend{
+ color: rgba(255,255,255,0.6);
+ text-indent: 0;
+ text-align: center;
+ margin-top : 100px;
+ background-color: @purpleDrk;
+ font-size : 24pt;
+ }
+
+ .spaceship,
+ .exhaust {
+ position: absolute;
+ background-repeat: no-repeat;
+ background-size: contain;
+ background-position: center center;
+ }
+
+ .spaceship {
+ width: 86px;
+ height: 46px;
+ left: 67%;
+ top: -55px;
+ background-image: url(../assets/header-pixel-logo-spaceship.svg);
+ animation: spaceship 4s ease-out;
+ }
+
+ .exhaust{
+ width: 64px;
+ height: 34px;
+ right: 64px;
+ top: 6px;
+ background-image: url(../assets/header-pixel-logo-exhaust.svg);
+ animation: exhaust 4s ease;
+ }
+ }
+ }
+
+ >section {
+ position: relative;
+ height: ~"calc(100% - 400px)";
+ display: flex;
+ .sessionspanel{
+ height: 100%;
+ min-width: 400px;
+ .sessionspanelcontent{
+ position : relative;
+ width:100%;
+ height: 100%;
+ overflow: hidden;
+
+ .panel{
+ position : absolute;
+ left:0;
+ top:0;
+ width:100%;
+ height: 100%;
+ display: flex;
+ flex-flow: column nowrap;
+ background-color : white;
+
+ transition: transform 200ms ease-out;
+
+ &.away{
+ transform: translate(-100%, 0);
+ }
+
+ .stretch{
+ flex:1;
+ padding : 8px;
+ box-sizing: border-box;
+ overflow-x : hidden;
+ overflow-y: auto;
+
+ .session-item {
+ padding : 4px 8px;
+ background-color: #EEE;
+ margin-bottom : 4px;
+ display: flex;
+
+ .status {
+ width:16px;
+ height:16px;
+ border-radius: 50%;
+ border : 1px solid #AAA;
+
+ &.status-up{
+ background-color: seagreen;
+ }
+ }
+ .title{
+ flex:1;
+ margin-left: 4px;
+ }
+
+ .dripicon{
+ margin-left: 10px;
+ color: #AAA;
+ font-size: 14pt;
+ cursor : pointer;
+ }
+ }
+ }
+
+ .toolbar{
+ display: flex;
+ align-items: center;
+ background-color : #AAA;
+ padding : 4px 8px;
+ box-sizing: border-box;
+ width:100%;
+ color: white;
+
+ .stretch{
+ flex:1;
+ }
+
+ &.addsession{
+ background-color : transparent;
+ // border-bottom : 1px solid #DDD;
+ }
+ }
+
+ .actions{
+ margin-left:10px;
+ button{
+ width : 32px;
+ height: 32px;
+ line-height: 29px;
+ border-radius: 50%;
+ padding : 2px;
+ text-align: center;
+ font-size: 12pt;
+ background-color: #777;
+ &:active{
+ transform: scale(0.95);
+ }
+ &:hover{
+ background-color:lighten(#777,5%);
+ }
+ }
+ }
+
+ .configcommons{
+ padding-bottom : 8px;
+ margin-bottom: 8px;
+ border-bottom: 1px solid #CCC;
+ }
+ }
+ }
+ }
+
+ .content{
+ overflow-x: hidden;
+ overflow-y: auto;
+ flex:1;
+ padding : 20px;
+ box-sizing: border-box;
+ display: flex;
+ flex-flow : row wrap;
+ align-items: center;
+ justify-content: center;
+
+ .contentbloc{
+ margin : 10px;
+ padding : 20px;
+ box-sizing: border-box;
+ background-color: white;
+ border : 1px solid @blocBorderColor;
+ width : 100%;
+ height : 180px;
+
+ input, button {
+ display: block;
+ width: 100%;
+ box-sizing: border-box;
+ }
+
+ button{
+ margin-top : 10px;
+ &:active{
+ transform: scale(0.98);
+ }
+ }
+ }
+
+ .fullsize-bloc{
+ width: 100%;
+ }
+ }
+ }
+
+ @media screen and (min-width: 1400px){
+ >section{
+ .content{
+ padding : 40px;
+ .contentbloc{
+ flex:1;
+ }
+ }
+ }
+ }
+
+ @media screen and (max-width: @mediumwidth){
+
+ .site-header{
+ height: 350px;
+
+ .tube-left{
+ left: 5%;
+ }
+ .tube-top{
+ top: -5%;
+ left: 15%;
+ }
+ .tube-right{
+ right: -75px;
+ }
+ .satellite{
+ display: none;
+ }
+ .logo{
+ height: 140px;
+ top: 28%;
+ background-image: url(../assets/vorlon-pixel-logo-large.svg);
+ .spaceship{
+ display: none;
+ }
+
+ .legend{
+ margin-top : 130px;
+ }
+ }
+ }
+
+ >section {
+ height: ~"calc(100% - 350px)";
+ display:block;
+ overflow:auto;
+ #sessionspanel{
+ height: :300px;
+ display:flex;
+ box-sizing: border-box;
+ padding:20px;
+ padding-bottom:0px;
+ .sessionspanelcontent{
+ margin:10px;
+
+ border:1px solid #AAA;
+ padding:20px;
+ box-sizing:border-box;
+ }
+ }
+ .content{
+ padding : 20px;
+ }
+ }
+ }
+
+ @media screen and (max-width: @smallwidth){
+
+ .site-header{
+ height: 250px;
+
+ .container{
+ background-position: 120% 140%, // planet-large
+ 85% -10px, // planet-medium
+ 10% 10%; // planet-small
+ }
+ .tube{
+ top: -35%;
+ }
+ .tube-left{
+ left: 2%;
+ }
+ .tube-top{
+ display: none;
+ }
+ .logo{
+ height: 120px;
+ top: 16%;
+
+ .legend{
+ margin-top : 110px;
+ font-size : 18pt;
+ }
+ }
+ }
+ >section {
+ height: ~"calc(100% - 250px)";
+ #sessionspanel{
+ min-width:auto;
+ padding:5px;
+ padding-bottom: 15px;
+ }
+ .content{
+ padding: 5px;
+ }
+ }
+ }
+
+ @media screen and (max-width: 480px){
+
+ .site-header{
+ height: 200px;
+
+ .container{
+ background-position: 120% 400%, // planet-large
+ 85% -50px, // planet-medium
+ -5% 5%; // planet-small
+ }
+ .tube{
+ display: none;
+ }
+ .logo{
+ height: 100px;
+ .legend{
+ margin-top : 90px;
+ font-size : 18pt;
+ }
+ }
+ }
+
+ >section {
+ height: ~"calc(100% - 200px)";
+ }
+ }
+
+ // Animations
+
+ // Spaceship in logo moving across text
+ @keyframes spaceship {
+ 0%{
+ left: 5%;
+ top: -55px;
+ }
+ 20%{
+ top: -50px;
+ }
+ 40%{
+ top: -55px;
+ }
+ 60%{
+ top: -47px;
+ }
+ 80%{
+ top: -51px;
+ }
+ 100%{
+ left: 67%;
+ top: -55px;
+ }
+ }
+ // Exhaust from spaceship
+ @keyframes exhaust {
+ 0%{
+ opacity: 0;
+ }
+ 5%{
+ opacity: 0;
+ }
+ 20%{
+ opacity: 1;
+ margin-right: 0;
+ margin-top: 0;
+ }
+ 27%{
+ opacity: 1;
+ }
+ 65%{
+ opacity: 0;
+ margin-right: 20px;
+ margin-top: 5px;
+ }
+ 75%{
+ opacity: 0;
+ margin-right: 0;
+ margin-top: 0;
+ }
+ 100%{
+ opacity: 1;
+ }
+ }
+
+ // Data moving through tube-left
+ @keyframes data1{
+ 0%{
+ top: -20px;
+ left: 8px;
+ }
+ 15%{
+ top: 120px;
+ left: 8px;
+ }
+ 30%{
+ top: 265px;
+ left: 75px;
+ }
+ 45%{
+ top: 400px;
+ left: 75px;
+ }
+ 100%{
+ top: 400px;
+ left: 10px;
+ }
+ }
+
+ // Data moving through tube-top
+ @keyframes data2{
+ 0%{
+ top: -28px;
+ left: 8px
+ }
+ 3.0578118439665722%{
+ top: -8px;
+ left: 8px;
+ }
+ 6.1156236879331445%{
+ top: 12px;
+ left: 8px;
+ }
+ 8.86765434750306%{
+ top: 30px;
+ left: 8px;
+ }
+ 11.723886320011895%{
+ top: 48px;
+ left: 13px;
+ }
+ 14.057659923338075%{
+ top: 61px;
+ left: 21px;
+ }
+ 16.43607936284551%{
+ top: 72px;
+ left: 32px;
+ }
+ 19.587999666830232%{
+ top: 77px;
+ left: 52px;
+ }
+ 21.90165415677704%{
+ top: 80px;
+ left: 67px;
+ }
+ 42.08379144967832%{
+ top: 80px;
+ left: 199px;
+ }
+ 46.01459638426888%{
+ top: 74px;
+ left: 224px;
+ }
+ 48.61822935052951%{
+ top: 63px;
+ left: 237px;
+ }
+ 50.66947189418348%{
+ top: 51px;
+ left: 243px;
+ }
+ 53.062588195113115%{
+ top: 37px;
+ left: 250px;
+ }
+ 55.35594707808804%{
+ top: 22px;
+ left: 250px;
+ }
+ 59.94266484403791%{
+ top: -8px;
+ left: 250px;
+ }
+ 63.00047668800448%{
+ top: -28px;
+ left: 250px;
+ }
+ 100%{
+ top: -28px;
+ left: 8px;
+ }
+ }
+
+ // Data moving through tube-right
+ @keyframes data3{
+ 0%{
+ top: -20px;
+ right: 10px;
+ }
+ 50%{
+ top: 400px;
+ right: 10px;
+ }
+ 100%{
+ top: 400px;
+ right: 10px;
+ }
+ }
+}
\ No newline at end of file
diff --git a/desktop/app/screens/home/app.home.sessionsmgr.ts b/desktop/app/screens/home/app.home.sessionsmgr.ts
new file mode 100644
index 00000000..f797eab1
--- /dev/null
+++ b/desktop/app/screens/home/app.home.sessionsmgr.ts
@@ -0,0 +1,254 @@
+var os = require('os');
+var ipc = require('ipc');
+var $ = require('jquery');
+var app = require('remote').require('app');
+var shell = require('shell');
+import config = require("../../vorlon.config");
+var userDataPath = app.getPath('userData');
+
+
+export class SessionsManager {
+ sessions: any;
+ txtAddSession: HTMLInputElement;
+ btnAddSession: HTMLElement;
+ btnRefreshSessions: HTMLElement;
+ sessionsList: HTMLElement;
+ sessionconfigpanel: HTMLElement;
+ btnSaveConfig: HTMLElement;
+ btnCloseConfig: HTMLElement;
+ btnRemoveConfig: HTMLElement;
+ currentSessionCallback : (success:boolean) => void;
+ currentSessionConfig : any;
+ currentSessionId : string;
+
+ constructor(element) {
+ var mgr = this;
+ this.sessions = {};
+
+
+ this.txtAddSession = element.querySelector('#txtnewsession');
+ this.btnAddSession = element.querySelector('#btnAddSession');
+ this.sessionsList = element.querySelector('#sessionslist');
+ this.sessionconfigpanel = element.querySelector('#sessionconfigpanel');
+ this.btnSaveConfig = element.querySelector('#btnSaveConfig');
+ this.btnCloseConfig = element.querySelector('#btnCloseConfig');
+ this.btnRemoveConfig = element.querySelector('#btnRemoveConfig');
+
+ ipc.on("session.init", function(args) {
+ console.log("init sessions", args);
+ mgr.sessionsList.innerHTML = '';
+ mgr.sessions = {};
+ var sessions = [];
+ var sessionsKeys = {}
+ args.forEach(function(session) {
+ sessions.push(session);
+ sessionsKeys[session.sessionId] = true;
+ });
+
+ var storedsessions = config.getSessions(userDataPath);
+ for (var n in storedsessions) {
+ if (!sessionsKeys[n]) {
+ sessions.push({
+ sessionId: n,
+ nbClients: -1
+ });
+ }
+ }
+
+ sessions.sort(function(a, b) {
+ return a.sessionId.localeCompare(b.sessionId);
+ });
+
+ sessions.forEach(function(session) {
+ mgr.addSession(session);
+ mgr.updateSession(session);
+ });
+ });
+
+ ipc.on("session.added", function(args) {
+ mgr.addSession(args);
+ mgr.updateSession(args);
+ });
+
+ ipc.on("session.removed", function(args) {
+ mgr.removeSession(args);
+ });
+
+ ipc.on("session.updated", function(args) {
+ mgr.updateSession(args);
+ });
+
+ mgr.refresh();
+
+ this.btnCloseConfig.onclick = function() {
+ mgr.closeConfig(false);
+ }
+
+ this.btnSaveConfig.onclick = function() {
+ mgr.saveConfig();
+ }
+
+ this.btnRemoveConfig.onclick = function() {
+ mgr.removeConfig();
+ }
+
+ this.btnRefreshSessions = element.querySelector('#btnRefreshSessions');
+ this.btnRefreshSessions.onclick = function() {
+ mgr.refresh();
+ }
+
+ this.btnAddSession.onclick = function() {
+ var sessionid = mgr.txtAddSession.value;
+ if (sessionid && sessionid.length > 2) {
+ var session = {
+ sessionId: sessionid,
+ nbClients: -1
+ };
+ mgr.sessions[sessionid] = session;
+ mgr.showConfig(session);
+ mgr.currentSessionCallback = function(success) {
+ if (!success) {
+ delete mgr.sessions[sessionid];
+ }
+
+ mgr.refresh();
+ }
+ }
+ }
+ }
+
+ refresh() {
+ this.sessionsList.innerHTML = "";
+ ipc.send("getVorlonSessions");
+ }
+
+ addSession(session) {
+
+ var mgr = this;
+ var existing = mgr.sessions[session.sessionId];
+ if (existing) {
+ return;
+ }
+
+ var elt = document.createElement("DIV");
+ elt.className = "session-item";
+ elt.innerHTML = '
' + session.sessionId + '
' +
+ '
' +
+ '
';
+ //'
';
+
+ mgr.sessionsList.appendChild(elt);
+ mgr.sessions[session.sessionId] = {
+ element: elt,
+ session: session
+ };
+
+ var opendashboard = elt.querySelector('.opendashboard');
+ opendashboard.onclick = function() {
+ ipc.send("opendashboard", { sessionid: session.sessionId });
+ }
+
+ var openconfig = elt.querySelector('.opensettings');
+ openconfig.onclick = function() {
+ mgr.showConfig(mgr.sessions[session.sessionId].session);
+ }
+ }
+
+ removeSession(session) {
+ var mgr = this;
+ var existingsession = mgr.sessions[session.sessionId];
+ if (existingsession) {
+ existingsession.session.nbClients = -1;
+ }
+ mgr.updateSession(existingsession.session);
+ }
+
+ updateSession(session) {
+ var mgr = this;
+ var existingsession = mgr.sessions[session.sessionId];
+ if (!existingsession) {
+ mgr.addSession(existingsession);
+ }
+ existingsession.session = session;
+ var clientCountElt = existingsession.element.querySelector('.clientcount');
+ var statusElt = existingsession.element.querySelector('.status');
+ console.log(session.nbClients + " clients for " + session.sessionId)
+ if (session.nbClients >= 0) {
+ clientCountElt.innerText = (session.nbClients + 1);
+ clientCountElt.style.display = '';
+ statusElt.classList.remove('status-down');
+ statusElt.classList.add('status-up');
+ } else {
+ clientCountElt.style.display = 'none';
+ statusElt.classList.add('status-down');
+ statusElt.classList.remove('status-up');
+ }
+ }
+
+ showConfig(session) {
+ var mgr = this;
+ mgr.sessionconfigpanel.classList.remove('away');
+ $('.sessionname', mgr.sessionconfigpanel).text(session.sessionId);
+ var pluginscontainer = mgr.sessionconfigpanel.querySelector('#sessionsplugins');
+ pluginscontainer.innerHTML = '';
+
+ var pluginsConfig = config.getSessionConfig(userDataPath, session.sessionId);
+
+ // pluginsConfig.plugins.sort(function (a, b) {
+ // return a.name.localeCompare(b.name);
+ // });
+
+ mgr.currentSessionConfig = pluginsConfig;
+ mgr.currentSessionId = session.sessionId;
+
+ var includeSocketIO = mgr.sessionconfigpanel.querySelector('#includeSocketIO');
+ includeSocketIO.checked = pluginsConfig.includeSocketIO;
+ includeSocketIO.onchange = function() {
+ pluginsConfig.includeSocketIO = includeSocketIO.checked;
+ };
+
+ pluginsConfig.plugins.forEach(function(plugin) {
+ var e = document.createElement('DIV');
+ e.className = "plugin-config";
+
+ e.innerHTML = '' + plugin.name + '';
+ var input = e.querySelector("input");
+ input.onchange = function() {
+ plugin.enabled = input.checked;
+ };
+ pluginscontainer.appendChild(e);
+ });
+ }
+
+ closeConfig(success) {
+ var mgr = this;
+ mgr.sessionconfigpanel.classList.add('away');
+ if (mgr.currentSessionCallback) {
+ mgr.currentSessionCallback(success);
+ }
+ mgr.currentSessionConfig = null;
+ mgr.currentSessionId = null;
+ mgr.currentSessionCallback = null;
+ }
+
+
+ saveConfig() {
+ var mgr = this;
+ console.log(mgr.currentSessionConfig);
+ mgr.sessions[mgr.currentSessionId].fromConfig = true;
+ config.saveSessionConfig(userDataPath, mgr.currentSessionId, mgr.currentSessionConfig);
+ mgr.closeConfig(true);
+ ipc.send("updateSession", { sessionid: mgr.currentSessionId });
+ }
+
+ removeConfig() {
+ var mgr = this;
+ if (confirm("Do you really want to remove configuration for " + mgr.currentSessionId)) {
+ mgr.sessions[mgr.currentSessionId].fromConfig = false;
+ config.removeSessionConfig(userDataPath, mgr.currentSessionId);
+ mgr.closeConfig(false);
+ ipc.send("updateSession", { sessionid: mgr.currentSessionId });
+ mgr.refresh();
+ }
+ }
+}
\ No newline at end of file
diff --git a/desktop/app/screens/home/app.home.ts b/desktop/app/screens/home/app.home.ts
new file mode 100644
index 00000000..efae2335
--- /dev/null
+++ b/desktop/app/screens/home/app.home.ts
@@ -0,0 +1,119 @@
+var os = require('os');
+var ipc = require('ipc');
+var $ = require('jquery');
+var app = require('remote').require('app');
+var shell = require('shell');
+var config = require("../../vorlon.config");
+var SessionsManager = require("./app.home.sessionsmgr").SessionsManager;
+var userDataPath = app.getPath('userData');
+
+export class HomePanel {
+ statusText: HTMLElement;
+ btnStart: HTMLElement;
+ btnStop: HTMLElement;
+
+ constructor(element) {
+ var panel = this;
+ var sessionspanel = document.getElementById('sessionspanel');
+ var sessionsManager = new SessionsManager(sessionspanel);
+
+ var btnopendashboard = document.getElementById('btnopendashboard');
+ var txtSessionId = document.getElementById('vorlonsessionid');
+ txtSessionId.onkeypress = function(e) {
+ var key = e.which ? e.which : e.keyCode;
+ if (key == 13) {
+ txtSessionId.blur();
+ e.preventDefault();
+ e.stopPropagation();
+ btnopendashboard.focus();
+ btnopendashboard.click();
+ }
+ };
+
+ btnopendashboard.onclick = function() {
+ var sessionid = txtSessionId.value;
+ if (sessionid && sessionid.length) {
+ console.log("send command opendashboard " + sessionid);
+ ipc.send("opendashboard", { sessionid: sessionid });
+ }
+ };
+
+ var txtProxyTarget = document.getElementById('vorlonproxytarget');
+ var btnopenproxy = document.getElementById('btnopenproxy');
+ txtProxyTarget.onkeypress = function(e) {
+ var key = e.which ? e.which : e.keyCode;
+ if (key == 13) {
+ txtProxyTarget.blur();
+ e.preventDefault();
+ e.stopPropagation();
+ btnopenproxy.focus();
+ btnopenproxy.click();
+ }
+ };
+
+ btnopenproxy.onclick = function() {
+ var targeturl = txtProxyTarget.value;
+ if (targeturl && targeturl.length) {
+ if (!(targeturl.indexOf("http://") == 0 || targeturl.indexOf("https://") == 0)) {
+ txtProxyTarget.value = "http://" + targeturl;
+ targeturl = txtProxyTarget.value;
+ }
+ console.log("request data for proxying " + targeturl);
+ getProxyData(targeturl, function(data) {
+ //console.log(data);
+ if (data) {
+ ipc.send("opendashboard", { sessionid: data.session });
+ setTimeout(function() {
+ shell.openExternal(data.url);
+ }, 500);
+ }
+ });
+ }
+ };
+
+ this.statusText = document.getElementById('vorlonServerStatus');
+
+ this.btnStart = document.getElementById('btnStartServer');
+ this.btnStart.onclick = function() {
+ ipc.send("startVorlon");
+ }
+
+ this.btnStop = document.getElementById('btnStopServer');
+ this.btnStop.onclick = function() {
+ ipc.send("stopVorlon");
+ }
+
+
+ ipc.on("vorlonStatus", function(args) {
+ var cfg = config.getConfig(userDataPath);
+ console.log("receive status", args);
+ if (panel.statusText) {
+ if (args.running) {
+ panel.statusText.innerHTML = "VORLON server is running on port " + cfg.port;
+ panel.btnStart.style.display = "none";
+ panel.btnStop.style.display = "";
+ } else {
+ panel.statusText.innerHTML = "VORLON server is NOT running";
+ panel.btnStart.style.display = "";
+ panel.btnStop.style.display = "none";
+ }
+ }
+ });
+ }
+}
+
+
+function getProxyData(targeturl, callback) {
+ var cfg = config.getConfig(userDataPath);
+ var callurl = "http://localhost:" + cfg.port + "/httpproxy/inject?url=" + encodeURIComponent(targeturl) + "&ts=" + new Date();
+
+ $.ajax({
+ type: "GET",
+ url: callurl,
+ success: function(data) {
+ console.log('proxy targets');
+ console.log(data);
+ callback(JSON.parse(data));
+ },
+ });
+}
diff --git a/desktop/app/screens/info/app.info.html b/desktop/app/screens/info/app.info.html
new file mode 100644
index 00000000..b04aac84
--- /dev/null
+++ b/desktop/app/screens/info/app.info.html
@@ -0,0 +1,28 @@
+
+
+
+
+
+ Vorlon.js Desktop, version
+
+
+ Based on Vorlon.js and electron
+
+
+ Visit Vorlon.js website to learn more and check documentation
+
+
+
+
Getting started
+
You could start using VORLON by adding this script tag to your website or web application :
+
+ <script src=" "></script>
+
+
or explicitely specify the session id like this :
+
+ <script src=" /mysessionid"></script>
+
+
+
\ No newline at end of file
diff --git a/desktop/app/screens/info/app.info.less b/desktop/app/screens/info/app.info.less
new file mode 100644
index 00000000..55e96211
--- /dev/null
+++ b/desktop/app/screens/info/app.info.less
@@ -0,0 +1,23 @@
+@import "../../stylesheets/theme.less";
+
+#panelInfo{
+ .vorlonlogo{
+ max-width:100%;
+ max-height: 170px;
+ text-align: center;
+ }
+
+ .infobloc{
+ h3,h4{
+ text-align: center;
+ }
+ }
+
+ .gettingstarted{
+ margin-top : 10px;
+ }
+
+ .vorlonscript{
+ color: #777;
+ }
+}
\ No newline at end of file
diff --git a/desktop/app/screens/info/app.info.ts b/desktop/app/screens/info/app.info.ts
new file mode 100644
index 00000000..8f9f52e9
--- /dev/null
+++ b/desktop/app/screens/info/app.info.ts
@@ -0,0 +1,24 @@
+var os = require('os');
+var ipc = require('ipc');
+var $ = require('jquery');
+var app = require('remote').require('app');
+var shell = require('shell');
+var path = require("path");
+var jetpack = require('fs-jetpack');
+
+export class InfoPanel {
+ versions : { app: string, electron:string, vorlon: string };
+
+ constructor(element) {
+ this.versions = jetpack.cwd(__dirname).read('../../versions.json', 'json');
+ var electronversion = app.getVersion();
+ console.log(electronversion);
+ if (this.versions){
+ $('.appversion',element).text(this.versions.app);
+ $('.vorlonversion',element).text(this.versions.vorlon);
+ $('.electronversion',element).text(this.versions.electron);
+ }else{
+ console.warn("versions file not found " + __dirname)
+ }
+ }
+}
\ No newline at end of file
diff --git a/desktop/app/screens/settings/app.settings.html b/desktop/app/screens/settings/app.settings.html
new file mode 100644
index 00000000..aa4dfa04
--- /dev/null
+++ b/desktop/app/screens/settings/app.settings.html
@@ -0,0 +1,29 @@
+
+ Configure your Vorlon
+
+
+
+
+ VORLON port
+
+
+
+
+ VORLON proxy port
+
+
+
+ Save changes
+ Cancel changes
+ Reset to default
+
+
+ You could start using VORLON by adding this script tag to your website or web application :
+
+
<script src=" "></script>
+
or explicitely specify the session id like this :
+
+
<script src=" /mysession"></script>
+
+
+
diff --git a/desktop/app/screens/settings/app.settings.less b/desktop/app/screens/settings/app.settings.less
new file mode 100644
index 00000000..97c83a3c
--- /dev/null
+++ b/desktop/app/screens/settings/app.settings.less
@@ -0,0 +1,14 @@
+@import "../../stylesheets/theme.less";
+
+#panelConfig{
+ section{
+ .contentbloc{
+ label{
+ display: block;
+ font-size: 0.6em;
+ text-transform: uppercase;
+ color: #777;
+ }
+ }
+ }
+}
\ No newline at end of file
diff --git a/desktop/app/screens/settings/app.settings.ts b/desktop/app/screens/settings/app.settings.ts
new file mode 100644
index 00000000..96b33372
--- /dev/null
+++ b/desktop/app/screens/settings/app.settings.ts
@@ -0,0 +1,75 @@
+var os = require('os');
+var ipc = require('ipc');
+var $ = require('jquery');
+var app = require('remote').require('app');
+
+import config = require("../../vorlon.config");
+var userDataPath = app.getPath('userData');
+
+export class SettingsPanel {
+ element: HTMLElement;
+ vorlonPort: HTMLInputElement;
+ vorlonProxyPort: HTMLInputElement;
+ btnSaveConfig: HTMLElement;
+ btnCancelConfig: HTMLElement;
+ btnResetConfig: HTMLElement;
+ vorlonscriptsample: HTMLElement;
+ cfg : { port: string, proxyPort: string };
+
+ constructor(element) {
+ var panel = this;
+ this.element = element;
+ this.vorlonPort = element.querySelector("#vorlonPort");
+ this.vorlonProxyPort = element.querySelector("#vorlonProxyPort");
+ this.btnSaveConfig = element.querySelector("#btnSaveConfig");
+ this.btnCancelConfig = element.querySelector("#btnCancelConfig");
+ this.btnResetConfig = element.querySelector("#btnResetConfig");
+ this.vorlonscriptsample = element.querySelector("#vorlonscriptsample");
+
+ this.loadConfig();
+
+ this.btnResetConfig.onclick = function() {
+ ipc.send("stopVorlon");
+
+ config.resetConfig(userDataPath);
+
+ setTimeout(function() {
+ ipc.send("startVorlon");
+ panel.configChanged();
+ }, 1000);
+ }
+
+ this.btnSaveConfig.onclick = function() {
+ ipc.send("stopVorlon");
+
+ panel.cfg.port = panel.vorlonPort.value;
+ panel.cfg.proxyPort = panel.vorlonProxyPort.value;
+
+ config.saveConfig(userDataPath, panel.cfg);
+ setTimeout(function() {
+ ipc.send("startVorlon");
+ panel.configChanged();
+ }, 1000);
+ }
+
+ this.btnCancelConfig.onclick = function() {
+ panel.loadConfig();
+ }
+ }
+
+ configChanged() {
+ ipc.send("configChanged");
+ this.loadConfig();
+ }
+
+ loadConfig() {
+ console.log("load config from " + userDataPath);
+ this.cfg = config.getConfig(userDataPath);
+
+ this.vorlonPort.value = this.cfg.port;
+ this.vorlonProxyPort.value = this.cfg.proxyPort;
+
+ $(".vorlonscriptsample").text("http://" + os.hostname() + ":" + this.cfg.port + "/vorlon.js");
+ }
+
+}
diff --git a/desktop/app/scripts/context_menu.ts b/desktop/app/scripts/context_menu.ts
new file mode 100644
index 00000000..f704b96a
--- /dev/null
+++ b/desktop/app/scripts/context_menu.ts
@@ -0,0 +1,48 @@
+// This gives you default context menu (cut, copy, paste)
+// in all input fields and textareas across your app.
+
+(function () {
+ 'use strict';
+
+ var remote = require('remote');
+ var Menu = remote.require('menu');
+ var MenuItem = remote.require('menu-item');
+
+ var cut = new MenuItem({
+ label: "Cut",
+ click: function () {
+ document.execCommand("cut");
+ }
+ });
+
+ var copy = new MenuItem({
+ label: "Copy",
+ click: function () {
+ document.execCommand("copy");
+ }
+ });
+
+ var paste = new MenuItem({
+ label: "Paste",
+ click: function () {
+ document.execCommand("paste");
+ }
+ });
+
+ var textMenu = new Menu();
+ textMenu.append(cut);
+ textMenu.append(copy);
+ textMenu.append(paste);
+
+ document.addEventListener('contextmenu', function(e:any) {
+ switch (e.target.nodeName) {
+ case 'TEXTAREA':
+ case 'INPUT':
+ e.preventDefault();
+ textMenu.popup(remote.getCurrentWindow());
+ break;
+ }
+
+ }, false);
+
+}());
diff --git a/desktop/app/scripts/dev_helper.ts b/desktop/app/scripts/dev_helper.ts
new file mode 100644
index 00000000..04160acb
--- /dev/null
+++ b/desktop/app/scripts/dev_helper.ts
@@ -0,0 +1,31 @@
+'use strict';
+
+var app = require('app');
+var Menu = require('menu');
+var BrowserWindow = require('browser-window');
+
+module.exports.setDevMenu = function () {
+ var devMenu = Menu.buildFromTemplate([{
+ label: 'Development',
+ submenu: [{
+ label: 'Reload',
+ accelerator: 'CmdOrCtrl+R',
+ click: function () {
+ BrowserWindow.getFocusedWindow().reloadIgnoringCache();
+ }
+ },{
+ label: 'Toggle DevTools',
+ accelerator: 'Alt+CmdOrCtrl+I',
+ click: function () {
+ BrowserWindow.getFocusedWindow().toggleDevTools();
+ }
+ },{
+ label: 'Quit',
+ accelerator: 'CmdOrCtrl+Q',
+ click: function () {
+ app.quit();
+ }
+ }]
+ }]);
+ Menu.setApplicationMenu(devMenu);
+};
diff --git a/desktop/app/scripts/env_config.ts b/desktop/app/scripts/env_config.ts
new file mode 100644
index 00000000..15bb38da
--- /dev/null
+++ b/desktop/app/scripts/env_config.ts
@@ -0,0 +1,15 @@
+// Loads config/env_XXX.json file and puts it
+// in proper place for given Electron context.
+
+'use strict';
+
+(function () {
+ var jetpack = require('fs-jetpack');
+ if (typeof window === 'object') {
+ // Web browser context, __dirname points to folder where app.html file is.
+ (window).env = jetpack.read(__dirname + '/env_config.json', 'json');
+ } else {
+ // Node context
+ module.exports = jetpack.read(__dirname + '/../../env_config.json', 'json');
+ }
+}());
diff --git a/desktop/app/scripts/external_links.ts b/desktop/app/scripts/external_links.ts
new file mode 100644
index 00000000..6ef58750
--- /dev/null
+++ b/desktop/app/scripts/external_links.ts
@@ -0,0 +1,44 @@
+// Convenient way for opening links in external browser, not in the app.
+// Useful especially if you have a lot of links to deal with.
+//
+// Usage:
+//
+// Every link with class ".js-external-link" will be opened in external browser.
+// google
+//
+// The same behaviour for many links can be achieved by adding
+// this class to any parent tag of an anchor tag.
+//
+// google
+// bing
+//
+
+(function () {
+ 'use strict';
+
+ var shell = require('shell');
+
+ var supportExternalLinks = function (e) {
+ var href;
+ var isExternal = false;
+
+ var checkDomElement = function (element) {
+ if (element.nodeName === 'A') {
+ href = element.getAttribute('href');
+ }
+ if (element.classList.contains('js-external-link')) {
+ isExternal = true;
+ }
+ if (href && isExternal) {
+ shell.openExternal(href);
+ e.preventDefault();
+ } else if (element.parentElement) {
+ checkDomElement(element.parentElement);
+ }
+ }
+
+ checkDomElement(e.target);
+ }
+
+ document.addEventListener('click', supportExternalLinks, false);
+}());
diff --git a/desktop/app/scripts/window_state.ts b/desktop/app/scripts/window_state.ts
new file mode 100644
index 00000000..67f359c5
--- /dev/null
+++ b/desktop/app/scripts/window_state.ts
@@ -0,0 +1,41 @@
+// Simple module to help you remember the size and position of windows.
+// Can be used for more than one window, just construct many
+// instances of it and give each different name.
+
+'use strict';
+
+var app = require('app');
+var jetpack = require('fs-jetpack');
+
+module.exports = function (name, defaults) {
+
+ var userDataDir = jetpack.cwd(app.getPath('userData'));
+ var stateStoreFile = 'window-state-' + name +'.json';
+
+ var state = userDataDir.read(stateStoreFile, 'json') || {
+ width: defaults.width,
+ height: defaults.height
+ };
+
+ var saveState = function (win) {
+ if (!win.isMaximized() && !win.isMinimized()) {
+ var position = win.getPosition();
+ var size = win.getSize();
+ state.x = position[0];
+ state.y = position[1];
+ state.width = size[0];
+ state.height = size[1];
+ }
+ state.isMaximized = win.isMaximized();
+ userDataDir.write(stateStoreFile, state, { atomic: true });
+ };
+
+ return {
+ get x() { return state.x; },
+ get y() { return state.y; },
+ get width() { return state.width; },
+ get height() { return state.height; },
+ get isMaximized() { return state.isMaximized; },
+ saveState: saveState
+ };
+};
diff --git a/desktop/app/stylesheets/app.less b/desktop/app/stylesheets/app.less
new file mode 100644
index 00000000..5da58306
--- /dev/null
+++ b/desktop/app/stylesheets/app.less
@@ -0,0 +1,5 @@
+@import "main.less";
+@import "../screens/home/app.home.less";
+@import "../screens/console/app.console.less";
+@import "../screens/settings/app.settings.less";
+@import "../screens/info/app.info.less";
\ No newline at end of file
diff --git a/desktop/app/stylesheets/main.less b/desktop/app/stylesheets/main.less
new file mode 100644
index 00000000..2df0106b
--- /dev/null
+++ b/desktop/app/stylesheets/main.less
@@ -0,0 +1,223 @@
+@import "theme.less";
+
+@blocwidth : 400px;
+@doubleblocwidth: (2*@blocwidth + 140px);
+
+html, body {
+ width: 100%;
+ height: 100%;
+ margin: 0;
+ padding: 0;
+ font-family: "Roboto";
+ -webkit-user-select: none;
+-khtml-user-select: none;
+-moz-user-select: none;
+-ms-user-select: none;
+user-select: none;
+}
+*{
+-webkit-touch-callout: none;
+-moz-touch-callout: none;
+-ms-touch-callout: none;
+touch-callout: none;
+-webkit-user-drag: none;
+-moz-user-drag: none;
+-ms-user-drag: none;
+user-drag: none;
+}
+button, input{
+outline: none;
+}
+ input
+{
+-webkit-user-select: auto !important;
+-khtml-user-select: auto !important;
+-moz-user-select: auto !important;
+-ms-user-select: auto !important;
+user-select: auto !important;
+}
+body {
+
+}
+
+.messageWindow{
+ display : flex;
+ align-items: center;
+ justify-content: center;
+
+ .message{
+ font-size: 18pt;
+ text-transform: uppercase;
+ text-align: center;
+ max-width: 70%;
+ }
+}
+
+a {
+ text-decoration: none;
+ color: @blue;
+}
+
+h1,h2,h3,h4,h5,h6 {
+ font-family: Oswald;
+ color: @purpleDrk;
+}
+
+button{
+ background-color: @purple;
+ border: none;
+ padding : 0.4em 1em;
+ color: white;
+ cursor : pointer;
+ text-transform: uppercase;
+
+ &:hover{
+ background-color:lighten(@purple,20%);
+ }
+}
+
+.mainpage {
+ background-color: #AAA;
+ width: 100%;
+ height: 100%;
+ overflow: hidden;
+ position : relative;
+
+ >.toolbar{
+ position : absolute;
+ left: 0;
+ top: 0;
+ bottom: 0;
+ width: 60px;
+ background-color: @purpleDrk;
+ color: white;
+
+ .icon{
+ width: 60px;
+ height: 60px;
+ text-align: center;
+ cursor : pointer;
+
+ i{
+ font-size : 18pt;
+ line-height: 60px;
+ }
+ }
+ }
+ .pagecontainer{
+ position : absolute;
+ left: 60px;
+ top: 0;
+ bottom: 0;
+ right: 0;
+ overflow: hidden;
+
+ .pagecontainer-panels{
+ position : relative;
+ width: 100%;
+ height: 100%;
+ overflow: hidden;
+
+ >.panel{
+ background-color: #DDD;
+ position : absolute;
+ left: 0;
+ top: 0;
+ bottom: 0;
+ right: 0;
+ overflow-x: hidden;
+ overflow-y: auto;
+ -webkit-transform : translate(0, 20%);
+ transform : translate(0,20%);
+ opacity : 0;
+ transition : opacity 200ms ease-out, transform 300ms cubic-bezier(0.250, 0.460, 0.450, 0.940);
+ z-index: 0;
+
+ &.selected{
+ opacity : 1;
+ -webkit-transform : translate(0,0);
+ transform : translate(0,0);
+ z-index: 1;
+ }
+
+ &.with-header{
+ display : flex;
+ flex-flow : column nowrap;
+ overflow: hidden;
+
+ >header{
+ flex-shrink: 0;
+ height : 40px;
+ background-color: @purple;
+ color : white;
+ display : flex;
+ flex-flow : row nowrap;
+ align-items: center;
+ padding : 0 20px;
+
+ .title{
+ flex : 1;
+ text-transform: uppercase;
+ }
+
+ .actions{
+ display : flex;
+ flex-flow : row nowrap;
+ align-items: center;
+ }
+ }
+
+ >section{
+ padding : 20px;
+ flex : 1;
+ overflow-x: hidden;
+ overflow-y: auto;
+
+ .contentbloc{
+ background-color: white;
+ border : 1px solid @blocBorderColor;
+ padding : 20px;
+ }
+ }
+ }
+ }
+
+
+ }
+ }
+}
+
+.subtitle {
+ color: gray;
+}
+
+@media screen and (max-width: @doubleblocwidth){
+ .mainpage .pagecontainer .content{
+ padding : 20px;
+ .contentbloc{
+ width: 100%;
+ height: auto;
+ }
+ }
+}
+
+@media screen and (max-width: @smallwidth){
+ .mainpage .pagecontainer .content{
+ padding : 10px;
+ .contentbloc{
+ width: 100%;
+ height: auto;
+ }
+ }
+}
+
+@media screen and (max-width: 480px){
+ .mainpage .pagecontainer .content{
+ padding : 5px;
+ .contentbloc{
+ margin : 5px;
+ width: 100%;
+ height: auto;
+ }
+ }
+}
diff --git a/desktop/app/stylesheets/theme.less b/desktop/app/stylesheets/theme.less
new file mode 100644
index 00000000..58787ccd
--- /dev/null
+++ b/desktop/app/stylesheets/theme.less
@@ -0,0 +1,26 @@
+@containerwidth : 1200px;
+@smallwidth : 600px;
+@mediumwidth : 900px;
+
+@vorlonPurple : #1d0c3d;
+
+@purple : #6b2d81;
+@purpleDrk : #411748;
+
+@blue : #007ca7;
+@blueDrk : #0a567f;
+
+@yellow : #fee600;
+@yellowDrk : #ffcb05;
+
+@green : #a2c13b;
+@greenDrk : #899c3a;
+
+@teal : #00b7c7;
+@red : #ed2424;
+
+@greyDrk : #444;
+@greyMed : #ccc;
+@greyLight : #f7f7f7;
+
+@blocBorderColor : #AAA;
diff --git a/desktop/app/versions.json b/desktop/app/versions.json
new file mode 100644
index 00000000..c0ee17d3
--- /dev/null
+++ b/desktop/app/versions.json
@@ -0,0 +1,5 @@
+{
+ "app" : "0.0.1 beta",
+ "electron" : "0.34.1",
+ "vorlon" : "0.1.0"
+}
\ No newline at end of file
diff --git a/desktop/app/vorlon.config.ts b/desktop/app/vorlon.config.ts
new file mode 100644
index 00000000..9b8c1b74
--- /dev/null
+++ b/desktop/app/vorlon.config.ts
@@ -0,0 +1,95 @@
+'use strict';
+
+var path = require("path");
+var jetpack = require('fs-jetpack');
+var vorlonConfigFile = 'vorlonconfig.json';
+var sessionConfigsStoreFile = 'vorlonsessions.json';
+import vorlonConfig = require("./vorlon/config/vorlon.servercontext");
+
+var vorlonOriginalConfig = jetpack.cwd(path.join(__dirname, "vorlon")).read('config.json', 'json');
+
+export interface ISessionsConfig {
+
+}
+
+export interface ISessionConfig {
+ includeSocketIO: boolean;
+ plugins : vorlonConfig.VORLON.IPluginConfig[]
+}
+
+export function getConfig(configpath : string) {
+ var userDataDir = jetpack.cwd(configpath);
+ var config = userDataDir.read(vorlonConfigFile, 'json');
+ if (!config)
+ config = JSON.parse(JSON.stringify(vorlonOriginalConfig));
+
+ return config;
+}
+
+export function saveConfig(path : string, config) {
+ var userDataDir = jetpack.cwd(path);
+ userDataDir.write(vorlonConfigFile, config, { atomic: true });
+};
+
+export function resetConfig(path : string){
+ var userDataDir = jetpack.cwd(path);
+ userDataDir.write(vorlonConfigFile, vorlonOriginalConfig, { atomic: true });
+}
+
+export function availablePlugins() : ISessionConfig{
+ return JSON.parse(JSON.stringify({ includeSocketIO : vorlonOriginalConfig.includeSocketIO, plugins : vorlonOriginalConfig.plugins }));
+}
+
+export function getSessions(configpath : string) : ISessionsConfig{
+ var userDataDir = jetpack.cwd(configpath);
+ var config = userDataDir.read(sessionConfigsStoreFile, 'json') || {};
+
+ return config;
+}
+
+
+export function getSessionConfig(configpath : string, sessionid : string) : ISessionConfig {
+ var defaultConfig = JSON.parse(JSON.stringify({ includeSocketIO : vorlonOriginalConfig.includeSocketIO, plugins : vorlonOriginalConfig.plugins }));
+
+ var userDataDir = jetpack.cwd(configpath);
+ var config = userDataDir.read(sessionConfigsStoreFile, 'json');
+
+ if (!config || !config[sessionid])
+ return defaultConfig
+
+ var sessionConfig = config[sessionid];
+
+ var retainedplugins = [];
+ //merge default & stored config to ensure plugins availability
+ var refplugins:vorlonConfig.VORLON.IPluginConfig[] = vorlonOriginalConfig.plugins;
+ refplugins.forEach(function(plugin){
+ var configured = sessionConfig.plugins.filter((p) =>{
+ return p.id == plugin.id;
+ })[0];
+
+ if (!configured){
+ retainedplugins.push(plugin);
+ }else{
+ retainedplugins.push(configured);
+ }
+ });
+ sessionConfig.plugins=retainedplugins;
+
+ return sessionConfig;
+}
+
+export function saveSessionConfig(path : string, sessionid : string, config: ISessionConfig) {
+ var userDataDir = jetpack.cwd(path);
+ var storedconfig = userDataDir.read(sessionConfigsStoreFile, 'json') || {};
+ storedconfig[sessionid] = config
+
+ userDataDir.write(sessionConfigsStoreFile, storedconfig, { atomic: true });
+};
+
+export function removeSessionConfig(path : string, sessionid : string) {
+ var userDataDir = jetpack.cwd(path);
+ var storedconfig = userDataDir.read(sessionConfigsStoreFile, 'json') || {};
+ delete storedconfig[sessionid];
+
+ userDataDir.write(sessionConfigsStoreFile, storedconfig, { atomic: true });
+};
\ No newline at end of file
diff --git a/desktop/app/vorlon.ts b/desktop/app/vorlon.ts
new file mode 100644
index 00000000..b98fd58b
--- /dev/null
+++ b/desktop/app/vorlon.ts
@@ -0,0 +1,99 @@
+var http = require("http");
+
+import vorlonhttpConfig = require("./vorlon/config/vorlon.httpconfig");
+import vorlonServer = require("./vorlon/Scripts/vorlon.server");
+import vorlonDashboard = require("./vorlon/Scripts/vorlon.dashboard");
+import vorlonWebserver = require("./vorlon/Scripts/vorlon.webServer");
+import vorlonHttpProxy = require("./vorlon/Scripts/vorlon.httpproxy.server");
+import servercontext = require("./vorlon/config/vorlon.servercontext");
+import config = require("./vorlon.config");
+
+//console.log("STARTING VORLON FROM ELECTRON");
+
+var global = this;
+if (!global.setImmediate) {
+ global.setImmediate = function (callback) {
+ setTimeout(callback, 1);
+ }
+}
+
+try {
+ var logger = {
+ debug: function (...logargs) {
+ var args = Array.prototype.slice.call(arguments);
+ process.send({ log: { level: "debug", args: args, origin: 'logger.debug' } });
+ },
+ info: function (...logargs) {
+ var args = Array.prototype.slice.call(arguments);
+ process.send({ log: { level: "info", args: args, origin: 'logger.info' } });
+ },
+ warn: function (...logargs) {
+ var args = Array.prototype.slice.call(arguments);
+
+ process.send({ log: { level: "warn", args: args, origin: 'logger.warn' } });
+ },
+ error: function (...logargs) {
+ var args = Array.prototype.slice.call(arguments);
+ process.send({ log: { level: "error", args: args, origin: 'logger.error' } });
+ },
+ };
+
+ var userdatapath = process.argv[2];
+ var vorlonconfig = config.getConfig(userdatapath);
+ var context = new servercontext.VORLON.DefaultContext();
+
+ context.sessions.onsessionadded = function (session) {
+ process.send({ session: { action: "added", session: session } });
+ }
+
+ context.sessions.onsessionremoved = function (session) {
+ process.send({ session: { action: "removed", session: session } });
+ }
+
+ context.sessions.onsessionupdated = function (session) {
+ process.send({ session: { action: "updated", session: session } });
+ }
+
+ context.plugins = {
+ getPluginsFor : function(sessionid, callback) { // (error, plugins: ISessionPlugins) => void)
+ var plugins = config.getSessionConfig(userdatapath, sessionid);
+ logger.debug("get plugins from local for " + sessionid);
+ if (callback)
+ callback(null, plugins);
+ }
+ }
+
+ context.sessions.logger = logger;
+ vorlonconfig.httpModule = http;
+ vorlonconfig.protocol = "http";
+ context.httpConfig = vorlonconfig;
+ context.baseURLConfig = vorlonconfig;
+
+ context.logger = logger;
+
+ var webServer = new vorlonWebserver.VORLON.WebServer(context);
+ var dashboard = new vorlonDashboard.VORLON.Dashboard(context);
+ var server = new vorlonServer.VORLON.Server(context);
+ var HttpProxy = new vorlonHttpProxy.VORLON.HttpProxy(context, false);
+
+ webServer.components.push(dashboard);
+ webServer.components.push(server);
+ webServer.components.push(HttpProxy);
+
+ webServer.start();
+
+ var webapp = (webServer)._app;
+ webapp.use(function logErrors(err, req, res, next) {
+ if (err) {
+ process.send({ log: { level: "error", args: err.stack, origin: 'logger.error' } });
+ }
+ next(err);
+ });
+
+ process.on("message", function(args){
+ process.send({ session: { action: "init", session: context.sessions.all() } });
+ });
+
+} catch (exception) {
+ process.send({ log: { level: "error", args: [exception.stack], origin: 'trycatch' } });
+}
diff --git a/desktop/config/env_development.json b/desktop/config/env_development.json
new file mode 100644
index 00000000..efb77484
--- /dev/null
+++ b/desktop/config/env_development.json
@@ -0,0 +1,4 @@
+{
+ "name": "development",
+ "description": "Add here any environment specific stuff you like."
+}
diff --git a/desktop/config/env_production.json b/desktop/config/env_production.json
new file mode 100644
index 00000000..600b2d71
--- /dev/null
+++ b/desktop/config/env_production.json
@@ -0,0 +1,4 @@
+{
+ "name": "production",
+ "description": "Add here any environment specific stuff you like."
+}
diff --git a/desktop/config/env_test.json b/desktop/config/env_test.json
new file mode 100644
index 00000000..e3956a52
--- /dev/null
+++ b/desktop/config/env_test.json
@@ -0,0 +1,4 @@
+{
+ "name": "test",
+ "description": "Add here any environment specific stuff you like."
+}
diff --git a/desktop/gulpfile.js b/desktop/gulpfile.js
new file mode 100644
index 00000000..bc266bcf
--- /dev/null
+++ b/desktop/gulpfile.js
@@ -0,0 +1,4 @@
+'use strict';
+
+require('./tasks/build');
+require('./tasks/release');
diff --git a/desktop/main.css b/desktop/main.css
new file mode 100644
index 00000000..693e7e14
--- /dev/null
+++ b/desktop/main.css
@@ -0,0 +1,22 @@
+html,
+body {
+ width: 100%;
+ height: 100%;
+ margin: 0;
+ padding: 0;
+}
+body {
+ display: flex;
+ justify-content: center;
+ align-items: center;
+ font-family: sans-serif;
+}
+a {
+ text-decoration: none;
+}
+.container {
+ text-align: center;
+}
+.subtitle {
+ color: gray;
+}
diff --git a/desktop/package.json b/desktop/package.json
new file mode 100644
index 00000000..d64b3513
--- /dev/null
+++ b/desktop/package.json
@@ -0,0 +1,27 @@
+{
+ "devDependencies": {
+ "asar": "^0.7.2",
+ "electron-prebuilt": "^0.34.1",
+ "fs-jetpack": "^0.7.0",
+ "gulp": "^3.9.0",
+ "gulp-less": "^3.0.3",
+ "gulp-typescript": "^2.9.2",
+ "gulp-util": "^3.0.6",
+ "q": "^1.4.1",
+ "rollup": "^0.16.1",
+ "tree-kill": "^0.1.1",
+ "yargs": "^3.15.0"
+ },
+ "optionalDependencies": {
+ "appdmg": "^0.3.2",
+ "rcedit": "^0.3.0"
+ },
+ "scripts": {
+ "postinstall": "node ./tasks/app_npm_install",
+ "app-install": "node ./tasks/app_npm_install",
+ "build": "./node_modules/.bin/gulp build",
+ "release": "./node_modules/.bin/gulp release --env=production",
+ "start": "node ./tasks/start",
+ "test": "node ./tasks/start --env=test"
+ }
+}
diff --git a/desktop/resources/icon.png b/desktop/resources/icon.png
new file mode 100644
index 00000000..73f578d1
Binary files /dev/null and b/desktop/resources/icon.png differ
diff --git a/desktop/resources/linux/DEBIAN/control b/desktop/resources/linux/DEBIAN/control
new file mode 100644
index 00000000..d989bfb6
--- /dev/null
+++ b/desktop/resources/linux/DEBIAN/control
@@ -0,0 +1,7 @@
+Package: {{name}}
+Version: {{version}}
+Maintainer: {{author}}
+Priority: optional
+Architecture: amd64
+Installed-Size: {{size}}
+Description: {{description}}
diff --git a/desktop/resources/linux/app.desktop b/desktop/resources/linux/app.desktop
new file mode 100644
index 00000000..f01819ed
--- /dev/null
+++ b/desktop/resources/linux/app.desktop
@@ -0,0 +1,11 @@
+[Desktop Entry]
+Version=1.0
+Type=Application
+Encoding=UTF-8
+Name={{productName}}
+Comment={{description}}
+Exec=/opt/{{name}}/{{name}}
+Path=/opt/{{name}}/
+Icon=/opt/{{name}}/icon.png
+Terminal=false
+Categories=Application;
diff --git a/desktop/resources/osx/Info.plist b/desktop/resources/osx/Info.plist
new file mode 100644
index 00000000..df6f4624
--- /dev/null
+++ b/desktop/resources/osx/Info.plist
@@ -0,0 +1,32 @@
+
+
+
+
+ CFBundleDisplayName
+ {{productName}}
+ CFBundleExecutable
+ {{productName}}
+ CFBundleIconFile
+ icon.icns
+ CFBundleIdentifier
+ {{identifier}}
+ CFBundleInfoDictionaryVersion
+ 6.0
+ CFBundleName
+ {{productName}}
+ CFBundlePackageType
+ APPL
+ CFBundleVersion
+ {{version}}
+ CFBundleGetInfoString
+ {{version}}
+ LSMinimumSystemVersion
+ 10.8.0
+ NSMainNibFile
+ MainMenu
+ NSPrincipalClass
+ AtomApplication
+ NSSupportsAutomaticGraphicsSwitching
+
+
+
diff --git a/desktop/resources/osx/appdmg.json b/desktop/resources/osx/appdmg.json
new file mode 100644
index 00000000..c0aff23a
--- /dev/null
+++ b/desktop/resources/osx/appdmg.json
@@ -0,0 +1,10 @@
+{
+ "title": "{{productName}}",
+ "icon": "{{dmgIcon}}",
+ "background": "{{dmgBackground}}",
+ "icon-size": 128,
+ "contents": [
+ { "x": 410, "y": 220, "type": "link", "path": "/Applications" },
+ { "x": 130, "y": 220, "type": "file", "path": "{{appPath}}" }
+ ]
+}
diff --git a/desktop/resources/osx/dmg-background.png b/desktop/resources/osx/dmg-background.png
new file mode 100644
index 00000000..69f0d9cb
Binary files /dev/null and b/desktop/resources/osx/dmg-background.png differ
diff --git a/desktop/resources/osx/dmg-background@2x.png b/desktop/resources/osx/dmg-background@2x.png
new file mode 100644
index 00000000..5103f455
Binary files /dev/null and b/desktop/resources/osx/dmg-background@2x.png differ
diff --git a/desktop/resources/osx/dmg-icon.icns b/desktop/resources/osx/dmg-icon.icns
new file mode 100644
index 00000000..a8e9f740
Binary files /dev/null and b/desktop/resources/osx/dmg-icon.icns differ
diff --git a/desktop/resources/osx/helper_apps/Info EH.plist b/desktop/resources/osx/helper_apps/Info EH.plist
new file mode 100644
index 00000000..2d1ff4c0
--- /dev/null
+++ b/desktop/resources/osx/helper_apps/Info EH.plist
@@ -0,0 +1,22 @@
+
+
+
+
+ CFBundleDisplayName
+ {{productName}} Helper EH
+ CFBundleExecutable
+ {{productName}} Helper EH
+ CFBundleIdentifier
+ {{identifier}}.helper.EH
+ CFBundleName
+ {{productName}} Helper EH
+ CFBundlePackageType
+ APPL
+ DTSDKName
+ macosx
+ LSUIElement
+
+ NSSupportsAutomaticGraphicsSwitching
+
+
+
diff --git a/desktop/resources/osx/helper_apps/Info NP.plist b/desktop/resources/osx/helper_apps/Info NP.plist
new file mode 100644
index 00000000..82eb2f82
--- /dev/null
+++ b/desktop/resources/osx/helper_apps/Info NP.plist
@@ -0,0 +1,22 @@
+
+
+
+
+ CFBundleDisplayName
+ {{productName}} Helper NP
+ CFBundleExecutable
+ {{productName}} Helper NP
+ CFBundleIdentifier
+ {{identifier}}.helper.NP
+ CFBundleName
+ {{productName}} Helper NP
+ CFBundlePackageType
+ APPL
+ DTSDKName
+ macosx
+ LSUIElement
+
+ NSSupportsAutomaticGraphicsSwitching
+
+
+
diff --git a/desktop/resources/osx/helper_apps/Info.plist b/desktop/resources/osx/helper_apps/Info.plist
new file mode 100644
index 00000000..ccbf6ba7
--- /dev/null
+++ b/desktop/resources/osx/helper_apps/Info.plist
@@ -0,0 +1,18 @@
+
+
+
+
+ CFBundleIdentifier
+ {{identifier}}.helper
+ CFBundleName
+ {{productName}} Helper
+ CFBundlePackageType
+ APPL
+ DTSDKName
+ macosx
+ LSUIElement
+
+ NSSupportsAutomaticGraphicsSwitching
+
+
+
diff --git a/desktop/resources/osx/icon.icns b/desktop/resources/osx/icon.icns
new file mode 100644
index 00000000..a8e9f740
Binary files /dev/null and b/desktop/resources/osx/icon.icns differ
diff --git a/desktop/resources/windows/icon.ico b/desktop/resources/windows/icon.ico
new file mode 100644
index 00000000..93ea50c2
Binary files /dev/null and b/desktop/resources/windows/icon.ico differ
diff --git a/desktop/resources/windows/installer.nsi b/desktop/resources/windows/installer.nsi
new file mode 100644
index 00000000..cdd70c2c
--- /dev/null
+++ b/desktop/resources/windows/installer.nsi
@@ -0,0 +1,160 @@
+; NSIS packaging/install script
+; Docs: http://nsis.sourceforge.net/Docs/Contents.html
+
+!include LogicLib.nsh
+!include nsDialogs.nsh
+
+; --------------------------------
+; Variables
+; --------------------------------
+
+!define dest "{{dest}}"
+!define src "{{src}}"
+!define name "{{name}}"
+!define productName "{{productName}}"
+!define version "{{version}}"
+!define icon "{{icon}}"
+!define setupIcon "{{setupIcon}}"
+!define banner "{{banner}}"
+
+!define exec "{{productName}}.exe"
+
+!define regkey "Software\${productName}"
+!define uninstkey "Software\Microsoft\Windows\CurrentVersion\Uninstall\${productName}"
+
+!define uninstaller "uninstall.exe"
+
+; --------------------------------
+; Installation
+; --------------------------------
+
+SetCompressor lzma
+
+Name "${productName}"
+Icon "${setupIcon}"
+OutFile "${dest}"
+InstallDir "$PROGRAMFILES\${productName}"
+InstallDirRegKey HKLM "${regkey}" ""
+
+CRCCheck on
+SilentInstall normal
+
+XPStyle on
+ShowInstDetails nevershow
+AutoCloseWindow false
+WindowIcon off
+
+Caption "${productName} Setup"
+; Don't add sub-captions to title bar
+SubCaption 3 " "
+SubCaption 4 " "
+
+Page custom welcome
+Page instfiles
+
+Var Image
+Var ImageHandle
+
+Function .onInit
+
+ ; Extract banner image for welcome page
+ InitPluginsDir
+ ReserveFile "${banner}"
+ File /oname=$PLUGINSDIR\banner.bmp "${banner}"
+
+FunctionEnd
+
+; Custom welcome page
+Function welcome
+
+ nsDialogs::Create 1018
+
+ ${NSD_CreateLabel} 185 1u 210 100% "Welcome to ${productName} version ${version} installer.$\r$\n$\r$\nClick install to begin."
+
+ ${NSD_CreateBitmap} 0 0 170 210 ""
+ Pop $Image
+ ${NSD_SetImage} $Image $PLUGINSDIR\banner.bmp $ImageHandle
+
+ nsDialogs::Show
+
+ ${NSD_FreeImage} $ImageHandle
+
+FunctionEnd
+
+; Installation declarations
+Section "Install"
+
+ WriteRegStr HKLM "${regkey}" "Install_Dir" "$INSTDIR"
+ WriteRegStr HKLM "${uninstkey}" "DisplayName" "${productName}"
+ WriteRegStr HKLM "${uninstkey}" "DisplayIcon" '"$INSTDIR\icon.ico"'
+ WriteRegStr HKLM "${uninstkey}" "UninstallString" '"$INSTDIR\${uninstaller}"'
+
+ ; Remove all application files copied by previous installation
+ RMDir /r "$INSTDIR"
+
+ SetOutPath $INSTDIR
+
+ ; Include all files from /build directory
+ File /r "${src}\*"
+
+ ; Create start menu shortcut
+ CreateShortCut "$SMPROGRAMS\${productName}.lnk" "$INSTDIR\${exec}" "" "$INSTDIR\icon.ico"
+
+ WriteUninstaller "${uninstaller}"
+
+SectionEnd
+
+; --------------------------------
+; Uninstaller
+; --------------------------------
+
+ShowUninstDetails nevershow
+
+UninstallCaption "Uninstall ${productName}"
+UninstallText "Don't like ${productName} anymore? Hit uninstall button."
+UninstallIcon "${icon}"
+
+UninstPage custom un.confirm un.confirmOnLeave
+UninstPage instfiles
+
+Var RemoveAppDataCheckbox
+Var RemoveAppDataCheckbox_State
+
+; Custom uninstall confirm page
+Function un.confirm
+
+ nsDialogs::Create 1018
+
+ ${NSD_CreateLabel} 1u 1u 100% 24u "If you really want to remove ${productName} from your computer press uninstall button."
+
+ ${NSD_CreateCheckbox} 1u 35u 100% 10u "Remove also my ${productName} personal data"
+ Pop $RemoveAppDataCheckbox
+
+ nsDialogs::Show
+
+FunctionEnd
+
+Function un.confirmOnLeave
+
+ ; Save checkbox state on page leave
+ ${NSD_GetState} $RemoveAppDataCheckbox $RemoveAppDataCheckbox_State
+
+FunctionEnd
+
+; Uninstall declarations
+Section "Uninstall"
+
+ DeleteRegKey HKLM "${uninstkey}"
+ DeleteRegKey HKLM "${regkey}"
+
+ Delete "$SMPROGRAMS\${productName}.lnk"
+
+ ; Remove whole directory from Program Files
+ RMDir /r "$INSTDIR"
+
+ ; Remove also appData directory generated by your app if user checked this option
+ ${If} $RemoveAppDataCheckbox_State == ${BST_CHECKED}
+ RMDir /r "$APPDATA\${productName}"
+ ${EndIf}
+
+SectionEnd
diff --git a/desktop/resources/windows/setup-banner.bmp b/desktop/resources/windows/setup-banner.bmp
new file mode 100644
index 00000000..7471d55f
Binary files /dev/null and b/desktop/resources/windows/setup-banner.bmp differ
diff --git a/desktop/resources/windows/setup-icon.ico b/desktop/resources/windows/setup-icon.ico
new file mode 100644
index 00000000..93ea50c2
Binary files /dev/null and b/desktop/resources/windows/setup-icon.ico differ
diff --git a/desktop/stylesheets/main.css b/desktop/stylesheets/main.css
new file mode 100644
index 00000000..693e7e14
--- /dev/null
+++ b/desktop/stylesheets/main.css
@@ -0,0 +1,22 @@
+html,
+body {
+ width: 100%;
+ height: 100%;
+ margin: 0;
+ padding: 0;
+}
+body {
+ display: flex;
+ justify-content: center;
+ align-items: center;
+ font-family: sans-serif;
+}
+a {
+ text-decoration: none;
+}
+.container {
+ text-align: center;
+}
+.subtitle {
+ color: gray;
+}
diff --git a/desktop/tasks/app_npm_install.js b/desktop/tasks/app_npm_install.js
new file mode 100644
index 00000000..775f295f
--- /dev/null
+++ b/desktop/tasks/app_npm_install.js
@@ -0,0 +1,54 @@
+// This script allows you to install native modules (those which have
+// to be compiled) for your Electron app.
+// The problem is that 'npm install' compiles them against node.js you have
+// installed on your computer, NOT against node.js used in Electron
+// runtime we've downloaded to this project.
+
+'use strict';
+
+var childProcess = require('child_process');
+var jetpack = require('fs-jetpack');
+var argv = require('yargs').argv;
+
+var utils = require('./utils');
+
+var electronVersion = utils.getElectronVersion();
+
+var nodeModulesDir = jetpack.cwd(__dirname + '/../app/node_modules')
+var dependenciesCompiledAgainst = nodeModulesDir.read('electron_version');
+
+// When you raised version of Electron used in your project, the safest
+// thing to do is remove all installed dependencies and install them
+// once again (so they compile against new version if you use any
+// native package).
+if (electronVersion !== dependenciesCompiledAgainst) {
+ nodeModulesDir.dir('.', { empty: true });
+ nodeModulesDir.write('electron_version', electronVersion);
+}
+
+// Tell the 'npm install' which is about to start that we want for it
+// to compile for Electron.
+process.env.npm_config_disturl = "https://atom.io/download/atom-shell";
+process.env.npm_config_target = electronVersion;
+
+var params = ['install'];
+// Maybe there was name of package user wants to install passed as a parameter.
+if (argv._.length > 0) {
+ params.push(argv._[0]);
+ params.push('--save');
+}
+
+
+var installCommand = null;
+
+if (process.platform === 'win32') {
+ installCommand = 'npm.cmd'
+} else {
+ installCommand = 'npm'
+}
+
+var install = childProcess.spawn(installCommand, params, {
+ cwd: __dirname + '/../app',
+ env: process.env,
+ stdio: 'inherit'
+});
diff --git a/desktop/tasks/build.js b/desktop/tasks/build.js
new file mode 100644
index 00000000..3305738d
--- /dev/null
+++ b/desktop/tasks/build.js
@@ -0,0 +1,168 @@
+'use strict';
+
+var pathUtil = require('path');
+var Q = require('q');
+var gulp = require('gulp');
+var rollup = require('rollup');
+var less = require('gulp-less');
+var jetpack = require('fs-jetpack');
+var typescript = require('gulp-typescript');
+
+var utils = require('./utils');
+var generateSpecsImportFile = require('./generate_specs_import');
+
+var projectDir = jetpack;
+var srcDir = projectDir.cwd('./app');
+var destDir = projectDir.cwd('./build');
+
+var paths = {
+ copyFromAppDir: [
+ './node_modules/**',
+ './assets/**',
+ './fonts/**',
+ './vorlon/**',
+ './**/*.html',
+ './screens/**/*.js',
+ './screens/**/*.html',
+ './*.js'
+ ],
+}
+
+// -------------------------------------
+// Tasks
+// -------------------------------------
+
+gulp.task('clean', function(callback) {
+ return destDir.dirAsync('.', { empty: true });
+});
+
+
+var copyTask = function () {
+ return projectDir.copyAsync('app', destDir.path(), {
+ overwrite: true,
+ matching: paths.copyFromAppDir
+ });
+};
+gulp.task('copy', ['clean'], copyTask);
+gulp.task('copy-watch', copyTask);
+
+
+var bundle = function (src, dest) {
+ var deferred = Q.defer();
+
+ rollup.rollup({
+ entry: src
+ }).then(function (bundle) {
+ var jsFile = pathUtil.basename(dest);
+ var result = bundle.generate({
+ format: 'iife',
+ sourceMap: true,
+ sourceMapFile: jsFile,
+ });
+ return Q.all([
+ destDir.writeAsync(dest, result.code + '\n//# sourceMappingURL=' + jsFile + '.map'),
+ destDir.writeAsync(dest + '.map', result.map.toString()),
+ ]);
+ }).then(function () {
+ deferred.resolve();
+ }).catch(function (err) {
+ console.error(err);
+ });
+
+ return deferred.promise;
+};
+
+var bundleApplication = function () {
+ return Q.all([
+ bundle(srcDir.path('background.js'), destDir.path('background.js')),
+ bundle(srcDir.path('mainpage.js'), destDir.path('mainpage.js')),
+ ]);
+};
+
+var bundleSpecs = function () {
+ generateSpecsImportFile().then(function (specEntryPointPath) {
+ return Q.all([
+ bundle(srcDir.path('background.js'), destDir.path('background.js')),
+ bundle(specEntryPointPath, destDir.path('spec.js')),
+ ]);
+ });
+};
+
+var bundleTask = function () {
+ if (utils.getEnvName() === 'test') {
+ return bundleSpecs();
+ }
+ return bundleApplication();
+};
+gulp.task('bundle', ['clean'], bundleTask);
+gulp.task('bundle-watch', bundleTask);
+
+gulp.task('typescript-to-js', function() {
+ var tsResult = gulp.src(['./**/*.ts', '../typings/**/*.d.ts', '!./node_modules', '!./node_modules/**'], { cwd: './app' })
+ .pipe(typescript({ noExternalResolve: true, target: 'ES5', module: 'commonjs' }));
+
+ return tsResult.js
+ .pipe(gulp.dest('build'));
+});
+
+gulp.task('dev-typescript-to-js', function() {
+ var tsResult = gulp.src(['./app/**/*.ts', './typings/**/*.d.ts', '!./node_modules', '!./node_modules/**'], { base: './' })
+ .pipe(typescript({ noExternalResolve: true, target: 'ES5', module: 'commonjs' }));
+
+ return tsResult.js
+ .pipe(gulp.dest('.'));
+});
+
+var lessTask = function () {
+ return gulp.src(['app/**/*.less'])
+ .pipe(less())
+ .pipe(gulp.dest("build"));
+};
+gulp.task('less', ['clean'], lessTask);
+gulp.task('less-watch', lessTask);
+
+var devlessTask = function () {
+ return gulp.src(['app/**/*.less'], {base : '.'} )
+ .pipe(less())
+ .pipe(gulp.dest(''));
+};
+gulp.task('dev-less', devlessTask);
+
+gulp.task('finalize', ['clean'], function () {
+ var manifest = srcDir.read('package.json', 'json');
+ // Add "dev" or "test" suffix to name, so Electron will write all data
+ // like cookies and localStorage in separate places for each environment.
+ switch (utils.getEnvName()) {
+ case 'development':
+ manifest.name += '-dev';
+ manifest.productName += ' Dev';
+ break;
+ case 'test':
+ manifest.name += '-test';
+ manifest.productName += ' Test';
+ break;
+ }
+ destDir.write('package.json', manifest);
+
+ var configFilePath = projectDir.path('config/env_' + utils.getEnvName() + '.json');
+ destDir.copy(configFilePath, 'env_config.json');
+});
+
+
+gulp.task('watch', function () {
+ gulp.watch('app/**/*.js', ['bundle-watch']);
+ gulp.watch(paths.copyFromAppDir, { cwd: 'app' }, ['copy-watch']);
+ gulp.watch('app/**/*.less', ['less-watch']);
+});
+
+gulp.task('dev-watch', function () {
+ //gulp.watch('app/**/*.js', ['bundle-watch']);
+ //gulp.watch(paths.copyFromAppDir, { cwd: 'app' }, ['copy-watch']);
+ gulp.watch(['./app/**/*.ts', '!./node_modules', '!./node_modules/**'], ['dev-typescript-to-js']);
+ gulp.watch('app/**/*.less', ['dev-less']);
+});
+
+
+gulp.task('build', ['bundle', 'less', 'copy', 'finalize','typescript-to-js']);
+
+gulp.task('devbuild', ['dev-less','dev-typescript-to-js']);
diff --git a/desktop/tasks/generate_specs_import.js b/desktop/tasks/generate_specs_import.js
new file mode 100644
index 00000000..ea1bc196
--- /dev/null
+++ b/desktop/tasks/generate_specs_import.js
@@ -0,0 +1,28 @@
+// Spec files are scattered through the whole project. Here we're searching
+// for them and generate one entry file which will run all the tests.
+
+'use strict';
+
+var jetpack = require('fs-jetpack');
+var srcDir = jetpack.cwd('app');
+
+var fileName = 'spec.js';
+var fileBanner = "// This file is generated automatically.\n"
+ + "// All your modifications to it will be lost (so don't do it).\n";
+var whatToInclude = [
+ '*.spec.js',
+ '!node_modules/**',
+];
+
+module.exports = function () {
+ return srcDir.findAsync('.', { matching: whatToInclude }, 'relativePath')
+ .then(function (specPaths) {
+ var fileContent = specPaths.map(function (path) {
+ return 'import "' + path + '";';
+ }).join('\n');
+ return srcDir.writeAsync(fileName, fileBanner + fileContent);
+ })
+ .then(function () {
+ return srcDir.path(fileName);
+ });
+};
diff --git a/desktop/tasks/release.js b/desktop/tasks/release.js
new file mode 100644
index 00000000..0c243fbc
--- /dev/null
+++ b/desktop/tasks/release.js
@@ -0,0 +1,14 @@
+'use strict';
+
+var gulp = require('gulp');
+var utils = require('./utils');
+
+var releaseForOs = {
+ osx: require('./release_osx'),
+ linux: require('./release_linux'),
+ windows: require('./release_windows'),
+};
+
+gulp.task('release', ['build'], function () {
+ return releaseForOs[utils.os()]();
+});
diff --git a/desktop/tasks/release_linux.js b/desktop/tasks/release_linux.js
new file mode 100644
index 00000000..03dd62a1
--- /dev/null
+++ b/desktop/tasks/release_linux.js
@@ -0,0 +1,117 @@
+'use strict';
+
+var Q = require('q');
+var gulpUtil = require('gulp-util');
+var childProcess = require('child_process');
+var jetpack = require('fs-jetpack');
+var asar = require('asar');
+var utils = require('./utils');
+
+var projectDir;
+var releasesDir;
+var packName;
+var packDir;
+var tmpDir;
+var readyAppDir;
+var manifest;
+
+var init = function () {
+ projectDir = jetpack;
+ tmpDir = projectDir.dir('./tmp', { empty: true });
+ releasesDir = projectDir.dir('./releases');
+ manifest = projectDir.read('app/package.json', 'json');
+ packName = manifest.name + '_' + manifest.version;
+ packDir = tmpDir.dir(packName);
+ readyAppDir = packDir.cwd('opt', manifest.name);
+
+ return Q();
+};
+
+var copyRuntime = function () {
+ return projectDir.copyAsync('node_modules/electron-prebuilt/dist', readyAppDir.path(), { overwrite: true });
+};
+
+var packageBuiltApp = function () {
+ var deferred = Q.defer();
+
+ asar.createPackage(projectDir.path('build'), readyAppDir.path('resources/app.asar'), function() {
+ deferred.resolve();
+ });
+
+ return deferred.promise;
+};
+
+var finalize = function () {
+ // Create .desktop file from the template
+ var desktop = projectDir.read('resources/linux/app.desktop');
+ desktop = utils.replace(desktop, {
+ name: manifest.name,
+ productName: manifest.productName,
+ description: manifest.description,
+ version: manifest.version,
+ author: manifest.author
+ });
+ packDir.write('usr/share/applications/' + manifest.name + '.desktop', desktop);
+
+ // Copy icon
+ projectDir.copy('resources/icon.png', readyAppDir.path('icon.png'));
+
+ return Q();
+};
+
+var renameApp = function() {
+ return readyAppDir.renameAsync("electron", manifest.name);
+};
+
+var packToDebFile = function () {
+ var deferred = Q.defer();
+
+ var debFileName = packName + '_amd64.deb';
+ var debPath = releasesDir.path(debFileName);
+
+ gulpUtil.log('Creating DEB package...');
+
+ // Counting size of the app in KiB
+ var appSize = Math.round(readyAppDir.inspectTree('.').size / 1024);
+
+ // Preparing debian control file
+ var control = projectDir.read('resources/linux/DEBIAN/control');
+ control = utils.replace(control, {
+ name: manifest.name,
+ description: manifest.description,
+ version: manifest.version,
+ author: manifest.author,
+ size: appSize
+ });
+ packDir.write('DEBIAN/control', control);
+
+ // Build the package...
+ childProcess.exec('fakeroot dpkg-deb -Zxz --build ' + packDir.path().replace(/\s/g, '\\ ') + ' ' + debPath.replace(/\s/g, '\\ '),
+ function (error, stdout, stderr) {
+ if (error || stderr) {
+ console.log("ERROR while building DEB package:");
+ console.log(error);
+ console.log(stderr);
+ } else {
+ gulpUtil.log('DEB package ready!', debPath);
+ }
+ deferred.resolve();
+ });
+
+ return deferred.promise;
+};
+
+var cleanClutter = function () {
+ return tmpDir.removeAsync('.');
+};
+
+module.exports = function () {
+ return init()
+ .then(copyRuntime)
+ .then(packageBuiltApp)
+ .then(finalize)
+ .then(renameApp)
+ .then(packToDebFile)
+ .then(cleanClutter)
+ .catch(console.error);
+};
diff --git a/desktop/tasks/release_osx.js b/desktop/tasks/release_osx.js
new file mode 100644
index 00000000..335d41e4
--- /dev/null
+++ b/desktop/tasks/release_osx.js
@@ -0,0 +1,133 @@
+'use strict';
+
+var Q = require('q');
+var gulpUtil = require('gulp-util');
+var jetpack = require('fs-jetpack');
+var asar = require('asar');
+var utils = require('./utils');
+
+var projectDir;
+var releasesDir;
+var tmpDir;
+var finalAppDir;
+var manifest;
+
+var init = function () {
+ projectDir = jetpack;
+ tmpDir = projectDir.dir('./tmp', { empty: true });
+ releasesDir = projectDir.dir('./releases');
+ manifest = projectDir.read('app/package.json', 'json');
+ finalAppDir = tmpDir.cwd(manifest.productName + '.app');
+
+ return Q();
+};
+
+var copyRuntime = function () {
+ return projectDir.copyAsync('node_modules/electron-prebuilt/dist/Electron.app', finalAppDir.path());
+};
+
+var cleanupRuntime = function() {
+ finalAppDir.remove('Contents/Resources/default_app');
+ finalAppDir.remove('Contents/Resources/atom.icns');
+ return Q();
+}
+
+var packageBuiltApp = function () {
+ var deferred = Q.defer();
+
+ asar.createPackage(projectDir.path('build'), finalAppDir.path('Contents/Resources/app.asar'), function() {
+ deferred.resolve();
+ });
+
+ return deferred.promise;
+};
+
+var finalize = function () {
+ // Prepare main Info.plist
+ var info = projectDir.read('resources/osx/Info.plist');
+ info = utils.replace(info, {
+ productName: manifest.productName,
+ identifier: manifest.identifier,
+ version: manifest.version
+ });
+ finalAppDir.write('Contents/Info.plist', info);
+
+ // Prepare Info.plist of Helper apps
+ [' EH', ' NP', ''].forEach(function (helper_suffix) {
+ info = projectDir.read('resources/osx/helper_apps/Info' + helper_suffix + '.plist');
+ info = utils.replace(info, {
+ productName: manifest.productName,
+ identifier: manifest.identifier
+ });
+ finalAppDir.write('Contents/Frameworks/Electron Helper' + helper_suffix + '.app/Contents/Info.plist', info);
+ });
+
+ // Copy icon
+ projectDir.copy('resources/osx/icon.icns', finalAppDir.path('Contents/Resources/icon.icns'));
+
+ return Q();
+};
+
+var renameApp = function() {
+ // Rename helpers
+ [' Helper EH', ' Helper NP', ' Helper'].forEach(function (helper_suffix) {
+ finalAppDir.rename('Contents/Frameworks/Electron' + helper_suffix + '.app/Contents/MacOS/Electron' + helper_suffix, manifest.productName + helper_suffix );
+ finalAppDir.rename('Contents/Frameworks/Electron' + helper_suffix + '.app', manifest.productName + helper_suffix + '.app');
+ });
+ // Rename application
+ finalAppDir.rename('Contents/MacOS/Electron', manifest.productName);
+ return Q();
+}
+
+var packToDmgFile = function () {
+ var deferred = Q.defer();
+
+ var appdmg = require('appdmg');
+ var dmgName = manifest.name + '_' + manifest.version + '.dmg';
+
+ // Prepare appdmg config
+ var dmgManifest = projectDir.read('resources/osx/appdmg.json');
+ dmgManifest = utils.replace(dmgManifest, {
+ productName: manifest.productName,
+ appPath: finalAppDir.path(),
+ dmgIcon: projectDir.path("resources/osx/dmg-icon.icns"),
+ dmgBackground: projectDir.path("resources/osx/dmg-background.png")
+ });
+ tmpDir.write('appdmg.json', dmgManifest);
+
+ // Delete DMG file with this name if already exists
+ releasesDir.remove(dmgName);
+
+ gulpUtil.log('Packaging to DMG file...');
+
+ var readyDmgPath = releasesDir.path(dmgName);
+ appdmg({
+ source: tmpDir.path('appdmg.json'),
+ target: readyDmgPath
+ })
+ .on('error', function (err) {
+ console.error(err);
+ })
+ .on('finish', function () {
+ gulpUtil.log('DMG file ready!', readyDmgPath);
+ deferred.resolve();
+ });
+
+ return deferred.promise;
+};
+
+var cleanClutter = function () {
+ return tmpDir.removeAsync('.');
+};
+
+module.exports = function () {
+ return init()
+ .then(copyRuntime)
+ .then(cleanupRuntime)
+ .then(packageBuiltApp)
+ .then(finalize)
+ .then(renameApp)
+ .then(packToDmgFile)
+ .then(cleanClutter)
+ .catch(console.error);
+};
diff --git a/desktop/tasks/release_windows.js b/desktop/tasks/release_windows.js
new file mode 100644
index 00000000..94997d61
--- /dev/null
+++ b/desktop/tasks/release_windows.js
@@ -0,0 +1,128 @@
+'use strict';
+
+var Q = require('q');
+var gulpUtil = require('gulp-util');
+var childProcess = require('child_process');
+var jetpack = require('fs-jetpack');
+var asar = require('asar');
+var utils = require('./utils');
+
+var projectDir;
+var tmpDir;
+var releasesDir;
+var readyAppDir;
+var manifest;
+
+var init = function () {
+ projectDir = jetpack;
+ tmpDir = projectDir.dir('./tmp', { empty: true });
+ releasesDir = projectDir.dir('./releases');
+ manifest = projectDir.read('app/package.json', 'json');
+ readyAppDir = tmpDir.cwd(manifest.name);
+
+ return Q();
+};
+
+var copyRuntime = function () {
+ return projectDir.copyAsync('node_modules/electron-prebuilt/dist', readyAppDir.path(), { overwrite: true });
+};
+
+var cleanupRuntime = function () {
+ return readyAppDir.removeAsync('resources/default_app');
+};
+
+var packageBuiltApp = function () {
+ var deferred = Q.defer();
+
+ asar.createPackage(projectDir.path('build'), readyAppDir.path('resources/app.asar'), function() {
+ deferred.resolve();
+ });
+
+ return deferred.promise;
+};
+
+var finalize = function () {
+ var deferred = Q.defer();
+
+ projectDir.copy('resources/windows/icon.ico', readyAppDir.path('icon.ico'));
+
+ // Replace Electron icon for your own.
+ var rcedit = require('rcedit');
+ rcedit(readyAppDir.path('electron.exe'), {
+ 'icon': projectDir.path('resources/windows/icon.ico'),
+ 'version-string': {
+ 'ProductName': manifest.productName,
+ 'FileDescription': manifest.description,
+ }
+ }, function (err) {
+ if (!err) {
+ deferred.resolve();
+ }
+ });
+
+ return deferred.promise;
+};
+
+var renameApp = function () {
+ return readyAppDir.renameAsync('electron.exe', manifest.productName + '.exe');
+};
+
+var createInstaller = function () {
+ var deferred = Q.defer();
+
+ var finalPackageName = manifest.name + '_' + manifest.version + '.exe';
+ var installScript = projectDir.read('resources/windows/installer.nsi');
+ installScript = utils.replace(installScript, {
+ name: manifest.name,
+ productName: manifest.productName,
+ version: manifest.version,
+ src: readyAppDir.path(),
+ dest: releasesDir.path(finalPackageName),
+ icon: readyAppDir.path('icon.ico'),
+ setupIcon: projectDir.path('resources/windows/setup-icon.ico'),
+ banner: projectDir.path('resources/windows/setup-banner.bmp'),
+ });
+ tmpDir.write('installer.nsi', installScript);
+
+ gulpUtil.log('Building installer with NSIS...');
+
+ // Remove destination file if already exists.
+ releasesDir.remove(finalPackageName);
+
+ // Note: NSIS have to be added to PATH (environment variables).
+ var nsis = childProcess.spawn('makensis', [
+ tmpDir.path('installer.nsi')
+ ], {
+ stdio: 'inherit'
+ });
+ nsis.on('error', function (err) {
+ if (err.message === 'spawn makensis ENOENT') {
+ throw "Can't find NSIS. Are you sure you've installed it and"
+ + " added to PATH environment variable?";
+ } else {
+ throw err;
+ }
+ });
+ nsis.on('close', function () {
+ gulpUtil.log('Installer ready!', releasesDir.path(finalPackageName));
+ deferred.resolve();
+ });
+
+ return deferred.promise;
+};
+
+var cleanClutter = function () {
+ return tmpDir.removeAsync('.');
+};
+
+module.exports = function () {
+ return init()
+ .then(copyRuntime)
+ .then(cleanupRuntime)
+ .then(packageBuiltApp)
+ .then(finalize)
+ .then(renameApp)
+ .then(createInstaller)
+ .then(cleanClutter)
+ .catch(console.error);
+};
diff --git a/desktop/tasks/start.js b/desktop/tasks/start.js
new file mode 100644
index 00000000..9d641d6c
--- /dev/null
+++ b/desktop/tasks/start.js
@@ -0,0 +1,108 @@
+'use strict';
+
+var Q = require('q');
+var electron = require('electron-prebuilt');
+var pathUtil = require('path');
+var childProcess = require('child_process');
+var kill = require('tree-kill');
+var utils = require('./utils');
+var watch;
+
+var gulpPath = pathUtil.resolve('./node_modules/.bin/gulp');
+if (process.platform === 'win32') {
+ gulpPath += '.cmd';
+}
+
+var runBuild = function () {
+ var deferred = Q.defer();
+
+ var build = childProcess.spawn(gulpPath, [
+ 'build',
+ '--env=' + utils.getEnvName(),
+ '--color'
+ ], {
+ stdio: 'inherit'
+ });
+
+ build.on('close', function (code) {
+ deferred.resolve();
+ });
+
+ return deferred.promise;
+};
+
+
+var runDevBuild = function () {
+ var deferred = Q.defer();
+
+ var build = childProcess.spawn(gulpPath, [
+ 'devbuild',
+ '--env=' + utils.getEnvName(),
+ '--color'
+ ], {
+ stdio: 'inherit'
+ });
+
+ build.on('close', function (code) {
+ deferred.resolve();
+ });
+
+ return deferred.promise;
+};
+
+var runGulpWatch = function () {
+ watch = childProcess.spawn(gulpPath, [
+ 'watch',
+ '--env=' + utils.getEnvName(),
+ '--color'
+ ], {
+ stdio: 'inherit'
+ });
+
+ watch.on('close', function (code) {
+ // Gulp watch exits when error occured during build.
+ // Just respawn it then.
+ runGulpWatch();
+ });
+};
+
+var runDevWatch = function () {
+ watch = childProcess.spawn(gulpPath, [
+ 'dev-watch',
+ '--env=' + utils.getEnvName(),
+ '--color'
+ ], {
+ stdio: 'inherit'
+ });
+
+ watch.on('close', function (code) {
+ // Gulp watch exits when error occured during build.
+ // Just respawn it then.
+ runDevWatch();
+ });
+};
+
+var runApp = function () {
+ var app = childProcess.spawn(electron, ['./app'], {
+ stdio: 'inherit'
+ });
+
+ app.on('close', function (code) {
+ console.log("EXITED WITH CODE " + code);
+ if (watch){
+ // User closed the app. Kill the host process.
+ kill(watch.pid, 'SIGKILL', function () {
+ process.exit();
+ });
+ }else{
+ process.exit();
+ }
+ });
+};
+
+runDevBuild()
+.then(function () {
+ runDevWatch();
+ runApp();
+});
+
diff --git a/desktop/tasks/utils.js b/desktop/tasks/utils.js
new file mode 100644
index 00000000..a4c1e70c
--- /dev/null
+++ b/desktop/tasks/utils.js
@@ -0,0 +1,34 @@
+'use strict';
+
+var argv = require('yargs').argv;
+var os = require('os');
+var jetpack = require('fs-jetpack');
+
+module.exports.os = function () {
+ switch (os.platform()) {
+ case 'darwin':
+ return 'osx';
+ case 'linux':
+ return 'linux';
+ case 'win32':
+ return 'windows';
+ }
+ return 'unsupported';
+};
+
+module.exports.replace = function (str, patterns) {
+ Object.keys(patterns).forEach(function (pattern) {
+ var matcher = new RegExp('{{' + pattern + '}}', 'g');
+ str = str.replace(matcher, patterns[pattern]);
+ });
+ return str;
+};
+
+module.exports.getEnvName = function () {
+ return argv.env || 'development';
+};
+
+module.exports.getElectronVersion = function () {
+ var manifest = jetpack.read(__dirname + '/../package.json', 'json');
+ return manifest.devDependencies['electron-prebuilt'].substring(1);
+};
diff --git a/desktop/todo.txt b/desktop/todo.txt
new file mode 100644
index 00000000..69639a72
--- /dev/null
+++ b/desktop/todo.txt
@@ -0,0 +1,12 @@
+disable user-select on almost all elements
+
+improve console screen
+ add filtering
+
+improve sessions
+ add reload btn
+home
+ better responsive
+
+tray icon
+integration browser-sync
\ No newline at end of file
diff --git a/desktop/typings/github-electron/electron-prebuilt.d.ts b/desktop/typings/github-electron/electron-prebuilt.d.ts
new file mode 100644
index 00000000..7ed0ccc5
--- /dev/null
+++ b/desktop/typings/github-electron/electron-prebuilt.d.ts
@@ -0,0 +1,9 @@
+// Type definitions for electron-prebuilt 0.30.1
+// Project: https://github.com/mafintosh/electron-prebuilt
+// Definitions by: rhysd
+// Definitions: https://github.com/borisyankov/DefinitelyTyped
+
+declare module 'electron-prebuilt' {
+ var electron: string;
+ export = electron;
+}
diff --git a/desktop/typings/github-electron/github-electron-main.d.ts b/desktop/typings/github-electron/github-electron-main.d.ts
new file mode 100644
index 00000000..07535b0f
--- /dev/null
+++ b/desktop/typings/github-electron/github-electron-main.d.ts
@@ -0,0 +1,272 @@
+// Type definitions for the Electron 0.25.2 main process
+// Project: http://electron.atom.io/
+// Definitions by: jedmao
+// Definitions: https://github.com/borisyankov/DefinitelyTyped
+
+///
+
+declare module GitHubElectron {
+ interface ContentTracing {
+ /**
+ * Get a set of category groups. The category groups can change as new code paths are reached.
+ * @param callback Called once all child processes have acked to the getCategories request.
+ */
+ getCategories(callback: (categoryGroups: any[]) => void): void;
+ /**
+ * Start recording on all processes. Recording begins immediately locally, and asynchronously
+ * on child processes as soon as they receive the EnableRecording request.
+ * @param categoryFilter A filter to control what category groups should be traced.
+ * A filter can have an optional "-" prefix to exclude category groups that contain
+ * a matching category. Having both included and excluded category patterns in the
+ * same list would not be supported.
+ * @param options controls what kind of tracing is enabled, it could be a OR-ed
+ * combination of tracing.DEFAULT_OPTIONS, tracing.ENABLE_SYSTRACE, tracing.ENABLE_SAMPLING
+ * and tracing.RECORD_CONTINUOUSLY.
+ * @param callback Called once all child processes have acked to the startRecording request.
+ */
+ startRecording(categoryFilter: string, options: number, callback: Function): void;
+ /**
+ * Stop recording on all processes. Child processes typically are caching trace data and
+ * only rarely flush and send trace data back to the main process. That is because it may
+ * be an expensive operation to send the trace data over IPC, and we would like to avoid
+ * much runtime overhead of tracing. So, to end tracing, we must asynchronously ask all
+ * child processes to flush any pending trace data.
+ * @param resultFilePath Trace data will be written into this file if it is not empty,
+ * or into a temporary file.
+ * @param callback Called once all child processes have acked to the stopRecording request.
+ */
+ stopRecording(resultFilePath: string, callback:
+ /**
+ * @param filePath A file that contains the traced data.
+ */
+ (filePath: string) => void
+ ): void;
+ /**
+ * Start monitoring on all processes. Monitoring begins immediately locally, and asynchronously
+ * on child processes as soon as they receive the startMonitoring request.
+ * @param callback Called once all child processes have acked to the startMonitoring request.
+ */
+ startMonitoring(categoryFilter: string, options: number, callback: Function): void;
+ /**
+ * Stop monitoring on all processes.
+ * @param callback Called once all child processes have acked to the stopMonitoring request.
+ */
+ stopMonitoring(callback: Function): void;
+ /**
+ * Get the current monitoring traced data. Child processes typically are caching trace data
+ * and only rarely flush and send trace data back to the main process. That is because it may
+ * be an expensive operation to send the trace data over IPC, and we would like to avoid much
+ * runtime overhead of tracing. So, to end tracing, we must asynchronously ask all child
+ * processes to flush any pending trace data.
+ * @param callback Called once all child processes have acked to the captureMonitoringSnapshot request.
+ */
+ captureMonitoringSnapshot(resultFilePath: string, callback:
+ /**
+ * @param filePath A file that contains the traced data
+ * @returns {}
+ */
+ (filePath: string) => void
+ ): void;
+ /**
+ * Get the maximum across processes of trace buffer percent full state.
+ * @param callback Called when the TraceBufferUsage value is determined.
+ */
+ getTraceBufferUsage(callback: Function): void;
+ /**
+ * @param callback Called every time the given event occurs on any process.
+ */
+ setWatchEvent(categoryName: string, eventName: string, callback: Function): void;
+ /**
+ * Cancel the watch event. If tracing is enabled, this may race with the watch event callback.
+ */
+ cancelWatchEvent(): void;
+ DEFAULT_OPTIONS: number;
+ ENABLE_SYSTRACE: number;
+ ENABLE_SAMPLING: number;
+ RECORD_CONTINUOUSLY: number;
+ }
+
+ interface Dialog {
+ /**
+ * @param callback If supplied, the API call will be asynchronous.
+ * @returns On success, returns an array of file paths chosen by the user,
+ * otherwise returns undefined.
+ */
+ showOpenDialog: typeof GitHubElectron.Dialog.showOpenDialog;
+ /**
+ * @param callback If supplied, the API call will be asynchronous.
+ * @returns On success, returns the path of file chosen by the user, otherwise
+ * returns undefined.
+ */
+ showSaveDialog: typeof GitHubElectron.Dialog.showSaveDialog;
+ /**
+ * Shows a message box. It will block until the message box is closed. It returns .
+ * @param callback If supplied, the API call will be asynchronous.
+ * @returns The index of the clicked button.
+ */
+ showMessageBox: typeof GitHubElectron.Dialog.showMessageBox;
+
+ /**
+ * Runs a modal dialog that shows an error message. This API can be called safely
+ * before the ready event of app module emits, it is usually used to report errors
+ * in early stage of startup.
+ */
+ showErrorBox(title: string, content: string): void;
+ }
+
+ interface GlobalShortcut {
+ /**
+ * Registers a global shortcut of accelerator.
+ * @param accelerator Represents a keyboard shortcut. It can contain modifiers
+ * and key codes, combined by the "+" character.
+ * @param callback Called when the registered shortcut is pressed by the user.
+ * @returns {}
+ */
+ register(accelerator: string, callback: Function): void;
+ /**
+ * @param accelerator Represents a keyboard shortcut. It can contain modifiers
+ * and key codes, combined by the "+" character.
+ * @returns Whether the accelerator is registered.
+ */
+ isRegistered(accelerator: string): boolean;
+ /**
+ * Unregisters the global shortcut of keycode.
+ * @param accelerator Represents a keyboard shortcut. It can contain modifiers
+ * and key codes, combined by the "+" character.
+ */
+ unregister(accelerator: string): void;
+ /**
+ * Unregisters all the global shortcuts.
+ */
+ unregisterAll(): void;
+ }
+
+ class RequestFileJob {
+ /**
+ * Create a request job which would query a file of path and set corresponding mime types.
+ */
+ constructor(path: string);
+ }
+
+ class RequestStringJob {
+ /**
+ * Create a request job which sends a string as response.
+ */
+ constructor(options?: {
+ /**
+ * Default is "text/plain".
+ */
+ mimeType?: string;
+ /**
+ * Default is "UTF-8".
+ */
+ charset?: string;
+ data?: string;
+ });
+ }
+
+ class RequestBufferJob {
+ /**
+ * Create a request job which accepts a buffer and sends a string as response.
+ */
+ constructor(options?: {
+ /**
+ * Default is "application/octet-stream".
+ */
+ mimeType?: string;
+ /**
+ * Default is "UTF-8".
+ */
+ encoding?: string;
+ data?: Buffer;
+ });
+ }
+
+ interface Protocol {
+ registerProtocol(scheme: string, handler: (request: any) => void): void;
+ unregisterProtocol(scheme: string): void;
+ isHandledProtocol(scheme: string): boolean;
+ interceptProtocol(scheme: string, handler: (request: any) => void): void;
+ uninterceptProtocol(scheme: string): void;
+ RequestFileJob: typeof RequestFileJob;
+ RequestStringJob: typeof RequestStringJob;
+ RequestBufferJob: typeof RequestBufferJob;
+ }
+}
+
+
+declare module 'app' {
+ var _app: GitHubElectron.App;
+ export = _app;
+}
+
+declare module 'auto-updater' {
+ var _autoUpdater: GitHubElectron.AutoUpdater;
+ export = _autoUpdater;
+}
+
+declare module 'browser-window' {
+ var BrowserWindow: typeof GitHubElectron.BrowserWindow;
+ export = BrowserWindow;
+}
+
+declare module 'content-tracing' {
+ var contentTracing: GitHubElectron.ContentTracing
+ export = contentTracing;
+}
+
+declare module 'dialog' {
+ var dialog: GitHubElectron.Dialog
+ export = dialog;
+}
+
+declare module 'global-shortcut' {
+ var globalShortcut: GitHubElectron.GlobalShortcut;
+ export = globalShortcut;
+}
+//
+// declare module 'ipc' {
+// var ipc: NodeJS.EventEmitter;
+// export = ipc;
+// }
+
+declare module 'menu' {
+ var Menu: typeof GitHubElectron.Menu;
+ export = Menu;
+}
+
+declare module 'menu-item' {
+ var MenuItem: typeof GitHubElectron.MenuItem;
+ export = MenuItem;
+}
+
+declare module 'power-monitor' {
+ var powerMonitor: NodeJS.EventEmitter;
+ export = powerMonitor;
+}
+
+declare module 'protocol' {
+ var protocol: GitHubElectron.Protocol;
+ export = protocol;
+}
+
+declare module 'tray' {
+ var Tray: typeof GitHubElectron.Tray;
+ export = Tray;
+}
+//
+// interface NodeRequireFunction {
+// (id: 'app'): GitHubElectron.App
+// (id: 'auto-updater'): GitHubElectron.AutoUpdater
+// (id: 'browser-window'): typeof GitHubElectron.BrowserWindow
+// (id: 'content-tracing'): GitHubElectron.ContentTracing
+// (id: 'dialog'): GitHubElectron.Dialog
+// (id: 'global-shortcut'): GitHubElectron.GlobalShortcut
+// (id: 'ipc'): NodeJS.EventEmitter
+// (id: 'menu'): typeof GitHubElectron.Menu
+// (id: 'menu-item'): typeof GitHubElectron.MenuItem
+// (id: 'power-monitor'): NodeJS.EventEmitter
+// (id: 'protocol'): GitHubElectron.Protocol
+// (id: 'tray'): typeof GitHubElectron.Tray
+// }
+//
diff --git a/desktop/typings/github-electron/github-electron-renderer.d.ts b/desktop/typings/github-electron/github-electron-renderer.d.ts
new file mode 100644
index 00000000..69f9796b
--- /dev/null
+++ b/desktop/typings/github-electron/github-electron-renderer.d.ts
@@ -0,0 +1,117 @@
+// Type definitions for the Electron 0.25.2 renderer process (web page)
+// Project: http://electron.atom.io/
+// Definitions by: jedmao
+// Definitions: https://github.com/borisyankov/DefinitelyTyped
+
+///
+
+declare module GitHubElectron {
+ export class InProcess implements NodeJS.EventEmitter {
+ addListener(event: string, listener: Function): InProcess;
+ on(event: string, listener: Function): InProcess;
+ once(event: string, listener: Function): InProcess;
+ removeListener(event: string, listener: Function): InProcess;
+ removeAllListeners(event?: string): InProcess;
+ setMaxListeners(n: number): void;
+ listeners(event: string): Function[];
+ emit(event: string, ...args: any[]): boolean;
+ /**
+ * Send ...args to the renderer via channel in asynchronous message, the main
+ * process can handle it by listening to the channel event of ipc module.
+ */
+ send(channel: string, ...args: any[]): void;
+ /**
+ * Send ...args to the renderer via channel in synchronous message, and returns
+ * the result sent from main process. The main process can handle it by listening
+ * to the channel event of ipc module, and returns by setting event.returnValue.
+ * Note: Usually developers should never use this API, since sending synchronous
+ * message would block the whole renderer process.
+ * @returns The result sent from the main process.
+ */
+ sendSync(channel: string, ...args: any[]): string;
+ /**
+ * Like ipc.send but the message will be sent to the host page instead of the main process.
+ * This is mainly used by the page in to communicate with host page.
+ */
+ sendToHost(channel: string, ...args: any[]): void;
+ }
+
+ interface Remote {
+ /**
+ * @returns The object returned by require(module) in the main process.
+ */
+ require(module: string): any;
+ /**
+ * @returns The BrowserWindow object which this web page belongs to.
+ */
+ getCurrentWindow(): BrowserWindow
+ /**
+ * @returns The global variable of name (e.g. global[name]) in the main process.
+ */
+ getGlobal(name: string): any;
+ /**
+ * Returns the process object in the main process. This is the same as
+ * remote.getGlobal('process'), but gets cached.
+ */
+ process: any;
+ }
+
+ interface WebFrame {
+ /**
+ * Changes the zoom factor to the specified factor, zoom factor is
+ * zoom percent / 100, so 300% = 3.0.
+ */
+ setZoomFactor(factor: number): void;
+ /**
+ * @returns The current zoom factor.
+ */
+ getZoomFactor(): number;
+ /**
+ * Changes the zoom level to the specified level, 0 is "original size", and each
+ * increment above or below represents zooming 20% larger or smaller to default
+ * limits of 300% and 50% of original size, respectively.
+ */
+ setZoomLevel(level: number): void;
+ /**
+ * @returns The current zoom level.
+ */
+ getZoomLevel(): number;
+ /**
+ * Sets a provider for spell checking in input fields and text areas.
+ */
+ setSpellCheckProvider(language: string, autoCorrectWord: boolean, provider: {
+ /**
+ * @returns Whether the word passed is correctly spelled.
+ */
+ spellCheck: (text: string) => boolean;
+ }): void;
+ /**
+ * Sets the scheme as secure scheme. Secure schemes do not trigger mixed content
+ * warnings. For example, https and data are secure schemes because they cannot be
+ * corrupted by active network attackers.
+ */
+ registerUrlSchemeAsSecure(scheme: string): void;
+ }
+}
+
+// declare module 'ipc' {
+// var inProcess: GitHubElectron.InProcess;
+// export = inProcess;
+// }
+
+declare module 'remote' {
+ var remote: GitHubElectron.Remote;
+ export = remote;
+}
+
+declare module 'web-frame' {
+ var webframe: GitHubElectron.WebFrame;
+ export = webframe;
+}
+
+// interface NodeRequireFunction {
+// (id: 'ipc'): GitHubElectron.InProcess
+// (id: 'remote'): GitHubElectron.Remote
+// (id: 'web-frame'): GitHubElectron.WebFrame
+// }
+
diff --git a/desktop/typings/github-electron/github-electron.d.ts b/desktop/typings/github-electron/github-electron.d.ts
new file mode 100644
index 00000000..a0952ecd
--- /dev/null
+++ b/desktop/typings/github-electron/github-electron.d.ts
@@ -0,0 +1,1448 @@
+// Type definitions for Electron 0.25.2 (shared between main and rederer processes)
+// Project: http://electron.atom.io/
+// Definitions by: jedmao
+// Definitions: https://github.com/borisyankov/DefinitelyTyped
+
+
+declare module GitHubElectron {
+ /**
+ * This class is used to represent an image.
+ */
+ class NativeImage {
+ /**
+ * Creates an empty NativeImage instance.
+ */
+ static createEmpty(): NativeImage;
+ /**
+ * Creates a new NativeImage instance from file located at path.
+ */
+ static createFromPath(path: string): NativeImage;
+ /**
+ * Creates a new NativeImage instance from buffer.
+ * @param scaleFactor 1.0 by default.
+ */
+ static createFromBuffer(buffer: Buffer, scaleFactor?: number): NativeImage;
+ /**
+ * Creates a new NativeImage instance from dataUrl
+ */
+ static createFromDataUrl(dataUrl: string): NativeImage;
+ /**
+ * @returns Buffer Contains the image's PNG encoded data.
+ */
+ toPng(): Buffer;
+ /**
+ * @returns Buffer Contains the image's JPEG encoded data.
+ */
+ toJpeg(quality: number): Buffer;
+ /**
+ * @returns string The data URL of the image.
+ */
+ toDataUrl(): string;
+ /**
+ * @returns boolean Whether the image is empty.
+ */
+ isEmpty(): boolean;
+ /**
+ * @returns {} The size of the image.
+ */
+ getSize(): any;
+ /**
+ * Marks the image as template image.
+ */
+ setTemplateImage(option: boolean): void;
+ }
+
+ module Clipboard {
+ /**
+ * @returns The contents of the clipboard as a NativeImage.
+ */
+ function readImage(type?: string): NativeImage;
+ /**
+ * Writes the image into the clipboard.
+ */
+ function writeImage(image: NativeImage, type?: string): void;
+ }
+
+ class Screen implements NodeJS.EventEmitter {
+ addListener(event: string, listener: Function): Screen;
+ on(event: string, listener: Function): Screen;
+ once(event: string, listener: Function): Screen;
+ removeListener(event: string, listener: Function): Screen;
+ removeAllListeners(event?: string): Screen;
+ setMaxListeners(n: number): void;
+ listeners(event: string): Function[];
+ emit(event: string, ...args: any[]): boolean;
+ /**
+ * @returns The current absolute position of the mouse pointer.
+ */
+ getCursorScreenPoint(): any;
+ /**
+ * @returns The primary display.
+ */
+ getPrimaryDisplay(): any;
+ /**
+ * @returns An array of displays that are currently available.
+ */
+ getAllDisplays(): any[];
+ /**
+ * @returns The display nearest the specified point.
+ */
+ getDisplayNearestPoint(point: {
+ x: number;
+ y: number;
+ }): any;
+ /**
+ * @returns The display that most closely intersects the provided bounds.
+ */
+ getDisplayMatching(rect: Rectangle): any;
+ }
+
+ /**
+ * The BrowserWindow class gives you ability to create a browser window.
+ * You can also create a window without chrome by using Frameless Window API.
+ */
+ class BrowserWindow implements NodeJS.EventEmitter {
+ addListener(event: string, listener: Function): WebContents;
+ on(event: string, listener: Function): WebContents;
+ once(event: string, listener: Function): WebContents;
+ removeListener(event: string, listener: Function): WebContents;
+ removeAllListeners(event?: string): WebContents;
+ setMaxListeners(n: number): void;
+ listeners(event: string): Function[];
+ emit(event: string, ...args: any[]): boolean;
+ constructor(options?: BrowserWindowOptions);
+ /**
+ * @returns All opened browser windows.
+ */
+ static getAllWindows(): BrowserWindow[];
+ /**
+ * @returns The window that is focused in this application.
+ */
+ static getFocusedWindow(): BrowserWindow;
+ /**
+ * Find a window according to the webContents it owns.
+ */
+ static fromWebContents(webContents: WebContents): BrowserWindow;
+ /**
+ * Find a window according to its ID.
+ */
+ static fromId(id: number): BrowserWindow;
+ /**
+ * Adds devtools extension located at path. The extension will be remembered
+ * so you only need to call this API once, this API is not for programming use.
+ * @returns The extension's name.
+ */
+ static addDevToolsExtension(path: string): string;
+ /**
+ * Remove a devtools extension.
+ * @param name The name of the devtools extension to remove.
+ */
+ static removeDevToolsExtension(name: string): void;
+ /**
+ * The WebContents object this window owns, all web page related events and
+ * operations would be done via it.
+ * Note: Users should never store this object because it may become null when
+ * the renderer process (web page) has crashed.
+ */
+ webContents: WebContents;
+ /**
+ * Get the WebContents of devtools of this window.
+ * Note: Users should never store this object because it may become null when
+ * the devtools has been closed.
+ */
+ devToolsWebContents: WebContents;
+ /**
+ * Get the unique ID of this window.
+ */
+ id: number;
+ /**
+ * Force closing the window, the unload and beforeunload event won't be emitted
+ * for the web page, and close event would also not be emitted for this window,
+ * but it would guarantee the closed event to be emitted.
+ * You should only use this method when the renderer process (web page) has crashed.
+ */
+ destroy(): void;
+ /**
+ * Try to close the window, this has the same effect with user manually clicking
+ * the close button of the window. The web page may cancel the close though,
+ * see the close event.
+ */
+ close(): void;
+ /**
+ * Focus on the window.
+ */
+ focus(): void;
+ /**
+ * @returns Whether the window is focused.
+ */
+ isFocused(): boolean;
+ /**
+ * Shows and gives focus to the window.
+ */
+ show(): void;
+ /**
+ * Shows the window but doesn't focus on it.
+ */
+ showInactive(): void;
+ /**
+ * Hides the window.
+ */
+ hide(): void;
+ /**
+ * @returns Whether the window is visible to the user.
+ */
+ isVisible(): boolean;
+ /**
+ * Maximizes the window.
+ */
+ maximize(): void;
+ /**
+ * Unmaximizes the window.
+ */
+ unmaximize(): void;
+ /**
+ * @returns Whether the window is maximized.
+ */
+ isMaximized(): boolean;
+ /**
+ * Minimizes the window. On some platforms the minimized window will be
+ * shown in the Dock.
+ */
+ minimize(): void;
+ /**
+ * Restores the window from minimized state to its previous state.
+ */
+ restore(): void;
+ /**
+ * @returns Whether the window is minimized.
+ */
+ isMinimized(): boolean;
+ /**
+ * Sets whether the window should be in fullscreen mode.
+ */
+ setFullScreen(flag: boolean): void;
+ /**
+ * @returns Whether the window is in fullscreen mode.
+ */
+ isFullScreen(): boolean;
+ /**
+ * Resizes and moves the window to width, height, x, y.
+ */
+ setBounds(options: Rectangle): void;
+ /**
+ * @returns The window's width, height, x and y values.
+ */
+ getBounds(): Rectangle;
+ /**
+ * Resizes the window to width and height.
+ */
+ setSize(width: number, height: number): void;
+ /**
+ * @returns The window's width and height.
+ */
+ getSize(): number[];
+ /**
+ * Resizes the window's client area (e.g. the web page) to width and height.
+ */
+ setContentSize(width: number, height: number): void;
+ /**
+ * @returns The window's client area's width and height.
+ */
+ getContentSize(): number[];
+ /**
+ * Sets the minimum size of window to width and height.
+ */
+ setMinimumSize(width: number, height: number): void;
+ /**
+ * @returns The window's minimum width and height.
+ */
+ getMinimumSize(): number[];
+ /**
+ * Sets the maximum size of window to width and height.
+ */
+ setMaximumSize(width: number, height: number): void;
+ /**
+ * @returns The window's maximum width and height.
+ */
+ getMaximumSize(): number[];
+ /**
+ * Sets whether the window can be manually resized by user.
+ */
+ setResizable(resizable: boolean): void;
+ /**
+ * @returns Whether the window can be manually resized by user.
+ */
+ isResizable(): boolean;
+ /**
+ * Sets whether the window should show always on top of other windows. After
+ * setting this, the window is still a normal window, not a toolbox window
+ * which can not be focused on.
+ */
+ setAlwaysOnTop(flag: boolean): void;
+ /**
+ * @returns Whether the window is always on top of other windows.
+ */
+ isAlwaysOnTop(): boolean;
+ /**
+ * Moves window to the center of the screen.
+ */
+ center(): void;
+ /**
+ * Moves window to x and y.
+ */
+ setPosition(x: number, y: number): void;
+ /**
+ * @returns The window's current position.
+ */
+ getPosition(): number[];
+ /**
+ * Changes the title of native window to title.
+ */
+ setTitle(title: string): void;
+ /**
+ * Note: The title of web page can be different from the title of the native window.
+ * @returns The title of the native window.
+ */
+ getTitle(): string;
+ /**
+ * Starts or stops flashing the window to attract user's attention.
+ */
+ flashFrame(flag: boolean): void;
+ /**
+ * Makes the window do not show in Taskbar.
+ */
+ setSkipTaskbar(skip: boolean): void;
+ /**
+ * Enters or leaves the kiosk mode.
+ */
+ setKiosk(flag: boolean): void;
+ /**
+ * @returns Whether the window is in kiosk mode.
+ */
+ isKiosk(): boolean;
+ /**
+ * Sets the pathname of the file the window represents, and the icon of the
+ * file will show in window's title bar.
+ * Note: This API is available only on OS X.
+ */
+ setRepresentedFilename(filename: string): void;
+ /**
+ * Note: This API is available only on OS X.
+ * @returns The pathname of the file the window represents.
+ */
+ getRepresentedFilename(): string;
+ /**
+ * Specifies whether the window’s document has been edited, and the icon in
+ * title bar will become grey when set to true.
+ * Note: This API is available only on OS X.
+ */
+ setDocumentEdited(edited: boolean): void;
+ /**
+ * Note: This API is available only on OS X.
+ * @returns Whether the window's document has been edited.
+ */
+ isDocumentEdited(): boolean;
+ /**
+ * Opens the developer tools.
+ */
+ openDevTools(options?: {
+ /**
+ * Opens devtools in a new window.
+ */
+ detach?: boolean;
+ }): void;
+ /**
+ * Closes the developer tools.
+ */
+ closeDevTools(): void;
+ /**
+ * Returns whether the developer tools are opened.
+ */
+ isDevToolsOpened(): boolean;
+ /**
+ * Toggle the developer tools.
+ */
+ toggleDevTools(): void;
+ reloadIgnoringCache(): void;
+ /**
+ * Starts inspecting element at position (x, y).
+ */
+ inspectElement(x: number, y: number): void;
+ focusOnWebView(): void;
+ blurWebView(): void;
+ /**
+ * Captures the snapshot of page within rect, upon completion the callback
+ * will be called. Omitting the rect would capture the whole visible page.
+ * Note: Be sure to read documents on remote buffer in remote if you are going
+ * to use this API in renderer process.
+ * @param callback Supplies the image that stores data of the snapshot.
+ */
+ capturePage(rect: Rectangle, callback: (image: NativeImage) => void): void;
+ capturePage(callback: (image: NativeImage) => void): void;
+ /**
+ * Same with webContents.print([options])
+ */
+ print(options?: {
+ silent?: boolean;
+ printBackground?: boolean;
+ }): void;
+ /**
+ * Same with webContents.printToPDF([options])
+ */
+ printToPDF(options: {
+ marginsType?: number;
+ pageSize?: string;
+ printBackground?: boolean;
+ printSelectionOnly?: boolean;
+ landscape?: boolean;
+ }, callback: (error: Error, data: Buffer) => void): void;
+ /**
+ * Same with webContents.loadUrl(url).
+ */
+ loadUrl(url: string, options?: {
+ httpReferrer?: string;
+ userAgent?: string;
+ }): void;
+ /**
+ * Same with webContents.reload.
+ */
+ reload(): void;
+ /**
+ * Sets the menu as the window top menu.
+ * Note: This API is not available on OS X.
+ */
+ setMenu(menu: Menu): void;
+ /**
+ * Sets the progress value in the progress bar.
+ * On Linux platform, only supports Unity desktop environment, you need to
+ * specify the *.desktop file name to desktopName field in package.json.
+ * By default, it will assume app.getName().desktop.
+ * @param progress Valid range is [0, 1.0]. If < 0, the progress bar is removed.
+ * If greater than 0, it becomes indeterminate.
+ */
+ setProgressBar(progress: number): void;
+ /**
+ * Sets a 16px overlay onto the current Taskbar icon, usually used to convey
+ * some sort of application status or to passively notify the user.
+ * Note: This API is only available on Windows 7 or above.
+ * @param overlay The icon to display on the bottom right corner of the Taskbar
+ * icon. If this parameter is null, the overlay is cleared
+ * @param description Provided to Accessibility screen readers.
+ */
+ setOverlayIcon(overlay: NativeImage, description: string): void;
+ send(channel: string, ...args: any[]): void;
+ /**
+ * Shows pop-up dictionary that searches the selected word on the page.
+ * Note: This API is available only on OS X.
+ */
+ showDefinitionForSelection(): void;
+ /**
+ * Sets whether the window menu bar should hide itself automatically. Once set
+ * the menu bar will only show when users press the single Alt key.
+ * If the menu bar is already visible, calling setAutoHideMenuBar(true) won't
+ * hide it immediately.
+ */
+ setAutoHideMenuBar(hide: boolean): void;
+ /**
+ * @returns Whether menu bar automatically hides itself.
+ */
+ isMenuBarAutoHide(): boolean;
+ /**
+ * Sets whether the menu bar should be visible. If the menu bar is auto-hide,
+ * users can still bring up the menu bar by pressing the single Alt key.
+ */
+ setMenuBarVisibility(visibile: boolean): void;
+ /**
+ * @returns Whether the menu bar is visible.
+ */
+ isMenuBarVisible(): boolean;
+ /**
+ * Sets whether the window should be visible on all workspaces.
+ * Note: This API does nothing on Windows.
+ */
+ setVisibleOnAllWorkspaces(visible: boolean): void;
+ /**
+ * Note: This API always returns false on Windows.
+ * @returns Whether the window is visible on all workspaces.
+ */
+ isVisibleOnAllWorkspaces(): boolean;
+ }
+
+ // Includes all options BrowserWindow can take as of this writing
+ // http://electron.atom.io/docs/v0.29.0/api/browser-window/
+ interface BrowserWindowOptions extends Rectangle {
+ show?: boolean;
+ 'use-content-size'?: boolean;
+ center?: boolean;
+ 'min-width'?: number;
+ 'min-height'?: number;
+ 'max-width'?: number;
+ 'max-height'?: number;
+ resizable?: boolean;
+ 'always-on-top'?: boolean;
+ fullscreen?: boolean;
+ 'skip-taskbar'?: boolean;
+ 'zoom-factor'?: number;
+ kiosk?: boolean;
+ title?: string;
+ icon?: NativeImage | string;
+ frame?: boolean;
+ 'node-integration'?: boolean;
+ 'accept-first-mouse'?: boolean;
+ 'disable-auto-hide-cursor'?: boolean;
+ 'auto-hide-menu-bar'?: boolean;
+ 'enable-larger-than-screen'?: boolean;
+ 'dark-theme'?: boolean;
+ preload?: string;
+ transparent?: boolean;
+ type?: string;
+ 'standard-window'?: boolean;
+ 'web-preferences'?: any; // Object
+ javascript?: boolean;
+ 'web-security'?: boolean;
+ images?: boolean;
+ java?: boolean;
+ 'text-areas-are-resizable'?: boolean;
+ webgl?: boolean;
+ webaudio?: boolean;
+ plugins?: boolean;
+ 'extra-plugin-dirs'?: string[];
+ 'experimental-features'?: boolean;
+ 'experimental-canvas-features'?: boolean;
+ 'subpixel-font-scaling'?: boolean;
+ 'overlay-scrollbars'?: boolean;
+ 'overlay-fullscreen-video'?: boolean;
+ 'shared-worker'?: boolean;
+ 'direct-write'?: boolean;
+ 'page-visibility'?: boolean;
+ 'title-bar-style'?: string;
+ }
+
+ interface Rectangle {
+ x?: number;
+ y?: number;
+ width?: number;
+ height?: number;
+ }
+
+ /**
+ * A WebContents is responsible for rendering and controlling a web page.
+ */
+ class WebContents implements NodeJS.EventEmitter {
+ addListener(event: string, listener: Function): WebContents;
+ on(event: string, listener: Function): WebContents;
+ once(event: string, listener: Function): WebContents;
+ removeListener(event: string, listener: Function): WebContents;
+ removeAllListeners(event?: string): WebContents;
+ setMaxListeners(n: number): void;
+ listeners(event: string): Function[];
+ emit(event: string, ...args: any[]): boolean;
+ /**
+ * Loads the url in the window.
+ * @param url Must contain the protocol prefix (e.g., the http:// or file://).
+ */
+ loadUrl(url: string, options?: {
+ httpReferrer?: string;
+ userAgent?: string;
+ }): void;
+ /**
+ * @returns The URL of current web page.
+ */
+ getUrl(): string;
+ /**
+ * @returns The title of web page.
+ */
+ getTitle(): string;
+ /**
+ * @returns The favicon of the web page.
+ */
+ getFavicon(): NativeImage;
+ /**
+ * @returns Whether web page is still loading resources.
+ */
+ isLoading(): boolean;
+ /**
+ * @returns Whether web page is waiting for a first-response for the main
+ * resource of the page.
+ */
+ isWaitingForResponse(): boolean;
+ /**
+ * Stops any pending navigation.
+ */
+ stop(): void;
+ /**
+ * Reloads current page.
+ */
+ reload(): void;
+ /**
+ * Reloads current page and ignores cache.
+ */
+ reloadIgnoringCache(): void;
+ /**
+ * @returns Whether the web page can go back.
+ */
+ canGoBack(): boolean;
+ /**
+ * @returns Whether the web page can go forward.
+ */
+ canGoForward(): boolean;
+ /**
+ * @returns Whether the web page can go to offset.
+ */
+ canGoToOffset(offset: number): boolean;
+ /**
+ * Makes the web page go back.
+ */
+ goBack(): void;
+ /**
+ * Makes the web page go forward.
+ */
+ goForward(): void;
+ /**
+ * Navigates to the specified absolute index.
+ */
+ goToIndex(index: number): void;
+ /**
+ * Navigates to the specified offset from the "current entry".
+ */
+ goToOffset(offset: number): void;
+ /**
+ * @returns Whether the renderer process has crashed.
+ */
+ isCrashed(): boolean;
+ /**
+ * Overrides the user agent for this page.
+ */
+ setUserAgent(userAgent: string): void;
+ /**
+ * Injects CSS into this page.
+ */
+ insertCSS(css: string): void;
+ /**
+ * Evaluates code in page.
+ * @param code Code to evaluate.
+ */
+ executeJavaScript(code: string): void;
+ /**
+ * Executes Edit -> Undo command in page.
+ */
+ undo(): void;
+ /**
+ * Executes Edit -> Redo command in page.
+ */
+ redo(): void;
+ /**
+ * Executes Edit -> Cut command in page.
+ */
+ cut(): void;
+ /**
+ * Executes Edit -> Copy command in page.
+ */
+ copy(): void;
+ /**
+ * Executes Edit -> Paste command in page.
+ */
+ paste(): void;
+ /**
+ * Executes Edit -> Delete command in page.
+ */
+ delete(): void;
+ /**
+ * Executes Edit -> Select All command in page.
+ */
+ selectAll(): void;
+ /**
+ * Executes Edit -> Unselect command in page.
+ */
+ unselect(): void;
+ /**
+ * Executes Edit -> Replace command in page.
+ */
+ replace(text: string): void;
+ /**
+ * Executes Edit -> Replace Misspelling command in page.
+ */
+ replaceMisspelling(text: string): void;
+ /**
+ * Checks if any serviceworker is registered.
+ */
+ hasServiceWorker(callback: (hasServiceWorker: boolean) => void): void;
+ /**
+ * Unregisters any serviceworker if present.
+ */
+ unregisterServiceWorker(callback:
+ /**
+ * @param isFulfilled Whether the JS promise is fulfilled.
+ */
+ (isFulfilled: boolean) => void): void;
+ /**
+ *
+ * Prints window's web page. When silent is set to false, Electron will pick up system's default printer and default settings for printing.
+ * Calling window.print() in web page is equivalent to call WebContents.print({silent: false, printBackground: false}).
+ * Note:
+ * On Windows, the print API relies on pdf.dll. If your application doesn't need print feature, you can safely remove pdf.dll in saving binary size.
+ */
+ print(options?: {
+ /**
+ * Don't ask user for print settings, defaults to false
+ */
+ silent?: boolean;
+ /**
+ * Also prints the background color and image of the web page, defaults to false.
+ */
+ printBackground: boolean;
+ }): void;
+ /**
+ * Prints windows' web page as PDF with Chromium's preview printing custom settings.
+ */
+ printToPDF(options: {
+ /**
+ * Specify the type of margins to use. Default is 0.
+ * 0 - default
+ * 1 - none
+ * 2 - minimum
+ */
+ marginsType?: number;
+ /**
+ * String - Specify page size of the generated PDF. Default is A4.
+ * A4
+ * A3
+ * Legal
+ * Letter
+ * Tabloid
+ */
+ pageSize?: string;
+ /**
+ * Whether to print CSS backgrounds. Default is false.
+ */
+ printBackground?: boolean;
+ /**
+ * Whether to print selection only. Default is false.
+ */
+ printSelectionOnly?: boolean;
+ /**
+ * true for landscape, false for portrait. Default is false.
+ */
+ landscape?: boolean;
+ },
+ /**
+ * Callback function on completed converting to PDF.
+ * error Error
+ * data Buffer - PDF file content
+ */
+ callback: (error: Error, data: Buffer) => void): void;
+ /**
+ * Send args.. to the web page via channel in asynchronous message, the web page
+ * can handle it by listening to the channel event of ipc module.
+ * Note:
+ * 1. The IPC message handler in web pages do not have a event parameter,
+ * which is different from the handlers on the main process.
+ * 2. There is no way to send synchronous messages from the main process
+ * to a renderer process, because it would be very easy to cause dead locks.
+ */
+ send(channel: string, ...args: any[]): void;
+ }
+
+ /**
+ * The Menu class is used to create native menus that can be used as application
+ * menus and context menus. Each menu consists of multiple menu items, and each
+ * menu item can have a submenu.
+ */
+ class Menu {
+ /**
+ * Creates a new menu.
+ */
+ constructor();
+ /**
+ * Sets menu as the application menu on OS X. On Windows and Linux, the menu
+ * will be set as each window's top menu.
+ */
+ static setApplicationMenu(menu: Menu): void;
+ /**
+ * Sends the action to the first responder of application, this is used for
+ * emulating default Cocoa menu behaviors, usually you would just use the
+ * selector property of MenuItem.
+ *
+ * Note: This method is OS X only.
+ */
+ static sendActionToFirstResponder(action: string): void;
+ /**
+ * @param template Generally, just an array of options for constructing MenuItem.
+ * You can also attach other fields to element of the template, and they will
+ * become properties of the constructed menu items.
+ */
+ static buildFromTemplate(template: MenuItemOptions[]): Menu;
+ /**
+ * Popups this menu as a context menu in the browserWindow. You can optionally
+ * provide a (x,y) coordinate to place the menu at, otherwise it will be placed
+ * at the current mouse cursor position.
+ * @param x Horizontal coordinate where the menu will be placed.
+ * @param y Vertical coordinate where the menu will be placed.
+ */
+ popup(browserWindow: BrowserWindow, x?: number, y?: number): void;
+ /**
+ * Appends the menuItem to the menu.
+ */
+ append(menuItem: MenuItem): void;
+ /**
+ * Inserts the menuItem to the pos position of the menu.
+ */
+ insert(position: number, menuItem: MenuItem): void;
+ items: MenuItem[];
+ }
+
+ class MenuItem {
+ constructor(options?: MenuItemOptions);
+ options: MenuItemOptions;
+ }
+
+ interface MenuItemOptions {
+ /**
+ * Callback when the menu item is clicked.
+ */
+ click?: Function;
+ /**
+ * Call the selector of first responder when clicked (OS X only).
+ */
+ selector?: string;
+ /**
+ * Can be normal, separator, submenu, checkbox or radio.
+ */
+ type?: string;
+ label?: string;
+ sublabel?: string;
+ /**
+ * An accelerator is string that represents a keyboard shortcut, it can contain
+ * multiple modifiers and key codes, combined by the + character.
+ *
+ * Examples:
+ * Command+A
+ * Ctrl+Shift+Z
+ *
+ * Platform notice: On Linux and Windows, the Command key would not have any effect,
+ * you can use CommandOrControl which represents Command on OS X and Control on
+ * Linux and Windows to define some accelerators.
+ *
+ * Available modifiers:
+ * Command (or Cmd for short)
+ * Control (or Ctrl for short)
+ * CommandOrControl (or CmdOrCtrl for short)
+ * Alt
+ * Shift
+ *
+ * Available key codes:
+ * 0 to 9
+ * A to Z
+ * F1 to F24
+ * Punctuations like ~, !, @, #, $, etc.
+ * Plus
+ * Space
+ * Backspace
+ * Delete
+ * Insert
+ * Return (or Enter as alias)
+ * Up, Down, Left and Right
+ * Home and End
+ * PageUp and PageDown
+ * Escape (or Esc for short)
+ * VolumeUp, VolumeDown and VolumeMute
+ * MediaNextTrack, MediaPreviousTrack, MediaStop and MediaPlayPause
+ */
+ accelerator?: string;
+ /**
+ * In Electron for the APIs that take images, you can pass either file paths
+ * or NativeImage instances. When passing null, an empty image will be used.
+ */
+ icon?: NativeImage | string;
+ enabled?: boolean;
+ visible?: boolean;
+ checked?: boolean;
+ /**
+ * Should be specified for submenu type menu item, when it's specified the
+ * type: 'submenu' can be omitted for the menu item
+ */
+ submenu?: MenuItemOptions[];
+ /**
+ * Unique within a single menu. If defined then it can be used as a reference
+ * to this item by the position attribute.
+ */
+ id?: string;
+ /**
+ * This field allows fine-grained definition of the specific location within
+ * a given menu.
+ */
+ position?: string;
+ }
+
+ class BrowserWindowProxy {
+ /**
+ * Removes focus from the child window.
+ */
+ blur(): void;
+ /**
+ * Forcefully closes the child window without calling its unload event.
+ */
+ close(): void;
+ /**
+ * Set to true after the child window gets closed.
+ */
+ closed: boolean;
+ /**
+ * Evaluates the code in the child window.
+ */
+ eval(code: string): void;
+ /**
+ * Focuses the child window (brings the window to front).
+ */
+ focus(): void;
+ /**
+ * Sends a message to the child window with the specified origin or * for no origin preference.
+ * In addition to these methods, the child window implements window.opener object with no
+ * properties and a single method.
+ */
+ postMessage(message: string, targetOrigin: string): void;
+ }
+
+ class App implements NodeJS.EventEmitter {
+ addListener(event: string, listener: Function): App;
+ on(event: string, listener: Function): App;
+ once(event: string, listener: Function): App;
+ removeListener(event: string, listener: Function): App;
+ removeAllListeners(event?: string): App;
+ setMaxListeners(n: number): void;
+ listeners(event: string): Function[];
+ emit(event: string, ...args: any[]): boolean;
+ /**
+ * Try to close all windows. The before-quit event will first be emitted.
+ * If all windows are successfully closed, the will-quit event will be emitted
+ * and by default the application would be terminated.
+ *
+ * This method guarantees all beforeunload and unload handlers are correctly
+ * executed. It is possible that a window cancels the quitting by returning
+ * false in beforeunload handler.
+ */
+ quit(): void;
+ /**
+ * Quit the application directly, it will not try to close all windows so
+ * cleanup code will not run.
+ */
+ terminate(): void;
+ /**
+ * Returns the current application directory.
+ */
+ getAppPath(): string;
+ /**
+ * @param name One of: home, appData, userData, cache, userCache, temp, userDesktop, exe, module
+ * @returns The path to a special directory or file associated with name.
+ * On failure an Error would throw.
+ */
+ getPath(name: string): string;
+ /**
+ * Overrides the path to a special directory or file associated with name.
+ * If the path specifies a directory that does not exist, the directory will
+ * be created by this method. On failure an Error would throw.
+ *
+ * You can only override paths of names defined in app.getPath.
+ *
+ * By default web pages' cookies and caches will be stored under userData
+ * directory, if you want to change this location, you have to override the
+ * userData path before the ready event of app module gets emitted.
+ */
+ setPath(name: string, path: string): void;
+ /**
+ * @returns The version of loaded application, if no version is found in
+ * application's package.json, the version of current bundle or executable.
+ */
+ getVersion(): string;
+ /**
+ *
+ * @returns The current application's name, the name in package.json would be used.
+ * Usually the name field of package.json is a short lowercased name, according to
+ * the spec of npm modules. So usually you should also specify a productName field,
+ * which is your application's full capitalized name, and it will be preferred over
+ * name by Electron.
+ */
+ getName(): string;
+ /**
+ * Resolves the proxy information for url, the callback would be called with
+ * callback(proxy) when the request is done.
+ */
+ resolveProxy(url: string, callback: Function): void;
+ /**
+ * Adds path to recent documents list.
+ *
+ * This list is managed by the system, on Windows you can visit the list from
+ * task bar, and on Mac you can visit it from dock menu.
+ */
+ addRecentDocument(path: string): void;
+ /**
+ * Clears the recent documents list.
+ */
+ clearRecentDocuments(): void;
+ /**
+ * Adds tasks to the Tasks category of JumpList on Windows.
+ *
+ * Note: This API is only available on Windows.
+ */
+ setUserTasks(tasks: Task[]): void;
+ dock: BrowserWindow;
+ commandLine: CommandLine;
+ /**
+ * This method makes your application a Single Instance Application instead of allowing
+ * multiple instances of your app to run, this will ensure that only a single instance
+ * of your app is running, and other instances signal this instance and exit.
+ */
+ makeSingleInstance(callback: (args: string[], workingDirectory: string) => boolean): boolean;
+ }
+
+ interface CommandLine {
+ /**
+ * Append a switch [with optional value] to Chromium's command line.
+ *
+ * Note: This will not affect process.argv, and is mainly used by developers
+ * to control some low-level Chromium behaviors.
+ */
+ appendSwitch(_switch: string, value?: string | number): void;
+ /**
+ * Append an argument to Chromium's command line. The argument will quoted properly.
+ *
+ * Note: This will not affect process.argv.
+ */
+ appendArgument(value: any): void;
+ }
+
+ interface Task {
+ /**
+ * Path of the program to execute, usually you should specify process.execPath
+ * which opens current program.
+ */
+ program: string;
+ /**
+ * The arguments of command line when program is executed.
+ */
+ arguments: string;
+ /**
+ * The string to be displayed in a JumpList.
+ */
+ title: string;
+ /**
+ * Description of this task.
+ */
+ description: string;
+ /**
+ * The absolute path to an icon to be displayed in a JumpList, it can be
+ * arbitrary resource file that contains an icon, usually you can specify
+ * process.execPath to show the icon of the program.
+ */
+ iconPath: string;
+ /**
+ * The icon index in the icon file. If an icon file consists of two or more
+ * icons, set this value to identify the icon. If an icon file consists of
+ * one icon, this value is 0.
+ */
+ iconIndex: number;
+ commandLine: CommandLine;
+ dock: {
+ /**
+ * When critical is passed, the dock icon will bounce until either the
+ * application becomes active or the request is canceled.
+ *
+ * When informational is passed, the dock icon will bounce for one second.
+ * The request, though, remains active until either the application becomes
+ * active or the request is canceled.
+ *
+ * Note: This API is only available on Mac.
+ * @param type Can be critical or informational, the default is informational.
+ * @returns An ID representing the request
+ */
+ bounce(type?: string): any;
+ /**
+ * Cancel the bounce of id.
+ *
+ * Note: This API is only available on Mac.
+ */
+ cancelBounce(id: number): void;
+ /**
+ * Sets the string to be displayed in the dock’s badging area.
+ *
+ * Note: This API is only available on Mac.
+ */
+ setBadge(text: string): void;
+ /**
+ * Returns the badge string of the dock.
+ *
+ * Note: This API is only available on Mac.
+ */
+ getBadge(): string;
+ /**
+ * Hides the dock icon.
+ *
+ * Note: This API is only available on Mac.
+ */
+ hide(): void;
+ /**
+ * Shows the dock icon.
+ *
+ * Note: This API is only available on Mac.
+ */
+ show(): void;
+ /**
+ * Sets the application dock menu.
+ *
+ * Note: This API is only available on Mac.
+ */
+ setMenu(menu: Menu): void;
+ }
+ }
+
+ class AutoUpdater implements NodeJS.EventEmitter {
+ addListener(event: string, listener: Function): AutoUpdater;
+ on(event: string, listener: Function): AutoUpdater;
+ once(event: string, listener: Function): AutoUpdater;
+ removeListener(event: string, listener: Function): AutoUpdater;
+ removeAllListeners(event?: string): AutoUpdater;
+ setMaxListeners(n: number): void;
+ listeners(event: string): Function[];
+ emit(event: string, ...args: any[]): boolean;
+ /**
+ * Set the url and initialize the auto updater.
+ * The url cannot be changed once it is set.
+ */
+ setFeedUrl(url: string): void;
+ /**
+ * Ask the server whether there is an update, you have to call setFeedUrl
+ * before using this API
+ */
+ checkForUpdates(): any;
+ }
+
+ module Dialog {
+ /**
+ * @param callback If supplied, the API call will be asynchronous.
+ * @returns On success, returns an array of file paths chosen by the user,
+ * otherwise returns undefined.
+ */
+ export function showOpenDialog(
+ browserWindow?: BrowserWindow,
+ options?: OpenDialogOptions,
+ callback?: (fileNames: string[]) => void
+ ): void;
+ export function showOpenDialog(
+ options?: OpenDialogOptions,
+ callback?: (fileNames: string[]) => void
+ ): void;
+
+ interface OpenDialogOptions {
+ title?: string;
+ defaultPath?: string;
+ /**
+ * File types that can be displayed or selected.
+ */
+ filters?: {
+ name: string;
+ extensions: string[];
+ }[];
+ /**
+ * Contains which features the dialog should use, can contain openFile,
+ * openDirectory, multiSelections and createDirectory
+ */
+ properties?: string | string[];
+ }
+
+ /**
+ * @param browserWindow
+ * @param options
+ * @param callback If supplied, the API call will be asynchronous.
+ * @returns On success, returns the path of file chosen by the user, otherwise
+ * returns undefined.
+ */
+ export function showSaveDialog(browserWindow?: BrowserWindow, options?: {
+ title?: string;
+ defaultPath?: string;
+ /**
+ * File types that can be displayed, see dialog.showOpenDialog for an example.
+ */
+ filters?: string[];
+ }, callback?: (fileName: string) => void): void;
+
+ /**
+ * Shows a message box. It will block until the message box is closed. It returns .
+ * @param callback If supplied, the API call will be asynchronous.
+ * @returns The index of the clicked button.
+ */
+ export function showMessageBox(
+ browserWindow?: BrowserWindow,
+ options?: ShowMessageBoxOptions,
+ callback?: (response: any) => void
+ ): number;
+ export function showMessageBox(
+ options: ShowMessageBoxOptions,
+ callback?: (response: any) => void
+ ): number;
+
+ export interface ShowMessageBoxOptions {
+ /**
+ * Can be "none", "info" or "warning".
+ */
+ type?: string;
+ /**
+ * Texts for buttons.
+ */
+ buttons?: string[];
+ /**
+ * Title of the message box (some platforms will not show it).
+ */
+ title?: string;
+ /**
+ * Contents of the message box.
+ */
+ message?: string;
+ /**
+ * Extra information of the message.
+ */
+ detail?: string;
+ icon?: NativeImage;
+ }
+ }
+
+ class Tray implements NodeJS.EventEmitter {
+ addListener(event: string, listener: Function): Tray;
+ on(event: string, listener: Function): Tray;
+ once(event: string, listener: Function): Tray;
+ removeListener(event: string, listener: Function): Tray;
+ removeAllListeners(event?: string): Tray;
+ setMaxListeners(n: number): void;
+ listeners(event: string): Function[];
+ emit(event: string, ...args: any[]): boolean;
+ /**
+ * Creates a new tray icon associated with the image.
+ */
+ constructor(image: NativeImage | string);
+ /**
+ * Destroys the tray icon immediately.
+ */
+ destroy(): void;
+ /**
+ * Sets the image associated with this tray icon.
+ */
+ setImage(image: NativeImage | string): void;
+ /**
+ * Sets the image associated with this tray icon when pressed.
+ */
+ setPressedImage(image: NativeImage): void;
+ /**
+ * Sets the hover text for this tray icon.
+ */
+ setToolTip(toolTip: string): void;
+ /**
+ * Sets the title displayed aside of the tray icon in the status bar.
+ * Note: This is only implemented on OS X.
+ */
+ setTitle(title: string): void;
+ /**
+ * Sets whether the tray icon is highlighted when it is clicked.
+ * Note: This is only implemented on OS X.
+ */
+ setHighlightMode(highlight: boolean): void;
+ /**
+ * Displays a tray balloon.
+ * Note: This is only implemented on Windows.
+ */
+ displayBalloon(options?: {
+ icon?: NativeImage;
+ title?: string;
+ content?: string;
+ }): void;
+ /**
+ * Sets the context menu for this icon.
+ */
+ setContextMenu(menu: Menu): void;
+ }
+
+ interface Clipboard {
+ /**
+ * @returns The contents of the clipboard as plain text.
+ */
+ readText(type?: string): string;
+ /**
+ * Writes the text into the clipboard as plain text.
+ */
+ writeText(text: string, type?: string): void;
+ /**
+ * @returns The contents of the clipboard as a NativeImage.
+ */
+ readImage: typeof GitHubElectron.Clipboard.readImage;
+ /**
+ * Writes the image into the clipboard.
+ */
+ writeImage: typeof GitHubElectron.Clipboard.writeImage;
+ /**
+ * Clears everything in clipboard.
+ */
+ clear(type?: string): void;
+ /**
+ * Note: This API is experimental and could be removed in future.
+ * @returns Whether the clipboard has data in the specified format.
+ */
+ has(format: string, type?: string): boolean;
+ /**
+ * Reads the data in the clipboard of the specified format.
+ * Note: This API is experimental and could be removed in future.
+ */
+ read(format: string, type?: string): any;
+ }
+
+ interface CrashReporterStartOptions {
+ /**
+ * Default: Electron
+ */
+ productName?: string;
+ /**
+ * Default: GitHub, Inc.
+ */
+ companyName?: string;
+ /**
+ * URL that crash reports would be sent to as POST.
+ * Default: http://54.249.141.255:1127/post
+ */
+ submitUrl?: string;
+ /**
+ * Send the crash report without user interaction.
+ * Default: true.
+ */
+ autoSubmit?: boolean;
+ /**
+ * Default: false.
+ */
+ ignoreSystemCrashHandler?: boolean;
+ /**
+ * An object you can define which content will be send along with the report.
+ * Only string properties are send correctly.
+ * Nested objects are not supported.
+ */
+ extra?: {}
+ }
+
+ interface CrashReporterPayload extends Object {
+ /**
+ * E.g., "electron-crash-service".
+ */
+ rept: string;
+ /**
+ * The version of Electron.
+ */
+ ver: string;
+ /**
+ * E.g., "win32".
+ */
+ platform: string;
+ /**
+ * E.g., "renderer".
+ */
+ process_type: string;
+ ptime: number;
+ /**
+ * The version in package.json.
+ */
+ _version: string;
+ /**
+ * The product name in the crashReporter options object.
+ */
+ _productName: string;
+ /**
+ * Name of the underlying product. In this case, Electron.
+ */
+ prod: string;
+ /**
+ * The company name in the crashReporter options object.
+ */
+ _companyName: string;
+ /**
+ * The crashreporter as a file.
+ */
+ upload_file_minidump: File;
+ }
+
+ interface CrashReporter {
+ start(options?: CrashReporterStartOptions): void;
+
+ /**
+ * @returns The date and ID of the last crash report. When there was no crash report
+ * sent or the crash reporter is not started, null will be returned.
+ */
+ getLastCrashReport(): CrashReporterPayload;
+ }
+
+ interface Shell {
+ /**
+ * Show the given file in a file manager. If possible, select the file.
+ */
+ showItemInFolder(fullPath: string): void;
+ /**
+ * Open the given file in the desktop's default manner.
+ */
+ openItem(fullPath: string): void;
+ /**
+ * Open the given external protocol URL in the desktop's default manner
+ * (e.g., mailto: URLs in the default mail user agent).
+ */
+ openExternal(url: string): void;
+ /**
+ * Move the given file to trash and returns boolean status for the operation.
+ */
+ moveItemToTrash(fullPath: string): void;
+ /**
+ * Play the beep sound.
+ */
+ beep(): void;
+ }
+}
+//
+// declare module 'clipboard' {
+// var clipboard: GitHubElectron.Clipboard
+// export = clipboard;
+// }
+//
+// declare module 'crash-reporter' {
+// var crashReporter: GitHubElectron.CrashReporter
+// export = crashReporter;
+// }
+//
+// declare module 'native-image' {
+// var nativeImage: typeof GitHubElectron.NativeImage;
+// export = nativeImage;
+// }
+//
+// declare module 'screen' {
+// var screen: GitHubElectron.Screen;
+// export = screen;
+// }
+//
+// declare module 'shell' {
+// var shell: GitHubElectron.Shell;
+// export = shell;
+// }
+//
+// interface Window {
+// /**
+// * Creates a new window.
+// * @returns An instance of BrowserWindowProxy class.
+// */
+// open(url: string, frameName?: string, features?: string): GitHubElectron.BrowserWindowProxy;
+// }
+//
+// interface File {
+// /**
+// * Exposes the real path of the filesystem.
+// */
+// path: string;
+// }
+//
+// interface NodeRequireFunction {
+// (id: 'clipboard'): GitHubElectron.Clipboard
+// (id: 'crash-reporter'): GitHubElectron.CrashReporter
+// (id: 'native-image'): typeof GitHubElectron.NativeImage
+// (id: 'screen'): GitHubElectron.Screen
+// (id: 'shell'): GitHubElectron.Shell
+// }
+
diff --git a/gulpfile.js b/gulpfile.js
new file mode 100644
index 00000000..8cc26e2f
--- /dev/null
+++ b/gulpfile.js
@@ -0,0 +1,342 @@
+var gulp = require('gulp'),
+ uglify = require('gulp-uglify'),
+ rename = require('gulp-rename'),
+ concat = require('gulp-concat'),
+ typescript = require('gulp-typescript'),
+ merge = require('merge2'),
+ webserver = require('gulp-webserver'),
+ less = require('gulp-less'),
+ gulputil = require('gulp-util'),
+ gulpFilter = require('gulp-filter'),
+ path = require('path'),
+ sourcemaps = require('gulp-sourcemaps'),
+ zip = require('gulp-zip');
+
+/// ********
+
+/// GLOBAL
+
+gulp.task('default', function(){
+ return gulp.start('default-server-all');
+});
+
+gulp.task('default-server-all', ['default-plugins', 'copyDTS-plugins'], function(){
+ return gulp.start('default-server');
+});
+
+
+//// *****
+
+//****
+
+// PLUGIN PART
+
+// ***
+
+/**
+ * Compile typescript files to their js respective files
+ */
+gulp.task('typescript-to-js-plugins', function() {
+ //Compile all ts file into their respective js file.
+
+ var tsResult = gulp.src(['Plugins/Vorlon/**/*.ts', 'Plugins/libs/**.ts'])
+ .pipe(typescript({
+ declarationFiles: true,
+ noExternalResolve: true, target: 'ES5'}
+ ));
+
+ return merge([
+ tsResult.dts.pipe(gulp.dest('Plugins/release')),
+ tsResult.js.pipe(gulp.dest('Plugins/release'))
+ ]);
+});
+
+
+ /* Compile less files to their css respective files
+ */
+gulp.task('less-to-css-plugins', function() {
+ return gulp.src(['Plugins/Vorlon/**/*.less'], { base : '.' })
+ .pipe(less())
+ .pipe(gulp.dest(''));
+});
+
+/**
+ * Concat all js files in order into one big js file and minify it.
+ * Do not hesitate to update it if you need to add your own files.
+ */
+gulp.task('scripts-noplugin-plugins', ['typescript-to-js-plugins'], function() {
+ return gulp.src([
+ 'Plugins/libs/css.js',
+ 'Plugins/release/vorlon.tools.js',
+ 'Plugins/release/vorlon.enums.js',
+ 'Plugins/release/vorlon.basePlugin.js',
+ 'Plugins/release/vorlon.clientPlugin.js',
+ 'Plugins/release/vorlon.dashboardPlugin.js',
+ 'Plugins/release/vorlon.clientMessenger.js',
+ 'Plugins/release/vorlon.core.js'
+ ])
+ .pipe(concat('vorlon-noplugin.max.js'))
+ .pipe(gulp.dest('Plugins/release/'))
+ .pipe(rename('vorlon-noplugin.js'))
+ .pipe(uglify())
+ .pipe(gulp.dest('Plugins/release/'));
+});
+
+gulp.task('concat-webstandards-rules-plugins', ['typescript-to-js-plugins'], function () {
+ return gulp.src(['./Plugins/release/**/webstandards/rules/*.js', './Plugins/release/**/webstandards/vorlon.webstandards.client.js'])
+ .pipe(concat('vorlon.webstandards.client.js'))
+ .pipe(gulp.dest('Plugins/release/plugins/webstandards/'));
+});
+
+/**
+ * Specific task that need to be handled for specific plugins.
+ * Do not hesitate to update it if you need to add your own files
+ */
+gulp.task('scripts-specific-plugins-plugins', ['scripts-plugins'], function() {
+ // Babylon Inspector
+ gulp.src([
+ 'Plugins/release/plugins/babylonInspector/vorlon.babylonInspector.interfaces.js',
+ 'Plugins/release/plugins/babylonInspector/vorlon.babylonInspector.client.js'
+ ])
+ .pipe(concat('vorlon.babylonInspector.client.js'))
+ .pipe(gulp.dest('Plugins/release/plugins/babylonInspector/'));
+
+ gulp.src([
+ 'Plugins/release/plugins/babylonInspector/vorlon.babylonInspector.interfaces.js',
+ 'Plugins/release/plugins/babylonInspector/vorlon.babylonInspector.dashboard.js'
+ ])
+ .pipe(concat('vorlon.babylonInspector.dashboard.js'))
+ .pipe(gulp.dest('Plugins/release/plugins/babylonInspector/'));
+
+ gulp.src([
+ 'Plugins/release/plugins/babylonInspector/vorlon.babylonInspector.interfaces.min.js',
+ 'Plugins/release/plugins/babylonInspector/vorlon.babylonInspector.client.min.js'
+ ])
+ .pipe(concat('vorlon.babylonInspector.client.min.js'))
+ .pipe(gulp.dest('Plugins/release/plugins/babylonInspector/'));
+
+ gulp.src([
+ 'Plugins/release/plugins/babylonInspector/vorlon.babylonInspector.interfaces.min.js',
+ 'Plugins/release/plugins/babylonInspector/vorlon.babylonInspector.dashboard.min.js'
+ ])
+ .pipe(concat('vorlon.babylonInspector.dashboard.min.js'))
+ .pipe(gulp.dest('Plugins/release/plugins/babylonInspector/'));
+
+ // NG Inspector
+ gulp.src([
+ 'Plugins/release/plugins/ngInspector/vorlon.ngInspector.interfaces.js',
+ 'Plugins/release/plugins/ngInspector/vorlon.ngInspector.client.js'
+ ])
+ .pipe(concat('vorlon.ngInspector.client.js'))
+ .pipe(gulp.dest('Plugins/release/plugins/ngInspector/'));
+
+ gulp.src([
+ 'Plugins/release/plugins/ngInspector/vorlon.ngInspector.interfaces.js',
+ 'Plugins/release/plugins/ngInspector/vorlon.ngInspector.dashboard.js'
+ ])
+ .pipe(concat('vorlon.ngInspector.dashboard.js'))
+ .pipe(gulp.dest('Plugins/release/plugins/ngInspector/'));
+
+ gulp.src([
+ 'Plugins/release/plugins/ngInspector/vorlon.ngInspector.interfaces.min.js',
+ 'Plugins/release/plugins/ngInspector/vorlon.ngInspector.client.min.js'
+ ])
+ .pipe(concat('vorlon.ngInspector.client.min.js'))
+ .pipe(gulp.dest('Plugins/release/plugins/ngInspector/'));
+
+ return gulp.src([
+ 'Plugins/release/plugins/ngInspector/vorlon.ngInspector.interfaces.min.js',
+ 'Plugins/release/plugins/ngInspector/vorlon.ngInspector.dashboard.min.js'
+ ])
+ .pipe(concat('vorlon.ngInspector.dashboard.min.js'))
+ .pipe(gulp.dest('Plugins/release/plugins/ngInspector/'));
+
+});
+
+/**
+ * Minify all plugins.
+ * Do not hesitate to update it if you need to add your own files.
+ */
+gulp.task('scripts-plugins', ['concat-webstandards-rules-plugins'], function () {
+
+ return gulp.src([
+ './Plugins/**/vorlon.interactiveConsole.interfaces.js',
+ './Plugins/**/vorlon.interactiveConsole.client.js',
+ './Plugins/**/vorlon.interactiveConsole.dashboard.js',
+ './Plugins/**/vorlon.domExplorer.interfaces.js',
+ './Plugins/**/vorlon.domExplorer.client.js',
+ './Plugins/**/vorlon.domExplorer.dashboard.js',
+ './Plugins/**/vorlon.modernizrReport.interfaces.js',
+ './Plugins/**/vorlon.modernizrReport.client.js',
+ './Plugins/**/vorlon.modernizrReport.dashboard.js',
+ './Plugins/**/objectExplorer/vorlon.objectExplorer.interfaces.js',
+ './Plugins/**/objectExplorer/vorlon.objectExplorer.client.js',
+ './Plugins/**/objectExplorer/vorlon.objectExplorer.dashboard.js',
+ './Plugins/**/xhrPanel/vorlon.xhrPanel.interfaces.js',
+ './Plugins/**/xhrPanel/vorlon.xhrPanel.client.js',
+ './Plugins/**/xhrPanel/vorlon.xhrPanel.dashboard.js',
+ './Plugins/**/vorlon.ngInspector.interfaces.js',
+ './Plugins/**/vorlon.ngInspector.client.js',
+ './Plugins/**/vorlon.ngInspector.dashboard.js',
+ './Plugins/**/networkMonitor/vorlon.networkMonitor.interfaces.js',
+ './Plugins/**/networkMonitor/vorlon.networkMonitor.client.js',
+ './Plugins/**/networkMonitor/vorlon.networkMonitor.dashboard.js',
+ './Plugins/**/resourcesExplorer/vorlon.resourcesExplorer.interfaces.js',
+ './Plugins/**/resourcesExplorer/vorlon.resourcesExplorer.client.js',
+ './Plugins/**/resourcesExplorer/vorlon.resourcesExplorer.dashboard.js',
+ './Plugins/**/unitTestRunner/vorlon.unitTestRunner.interfaces.js',
+ './Plugins/**/unitTestRunner/vorlon.unitTestRunner.client.js',
+ './Plugins/**/unitTestRunner/vorlon.unitTestRunner.dashboard.js',
+ './Plugins/**/sample/vorlon.sample.client.js',
+ './Plugins/**/sample/vorlon.sample.dashboard.js',
+ './Plugins/**/device/vorlon.device.interfaces.js',
+ './Plugins/**/device/vorlon.device.client.js',
+ './Plugins/**/device/vorlon.device.dashboard.js',
+ './Plugins/**/webstandards/vorlon.webstandards.client.js',
+ './Plugins/**/webstandards/vorlon.webstandards.interfaces.js',
+ './Plugins/**/webstandards/vorlon.webstandards.dashboard.js',
+ './Plugins/**/babylonInspector/vorlon.babylonInspector.client.js',
+ './Plugins/**/babylonInspector/vorlon.babylonInspector.interfaces.js',
+ './Plugins/**/babylonInspector/vorlon.babylonInspector.dashboard.js'
+ ])
+ .pipe(rename(function (path) {
+ path.extname = ".min.js";
+ })
+ )
+ .pipe(uglify())
+ .pipe(gulp.dest('./Plugins'));
+});
+
+/**
+ * Move all files from Plugins to Server
+ */
+gulp.task('copy-plugins', function () {
+
+ return gulp.src([
+ 'Plugins/release/vorlon-noplugin.max.js',
+ 'Plugins/release/vorlon-noplugin.js'
+ ])
+ .pipe(gulp.dest('./Server/public/vorlon'));
+
+});
+
+gulp.task('copyPlugins-plugins', function () {
+
+ return gulp.src([
+ 'Plugins/Vorlon/plugins/**/*.js',
+ 'Plugins/Vorlon/plugins/**/*.css',
+ 'Plugins/Vorlon/plugins/**/*.html',
+ 'Plugins/Vorlon/plugins/**/*.png',
+ 'Plugins/release/plugins/**/*.js'
+ ])
+ .pipe(gulp.dest('./Server/public/vorlon/plugins'));
+
+});
+
+gulp.task('copyDTS-plugins', function () {
+
+ return gulp.src(['Plugins/release/*.d.ts'])
+ .pipe(gulp.dest('./Server/Scripts/typings/Vorlon'));
+
+});
+
+/**
+ * The default task, call the tasks: scripts, scripts-noplugin, copy, copyPlugins
+ */
+gulp.task('default-plugins', ['scripts-plugins', 'scripts-noplugin-plugins', 'less-to-css-plugins', 'scripts-specific-plugins-plugins'], function() {
+ return gulp.start('copy-plugins', 'copyPlugins-plugins', 'copyDTS-plugins');
+});
+
+/**
+ * Watch task, will call the default task if a js file is updated.
+ */
+//gulp.task('watch', function() {
+// gulp.watch('src/**/*.js', ['default']);
+//});
+
+/**
+ * Watch typescript task, will call the default typescript task if a typescript file is updated.
+ */
+gulp.task('watch-plugins', function() {
+ return gulp.watch([
+ 'Plugins/Vorlon/**/*.ts',
+ 'Plugins/Vorlon/**/*.less',
+ 'Plugins/Vorlon/**/*.html'
+ //'Vorlon/plugins/**/*.*',
+ ], ['default-plugins']);
+});
+
+/**
+ * Web server task to serve a local test page
+ */
+gulp.task('webserver', function() {
+ return gulp.src('client samples/webpage')
+ .pipe(webserver({
+ livereload: false,
+ open: 'http://localhost:1338/index.html',
+ port: 1338,
+ fallback: 'index.html'
+ }));
+});
+
+//****
+
+// SERVER PART
+
+// ***
+
+gulp.task('typescript-to-js-server', function() {
+ var tsResult = gulp.src(['./Server/**/*.ts', '!./Server/node_modules', '!./Server/node_modules/**'], { base: './' })
+ .pipe(sourcemaps.init())
+ .pipe(typescript({ noExternalResolve: true, target: 'ES5', module: 'commonjs' }));
+
+ return tsResult.js
+ .pipe(sourcemaps.write({
+ includeContent: false,
+ // Return relative source map root directories per file.
+ sourceRoot: function (file) {
+ var sourceFile = path.join(file.cwd, file.sourceMap.file);
+ return path.relative(path.dirname(sourceFile), file.cwd);
+ }
+ }))
+ .pipe(gulp.dest('.'));
+});
+
+gulp.task('build-server', ['typescript-to-js-server'], function() {
+ //copy server files to desktop app
+ return gulp.src([
+ './config.json',
+ 'cert/**',
+ 'config/**',
+ 'public/**',
+ 'Scripts/**',
+ 'views/**',
+ ], { base: './Plugins' })
+ .pipe(gulp.dest('./desktop/app/vorlon'));
+});
+
+gulp.task('default-server', ['build-server'], function() {
+});
+
+/**
+ * Watch typescript task, will call the default typescript task if a typescript file is updated.
+ */
+gulp.task('watch-server', function() {
+ gulp.watch([
+ './Server/**/*.ts',
+ ], ['default-server']);
+});
+
+
+gulp.task('watch', ["watch-server", "watch-plugins", "webserver"], function() {
+});
+
+/**
+ * Zip task used within the build to create an archive that will be deployed using VSTS Release Management
+ */
+
+gulp.task('zip', function() {
+ gulp.src(['./**/*', '!./DeploymentTools/**', '!./desktop/**', '!./plugins library/**', '!./Plugins/**', '!./Tests/**', '!./desktop', '!./plugins library', '!./DeploymentTools', '!./Plugins', '!./Tests'])
+ .pipe(zip('deployment-package.zip'))
+ .pipe(gulp.dest('DeploymentTools'));
+});
\ No newline at end of file
diff --git a/package.json b/package.json
index 761abda9..38b7388c 100644
--- a/package.json
+++ b/package.json
@@ -1,6 +1,6 @@
{
"name": "vorlon",
- "version": "0.1.0",
+ "version": "0.2.0",
"description": "vorlon",
"main": "Server/server.js",
"dependencies": {
@@ -10,7 +10,6 @@
"cookieparser": "~0.1.0",
"express": "~4.12.3",
"express-session": "~1.11.1",
- "fakeredis": "~0.3.1",
"favicon": "0.0.2",
"jade": "~1.9.2",
"json": "~9.0.3",
@@ -19,9 +18,7 @@
"passport": "~0.2.1",
"passport-local": "~1.0.0",
"passport-twitter": "~1.0.3",
- "redis": "~0.12.1",
- "socket.io": "1.3.6",
- "socket.io-redis": "~0.1.4",
+ "socket.io": "1.4.4",
"stylus": "~0.50.0",
"winston": "~1.0.1",
"winston-azure": "0.0.4",
@@ -30,16 +27,19 @@
"http-proxy": "~1.11.2"
},
"devDependencies": {
+ "cors": "^2.7.1",
"gulp": "~3.8.11",
"gulp-concat": "~2.2.0",
"gulp-filter": "~0.4.1",
"gulp-less": "~3.0.3",
+ "gulp-mocha": "~2.2.0",
"gulp-rename": "~1.2.0",
"gulp-sourcemaps": "~1.5.2",
"gulp-typescript": "~2.8.2",
"gulp-uglify": "~0.3.0",
"gulp-util": "~2.2.14",
"gulp-webserver": "~0.9.0",
+ "gulp-zip": "~3.0.2",
"merge2": "~0.3.5",
"through": "~2.3.4",
"typescript": "~1.6.0-beta"
@@ -47,9 +47,8 @@
"scripts": {
"global-deploy-gulp": "npm install -g gulp",
"global-deploy-gulp-cli": "npm install -g gulp-cli",
- "build-server": "gulp --gulpfile=./Server/gulpfile.js --cwd=./Server",
- "build-client": "gulp --gulpfile=./Plugins/gulpfile.js --cwd=./Plugins",
- "build": "node disclaimer.js && npm run global-deploy-gulp && npm run global-deploy-gulp-cli && npm run build-client && npm run build-server",
+ "build-all": "gulp --gulpfile=./gulpfile.js",
+ "build": "node disclaimer.js && npm run build-all",
"prepublish": "npm run build",
"start": "node ./Server/server.js"
},
diff --git a/whatsnew.md b/whatsnew.md
index bc096e0a..692931d5 100644
--- a/whatsnew.md
+++ b/whatsnew.md
@@ -1,3 +1,30 @@
+## 0.2.0
+
+- Plugins
+ - XhrPanel: changing hook to go over prototype for node.js implementation
+ - Best practices:
+ - integration with aXe rules for accessibility : http://www.deque.com/products/aXe/
+ - Moved all code to client side
+ - Updated Modernizr plugin to support modernizr 3.0
+ - Various bug fixes and improvements
+ - Removed redis dependency
+ - Moved to socket.io 1.4+
+ - Tons of small fixes all around the place
+ - DOM Explorer
+ - Click on an absolute uri by holding the ctrl key will display its content into another tab. Hover is effective too.
+- Core
+ - Added node.js remote debug support. Now plugins can be flagged with nodeCompliant = true
+- Dashboard
+ - Stability improvements
+- Vorlon Desktop
+ - First release of this new way to deploy vorlon without having to use NPM command line
+ - Read mode here: http://vorlonjs.io/#vorlon-desktop
+- General
+ - Generation of source maps file to allow debugging using TypeScript files
+ - Adding features around DevOps: http://blogs.technet.com/b/devops/archive/2016/01/12/vorlonjs-a-journey-to-devops-introducing-the-blog-post-series.aspx
+ - One gulp to rule them all: You now only have to run gulp watch from the root folder to track and compile any change
+ - Moved samples to /client samples. Added sample for node.js remote debugging
+
## 0.1.0
- Plugins